Python Interview Question | Python Programming Challenge

Question 1. Write a program that takes a list of numbers as input and returns the two numbers that add up to a specific target value. If no such pair exists, the program should return an empty list. Your program should be able to handle duplicate numbers in the input list.

For example, if the input list is [1, 2, 3, 4, 5] and the target value is 7, the program should return [2, 5], because 2 + 5 = 7.

Solution :


def find_two_numbers(numbers, target):
for i in range(len(numbers)-1):
for j in range(i,len(numbers)):
if numbers[i]+numbers[j] == target:
return [numbers[i],numbers[j]]
return []

target = 23
num = [9,8,7,6,5,4,3,21,2,34,5,6,7]
print(find_two_numbers(num,target))


Question 2. Write a function that takes in a list of integers and returns the sum of all the even numbers in the list.

For example, given the list [1, 2, 3, 4, 5, 6], the function should return 12 (which is the sum of 2, 4, and 6).

Solution :

def sum_even_numbers(numbers):

result = sum(filter(lambda x: x % 2 == 0, numbers))

return result

# example usage
numbers = [1, 2, 3, 4, 5, 6]
result = sum_even_numbers(numbers)
print(result)


Question 3. Write a Python program that takes in a string as input and prints out the most common character(s) in the string and their frequency.

For example, if the input string is "hello world", the program should output "The most common character(s) are: 'l' with frequency 3".

If there are multiple characters with the same highest frequency, the program should output all of them.

You can assume that the input string only contains lowercase letters and spaces. 

Solution :

from collections import Counter


def get_word_freq(string):

freq = Counter(string)

return max(freq.values())


str = 'Hello World'

print(get_word_freq(str))

Question 4. Write a Python function called reverse_words that takes a string as input and returns the string with the words reversed. For example, if the input string is "hello world", the function should return "world hello".

Solution : 

def reverse_word(str):

str = str.strip().split(' ')

return str[::-1]

str = ' Hello Ranjan Pandey '
print(reverse_word(str))
Next Post Previous Post
No Comment
Add Comment
comment url