Learn Python Coding
40.6K subscribers
707 photos
36 videos
24 files
509 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 interviews, understanding common algorithms like binary search is crucial for demonstrating problem-solving efficiencyโ€”often asked to optimize time complexity from O(n) to O(log n) for sorted data, showing your grasp of divide-and-conquer strategies.

# Basic linear search (O(n) - naive approach)
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1

nums = [1, 3, 5, 7, 9]
print(linear_search(nums, 5)) # Output: 2

# Binary search (O(log n) - efficient for sorted arrays)
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right: # Divide range until found or empty
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1 # Search right half
else:
right = mid - 1 # Search left half
return -1

sorted_nums = [1, 3, 5, 7, 9]
print(binary_search(sorted_nums, 5)) # Output: 2
print(binary_search(sorted_nums, 6)) # Output: -1 (not found)

# Edge cases
print(binary_search([], 1)) # Output: -1 (empty list)
print(binary_search(, 1)) # Output: 0 (single element)


#python #algorithms #binarysearch #interviews #timescomplexity #problemsolving

๐Ÿ‘‰ @DataScience4
โค5
# 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
โœจ Quiz: Recursion in Python: An Introduction โœจ

๐Ÿ“– Test your understanding of recursion in Python, including base cases, recursive structure, performance considerations, and common use cases.

๐Ÿท๏ธ #intermediate #algorithms #python
โค1
โœจ Quiz: Build a Hash Table in Python With TDD โœจ

๐Ÿ“– Learn how Python hashing spreads values into buckets and powers hash tables. Practice collisions, uniform distribution, and test-driven development.

๐Ÿท๏ธ #intermediate #algorithms #data-structures
โค2
โœจ Quiz: Python Stacks, Queues, and Priority Queues in Practice โœจ

๐Ÿ“– Test your knowledge of stacks, queues, deques, and priority queues with practical questions and Python coding exercises.

๐Ÿท๏ธ #intermediate #algorithms #data-structures
"Open Data Structures" is another very useful free resource for anyone studying data structures and algorithms. ๐Ÿ“šโœจ

The book discusses the implementation and analysis of basic structures: array-based lists, linked lists, hash tables, binary trees, red-black trees, heaps, sorting algorithms, graphs, and data structures for working with integers. ๐Ÿ”๐Ÿงฎ

This is a full-fledged open textbook for studying one of the fundamental topics of computer science and a good reference that's worth keeping on hand. ๐Ÿ’ป๐ŸŒŸ

https://opendatastructures.org/ods-python.pdf ๐Ÿ“„

๐Ÿ‘‰ @PythonRe

#DataStructures #Algorithms #Python #ComputerScience #OpenSource #Learning
Please open Telegram to view this post
VIEW IN TELEGRAM
โค8๐Ÿ‘1
"Introduction to Algorithms" ๐Ÿ“˜ - an outstanding university resource for everyone studying algorithms and computer science. ๐ŸŽ“๐Ÿ’ป

The book covers computational complexity, data structures, algorithms on graphs, dynamic programming, divide-and-conquer methods, greedy algorithms, randomized algorithms, and many mathematical foundations of modern computer science. ๐Ÿงฎ๐Ÿ“Š๐Ÿ”

What's particularly valuable here is the combination of mathematical rigor and practical algorithmic thinking. ๐Ÿง โœจ This is one of those books that greatly change the approach to problem analysis, efficiency, and computing itself. ๐Ÿš€๐Ÿ› 

An essential tool in the library of any developer and engineer working in the field of computer science. ๐Ÿ—๐Ÿ’พ

https://www.cs.mcgill.ca/~akroit/math/compsci/Cormen%20Introduction%20to%20Algorithms.pdf ๐Ÿ”—

#Algorithms #ComputerScience #Programming #CSStudent #TechEducation #DevTools
โค2
This media is not supported in your browser
VIEW IN TELEGRAM
This is how the Dijkstra algorithm works.

It's a pathfinding method used to find the shortest route between nodes in a graph. ๐Ÿ—บ๏ธ

1. Start at the source node.
2. Assign distance 0 to source, infinity to others.
3. Mark source as visited.
4. Select the unvisited node with the smallest distance.
5. Update neighbors' distances if a shorter path is found.
6. Repeat until all nodes are visited.

Key points:
- Greedy approach โœ…
- No negative weights allowed โš ๏ธ
- Time complexity: O((V + E) log V) ๐Ÿ•’

#Dijkstra #Algorithms #Pathfinding #ComputerScience #GraphTheory #TechEducation

โœจ Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

โญ๏ธ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A

๐Ÿš€ Level up your AI & Data Science skills with HelloEncyclo โ€” a growing all-in-one platform featuring hands-on courses in LLMs, Deep Learning, MLOps, Data Engineering, and more.
โœ… 13 courses live + 40+ coming soon
๐ŸŽฏ One access, lifetime updates
๐Ÿ”‘ Use code: PRESALE-BOOK-WAVE-2GFG
๐Ÿ‘‰ https://helloencyclo.com/?ref=HUSSEINSHEIKHO
1โค6๐Ÿ‘2๐Ÿ‘2
๐Ÿ‘ฉโ€๐Ÿ’ป heapq.merge(): Combining sorted data!

If you have multiple sources of data that are already sorted, you don't need to collect them into a single collection and sort them again. heapq.merge() combines such sources into a single, ordered iterator.

In this guide:
โ€ข We will combine multiple sorted sequences;
โ€ข We will explore lazy processing of large data sources;
โ€ข We will configure comparison using the key argument;
โ€ข We will combine data sorted in reverse order.

This is especially useful when working with logs, files, and query results, where each source already provides data in the correct order.

#Python #heapq #DataProcessing #CodingTips #Programming #Algorithms

โœจ Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

โญ๏ธ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
โค1