Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
20 views
Kernel: Python 2 (SageMath)

Issue 1: Referencing the counter of a loop

This is problematic. Each time the loop is completed the variable reverts to its value as a counter.

for i in range(5): print i i = 100 print i
0 100 1 100 2 100 3 100 4 100

Issue 2: functions that do not return anything

You can create functions which do not return anything:

def nothing(x): if x == 5: return 5
nothing(5)
5
nothing(4)
print nothing(4)
None
def reverse(L): return L.reverse()
print reverse([1, 2])
None

What happened here?

L = [1, 2]
M = L.reverse() print L print M
[1, 2] None

The reverse method for lists reverses the list in-place. It does not return any value.

Lists and generators:

A binary list if length n is a list of length n, all of whose elements are 0 or 1. Recursion is a convenient method to generate a list of all such strings:

def list_of_binary_lists(n): if n == 0: return [[]] # The only binary string of length 0 is the empty string else: L = [] for s in list_of_binary_lists(n-1): L += [s + [0], s + [1]] return L
list_of_binary_lists(3)
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

We now look at a generator for such lists:

def binary_list_gen(n): if n == 0: yield [] else: for s in binary_list_gen(n-1): yield s + [0] yield s + [1]
list(binary_list_gen(4))
[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1], [0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1], [1, 0, 1, 0], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1]]
D = dict((i,0) for i in range(21)) for L in binary_list_gen(20): D[sum(L)] += 1
D
{0: 1, 1: 20, 2: 190, 3: 1140, 4: 4845, 5: 15504, 6: 38760, 7: 77520, 8: 125970, 9: 167960, 10: 184756, 11: 167960, 12: 125970, 13: 77520, 14: 38760, 15: 15504, 16: 4845, 17: 1140, 18: 190, 19: 20, 20: 1}
D = dict((i,0) for i in range(21)) for L in list_of_binary_lists(20): D[sum(L)] += 1
D
{0: 1, 1: 20, 2: 190, 3: 1140, 4: 4845, 5: 15504, 6: 38760, 7: 77520, 8: 125970, 9: 167960, 10: 184756, 11: 167960, 12: 125970, 13: 77520, 14: 38760, 15: 15504, 16: 4845, 17: 1140, 18: 190, 19: 20, 20: 1}

Generating all the square numbers

def squares_gen(): i = 1 while True: yield i^2 i += 1

Find the smallest square number that is greater than n

def smallest_square_greater_than()
2 + 2
4