Skip to content

Instantly share code, notes, and snippets.

@Azoay

Azoay/a.py Secret

Created August 4, 2015 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Azoay/b2cc5ec6c8347ee42df4 to your computer and use it in GitHub Desktop.
Save Azoay/b2cc5ec6c8347ee42df4 to your computer and use it in GitHub Desktop.
Five programming problems every Software Engineer should be able to solve in less than 1 hour
def sum_of_for(li):
s = 0
for l in li:
s += l
return s
def sum_of_while(li):
s = 0
i = 0
while i < len(li):
s += li[i]
i += 1
return s
def sum_of_rec(li):
if len(li) == 0:
return 0
else:
e = li.pop()
return sum_of_rec(li) + e
if __name__ == '__main__':
li = [1, 2, 3, 4, 5]
print(sum_of_for(li))
print(sum_of_while(li))
print(sum_of_rec(li))
def merge(x, y):
ret = []
m = len(x) if len(x) > len(y) else len(y)
for i in range(m):
if i < len(x):
ret.append(x[i])
if i < len(y):
ret.append(y[i])
return ret
if __name__ == '__main__':
x = ['a', 'b', 'c', 'd', 'e']
y = ['1', '2', '3', '4']
print(merge(x, y))
def sum_of_fib(n=100):
fib = [0, 1]
s = 1
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
s += fib[i]
i += 1
return s
if __name__ == '__main__':
print(sum_of_fib())
from functools import cmp_to_key
def cmp(a, b):
if a == b: return 0
return -1 if a < b else 1
def mycomp(x, y):
sx = str(x)
sy = str(y)
return cmp((sx + sy) , (sy + sx))
def max_num(lst):
lst = sorted(lst, key=cmp_to_key(mycomp))
ret = ""
for i in reversed(lst):
ret += str(i)
return ret
if __name__ == '__main__':
lst = [50, 2, 1, 9]
print(max_num(lst))
import itertools
def one_hundred():
lst = range(1,10)
for calc in itertools.product('+- ', repeat=8):
s = []
for i,c in enumerate(calc):
s.append(str(lst[i]) + c)
s.append(str(lst[8]))# 9
x = ''.join(s).replace(' ' , '')
if eval(x) == 100:
print(x)
if __name__ == '__main__':
one_hundred()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment