# Paste this into a Python environment (Python 3.8+). No external internet needed. # Replace CIPHER with the exact ciphertext string (digits or letters). import math from collections import Counter, defaultdict import itertools import random # ------------------------- CIPHER = "PASTE_CIPHERTEXT_HERE" # <-- replace this with the D'Agapeyeff ciphertext # ------------------------- # Basic normalization text_raw = "".join(CIPHER.strip().split()) # If digits, keep digits and maybe split into pairs/triples; if letters, uppercase letters only. is_digit = all(ch.isdigit() for ch in text_raw) is_alpha = all(ch.isalpha() for ch in text_raw) def split_digits(text, group=2): return [text[i:i+group] for i in range(0,len(text),group)] def freq_stats(s): c = Counter(s) total = len(s) freqs = [(ch, count, count/total) for ch,count in c.most_common()] return freqs print("Raw length:", len(text_raw)) print("All digits?", is_digit, "All letters?", is_alpha) if is_digit: for g in (1,2,3): groups = split_digits(text_raw, g) print(f"\nGrouping by {g} -> {len(groups)} tokens. Sample:", groups[:20]) print("Frequencies:", freq_stats(groups)[:10]) else: letters = [c.upper() for c in text_raw if c.isalpha()] print("\nLetter sample:", "".join(letters[:80])) print("Letter frequencies:", freq_stats(letters)[:20]) # compute Index of Coincidence N = len(letters) ic = sum(v*(v-1) for v in Counter(letters).values()) / (N*(N-1)) if N>1 else 0 print("Index of Coincidence:", ic) # ------------------------- # Quick Vigenere bruteforce using english quadgram scoring # ------------------------- # Quadgram statistics small sample (for speed). For best results replace with a full quadgram table. quadgrams = { 'TION': 1.0, 'THER':0.9, 'HERE':0.8, 'MENT':0.7, 'ENTH':0.6, # not exhaustive } def score_text_quads(s): s = "".join(ch for ch in s.upper() if ch.isalpha()) score = 0.0 for i in range(len(s)-3): w = s[i:i+4] score += math.log10(quadgrams.get(w, 0.01)) return score def vigenere_decrypt(ct, key): res = [] ki = 0 for ch in ct: if ch.isalpha(): offset = ord('A') k = ord(key[ki%len(key)].upper())-offset p = chr((ord(ch.upper())-offset - k) % 26 + offset) res.append(p) ki += 1 else: res.append(ch) return "".join(res) def try_vigenere(ct, max_keylen=10): ct_letters = "".join(ch for ch in ct.upper() if ch.isalpha()) best = [] for klen in range(1, max_keylen+1): for key_candidate in itertools.product("ABCDEFGHIJKLMNOPQRSTUVWXYZ", repeat=klen): key = "".join(key_candidate) pt = vigenere_decrypt(ct_letters, Had to remove some of the code due to 3000 word limit 🥺🤔🤐🥴 having a nerd 🤓 moment. Things are different 🤫
Python script for D'Agapeyeff cipher decryption
More Relevant Posts
-
Top Five python tricks 1. Multiple Assignment & Swapping Variables # Instead of: a = 1 b = 2 c = 3 # Do this: a, b, c = 1, 2, 3 # Swap variables without temp variable x, y = 10, 20 x, y = y, x # Now x=20, y=10 # Unpacking iterables first, *middle, last = [1, 2, 3, 4, 5] print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5 2. List Comprehensions with Conditions # Instead of: squares = [] for i in range(10): if i % 2 == 0: squares.append(i**2) # Do this: squares = [i**2 for i in range(10) if i % 2 == 0] # More complex example: result = [x.upper() for x in ['hello', 'world', 'python'] if len(x) > 4] print(result) # ['HELLO', 'WORLD', 'PYTHON'] 3. The zip() Function for Parallel Iteration # Iterate over multiple lists simultaneously names = ['Alice', 'Bob', 'Charlie'] scores = [85, 92, 78] subjects = ['Math', 'Science', 'English'] for name, score, subject in zip(names, scores, subjects): print(f"{name} scored {score} in {subject}") # Create dictionary from two lists score_dict = dict(zip(names, scores)) print(score_dict) # {'Alice': 85, 'Bob': 92, 'Charlie': 78} 4. enumerate() for Index-Value Pairs # Instead of: fruits = ['apple', 'banana', 'cherry'] for i in range(len(fruits)): print(f"Index {i}: {fruits[i]}") # Do this: for i, fruit in enumerate(fruits): print(f"Index {i}: {fruit}") # With custom start index for i, fruit in enumerate(fruits, start=1): print(f"#{i}: {fruit}") 5. Dictionary Comprehensions & Merging # Create dictionary from list names = ['Alice', 'Bob', 'Charlie'] name_lengths = {name: len(name) for name in names} print(name_lengths) # {'Alice': 5, 'Bob': 3, 'Charlie': 7} # Merge dictionaries (Python 3.9+) dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged = dict1 | dict2 # {'a': 1, 'b': 3, 'c': 4} # For older Python versions: merged = {**dict1, **dict2}
To view or add a comment, sign in
-
#AI #ML #Python #Post4🚀 Decorator in Python, is a special function that modifies or enhances the behavior of another function or method — without permanently changing its code. You can think of a decorator as a wrapper that adds extra functionality around your existing functions. ------------------------------------------------------------- ✅️Real-World Use Cases ------------------------------------------------------------- 📌1. Logging def log(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") result = func(*args, **kwargs) print(f"{func.__name__} finished") return result return wrapper @log def add(a, b): return a + b add(2, 3) 📌2. Authorization (Flask/Django-style) def require_login(func): def wrapper(user): if not user.get("logged_in"): print("Access denied") return return func(user) return wrapper @require_login def view_profile(user): print(f"Welcome {user['name']}") view_profile({"name": "Alice", "logged_in": False}) 📌3. Timing Function Execution import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__} took {end - start:.4f} seconds") return result return wrapper @timer def compute(): sum([i*i for i in range(100000)]) compute() Class-based decorators, which do the same thing as function-based ones — but give you more power and flexibility, especially when you need to store state or maintain configuration across multiple calls. ------------------------------------------------------------- ✅️What is a Class-Based Decorator? ------------------------------------------------------------- A class-based decorator is simply a class that: 📌1. Takes a function in its constructor (__init__) 📌2. Implements the __call__() method, so that the instance can be called like a function 👉This way, when Python sees @MyDecorator, it: 👉Creates an instance of MyDecorator, passing the decorated function to it. 👉Then, every time you call the decorated function, it actually calls MyDecorator.__call__(). ------------------------------------------------------------- ✍️Example 1: Simple Class Decorator ‐------------------------------------------------------------ class MyDecorator: def __init__(self, func): self.func = func # store the original function def __call__(self, *args, **kwargs): print("Before the function runs") result = self.func(*args, **kwargs) print("After the function runs") return result @MyDecorator def say_hello(): print("Hello!") say_hello() ------------------------------------------------------------- 💻Output: ------------------------------------------------------------- Before the function runs Hello! After the function runs
To view or add a comment, sign in
-
-
Ever wonder how 'resilient' your code really is? Built this quick Python scorer: Blends structure (goals/steps/tests) with resonance (soft vs harsh lang) for a coherence metric—ρ=exp(-λD-κIu) guards the edge of chaos. Demo on sample snippets: density 0.65, coherence 0.94 (solid pass!). Open to thoughts or collabs on agent tools. #Python #AIAgents #CodeResilience from math import exp from typing import List, Dict import re import statistics as stats # Code Resilience Scorer SOFT = {"we", "let", "can", "now", "together", "clear", "safe", "steady", "choice"} HARSH = {"must", "always", "never", "fail", "worthless", "stupid", "idiot"} def resonance_score(text: str) -> float: words = re.findall(r"\w+", text.lower()) if not words: return 0.5 s = sum(w in SOFT for w in words); h = sum(w in HARSH for w in words) base = 0.6 + 0.05 * s - 0.08 * h return max(0.0, min(1.0, base)) def structure_ok(text: str) -> bool: g = re.search(r"\b(goal|objective|spec|requirement)\b", text, re.I) s = re.search(r"\b(step|procedure|algorithm|pipeline|pseudo)\b", text, re.I) t = re.search(r"\b(test|assert|verify|benchmark|pass|fail)\b", text, re.I) return sum(bool(x) for x in (g, s, t)) >= 2 def coherence_summary(snippets: List[str], lam: float = 3.7, kappa: float = 0.18) -> Dict: non_empty = [s for s in snippets if s and s.strip()] if not non_empty: density = 0.0 disp = 0.0 else: struct = [1.0 if structure_ok(s) else 0.3 for s in non_empty] density = sum(struct) / len(non_empty) res = [resonance_score(s) for s in non_empty] disp = stats.pvariance(res) if len(res) > 1 else 0.0 iu = disp + (1.0 - density) coh = exp(-(lam * disp + kappa * iu)) return {"density": round(density, 4), "dispersion": round(disp, 6), "coherence": round(coh, 6)} # Demo demo_snippets = [ "Goal: Build a resilient agent. Step: Add coherence check. Test: Rho > 0.5", "Explain core logic clearly. Include a simple benchmark for stability." ] result = coherence_summary(demo_snippets) print(result) # Output: {'density': 0.65, 'dispersion': 0.0, 'coherence': 0.938943}
To view or add a comment, sign in
-
🚀 **Day 34 of #100DaysOfPython – Date and Time in Python** 🕒 Python provides the **`datetime`** module to handle dates and times efficiently. Let’s explore the most useful features with simple examples 👇 --- ### 🧭 1️⃣ Importing the datetime Module ```python import datetime ``` This gives access to classes like `date`, `time`, `datetime`, and `timedelta`. --- ### 📅 2️⃣ Working with Dates ```python from datetime import date today = date.today() print("Today's date:", today) specific_date = date(2024, 2, 16) print("Specific date:", specific_date) ``` ✅ You can extract parts of a date: ```python print("Year:", today.year) print("Month:", today.month) print("Day:", today.day) ``` ✅ To find the weekday: ```python print("Weekday (0=Mon):", today.weekday()) print("ISO Weekday (1=Mon):", today.isoweekday()) ``` --- ### ⏰ 3️⃣ Working with Time ```python from datetime import time specific_time = time(14, 30, 15) print("Specific time:", specific_time) print("Hour:", specific_time.hour) print("Minute:", specific_time.minute) print("Second:", specific_time.second) ``` --- ### 📆 4️⃣ Date and Time Together ```python from datetime import datetime now = datetime.now() print("Current date and time:", now) specific_datetime = datetime(2024, 2, 16, 14, 30, 15) print("Specific date and time:", specific_datetime) ``` ✅ Extract individual parts: ```python print("Year:", now.year) print("Month:", now.month) print("Day:", now.day) print("Hour:", now.hour) print("Minute:", now.minute) print("Second:", now.second) ``` --- ### 🕓 5️⃣ Formatting Dates & Times ```python formatted_date = now.strftime("%Y-%m-%d") formatted_time = now.strftime("%H:%M:%S") formatted_datetime = now.strftime("%d-%b-%Y %I:%M %p") print("Formatted Date:", formatted_date) print("Formatted Time:", formatted_time) print("Formatted Date and Time:", formatted_datetime) ``` 📘 Example: `%Y` = Year, `%m` = Month, `%d` = Day, `%H` = Hour, `%M` = Minute, `%S` = Second, `%p` = AM/PM --- ### 🔁 6️⃣ Parsing Strings into Dates ```python from datetime import datetime date_string = "16-02-2024 14:30" parsed_date = datetime.strptime(date_string, "%d-%m-%Y %H:%M") print("Parsed Date and Time:", parsed_date) ``` --- ### ⏳ 7️⃣ Date and Time Arithmetic ```python from datetime import timedelta from datetime import date, datetime today = date.today() now = datetime.now() future_date = today + timedelta(days=7) past_date = today - timedelta(days=3) future_time = now + timedelta(hours=2) print("Date after 7 days:", future_date) print("Date 3 days ago:", past_date) print("Time after 2 hours:", future_time) ``` --- ✨ **In short:** - `date` → handles calendar dates - `time` → handles time only - `datetime` → combines both - `timedelta` → does date/time math 💬 What’s the most common date format you use in your projects? #Python #100DaysOfCode #PythonProgramming #LearningPython #DateTime
To view or add a comment, sign in
-
Proposed #Python Solution: Automated File Organizer One common real-world problem is digital clutter, where files downloaded or created accumulate in a single folder (like 'Downloads' or 'Desktop'), making it difficult to locate specific documents quickly. A short Python script can solve this by automatically organizing files into specific, designated subfolders based on their file extension (e.g., all .pdf files go into a 'PDFs' folder, all .jpg files go into an 'Images' folder). import os import shutil # 1. Define the directory to organize (e.g., your Downloads folder) SOURCE_DIR = "/path/to/your/unorganized/folder" # 2. Define mapping from file extensions to folder names FILE_TYPE_MAPPING = { 'pdf': 'PDFs', 'jpg': 'Images', 'png': 'Images', 'docx': 'Documents', 'xlsx': 'Spreadsheets', 'mp4': 'Videos', 'zip': 'Archives' } def organize_files(directory): for filename in os.listdir(directory): # Skip directories and the script itself if os.path.isdir(os.path.join(directory, filename)) or filename == os.path.basename(__file__): continue # Get the file extension (lowercase) file_ext = filename.split('.')[-1].lower() # Determine the target folder name target_folder_name = FILE_TYPE_MAPPING.get(file_ext, 'Others') # Create the full path for the target folder target_path = os.path.join(directory, target_folder_name) # 3. Create the folder if it doesn't exist if not os.path.exists(target_path): os.makedirs(target_path) # 4. Move the file source_file = os.path.join(directory, filename) destination_file = os.path.join(target_path, filename) # Handle files with the same name (optional: adds a simple rename for safety) if os.path.exists(destination_file): print(f"Skipping duplicate: {filename}") continue shutil.move(source_file, destination_file) print(f"Moved {filename} to {target_folder_name}") # Execute the organization if __name__ == "__main__": print(f"Starting organization in: {SOURCE_DIR}") organize_files(SOURCE_DIR) print("Organization complete!")
To view or add a comment, sign in
-
QUICK TIP #4 — QUEUE - Counter Line - First In, First Served (Python Queue) 1. Goal Clearly demonstrate how the queue follows the FIFO rule — First In, First Out — meaning the first item to enter is the first one to leave. 2. Everyday Analogy The deli counter line: first ticket gets served first. Last to enter? Wait your turn. 3. Technical Concept A queue is FIFO (First-In, First-Out). In Python, use collections.deque (light & fast) or queue.Queue (thread-safe for multithreading). 4. When to Use · Sequential processing (orders, messages, jobs) · Producer–consumer buffers · Async/multithread task control 5. Python Example (simple & commented) # ================================================ # Script: The Counter Line – Processing in FIFO Order # Author: Izairton Oliveira de Vasconcelos # ================================================ from collections import deque from time import sleep # 1️⃣ First Step — Create an empty queue queue = deque() print("🏁 Starting the service system...\n") # 2️⃣ Second Step — Arrivals (incoming orders) queue.append("Order #101") print("🟢 Arrived:", queue[-1]) sleep(0.5) queue.append("Order #102") print("🟢 Arrived:", queue[-1]) sleep(0.5) queue.append("Order #103") print("🟢 Arrived:", queue[-1]) sleep(0.5) # 3️⃣ Third Step — Peek the first (without removing) print("\n👀 First in line (no service yet):", queue[0]) # 4️⃣ Fourth Step — Service (leave from the left → FIFO) served_1 = queue.popleft() print("🔵 Served:", served_1) sleep(0.5) served_2 = queue.popleft() print("🔵 Served:", served_2) sleep(0.5) # 5️⃣ Fifth Step — New arrival queue.append("Order #104") print("🟢 New order arrived:", queue[-1]) sleep(0.5) # 6️⃣ Sixth Step — Final state print("\n📦 Current queue:", list(queue)) print("✅ Service finished!") # ================================================ # Expected output: # 🟢 Arrived: Order #101 # 🟢 Arrived: Order #102 # 🟢 Arrived: Order #103 # 👀 First in line (no service yet): Order #101 # 🔵 Served: Order #101 # 🔵 Served: Order #102 # 🟢 New order arrived: Order #104 # 📦 Current queue: ['Order #103', 'Order #104'] # ================================================ 6. Expected Output (example) Order #101 | Order #101 | Order #102 | ['Order #103', 'Order #104'] 7. Real-World Uses · Print/spool queues, customer service tickets · ETL orchestration: events flowing and consumed · Message brokers (RabbitMQ, SQS, Redis) 8. Common Pitfalls · Using list.pop(0) (slow) instead of deque.popleft() (fast) · Mixing FIFO with priority (use heapq/PriorityQueue if you need it) · Ignoring thread safety with multiple threads (use queue.Queue) 9. Fun Fact deque is a high-performance double-ended queue, O(1) ops at both ends. 10. The Aha Moment (a.k.a. The Cat’s Meow) Single-threaded speed? deque with append/popleft. Multithread producer/consumer? queue.Queue with put/get.
To view or add a comment, sign in
-
-
🧱 QUICK TIP #2 – “Numbered Shelf: How the ARRAY Keeps Everything in Place (Python)” 1️⃣ Structure Name Array (indexed collection) 2️⃣ Goal Store many elements side by side and access each one by index with constant-time speed. 3️⃣ Everyday Analogy Think of a numbered shelf (0, 1, 2, 3…). You know exactly where each item is and grab it by position — no searching required. 4️⃣ Common Use Cases Math & stats operations Signals, images, numeric series Data buffers & batch processing Compact memory layouts 5️⃣ Technical Advantage Random access O(1) by index: read/write is blazing fast when you know the position. 6️⃣ Technical Drawback Often fixed-size in low-level arrays; inserting in the middle is costly (shifts elements). 7️⃣ Python Example (lists used like arrays) # Arrays in Python – quick demo ⚡ # Author: Izairton Oliveira de Vasconcelos import time import numpy as np print("=== ARRAYS IN PYTHON ===") # Basic list demo prices = [9.90, 12.50, 7.80, 15.00] prices[2] = 8.10 prices.insert(1, 10.00) print("Prices:", prices) # NumPy fast math a = np.array([1, 2, 3, 4]) print("a * 10 ->", a * 10) print("mean ->", a.mean(), "std ->", a.std()) # Middle insertion cost arr = list(range(100000)) t0 = time.perf_counter() arr.insert(len(arr)//2, -1) print(f"Insertion in middle took {(time.perf_counter()-t0)*1000:.3f} ms") print(prices, first_item) 8️⃣ Efficient Numeric Example (NumPy) import numpy as np a = np.array([1, 2, 3, 4]) b = a * 10 # vectorized op mean_val = a.mean() # fast stats print(b, mean_val) # [10 20 30 40], 2.5 9️⃣ When to Use When you need fast index-based access and batch numeric operations with contiguous memory. 🔟 ✨ The Aha Moment (Resumo do Pulo do Gato) “An array is your program’s numbered shelf: every item has a fixed address, so you grab exactly what you need instantly.”
To view or add a comment, sign in
-
-
𝗦𝘁𝗼𝗽 𝗺𝗮𝗻𝘂𝗮𝗹𝗹𝘆 𝗰𝗼𝗹𝗼𝗿𝗶𝗻𝗴 𝗰𝗲𝗹𝗹𝘀 𝗶𝗻 𝗚𝗼𝗼𝗴𝗹𝗲 𝗦𝗵𝗲𝗲𝘁𝘀! 🎨 If you're still spending time clicking Format -> Conditional Formatting on your reports, there's a better way. By leveraging Python, you can transform your data reporting from a manual chore into a fully automated workflow. 𝗪𝗵𝘆 𝘂𝘀𝗲 𝗣𝘆𝘁𝗵𝗼𝗻 𝗳𝗼𝗿 𝗚𝗼𝗼𝗴𝗹𝗲 𝗦𝗵𝗲𝗲𝘁𝘀 𝗳𝗼𝗿𝗺𝗮𝘁𝘁𝗶𝗻𝗴? ✅ 𝗦𝗰𝗮𝗹𝗮𝗯𝗶𝗹𝗶𝘁𝘆: Format 100 columns as easily as you format 1. ✅ 𝗖𝗼𝗻𝘀𝗶𝘀𝘁𝗲𝗻𝗰𝘆: Eliminate "oops" moments. Get pixel-perfect reports every time. ✅ 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗥𝘂𝗹𝗲𝘀: Implement complex logic that the UI can't handle. 𝗖𝘂𝗿𝗶𝗼𝘂𝘀 𝗵𝗼𝘄 𝗶𝘁 𝘄𝗼𝗿𝗸𝘀 𝗶𝗻 𝗽𝗿𝗮𝗰𝘁𝗶𝗰𝗲? 𝗛𝗲𝗿𝗲'𝘀 𝘁𝗵𝗲 𝘀𝗶𝗺𝗽𝗹𝗲, 𝟯-𝘀𝘁𝗲𝗽 𝗹𝗼𝗴𝗶𝗰: 𝗦𝘁𝗲𝗽 𝟭: 𝗖𝗼𝗻𝗻𝗲𝗰𝘁 𝘁𝗼 𝗬𝗼𝘂𝗿 𝗦𝗵𝗲𝗲𝘁 Use the gspread library to securely authenticate and open your target Google Sheet, all from your Python script. 𝗦𝘁𝗲𝗽 𝟮: 𝗗𝗲𝗳𝗶𝗻𝗲 𝗬𝗼𝘂𝗿 𝗥𝘂𝗹𝗲 𝗶𝗻 𝗖𝗼𝗱𝗲 This is the magic. You create a "rule" object that specifies three things: 𝗧𝗵𝗲 𝗥𝗮𝗻𝗴𝗲: Which cells do you want to format? (e.g., 'C2:C100') 𝗧𝗵𝗲 𝗖𝗼𝗻𝗱𝗶𝘁𝗶𝗼𝗻: What logic should trigger the format? This is written as a standard Google Sheets formula. (e.g., =C2 < B2 to check if the value went down). 𝗧𝗵𝗲 𝗙𝗼𝗿𝗺𝗮𝘁: What should the cell look like? (e.g., a red background). 𝗦𝘁𝗲𝗽 𝟯: 𝗔𝗽𝗽𝗹𝘆 𝘁𝗵𝗲 𝗥𝘂𝗹𝗲 Your script sends these instructions to the Google Sheets API, and your sheet is formatted instantly. Here's a simplified code example of a rule that colors a cell red if its value is less than the cell to its left: 𝗣𝘆𝘁𝗵𝗼𝗻 𝗰𝗼𝗱𝗲 # 𝙸𝚖𝚙𝚘𝚛𝚝 𝚝𝚑𝚎 𝚗𝚎𝚌𝚎𝚜𝚜𝚊𝚛𝚢 𝚏𝚘𝚛𝚖𝚊𝚝𝚝𝚒𝚗𝚐 𝚝𝚘𝚘𝚕𝚜 𝚏𝚛𝚘𝚖 𝚐𝚜𝚙𝚛𝚎𝚊𝚍_𝚏𝚘𝚛𝚖𝚊𝚝𝚝𝚒𝚗𝚐 𝚒𝚖𝚙𝚘𝚛𝚝 * # 𝟷. 𝙳𝚎𝚏𝚒𝚗𝚎 𝚝𝚑𝚎 𝚛𝚞𝚕𝚎 𝚛𝚞𝚕𝚎 = 𝙲𝚘𝚗𝚍𝚒𝚝𝚒𝚘𝚗𝚊𝚕𝙵𝚘𝚛𝚖𝚊𝚝𝚁𝚞𝚕𝚎( 𝚛𝚊𝚗𝚐𝚎𝚜=['𝙲𝟸:𝙲𝟷𝟶𝟶'], # 𝚃𝚑𝚎 𝚛𝚊𝚗𝚐𝚎 𝚝𝚘 𝚊𝚙𝚙𝚕𝚢 𝚏𝚘𝚛𝚖𝚊𝚝𝚝𝚒𝚗𝚐 𝚝𝚘 𝚋𝚘𝚘𝚕𝚎𝚊𝚗𝚁𝚞𝚕𝚎=𝙱𝚘𝚘𝚕𝚎𝚊𝚗𝚁𝚞𝚕𝚎( 𝚌𝚘𝚗𝚍𝚒𝚝𝚒𝚘𝚗=𝙱𝚘𝚘𝚕𝚎𝚊𝚗𝙲𝚘𝚗𝚍𝚒𝚝𝚒𝚘𝚗('𝙲𝚄𝚂𝚃𝙾𝙼_𝙵𝙾𝚁𝙼𝚄𝙻𝙰', ['=𝙲𝟸 < 𝙱𝟸']), 𝚏𝚘𝚛𝚖𝚊𝚝=𝙲𝚎𝚕𝚕𝙵𝚘𝚛𝚖𝚊𝚝(𝚋𝚊𝚌𝚔𝚐𝚛𝚘𝚞𝚗𝚍𝙲𝚘𝚕𝚘𝚛=𝙲𝚘𝚕𝚘𝚛(𝟷, 𝟶, 𝟶)) # 𝚁𝚎𝚍 𝚋𝚊𝚌𝚔𝚐𝚛𝚘𝚞𝚗𝚍 ) ) # 𝟸. 𝙰𝚍𝚍 𝚝𝚑𝚎 𝚛𝚞𝚕𝚎 𝚝𝚘 𝚢𝚘𝚞𝚛 𝚠𝚘𝚛𝚔𝚜𝚑𝚎𝚎𝚝 𝚊𝚗𝚍 𝚜𝚊𝚟𝚎 𝚛𝚞𝚕𝚎𝚜 = 𝚐𝚎𝚝_𝚌𝚘𝚗𝚍𝚒𝚝𝚒𝚘𝚗𝚊𝚕_𝚏𝚘𝚛𝚖𝚊𝚝_𝚛𝚞𝚕𝚎𝚜(𝚠𝚘𝚛𝚔𝚜𝚑𝚎𝚎𝚝) 𝚛𝚞𝚕𝚎𝚜.𝚊𝚙𝚙𝚎𝚗𝚍(𝚛𝚞𝚕𝚎) 𝚛𝚞𝚕𝚎𝚜.𝚜𝚊𝚟𝚎() By placing this logic inside a loop, you can apply similar rules across an entire report in seconds. A little bit of code saves hours in the long run. It's a true "set it and forget it" solution. What's the most tedious task you've automated in your workflow? Share below! 👇 #Python #GoogleSheets #DataAutomation #Automation #DataAnalytics #Reporting #BusinessIntelligence #Gspread
To view or add a comment, sign in
-
-
⚡ Handling Missing Values in Python Here’s a simple breakdown of the different methods used in Python 1️⃣ Identify Missing Values df.isnull() # Shows True/False for missing values df.isnull(). sum() # Counts missing values per column You can also check the percentage of missing data: (df.isnull(). sum() / len(df)) * 100 2️⃣ Remove Missing Values If the missing values are few or not significant: df.dropna() # Removes rows with missing values df.dropna(axis=1) # Removes columns with missing values Use this when deleting data doesn’t affect the dataset’s overall quality. 3️⃣ Fill Missing Values When you can’t afford to drop data, fill the missing values instead. 🔹 Constant value df['Name']. fillna('Unknown', inplace=True) 🔹 Mean / Median / Mode (for numerical columns) df['Age']. fillna (df['Age']. mean(), inplace=True) df['Salary'].fillna (df['Salary'].median(), inplace=True) 🔹Forward or Backward Fill (for time series) df.fillna(method='ffill', inplace=True) # Forward fill df.fillna(method='bfill', inplace=True) # Backward fill 4️⃣ Advanced Imputation Using Models For large datasets or when data is missing in patterns: from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy='mean') df[['Age', 'Salary']] = imputer.fit_transform(df[['Age', 'Salary']]) Other strategies: 'median,' 'most_frequent,' and 'constant.' 🔹 Best Practices Use mean/median for numerical data. Use mode or “Unknown” for categorical data. Drop columns if more than 40–50% of the data is missing. Always analyze the pattern of missingness before deciding. #Python #DataCleaning #Pandas #DataAnalytics
To view or add a comment, sign in
-
-
🚀 Day 35 of #100DaysOfPython – Working with Date, Time & Calendar 🕒📅 Today’s topic helps us retrieve and manipulate the current date, time, and calendar using Python’s built-in modules — time and calendar. 🕐 1️⃣ Retrieving the Current Time Python provides the time() and localtime() functions to get system time. import time lt = time.localtime(time.time()) print(lt) 🧩 Output example: time.struct_time(tm_year=2022, tm_mon=4, tm_mday=14, tm_hour=10, tm_min=30, ...) 🔹 Attributes of time.struct_time: tm_year → Current year tm_mon → Current month tm_mday → Day of month tm_hour → Hour tm_min → Minute tm_sec → Second tm_wday → Weekday tm_yday → Day of year tm_isdst → Daylight saving flag 🕓 2️⃣ Formatted Time with asctime() The asctime() method returns the current time as a formatted string. import time lt = time.asctime(time.localtime(time.time())) print(lt) ✅ Example Output: Thu Apr 14 10:33:59 2022 🧮 3️⃣ Converting String to Time – strptime() Used to parse strings into time structures. import time tr = time.strptime("26 jun 14", "%d %b %y") print(tr) 📖 Example Output: time.struct_time(tm_year=2014, tm_mon=6, tm_mday=26, ...) 🧭 4️⃣ Formatting Time – strftime() Converts time into a specific string format. import time t = (2014, 6, 26, 17, 3, 38, 1, 48, -1) t = time.mktime(t) print(time.strftime("%d %m %y %H:%M:%S", time.gmtime(t))) ✅ Output: 26 06 14 11:33:38 📆 5️⃣ Python Calendar Module The calendar module allows working with dates, months, and years. import calendar print(calendar.prcal(2023)) 🧠 Common Calendar Functions: Method Description prcal(year) Prints full calendar for a year firstweekday() Returns first weekday (default Monday = 0) isleap(year) Checks if year is leap monthcalendar(year, month) Returns matrix of weeks in month leapdays(y1, y2) Counts leap years between y1 and y2 prmonth(year, month) Prints specific month 🗓️ Example: import calendar print(calendar.isleap(2020)) # True print(calendar.monthcalendar(2022, 6)) calendar.prmonth(2022, 5) ✨ In Short: time → retrieves and formats time strptime / strftime → convert between strings & time calendar → helps print and analyze calendars 💬 Which one do you use most often — datetime, time, or calendar? #Python #100DaysOfCode #LearningPython #PythonProgramming #DateTime #Calendar
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development