Practical Technical Cheat Sheet for Python, Linux, SQL and Software Testing
Python Programming Examples
Sorting
Selection Sort
def selection_sort(input_list):
for idx in range(len(input_list)):
min_pos = idx
for sub_idx in range(idx + 1, len(input_list)):
if input_list[sub_idx] < input_list[min_pos]:
min_pos = sub_idx
input_list[idx], input_list[min_pos] = input_list[min_pos], input_list[idx]
return input_list
sample_list = [3, 2, 5, 1]
print(selection_sort(sample_list))
Built-in Sorted Function
sample_list = [3, 2, 5, 1]
print(sorted(sample_list, reverse=True))
Find Min/Max Values
sample_list = [3, 2, 5, 1, 5]
# Built-in method
print(max(sample_list))
print(min(sample_list))
# Custom implementation
def find_max(input_list):
current_max = input_list[0]
for num in input_list:
if num > current_max:
current_max = num
return current_max
print(find_max(sample_list))
List Deduplication
original_list = [3, 2, 3, 5, 1, 5, 5]
# Using set
unique_list = list(set(original_list))
print(unique_list)
# Custom implementation preserving order
unique_ordered = []
for item in original_list:
if item not in unique_ordered:
unique_ordered.append(item)
print(unique_ordered)
Count Element Occurrences
original_list = [3, 2, 3, 5, 1, 5, 5]
# Using dictionary
count_dict = {}
for item in original_list:
count_dict[item] = original_list.count(item)
print(count_dict)
# Alternative using collections.Counter
from collections import Counter
print(Counter(original_list))
Reverse a Sequence
test_str = "tom"
# Slicing method
reversed_str = test_str[::-1]
print(reversed_str)
# Using pop()
def reverse_with_pop(input_str):
char_list = list(input_str)
reversed_result = ""
while char_list:
reversed_result += char_list.pop()
return reversed_result
print(reverse_with_pop(test_str))
# Index-based reversal
def reverse_by_index(input_str):
char_list = list(input_str)
reversed_result = ""
length = len(char_list)
for idx in range(length):
reversed_result += char_list[length - 1 - idx]
return reversed_result
print(reverse_by_index(test_str))
Recursive File Traversal
import os
def list_all_files(base_path):
for entry in os.listdir(base_path):
full_path = os.path.join(base_path, entry)
if os.path.isdir(full_path):
list_all_files(full_path)
else:
print(full_path)
target_dir = r"D:\test_cases"
list_all_files(target_dir)
Parameterized Decorator
def decorator_factory(option):
def outer_wrapper(func):
def inner_wrapper(*args, **kwargs):
if option == 1:
print("Applying decoration 1...")
elif option == 2:
print("Applying decoration 2...")
func(*args, **kwargs)
return inner_wrapper
return outer_wrapper
@decorator_factory(2)
def sample_function():
print("Operation completed successfully...")
sample_function()
Sort a Dictionary
sample_dict = {"1": "tom", "3": "Lily", "2": "Jim"}
# Sort by key using sorted()
sorted_items = sorted(sample_dict.items(), key=lambda x: x[0])
print(sorted_items)
# Alternative manual sorting
sorted_keys = sorted(sample_dict.keys())
sorted_values = [sample_dict[key] for key in sorted_keys]
sorted_dict = {k: v for k, v in zip(sorted_keys, sorted_values)}
print(sorted_dict)
Longest Common Prefix
def longest_common_prefix(str_list):
if not str_list:
return ""
min_length = min(len(s) for s in str_list)
common_prefix = ""
for idx in range(min_length):
current_char = str_list[0][idx]
for s in str_list:
if s[idx] != current_char:
return common_prefix
common_prefix += current_char
return common_prefix
test_list = ["flight", "floor", "floy", "flower"]
print(longest_common_prefix(test_list))
Recursive Sum Calculation
def recursive_sum(n):
if n <= 1:
return 1
return n + recursive_sum(n - 1)
print(recursive_sum(100))
Build Nested Menu Tree
menu_data = [
{'id': 1, 'name': 'Main Menu', 'status': 1, 'parent_id': 0},
{'id': 2, 'name': 'Submenu 1', 'status': 1, 'parent_id': 1},
{'id': 3, 'name': 'Submenu 1.1', 'status': 1, 'parent_id': 2},
# Add additional menu items as needed
]
def build_nested_menu(menu_items, parent_id=0):
nested_menu = []
for item in menu_items:
if item['parent_id'] == parent_id:
child_nodes = build_nested_menu(menu_items, item['id'])
nested_menu.append({
"name": item['name'],
"children": child_nodes
})
return nested_menu
print(build_nested_menu(menu_data))
Find Consecutive Number Sequences
def find_consecutive_groups(num_list):
if not num_list:
return []
consecutive_groups = []
current_group = [num_list[0]]
for num in num_list[1:]:
if num == current_group[-1] + 1:
current_group.append(num)
else:
if len(current_group) == 1:
consecutive_groups.append(current_group[0])
else:
consecutive_groups.append([current_group[0], current_group[-1]])
current_group = [num]
# Add final group
if len(current_group) == 1:
consecutive_groups.append(current_group[0])
else:
consecutive_groups.append([current_group[0], current_group[-1]])
return consecutive_groups
test_list = [1,2,3,5,6,8]
print(find_consecutive_groups(test_list))
LRU Cache Implementation
from collections import OrderedDict
class LRUCache:
def __init__(self, max_size):
self.max_size = max_size
self.cache = OrderedDict()
def put(self, key, value):
if key in self.cache:
self.cache.pop(key)
if len(self.cache) >= self.max_size:
self.cache.popitem(last=False)
self.cache[key] = value
def get(self, key):
if key not in self.cache:
return None
# Move key to end to mark as recently used
val = self.cache.pop(key)
self.cache[key] = val
return val
# Test usage
cache = LRUCache(3)
cache.put("1", "1")
cache.put("2", "2")
cache.put("1", "3")
print(cache.cache)
cache.get("1")
print(cache.cache)
Fibonacci for Frog Jump Problem
def frog_jump_recursive(n):
"""Calculate ways for frog to jump up n stairs, can jump 1 or 2 steps"""
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
else:
return frog_jump_recursive(n-1) + frog_jump_recursive(n-2)
print(frog_jump_recursive(4))
Additional Utility Functions
# 99 Multiplication Table
def print_multiplication_table():
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}*{i}={j*i}\t", end="")
print()
# Prime Number Check
import math
def is_prime(num):
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for divisor in range(3, int(math.sqrt(num)) +1, 2):
if num % divisor == 0:
return False
return True
# Palindrome Check
def is_palindrome(input_str):
reversed_str = input_str[::-1]
return input_str == reversed_str
Linux Administration Commands
Network and Process Monitoring
- List all TCP/UDP connections:
lsof -i - Check process using port 80:
lsof -i:80 - Find port for a specific process:
lsof -i -P | grep influxd - Kill process by port 80:
lsof -i:80 | awk '{print $2}' | xargs killorlsof -ti:8000 | xargs kill - Kill all Python processes:
ps aux | grep python | awk '{print $2}' | xargs kill
Log File Operations
- View lines 100-200:
head -n 200 filename | tail -n 100 - View lines 5-6:
head -n 6 filename | tail -n 1 - Search logs for keyword in last 100 lines:
tail -n 100 filename | grep "keyword"
Disk and Directory Managemant
- Check top 3 largest top-level directories (including hidden files):
du -h -d 1 | sort -hr | head -n 3 - Check top 3 largest top-level directories (excluding hidden files):
du -sh * | sort -hr | head -n 3 - List disk partition usage:
df -h
Compression and Extraction
- Extract tar file:
tar -xvf archive.tar - Create tar archive:
tar -cvf archive.tar target_file/
Grep Usage
- Search file with line numbers:
grep -n "keyword" filename - Recursively search directory:
grep -r "keyword" target_dir/ - Case-insensitive search:
grep -i "keyword" filename - Inverse search (exclude matches):
grep -v "keyword" filename
System Monitoring
- View overall system load:
woruptime(shows 1/5/15 minute CPU load averages) - Dynamic system resource monitor:
top - Memory usage summary:
free -h, or refresh every 5 seconds with units in GB:free -g -t -s 5 - Detailed disk I/O stats:
iostat, or extended stats:iostat -dx - Virtual memory and system stats:
vmstat
SQL Basics
Differences Between DELETE, TRUNCATE, DROP
DELETE: Removes table rows, supports transaction rolllbackTRUNCATE: Removes all table rows, no rollback support, faster than DELETEDROP: Deletes entire table structure, no rollback support
MySQL Query Order
Writing order: SELECT → FROM → JOIN → ON → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
Execution order: FROM → ON → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT
Grouping and Sorting Example
Group student data by gender, sort by age descending:
SELECT name, sex, age FROM student_users GROUP BY sex, age, name ORDER BY sex, age DESC;
Common Index Types
- Primary Key Index: Auto-created for primary key columns, supports auto-increment
- Unique Index: Prevents duplicate values, allows single NULL value
- Regular Index: Basic index for faster querying
- Composite Index: Uses left-most prefix matching for multi-column queries
- Full-Text Index: For efficient text search, not compatible with LIKE '%keyword%'
- Spatial Index: For geographic location data
Software Testing
Test Design Techniques
Equivalence partitioning, boundary value analysis, decision table testing
General Test Case Checklist
- Functional testing and state transitions
- UI/UX testing
- Performance testing (sharding, database scaling)
- Usability testing
- Compatibility testing
- Weak network testing
- Interruption testing
- Installation/uninstallation and version testing
API Testing Strategy
Cover these categories:
- Functional: Validate input/output data types, required/optional fields, file size/type limits, pagination, sorting, input validation, output correctness
- Performance: Response time, concurrent request handling
- Security: XSS/JS injection protection, sensitive data encryption, authentication/authorization
- Exception Handling: Network interruptions, database failures, idempotency
- Compatibility: New and legacy data compatibility
- End-to-end: Single interface and chained interface flows
Coupon System Test Cases
Functional
- Full discount, percentage discount
- Prevent negative/zero discount after calculation
- Validate state before/after coupon use
- Handle decimal precision
- Expired coupon validation
- Multi-coupon stacking rules
- Coupon application order rules
Performance/Exception: Weak network, idempotency checks
Input Field Testing
Functional
- Dropdown loading default data sorted by time descending
- Search historical data
- Exact and fuzzy (prefix/middle/suffix) search
- Character limit validation
- Pagination and sorting for search results
- Invalid input handling (special characters, empty searches)
Performance: Response time validation
Security: XSS protection, authentication checks
Compatibility: Browser and screen resolution compatibility
Exception: Network interruptions, database failures, authentication errors
Performance Metrics and Testing
Key Performance Indicators
- Throughput: Number of requests processed per unit time (network performance metric)
- TPS: Transactions per second (server performance metric)
- CPU Utilization: Target <80% for stable operation
- Response Time: Time taken to complete a request
Server Performance Monitoring Focus Areas
- CPU Usage: Use
topfor real-time monitoring - Memory Usage: Use
free -h -tto check physicla and swap memory - CPU Load: Use
w/uptimeto check 1/5/15 minute average loads - Disk Space: Use
df -hto check partition usage - Disk I/O: Monitor read/write rates, I/O operations, queue length, wait time, utilization
Miscellaneous Technical Notes
CI/CD Workflow
- Common stack: GitLab + TeamCity
- CI Steps: Static code analysis, security vulnerability scanning
- CD Steps: Test environment validation, canary release, full production rollout
Charles Proxy Usage
- Breakpoints: Modify request/response data
- Throttling: Simulate weak network conditions
- Map Remote: Redirect requests to alternate endpoints
unittest vs pytest
- Both are Python testing frameworks for API testing
unittestis built into Python standard librarypytestis third-party, with simpler syntax, rich plugin ecosystem, and detailed test reports
Selenium Automation Workflow
- Test script acts as client
- Browser driver acts as server
- Client sends HTTP requests to browser driver
- Browser driver executes native browser APIs
- Browser returns operation results to driver
- Driver sends final results back to test script