Looping with lists: adding up the numbers in a list of numbers:
def listsum(L):
total = 0
for i in range(len(L)):
total += L[i]
return total
# By the way, there is already a built-in function in Python called "sum()",
# and sum(L) will return the sum of the numbers in a list L
Looping with lists: Creating a list, element by element:
# Create a list with many copies of a given number
def dups(this_number, this_many_times):
answer = []
for i in range(this_many_times):
answer += [this_number]
return answer
# By the way, Python can create a list of duplicates this way as well:
# [this_number]*this_many_times
CodingBat Exercises:
Do the following problems from the
CodingBat section
"List related problems"...
In these exercises do all of your looping using "while" and not "for"
The Fibonacci Sequence:
The sequence usually starts at at 1: 1 1 2 3
5 8 ... etc. but we can also start it at 0: 0
1 1 2 3 5 8.
So let's define the function fib(n) such that
fib(0) = 0, and fib(1) = 1, and
fib(2) = 1, and fib(3) = 2, etc.
The Collatz Conjecture in mathematics (see video) uses the "Hailstone
Sequence" of numbers, which is explained in the video.
Start with a positive whole number as a "seed" and then generate the
next number according to the following rule, if the number is even, divide it by
2, and if it's odd, multiply it by 3 and add 1. Then go until you get to
1.
Suppose the "seed" or starting number is 5, then the sequence, as a list would
be [5, 16, 8, 4, 2, 1], and its length would be 6.
If the seed is 7, then the sequence would be [7, 22, 11, 34, 17, 52, 26, 13, 40,
20, 10, 5, 16, 8, 4, 2 ,1] and its length would be 17.