2025 Essential Python Coding Interview Questions And Answers

Here’s the availability of the most important and valuable Python coding interview questions and answers in a simple and user-friendly format. You can use these Python interview questions in your interviews or even coding exams. We have divided these questions into three parts: basic, intermediate and advanced level. so, learn these important coding questions and enhance your coding journey.

Basic Python Coding Interview Questions

1) Write a Python program to swap the first and last digits of a number.

Ans: First, we convert a number into a String format and then write a condition for single-digit numbers, because single-digit numbers can’t be converted. then, swap the first and last numbers using the following code.

def swap(number):
n = str(number)

if len(n) == 1:
return number

swaped = n[-1] + n[1:-1] + n[0]
return int(swaped)

print(swap(12345))

swaped = n[-1] + n[1:-1] + n[0] => This line describe as,

ValuesIndex
10
21
32
43
54 or -1
  • -1 means the last number of digits. => 5
  • [1:-1] means the second number to the last second digit. => “234”
  • [0] means the first number of digits. => 1

2) Create a function that repeats each character in a string three times.

Ans: Learn this simple logic code and create a new function in your own logic.

def repeat_characters_three_times(text):
result = ""

for char in text:
result += char * 3

return result

# Example
input_text = "abc"
print(repeat_characters_three_times(input_text))

Output:

aaabbbccc

First, we have created the “repeat_characters_three_times” function.

  result = ""

for char in text:
result += char * 3

Then, we multiply each character by 3, and then all the characters will be added to the result variable using the += sign.

3) Write a function to find the sum of digits in a string that contain both letters and digits.

Ans: We can sum of digits using Python’s isdigit() string method.

def sum_of_digits_in_text(text):
total = 0

for char in text:
if char.isdigit():
total += int(char)

return total

# Example
sample = "a1b2c3"
print("Sum of digits:", sum_of_digits_in_text(sample))

Output:

Sum of digits: 6

4) Convert an integer list into a single serial number.

Input: [1, 23, 45] → Output: 12345

Ans: Learn this easy code for the concatenated number:

def concatenated_number(numbers):
result = ""

for num in numbers:
result += str(num)

return int(result)

# Example
data = [1, 23, 45]
print("Concatenated Number:", concatenated_number(data))

Output:

Concatenated Number: 12345

5) Write a program that can make every alternate word capital in a sentence.

Example Input: "this is a coding challenge"

Output: "this IS a CODING challenge"

Ans: We can make odd values into upper() case using this code.

def capitalize_alternate_words(sentence):
words = sentence.split()
result = []

for i in range(len(words)):
if i % 2 == 1:
result.append(words[i].upper())
else:
result.append(words[i])

return ' '.join(result)

# Example
text = "this is a coding challenge"
print("Output:", capitalize_alternate_words(text))

Output:

this IS a CODING challenge

6) Count how many times the word “code” appears in a given paragraph (case-insensitive).

text = "I love to CODE. Code is fun. Coding and CODE are different."

Output: 3

Ans: This is the simple logic of counting the number of words in the sentence.

def count_code_word(paragraph):
words = paragraph.lower().split()
count = 0

for word in words:
if word.strip(".,!?") == "code":
count += 1

return count

# Example
text = "I love to CODE. Code is fun. Coding and CODE are different."
print("Count of 'code':", count_code_word(text))

Output:

Count of 'code': 3

7) Replace all spaces in a string with dashes, but only if the word has more than 3 characters.

Example Input:

text = "I love coding and learning"

Output:

I-love-coding and learning

Python Code

def replace_space_if_word_long(text):
words = text.split()
result = []

for i in range(len(words)):
result.append(words[i])

# Check if next word exists and current word length > 3
if i < len(words) - 1:
if len(words[i]) > 3:
result.append("-")
else:
result.append(" ")

return ''.join(result)

# Example
text = "I love coding and learning"
print("Result:", replace_space_if_word_long(text))

Output:

Result: I-love-coding and learning

8) Create a function that checks if all list elements are in a specific range.

Ans: We are using a simple loop and arguments for checking the range of the numbers.

def are_all_elements_in_range(numbers, minimum, maximum):
for num in numbers:
if num < minimum or num > maximum:
return False
return True

# Example
nums = [10, 15, 20, 25]
print("All in range:", are_all_elements_in_range(nums, 10, 30))

Output:

All in range: True

Because all numbers are between 10 and 30.

9) Convert a given list of words into camelCase string.

Ans:

def list_to_camel_case(words):
result = ""

for i in range(len(words)):
if i == 0:
result += words[i].lower()
else:
result += words[i].capitalize()

return result

# Example
word_list = ["convert", "this", "to", "camel", "case"]
print("CamelCase String:", list_to_camel_case(word_list))

Output:

CamelCase String: convertThisToCamelCase

In this example:

  • words[i].lower() = sets the first word to a small letter.
  • words[i].capitalize() = Change all other words latter capital.
  • result += … = Combining all the words into a sentence.

Note: In camelCase, the first word starts with a lowercase letter, and each subsequent word starts with an uppercase letter. In PascalCase, every word starts with an uppercase letter, including the first one.

10) Write a program that can reverse each word in a sentence, but keeps the word order.

Ans: Example Input:

"This is coding fun"

// Output:
"sihT si gnidoc nuf"

Python Code:

def reverse_each_word(sentence):
words = sentence.split()
result = []

for word in words:
result.append(word[::-1]) # reverse each word using slicing

return ' '.join(result)

# Example
text = "This is coding fun"
print("Reversed words:", reverse_each_word(text))

Output:

Reversed words: sihT si gnidoc nuf

Logic Explained:

  • split(): Break the sentence into words.
  • [::-1]: Reverse each word.
  • append(): Add the reversed words into the list
  • ‘ ‘.join(): Created into a proper sentence.

11) Create a function to count how many vowels are available in each word of a sentence.

Ans: This simple code counts each vowel in words:

def count_vowels_in_each_word(sentence):
words = sentence.split()
vowels = "aeiouAEIOU"
result = {}

for word in words:
count = 0
for letter in word:
if letter in vowels:
count += 1
result[word] = count

return result

# Example
text = "This is amazing"
print("Vowel count per word:", count_vowels_in_each_word(text))

Output:

Vowel count per word: {'This': 1, 'is': 1, 'amazing': 3}

12) Find the second largest number in a list without using sort() function.

Ans: We will use an infinity function to find the second-largest number.

def find_second_largest(numbers):
first = second = float('-inf')

for num in numbers:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num

return second if second != float('-inf') else None

# Example
nums = [10, 25, 30, 20, 5]
print("Second largest:", find_second_largest(nums))

Output:

Second largest: 25

Understand this logic and write a new code in your own logic.

13) Write a function that rotates a string by two characters from the right.

Ans:

"hello"

//Output:
"lohel"
def rotate_string_right_by_2(text):
if len(text) < 2:
return text # No need to rotate

last_two = text[-2:] # last 2 characters
remaining = text[:-2] # rest of the string

return last_two + remaining

# Example
print("Rotated:", rotate_string_right_by_2("hello"))

Output:

Rotated: lohel

14) Check if a string is a mirrored palindrome (e.g., “AHA”, “OHO”).

Ans:

def is_mirrored_palindrome(text):
mirror_letters = set("AHIMOTUVWXY")
text = text.upper()

# Check: 1) Palindrome, 2) All letters are mirror-friendly
if text != text[::-1]:
return False

for char in text:
if char not in mirror_letters:
return False

return True

# Examples
print(is_mirrored_palindrome("AHA")) # True
print(is_mirrored_palindrome("HELLO")) # False
print(is_mirrored_palindrome("OHO")) # True
print(is_mirrored_palindrome("MOM")) # True
print(is_mirrored_palindrome("NOON")) # False

Output:

True
False
True
True
False

15) Implement a function that checks if two strings are almost equal (only 1 character change allowed).

Ans: In this example, we compare each character using a loop.

def are_almost_equal(s1, s2):
if len(s1) != len(s2):
return False

differences = 0

for i in range(len(s1)):
if s1[i] != s2[i]:
differences += 1
if differences > 1:
return False

return differences == 1

Test Examples:

print(are_almost_equal("test", "tent"))   # True
print(are_almost_equal("book", "back")) # False
print(are_almost_equal("same", "same")) # False
print(are_almost_equal("code", "cope")) # True

Output:

True
False
False
True

Intermediate Level Python Coding Interview Questions

16) Write a function that returns the index of the first non-repeating character in a string.

Ans: First, understand the logic:

"coding" = 0 ('c' is unique)
"aabbccdeff" = 6 ('d' is first non-repeating)
"aabbcc" = -1 (no unique character)
"hello" = 0 ('h' is first unique)

Now, create a simple logic code of this python program:

def first_unique_index(text):
for i in range(len(text)):
if text.count(text[i]) == 1:
return i
return -1

print(first_unique_index("coding")) # 0
print(first_unique_index("aabbccdeff")) # 6
print(first_unique_index("aabbcc")) # -1
print(first_unique_index("hello")) # 0

Output:

0  
6
-1
0

17) Create a program to compress a string like “aaabcc” to “a3b1c2”.

Ans: We will use a condition, a loop and operators in this code:

def compress_string(text):
if not text:
return ""

result = ""
count = 1

for i in range(1, len(text)):
if text[i] == text[i - 1]:
count += 1
else:
result += text[i - 1] + str(count)
count = 1

result += text[-1] + str(count) # Add last char group
return result

# Example
print(compress_string("aaabcc")) # a3b1c2
print(compress_string("xxxyyyz")) # x3y3z1
print(compress_string("abc")) # a1b1c1
print(compress_string("")) # ""

Output:

a3b1c2  
x3y3z1
a1b1c1
""

18) Given a 2D list (matrix), write a function to print its transpose.

Ans: Transpose means: Rows become columns and columns become rows

For Example Input:

matrix = [
[1, 2, 3],
[4, 5, 6]
]

Output:

[1, 4]  
[2, 5]
[3, 6]

Learn this Python Code:

def transpose_matrix(matrix):
rows = len(matrix)
cols = len(matrix[0])

for c in range(cols):
new_row = []
for r in range(rows):
new_row.append(matrix[r][c])
print(new_row)

# Example
matrix = [
[1, 2, 3],
[4, 5, 6]
]

transpose_matrix(matrix)

Output:

[1, 4]  
[2, 5]
[3, 6]

19) Write a function to flatten a nested list of integers.

Ans:

Input:  [1, [2, 3], [4, [5, 6]]]
Output: [1, 2, 3, 4, 5, 6]
def flatten_list(nested):
result = []

for item in nested:
if isinstance(item, list):
result.extend(flatten_list(item)) # Recursive flatten
else:
result.append(item)

return result

# Examples
print(flatten_list([1, [2, 3], [4, [5, 6]]]))
print(flatten_list([7, [8, [9]], 10]))

Output:

[1, 2, 3, 4, 5, 6]  
[7, 8, 9, 10]

20) Implement a function that removes consecutive duplicates from a list.

Ans: Python Code:

def remove_consecutive_duplicates(data):
if not data:
return []

result = [data[0]] # First element always kept

for i in range(1, len(data)):
if data[i] != data[i - 1]:
result.append(data[i])

return result

# Examples
print(remove_consecutive_duplicates([1, 2, 2, 3, 3, 3, 2, 2])) # [1, 2, 3, 2]
print(remove_consecutive_duplicates(['a', 'a', 'b', 'a'])) # ['a', 'b', 'a']
print(remove_consecutive_duplicates([5, 5, 5, 5])) # [5]
print(remove_consecutive_duplicates([])) # []

Output:

[1, 2, 3, 2]  
['a', 'b', 'a']
[5]
[]

21) Write a function to rotate a list k positions to the left.

Ans: Left rotation of a list by k positions is common in DSA, array manipulation, and circular logic problems.

In programming, k position typically represents a generic variable used for indexing, counting, or specifying a position/step in a collection of a list, string, or tuple.

def rotate_left(lst, k):
if not lst:
return []

k = k % len(lst) # To handle k > len
return lst[k:] + lst[:k]

# Examples
print(rotate_left([1, 2, 3, 4, 5], 2)) # [3, 4, 5, 1, 2]
print(rotate_left([10, 20, 30, 40], 1)) # [20, 30, 40, 10]
print(rotate_left([1, 2, 3], 3)) # [1, 2, 3]
print(rotate_left([], 4)) # []

Output:

[3, 4, 5, 1, 2]  
[20, 30, 40, 10]
[1, 2, 3]
[]

If you want the right rotation, just reverse the slice:

return lst[-k:] + lst[:-k]

22) Write a function to split a list into n equal parts.

Ans: Example Inputs & Outputs:

ListnOutput
[1, 2, 3, 4, 5, 6]3[[1, 2], [3, 4], [5, 6]]
[10, 20, 30, 40]2[[10, 20], [30, 40]]
[1, 2, 3, 4]3Invalid: can’t split equally
def split_into_parts(lst, n):
if len(lst) % n != 0:
return "Cannot split list equally into", n, "parts"

part_size = len(lst) // n
result = []

for i in range(0, len(lst), part_size):
result.append(lst[i:i + part_size])

return result

# Examples
print(split_into_parts([1, 2, 3, 4, 5, 6], 3)) # [[1, 2], [3, 4], [5, 6]]
print(split_into_parts([10, 20, 30, 40], 2)) # [[10, 20], [30, 40]]
print(split_into_parts([1, 2, 3, 4], 3)) # Error message

Output:

[[1, 2], [3, 4], [5, 6]]  
[[10, 20], [30, 40]]
('Cannot split list equally into', 3, 'parts')

23) Write a function that replaces every prime number in a list with 0.

Ans:

Example Inputs & Outputs:

InputOutput
[2, 4, 5, 6, 7][0, 4, 0, 6, 0]
[10, 11, 13, 14][10, 0, 0, 14]
[1, 3, 9, 17][1, 0, 9, 0]
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

def replace_primes_with_zero(lst):
result = []
for num in lst:
if is_prime(num):
result.append(0)
else:
result.append(num)
return result

# Examples
print(replace_primes_with_zero([2, 4, 5, 6, 7])) # [0, 4, 0, 6, 0]
print(replace_primes_with_zero([10, 11, 13, 14])) # [10, 0, 0, 14]
print(replace_primes_with_zero([1, 3, 9, 17])) # [1, 0, 9, 0]

Output:

[0, 4, 0, 6, 0]  
[10, 0, 0, 14]
[1, 0, 9, 0]

Code Explanation:

  • is_prime(num) > This function checks if the number is prime or not.
  • replace_primes_with_zero(lst) > Check each number in the list.

24) Given a string, count the frequency of each character without using collections.

Ans: It counts and shows how many times each character is used in the word.

For Example:

text = "hello"

Output:
{'h': 1, 'e': 1, 'l': 2, 'o': 1}

Python code logic:

def count_char_frequency(text):
freq = {}

for char in text:
if char in freq:
freq[char] += 1
else:
freq[char] = 1

return freq

# Example
print(count_char_frequency("hello"))
print(count_char_frequency("banana"))

Output:

{'h': 1, 'e': 1, 'l': 2, 'o': 1}  
{'b': 1, 'a': 3, 'n': 2}

25) Create a dictionary from two lists: one for keys and one for values.

Ans:

Example Input:

keys = ["name", "age", "city"]
values = ["Alice", 25, "Delhi"]

Output:

{'name': 'Alice', 'age': 25, 'city': 'Delhi'}

Python Code:

def make_dict(keys, values):
result = {}
for i in range(len(keys)):
result[keys[i]] = values[i]
return result

# Example
keys = ["name", "age", "city"]
values = ["Alice", 25, "Delhi"]
print(make_dict(keys, values))

Output:

{'name': 'Alice', 'age': 25, 'city': 'Delhi'}

Code Explanation:

  • result = {} > First, created an empty dictionary.
  • for i in range(len(keys)) > Accessed both list through index.
  • result[keys[i]] = values[i] > Inserted the key value pair in the dictionary.
  • return result > Return the final dictionary.

26) Write a function that checks if all the brackets in a string are balanced.

Ans:

For example:

InputOutput
“(a+b)”True
“[(a+b) * c]”True
“{[()]}”True
“(a+b”False
“{(})”False

Python code:

def are_brackets_balanced(text):
stack = []
opening = "({["
closing = ")}]"
match = {')': '(', '}': '{', ']': '['}

for char in text:
if char in opening:
stack.append(char)
elif char in closing:
if not stack or stack[-1] != match[char]:
return False
stack.pop()

return len(stack) == 0

print(are_brackets_balanced("(a+b)")) # True
print(are_brackets_balanced("[(a+b) * c]")) # True
print(are_brackets_balanced("{[()]}")) # True
print(are_brackets_balanced("(a+b")) # False
print(are_brackets_balanced("{(})")) # False

Output:

True  
True
True
False
False

27) Implement a simple calculator that can add, subtract, multiply, or divide two numbers based on user input.

Ans:

def simple_calculator():
print("Welcome to Simple Calculator")

# Step 1: Get inputs from user
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

# Step 2: Perform operation
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
result = "Error: Cannot divide by zero"
else:
result = num1 / num2
else:
result = "Invalid operator"

# Step 3: Show result
print("Result:", result)

# Call function
simple_calculator()

Run The Code:

Welcome to Simple Calculator  
Enter first number: 10
Enter operator (+, -, *, /): *
Enter second number: 5
Result: 50.0

28) Write a function that returns all duplicate values from a list.

Ans:

Python Code:

def find_duplicates(lst):
duplicates = []
seen = []

for item in lst:
if item in seen:
if item not in duplicates:
duplicates.append(item)
else:
seen.append(item)

return duplicates

# Examples
print(find_duplicates([1, 2, 2, 3, 4, 4, 5])) # [2, 4]
print(find_duplicates(['a', 'b', 'a', 'c'])) # ['a']
print(find_duplicates([1, 2, 3])) # []

Output:

[2, 4]  
['a']
[ ]

29) Create a function to merge two dictionaries. If keys match, add their values.

Ans:

For Example:

dict1 = {'a': 10, 'b': 20, 'c': 30}
dict2 = {'b': 5, 'c': 15, 'd': 40}

Output:

{'a': 10, 'b': 25, 'c': 45, 'd': 40}

Python Code:

def merge_dicts_add_values(d1, d2):
result = {}

# Step 1: Add all keys from d1
for key in d1:
if key in d2:
result[key] = d1[key] + d2[key]
else:
result[key] = d1[key]

# Step 2: Add remaining keys from d2
for key in d2:
if key not in d1:
result[key] = d2[key]

return result

# Example
dict1 = {'a': 10, 'b': 20, 'c': 30}
dict2 = {'b': 5, 'c': 15, 'd': 40}

print(merge_dicts_add_values(dict1, dict2))

Output:

{'a': 10, 'b': 25, 'c': 45, 'd': 40}

30) Check if two strings are anagrams without using sorted().

Ans: What is an anagram?

Anagram means they have the same characters, same number of each character, but order doesn’t matter.

For example: “listen” and “silent” > It is an anagram, because all words are the same, order doesn’t matter.

Python Code:

def are_anagrams(str1, str2):
if len(str1) != len(str2):
return False

freq1 = {}
freq2 = {}

for char in str1:
if char in freq1:
freq1[char] += 1
else:
freq1[char] = 1

for char in str2:
if char in freq2:
freq2[char] += 1
else:
freq2[char] = 1

return freq1 == freq2

print(are_anagrams("listen", "silent")) # True
print(are_anagrams("hello", "world")) # False
print(are_anagrams("race", "care")) # True
print(are_anagrams("aabb", "bbaa")) # True
print(are_anagrams("aabb", "ababab")) # False

Output:

True  
False
True
True
False

Note:

  • Code is case-sensitive (“Listen” ≠ “silent”).
  • Use .lower() to ignore the case.
str1 = str1.lower()
str2 = str2.lower()

31) Create a pattern generator that prints numbers in a pyramid format.

Ans:

Python Code:

def number_pyramid(rows):
for i in range(1, rows + 1):
# Print spaces first
spaces = ' ' * (rows - i)

# Print numbers from 1 to i
numbers = ''
for j in range(1, i + 1):
numbers += str(j) + ' '

print(spaces + numbers.strip())

number_pyramid(5)

Output:

    1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

32) Write a function that reverses only the digits in a string (e.g., “ab12cd34” → “ab43cd21”).

Ans:

Python Code:

def reverse_only_digits(s):
digits = []

# Step 1: Collect all digits from the string
for char in s:
if char.isdigit():
digits.append(char)

# Step 2: Reverse the collected digits
digits = digits[::-1]

result = ""
digit_index = 0

# Step 3: Rebuild the string
for char in s:
if char.isdigit():
result += digits[digit_index]
digit_index += 1
else:
result += char

return result

print(reverse_only_digits("ab12cd34")) # Output: ab43cd21
print(reverse_only_digits("a1b2c3")) # Output: a3b2c1
print(reverse_only_digits("x9y")) # Output: x9y

Output:

ab43cd21  
a3b2c1
x9

33) Write a program that removes the outermost brackets of a valid bracketed string.

Ans:

Python Code:

def remove_outermost_brackets(s):
result = ""
depth = 0

for char in s:
if char == '(':
if depth > 0:
result += '('
depth += 1
elif char == ')':
depth -= 1
if depth > 0:
result += ')'

return result

print(remove_outermost_brackets("(()())(())")) # Output: ()()()
print(remove_outermost_brackets("(()())(())(()(()))")) # Output: ()()()()(())
print(remove_outermost_brackets("()()")) # Output: ""

Output:

()()()  
()()()()(())
""

34) Write a function that checks if a list of numbers can form an arithmetic progression.

Ans:

For Example:

InputOutput
[3, 5, 1]True
[1, 2, 4]False
[10, 20, 30, 40]True

Python Code:

def is_arithmetic_progression(nums):
if len(nums) < 2:
return True # One or zero elements always form a progression

nums = sorted(nums) # Sort to check equal gaps
diff = nums[1] - nums[0]

for i in range(2, len(nums)):
if nums[i] - nums[i - 1] != diff:
return False

return True

print(is_arithmetic_progression([3, 5, 1])) # True
print(is_arithmetic_progression([1, 2, 4])) # False
print(is_arithmetic_progression([10, 20, 30, 40])) # True
print(is_arithmetic_progression([7])) # True

Output:

True  
False
True
True

Note: First, it will sort the list and then check whether it’s an arithmetic progression.

Advanced Level Python Coding Interview Questions

35) Implement your own version of enumerate() in Python.

Ans: What does enumerate() do? For example:

for i, val in enumerate(['a', 'b', 'c']):
print(i, val)

Output:

0 a  
1 b
2 c

Python Code:

def my_enumerate(iterable, start=0):
index = start
result = []
for item in iterable:
result.append((index, item))
index += 1
return result

items = ['apple', 'banana', 'cherry']
for i, val in my_enumerate(items):
print(i, val)

Output:

0 apple  
1 banana
2 cherry

36) Create a function that finds the longest common prefix in a list of strings.

Ans:

For Example:

InputOutput
[“flower”, “flow”, “flight”]“fl”
[“dog”, “racecar”, “car”]“”
[“in”, “input”, “inside”]“in”

Python Code:

def longest_common_prefix(words):
if not words:
return ""

prefix = words[0]

for word in words[1:]:
i = 0
while i < len(prefix) and i < len(word) and prefix[i] == word[i]:
i += 1
prefix = prefix[:i]
if prefix == "":
break

return prefix

print(longest_common_prefix(["flower", "flow", "flight"])) # fl
print(longest_common_prefix(["dog", "racecar", "car"])) # (empty)
print(longest_common_prefix(["apple", "app", "application"])) # app
print(longest_common_prefix(["same", "same", "same"])) # same
print(longest_common_prefix([])) # (empty)

Output:

fl  
(empty string)
app
same
(empty string)

37) Write a recursive function to calculate the sum of all digits of a number.

Ans:

Python Code:

def sum_of_digits(n):
if n == 0:
return 0
return (n % 10) + sum_of_digits(n // 10)

print(sum_of_digits(123)) # 6
print(sum_of_digits(4567)) # 22
print(sum_of_digits(0)) # 0
print(sum_of_digits(9)) # 9

Output:

6  
22
0
9

38) Write a function that converts a sentence into title case without using title().

Ans:

Python Code:

def to_title_case(sentence):
words = sentence.split()
result = []

for word in words:
if len(word) > 0:
first = word[0].upper()
rest = word[1:].lower()
result.append(first + rest)
else:
result.append("")

return ' '.join(result)

print(to_title_case("hEllo wORld! this IS pyThOn."))
print(to_title_case("123abc DEF ghi")) # "123abc Def Ghi"
print(to_title_case(" already Title")) # "Already Title"

Output:

Hello World! This Is Python.  
123abc Def Ghi
Already Title

39) Implement a basic stack class using only lists.

Ans:

Python Code:

class Stack:
def __init__(self):
self.items = []

def push(self, value):
self.items.append(value)

def pop(self):
if self.is_empty():
return None # Or raise an error
return self.items.pop()

def peek(self):
if self.is_empty():
return None
return self.items[-1]

def is_empty(self):
return len(self.items) == 0

def size(self):
return len(self.items)

def display(self):
return self.items[::-1] # Show top at the start

s = Stack()
s.push(10)
s.push(20)
s.push(30)

print("Stack:", s.display()) # [30, 20, 10]
print("Top:", s.peek()) # 30
print("Popped:", s.pop()) # 30
print("After pop:", s.display()) # [20, 10]
print("Is empty?", s.is_empty()) # False
print("Size:", s.size()) # 2

Output:

Stack: [30, 20, 10]  
Top: 30
Popped: 30
After pop: [20, 10]
Is empty? False
Size: 2

40) Write a function that finds all pairs in a list that add up to a specific target.

Ans:

Python Code:

pythonCopyEditdef find_pairs(nums, target):
seen = set()
result = []

for num in nums:
complement = target - num
if complement in seen:
result.append((complement, num))
seen.add(num)

return result

print(find_pairs([2, 4, 3, 5, 7, 8, 1], 9))
print(find_pairs([1, 2, 3, 4, 5], 6))
print(find_pairs([10, 20, 30], 100)) # []

Output:

[(2, 7), (4, 5), (8, 1)]  
[(1, 5), (2, 4)]
[]

Also Read:

Leave a Comment