0% found this document useful (0 votes)
3 views12 pages

Python 60 Coding Q and A

The document contains a collection of coding problems and their solutions in Python, covering various topics such as string manipulation, data structures, algorithms, and mathematical computations. Each problem includes a brief description followed by a code implementation and an example output. Key topics include reversing a string, finding factorials, checking for prime numbers, and implementing data structures like linked lists and trees.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

Python 60 Coding Q and A

The document contains a collection of coding problems and their solutions in Python, covering various topics such as string manipulation, data structures, algorithms, and mathematical computations. Each problem includes a brief description followed by a code implementation and an example output. Key topics include reversing a string, finding factorials, checking for prime numbers, and implementing data structures like linked lists and trees.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Coding Questions Answers in .

( By Angel Mary)

1. Reverse a String
.

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

# Example
print(reverse_string("hello")) # Output: 'olleh'

2. Find the Factorial of a Number


.

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

# Example
print(factorial(5)) # Output: 120

3. 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

# Example
print(is_prime(7)) # Output: True

4. Find the Fibonacci Series up to N Terms


.

def fibonacci_series(n):
series = []
a, b = 0, 1
for _ in range(n):
series.append(a)
a, b = b, a + b
return series

# Example
print(fibonacci_series(7)) # Output: [0, 1, 1, 2, 3, 5, 8]
5. Find the Largest Element in an Array
.

def largest_element(arr):
return max(arr)

# Example
print(largest_element([3, 8, 1, 99, 23])) # Output: 99

6. Use a Lambda Expression to Sort a List


.

# Sort a list of tuples by second element


items = [(1, 3), (2, 2), (4, 1)]
sorted_items = sorted(items, key=lambda x: x[1])

# Example
print(sorted_items) # Output: [(4, 1), (2, 2), (1, 3)]

7. Filter a List using . Collection (e.g., filter)


.

# Filter even numbers


nums = [1, 2, 3, 4, 5, 6]
even_nums = list(filter(lambda x: x % 2 == 0, nums))

# Example
print(even_nums) # Output: [2, 4, 6]

8. Compute Sum of a List of Integers Using Streams


.

nums = [1, 2, 3, 4, 5]
total = sum(nums)
print(total) # Output: 15

9. Find the Maximum Value in a List Using Streams


.

nums = [10, 20, 5, 80, 3]


max_val = max(nums)
print(max_val) # Output: 80
10. Create and Use Optional

(. doesn't have Optional like Java, but uses None with checks or the or operator.)

def get_value(val):
return val if val is not None else "Default Value"

print(get_value(None)) # Output: Default Value


print(get_value("Present")) # Output: Present

11. Implement a Singleton Pattern


.

class Singleton:
_instance = None

def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance

# Example
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # Output: True

12. Implement a Basic LinkedList


.

class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, data):


if not self.head:
self.head = Node(data)
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = Node(data)

def print_list(self):
curr = self.head
while curr:
print(curr.data, end=" -> ")
curr = curr.next
print("None")

# Example
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.print_list() # Output: 1 -> 2 -> 3 -> None

13. Find the Intersection of Two Arrays


.

def intersection(arr1, arr2):


return list(set(arr1) & set(arr2))

# Example
print(intersection([1, 2, 3], [2, 3, 4])) # Output: [2, 3]

14. Sort a Map by Values


.

data = {'a': 3, 'b': 1, 'c': 2}


sorted_map = dict(sorted(data.items(), key=lambda item: item[1]))
print(sorted_map) # Output: {'b': 1, 'c': 2, 'a': 3}

15. Implement a Basic Tree Structure


.

class TreeNode:
def __init__(self, value):
self.value = value
self.children = []

def add_child(self, child_node):


self.children.append(child_node)

def print_tree(self, level=0):


print(" " * level * 2 + str(self.value))
for child in self.children:
child.print_tree(level + 1)

# Example
root = TreeNode("Root")
child1 = TreeNode("Child1")
child2 = TreeNode("Child2")
root.add_child(child1)
root.add_child(child2)
child1.add_child(TreeNode("GrandChild1"))
root.print_tree()
16. Use Streams to Find Duplicate Elements in a List
.

from collections import Counter

def find_duplicates(lst):
counts = Counter(lst)
return [item for item, count in counts.items() if count > 1]

# Example
print(find_duplicates([1, 2, 3, 2, 4, 1, 5])) # Output: [1, 2]

17. Create a CompletableFuture Example

(Using asyncio in .)

import asyncio

async def async_task():


await asyncio.sleep(1)
return "Task Complete"

async def main():


result = await async_task()
print(result)

# Run it
asyncio.run(main()) # Output after 1 second: Task Complete

18. Use Optional with Default Values


.

# Like Java's optional.orElse("default")


value = None
result = value or "Default Value"
print(result) # Output: Default Value

21. Remove Duplicates from a List


.

list(set([1, 2, 2, 3])) # Output: [1, 2, 3]

22. Find the Intersection of Two Sets


.
set1 & set2 # Output: common elements

23. Longest Common Prefix


.

# longest_common_prefix(["flower", "flow", "flight"]) → "fl"

24. Basic Queue using deque


.

q = Queue()
q.enqueue(1)
q.dequeue()

25. GCD of Two Numbers


.

gcd(48, 18) # Output: 6

26. Merge Two Lists


.

merge_lists([1, 2], [3, 4]) # Output: [1, 2, 3, 4]

27. Generate Range


.

generate_range(5, 10) # Output: [5, 6, 7, 8, 9]

28. Group Strings by Length


.

group_by_length(["hi", "hello", "ok", "nope"])

29. Average of List


.

average([10, 20, 30]) # Output: 20.0

30. Convert Strings to Uppercase


.

to_uppercase(["hello", "world"]) # Output: ["HELLO", "WORLD"]

31. Stack Implementation


.

s = Stack()
s.push(10)
s.pop()

32. Priority Queue


.

pq = PriorityQueue()
pq.push("urgent", 1)
pq.pop()

33. HashMap Iteration


.

hashmap_example({'a': 1, 'b': 2})

34. First Non-Repeated Character


.

first_non_repeated_char("swiss") # Output: "w"

35. Sort Custom Objects


.

sort_people_by_age([Person("A", 30), Person("B", 25)])

36. Binary Search


.

binary_search([1, 3, 5, 7], 5) # Output: 2

37. Merge Sort


.

merge_sort([3, 1, 4, 1, 5])

38. Kth Largest Element


.

kth_largest([3, 2, 1, 5, 6, 4], 2) # Output: 5

39. Longest Palindromic Substring


.
longest_palindrome("babad") # Output: "bab" or "aba"

40. Convert String to Date


.

convert_to_date("2025-07-05") # Output: datetime object

41. GCD Using Euclid's Algorithm


.

def gcd_euclid(a, b):


while b:
a, b = b, a % b
return a

42. Generate Random Number Between 1 and 100


.

import random

def random_1_to_100():
return random.randint(1, 100)

43. Quick Sort Algorithm


.

def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
less = [x for x in arr[1:] if x <= pivot]
greater = [x for x in arr[1:] if x > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)

44. Merge Sort Algorithm


.

def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result

45. Check if a String is a Palindrome


.

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

46. First Non-Repeating Character


.

from collections import Counter

def first_non_repeating_char(s):
counts = Counter(s)
for ch in s:
if counts[ch] == 1:
return ch
return None

47. Count Number of Vowels in a String


.

def count_vowels(s):
return sum(1 for ch in s.lower() if ch in 'aeiou')

48. Remove Duplicates from a String


.

def remove_duplicates_string(s):
seen = set()
result = []
for ch in s:
if ch not in seen:
seen.add(ch)
result.append(ch)
return ''.join(result)
49. Longest Substring Without Repeating Characters
.

def longest_unique_substring(s):
start = max_len = 0
seen = {}
for i, ch in enumerate(s):
if ch in seen and seen[ch] >= start:
start = seen[ch] + 1
seen[ch] = i
max_len = max(max_len, i - start + 1)
return max_len

50. Check if Two Strings are Anagrams


.

def are_anagrams(s1, s2):


return sorted(s1) == sorted(s2)

51. Convert a String to an Integer


.

def string_to_integer(s):
try:
return int(s)
except ValueError:
return None # or raise an exception

52. Find All Occurrences of a Substring in a String


.

def find_all_occurrences(string, substring):


return [i for i in range(len(string)) if string.startswith(substring,
i)]

53. Find the Minimum Element in an Array


.

def find_min_element(arr):
return min(arr)

54. Rotate an Array by k Positions


.

def rotate_array(arr, k):


k = k % len(arr)
return arr[-k:] + arr[:-k]

55. Find the Longest Consecutive Sequence


.

def longest_consecutive(nums):
num_set = set(nums)
longest = 0
for n in nums:
if n - 1 not in num_set:
length = 1
while n + length in num_set:
length += 1
longest = max(longest, length)
return longest

56. Move Zeros to the End of an Array


.

def move_zeros(arr):
non_zeros = [x for x in arr if x != 0]
return non_zeros + [0] * (len(arr) - len(non_zeros))

57. Find the Common Elements in Three Sorted Arrays


.

def common_in_three_arrays(arr1, arr2, arr3):


i = j = k = 0
result = []
while i < len(arr1) and j < len(arr2) and k < len(arr3):
if arr1[i] == arr2[j] == arr3[k]:
result.append(arr1[i])
i += 1
j += 1
k += 1
else:
min_val = min(arr1[i], arr2[j], arr3[k])
if arr1[i] == min_val: i += 1
if arr2[j] == min_val: j += 1
if arr3[k] == min_val: k += 1
return result

58. Find the Missing and Repeating Numbers in an Array

Assumes numbers are from 1 to n, with one missing and one repeating.
.

def find_missing_and_repeating(arr):
n = len(arr)
total = sum(arr)
total_sq = sum(x*x for x in arr)
expected_sum = n * (n + 1) // 2
expected_sq = n * (n + 1) * (2 * n + 1) // 6
diff = total - expected_sum
sq_diff = total_sq - expected_sq
repeating = (diff + sq_diff // diff) // 2
missing = repeating - diff
return missing, repeating

59. Find the Maximum Element in an Array


.

def find_max_element(arr):
return max(arr)

You might also like