Lecture Week 1 Fri 10/4

Lecture Week 1 Fri 10/4#

a = [1,2, 3]
b = a
b[0] = True
a
[True, 2, 3]
a = [1, 2, 3]

b = []
for elem in a:
    b.append(elem)

# what is b
b
[1, 2, 3]
b[0] = 0
b
[0, 2, 3]
a
[1, 2, 3]
d = {'a': 1, 3: False}
d['a']
1
d[3]
False
d[2] = 100
d
{'a': 1, 3: False, 2: 100}
c = d
c[2] = 99
c
{'a': 1, 3: False, 2: 99}
d
{'a': 1, 3: False, 2: 99}
a = [1, 2, 3]
b = [elem for elem in a]
a[0] = 100
a
[100, 2, 3]
b
[1, 2, 3]
def f(x):
    a = 1
    y = x + a
    return y

y = 1
b = f(1)
# what is y
y
1
a = 2

def myadd(x):
    b = x + a
    return b

a = 3
z = myadd(1)
# what is z
# myadd will use the a at the time of the call, not the time of the definition
# In other words, in a notebook enveironment, it depends on the order of execution the code, not the order of writing the code
z
4
def myfun(x):
    return x**2, x**3

a,b = myfun(2)
print(a)
print(b)
4
8
def gen_list(x, y = 1):
    return [x,y]

print(gen_list(1,2))
[1, 2]
print(gen_list(1))
[1, 1]
f1 = lambda x: x + 1
def f2(x):
    return x + 1
f1(1)
2
a = 2
f_add_a = lambda x: x + a
a = 3
f_add_a(1)
4
def myfun(n):
    if n == 1:
        return 1
    else:
        return n*myfun(n-1)
# how to sort by decreasing order of the absolute value of the elements
c = [5, -2, 3, -1, 4]
sorted(c, reverse=True, key = lambda x:abs(x))
[5, 4, 3, -2, -1]
c_abs = [1 if elem > 0 else -1 for elem in c]
c_abs
[1, -1, 1, -1, 1]