In [16]:
def flatten(a):
if a == []:
return a
if isinstance(a[0], list):
return flatten(a[0]) + flatten(a[1:])
return [a[0]] + flatten(a[1:])
print(flatten([1, 2, 3]))
print(flatten([[[1, 2, 3], [4, 5, 6], [7], [8, 9], 10]]))
In [25]:
def identical(a, b):
for i in range(len(a)+1):
if a == b:
return True
a = a[1:]+[a[0]]
return False
print(identical([10, 10, 0, 10], [10, 10, 10, 0]))
print(identical([10, 10, 5, 10], [10, 10, 10, 0]))
In [36]:
def chunks(l, size):
result = []
pos = 0
while pos+size <= len(l):
result.append(l[pos:pos+size])
pos += size
if (pos < len(l)):
result.append(l[pos:])
return result
print(chunks([1,2,3,5,1,3,4,12,3,5,3,2,3,4,5], 6))
print(chunks([1,2,3,5,1,3,4,12,3,5,3,2], 6))
In [39]:
def sortbyfloat(a):
return sorted(a, key=lambda x: -x[1])
print(sortbyfloat([('item', 12.20), ('item2', 15.10), ('item3', 24.5)]))
In [46]:
def addbyelement(t1, t2):
return tuple([sum(t) for t in zip(t1, t2)])
print(addbyelement((1,2,3), (1,2,3)))
print(addbyelement((1,5,1), (1,-4,3)))
In [54]:
def myfun(elem):
return elem**2
def applyfunondict(a, myfun):
result = {}
for it in a:
if (isinstance(a[it], dict)):
result[it] = applyfunondict(a[it], myfun)
else:
result[it] = myfun(a[it])
return result
x = {'apple': 6, 'banana': {'hello': 5, 'world': 4}}
print(x)
print(applyfunondict(x, myfun))
In [55]:
def comparedicts(dict1, dict2):
for it in dict1:
if it not in dict2 or dict1[it] != dict2[it]:
return False
return True
print(comparedicts({'a':1, 'b':2}, {'a':1, 'b':2}))
print(comparedicts({'a':1, 'b':3}, {'a':1, 'b':2}))
In [63]:
def differences(dict1, dict2):
result = set()
for it in dict1:
if dict1[it] != dict2[it]:
result.add((it, dict1[it]))
result.add((it, dict2[it]))
return result
print(differences({'a':1, 'b':3}, {'a':1, 'b':2}))
print(differences({'a':1, 'b':3}, {'a':1, 'b':3}))
In [106]:
# sales = 2500 - 80 * price
# profit = sales * price - 8000
def profitTable(maxPrice):
print("{} {} {}".format("Price", "Income", "Profit"))
print("{} {} {}".format("-"*5, "-"*6, "-"*6))
for price in range(1, maxPrice+1):
sales = 2500 - 80 * price
income = sales * price
print(" £ {:<3} {:<5} {:<5}".format(price, income, income-8000))
profitTable(30)
In [113]:
# sales = 2500 - 80 * price
# profit = sales * price - 8000
def profitTable_50(maxPrice):
print("{} {} {}".format("Price", "Income", "Profit"))
print("{} {} {}".format("-"*5, "-"*6, "-"*6))
for price in [x/2.0 for x in range(1, (maxPrice)*2+1)]:
sales = 2500 - 80 * price
income = sales * price
print("£ {:<5} {:<7} {:<7}".format(price, income, income-8000))
profitTable_50(30)
In [122]:
import matplotlib.pyplot as plt
def profitList(maxPrice):
result = [], []
for price in [x/2.0 for x in range(1, (maxPrice)*2+1)]:
sales = 2500 - 80 * price
income = sales * price
result[0].append(price)
result[1].append(income-8000)
return result
lists = profitList(30)
plt.plot(lists[0], lists[1])
plt.ylabel('Profit')
plt.xlabel('Price')
plt.show()
In [ ]: