Learn Python Coding
38.7K subscribers
1.06K photos
37 videos
24 files
855 links
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
In Python, the collections module offers specialized container datatypes that solve real-world coding challenges with elegance and efficiency. These tools are interview favorites for optimizing time complexity and writing clean, professional code! 💡
import collections  

# defaultdict - Eliminate key errors with auto-initialization
from collections import defaultdict
gradebook = defaultdict(int)
gradebook['Alice'] += 95
print(gradebook['Alice']) # Output: 95
print(gradebook['Bob']) # Output: 0

# defaultdict for grouping operations
anagrams = defaultdict(list)
words = ["eat", "tea", "tan"]
for w in words:
key = ''.join(sorted(w))
anagrams[key].append(w)
print(anagrams['aet']) # Output: ['eat', 'tea']

# Counter - Frequency analysis in one line
from collections import Counter
text = "abracadabra"
freq = Counter(text)
print(freq['a']) # Output: 5
print(freq.most_common(2)) # Output: [('a', 5), ('b', 2)]

# Counter arithmetic for problem-solving
inventory = Counter(apples=10, oranges=5)
sales = Counter(apples=3, oranges=2)
print(inventory - sales) # Output: Counter({'apples': 7, 'oranges': 3})

# namedtuple - Self-documenting data structures
from collections import namedtuple
Employee = namedtuple('Employee', 'name role salary')
dev = Employee('Alex', 'Developer', 95000)
print(dev.role) # Output: Developer
print(dev[2]) # Output: 95000

# deque - Optimal for BFS and sliding windows
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.popleft()
print(queue) # Output: deque([2, 3, 4])
queue.rotate(1)
print(queue) # Output: deque([4, 2, 3])

# OrderedDict - Track insertion order (LRU cache essential)
from collections import OrderedDict
cache = OrderedDict()
cache['A'] = 1
cache['B'] = 2
cache.move_to_end('A')
cache.popitem(last=False)
print(list(cache.keys())) # Output: ['B', 'A']

# ChainMap - Manage layered configurations
from collections import ChainMap
defaults = {'theme': 'dark', 'font': 'Arial'}
user_prefs = {'theme': 'light'}
settings = ChainMap(user_prefs, defaults)
print(settings['font']) # Output: Arial

# Practical Interview Tip: Anagram detection
print(Counter("secure") == Counter("rescue")) # Output: True

# Pro Tip: Sliding window maximum
def max_sliding_window(nums, k):
dq, result = deque(), []
for i, n in enumerate(nums):
while dq and nums[dq[-1]] < n:
dq.pop()
dq.append(i)
if dq[0] == i - k:
dq.popleft()
if i >= k - 1:
result.append(nums[dq[0]])
return result
print(max_sliding_window([1,3,-1,-3,5,3,6,7], 3)) # Output: [3,3,5,5,6,7]

# Expert Move: Custom LRU Cache implementation
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
del self.cache[key]
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
cache = LRUCache(2)
cache.put(1, 10)
cache.put(2, 20)
cache.get(1)
cache.put(3, 30)
print(list(cache.cache.keys())) # Output: [2, 1, 3] → Wait! Correction: Should be [1, 3] (capacity=2 triggers eviction of '2')

# Bonus: Multiset operations with Counter
primes = Counter([2, 3, 5, 7])
odds = Counter([1, 3, 5, 7, 9])
print(primes | odds) # Output: Counter({3:1, 5:1, 7:1, 2:1, 9:1, 1:1})


By: @DatascienceN🌟

#Python #CodingInterview #DataStructures #collections #Programming #TechJobs #Algorithm #LeetCode #DeveloperTips #CareerGrowth
1
💡 Python Lists Cheatsheet: Essential Operations

This lesson provides a quick reference for common Python list operations. Lists are ordered, mutable collections of items, and mastering their use is fundamental for Python programming. This cheatsheet covers creation, access, modification, and utility methods.

# 1. List Creation
my_list = [1, "hello", 3.14, True]
empty_list = []
numbers = list(range(5)) # [0, 1, 2, 3, 4]

# 2. Accessing Elements (Indexing & Slicing)
first_element = my_list[0] # 1
last_element = my_list[-1] # True
sub_list = my_list[1:3] # ["hello", 3.14]
copy_all = my_list[:] # [1, "hello", 3.14, True]

# 3. Modifying Elements
my_list[1] = "world" # my_list is now [1, "world", 3.14, True]

# 4. Adding Elements
my_list.append(False) # [1, "world", 3.14, True, False]
my_list.insert(1, "new item") # [1, "new item", "world", 3.14, True, False]
another_list = [5, 6]
my_list.extend(another_list) # [1, "new item", "world", 3.14, True, False, 5, 6]

# 5. Removing Elements
removed_value = my_list.pop() # Removes and returns last item (6)
removed_at_index = my_list.pop(1) # Removes and returns "new item"
my_list.remove("world") # Removes the first occurrence of "world"
del my_list[0] # Deletes item at index 0 (1)
my_list.clear() # Removes all items, list becomes []

# Re-create for other examples
numbers = [3, 1, 4, 1, 5, 9, 2]

# 6. List Information
list_length = len(numbers) # 7
count_ones = numbers.count(1) # 2
index_of_five = numbers.index(5) # 4 (first occurrence)
is_present = 9 in numbers # True
is_not_present = 10 not in numbers # True

# 7. Sorting
numbers_sorted_asc = sorted(numbers) # Returns new list: [1, 1, 2, 3, 4, 5, 9]
numbers.sort(reverse=True) # Sorts in-place: [9, 5, 4, 3, 2, 1, 1]

# 8. Reversing
numbers.reverse() # Reverses in-place: [1, 1, 2, 3, 4, 5, 9]

# 9. Iteration
for item in numbers:
# print(item)
pass # Placeholder for loop body

# 10. List Comprehensions (Concise creation/transformation)
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
even_numbers = [x for x in numbers if x % 2 == 0] # [2, 4]


Code explanation: This script demonstrates fundamental list operations in Python. It covers creating lists, accessing elements using indexing and slicing, modifying existing elements, adding new items with append(), insert(), and extend(), and removing items using pop(), remove(), del, and clear(). It also shows how to get list information like length (len()), item counts (count()), and indices (index()), check for item existence (in), sort (sort(), sorted()), reverse (reverse()), and iterate through lists. Finally, it illustrates list comprehensions for concise list generation and filtering.

#Python #Lists #DataStructures #Programming #Cheatsheet

━━━━━━━━━━━━━━━
By: @DataScience4
Please open Telegram to view this post
VIEW IN TELEGRAM
2
💡 Python Tips Part 4

Level up your Python code with more advanced tips. This part covers chaining comparisons, using sets for uniqueness, and powerful tools from the collections module like Counter and defaultdict.

x = 10

# Check if x is between 5 and 15 in a clean way
if 5 < x < 15:
print("x is in range.")

# Output: x is in range.

Chaining Comparisons: Python allows you to chain comparison operators for more readable and concise range checks. This is equivalent to (5 < x) and (x < 15).

numbers = [1, 2, 2, 3, 4, 4, 4, 5]

# Use a set to quickly get unique elements
unique_numbers = list(set(numbers))

print(unique_numbers)
# Output: [1, 2, 3, 4, 5]

Sets for Uniqueness: Sets are unordered collections of unique elements. Converting a list to a set and back is the fastest and most Pythonic way to remove duplicates.

from collections import Counter

words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)

print(word_counts)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
print(word_counts.most_common(1))
# Output: [('apple', 3)]

collections.Counter: A specialized dictionary subclass for counting hashable objects. It simplifies frequency counting tasks and provides useful methods like .most_common().

from collections import defaultdict

data = [('fruit', 'apple'), ('fruit', 'banana'), ('veg', 'carrot')]
grouped_data = defaultdict(list)

for category, item in data:
grouped_data[category].append(item)

print(grouped_data)
# Output: defaultdict(<class 'list'>, {'fruit': ['apple', 'banana'], 'veg': ['carrot']})

collections.defaultdict: A dictionary that provides a default value for a non-existent key, avoiding KeyError. It's perfect for grouping items into lists or dictionaries without extra checks.

#Python #Programming #CodeTips #DataStructures

━━━━━━━━━━━━━━━
By: @DataScience4
1
#37. .startswith()
Returns True if the string starts with the specified value.

filename = "document.pdf"
print(filename.startswith("doc"))

True


#38. .endswith()
Returns True if the string ends with the specified value.

filename = "image.jpg"
print(filename.endswith(".jpg"))

True


#39. .find()
Searches the string for a specified value and returns the position of where it was found. Returns -1 if not found.

text = "hello world"
print(text.find("world"))

6


#40. f-string (Formatted String Literal)
A way to embed expressions inside string literals.

name = "Alice"
age = 30
print(f"{name} is {age} years old.")

Alice is 30 years old.

---
#Python #ListMethods #DataStructures

#41. .append()
Adds an element at the end of the list.

fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits)

['apple', 'banana', 'cherry']


#42. .pop()
Removes the element at the specified position.

fruits = ['apple', 'banana', 'cherry']
fruits.pop(1) # Removes 'banana'
print(fruits)

['apple', 'cherry']


#43. .remove()
Removes the first item with the specified value.

fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')
print(fruits)

['apple', 'cherry', 'banana']


#44. .insert()
Adds an element at the specified position.

fruits = ['apple', 'cherry']
fruits.insert(1, 'banana')
print(fruits)

['apple', 'banana', 'cherry']


#45. .sort()
Sorts the list in place.

numbers = [3, 1, 5, 2]
numbers.sort()
print(numbers)

[1, 2, 3, 5]

---
#Python #DictionaryMethods #DataStructures

#46. dict()
Creates a dictionary.

my_dict = dict(name="John", age=36)
print(my_dict)

{'name': 'John', 'age': 36}


#47. .keys()
Returns a view object displaying a list of all the keys in the dictionary.

person = {'name': 'Alice', 'age': 25}
print(person.keys())

dict_keys(['name', 'age'])


#48. .values()
Returns a view object displaying a list of all the values in the dictionary.

person = {'name': 'Alice', 'age': 25}
print(person.values())

dict_values(['Alice', 25])


#49. .items()
Returns a view object displaying a list of a given dictionary's key-value tuple pairs.

person = {'name': 'Alice', 'age': 25}
print(person.items())

dict_items([('name', 'Alice'), ('age', 25)])


#50. .get()
Returns the value of the specified key. Provides a default value if the key does not exist.

person = {'name': 'Alice', 'age': 25}
print(person.get('city', 'Unknown'))

Unknown

---
#Python #ErrorHandling #FileIO

#51. try, except
Used to handle errors and exceptions.
# Check if `n > 0` and `(n & (n - 1)) == 0`.

• Pow(x, n): Implement pow(x, n).
# Use exponentiation by squaring for an O(log n) solution.

• Majority Element:
# Boyer-Moore Voting Algorithm for an O(n) time, O(1) space solution.

• Excel Sheet Column Number:
# Base-26 conversion from string to integer.

• Valid Number:
# Use a state machine or a series of careful conditional checks.

• Integer to English Words:
# Handle numbers in chunks of three (hundreds, tens, ones) with helper functions.

• Sqrt(x): Compute and return the square root of x.
# Use binary search or Newton's method.

• Gray Code:
# Formula: `i ^ (i >> 1)`.

• Shuffle an Array:
# Implement the Fisher-Yates shuffle algorithm.


IX. Python Concepts

• Explain the GIL (Global Interpreter Lock):
# Conceptual: A mutex that allows only one thread to execute Python bytecode at a time in CPython.

• Difference between __str__ and __repr__:
# __str__ is for end-users (readable), __repr__ is for developers (unambiguous).

• Implement a Context Manager (with statement):
class MyContext:
def __enter__(self): # setup
return self
def __exit__(self, exc_type, exc_val, exc_tb): # teardown
pass

• Implement itertools.groupby logic:
# Iterate through the sorted iterable, collecting items into a sublist until the key changes.


#Python #CodingInterview #DataStructures #Algorithms #SystemDesign

━━━━━━━━━━━━━━━
By: @DataScience4
3
Learning Common Algorithms with Python

• This lesson covers fundamental algorithms implemented in Python. Understanding these concepts is crucial for building efficient software. We will explore searching, sorting, and recursion.

Linear Search: This is the simplest search algorithm. It sequentially checks each element of the list until a match is found or the whole list has been searched. Its time complexity is O(n).

def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i # Return the index of the found element
return -1 # Return -1 if the element is not found

# Example
my_list = [4, 2, 7, 1, 9, 5]
print(f"Linear Search: Element 7 found at index {linear_search(my_list, 7)}")


Binary Search: A much more efficient search algorithm, but it requires the list to be sorted first. It works by repeatedly dividing the search interval in half. Its time complexity is O(log n).

def binary_search(sorted_data, target):
low = 0
high = len(sorted_data) - 1

while low <= high:
mid = (low + high) // 2
if sorted_data[mid] < target:
low = mid + 1
elif sorted_data[mid] > target:
high = mid - 1
else:
return mid # Element found
return -1 # Element not found

# Example
my_sorted_list = [1, 2, 4, 5, 7, 9]
print(f"Binary Search: Element 7 found at index {binary_search(my_sorted_list, 7)}")


Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The process is repeated until the list is sorted. Its time complexity is O(n^2).

def bubble_sort(data):
n = len(data)
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
if data[j] > data[j+1]:
# Swap the elements
data[j], data[j+1] = data[j+1], data[j]
return data

# Example
my_list_to_sort = [4, 2, 7, 1, 9, 5]
print(f"Bubble Sort: Sorted list is {bubble_sort(my_list_to_sort)}")


Recursion (Factorial): Recursion is a method where a function calls itself to solve a problem. A classic example is calculating the factorial of a number (n!). It must have a base case to stop the recursion.

def factorial(n):
# Base case: if n is 1 or 0, factorial is 1
if n == 0 or n == 1:
return 1
# Recursive step: n * factorial of (n-1)
else:
return n * factorial(n - 1)

# Example
num = 5
print(f"Recursion: Factorial of {num} is {factorial(num)}")


#Python #Algorithms #DataStructures #Coding #Programming #LearnToCode

━━━━━━━━━━━━━━━
By: @DataScience4
1
Python's deque: Implement Efficient Queues and Stacks

📖 Use a Python deque to efficiently append and pop elements from both ends of a sequence, build queues and stacks, and set maxlen for history buffers.

🏷️ #intermediate #datastructures #python #stdlib
1