0% found this document useful (0 votes)
10 views9 pages

? Python Data Structures How To Use

Uploaded by

Temo
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)
10 views9 pages

? Python Data Structures How To Use

Uploaded by

Temo
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
You are on page 1/ 9

🐍 Python Data Structures & Algorithms (DSA) — Simple Guide

Python Data Structures and Algorithms are the building blocks for solving coding challenges.
Mastering them helps you solve problems efficiently and correctly.
🔹 PART 1: Common Python Data Structures
1. List ([])

Ordered, mutable, allows duplicates

Think of it like a row of items (e.g., [1, 2, 3])

✅ Use for:

Storing a sequence

Accessing by index

Modifying elements

numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]

2. Tuple (())

Ordered, immutable, allows duplicates

✅ Use for:

Fixed data (e.g., coordinates)

point = (3, 4)

3. Set (set())

Unordered, unique values, no duplicates

✅ Use for:

Removing duplicates

Set operations (union, intersection)

s = set([1, 2, 2, 3]) # {1, 2, 3}

4. Dictionary ({key: value})

Key-value pairs, fast lookup

✅ Use for:

Mapping data (like a phone book)

phone = {'John': '123', 'Jane': '456'}


print(phone['Jane']) # '456'

5. String ("")
Like a list of characters (immutable)

✅ Use for:

Text manipulation

s = "hello"
print(s[::-1]) # 'olleh'

🔹 PART 2: Common Algorithms


1. Sorting

Organizing data

nums = [5, 2, 9]
nums.sort() # [2, 5, 9]

2. Searching

Finding elements

if 3 in nums:
print("Found!")

3. Two Pointers

Use two indices to solve array problems

def has_pair_with_sum(arr, target):


left, right = 0, len(arr)-1
arr.sort()
while left < right:
s = arr[left] + arr[right]
if s == target:
return True
elif s < target:
left += 1
else:
right -= 1
return False

4. Sliding Window

Efficient for subarray problems

def max_sum(arr, k):


window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i-k]
max_sum = max(max_sum, window_sum)
return max_sum

5. Hashing

Use dictionaries or sets to solve problems faster


def has_duplicate(nums):
seen = set()
for n in nums:
if n in seen:
return True
seen.add(n)
return False

6. Recursion

Function that calls itself

def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)

7. Dynamic Programming

Break problems into sub-problems and cache results

def fib(n, memo={}):


if n in memo: return memo[n]
if n <= 2: return 1
memo[n] = fib(n-1, memo) + fib(n-2, memo)
return memo[n]

🔹 PART 3: Python Challenge Types and Strategies


Challenge Type Common Structures/Algorithms Strategy
✅ Arrays/Lists List, Set, Two Pointers, Sliding Window Looping, sorting, hashsets
✅ Strings String, Dict, Two Pointers Reverse, compare, count
✅ Hashing Dict, Set Store and lookup values
✅ Math/Number Loop, Conditions Modulo, division, primes
✅ Recursion/DP Recursion, Memoization Break into smaller problems
✅ Sorting/Searching List, Sort, Binary Search Efficient lookups
✅ Graphs/Trees Dict, Set, Recursion DFS, BFS
✅ Linked Lists Pointers, Classes Traverse and modify
✅ Stacks/Queues List, Deque LIFO / FIFO problems
✅ Example Problem + Solution Strategy

Problem: Return True if a list contains duplicates.

🔧 Use: Set + Loop

def contains_duplicate(nums):
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False

🔚 Final Tips for Solving Python Challenges

Understand the Problem — Write in your own words

Choose the Right Structure — Based on data and actions


Think of Edge Cases — Empty input, large size, etc.

Write & Test Code — Small examples

Optimize — Use time/space complexity knowledge

Would you like a printable cheat sheet or want to practice with Python challenge examples by type?
You said:
yes
ChatGPT said:

Great! Here's what I’ll give you in this response:

✅ A Printable Cheat Sheet (DSA summary)

✅ A list of Python Practice Challenges by type with examples and brief hints

✅ Option to generate PDF or Markdown version if you want it for offline use

🧠 1. PYTHON DSA CHEAT SHEET (Simple & Printable)

================= PYTHON DSA CHEAT SHEET =================

DATA STRUCTURES:
----------------
1. List [] - Ordered, Mutable, Duplicates allowed
2. Tuple () - Ordered, Immutable, Duplicates allowed
3. Set set() - Unordered, Unique, No duplicates
4. Dict {} - Key-value pairs, Fast lookup
5. String "" - Sequence of characters (immutable)

ALGORITHMS:
-----------
1. Sorting - list.sort(), sorted()
2. Searching - Linear, Binary Search
3. Two Pointers - Use two indices for efficient traversal
4. Sliding Window - Efficient fixed-size subarray logic
5. Hashing - Use dict/set to store seen values
6. Recursion - Function calls itself
7. Dynamic Programming - Store previous results to optimize

TIME COMPLEXITY HINTS:


-----------------------
- Loop: O(n)
- Nested loop: O(n^2)
- Sort: O(n log n)
- Dict/Set lookup: O(1)
- Recursion (no memo): exponential

🧩 2. PYTHON CHALLENGES BY TYPE (With Hints)


Challenge Type Example ProblemHint / Structure
✅ List/Array "Find max in list" Use max(), loop, or sort
✅ String "Is string a palindrome?" Use slicing: s == s[::-1]
✅ Hashing "Detect duplicate in list" Use set() or dict()
✅ Two Pointers "Two sum in sorted list" One pointer from start, one from end
✅ Sliding Window "Max sum of k-length subarray" Keep window sum, slide it
✅ Sorting "Sort list of tuples by 2nd item" Use sorted(data, key=lambda x: x[1])
✅ Recursion "Factorial or Fibonacci" Base case + function calling itself
✅ Dynamic Programming "Climbing stairs with 1 or 2 steps" DP with memo or bottom-up list
✅ Graph/BFS/DFS "Find connected components" Use dict for graph + visited set
✅ Linked List "Reverse a linked list" Track prev/current/next node
✅ Stack "Valid parentheses" Use list as a stack: .append()/.pop()
✅ Queue "First unique character" Use collections.deque()
✅ Binary Search "Find element in sorted array" Use while low <= high: logic
✅ Math "Is number a power of 2?" Check using bit manipulation
🎯 3. SAMPLE PRACTICE QUESTIONS (With Answers on Request)

Here are 5 beginner-friendly ones to start with:


1. Reverse a string

# Input: "hello"
# Output: "olleh"

2. Find the maximum number in a list

# Input: [1, 7, 3, 9, 2]
# Output: 9

3. Check if two strings are anagrams

# Input: "listen", "silent"


# Output: True
# Hint: Use `sorted()`

4. Find duplicates in a list

# Input: [1, 2, 3, 2, 4]
# Output: True

5. Return the first non-repeating character

# Input: "swiss"
# Output: "w"
# Hint: Use dict to count, then loop through string

📦 Want This as a PDF or Markdown?

Would you like:

📝 PDF version (Printable)

📄 Markdown version (For GitHub or Notebooks)

💻 Notebook version (With code cells to practice)

Let me know your preferred format and I’ll generate it!


You said:
example code for
2. PYTHON CHALLENGES BY TYPE (With Hints)
ChatGPT said:

Perfect! Here's example code for each item listed in “2. Python Challenges by Type (With Hints)” —
organized and explained clearly.
✅ 1. List/Array – Find Max in List

def find_max(nums):
max_val = nums[0]
for num in nums:
if num > max_val:
max_val = num
return max_val

print(find_max([1, 7, 3, 9, 2])) # Output: 9

✅ 2. String – Is String a Palindrome?

def is_palindrome(s):
return s == s[::-1]

print(is_palindrome("racecar")) # Output: True

✅ 3. Hashing – Detect Duplicates in List

def has_duplicate(nums):
seen = set()
for n in nums:
if n in seen:
return True
seen.add(n)
return False

print(has_duplicate([1, 2, 3, 4, 2])) # Output: True

✅ 4. Two Pointers – Two Sum in Sorted List

def two_sum_sorted(nums, target):


left, right = 0, len(nums) - 1
while left < right:
s = nums[left] + nums[right]
if s == target:
return [left, right]
elif s < target:
left += 1
else:
right -= 1
return []

print(two_sum_sorted([1, 2, 4, 6, 10], 8)) # Output: [1, 3]

✅ 5. Sliding Window – Max Sum of k-Length Subarray

def max_subarray_sum(nums, k):


window_sum = sum(nums[:k])
max_sum = window_sum
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k]
max_sum = max(max_sum, window_sum)
return max_sum

print(max_subarray_sum([1, 2, 3, 4, 5, 6], 3)) # Output: 15


✅ 6. Sorting – Sort Tuples by Second Item

data = [(1, 'b'), (3, 'a'), (2, 'c')]


sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data) # Output: [(3, 'a'), (1, 'b'), (2, 'c')]

✅ 7. Recursion – Factorial

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

✅ 8. Dynamic Programming – Climbing Stairs

def climb_stairs(n):
if n <= 2:
return n
dp = [0] * (n + 1)
dp[1], dp[2] = 1, 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]

print(climb_stairs(5)) # Output: 8

✅ 9. Graph/BFS – Number of Connected Components

from collections import defaultdict, deque

def count_components(n, edges):


graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)

visited = set()

def bfs(node):
queue = deque([node])
while queue:
curr = queue.popleft()
for neighbor in graph[curr]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)

count = 0
for i in range(n):
if i not in visited:
visited.add(i)
bfs(i)
count += 1
return count
print(count_components(5, [[0,1],[1,2],[3,4]])) # Output: 2

✅ 10. Linked List – Reverse a Linked List

class Node:
def __init__(self, val):
self.val = val
self.next = None

def reverse_list(head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev

✅ 11. Stack – Valid Parentheses

def is_valid(s):
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in mapping:
top = stack.pop() if stack else '#'
if mapping[char] != top:
return False
else:
stack.append(char)
return not stack

print(is_valid("({[]})")) # Output: True

✅ 12. Queue – First Unique Character

from collections import Counter

def first_unique(s):
count = Counter(s)
for ch in s:
if count[ch] == 1:
return ch
return None

print(first_unique("swiss")) # Output: "w"

✅ 13. Binary Search – Search in Sorted Array

def binary_search(nums, target):


left, right = 0, len(nums)-1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

print(binary_search([1, 3, 5, 7, 9], 7)) # Output: 3

✅ 14. Math – Is Power of 2

def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0

print(is_power_of_two(8)) # Output: True

You might also like