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

Key Python Programming Concepts Explained

The document outlines important Python programming questions and their explanations, covering topics such as anagrams, recursion, file handling, and data structures. Each question includes an example, complexity analysis, and additional notes where relevant. It serves as a comprehensive guide for understanding key Python concepts and coding practices.

Uploaded by

dhronyadav1818
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)
6 views11 pages

Key Python Programming Concepts Explained

The document outlines important Python programming questions and their explanations, covering topics such as anagrams, recursion, file handling, and data structures. Each question includes an example, complexity analysis, and additional notes where relevant. It serves as a comprehensive guide for understanding key Python concepts and coding practices.

Uploaded by

dhronyadav1818
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 Programming Important Question

1. Check if two strings are anagrams.


Explanation: Two strings are anagrams if they contain the same characters with
the same multiplicities, but possibly in different orders. Common approaches:
• Sort both strings and compare (simple, cost: sorting).
• Count frequencies of characters (using a dictionary or [Link]);
compare counts (more efficient when many repeated characters).
Complexity: Sorting approach: O(n log n). Counting approach: O(n).
Example:

s1 = "listen"
s2 = "silent"
# Simple
print(sorted(s1) == sorted(s2))
# Efficient (linear)
from collections import Counter
print(Counter(s1) == Counter(s2))

Notes: Normalize case and remove spaces/punctuation if comparing phrases (e.g.,


“Dormitory” vs “Dirty room”).
2. Reverse every word in a string.
Explanation: ”Reverse every word” means keep word order, but reverse characters
inside each word. Use split() to separate words and string slicing [::-1] to
reverse characters.
Complexity: O(n) where n is total characters (each char processed once).
Example:

s = "python language"
rev_words = " ".join(w[::-1] for w in [Link]())
print(rev_words) # "nohtyp egaugnal"

Note: Preserve punctuation rules: splitting by whitespace may include punctuation


attached to words.
3. Explain recursion with factorial example.
Explanation: Recursion is when a function calls itself to solve subproblems. Each
recursive call should make progress toward a base case. For factorial:
(
1 n = 0 or 1
fact(n) =
n × fact(n − 1) n > 1

Complexity: Time O(n), space O(n) due to call stack (unless tail-call elimination
is available — Python does not do TCO).
Example:

1
def fact(n):
if n <= 1:
return 1
return n * fact(n-1)

Note: For large n, recursion may hit recursion limit; use iterative method or
[Link]().

4. Difference between text and binary files.


Explanation:

• Text files: Human-readable, sequence of characters encoded (ASCII/UTF-8).


Open with modes like "r", "w".
• Binary files: Raw bytes (images, executables). Use modes like "rb", "wb".
No character encoding/decoding is applied by Python.

Pitfall: Always open in correct mode. Reading binary as text can corrupt data or
raise decoding errors.

5. Find vowels in a string.


Explanation: Iterate over characters and select those present in the vowel set.
Consider case normalization.
Complexity: O(n).
Example:

s = "education"
vowels = set("aeiou")
found = [ch for ch in [Link]() if ch in vowels]
print(found) # [’e’,’u’,’a’,’i’,’o’,’n’? no ’n’ not vowel]

6. Find frequency of characters.


Explanation: Use a dictionary to map characters to counts. [Link]
is concise and optimized.
Complexity: O(n).
Example:

s = "banana"
freq = {}
for ch in s:
freq[ch] = [Link](ch, 0) + 1
# or
from collections import Counter
freq = Counter(s)
print(freq) # Counter({’a’:3,’n’:2,’b’:1})

2
7. Program to unzip list of tuples.
Explanation: Use argument unpacking with zip(*). This effectively transposes
the list-of-tuples into tuples of each element position.
Complexity: O(n) where n is number of tuples.
Example:

data = [(1,2),(3,4),(5,6)]
a, b = zip(*data)
print(a, b) # (1,3,5) (2,4,6)

8. Explain list comprehension with example.


Explanation: List comprehension provides a concise way to build lists. Equivalent
to a for-loop but often more readable and concise.
Complexity: Same as equivalent loop; depends on operations.
Example:

nums = [2,3,4]
op = [(x, x**3) for x in nums]
print(op) # [(2,8),(3,27),(4,64)]

Tip: For complex logic, use a generator or normal loop for readability.

9. Difference between write() and writelines().


Explanation:

• write(str): writes the single string str to file.


• writelines(listo fs trings) : writeseachstringf romthelistsequentially; doesnotaddnewlin

Example:

with open("[Link]", "w") as f:


[Link]("Hello\n")
[Link](["Line1\n","Line2\n"])

10. Check palindrome string.


Explanation: Normalize case and remove non-alphanumeric characters if needed.
The fastest simple check is to compare with reversed string.
Complexity: O(n).
Example:

s = "Madam, I’m Adam"


import re
t = [Link](r’[^a-z0-9]’, ’’, [Link]())
print(t == t[::-1])

3
11. Remove punctuation from a string.
Explanation: Use [Link] or regex to remove punctuation. For
performance on large strings, use [Link]() with a translation table.
Example:

import string
s = "hello!! world??"
table = [Link](’’, ’’, [Link])
print([Link](table)) # "hello world"

12. Second largest number without max().


Explanation: Sort and pick second last — simple but O(n log n). More efficient:
single-pass keep track of largest and second largest (O(n), constant space).
Example (single pass):

nums = [5,9,2,7]
first = second = float(’-inf’)
for x in nums:
if x > first:
second = first
first = x
elif x > second and x != first:
second = x
print(second) # 7

13. Explain pass, break, continue with examples.


Explanation:

• pass: does nothing, placeholder where syntax requires a statement.


• break: exit loop immediately.
• continue: skip remainder of current iteration and continue with next.

Example:

for i in range(5):
if i == 2: continue
if i == 4: break
if i == 1: pass # no-op
print(i)
# prints 0,1,3

14. Multiply two 2×2 matrices.


P
Explanation: Matrix multiplication: Cij = k Aik Bkj . For 2×2, implement
nested loops. For general matrices, check dimension compatibility.
Complexity: naive multiplication O(n3 ) for n × n matrices.
Example:

4
A = [[1,2],[3,4]]
B = [[5,6],[7,8]]
C = [[0,0],[0,0]]
for i in range(2):
for j in range(2):
C[i][j] = sum(A[i][k]*B[k][j] for k in range(2))
print(C) # [[19,22],[43,50]]

15. Explain seek() and tell().


Explanation:

• seek(offset, whence) moves file cursor. whence=0 from start, 1 current, 2


end.
• tell() returns current file position (byte offset).

Example:

f = open("[Link]", "rb")
[Link](10)
pos = [Link]()
[Link]()

16. Reverse a string.


Explanation: Easiest: slice with step -1. Other ways: reversed() or iterative.
Complexity: O(n).
Example:

s = "Python"
print(s[::-1]) # "nohtyP"

17. Create a dictionary of squares 1–15.


Explanation: Use dictionary comprehension for concise, readable code.
Example:

d = {i: i*i for i in range(1,16)}


print(d)

18. What is a dictionary? How does it differ from a list?


Explanation:

• Dictionary: Unordered (in older Python — ordered insertion in Python


3.7+), stores key-value pairs, average O(1) lookup by key (hash table).
• List: Ordered collection, indexed by integer, lookup by index is O(1) but
search by value is O(n).

Use cases: Use a dict when you need named access to values (e.g., counts, lookups).

5
19. Swapcase characters.
Explanation: [Link]() returns a new string where each letter’s case is
inverted. Useful for simple text transforms.
Example:

s = "Hello World"
print([Link]()) # "hELLO wORLD"

20. Explain module with example.


Explanation: Module = Python file (.py) containing functions, classes, variables.
Import to reuse code. Packages are directories containing init .py.
Example:

# Use built-in math module


import math
print([Link](25))
# Create your module [Link] and import it.

21. Find words with more than 5 letters from a file.


Explanation: Read file content, split into words, filter by length. Consider
punctuation trimming and memory if file is large (iterate line by line).
Example (line-by-line):

with open("[Link]") as f:
for line in f:
for w in [Link]():
w = [Link](".,!?;:\"’()[]")
if len(w) > 5:
print(w)

22. Copy content of one file to another.


Explanation: For text files, read and write. For large files, do it chunked. Use
binary modes for non-text files.
Example:

with open("[Link]", "rb") as fr, open("[Link]","wb") as fw:


while True:
chunk = [Link](8192)
if not chunk: break
[Link](chunk)

23. Tuple explanation with example.


Explanation: Tuples are immutable ordered sequences. Use them for fixed
collections, keys (since immutable), or to return multiple values. Slightly more
memory efficient than lists.
Example:

6
t = (10, 20, 30)
a, b, c = t # unpacking

24. Program to merge two dictionaries.


Explanation: In Python 3.5+, dict unpacking {**a, **b} merges. In 3.9+, a |
b returns merged dict. update() modifies in-place.
Example:

a = {"x":1}
b = {"y":2}
c = {**a, **b} # {’x’:1,’y’:2’}
# or in-place
[Link](b)

25. Count lines, words, characters.


Explanation: Read file content and compute counts. For huge files stream line by
line to save memory.
Example:

with open("[Link]","r", encoding="utf-8") as f:


lines = 0; words = 0; chars = 0
for line in f:
lines += 1
words += len([Link]())
chars += len(line)
print(lines, words, chars)

26. Print lines starting with I or C.


Explanation: Iterate lines and use [Link] which can accept a tuple of
prefixes.
Example:

with open("[Link]") as f:
for line in f:
if [Link](("I","C")):
print([Link]())

27. Difference: Python lists vs arrays.


Explanation:

• List: Python built-in dynamic array; stores references to objects of any type.
• [Link]: stores C-style homogenous numeric data more compactly; effi-
cient for numeric loops but less common than NumPy arrays.
• NumPy arrays: (external library) provide high-performance operations on
homogeneous numeric arrays and are standard for scientific computing.

7
28. Local vs global variables.
Explanation: Local variables are defined inside functions and have function scope.
Global variables are defined at module level. Use global keyword to assign to a
global variable inside a function (but generally avoid global state).
Example:

x = 10 # global
def f():
y = 5 # local
global x
x = x + 1

29. Lambda function example.


Explanation: Lambda creates anonymous functions useful for inline short func-
tions, e.g., with map, sorted key, etc. Avoid long logic inside lambda.
Example:

square = lambda x: x*x


print(square(5)) # 25
# as key:
pairs = [(1,2),(3,1),(2,5)]
[Link](key=lambda p: p[1])

30. Remove duplicate characters from a string.


Explanation: If order must be preserved, iterate and add unseen characters to
result. If order doesn’t matter, convert to set.
Complexity: O(n).
Example (preserve order):

s = "python programming"
res = []
seen = set()
for ch in s:
if ch not in seen:
[Link](ch)
[Link](ch)
print("".join(res))

31. Explain slicing with example.


Explanation: Slicing extracts subsequences: seq[start:stop:step]. Negative
indices allowed; [::-1] reverses sequence.
Example:

s = "PythonProgramming"
print(s[2:8]) # substring from index 2 to 7
print(s[::-1]) # reverse

8
32. Check if a number is prime.

Explanation: Check divisibility up to n. Handle edge cases n < 2. For many
checks, use optimized wheel or sieve for ranges.

Complexity: O( n).
Simple Example:

def is_prime(n):
if n < 2: return False
if n == 2: return True
if n%2==0: return False
i = 3
while i*i <= n:
if n % i == 0: return False
i += 2
return True

33. Write odd/even numbers to separate files.


Explanation: Read numbers (one per line) and write to the appropriate file. Use
buffered writes and close files using with.
Example:

with open("[Link]") as f, open("[Link]","w") as fo, open("[Link]","w") as


for line in f:
n = int([Link]())
if n % 2 == 0:
[Link](str(n)+"\n")
else:
[Link](str(n)+"\n")

34. Explain update() of dictionary.


Explanation: [Link](other) merges key-value pairs from other into d, over-
writing existing keys. Accepts mapping or iterable of key-value pairs.
Example:

d = {’a’:1}
[Link]({’b’:2, ’a’:3})
# d is {’a’:3,’b’:2}

35. Convert lists to dictionary using zip().


Explanation: zip(keys, values) pairs corresponding elements; dict() con-
structs mapping.
Example:

keys = ["a","b","c"]
vals = [1,2,3]
print(dict(zip(keys, vals))) # {’a’:1,’b’:2,’c’:3}

9
36. Explain exception handling (try–except).
Explanation: Use try to run code that may raise errors and except to handle
specific exceptions. Optionally use finally to run cleanup code and else for code
when no exception occurs.
Best practices: Catch specific exceptions, not bare except:.
Example:

try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print("Other error:", e)
finally:
print("Cleanup")

37. Explain flush(), rename(), remove(), truncate().


Explanation:
• flush(): flush OS buffer — forces buffered write to disk (file object).
• [Link](src,dst): rename a file.
• [Link](path): delete a file.
• [Link](size): resize file to size bytes (current position if omitted).
Example:

import os
f = open("[Link]","w")
[Link]("hello")
[Link]()
[Link]()
[Link]("[Link]","[Link]")
[Link]("[Link]")

38. Explain map() with example.


Explanation: map(func, iterable) applies func to each element; returns a lazy
iterator in Python 3. Useful with list() to realize the result.
Example:

nums = [1,2,3]
squares = list(map(lambda x: x*x, nums))
print(squares) # [1,4,9]

39. Explain filter() with example.


Explanation: filter(func, iterable) returns elements where func(element)
is truthy. Returns iterator in Python 3.
Example:

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

40. Explain range() with examples.


Explanation: range(start, stop, step) produces an immutable sequence of
integers. Common uses in loops. Memory-efficient (iterator-like).
Examples:

list(range(5)) # [0,1,2,3,4]
list(range(1,10,2)) # [1,3,5,7,9]
for i in range(10):
pass

Notes: Negative step to iterate in reverse. range is ideal for index-based loops.

11

You might also like