Skip to content

Instantly share code, notes, and snippets.

origin ="""
S0110
01000
01010
00010
0001E
"""
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]
@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]))
# 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 / 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)
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
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))
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
@ahmed4end
ahmed4end / expand.py
Created August 10, 2020 14:58
pyqt5 expandable widget.
import sys
import inspect
import textwrap
from collections import OrderedDict, UserString
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import *
@ahmed4end
ahmed4end / feb.py
Created August 15, 2020 14:42
Fibonacci series between 0, n
feb = lambda n, t=[0, 1]: t if len(t)==n else feb(n, t+[sum(t[-2:])])
print(feb(100))