@pythonista
that fibonacci one-liner blew my mind! 🤯
// where python gets weird & wonderful
# Generate fibonacci sequence in one line
fib = lambda n: [0, 1] if n <= 2 else [*fib(n-1), fib(n-1)[-1] + fib(n-1)[-2]]
print(fib(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
from PIL import Image
import numpy as np
def img_to_ascii(image_path, width=80):
chars = "@%#*+=-:. "
img = Image.open(image_path).convert('L')
img = img.resize((width, int(width * img.height / img.width * 0.55)))
pixels = np.array(img)
ascii_art = ""
for row in pixels:
ascii_art += "".join([chars[pixel//32] for pixel in row]) + "\n"
return ascii_art
print(img_to_ascii("photo.jpg"))
import secrets
import string
def generate_password(length=16, include_symbols=True):
alphabet = string.ascii_letters + string.digits
if include_symbols:
alphabet += "!@#$%^&*"
password = ''.join(secrets.choice(alphabet) for _ in range(length))
return password
# Generate a secure 20-character password
secure_pwd = generate_password(20)
print(f"Your password: {secure_pwd}")
from sklearn.cluster import KMeans
from PIL import Image
import numpy as np
def extract_colors(image_path, num_colors=5):
img = Image.open(image_path)
img = img.resize((150, 150))
img_array = np.array(img)
# Reshape to 2D array
pixels = img_array.reshape(-1, 3)
# Apply K-means clustering
kmeans = KMeans(n_clusters=num_colors, random_state=42)
kmeans.fit(pixels)
colors = kmeans.cluster_centers_.astype(int)
return [f"#{r:02x}{g:02x}{b:02x}" for r, g, b in colors]
palette = extract_colors("sunset.jpg")
print(f"Color palette: {palette}")
def text_to_morse(text):
morse_dict = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..', ' ': '/'
}
return ' '.join(morse_dict.get(char.upper(), '') for char in text)
message = "HELLO WORLD"
morse = text_to_morse(message)
print(f"{message} → {morse}")
import hashlib
import os
from collections import defaultdict
def find_duplicates(directory):
file_hashes = defaultdict(list)
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
try:
with open(file_path, 'rb') as f:
file_hash = hashlib.md5(f.read()).hexdigest()
file_hashes[file_hash].append(file_path)
except:
continue
duplicates = {hash_val: paths for hash_val, paths in file_hashes.items() if len(paths) > 1}
return duplicates
dupes = find_duplicates("/path/to/folder")
for hash_val, files in dupes.items():
print(f"Duplicates: {files}")
def sieve_of_eratosthenes(limit):
"""Generate all primes up to limit using the Sieve of Eratosthenes"""
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(limit**0.5) + 1):
if is_prime[i]:
for j in range(i*i, limit + 1, i):
is_prime[j] = False
return [i for i in range(2, limit + 1) if is_prime[i]]
# Generate all primes up to 100
primes = sieve_of_eratosthenes(100)
print(f"Primes up to 100: {primes[:10]}...") # First 10 primes
import random
def rock_paper_scissors():
choices = ['rock', 'paper', 'scissors']
player = input("Enter your choice (rock/paper/scissors): ").lower()
computer = random.choice(choices)
print(f"You chose: {player}")
print(f"Computer chose: {computer}")
if player == computer:
return "It's a tie! 🤝"
elif (player == 'rock' and computer == 'scissors') or \
(player == 'paper' and computer == 'rock') or \
(player == 'scissors' and computer == 'paper'):
return "You win! 🎉"
else:
return "Computer wins! 🤖"
# Play the game
result = rock_paper_scissors()
print(result)
import qrcode
from PIL import Image
def create_qr_code(data, filename="qr_code.png"):
# Create QR code instance
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add data and generate QR code
qr.add_data(data)
qr.make(fit=True)
# Create image
img = qr.make_image(fill_color="black", back_color="white")
img.save(filename)
print(f"QR code saved as {filename}")
return img
# Generate QR code for a URL
url = "https://coolcode.dev"
create_qr_code(url, "coolcode_qr.png")
import pandas as pd
import numpy as np
def analyze_csv(file_path):
df = pd.read_csv(file_path)
analysis = {
'shape': df.shape,
'columns': list(df.columns),
'data_types': df.dtypes.to_dict(),
'missing_values': df.isnull().sum().to_dict(),
'numeric_summary': df.describe().to_dict()
}
# Find correlations for numeric columns
numeric_cols = df.select_dtypes(include=[np.number]).columns
if len(numeric_cols) > 1:
analysis['correlations'] = df[numeric_cols].corr().to_dict()
return analysis
# Analyze your data
data_insights = analyze_csv("sales_data.csv")
print(f"Dataset shape: {data_insights['shape']}")
print(f"Missing values: {data_insights['missing_values']}")
from collections import Counter
def are_anagrams(word1, word2):
"""Check if two words are anagrams of each other"""
# Remove spaces and convert to lowercase
word1 = word1.replace(" ", "").lower()
word2 = word2.replace(" ", "").lower()
# Compare character counts
return Counter(word1) == Counter(word2)
def find_anagrams(word, word_list):
"""Find all anagrams of a word in a given list"""
return [w for w in word_list if are_anagrams(word, w) and w.lower() != word.lower()]
# Test anagram detection
words = ["listen", "silent", "evil", "vile", "a gentleman", "elegant man"]
target = "listen"
anagrams = find_anagrams(target, words)
print(f"Anagrams of '{target}': {anagrams}")
print(f"'listen' and 'silent': {are_anagrams('listen', 'silent')}")
import requests
import json
def get_weather(city, api_key):
"""Fetch current weather data for a city"""
url = f"http://api.openweathermap.org/data/2.5/weather"
params = {
'q': city,
'appid': api_key,
'units': 'metric'
}
try:
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
weather_info = {
'city': data['name'],
'country': data['sys']['country'],
'temperature': data['main']['temp'],
'feels_like': data['main']['feels_like'],
'description': data['weather'][0]['description'],
'humidity': data['main']['humidity'],
'wind_speed': data['wind']['speed']
}
return weather_info
except requests.RequestException as e:
return f"Error fetching weather data: {e}"
# Get weather (requires API key from openweathermap.org)
# weather = get_weather("London", "your_api_key_here")
# print(f"Weather in {weather['city']}: {weather['temperature']}°C")
hey there! 👋 i'm chris, a caffeine-powered code enthusiast who believes that programming should be fun, weird, and occasionally make you go "wait, that actually works?!"
when i'm not wrestling with semicolons, you can find me collecting vintage keyboards, explaining to my rubber duck why my code doesn't work, or making coffee that's probably too strong.
leave a note, share a joke, or just say hi!