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

Python Practice Questions

This document provides a comprehensive collection of Python practice questions categorized by topics, difficulty levels, and the number of questions available. It covers essential Python concepts such as variables, data types, strings, lists, dictionaries, functions, and algorithms, with a total of over 90 questions. Each topic includes easy, moderate, and tough questions, along with hints to aid in problem-solving.

Uploaded by

vikigadhiya7011
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 views24 pages

Python Practice Questions

This document provides a comprehensive collection of Python practice questions categorized by topics, difficulty levels, and the number of questions available. It covers essential Python concepts such as variables, data types, strings, lists, dictionaries, functions, and algorithms, with a total of over 90 questions. Each topic includes easy, moderate, and tough questions, along with hints to aid in problem-solving.

Uploaded by

vikigadhiya7011
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

■ PYTHON

PRACTICE QUESTIONS
World-Class Coding Practice — Topic-Wise

10 3 90+
Topics Difficulty Levels Questions

Your Python Tutor • Claude AI • Practice. Debug. Master.

Variables, Data Types & I/O • Strings & String Methods • Lists, Tuples & Sets • Dictionaries • Functions & Recursion •
OOP (Classes & Objects) • File Handling • Exceptions & Error Handling • Comprehensions & Generators • Algorithms &
Problem Solving

Python Practice Questions — World Class Edition Page 1


TABLE OF CONTENTS

Easy:5 Med:3 Hard:2 | Total:


01 Topic 1 — Variables, Data Types & I/O
10

Easy:5 Med:4 Hard:3 | Total:


02 Topic 2 — Strings & String Methods
12

Easy:5 Med:4 Hard:3 | Total:


03 Topic 3 — Lists, Tuples & Sets
12

04 Topic 4 — Dictionaries Easy:4 Med:3 Hard:2 | Total: 9

Easy:4 Med:4 Hard:3 | Total:


05 Topic 5 — Functions & Recursion
11

06 Topic 6 — OOP (Classes & Objects) Easy:3 Med:4 Hard:2 | Total: 9

07 Topic 7 — File Handling Easy:3 Med:2 Hard:1 | Total: 6

08 Topic 8 — Exceptions & Error Handling Easy:2 Med:2 Hard:1 | Total: 5

09 Topic 9 — Comprehensions & Generators Easy:3 Med:3 Hard:1 | Total: 7

Easy:3 Med:4 Hard:3 | Total:


10 Topic 10 — Algorithms & Problem Solving
10

Python Practice Questions — World Class Edition Page 2


HOW TO USE THIS BOOK

GREEN — Easy Start here. Build confidence. Solve without hints first.

ORANGE — Core interview-level. Must master all. Try timed (15 min each).
Moderate

RED — Tough Competitive programming level. Use hints only if stuck 30+ min.

Hint Box Read hint only after a genuine attempt. Hints give direction, not solution.

Python Practice Questions — World Class Edition Page 3


Topic 1 — Variables, Data Types & I/O

◆ EASY (5 Questions)

Q1.
Write a program that takes a user's name and age as input and prints:
"Hello, ! You were born in ."
Hint: Use input(), int(), and current year arithmetic.

Q2.
Given two integer variables a = 15 and b = 4, print the result of all arithmetic operators: +, -,
*, /, //, %, **
Hint: Print each operation on a separate line with a label.

Q3.
Write a program that swaps two variables WITHOUT using a third variable.
Hint: Python allows: a, b = b, a

Q4.
Take a float as input (e.g., 3.14159) and print it rounded to 2 decimal places, as an integer,
and as a string.
Hint: Use round(), int(), str()

Q5.
Write a program that checks the type of each: 42, 3.14, 'hello', True, None — and prints the
type.
Hint: Use type() or isinstance()

◆ MODERATE (3 Questions)

Q6.
Write a program to check whether a given number is: positive/negative/zero AND even/odd
— all in one output line.
Hint: Combine both checks using nested if-else or logical operators.

Python Practice Questions — World Class Edition Page 4


Q7.
Accept a temperature in Celsius and convert it to both Fahrenheit and Kelvin. Display results
formatted to 2 decimal places.
Hint: F = C * 9/5 + 32; K = C + 273.15

Q8.
Write a program that takes a 10-digit mobile number as a string and prints it in the format:
+91-XXXXX-XXXXX
Hint: Use string slicing: num[:5] and num[5:]

◆ TOUGH (2 Questions)

Q9.
Write a program that takes any expression as a string (e.g., '3 + 5 * 2') and evaluates it safely
— without using eval(). Handle +, -, *, / operators and proper operator precedence.
Hint: Parse tokens manually. Build a recursive descent parser or use a stack-based approach for precedence.

Q10.
Implement a custom type-casting function my_cast(value, target_type) that converts a value
to int, float, bool, or str — and raises a descriptive TypeError with the attempted conversion
details if it fails.
Hint: Use try/except blocks for each conversion. Consider edge cases: bool('False'), int(True), float('inf').

Python Practice Questions — World Class Edition Page 5


Topic 2 — Strings & String Methods

◆ EASY (5 Questions)

Q1.
Write a function is_palindrome(s) that returns True if the string is a palindrome (ignore case
and spaces).
Hint: Clean the string first: [Link]().replace(' ', '')

Q2.
Count the number of vowels and consonants in a given string (ignore spaces and digits).
Hint: Iterate each character and check membership in 'aeiou'.

Q3.
Reverse each word in a sentence individually (not the whole sentence).
Input: 'Hello World' → Output: 'olleH dlroW'
Hint: Split, reverse each word, join back.

Q4.
Write a program to check if two strings are anagrams of each other.
Hint: sorted([Link]()) == sorted([Link]())

Q5.
Remove all duplicate characters from a string while preserving the original order.
Input: 'programming' → Output: 'progamin'
Hint: Use a seen set while building result.

◆ MODERATE (4 Questions)

Q6.
Write a function title_case(s) that converts a sentence to title case — but keeps words like
'a', 'an', 'the', 'in', 'of', 'and' lowercase (unless they are the first word).
Hint: Define a set of exception words. Capitalize first word always.

Python Practice Questions — World Class Edition Page 6


Q7.
Implement your own version of [Link]() — a function my_format(template, **kwargs) that
replaces {key} placeholders in a string.
Hint: Use [Link] or manual scanning to locate {key} patterns.

Q8.
Find the longest substring without repeating characters.
Input: 'abcabcbb' → Output: 'abc' (length 3)
Hint: Use sliding window with a dictionary tracking last seen index.

Q9.
Write a Caesar cipher: encrypt(text, shift) and decrypt(text, shift). Handle both upper and
lowercase letters; leave non-alpha characters unchanged.
Hint: Use ord() and chr(). Remember to wrap around with % 26.

◆ TOUGH (3 Questions)

Q10.
Implement a run-length encoding (RLE) compressor and decompressor.
encode('aaabbbccddddee') → '3a3b2c4d2e'
decode('3a3b2c4d2e') → 'aaabbbccddddee'
Hint: For encode, use [Link] or manual counting. For decode, parse digits then character.

Q11.
Write a function that finds ALL permutations of a given string — without using itertools — and
returns them as a sorted list (no duplicates).
Hint: Use backtracking/recursion. Track used indices. Use a set to eliminate duplicates.

Q12.
Implement a simple regex engine that supports: . (any char), * (zero or more of previous), ^
(start), $ (end).
is_match('aab', 'c*a*b') should return True.
Hint: Use recursive matching. Handle '*' by trying zero or more of the preceding element.

Python Practice Questions — World Class Edition Page 7


Topic 3 — Lists, Tuples & Sets

◆ EASY (5 Questions)

Q1.
Given a list of numbers, find: minimum, maximum, sum, and average — WITHOUT using
built-in min(), max(), sum() functions.
Hint: Initialize with first element. Loop and compare/accumulate.

Q2.
Remove all duplicates from a list and return it sorted.
Input: [3,1,4,1,5,9,2,6,5,3] → Output: [1,2,3,4,5,6,9]
Hint: Convert to set, then back to list and sort.

Q3.
Rotate a list to the right by k positions.
Input: [1,2,3,4,5], k=2 → Output: [4,5,1,2,3]
Hint: Use list slicing: lst[-k:] + lst[:-k]

Q4.
Flatten a 2D list (list of lists) into a single list.
Input: [[1,2],[3,4],[5,6]] → Output: [1,2,3,4,5,6]
Hint: List comprehension: [x for row in matrix for x in row]

Q5.
Find the second largest element in a list WITHOUT sorting.
Input: [10, 20, 4, 45, 99] → Output: 45
Hint: Track first_max and second_max in a single pass.

◆ MODERATE (4 Questions)

Q6.
Write a function that groups a list of words by their length.
Input: ['cat','dog','elephant','ant','bee']
Output: {3: ['cat','dog','ant','bee'], 8: ['elephant']}
Hint: Use a dictionary. For each word, append to dict[len(word)].

Python Practice Questions — World Class Edition Page 8


Q7.
Implement merge sort on a list without using sorted() or [Link]().
Hint: Split list in half recursively. Merge two sorted halves by comparing elements.

Q8.
Given a list of integers, find all pairs (a, b) such that a + b = target.
Return unique pairs (no duplicates, order doesn't matter).
Hint: Use a set to track seen numbers. For each x, check if target-x is in seen.

Q9.
Write a function that returns the most frequent element in a list. If there's a tie, return all tied
elements as a list.
Hint: Use a Counter or build a frequency dict. Find max frequency, then collect all keys with that frequency.

◆ TOUGH (3 Questions)

Q10.
Find all subsets (power set) of a list. The power set of [1,2,3] is: [[], [1], [2], [3], [1,2], [1,3],
[2,3], [1,2,3]].
Do NOT use itertools.
Hint: Use bitmask: for each number from 0 to 2^n-1, include elements where corresponding bit is set.

Q11.
Given an unsorted list, find the length of the longest consecutive sequence.
Input: [100,4,200,1,3,2] → Output: 4 (sequence: 1,2,3,4)
Must run in O(n) time.
Hint: Convert to set. For each number, only start counting if num-1 is NOT in the set (start of a sequence).
Count upward.

Q12.
Implement a data structure using only Python lists (no dict/set) that supports: add(x),
remove(x), contains(x), get_random() — all in O(1) average time.
Hint: Use two parallel lists: one as the array, one as index tracker. For remove, swap with last element.

Python Practice Questions — World Class Edition Page 9


Topic 4 — Dictionaries

◆ EASY (4 Questions)

Q1.
Count the frequency of each character in a string using a dictionary.
Input: 'banana' → Output: {'b':1, 'a':3, 'n':2}
Hint: Use [Link](char, 0) + 1 pattern, or [Link].

Q2.
Merge two dictionaries. If a key exists in both, add the values.
d1 = {'a':1,'b':2}, d2 = {'b':3,'c':4} → {'a':1,'b':5,'c':4}
Hint: Start with [Link](). Iterate d2; for existing keys, add values.

Q3.
Invert a dictionary (swap keys and values). Handle duplicate values by storing all original
keys in a list.
Input: {'a':1,'b':2,'c':1} → {1:['a','c'], 2:['b']}
Hint: Use [Link](v, []).append(k)

Q4.
Find the top-3 most frequent words in a paragraph of text. Ignore case and punctuation.
Hint: Use [Link](), [Link] or [Link]. Build frequency dict, then sort by value descending.

◆ MODERATE (3 Questions)

Q5.
Implement a simple phonebook using a dictionary:
- add_contact(name, number)
- search_contact(name)
- delete_contact(name)
- list_all() — sorted alphabetically
Hint: Store as {name: number}. For search, handle KeyError gracefully.

Python Practice Questions — World Class Edition Page 10


Q6.
Given a list of student records as dicts [{'name':..,'score':..}], group students into grade
bands: A(90-100), B(80-89), C(70-79), D(60-69), F(<60). Return counts per band.
Hint: Use integer division (score//10) to determine band quickly.

Q7.
Write a function that deeply compares two nested dictionaries and returns a list of
differences (keys whose values differ or keys missing in either).
Hint: Recursively compare. If both values are dicts, recurse. Otherwise compare directly.

◆ TOUGH (2 Questions)

Q8.
Implement an LRU Cache (Least Recently Used) using only a dict and a doubly-linked list
(no OrderedDict or functools.lru_cache).
Support: get(key), put(key, value) — both in O(1).
Hint: Dict maps keys to nodes. Doubly linked list maintains order (head=most recent, tail=least). On get/put,
move node to head. On overflow, remove tail.

Q9.
Given a list of transactions: [{'from':'A','to':'B','amount':10}, ...], compute the minimum number
of transactions to settle all debts.
Return the settlement list.
Hint: Compute net balance per person. Use two heaps (max-creditors, max-debtors). Greedily settle: match
largest creditor with largest debtor.

Python Practice Questions — World Class Edition Page 11


Topic 5 — Functions & Recursion

◆ EASY (4 Questions)

Q1.
Write a recursive function to compute the factorial of n. Add memoization to avoid redundant
calculations.
Hint: Base case: factorial(0) = 1. Memoize using a dict.

Q2.
Write a function that accepts *args and **kwargs and prints:
- Total positional arguments
- Sum of all numeric positional arguments
- All keyword arguments as 'key=value' pairs
Hint: Filter args with isinstance(x, (int,float)) for sum.

Q3.
Write a function power(base, exp) using recursion (no ** operator or [Link]).
Handle negative exponents.
Hint: Negative exp: return 1/power(base, -exp). Base case: exp==0 returns 1.

Q4.
Implement a decorator @timer that prints how long a function took to execute.
Hint: Use [Link]() or time.perf_counter() before and after the wrapped call.

◆ MODERATE (4 Questions)

Q5.
Write a recursive function to compute the nth Fibonacci number in O(log n) time using matrix
exponentiation.
Hint: [[1,1],[1,0]]^n gives Fibonacci numbers. Use fast matrix power (repeated squaring).

Python Practice Questions — World Class Edition Page 12


Q6.
Implement function currying: curry(f) takes a function f(a,b,c) and returns a curried version so
you can call it as curry(f)(1)(2)(3).
Hint: Use a closure that accumulates arguments and calls f when enough are collected. Use
f.__code__.co_argcount to know how many args are needed.

Q7.
Write a memoize decorator that works for functions with any hashable arguments (including
*args and **kwargs).
Hint: Cache key: (args, tuple(sorted([Link]()))). Use [Link].

Q8.
Solve the Tower of Hanoi for n disks. Print each move. Then count the minimum moves
required for n=20 (do NOT simulate — derive the formula and verify).
Hint: Minimum moves = 2^n - 1. Simulate only small n to verify your recursive code is correct.

◆ TOUGH (3 Questions)

Q9.
Implement a tail-call optimized version of recursive factorial using trampolining — Python
doesn't optimize TCO by default, so implement the trampoline manually.
Hint: Return a lambda (thunk) instead of making a direct recursive call. The trampoline loop calls the thunk
until a non-callable is returned.

Q10.
Write a generator-based coroutine pipeline:
- producer() yields numbers 1..100
- filter_evens(gen) filters only even numbers
- square(gen) squares each number
- take(gen, n) takes first n results
Chain them: take(square(filter_evens(producer())), 5)
Hint: Each stage is a generator function that takes a generator and yields transformed values. No lists should
be created.

Q11.
Implement Y-combinator in Python to achieve recursion without naming the function.
Use it to compute factorial(5).
Hint: Y = lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))) Apply it to a lambda that
implements factorial logic.

Python Practice Questions — World Class Edition Page 13


Topic 6 — OOP (Classes & Objects)

◆ EASY (3 Questions)

Q1.
Create a BankAccount class with:
- __init__(owner, balance=0)
- deposit(amount), withdraw(amount) — raise ValueError if insufficient funds
- __str__ to display account info
Hint: Check balance before withdraw. Keep balance as a private attribute (_balance).

Q2.
Create a Student class. Implement __lt__, __le__, __eq__ to compare students by their
GPA. Make a list of 5 students sortable using sorted().
Hint: Define __lt__ at minimum. Python derives others with @functools.total_ordering.

Q3.
Create a Rectangle and Circle class both inheriting from Shape. Each must implement area()
and perimeter(). Demonstrate polymorphism with a list of mixed shapes.
Hint: Define abstract base class Shape with abstract methods. Use [Link], @abstractmethod.

◆ MODERATE (4 Questions)

Q4.
Implement a Stack and Queue using Python classes. Both should support:
push/enqueue, pop/dequeue, peek, is_empty, size, __repr__.
Implement Queue using two stacks internally.
Hint: Queue with two stacks: stack_in for enqueue, stack_out for dequeue. Transfer when stack_out is empty.

Q5.
Design a Vector2D class supporting:
- Addition (+), subtraction (-), scalar multiplication (*)
- Dot product (matmul @)
- Magnitude (abs())
- Normalization, angle between two vectors
Hint: Implement __add__, __sub__, __mul__, __rmul__, __matmul__, __abs__.

Python Practice Questions — World Class Edition Page 14


Q6.
Implement the Singleton design pattern in Python using a metaclass. Prove that two
'instances' of the class are the same object.
Hint: Create SingletonMeta(type) that overrides __call__. Store instance in a class-level dict.

Q7.
Create a Polynomial class that:
- Stores coefficients [a0, a1, a2, ...] for a0 + a1*x + a2*x^2 ...
- Supports +, -, * between polynomials
- evaluate(x) computes the value at x
- __str__ returns a human-readable form like '3x^2 + 2x + 1'
Hint: For multiplication, convolve coefficient lists. For __str__, handle zero coefficients and x^1, x^0 edge
cases.

◆ TOUGH (2 Questions)

Q8.
Implement a fully functional Linked List class with:
append, prepend, insert_at, delete_at, reverse (in-place), find_middle (one pass),
detect_and_remove_cycle (Floyd's algorithm), merge_sorted(other).
Hint: For middle: slow/fast pointer. For cycle: Floyd's algorithm — slow moves 1, fast moves 2. For merge:
standard merge of two sorted lists.

Q9.
Build a generic Observable class (Observer pattern):
- subscribe(event, callback)
- unsubscribe(event, callback)
- emit(event, *args, **kwargs) — calls all callbacks for that event
Then build a reactive temperature sensor that emits 'high_alert' when temp > 50.
Hint: Store callbacks as {event: [list of functions]}. emit loops through and calls each.

Python Practice Questions — World Class Edition Page 15


Topic 7 — File Handling

◆ EASY (3 Questions)

Q1.
Write a program that reads a text file and prints:
- Total lines
- Total words
- Total characters (with and without spaces)
- Most common word
Hint: Read with open(). Split lines and words. Use a Counter for word frequency.

Q2.
Write a program that reads a CSV file of student data (name, marks) and writes a new CSV
with a 'Grade' column added based on marks.
Hint: Use [Link] for reading, [Link] for writing.

Q3.
Implement a simple to-do list app that:
- Saves tasks to '[Link]'
- Loads existing tasks on startup
- Supports: add, view, mark done, delete
Hint: Use a JSON file for structured storage instead of plain text if you want easy parsing.

◆ MODERATE (2 Questions)

Q4.
Write a log parser that reads a server log file (format: 'TIMESTAMP LEVEL MESSAGE'),
groups log entries by level (INFO/WARNING/ERROR), and writes a summary report with
counts and the last 3 messages per level.
Hint: Use [Link] or [Link](maxsplit=2). Build a dict per level.

Q5.
Build a file deduplicator: scan a folder, compute MD5 hash of each file, and list all groups of
duplicate files (same content, different names/locations).
Hint: Use hashlib.md5. Read file in chunks for large files. Group paths by hash.

Python Practice Questions — World Class Edition Page 16


◆ TOUGH (1 Questions)

Q6.
Implement a simple database using JSON files:
- create_table(name, schema)
- insert(table, record)
- query(table, **filters) — returns matching records
- delete(table, **filters)
- update(table, filters, updates)
Ensure concurrent-safe writes using file locking.
Hint: Use [Link] or a [Link]. Store each table as a separate JSON file. Load-modify-save on every
write operation.

Python Practice Questions — World Class Edition Page 17


Topic 8 — Exceptions & Error Handling

◆ EASY (2 Questions)

Q1.
Write a safe_divide(a, b) function that handles: ZeroDivisionError, TypeError (non-numeric
input), and returns None for invalid cases with a descriptive print message.
Hint: Use try/except with specific exception types. Add an else clause for success.

Q2.
Write a function that reads an integer from user input, retrying up to 3 times on invalid input,
then raising a custom TooManyAttemptsError.
Hint: Loop with a counter. Catch ValueError on int() conversion failure.

◆ MODERATE (2 Questions)

Q3.
Create a custom exception hierarchy:
AppError (base) → NetworkError, DatabaseError, ValidationError
Each should store a code and message. Demonstrate catching at different levels.
Hint: Each subclass calls super().__init__(message). Add [Link] = code attribute.

Q4.
Implement a context manager class DatabaseConnection using __enter__ and __exit__. It
should: open connection on enter, rollback on exception, commit on success, always close
connection.
Hint: __exit__ receives exc_type, exc_val, exc_tb. Return True to suppress exception, False to propagate.

◆ TOUGH (1 Questions)

Python Practice Questions — World Class Edition Page 18


Q5.
Write a retry decorator with exponential backoff:
@retry(max_attempts=5, base_delay=1.0, exceptions=(ConnectionError, TimeoutError))
It should: wait base_delay * 2^attempt seconds between retries, log each retry with attempt
number and exception, raise the last exception if all retries fail.
Hint: Use [Link](base_delay * (2**attempt)). Track attempt count. Store last exception and re-raise after
exhausting retries.

Python Practice Questions — World Class Edition Page 19


Topic 9 — Comprehensions & Generators

◆ EASY (3 Questions)

Q1.
Using list comprehension, create a list of all prime numbers between 1 and 100.
Hint: Nest: [n for n in range(2,101) if all(n%i!=0 for i in range(2,n))]

Q2.
Use a dict comprehension to create a mapping of {word: len(word)} for all words in a
sentence — but only for words with length > 3.
Hint: {w:len(w) for w in [Link]() if len(w)>3}

Q3.
Write a generator function fibonacci() that yields Fibonacci numbers infinitely. Print the first
20 using islice.
Hint: Maintain two variables a, b. yield a; a, b = b, a+b. Use [Link](fibonacci(), 20).

◆ MODERATE (3 Questions)

Q4.
Write a generator that reads a huge CSV file line by line (without loading it all into memory)
and yields only rows where a specified column matches a condition.
Hint: Use 'with open(file) as f: for line in f: yield ...' — never load all at once.

Q5.
Use nested list comprehensions to create a multiplication table as a 2D list (10x10), then
pretty-print it aligned.
Hint: table = [[i*j for j in range(1,11)] for i in range(1,11)]. Use f'{val:4}' for alignment.

Q6.
Implement a lazy pipeline using generators:
generate_numbers(n) → filter_primes(gen) → square_them(gen) → running_sum(gen)
All lazy — no intermediate lists. Print the first 10 values of the final pipeline.
Hint: Each function is a generator that wraps another generator. running_sum maintains a cumulative total.

Python Practice Questions — World Class Edition Page 20


◆ TOUGH (1 Questions)

Q7.
Implement a coroutine-based data processing pipeline using send():
- A generator that acts as a 'sink' collecting data
- A transformer generator that modifies data using send() and yield
- A source that drives the pipeline
Process a stream of numbers: filter odds, double evens, collect sum.
Hint: Use [Link](value). Remember to call next(gen) or [Link](None) to prime the generator
before sending values.

Python Practice Questions — World Class Edition Page 21


Topic 10 — Algorithms & Problem Solving

◆ EASY (3 Questions)

Q1.
Implement binary search on a sorted list. Return the index if found, else -1.
Hint: Use low, high, mid pointers. Check mid, then narrow left or right half.

Q2.
Given a list of coin denominations and a target amount, find the minimum number of coins to
make the amount. (Greedy approach — assume it works for the given denominations).
Hint: Sort denominations descending. Greedily take as many of the largest as possible.

Q3.
Implement bubble sort and count the number of swaps performed.
Hint: Add a swap_count variable. Increment every time you swap two elements.

◆ MODERATE (4 Questions)

Q4.
Given a matrix of 0s and 1s, count the number of 'islands' (connected groups of 1s —
horizontal/vertical adjacency only).
Hint: BFS or DFS from each unvisited '1'. Mark visited cells. Count how many times you start a new BFS/DFS.

Q5.
Implement the coin change problem using dynamic programming (DP): find the minimum
number of coins to make amount n. Return -1 if impossible.
Coins: [1,5,6,9], amount: 11 → answer: 2 (coins: 5+6)
Hint: dp[i] = min coins to make amount i. dp[0]=0. For each amount, try all coins.

Q6.
Given a string of brackets: '([{}])', determine if it is valid (properly nested and closed).
Handle: (), [], {}, and mixed nesting.
Hint: Use a stack. Push opening brackets. On closing bracket, check if stack top matches.

Python Practice Questions — World Class Edition Page 22


Q7.
Implement Dijkstra's shortest path algorithm for a weighted graph represented as an
adjacency list. Return shortest distances from source to all nodes.
Hint: Use a min-heap (heapq). Start with dist[source]=0. Relax edges greedily.

◆ TOUGH (3 Questions)

Q8.
Solve the N-Queens problem: place N queens on an N×N chessboard so that no two queens
attack each other. Return ALL valid configurations.
For N=8, there are 92 solutions.
Hint: Use backtracking. Track occupied columns, and both diagonals (col-row, col+row) as sets for O(1) attack
check.

Q9.
Implement Huffman Encoding from scratch:
1. Build frequency table from input text
2. Build Huffman tree using a min-heap
3. Generate variable-length binary codes
4. Encode the original text
5. Decode back to verify correctness
Print the compression ratio.
Hint: Use heapq. Each node stores (frequency, character, left_child, right_child). Build codes by traversing the
tree (left='0', right='1').

Q10.
Implement a Trie data structure supporting:
- insert(word)
- search(word) — exact match
- starts_with(prefix) — returns all words with given prefix
- delete(word)
- autocomplete(prefix) — returns top-3 suggestions by insertion order
Hint: Each TrieNode has children dict and is_end_of_word flag. For autocomplete, DFS from prefix node
collecting all complete words.

Python Practice Questions — World Class Edition Page 23


Keep Practicing. Keep Building.

Every expert was once a beginner who refused to give up.

Python Practice Questions — World Class Edition Page 24

You might also like