Python Programming Strings Interview Questions
Write a Python program to remove a Specific character from string?
Here’s a Python program to remove a specific character from a string:
def remove_char(text, char):
"""
Removes a specific character from a string.
Args:
text: The input string.
char: The character to remove.
Returns:
The string with the character removed.
"""
return text.replace(char, "")
# Example usage
text = "Hello, World!"
char_to_remove = "l"
new_text = remove_char(text, char_to_remove)
print(f"Original text: '{text}'")
print(f"Text after removing '{char_to_remove}': '{new_text}'")
Write a Python Program to count occurrence of characters in string?
to count the occurrence of characters in a string:
def char_count(text):
"""
Counts the occurrence of each character in a string.
Args:
text: The input string.
Returns:
A dictionary where keys are characters and values are their counts.
"""
char_counts = {}
for char in text:
if char in char_counts:
char_counts[char] += 1
else:
char_counts[char] = 1
return char_counts
# Example usage
text = "Mississippi"
char_counts = char_count(text)
print("Character counts:")
for char, count in char_counts.items():
print(f"{char}: {count}")
Write a Python program to count the occurrences of each word in a sentence?
def word_count(sentence):
"""
Counts the occurrence of each word in a sentence.
Args:
sentence: The input sentence as a string.
Returns:
A dictionary where keys are words (case-insensitive) and values are their counts.
"""
# Convert the sentence to lowercase and split it into words
words = sentence.lower().split()
# Initialize an empty dictionary to store word counts
word_counts = {}
# Count the occurrences of each word
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return word_counts
# Example usage
sentence = "This is a sample sentence to count words."
word_counts = word_count(sentence)
print("Word counts:")
for word, count in word_counts.items():
print(f"{word}: {count}")
Small Modification in Code
Write a Python program to reverse a string?
Here are several ways to reverse a string in Python:
Method 1: Using Slicing
def reverse_string_slicing(s):
return s[::-1]
# Example usage
original_string = "hello"
reversed_string = reverse_string_slicing(original_string)
print(reversed_string) # Output: "olleh"
Method 2: Using a For Loop
def reverse_string_loop(s):
reversed_str = ''
for char in s:
reversed_str = char + reversed_str
return reversed_str
# Example usage
original_string = "hello"
reversed_string = reverse_string_loop(original_string)
print(reversed_string) # Output: "olleh"
Method 3: Using the reversed()
Function
def reverse_string_reversed(s):
return ''.join(reversed(s))
# Example usage
original_string = "hello"
reversed_string = reverse_string_reversed(original_string)
print(reversed_string) # Output: "olleh"
Method 4: Using Recursion
def reverse_string_recursion(s):
if len(s) == 0:
return s
else:
return s[-1] + reverse_string_recursion(s[:-1])
# Example usage
original_string = "hello"
reversed_string = reverse_string_recursion(original_string)
print(reversed_string) # Output: "olleh"
Method 5: Using Stack (List)
def reverse_string_stack(s):
stack = list(s)
reversed_str = ''
while stack:
reversed_str += stack.pop()
return reversed_str
# Example usage
original_string = "hello"
reversed_string = reverse_string_stack(original_string)
print(reversed_string) # Output: "olleh"
Method 6: Using reduce
from functools
from functools import reduce
def reverse_string_reduce(s):
return reduce(lambda x, y: y + x, s)
# Example usage
original_string = "hello"
reversed_string = reverse_string_reduce(original_string)
print(reversed_string) # Output: "olleh"
Write a Python program in to check string is anagrams or not?
def is_anagram(str1, str2):
"""
Checks if two strings are anagrams (case-insensitive).
Args:
str1: The first string.
str2: The second string.
Returns:
True if the strings are anagrams, False otherwise.
"""
# Convert both strings to lowercase and remove whitespaces
str1 = str1.lower().replace(" ", "")
str2 = str2.lower().replace(" ", "")
# Check if the lengths are equal (anagrams must have the same length)
if len(str1) != len(str2):
return False
# Create a dictionary to store character counts for str1
char_counts = {}
for char in str1:
if char in char_counts:
char_counts[char] += 1
else:
char_counts[char] = 1
# Check if all characters in str2 can be formed using characters in str1 (and same count)
for char in str2:
if char not in char_counts or char_counts[char] == 0:
return False
char_counts[char] -= 1
return True
# Example usage
str1 = "cinema"
str2 = "iceman"
if is_anagram(str1, str2):
print(f"{str1} and {str2} are anagrams.")
else:
print(f"{str1} and {str2} are not anagrams.")
Write a Python program to check string is palindrome or not?
A palindrome is a string that reads the same forward and backward. Here’s a Python program that checks whether a given string is a palindrome:
Method 1: Using Slicing
def is_palindrome(s):
# Remove any non-alphanumeric characters and convert to lowercase
cleaned_str = ''.join(char.lower() for char in s if char.isalnum())
return cleaned_str == cleaned_str[::-1]
# Example usage
input_string = "A man, a plan, a canal, Panama!"
if is_palindrome(input_string):
print(f'"{input_string}" is a palindrome.')
else:
print(f'"{input_string}" is not a palindrome.')
Method 2: Using a For Loop
def is_palindrome_loop(s):
cleaned_str = ''.join(char.lower() for char in s if char.isalnum())
length = len(cleaned_str)
for i in range(length // 2):
if cleaned_str[i] != cleaned_str[length - i - 1]:
return False
return True
# Example usage
input_string = "A man, a plan, a canal, Panama!"
if is_palindrome_loop(input_string):
print(f'"{input_string}" is a palindrome.')
else:
print(f'"{input_string}" is not a palindrome.')
Method 3: Using Recursion
def is_palindrome_recursion(s):
def helper(sub_str):
if len(sub_str) <= 1:
return True
if sub_str[0] != sub_str[-1]:
return False
return helper(sub_str[1:-1])
cleaned_str = ''.join(char.lower() for char in s if char.isalnum())
return helper(cleaned_str)
# Example usage
input_string = "A man, a plan, a canal, Panama!"
if is_palindrome_recursion(input_string):
print(f'"{input_string}" is a palindrome.')
else:
print(f'"{input_string}" is not a palindrome.')
Method 4: Using Two-Pointer Technique
def is_palindrome_two_pointer(s):
cleaned_str = ''.join(char.lower() for char in s if char.isalnum())
left, right = 0, len(cleaned_str) - 1
while left < right:
if cleaned_str[left] != cleaned_str[right]:
return False
left += 1
right -= 1
return True
# Example usage
input_string = "A man, a plan, a canal, Panama!"
if is_palindrome_two_pointer(input_string):
print(f'"{input_string}" is a palindrome.')
else:
print(f'"{input_string}" is not a palindrome.')
Method 5: Using Stack (List)
def is_palindrome_stack(s):
cleaned_str = ''.join(char.lower() for char in s if char.isalnum())
stack = list(cleaned_str)
reversed_str = ''
while stack:
reversed_str += stack.pop()
return cleaned_str == reversed_str
# Example usage
input_string = "A man, a plan, a canal, Panama!"
if is_palindrome_stack(input_string):
print(f'"{input_string}" is a palindrome.')
else:
print(f'"{input_string}" is not a palindrome.')
These methods provide different approaches to checking whether a string is a palindrome. They include preprocessing the string to ignore non-alphanumeric characters and case differences, which ensures the palindrome check is accurate for phrases and sentences.
Write a Python Program to check given character is digit or not?
To check if a given character is a digit in Python, you can use the isdigit()
method, which is a built-in string method. Here are a few different ways to implement this check:
Method 1: Using isdigit()
Method
def is_digit(char):
return char.isdigit()
# Example usage
input_char = '5'
if is_digit(input_char):
print(f'"{input_char}" is a digit.')
else:
print(f'"{input_char}" is not a digit.')
Method 2: Using ASCII Values
def is_digit(char):
return '0' <= char <= '9'
# Example usage
input_char = 'a'
if is_digit(input_char):
print(f'"{input_char}" is a digit.')
else:
print(f'"{input_char}" is not a digit.')
Method 3: Using Regular Expression
pythonCopy codeimport re
def is_digit(char):
return bool(re.match(r'd', char))
# Example usage
input_char = '5'
if is_digit(input_char):
print(f'"{input_char}" is a digit.')
else:
print(f'"{input_char}" is not a digit.')
Method 4: Handling Input with a Single Character Check
pythonCopy codedef is_digit(char):
if len(char) != 1:
return False
return char.isdigit()
# Example usage
input_char = '9'
if is_digit(input_char):
print(f'"{input_char}" is a digit.')
else:
print(f'"{input_char}" is not a digit.')
Complete Program
Here is a complete program that prompts the user for input and checks if the provided character is a digit:
pythonCopy codedef is_digit(char):
if len(char) != 1:
return False
return char.isdigit()
# Get input from the user
input_char = input("Enter a character: ")
# Check if the input character is a digit
if is_digit(input_char):
print(f'"{input_char}" is a digit.')
else:
print(f'"{input_char}" is not a digit.')
These methods cover different ways to determine if a given character is a digit, providing flexibility depending on your needs and preferences. The isdigit()
method is the most straightforward and idiomatic way in Python, while the other methods provide alternative approaches for more specific use cases.
Write a Python program to find the most frequent character in a string?
Here are two Python programs to find the most frequent character in a string:
Method 1: Using a dictionary
This method iterates through the string, building a dictionary to store the frequency of each character. The character with the highest count is then identified.
def most_frequent_char(text):
"""
Finds the most frequent character in a string.
Args:
text: The input string.
Returns:
A tuple containing the most frequent character and its count.
"""
char_counts = {}
for char in text:
if char not in char_counts:
char_counts[char] = 0
char_counts[char] += 1
# Find the character with the highest count
most_frequent = max(char_counts, key=char_counts.get)
count = char_counts[most_frequent]
return most_frequent, count
# Example usage
text = "Mississippi"
most_frequent, count = most_frequent_char(text)
print(f"The most frequent character in '{text}' is '{most_frequent}' with a count of {count}")
Method 2: Using collections.Counter
This method utilizes the collections.Counter
class from the collections
module. Counter
automatically creates a dictionary to store character counts and provides a built-in method most_common(1)
to find the most frequent character.
from collections import Counter
def most_frequent_char(text):
"""
Finds the most frequent character in a string using Counter.
Args:
text: The input string.
Returns:
The most frequent character and its count as a tuple.
"""
char_counts = Counter(text)
most_frequent = char_counts.most_common(1)[0] # Get first element of the list
return most_frequent[0], most_frequent[1]
# Example usage
text = "Mississippi"
most_frequent, count = most_frequent_char(text)
print(f"The most frequent character in '{text}' is '{most_frequent}' with a count of {count}")
Both methods achieve the same result. The first method offers more control over the dictionary creation process, while the second method is more concise using Counter
.
Write a Python program to check if a string is a valid email address?
Checking if a string is a valid email address can be done using regular expressions (regex). Here’s a Python program that uses regex to validate email addresses:
Regular Expression for Email Validation
A typical email regex might look like this:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$
Explanation of the Regex
^
: Start of the string.[a-zA-Z0-9._%+-]+
: Matches one or more alphanumeric characters, dots, underscores, percent signs, plus signs, or hyphens.@
: Matches the “@” symbol.[a-zA-Z0-9.-]+
: Matches one or more alphanumeric characters, dots, or hyphens..
: Matches a literal dot.[a-zA-Z]{2,}
: Matches two or more alphabetic characters.$
: End of the string.
Python Program
import re
def is_valid_email(email):
# Define the regex pattern for a valid email address
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$'
# Use re.match to check if the email matches the regex pattern
if re.match(email_regex, email):
return True
else:
return False
# Example usage
email_addresses = [
"user@example.com",
"user.name+tag+sorting@example.com",
"user_name@example.co.in",
"user@example",
"user@.com",
"@example.com",
"user@com",
"user@domain.c"
]
for email in email_addresses:
if is_valid_email(email):
print(f'"{email}" is a valid email address.')
else:
print(f'"{email}" is not a valid email address.')
Output
"user@example.com" is a valid email address.
"user.name+tag+sorting@example.com" is a valid email address.
"user_name@example.co.in" is a valid email address.
"user@example" is not a valid email address.
"user@.com" is not a valid email address.
"@example.com" is not a valid email address.
"user@com" is not a valid email address.
"user@domain.c" is not a valid email address.
Explanation
- Regular Expression: The
email_regex
variable stores the regex pattern used to match valid email addresses. is_valid_email
Function:- This function takes an email address as input.
- It uses the
re.match
function to check if the email address matches the regex pattern. - It returns
True
if the email matches the pattern, otherwiseFalse
.
- Example Usage:
- A list of email addresses is defined.
- The program iterates over the list and checks if each email address is valid using the
is_valid_email
function. - It prints whether each email address is valid or not.
This program provides a robust way to check the validity of email addresses using regular expressions.
Write a Python program to Longest Palindromic Substring
Given a string s
, find the longest substring in s
that is a palindrome. A palindrome is a string that reads the same forwards and backwards.
Example
- Input:
"babad"
- Output:
"bab"
(Note:"aba"
is also a valid answer, since both are palindromes of the same length)
- Output:
- Input:
"cbbd"
- Output:
"bb"
- Output:
Constraints
- The length of
s
is up to 1000.
Solution
This problem can be approached using various techniques. One efficient way is to use dynamic programming or center expansion. Here, I’ll provide the center expansion method, which is relatively easy to understand and implement.
Center Expansion Method
This method leverages the fact that a palindrome mirrors around its center. Therefore, for each character in the string, we can expand outwards to check for the longest palindrome centered at that character.
def longest_palindromic_substring(s):
if len(s) == 0:
return ""
start, end = 0, 0
for i in range(len(s)):
len1 = expand_around_center(s, i, i) # Odd length palindromes
len2 = expand_around_center(s, i, i + 1) # Even length palindromes
max_len = max(len1, len2)
if max_len > end - start:
start = i - (max_len - 1) // 2
end = i + max_len // 2
return s[start:end + 1]
def expand_around_center(s, left, right):
L, R = left, right
while L >= 0 and R < len(s) and s[L] == s[R]:
L -= 1
R += 1
return R - L - 1
# Example usage
input_string = "babad"
result = longest_palindromic_substring(input_string)
print(f"The longest palindromic substring of '{input_string}' is '{result}'")
Explanation
- Function
longest_palindromic_substring(s)
:- Iterates over each character in the string
s
. - For each character, it considers two cases: the palindrome can be of odd length (centered at a single character) or even length (centered between two characters).
- It calls the helper function
expand_around_center
to get the lengths of the longest palindromes for both cases. - Updates the starting and ending indices of the longest palindrome found.
- Iterates over each character in the string
- Function
expand_around_center(s, left, right)
:- Expands outwards from the center as long as the characters on both sides are equal.
- Returns the length of the palindrome found.
This solution has a time complexity of O(n2)O(n^2)O(n2) where nnn is the length of the input string, and it efficiently finds the longest palindromic substring.
4o
Leave a Reply