Python Simple Scenario Based Interview Questions and Answers

Python Interview Questions & Answers | Lists, Dictionaries, Tuples | Code Examples Python Interview Questions

Python Simple Scenario Based Interview Questions

1. Reverse a string.
def reverse_string(s): return s[::-1] result = reverse_string("hello") print(result) # Output: olleh
String slicing with a step of -1 reverses the string.
2. Check if a string is a palindrome.
def is_palindrome(s): return s == s[::-1] result = is_palindrome("madam") print(result) # Output: True
A palindrome reads the same forwards and backward.
3. Find the factorial of a number.
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) result = factorial(5) print(result) # Output: 120
Recursive function to calculate factorial.
4. Find the Fibonacci sequence up to n.
def fibonacci(n): fib_list = [0, 1] while fib_list[-1] + fib_list[-2] <= n: fib_list.append(fib_list[-1] + fib_list[-2]) return fib_list result = fibonacci(10) print(result) # Output: [0, 1, 1, 2, 3, 5, 8]
Generate Fibonacci sequence until the last number is less than or equal to n.
5. Check if a number is prime.
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True result = is_prime(17) print(result) # Output: True
Check if a number is divisible by any number from 2 to its square root.
6. Remove duplicates from a list.
def remove_duplicates(lst): return list(set(lst)) result = remove_duplicates([1, 2, 2, 3, 4, 4, 5]) print(result) # Output: [1, 2, 3, 4, 5]
Using sets to remove duplicates efficiently.
7. Count the occurrences of each element in a list.
def count_occurrences(lst): counts = {} for item in lst: counts[item] = counts.get(item, 0) + 1 return counts result = count_occurrences([1, 2, 2, 3, 3, 3]) print(result) # Output: {1: 1, 2: 2, 3: 3}
Using a dictionary to store counts.
8. Find the largest element in a list.
def find_largest(lst): if not lst: return None return max(lst) result = find_largest([10, 5, 20, 8]) print(result) # Output: 20
Using the max() function to find the largest element.
9. Sort a list of dictionaries by a key.
def sort_dicts(lst, key): return sorted(lst, key=lambda x: x[key]) data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}] result = sort_dicts(data, 'age') print(result)
Using sorted() with a lambda function to sort by a specific key.
10. Find the intersection of two lists.
def intersection(list1, list2): return list(set(list1) & set(list2)) result = intersection([1, 2, 3, 4], [3, 4, 5, 6]) print(result) # Output: [3, 4]
Using sets to find common elements efficiently.
11. Implement a basic stack.
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() if self.items else None def peek(self): return self.items[-1] if self.items else None def is_empty(self): return len(self.items) == 0 s = Stack() s.push(1) s.push(2) print(s.pop()) # Output: 2
Basic stack implementation using a list.
12. Implement a basic queue.
class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): return self.items.pop(0) if self.items else None def is_empty(self): return len(self.items) == 0 q = Queue() q.enqueue(1) print(q.dequeue())
Basic queue implementation using a list.
13. Merge two dictionaries.
def merge_dicts(dict1, dict2): return {**dict1, **dict2} dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} result = merge_dicts(dict1, dict2) print(result) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using the ** operator to unpack dictionaries and merge them.
14. Get the value of a key in a dictionary, with a default if it doesn't exist.
def get_dict_value(dictionary, key, default=None): return dictionary.get(key, default) my_dict = {'name': 'Alice', 'age': 30} result = get_dict_value(my_dict, 'city', 'Unknown') print(result) # Output: Unknown
Using the get() method to retrieve a value with a default.
15. Create a list of tuples from two lists.
def create_tuples(list1, list2): return list(zip(list1, list2)) list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] result = create_tuples(list1, list2) print(result) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
Using the zip() function to combine lists into tuples.
16. Unzip a list of tuples into separate lists.
def unzip_tuples(tuple_list): return list(zip(*tuple_list)) tuple_list = [(1, 'a'), (2, 'b'), (3, 'c')] result = unzip_tuples(tuple_list) print(result) # Output: [(1, 2, 3), ('a', 'b', 'c')]
Using the * operator with zip() to unzip tuples.
17. Find the most frequent element in a list using a dictionary.
def most_frequent(lst): counts = {} for item in lst: counts[item] = counts.get(item, 0) + 1 return max(counts, key=counts.get) lst = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] result = most_frequent(lst) print(result) # Output: 4
Using a dictionary to count occurrences and then finding the max key based on value.
18. Check if all values in a dictionary are the same.
def all_values_same(dictionary): if not dictionary: return True values = list(dictionary.values()) return values.count(values[0]) == len(values) dict1 = {'a': 1, 'b': 1, 'c': 1} dict2 = {'a': 1, 'b': 2, 'c': 1} print(all_values_same(dict1)) # Output: True print(all_values_same(dict2)) # Output: False
Checks if the count of the first value equals the length of all values.

No comments:

Post a Comment