Skip to content

Instantly share code, notes, and snippets.

@ahmed4end
ahmed4end / powersOfTwo.py
Created August 19, 2020 15:22
fint powers of two less than n.
n = 50
prev = lambda n: [i for i,j in enumerate(bin(n)[:1:-1]) if int(j)][::-1][0]
powers = lambda x, t=[]: t+[1] if prev(x)==1 else powers(2**prev(x) - 1, t+[prev(x)])
print(powers(n))
@ahmed4end
ahmed4end / Josephus.py
Last active August 19, 2020 15:38
Josephus problem solution in python (simple one).
joseph = lambda x: (lambda j: 1 if x == j else 2*(x-j)+1)(2**[i for i,j in enumerate(bin(x)[:1:-1]) if int(j)][::-1][0])
print(joseph(10))
@ahmed4end
ahmed4end / Primes.py
Created August 27, 2020 22:02
lazy way to find prime numbers
def inf(n):
yield n
yield from inf(n+1)
def prime(s):
n = next(s)
yield n
yield from prime(i for i in s if i%n!=0)
@ahmed4end
ahmed4end / weighted choices.py
Created September 9, 2020 19:16
weighted choices
from random import random
from bisect import bisect
def weighted_choice(choices):
values, weights = zip(*choices)
total = 0
cum_weights = []
for w in weights:
total += w
cum_weights.append(total)
@ahmed4end
ahmed4end / QPushButton.py
Last active October 29, 2023 06:50
pyqt5 QPushButton animation example.
from PyQt5 import QtWidgets, QtGui, QtCore
from colour import Color # pip install colour
class Main(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet("QPushButton{height: 30px;width: 200px;}")
layout = QtWidgets.QHBoxLayout()
@ahmed4end
ahmed4end / squircle.py
Created October 3, 2020 02:55
make squircles using pillow ♥
import sys
from PIL import Image
import numpy as np
import math
def squircle(size=(50,50), color="black", level=4):
i = Image.new(mode = 'RGBA', size=size , color=color )
l = level
w, h = i.size
# Python - How to check for a valid sudoku.
sudoku = [[8, 7, 5, 6, 2, 1, 9, 3, 4],
[6, 9, 4, 5, 3, 7, 2, 1, 8],
[1, 2, 3, 8, 4, 9, 7, 5, 6],
[4, 5, 1, 9, 7, 3, 6, 8, 2],
[3, 6, 7, 1, 8, 2, 5, 4, 9],
[2, 8, 9, 4, 5, 6, 1, 7, 3],
[5, 3, 6, 7, 9, 8, 4, 2, 1],
#Python - Fibonacci sequence (Lazy solution).
def feb(first=0, second=1):
Next = first+second
yield Next
yield from feb(first=second, second=Next)
obj = feb()
for i in range(25):
#Sol 1 - performance: Exp
vowels = { 'A': 1, 'E': 21, 'I': 7, 'O': 8, 'U': 5, 'T':4 }
result = []
def backtrack(trac=[], totalWeight=10, vowelsRepeatLimit={'A':5}):
'''
:params:
:totalWeight: total weight target.
import random, re, pyautogui, time, pyperclip , sys
chat = pyperclip.paste()
chatNames = re.findall(r'(?<=[PM|AM]\r\n).*(?=\r\n)', chat)
chatNames = set(chatNames)-{'Shadow'}
print(chatNames)