Logic Building & Problem Solving in Python
Coding test rounds at IT service companies and product startups evaluate algorithmic reasoning, corner case handling, and space-time efficiency. Below are core coding patterns extracted from our Basic Programs & Logic Handbook.
1. Prime Number Checking with Optimized Square-Root Bound
Checking divisibility up to √N reduces time complexity from O(N) to O(√N).
import math
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n in (2, 3):
return True
if n % 2 == 0 or n % 3 == 0:
return False
# Check 6k +/- 1 primes
for i in range(5, int(math.isqrt(n)) + 1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
print("Is 97 prime?", is_prime(97)) # True
print("Is 100 prime?", is_prime(100)) # False
2. String Anagram Detection (Hash Map vs Sorting)
from collections import Counter
def are_anagrams(s1: str, s2: str) -> bool:
# Clean whitespace and case
clean_s1 = s1.replace(" ", "").lower()
clean_s2 = s2.replace(" ", "").lower()
return Counter(clean_s1) == Counter(clean_s2)
print("Listen & Silent:", are_anagrams("Listen", "Silent")) # True
3. Flattening Nested Arrays Recursively
def flatten(nested_list: list) -> list:
flat = []
for item in nested_list:
if isinstance(item, list):
flat.extend(flatten(item))
else:
flat.append(item)
return flat
sample = [1, [2, [3, 4], 5], 6, [7, 8]]
print("Flattened:", flatten(sample)) # [1, 2, 3, 4, 5, 6, 7, 8]