3.8 - 3.10 hacks and notes
for week 3
- notes
- Exercise 1
- Exercise 2
- Quiz reflection
- 4) How can we add something to the end of a list?
- 8) What does a WHILE loop do?
- 9) I want to iterate over a list until the user inputs 'quit'. What loop would I use?
notes
iteration is when something is repeated. usually done using loops. REPEAT N TIMES is pseudocode for this.
LISTS: collection of data in a sequence that can be iterated through.
EX: fruits = ["apple", "banana", "kiwi", "pomegranate"]
LISTS ARE MUTABLE. you can add and remove items from a list.
Nested Lists: you can store lists inside lists for more complex data. can create sublists with this.
can iterate through sublists in list and then iterate through values in those sublists.
Exercise 1
list = [1, 2, 3, 4, 5] # Print this list in reverse order
#list.reverse() also works
for i in range(len(list)):
print(i + 1)
a = list.pop() # pop element at the end of list
list.insert(i, a) # add new element with index val of last popped element
print(list)
list = [9, 8, 4, 3, 5, 2, 6, 7, 1, 0] # Sort this array using bubble sort
for i in list:
for a in range(len(list) - 1): # for loops look at the first element and the element next to it
if list[a] > list[a + 1]: # if the 1st element is larger than the 2nd one + 1
list[a], list[a + 1] = list[a + 1], list[a] # position of 2 elements are swapped so larger element is in front
# lesser element is in back
# list.sort() also works :/
print(list)
Quiz reflection
4) How can we add something to the end of a list?
(a) Use + sign
(b) The word Add
(c) Append
(d) Extend
ANS: Append
I picked extend and got the problem wrong because I mixed up the definition of extend with append. extend is for lists and append is for individual elements.
8) What does a WHILE loop do?
(a) Iterates over an iterable and for a set amount of time
(b) Intuitively takes an iterable and manipulates it over a set period using pointers
(c) Loop over a bound interval by comparing to a conditional
(d) Crash bitcoin
ANS: (C) I got this one wrong because I picked A initially. I forgot that the set amount of time part must be added in. C is the technical definition. A is how WHile loops work.
9) I want to iterate over a list until the user inputs 'quit'. What loop would I use?
(a) WHILE loops
(b) FOR loops
(c) Recursive Loops
(d) Paradoxical Loops
ANS: B, but I picked A because I was thinking of a while loop and a for loop. I understand why a for loop would be used.