0% found this document useful (0 votes)
12 views11 pages

Python Programming Challenges Solutions

The document contains a collection of Python programming exercises covering various topics such as string manipulation, prime number checking, Fibonacci sequence generation, and more. Each exercise includes a brief description and a corresponding Python function implementation. The document serves as a practical guide for learning and practicing Python programming concepts.

Uploaded by

Gayathri Thara
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views11 pages

Python Programming Challenges Solutions

The document contains a collection of Python programming exercises covering various topics such as string manipulation, prime number checking, Fibonacci sequence generation, and more. Each exercise includes a brief description and a corresponding Python function implementation. The document serves as a practical guide for learning and practicing Python programming concepts.

Uploaded by

Gayathri Thara
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Program

1. Reverse a String (Basic String Handling)

python

CopyEdit

def reverse_string(s):

return s[::-1]

print(reverse_string("DRDO Interview"))

🔢 2. Check Prime Number (Logic + Loop)

python

CopyEdit

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

print(is_prime(17)) # True

🔁 3. Fibonacci Sequence up to N Terms (Loop + Recursion)

python

CopyEdit

def fibonacci(n):

seq = [0, 1]

for _ in range(2, n):

[Link](seq[-1] + seq[-2])

Confidential C
return seq

print(fibonacci(10))

🧮 4. Factorial using Recursion (Math + Recursion)

python

CopyEdit

def factorial(n):

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

print(factorial(5)) # 120

📊 5. Count Frequency of Characters in a String (Dictionary + Loop)

python

CopyEdit

def char_frequency(s):

freq = {}

for char in s:

freq[char] = [Link](char, 0) + 1

return freq

print(char_frequency("radar"))

🧠 6. Palindrome Check (String Manipulation)

python

CopyEdit

def is_palindrome(s):

return s == s[::-1]

Confidential C
print(is_palindrome("madam")) # True

🗃️7. Remove Duplicates from List while Preserving Order (Set +


Logic)

python

CopyEdit

def remove_duplicates(lst):

seen = set()

result = []

for item in lst:

if item not in seen:

[Link](item)

[Link](item)

return result

print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))

🔍 8. Linear Search in a List (Basic Search Algorithm)

python

CopyEdit

def linear_search(arr, key):

for i, val in enumerate(arr):

if val == key:

return i

return -1

print(linear_search([10, 20, 30, 40], 30)) # 2

📐 9. Matrix Transpose (2D List Handling)

Confidential C
python

CopyEdit

def transpose(matrix):

return [list(row) for row in zip(*matrix)]

mat = [[1, 2], [3, 4], [5, 6]]

print(transpose(mat))

🧪 10. Basic Exception Handling

python

CopyEdit

try:

x = int(input("Enter a number: "))

print("Reciprocal is:", 1/x)

except ValueError:

print("Invalid input.")

except ZeroDivisionError:

print("Cannot divide by zero.")

1. Infix to Postfix Conversion (Stack Implementation)

python

CopyEdit

def precedence(op):

return {'+':1, '-':1, '*':2, '/':2}.get(op, 0)

def infix_to_postfix(expr):

output = []

stack = []

for ch in expr:

if [Link]():

Confidential C
[Link](ch)

elif ch in '+-*/':

while stack and precedence(stack[-1]) >= precedence(ch):

[Link]([Link]())

[Link](ch)

elif ch == '(':

[Link](ch)

elif ch == ')':

while stack and stack[-1] != '(':

[Link]([Link]())

[Link]()

while stack:

[Link]([Link]())

return ''.join(output)

print(infix_to_postfix("a+(b*c)")) # abc*+

📦 2. LRU Cache using OrderedDict

python

CopyEdit

from collections import OrderedDict

class LRUCache:

def __init__(self, capacity):

[Link] = OrderedDict()

[Link] = capacity

def get(self, key):

if key not in [Link]:

Confidential C
return -1

[Link].move_to_end(key)

return [Link][key]

def put(self, key, value):

[Link][key] = value

[Link].move_to_end(key)

if len([Link]) > [Link]:

[Link](last=False)

lru = LRUCache(2)

[Link](1, 1)

[Link](2, 2)

print([Link](1)) # 1

[Link](3, 3) # removes key 2

print([Link](2)) # -1

📊 3. Histogram Frequency Counter using [Link]

python

CopyEdit

from collections import Counter

def histogram(data):

count = Counter(data)

for k in sorted(count):

print(f"{k}: {'#' * count[k]}")

histogram("mississippi")

Confidential C
🧠 4. Detect Loop in Linked List (Floyd’s Cycle Detection)

python

CopyEdit

class Node:

def __init__(self, val):

[Link] = val

[Link] = None

def has_cycle(head):

slow = fast = head

while fast and [Link]:

slow = [Link]

fast = [Link]

if slow == fast:

return True

return False

# Create test list with cycle

a = Node(1)

b = Node(2)

c = Node(3)

[Link] = b

[Link] = c

[Link] = a # cycle

print(has_cycle(a)) # True

📈 5. Kadane’s Algorithm (Max Subarray Sum)

python

CopyEdit

Confidential C
def max_subarray(arr):

max_sum = curr = arr[0]

for val in arr[1:]:

curr = max(val, curr + val)

max_sum = max(max_sum, curr)

return max_sum

print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # 6

🧮 6. Evaluate Postfix Expression

python

CopyEdit

def eval_postfix(expr):

stack = []

for token in [Link]():

if [Link]():

[Link](int(token))

else:

b, a = [Link](), [Link]()

if token == '+': [Link](a + b)

elif token == '-': [Link](a - b)

elif token == '*': [Link](a * b)

elif token == '/': [Link](int(a / b))

return stack[0]

print(eval_postfix("5 1 2 + 4 * + 3 -")) # 14

📐 7. N-Queens Problem (Backtracking)

python

Confidential C
CopyEdit

def solve_n_queens(n):

board = []

def is_safe(pos, row, col):

for r, c in enumerate(pos):

if c == col or abs(r - row) == abs(c - col):

return False

return True

def backtrack(row=0, pos=[]):

if row == n:

[Link](pos)

return

for col in range(n):

if is_safe(pos, row, col):

backtrack(row + 1, pos + [col])

backtrack()

return board

print(len(solve_n_queens(8))) # 92 solutions

🧩 8. Merge Intervals

python

CopyEdit

def merge_intervals(intervals):

[Link]()

merged = [intervals[0]]

for start, end in intervals[1:]:

Confidential C
last_end = merged[-1][1]

if start <= last_end:

merged[-1][1] = max(last_end, end)

else:

[Link]([start, end])

return merged

print(merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]))

🔁 9. Producer-Consumer using Threading and Queue

python

CopyEdit

import threading

import queue

import time

q = [Link]()

def producer():

for i in range(5):

print("Produced", i)

[Link](i)

[Link](0.5)

def consumer():

while True:

item = [Link]()

print("Consumed", item)

q.task_done()

Confidential C
t1 = [Link](target=producer)

t2 = [Link](target=consumer, daemon=True)

[Link]()

[Link]()

[Link]()

[Link]()

📄 10. CSV Parser with Summary Stats

python

CopyEdit

import csv

def parse_csv(file_path):

with open(file_path, newline='') as f:

reader = [Link](f)

data = list(reader)

total = sum(float(row['Amount']) for row in data)

print("Total:", total)

# Sample CSV format: Name, Amount

# You can use this if file I/O is allowed during interview

# parse_csv("[Link]")

Confidential C

You might also like