Skip to content

Instantly share code, notes, and snippets.

@hanks
Last active August 29, 2015 14:21
Show Gist options
  • Save hanks/c40782e67526f3f6dd39 to your computer and use it in GitHub Desktop.
Save hanks/c40782e67526f3f6dd39 to your computer and use it in GitHub Desktop.
# 1.py
# coding: utf-8
def sum1(a):
sum = 0
for i in a:
sum += i
return sum
def sum2(a):
sum = 0
i = 0
while i < len(a):
sum += a[i]
i += 1
return sum
sum = 0
def sum3(a, step):
global sum
if step >= len(a):
return sum
sum += a[step]
sum3(a, step + 1)
if __name__ == '__main__':
a = range(5)
print sum1(a)
print sum2(a)
sum3(a, 0)
print sum
# 2.py
def chainIt(a, b):
result = []
i = 0
j = 0
while i < len(a) and j < len(b):
result.append(a[i])
result.append(b[j])
i += 1
j += 1
if i < len(a):
result.extend(a[i:])
if j < len(b):
result.extend(b[j:])
return result
if __name__ == '__main__':
a = ['a', 'b', 'c']
b = [1, 2, 3]
print chainIt(a, b)
a = ['a', 'b']
b = [1, 2 ,3]
print chainIt(a, b)
# 3.py
def fab(n):
a = 0
b = 1
if n == 1:
print a
if n == 2:
print b
print a
print b
for i in range(3, n + 1):
b = a + b
a = b - a
print b
if __name__ == '__main__':
fab(10)
# 4.py
def max_number(a):
b = [str(i) for i in a]
str_list = sorted(b, reverse=True)
num_str = ''.join(str_list)
return int(num_str)
if __name__ == '__main__':
a = [50, 2, 1, 9]
print max_number(a)
# 5.py
def count(str, pos):
if str.find('9') < pos - 1:
return
if eval(str) == 100:
print str
return
str = str[:pos] + '+' + str[pos:]
count(str, pos + 2)
str = str[:pos] + str[pos+1:]
str = str[:pos] + '-' + str[pos:]
count(str, pos + 2)
str = str[:pos] + str[pos+1:]
count(str, pos + 1)
if __name__ == '__main__':
s = '123456789'
count(s, 1)
@hanks
Copy link
Author

hanks commented May 13, 2015

solved these in 45 mins, Q4 is a little tricky, Q5 is just normal backtrace one that I spent 20mins...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment