CS1010S Tutorial 6 PDF
CS1010S Tutorial 6 PDF
CS1010S Tutorial 6 PDF
for i, j in seq:
print(i, j)
12
34
56
Q1
at_least_n which takes in a list of integers and an integer n, and returns the
original list with all the integers smaller than n removed.
>>> lst2
[5 , 6 , 7 , 8 , 9 ]
True
Q1
(c) Write a function transpose which takes in a matrix and transposes it.
Basically, this converts an m × n matrix into an n × m matrix.
Q2
(c) Write a function transpose which takes in a matrix and transposes it.
Basically, this converts an m × n matrix into an n × m matrix.
def transpose(m): def transpose(m):
for i in range(len(m)):
for j in range(len(m[i])):
if len(result) <= j:
result.append([m[i][j]]);
else:
result[j].append(m[i][j])
return result
Q3
- Insertion Sort
- Selection Sort
- Bubble Sort
- Merge Sort
Q4
Q4
def mode_score(students):
# get all scores
scores = list(map(lambda x:x[2], students))
# get the maximum frequency
max_fq = max(map(lambda score: scores.count(score), scores))
# get the scores with the maximum frequncy
mode = list(filter(lambda score: scores.count(score) == max_fq, scores))
# sort them, and retrive each score only once by jumping max_fq at a time
return sorted(mode)[::max_fq]
Q4
Q4
a = [1,2,3]
b = (1,2,3, a, 4, 5)
print(b)
a.clear()
print(b)
a = [1]
print(b)
Extra Question
a = [1, 2]
a += [a]
b = a.copy()
a[2] = 0
print(a)
print(b)
Extra Question
a = [1, 2]
a += [a]
[1, 2, […]]
if Python is printing a list and discovers that the list is on the stack, that must mean that this
is a self-referential list, and the list should be abbreviated, to avoid an infinite loop.
b = a.copy()
The difference between shallow and deep copying is only relevant for compound objects
(objects that contain other objects, like lists or class instances): A shallow copy constructs a
new compound object and then (to the extent possible) inserts references into it to the
objects found in the original. i.e. print(b) == [1, 2, a]
a[2] = 0
print(a)
print(b)