0% found this document useful (0 votes)
24 views5 pages

Advanced Python Solutions

Uploaded by

braju746508
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)
24 views5 pages

Advanced Python Solutions

Uploaded by

braju746508
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

Advanced Python — Questions & Complete Solutions

A concise collection of advanced Python problems and their worked solutions, focused for placement
preparation.

Core Python & OOP

1. Difference between @classmethod, @staticmethod, and instance method (example):


class Example:
def instance_method(self):
return f"Called instance method: {self}"

@classmethod
def class_method(cls):
return f"Called class method: {cls}"

@staticmethod
def static_method():
return "Called static method"

obj = Example()
print(obj.instance_method())
print(Example.class_method())
print(Example.static_method())

Explanation: Instance methods use 'self', classmethods use 'cls', staticmethods are independent utilities
inside class.

2. Method Resolution Order (MRO) example:


class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass

print([Link]())

Python uses C3 linearization for MRO.

3. Singleton using __new__:


class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance

a = Singleton()
b = Singleton()
print(a is b) # True

4. is vs == example:
a = [1,2,3]
b = [1,2,3]
print(a == b) # True (value equality)
print(a is b) # False (different objects)

5. Garbage collection & reference counting example:


import sys
a = []
b = a
print([Link](a))
del b
print([Link](a))

Note: Python uses reference counting plus a cyclic GC to collect unreachable cycles.

Data Structures & Algorithms

6. LRU Cache using [Link]:


from collections import OrderedDict

class LRUCache:
def __init__(self, capacity: int):
[Link] = OrderedDict()
[Link] = capacity

def get(self, key):


if key not in [Link]:
return -1
[Link].move_to_end(key)
return [Link][key]

def put(self, key, value):


if key in [Link]:
[Link].move_to_end(key)
[Link][key] = value
if len([Link]) > [Link]:
[Link](last=False)

7. Trie (Prefix Tree):


class TrieNode:
def __init__(self):
[Link] = {}
self.is_end = False

class Trie:
def __init__(self):
[Link] = TrieNode()

def insert(self, word):


node = [Link]
for ch in word:
node = [Link](ch, TrieNode())
node.is_end = True

def search(self, word):


node = [Link]
for ch in word:
if ch not in [Link]:
return False
node = [Link][ch]
return node.is_end

trie = Trie()
[Link]('apple')
print([Link]('apple'))

8. K-th largest using heapq:


import heapq

def kth_largest(nums, k):


return [Link](k, nums)[-1]

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

9. Permutations (recursive):
def permute(s, step=0):
if step == len(s):
print(''.join(s))
for i in range(step, len(s)):
s[step], s[i] = s[i], s[step]
permute(s, step+1)
s[step], s[i] = s[i], s[step]

permute(list('ABC'))

10. Rotate matrix 90° clockwise in-place:


def rotate(matrix):
n = len(matrix)
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
[Link]()

m = [[1,2,3],[4,5,6],[7,8,9]]
rotate(m)
print(m) # [[7,4,1],[8,5,2],[9,6,3]]

Advanced Python Concepts

11. Generator for Fibonacci:


def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

print(list(fibonacci(10)))

12. GIL (Global Interpreter Lock):

Explanation: GIL allows one thread at a time to execute Python bytecode. It limits multi-threading
effectiveness for
CPU-bound tasks; for I/O-bound tasks threads work well. Use multiprocessing for CPU-bound work.

13. Multiprocessing vs Multithreading example:


import threading, multiprocessing

def worker():
print('Work!')

t = [Link](target=worker)
[Link](); [Link]()

p = [Link](target=worker)
[Link](); [Link]()

CPU-bound → multiprocessing. I/O-bound → multithreading.

14. Coroutine maintaining running average:


def running_avg():
total, count = 0, 0
avg = None
while True:
num = yield avg
total += num
count += 1
avg = total / count
coro = running_avg()
next(coro)
print([Link](10)) # 10.0
print([Link](20)) # 15.0

15. Custom Context Manager:


class FileManager:
def __init__(self, filename, mode):
[Link], [Link] = filename, mode
def __enter__(self):
[Link] = open([Link], [Link])
return [Link]
def __exit__(self, exc_type, exc_val, exc_tb):
[Link]()

with FileManager('[Link]', 'w') as f:


[Link]('Hello Context!')

Problem Solving Challenges

16. Detect cycle in linked list (Floyd's algorithm):


class Node:
def __init__(self, val):
[Link] = val
[Link] = None

def detect_cycle(head):
slow = fast = head
while fast and [Link]:
slow, fast = [Link], [Link]
if slow == fast:
return True
return False

17. Serialize & Deserialize Binary Tree (preorder with sentinel):


class TreeNode:
def __init__(self, val=0, left=None, right=None):
[Link], [Link], [Link] = val, left, right

def serialize(root):
vals = []
def dfs(node):
if not node:
[Link]('N')
return
[Link](str([Link]))
dfs([Link])
dfs([Link])
dfs(root)
return ','.join(vals)

def deserialize(data):
vals = iter([Link](','))
def dfs():
val = next(vals)
if val == 'N': return None
node = TreeNode(int(val))
[Link], [Link] = dfs(), dfs()
return node
return dfs()

18. Longest substring without repeating characters (sliding window):


def longest_unique_substring(s: str) -> int:
seen = {}
left = max_len = 0
for right, char in enumerate(s):
if char in seen and seen[char] >= left:
left = seen[char] + 1
seen[char] = right
max_len = max(max_len, right - left + 1)
return max_len

print(longest_unique_substring('abcabcbb'))

19. N-Queens (backtracking):


def solveNQueens(n):
res = []
board = [['.']*n for _ in range(n)]

def is_safe(r, c):


for i in range(r):
if board[i][c] == 'Q': return False
i, j = r-1, c-1
while i >= 0 and j >= 0:
if board[i][j] == 'Q': return False
i, j = i-1, j-1
i, j = r-1, c+1
while i >= 0 and j < n:
if board[i][j] == 'Q': return False
i, j = i-1, j+1
return True

def backtrack(r):
if r == n:
[Link]([''.join(row) for row in board])
return
for c in range(n):
if is_safe(r, c):
board[r][c] = 'Q'
backtrack(r+1)
board[r][c] = '.'

backtrack(0)
return res

print(solveNQueens(4))

20. Producer-Consumer using threading + queue:


import threading, queue, time

q = [Link]()

def producer():
for i in range(5):
[Link](i)
print(f'Produced {i}')
[Link](1)

def consumer():
while True:
item = [Link]()
print(f'Consumed {item}')
q.task_done()

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

[Link](); [Link]()
[Link](); [Link]()

End of document. Use this PDF to revise and practice — run the code snippets in your local Python
environment to test
and modify them.

You might also like