Learn Python Coding
40.9K subscribers
718 photos
37 videos
24 files
532 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
Why regular expressions can hang on a simple string
Even a short string can cause a regular expression to take seconds or minutes to execute. The reason is catastrophic backtracking, where the engine tries a huge number of matching possibilities.
Let's look at an example:
import re

pattern = re.compile(r"(a+)+$")

text = "a" * 18 + "!"

print(bool(pattern.fullmatch(text)))

Output:
False

The expression (a+)+$ looks simple, but the problem lies in the nested quantifiers (a+)+. When the engine encounters the !, the match fails. However, before giving up, it tries various ways to distribute the a characters among the repetitions.
The number of possibilities grows rapidly with the length of the string. Let's check the execution time:
import re
from time import perf_counter

pattern = re.compile(r"(a+)+$")

for size in (10, 12, 14, 16, 18):
text = "a" * size + "!"

start = perf_counter()
pattern.fullmatch(text)
elapsed = perf_counter() - start

print(size, f"{elapsed:.6f} сек.")

The time depends on the processor and the version of Python, but for this pattern, you'll see an exponential increase in execution time as the number of a characters increases. This is dangerous when processing user input or external data.
If you need to check if a string consists only of a characters, nested repetitions are not necessary:
pattern = re.compile(r"a+")

print(bool(pattern.fullmatch("aaaa")))
print(bool(pattern.fullmatch("aaaa!")))

Output:
True
False

But not every problematic pattern can be simplified so easily. Starting with Python 3.11, the re module supports atomic groups (?x).
They prevent the engine from backtracking inside a successfully matched group to try other possibilities:
import re

pattern = re.compile(r"(?x)a+!$")

print(bool(pattern.fullmatch("aaaa")))
print(bool(pattern.fullmatch("aaaa!")))

Output:
True
False

The group (?x)a+ fixes the captured sequence of characters. The engine can no longer redistribute them within the group, which eliminates catastrophic backtracking in this example.
In Python 3.11, possessive quantifiers are also available: *+, ++, and ?+. They do not release captured characters during backtracking:
pattern = re.compile(r"(a++)+$")

print(bool(pattern.fullmatch("aaaa")))
print(bool(pattern.fullmatch("aaaa!")))

Output:
True
False

Here, a++ is equivalent to (?x)a+, so nested repetitions no longer cause exponential backtracking.
However, possessive quantifiers can change the matching result:
import re

print(bool(re.fullmatch(r"a+a", "aa")))
print(bool(re.fullmatch(r"a++a", "aa")))

Output:
True
False

A regular a+ might return one character for the last a. The quantifier a++ does not allow this.
Let's compare the performance of all three options using timeit:
import re
import timeit

text = "a" * 18 + "!"

patterns = {
"nested": re.compile(r"(a+)+$"),
"atomic": re.compile(r"(?x)a+!$"),
"possessive": re.compile(r"(a++)+$"),
}

for name, pattern in patterns.items():
elapsed = timeit.timeit(
lambda: pattern.fullmatch(text),
number=10
)

print(name, f"{elapsed:.6f} сек.")

Here, the total time for ten runs of each pattern is measured. It's useful to test strings that almost match the expression but contain an incorrect character at the end.
🔥 Ambiguous nested repetitions can cause exponential growth in execution time. Atomic groups and possessive quantifiers help limit backtracking, but only if their use preserves the necessary matching logic.
❤2
📝 Cheat sheet for Python:

Higher-order functions:

🔹 map() - applies a function to each element
🔹 filter() - selects elements based on a condition
🔹 reduce() - sequentially combines elements into a single value

These functions help to process collections concisely and perform data transformations.

#Python #Programming #Coding #HigherOrderFunctions #DataProcessing #TechTips

✨ Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
❤4
🔥 Free IT & Dev Study Kits – 2026 Prep & Double 11 Giveaway

Prepping for cloud, dev, or AI roles this year? These free kits cover the gaps most people skip — cert basics, hands-on labs, and mock exams.
📘 Cert E-Book — Cisco & AWS fundamentals, ideal for first-time cert takers
→
https://tinyurl.com/ynutkhec
🪜 Online Free Course — a structured path that works great as a refresher before exams
→
https://tinyurl.com/4kvuk4m6
☁️ Free AI Materials — from LLM basics to fine-tuning practice notebooks
→
https://tinyurl.com/2z46z8f4
📊 Cloud Study Guide — cheat-sheet style, handy for interview prep
→
https://tinyurl.com/ymncyj5k
🧠 Free Mock Exam — test yourself before booking the real thing
→
https://tinyurl.com/y7ffwecz

🎁 Double 11 Giveaway — win iPhone Duo & Amazon Gift Cards


📌 Save this or forward it to your dev/study group — good resources are worth sharing. 💪
🌐 Join Community to Draw: https://chat.whatsapp.com/KkbnOUuS55aJdZMtTGrVYL
📲 Personalized help: https://wa.link/xd2
❤4👍2
🚀 asyncio.Queue.shutdown() — shutting down handlers without special markers

Starting with Python 3.13, the asyncio.Queue can be closed using shutdown(), without the need to use None or other special values.

import asyncio

async def worker(queue):
while True:
try:
task = await queue.get()
except asyncio.QueueShutDown:
break

print(task)
queue.task_done()

async def main():
queue = asyncio.Queue()
task = asyncio.create_task(worker(queue))

await queue.put("task-1")
await queue.put("task-2")

queue.shutdown()
await queue.join()
await task

asyncio.run(main())

After shutdown(), no new items are added, and existing items are processed. When the queue is empty, get() will raise asyncio.QueueShutDown.

For a forced shutdown, there is shutdown(immediate=True), which clears the queue but may disrupt the normal behavior of join().

#Python #Asyncio #Programming #DevTips #Coding #Tech

✨ Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
❤1
🚨 SURPRISE ALERT! 🚨

Stop paying full price on Udemy. Seriously. 💸

I built a bot that hunts down 100% FREE Udemy coupons 24/7 — while you sleep, eat, or scroll. 🎯

Here's the magic:

📚 Mini App catalog — every active free coupon in one place
🔔 Auto-push — new courses land straight in your chat
📢 Live channel — never miss a deal

Why it matters?
Most people pay $200+ for courses you can grab for $0 — if you know where to look. Now you have a bot that does the looking for you. ⚡

🎓 Try it now: https://t.me/UdemySybot?start=adsun

Your future self (and your wallet) will thank you. 💜
❤1
Extracting named entities (NER) from contract texts using spaCy. 📝

Manually parsing legal documents to find organizations, dates, and amounts is too time-consuming. The spaCy library allows you to automatically find and classify named entities in unstructured text. We will write a Python script that loads a language model and recognizes key entities in a contract excerpt. 🚀

We will install the spaCy library and download a pre-trained language model for working with the Russian language. 🇷🇺

pip install spacy && python3 -m spacy download ru_core_news_sm


The spaCy library and the Russian language model have been successfully loaded into the environment. ✅

We will create a Python script called extract_ner.py that processes the contract text through a language pipeline and prints the identified entities. 🐍

import spacy

nlp = spacy.load("ru_core_news_sm")
text = "OOO 'Vector' undertakes to pay 500,000 rubles by October 15, 2026, in Moscow."
doc = nlp(text)

for ent in doc.ents:
print(f"{ent.text}


#spacy #python #nlp #dataScience #programming #automation

✨ Join Best TG Channels https://t.me/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
❤1
If you trade cryptocurrencies and are feeling confused about the current market, I strongly recommend you join the group I’ve mentioned

The group shares the following content every day:

✅ One trading signal a day (with a success rate of up to 85%)
✅ Real-time updates on cryptocurrency market trends
✅ Personalised, one-to-one technical trading advice

Whether you’re a beginner or an experienced trader, you’re welcome to join the group to exchange ideas and gain useful insights

Join now;https://t.me/+mEow9q0UJNhiYjg0
Please open Telegram to view this post
VIEW IN TELEGRAM
If you trade cryptocurrencies and are feeling confused about the current market, I strongly recommend you join the group I’ve mentioned

The group shares the following content every day:

✅ One trading signal a day (with a success rate of up to 85%)
✅ Real-time updates on cryptocurrency market trends
✅ Personalised, one-to-one technical trading advice

Whether you’re a beginner or an experienced trader, you’re welcome to join the group to exchange ideas and gain useful insights

Join now;https://t.me/+tF3JZ-Awdr9iZGYx
❤1👎1
💻 Into programming, AI or web development?

The tech world moves fast, and there's always something new to explore. Whether you're coding, testing new tools, or keeping up with the latest tech trends, having a reliable internet connection matters.

🌐 That's where DWZVPN comes in.
✔️ 30 days free
✔️ Multiple server locations
✔️ Switch between servers
✔️ Secure and private connections
✔️ Choose which apps use the VPN with Custom App Routing


👉🏼 No commitment. Download and try it:
Free, Secure & Private VPN | DWZVPN

Our channel : https://t.me/dwzvpn
 
🤖 ANDROID
🍎 IOS
💻 WINDOWS
🍔 MAC