Skip to content

Instantly share code, notes, and snippets.

def text_wrap(text, font, max_width):
"""Wrap text base on specified width.
This is to enable text of width more than the image width to be display
nicely.
@params:
text: str
text to wrap
font: obj
font of the text
arr = [[-1,1,-7,-8],[-10,-8,-5,-2],[0,9,7,-1],[4,4,-2,1]]
print((lambda n: (lambda x1, x2, y: abs(sum([x1[i] for i in range(0, len(x1), y+1)])- sum([x2[i] for i in range(0, len(x2), y+1)])))(x1=[j for i in n for j in i], x2=[j for i in n for j in i[::-1]], y=len(n[0])))(arr))
from contextlib import contextmanager
from timeit import default_timer
import time
@contextmanager
def elapsed_timer():
start = default_timer()
elapser = lambda: default_timer() - start
yield lambda: elapser()
end = default_timer()
elapser = lambda: end-start
@ahmed4end
ahmed4end / regex.py
Created July 5, 2020 20:09
how to replace multiple characters and words in a string using regex.
#python - how to replace multiple characters and words in a string using regex.
import re
text = "hello ,world!"
replaces = {"hello": "hi", "world":" 2020", "!":"."}
regex = re.sub("|".join(replaces.keys()), lambda match: replaces[match.string[match.start():match.end()]], text)
print(regex)
# one-liner
primes = lambda n: [i for i in range(2, n) if not ["" for j in range(2, i) if i%j==0]]
print(primes(55))
# the previous one-liner code after unpacking .
def primes(n):
all_primes = []
for i in range(2, n):
@ahmed4end
ahmed4end / change.py
Last active May 9, 2021 10:57
return money amount in change .
change = lambda t, r=[], coins={5,3,2,1}: r if t==0 else change(*(lambda g: (t-g, r+[g]))(t-min(t-i for i in coins-{sum(r)+t} if t-i>=0)))
print(change(999))
#better attempt
change = lambda x,y=[]: y if x<=0 else change(*(lambda series: (x-[i for i in series if x>=i][0], y+[[i for i in series if x>=i][0]]))([200, 100, 50, 20, 10, 5, 1]))
#with roman encode method
solution = lambda x,y="": y if x<=0 else solution(*(lambda series: (x-[i for i in series if x>=i][0], y+{1000:"M", 500:"D", 100:"C", 50:"L", 10:"X", 5:"V", 1:"I"}[[i for i in series if x>=i][0]]))([1000, 500, 100, 50, 10, 5, 1]))
def sum_of_squares(n, f=1):
if n<0:return None
if n==0:return []
start = n-1 if f else n
for j in range(start,0,-1):
if j**0.5 == int(j**0.5):
hold = sum_of_squares(n-j, f=0)
if hold !=None:return hold + [j]
origin ="""
S0110
01000
01010
00010
0001E
"""
@ahmed4end
ahmed4end / decompose.py
Created March 15, 2020 02:56
Square into Squares. Protect trees!
def decompose(n):
def rec(n, i):
if n<0:return None
if n==0:return []
for j in range(i-1,0,-1):
hold = rec(n-j**2, j)
if hold!=None:return hold+[j]
return rec(n**2, n)
print(decompose(11))
def spiralNumbers(n):
m = [[0]*n for _ in range(n)]
dx, dy = [0,1,0,-1], [1,0,-1,0]
x, y, c = 0,-1,1
for i in range(2*n-1):
for j in range((2*n-i)//2):
x += dx[i%4]
y += dy[i%4]
m[x][y] = c
c+=1