# Python String & Number Programs – Interview Preparation Guide html
Python Interview Programs
1. Check String is Palindrome or Not
Solution 1: Reverse the String & Compare
x = "dalad"
y = x[::-1]
if x == y:
print("String is palindrome")
else:
print("Not palindrome")
Output: String is palindrome
Solution 2: Compare Characters from Both Ends
x = "dalad"
is_palindrome = True
for i in range(len(x) // 2):
if x[i] != x[len(x) - 1 - i]:
is_palindrome = False
break
print("Given String is Palindrome:", is_palindrome)
2. Change Character Case in a String
x = "ChAnDaNsInGh"
y = ""
for char in x:
if char.isupper():
y += char.lower()
elif char.islower():
y += char.upper()
print(y)
Output: cHaNdAnSiNgH
3. Sort a String
Without Using Built-in Method
x = "chandansingh"
char_list = list(x)
for i in range(len(char_list)):
for j in range(len(char_list)):
if char_list[i] > char_list[j]:
char_list[i], char_list[j] = char_list[j], char_list[i]
result = "".join(char_list)
print(result)
Using sorted()
x = "chandansingh"
result = "".join(sorted(x))
print(result)
4. Check Whether Two Strings Have Same Characters
x = "chandansingh"
y = "singhchandan"
result = sorted(x) == sorted(y)
print("Are both strings same:", result)
5. Find the Greatest Number from a List
x = [1, 4, 10, 6, 8, 9, 5]
greatest = x[0]
for num in x:
if num > greatest:
greatest = num
print(greatest)
Output: 10
6. Reverse a String
x = "way2testing"
y = ""
for char in x:
y = char + y
print(y)
Output: gnitset2yaw
7. Reverse a Sentence
x = "i love reading from way2testing"
words = x.split()
result = []
for i in range(len(words)-1, -1, -1):
result.append(words[i])
print(" ".join(result))
8. Find the Largest Word in a Sentence
x = "I live in India and i like python"
words = x.split()
largest = words[0]
for word in words:
if len(word) > len(largest):
largest = word
print(largest)
print(len(largest))
9. Reverse the Sentence and Reverse Each Word
x = "i love reading from way2testing"
words = x.split()
result = []
for i in range(len(words)-1, -1, -1):
result.append(words[i][::-1])
print(" ".join(result))
Output: gnitset2yaw morf gnidaer evol i
10. Remove Duplicate Characters from String
x = "way2testing"
result = set(x)
print("".join(result))
11. Remove Duplicates and Maintain Sequence
x = "way2testing"
seen = set()
result = []
for char in x:
if char not in seen:
seen.add(char)
result.append(char)
print("".join(result))
Output: way2tesing
12. Find Character Count in a String
x = "way2testing"
count_dict = {}
for char in x:
if char in count_dict:
count_dict[char] += 1
else:
count_dict[char] = 1
print(count_dict)
13. Find Characters Whose Occurrence is More Than 1
from collections import Counter
x = "way2testing"
counts = Counter(x)
duplicates = {}
for char, count in counts.items():
if count > 1:
duplicates[char] = count
print(duplicates)
14. Reverse a Number
x = 123456
output = 0
while x > 0:
remainder = x % 10
output = (output * 10) + remainder
x = x // 10
print(output)
Output: 654321
No comments:
Post a Comment