Top 10 Python interview questions

Here are 10 Python code interview questions along with their answers:

1. Reverse a String

Question: Write a Python function to reverse a string.

Answer:

   def reverse_string(input_str):
       return input_str[::-1]

2. Check for Palindrome

Question: Write a Python function to check if a given string is a palindrome.

Answer:

   def is_palindrome(input_str):
       return input_str == input_str[::-1]

3. Find the Missing Number

Question: Given an array of integers from 1 to n with one number missing, find the missing number.

Answer:

   def find_missing_number(nums):
       n = len(nums) + 1
       expected_sum = n * (n + 1) // 2
       actual_sum = sum(nums)
       return expected_sum - actual_sum

4. Check for Anagrams

Question: Write a Python function to check if two strings are anagrams of each other.

Answer:

   def are_anagrams(str1, str2):
       return sorted(str1) == sorted(str2)

5. Find the Largest Element

Question: Write a Python function to find the largest element in an array.

Answer:

   def find_largest_element(nums):
       return max(nums)

6. Remove Duplicates

Question: Write a Python function to remove duplicates from a list.

Answer:

   def remove_duplicates(nums):
       return list(set(nums))

7. Calculate Factorial

Question: Write a Python function to calculate the factorial of a given number.

Answer:

   def factorial(n):
       if n == 0:
           return 1
       else:
           return n * factorial(n-1)

8. Check for Prime Number

Question: Write a Python function to check if a given number is prime.

Answer:

   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

9. Merge Two Sorted Lists

Question: Write a Python function to merge two sorted lists into a single sorted list.

Answer:

   def merge_sorted_lists(list1, list2):
       return sorted(list1 + list2)

10. Reverse a Linked List

Question: Write a Python function to reverse a singly linked list.

Answer:

   class ListNode:
       def __init__(self, val=0, next=None):
           self.val = val
           self.next = next

   def reverse_linked_list(head):
       prev = None
       current = head
       while current is not None:
           next_node = current.next
           current.next = prev
           prev = current
           current = next_node
       return prev

These code interview questions cover a range of common programming tasks and concepts in Python. Practicing these questions will help you become more confident and proficient in solving coding problems during interviews.