Python Coding Questions with Test Cases
1. Write a function to check if a number is prime.
Test Case:
Input: 7
Expected Output: True
2. Write a function to reverse a string.
Test Case:
Input: 'hello'
Expected Output: 'olleh'
3. Write a function to find the factorial of a number.
Test Case:
Input: 5
Expected Output: 120
4. Write a function to check if a string is a palindrome.
Test Case:
Input: 'radar'
Expected Output: True
5. Write a function to find the nth Fibonacci number.
Test Case:
Input: 6
Expected Output: 8
6. Write a function to find the largest number in a list.
Test Case:
Input: [1, 2, 3, 4, 5]
Expected Output: 5
7. Write a function to count the number of vowels in a string.
Test Case:
Input: 'hello world'
Expected Output: 3
8. Write a function to sort a list using bubble sort.
Test Case:
Input: [5, 1, 4, 2, 8]
Expected Output: [1, 2, 4, 5, 8]
9. Write a function to merge two sorted lists.
Test Case:
Input: [1, 3, 5], [2, 4, 6]
Expected Output: [1, 2, 3, 4, 5, 6]
10. Write a function to find the second largest number in a list.
Test Case:
Input: [1, 2, 3, 4, 5]
Expected Output: 4
11. Write a function to remove duplicates from a list.
Test Case:
Input: [1, 2, 2, 3, 4, 4, 5]
Expected Output: [1, 2, 3, 4, 5]
12. Write a function to check if two strings are anagrams.
Test Case:
Input: 'listen', 'silent'
Expected Output: True
13. Write a function to count the occurrences of each character in a string.
Test Case:
Input: 'hello'
Expected Output: {'h':1, 'e':1, 'l':2, 'o':1}
14. Write a function to implement binary search.
Test Case:
Input: [1, 2, 3, 4, 5], 3
Expected Output: 2
15. Write a function to compute the GCD of two numbers.
Test Case:
Input: 54, 24
Expected Output: 6
16. Write a function to check if a number is an Armstrong number.
Test Case:
Input: 153
Expected Output: True
17. Write a function to flatten a nested list.
Test Case:
Input: [1, [2, [3, 4], 5]]
Expected Output: [1, 2, 3, 4, 5]
18. Write a function to calculate the sum of digits of a number.
Test Case:
Input: 1234
Expected Output: 10
19. Write a function to convert a decimal number to binary.
Test Case:
Input: 10
Expected Output: '1010'
20. Write a function to find the common elements in two lists.
Test Case:
Input: [1, 2, 3], [2, 3, 4]
Expected Output: [2, 3]
21. Write a function to move all zeros in a list to the end.
Test Case:
Input: [0, 1, 0, 3, 12]
Expected Output: [1, 3, 12, 0, 0]
22. Write a function to reverse every word in a sentence.
Test Case:
Input: 'Hello World'
Expected Output: 'olleH dlroW'
23. Write a function to check if a number is a perfect square.
Test Case:
Input: 16
Expected Output: True
24. Write a function to rotate a list by k elements.
Test Case:
Input: [1, 2, 3, 4, 5], k=2
Expected Output: [3, 4, 5, 1, 2]
25. Write a function to return the intersection of two arrays.
Test Case:
Input: [4, 9, 5], [9, 4, 9, 8, 4]
Expected Output: [4, 9]