Python | Algorithms | Data Structures | Cyber ​​Security | Networks
38.7K subscribers
788 photos
23 videos
21 files
717 links
This channel is for Programmers, Coders, Software Engineers.

1) Python
2) django
3) python frameworks
4) Data Structures
5) Algorithms
6) DSA

Admin: @Hussein_Sheikho

Ad & Earn money form your channel:
https://telega.io/?r=nikapsOH
Download Telegram
def process_data(data):
if data is None:
return "Error: No data provided."
if not isinstance(data, list) or not data:
return "Error: Invalid data format."

# ... logic is now at the top level ...
print("Processing data...")
return "Done"


#Python #CleanCode #Programming #BestPractices #CodingTips

━━━━━━━━━━━━━━━
By: @DataScience4
9. Use isinstance() for Type Checking
(It's safer and more robust than type() because it correctly handles inheritance.)

Cluttered Way (brittle, fails on subclasses):
class MyList(list): pass
my_list_instance = MyList()
if type(my_list_instance) == list:
print("It's a list!") # This will not print

Clean Way (correctly handles subclasses):
class MyList(list): pass
my_list_instance = MyList()
if isinstance(my_list_instance, list):
print("It's an instance of list or its subclass!") # This prints


10. Use the else Block in try/except
(Clearly separates the code that runs on success from the try block being monitored.)

Cluttered Way:
try:
data = my_ risky_operation()
# It's not clear if this next part can also raise an error
process_data(data)
except ValueError:
handle_error()

Clean Way:
try:
data = my_risky_operation()
except ValueError:
handle_error()
else:
# This code only runs if the 'try' block succeeds with NO exception
process_data(data)


#Python #CleanCode #Programming #BestPractices #CodeReadability

━━━━━━━━━━━━━━━
By: @DataScience4
10👍3
few-shot learning | AI Coding Glossary

📖 A setting where a model adapts to a new task using only a small number of labeled examples.

🏷️ #Python
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
reasoning model | AI Coding Glossary

📖 A generative model tuned to solve multi-step problems.

🏷️ #Python
chain of thought (CoT) | AI Coding Glossary

📖 A prompting technique that asks models to show intermediate steps, often improving multi-step reasoning but not guaranteeing accurate explanations.

🏷️ #Python
Interview Question

What is the potential pitfall of using a mutable object (like a list or dictionary) as a default argument in a Python function?

Answer: A common pitfall is that the default argument is evaluated only once, when the function is defined, not each time it is called. If that default object is mutable, any modifications made to it in one call will persist and be visible in subsequent calls.

This can lead to unexpected and buggy behavior.

Incorrect Example (The Pitfall):

def add_to_list(item, my_list=[]):
my_list.append(item)
return my_list

# First call seems to work fine
print(add_to_list(1)) # Output: [1]

# Second call has unexpected behavior
print(add_to_list(2)) # Output: [1, 2] -- The list from the first call was reused!

# Third call continues the trend
print(add_to_list(3)) # Output: [1, 2, 3]


The Correct, Idiomatic Solution:

The standard practice is to use None as the default and create a new mutable object inside the function if one isn't provided.

def add_to_list_safe(item, my_list=None):
if my_list is None:
my_list = [] # Create a new list for each call
my_list.append(item)
return my_list

# Each call now works independently
print(add_to_list_safe(1)) # Output: [1]
print(add_to_list_safe(2)) # Output: [2]
print(add_to_list_safe(3)) # Output: [3]


tags: #Python #Interview #CodingInterview #PythonTips #Developer #SoftwareEngineering #TechInterview

━━━━━━━━━━━━━━━
By: @DataScience4
2
How to Properly Indent Python Code

📖 Learn how to properly indent Python code in IDEs, Python-aware editors, and plain text editors—plus explore PEP 8 formatters like Black and Ruff.

🏷️ #basics #best-practices #python
1
😰 80 pages with problems, solutions, and code from a Python developer interview, ranging from simple to complex

⬇️ Save the PDF, it will come in handy!

#python #job
Please open Telegram to view this post
VIEW IN TELEGRAM
1
Editorial Guidelines

📖 See how Real Python's editorial guidelines shape comprehensive, up-to-date resources, with Python experts, educators, and editors refining all learning content.

🏷️ #Python
Send Feedback

📖 We welcome ideas, suggestions, feedback, and the occasional rant. Did you find a topic confusing? Or did you find an error in the text or code? Send us your feedback via this page.

🏷️ #Python
evaluation | AI Coding Glossary

📖 The process of measuring how well an AI system or model meets its objectives.

🏷️ #Python
1
vector | AI Coding Glossary

📖 An ordered array of numbers that represents a point, magnitude, and direction.

🏷️ #Python
Meet Our Team

📖 Meet Real Python's team of expert Python developers, educators, and 190+ contributors bringing real-world experience to create practical Python education.

🏷️ #Python
Pydantic AI | AI Coding Tools

📖 A Python framework for building typed LLM agents leveraging Pydantic.

🏷️ #Python
bias | AI Coding Glossary

📖 A systematic deviation from truth or fairness.

🏷️ #Python
Google Antigravity | AI Coding Tools

📖 An agent-first IDE where AI agents operate the editor, terminal, and browser and produce verifiable Artifacts of their work.

🏷️ #Python
nearest neighbor | AI Coding Glossary

📖 The data point in a reference set that has the smallest distance to a query point.

🏷️ #Python
autoregressive generation | AI Coding Glossary

📖 A method in which a model produces a sequence one token at a time, with each token conditioned on all previously generated tokens.

🏷️ #Python
💀 How to encrypt a PDF with a password using Python

Ready Python script: takes a regular PDF and creates a password-protected copy.

📦 Library installation
pip install PyPDF2


⌨️ Code
from __future__ import annotations
from pathlib import Path
from typing import Union

from PyPDF2 import PdfReader, PdfWriter

PDFPath = Union[str, Path]


def encrypt_pdf(input_path: PDFPath, output_path: PDFPath, password: str) -> Path:
    """
    Encrypts a PDF file with a password and saves it to output_path.
    Returns the path to the encrypted file.
    """
    in_path = Path(input_path)
    out_path = Path(output_path)

    reader = PdfReader(in_path)
    writer = PdfWriter()

    for page in reader.pages:
        writer.add_page(page)

    writer.encrypt(password)

    with out_path.open("wb") as f:
        writer.write(f)

    return out_path


def encrypt_with_suffix(input_path: PDFPath, password: str, suffix: str = "_encrypted") -> Path:
    """
    Creates an encrypted copy next to the original file.
    For example: secret.pdf → secret_encrypted.pdf
    """
    in_path = Path(input_path)
    output_path = in_path.with_name(f"{in_path.stem}{suffix}{in_path.suffix}")
    return encrypt_pdf(in_path, output_path, password)


if __name__ == "__main__":
    pdf_file = "secret.pdf"
    pdf_password = "pythontoday"

    encrypted_path = encrypt_with_suffix(pdf_file, pdf_password)
    print(f"Encrypted file created: {encrypted_path}")


💡 Where it will be useful

🟢send a document to a client with the password via a separate channel;
🟢store important PDFs in encrypted form;
🟢integrate encryption into your service/bot/admin panel.

#python #code #tipsandtricks

https://t.iss.one/DataScience4 🌟
Please open Telegram to view this post
VIEW IN TELEGRAM
👍1