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

Essential Python Coding Concepts

The document provides a comprehensive guide to various Python programming concepts, including string manipulation, data structures, statistics, and machine learning techniques. It covers essential coding tasks and algorithms, such as reversing strings, checking for palindromes, and performing data analysis using libraries like Pandas and NumPy. Additionally, it includes practical examples and common interview questions related to these topics.

Uploaded by

Cathy Catherine
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)
6 views7 pages

Essential Python Coding Concepts

The document provides a comprehensive guide to various Python programming concepts, including string manipulation, data structures, statistics, and machine learning techniques. It covers essential coding tasks and algorithms, such as reversing strings, checking for palindromes, and performing data analysis using libraries like Pandas and NumPy. Additionally, it includes practical examples and common interview questions related to these topics.

Uploaded by

Cathy Catherine
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

1️⃣ String & Array Basics (VERY Create DataFrame & basic operations 9️⃣ Dictionary & Hashing

onary & Hashing (VERY


COMMON) import pandas as pd COMMON)
Reverse a string df = [Link]({ Character frequency
s = "hello" 'name': ['A','B','C'], s = "interview"
print(s[::-1]) 'salary': [50000,60000,55000] freq = {}
Check palindrome }) for c in s:
s = "madam" print(df['salary'].mean()) freq[c] = [Link](c, 0) + 1
print(s == s[::-1]) Filter rows print(freq)
Count vowels in a string df[df['salary'] > 55000] First non-repeating character
s = "datascience" GroupBy s = "swiss"
vowels = "aeiou" [Link]('name')['salary'].sum() for c in s:
count = sum(1 for c in s if c in vowels) 📌 Often asked verbally if not hands-on if [Link](c) == 1:
print(count) print(c)
Find duplicate elements in a list 5️⃣ Statistics + Logic Coding (Data break
lst = [1,2,3,2,4,1] Science Specific)
duplicates = set([x for x in lst if Mean, Median, Mode 🔟 List Manipulation
[Link](x) > 1]) import statistics Rotate list
print(duplicates) data = [1,2,2,3,4] lst = [1,2,3,4,5]
print([Link](data)) k=2
2️⃣ Number-Based Programs (Logic print([Link](data)) print(lst[k:] + lst[:k])
Check) print([Link](data)) Flatten nested list
Prime number check Standard deviation lst = [[1,2],[3,4],[5]]
n=7 import numpy as np flat = [i for sub in lst for i in sub]
is_prime = n > 1 and all(n % i != 0 for i data = [Link]([10,20,30]) print(flat)
in range(2, int(n**0.5)+1)) print([Link](data))
print(is_prime) 1️⃣1️⃣ Searching & Sorting (Basic
Fibonacci series 6️⃣ List Comprehension (Companies Logic)
n=5 LOVE this) Binary search
a, b = 0, 1 lst = [1,2,3,4] lst = [1,3,5,7,9]
for _ in range(n): squares = [x**2 for x in lst if x % 2 == x=5
print(a, end=" ") 0] l, r = 0, len(lst)-1
a, b = b, a+b print(squares) while l <= r:
Factorial m = (l+r)//2
import math if lst[m] == x:
7️⃣ SQL-Style Logic in Python
print([Link](5)) print("Found")
(TRENDING)
Second highest number break
3️⃣ Python Data Structures (VERY lst = [10,20,30,40] elif lst[m] < x:
IMPORTANT) print(sorted(set(lst))[-2]) l = m+1
Word frequency count Remove duplicates else:
s = "data science data" lst = [1,2,2,3] r = m-1
words = [Link]() print(list(set(lst))) Sort dictionary by values
freq = {} d = {'a':3,'b':1,'c':2}
for w in words: print(dict(sorted([Link](),
8️⃣ Machine Learning Logic (Fresher
freq[w] = [Link](w, 0) + 1 key=lambda x: x[1])))
Level)
print(freq)
Train-test split
Find max & min without built-in 1️⃣2️⃣ Numpy (Often Asked in DS
from sklearn.model_selection import
lst = [4,2,9,1] Interviews)
train_test_split
mx = mn = lst[0] Create array & reshape
X = [1,2,3,4]
for x in lst: import numpy as np
y = [0,1,0,1]
if x > mx: mx = x a = [Link]([1,2,3,4,5,6])
X_train, X_test, y_train, y_test =
if x < mn: mn = x print([Link](2,3))
train_test_split(X, y, test_size=0.25)
print(mx, mn) Find missing values
Overfitting vs Underfitting
(conceptual + example) a = [Link]([1,2,[Link],4])
4️⃣ Pandas-Based Coding (INTERVIEW 👉 Almost always asked even if no code print([Link](a))
FAVORITE) Mean ignoring NaN
print([Link](a)) df['dept'] = le.fit_transform(df['dept']) r -= 1
Normalize data
1️⃣3️⃣ Pandas (REAL INTERVIEW from [Link] import 2️⃣3️⃣ Recursion (Basic
FAVORITES) MinMaxScaler Understanding)
Handle missing values scaler = MinMaxScaler() Factorial using recursion
[Link]([Link](), inplace=True) df[['salary']] = def fact(n):
Sort DataFrame scaler.fit_transform(df[['salary']]) if n == 1:
df.sort_values(by='salary', return 1
ascending=False) 1️⃣8️⃣ Debugging Questions return n * fact(n-1)
Find duplicate rows (COMMON!)
df[[Link]()] Find the bug print(fact(5))
Apply function for i in range(5): Reverse string using recursion
df['tax'] = df['salary'].apply(lambda x: print(i) def rev(s):
x*0.1) 👉 They’ll ask: Why does this print 0 to if len(s) == 0:
4 and not 1 to 5? return s
1️⃣4️⃣ Data Cleaning Logic (Scenario- return rev(s[1:]) + s[0]
Based) 1️⃣9️⃣ Time & Space Complexity
Remove outliers (IQR method) (DON’T IGNORE) print(rev("data"))
Q1 = df['salary'].quantile(0.25) Explain complexity
Q3 = df['salary'].quantile(0.75) for i in range(n): 2️⃣4️⃣ File Handling (SURPRISINGLY
IQR = Q3 - Q1 for j in range(n): COMMON)
df = df[(df['salary'] >= Q1 - 1.5*IQR) & print(i,j) Read file & count words
(df['salary'] <= Q3 + 1.5*IQR)] 👉 Time Complexity = O(n²) with open("[Link]") as f:
📌 Frequently asked as “How would 👉 Asked verbally 90% of the time text = [Link]()
you clean messy data?” print(len([Link]()))
2️⃣1️⃣ Sliding Window & Pattern
1️⃣5️⃣ SQL-Equivalent Questions Problems 2️⃣5️⃣ Exception Handling (REAL-
(VERY TRENDING) Maximum sum of subarray of size k WORLD CODING)
Top N values arr = [2,1,5,1,3,2] try:
lst = [10,50,30,20] k=3 x = int("abc")
print(sorted(lst, reverse=True)[:2]) window_sum = sum(arr[:k]) except ValueError:
Count per category max_sum = window_sum print("Invalid conversion")
from collections import Counter 📌 They test if you write production-
data = ['HR','IT','HR','Finance'] for i in range(k, len(arr)): safe code
print(Counter(data)) window_sum += arr[i] - arr[i-k]
max_sum = max(max_sum,
2️⃣6️⃣ Object-Oriented Programming
window_sum)
1️⃣6️⃣ Probability & Stats Coding (YES, for DS too!)
Random sampling Create simple class
print(max_sum)
import random class Employee:
📌 Asked as “optimize this logic”
print([Link](range(1,100), def __init__(self, name, salary):
5)) [Link] = name
Probability simulation 2️⃣2️⃣ Two Pointer Technique [Link] = salary
import random Pair with target sum
heads = 0 arr = [1,2,3,4,5] def bonus(self):
for _ in range(1000): target = 6 return [Link] * 0.1
if [Link](['H','T']) == 'H': l, r = 0, len(arr)-1
heads += 1 e = Employee("A", 50000)
print(heads/1000) while l < r: print([Link]())
s = arr[l] + arr[r]
if s == target:
1️⃣7️⃣ ML-Related Coding (ENTRY 2️⃣7️⃣ Lambda, Map, Filter
print(arr[l], arr[r])
LEVEL) (INTERVIEW FAV)
break
Encode categorical data lst = [1,2,3,4,5]
elif s < target:
from [Link] import
l += 1
LabelEncoder print(list(map(lambda x: x*x, lst)))
else:
le = LabelEncoder()
print(list(filter(lambda x: x % 2 == 0,
lst)))

2️⃣8️⃣ Regular Expressions (Basic)


Extract numbers from string
import re
s = "Order123 amount450"
print([Link](r'\d+', s))

2️⃣9️⃣ Date & Time Handling


from datetime import datetime
date = "2024-12-01"
dt = [Link](date, "%Y-%m-
%d")
print([Link])

3️⃣0️⃣ Feature Engineering Logic


(VERY IMPORTANT)
Create new feature
df['salary_per_year'] =
df['monthly_salary'] * 12
Binning
df['age_group'] = [Link](df['age'],
bins=[0,18,35,60])
3️⃣1️⃣ EDA QUICK COMMANDS
(MEMORIZE!)
[Link]
[Link]()
[Link]()
[Link]()
df.value_counts()

3️⃣2️⃣ Visualization Coding (BASIC)


import [Link] as plt

[Link](df['salary'])
[Link]()
📌 Often asked conceptually if not
hands-on

3️⃣3️⃣ Model Evaluation (ENTRY


LEVEL)
from [Link] import
accuracy_score
accuracy_score(y_test, y_pred)

3️⃣4️⃣ Overfitting Check (LOGIC)


print([Link](X_train, y_train))
print([Link](X_test, y_test))
🔹 PYTHON BASICS (1–15) 🔹 SEARCHING & SORTING (41–45) 75. Overfitting check (train vs
1. Reverse a string 41. Linear search test score)
2. Check palindrome 42. Binary search
(string/number) 43. Bubble sort # 1. Reverse a string
3. Count vowels in a string 44. Selection sort s = "hello"
4. Count words in a sentence 45. Sort dictionary by values print(s[::-1])
5. Find length of string without
len() 🔹 NUMPY (46–50) # 2. Check palindrome
6. Swap two numbers without 46. Create NumPy array & s = "madam"
temp reshape print(s == s[::-1])
7. Check even or odd 47. Mean, median, std using
8. Find factorial (loop) NumPy # 3. Count vowels
9. Find factorial (recursion) 48. Handle NaN values s = "datascience"
10. Generate Fibonacci series 49. Array operations (add, vowels = "aeiou"
11. Check prime number multiply) print(sum(1 for c in s if c in vowels))
12. Print primes in a range 50. Find unique elements
13. Sum of digits of a number # 4. Count words
14. Reverse a number s = "data science interview"
🔹 PANDAS (VERY IMPORTANT) (51–
15. Armstrong number check print(len([Link]()))
60)
51. Create DataFrame
🔹 LIST & ARRAY LOGIC (16–30) # 5. Length without len()
52. Read CSV file
16. Find maximum element in s = "hello"
53. Find null values
list count = 0
54. Fill missing values
17. Find minimum element in list for _ in s:
55. Drop missing values
18. Find second largest number count += 1
56. Filter rows using condition
19. Remove duplicates from list print(count)
57. Sort DataFrame by column
20. Count frequency of elements 58. GroupBy & aggregate
in list # 6. Swap without temp
59. Find duplicate rows
21. Find duplicate elements a, b = 5, 10
60. Create new column (feature
22. Rotate list by k positions a, b = b, a
engineering)
23. Merge two lists print(a, b)
24. Sort list without using sort()
🔹 STATISTICS & PROBABILITY (61–65)
25. Find missing number in list # 7. Even or odd
61. Mean, median, mode
26. Sum of list elements n=7
62. Standard deviation
27. Flatten nested list print(n % 2 == 0)
63. Variance
28. Find common elements
64. Random sampling
between two lists # 8. Factorial (loop)
65. Probability simulation (coin
29. Check if list is sorted n=5
toss)
30. Split list into chunks fact = 1
for i in range(1, n+1):
🔹 MACHINE LEARNING – ENTRY fact *= i
🔹 STRING + DICTIONARY (31–40)
LEVEL (66–70) print(fact)
31. Character frequency in string
66. Train-test split
32. Word frequency in string
67. Label encoding # 9. Factorial (recursion)
33. First non-repeating character
68. One-hot encoding def fact(n):
34. Check anagram
69. Data normalization / scaling return 1 if n == 1 else n * fact(n-1)
35. Remove special characters
70. Accuracy score calculation print(fact(5))
from string
36. Count uppercase &
🔹 REAL INTERVIEW CODING TASKS # 10. Fibonacci
lowercase letters
(71–75) n=5
37. Reverse words in sentence
71. Second highest salary (logic / a, b = 0, 1
38. Replace characters in string
SQL-style) for _ in range(n):
39. Sort string alphabetically
72. Remove outliers using IQR print(a, end=" ")
40. Find longest word in
73. Handle categorical + numeric a, b = b, a+b
sentence
data print()
74. Simple EDA (info, describe)
# 11. Prime check lst = [3,1,2] # 36. Upper & lower count
n=7 for i in range(len(lst)): s = "DaTa"
print(n > 1 and all(n % i != 0 for i in for j in range(i+1, len(lst)): upper = sum(1 for c in s if [Link]())
range(2, int(n**0.5)+1))) if lst[i] > lst[j]: lower = sum(1 for c in s if [Link]())
lst[i], lst[j] = lst[j], lst[i] print(upper, lower)
# 12. Primes in range print(lst)
for n in range(2, 20): # 37. Reverse words
if all(n % i != 0 for i in range(2, # 25. Missing number s = "data science"
int(n**0.5)+1)): lst = [1,2,4,5] print(" ".join([Link]()[::-1]))
print(n, end=" ") n=5
print() print(n*(n+1)//2 - sum(lst)) # 38. Replace characters
print("hello".replace('l','x'))
# 13. Sum of digits # 26. Sum of list
n = 123 print(sum(lst)) # 39. Sort string
print(sum(map(int, str(n)))) print("python".join(sorted("python")))
# 27. Flatten list
# 14. Reverse number lst = [[1,2],[3,4]] # 40. Longest word
n = 123 print([i for sub in lst for i in sub]) s = "data science interview"
print(int(str(n)[::-1])) print(max([Link](), key=len))
# 28. Common elements
# 15. Armstrong number print(set([1,2,3]) & set([2,3,4])) # 41. Linear search
n = 153 lst = [1,2,3]
print(n == sum(int(d)**len(str(n)) for # 29. Check sorted x=2
d in str(n))) lst = [1,2,3] print(x in lst)
print(lst == sorted(lst))
# 16. Max in list # 42. Binary search
lst = [1, 5, 3] # 30. Split into chunks lst = [1,2,3,4]
print(max(lst)) lst = [1,2,3,4,5] x=3
size = 2 l, r = 0, len(lst)-1
# 17. Min in list print([lst[i:i+size] for i in range(0, found = False
print(min(lst)) len(lst), size)]) while l <= r:
m = (l+r)//2
# 18. Second largest # 31. Character frequency if lst[m] == x:
lst = [1, 5, 3, 5] s = "hello" found = True
print(sorted(set(lst))[-2]) print(Counter(s)) break
elif lst[m] < x:
# 19. Remove duplicates # 32. Word frequency l = m+1
lst = [1,2,2,3] s = "data science data" else:
print(list(set(lst))) print(Counter([Link]())) r = m-1
print(found)
# 20. Frequency of elements # 33. First non-repeating
from collections import Counter s = "swiss" # 43. Bubble sort
print(Counter(lst)) for c in s: lst = [3,2,1]
if [Link](c) == 1: for i in range(len(lst)):
# 21. Duplicate elements print(c) for j in range(len(lst)-i-1):
print([x for x in lst if [Link](x) > 1]) break if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
# 22. Rotate list # 34. Anagram print(lst)
lst = [1,2,3,4] print(sorted("listen") ==
k=2 sorted("silent")) # 44. Selection sort
print(lst[k:] + lst[:k]) lst = [3,1,2]
# 35. Remove special chars for i in range(len(lst)):
# 23. Merge lists import re min_i = i
print([1,2] + [3,4]) s = "hi@123" for j in range(i+1, len(lst)):
print([Link](r'[^a-zA-Z0-9]', '', s)) if lst[j] < lst[min_i]:
# 24. Sort without sort min_i = j
lst[i], lst[min_i] = lst[min_i], lst[i] # 60. New column print(sorted(set(salaries))[-2])
print(lst) df['C'] = df['A'] + df['B']
# 72. Remove outliers (IQR)
# 45. Sort dict by value # 61. Mean median mode df = [Link]({'x':[1,2,3,100]})
d = {'a':3,'b':1} import statistics Q1 = df['x'].quantile(0.25)
print(dict(sorted([Link](), data = [1,2,2,3] Q3 = df['x'].quantile(0.75)
key=lambda x: x[1]))) print([Link](data), IQR = Q3 - Q1
[Link](data), print(df[(df['x'] >= Q1 - 1.5*IQR) &
# 46. NumPy reshape [Link](data)) (df['x'] <= Q3 + 1.5*IQR)])
import numpy as np
a = [Link]([1,2,3,4]) # 62. Standard deviation # 73. Handle categorical + numeric
print([Link](2,2)) print([Link](data)) df = [Link]({'dept':['HR','IT'],
'salary':[30,40]})
# 47. Mean median std # 63. Variance df['dept'] = le.fit_transform(df['dept'])
print([Link](a), [Link](a), print([Link](data))
[Link](a)) # 74. Simple EDA
# 64. Random sampling print([Link]())
# 48. Handle NaN import random print([Link]())
b = [Link]([1, [Link], 3]) print([Link](range(10), 3))
print([Link](b)) # 75. Overfitting check
# 65. Coin toss simulation # Compare train vs test score
# 49. Array operations heads = sum(1 for _ in range(1000) if
print(a + 2) [Link](['H','T']) == 'H')
print(heads/1000)
# 50. Unique elements
print([Link]([1,2,2,3])) # 66. Train-test split
from sklearn.model_selection import
# 51. Create DataFrame train_test_split
import pandas as pd X = [1,2,3,4]
df = [Link]({'A':[1,2],'B':[3,4]}) y = [0,1,0,1]
print(df) Xtr, Xte, ytr, yte = train_test_split(X, y,
test_size=0.25)
# 52. Read CSV
# df = pd.read_csv('[Link]') # 67. Label encoding
from [Link] import
# 53. Find nulls LabelEncoder
print([Link]().sum()) le = LabelEncoder()
print(le.fit_transform(['HR','IT','HR']))
# 54. Fill nulls
[Link](0, inplace=True) # 68. One-hot encoding
print(pd.get_dummies(['HR','IT','HR']))
# 55. Drop nulls
[Link](inplace=True) # 69. Normalization
from [Link] import
# 56. Filter rows MinMaxScaler
print(df[df['A'] > 1]) scaler = MinMaxScaler()
print(scaler.fit_transform([[10],[20],
# 57. Sort DataFrame [30]]))
print(df.sort_values(by='A'))
# 70. Accuracy score
# 58. GroupBy from [Link] import
print([Link]('A').sum()) accuracy_score
print(accuracy_score([1,0,1],[1,0,0]))
# 59. Duplicate rows
print(df[[Link]()]) # 71. Second highest salary
salaries = [30000,50000,40000]
🧠 THE 10 CORE PATTERNS BEHIND ALL 75  Filter DataFrame rows 📌 Asked verbally in almost every DS
PROGRAMS  Remove outliers interview
 Even/odd
🔑 PATTERN 1: STRING REVERSAL /  Prime numbers 🔑 PATTERN 10: SIMULATION /
PALINDROME RANDOMNESS
👉 “Go from back to front” 🔑 PATTERN 5: TWO POINTER / WINDOW 👉 “Repeat experiment many times”
Mental trigger: 👉 “Compare from both ends or sliding for _ in range(1000):
“I need to compare or reverse characters” window” [Link](...)
Core ideas: Mental trigger: 💡 Covers:
 Slicing “Pair, subarray, optimized”  Probability
 Two-pointer l, r = 0, len(arr)-1  Sampling
 Loop backward while l < r:  Monte Carlo style questions
s = "madam" ...
print(s == s[::-1]) 💡 Covers: 🧠 INTERVIEW ANTI-PANIC FRAMEWORK
💡 Covers:  Pair sum (VERY IMPORTANT)
 Reverse string  Binary search When you hear a question:
 Palindrome  Reverse logic 1️⃣ Identify the pattern (NOT the code)
 Reverse words  Sliding window problems “Ah, this is a counting problem”
 Reverse number 2️⃣ Say your approach aloud
🔑 PATTERN 6: SORT → PICK “I’ll use a dictionary to track frequency”
🔑 PATTERN 2: COUNTING (MOST 👉 “Sort once, then answer easily” 3️⃣ Write minimal code
COMMON) sorted(set(lst))[-2] Interviewers prefer clear logic over fancy
👉 “Count something” 💡 Covers: code
Mental trigger:  Second largest
“How many times does X appear?”  Second highest salary 🧪 QUICK PRACTICE (TRY MENTALLY)
Core ideas:  Median ❓ Find first non-repeating character
 Dictionary  Anagram → Pattern? COUNTING
 Counter  Sorted string ❓ Second highest salary
 Loop + increment 📌 Interviewers LOVE this pattern → Pattern? SORT → PICK
freq = {} ❓ Remove outliers
for c in "data": 🔑 PATTERN 7: RECURSION (BREAK INTO → Pattern? FILTERING
freq[c] = [Link](c, 0) + 1 SMALLER) ❓ Palindrome check
💡 Covers: 👉 “Solve smaller version of same problem” → Pattern? STRING REVERSAL
 Character frequency def fact(n): If you can do this mapping, you’re safe.
 Word frequency return 1 if n == 1 else n * fact(n-1)
 Duplicate elements 💡 Covers:
 Upper/lower count  Factorial
 First non-repeating character  Reverse string
 Fibonacci
🔑 PATTERN 3: ACCUMULATOR (SUM / 📌 Even if not required, it shows clarity
PRODUCT)
👉 “Keep adding or multiplying” 🔑 PATTERN 8: DATA TRANSFORMATION
Mental trigger: (DS GOLD)
“Total / sum / factorial” 👉 “Raw → Clean → Useful”
total = 0 [Link]([Link](), inplace=True)
for x in lst: df['new'] = df['a'] * 12
total += x 💡 Covers:
💡 Covers:  Feature engineering
 Sum of digits  Scaling
 Sum of list  Encoding
 Factorial  GroupBy
 Fibonacci  EDA
 Mean calculation

🔑 PATTERN 9: COMPARE TRAIN vs TEST


🔑 PATTERN 4: FILTERING (KEEP OR 👉 “Check generalization”
REMOVE) train_score > test_score
👉 “Select only what matches condition” 💡 Covers:
[x for x in lst if x > 10]  Overfitting
💡 Covers:  Model evaluation
 Remove duplicates  Accuracy logic

You might also like