Starting from:

$29

ECE-203 Laboratory Experiment Week 6

ECE-203 Programming for Engineers
Laboratory Experiment Week 6
Name:
Lab Assignments (Due end of this lab session)
(20 Points) The following code produces the first 10 integers in the Fibonacci sequence:
1 a = b = 1
2 fib_numbers = [a]
3 a,b = b, a + b
4 fib_numbers.append(a)
5 a,b = b, a + b
6 fib_numbers.append(a)
7 a,b = b, a + b
8 fib_numbers.append(a)
9 a,b = b, a + b
10 fib_numbers.append(a)
11 a,b = b, a + b
12 fib_numbers.append(a)
13 a,b = b, a + b
14 fib_numbers.append(a)
15 a,b = b, a + b
16 fib_numbers.append(a)
17 a,b = b, a + b
18 fib_numbers.append(a)
19 a,b = b, a + b
20 fib_numbers.append(a)
21
22 print fib_numbers
Output:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Write a generator called Fib that produces Fibonacci numbers. Your generator should accept
a parameter named end that specifies how many numbers will be produced before throwing a
StopIteration exception.
Use your generator with a for-loop to print the first 20 numbers in the Fibonacci sequence to the
screen. For example:
for i in Fib(20):
print i
TA Initials
1
(20 Points) In class we discussed list comprehensions, which take the form of:
new_list = [expression for name in list]
where name can be used in expression. It is also possible for expression to be another list
comprehension!
Nesting two list comprehensions in this way results in the following form:
new_list = [[expression for name2 in list2] for name1 in list1]
where both name1 and name2 can be used in expression.
Write a nested list comprehension that transposes the following “matrix” A:
(Note: A is really just a list of lists).
A = [[10, 20, 30, 40, 50, 60],
[11, 21, 31, 41, 51, 61],
[12, 22, 32, 42, 52, 62],
[13, 23, 33, 43, 53, 63],
[14, 24, 34, 44, 54, 64],
[15, 25, 35, 45, 55, 65],
[16, 26, 36, 46, 56, 66]]
Here is a hint to get you started. The form of your list comprehension should look like this:
transpose = [[??????????????????] for i,_ in enumerate(A[0])]
Start by asking yourself, ”What is i and how could it be useful?” Next, think about what the
contents of each row of the resulting transposed matrix should be.
TA Initials
2

More products