3.8 Iteration

Key Vocabulary

  • Iteration - Repetition of a Process
  • For Loop - repeats a function for a set number of times; I is the number of times repeated
  • While Loop - (repeat until), is used to repeat a section of code an unknown number of times until a specific condition is met
  • Initialization - What sets the counter variable to a starting value. For example (var i = 0) represents an initial value of 0.
  • Condition - Allows the computer to know whether or not to keep repeating the loop.
  • increment/decrement - Modifies the counter variable after each repetition.

Iteration Ideas

Iterative statements are also called loops, and they repeat themselves over and over until the condition for stopping is met.

i = 10
for (i > 0; i--) {
   println(i);
}
  Input In [14]
    for (i > 0; i--) {
              ^
SyntaxError: invalid syntax
for (var i = 1; i <= 10; i++) {
    for (var j = 1; j <= 10; j++) {
        println(i * j);
    }
}
  Input In [7]
    for (var i = 1; i <= 10; i++) {
             ^
SyntaxError: invalid syntax
var numRabbits = 2;
var numYears = 0;
while (numRabbits <= 100) {
    numRabbits += (numRabbits/2 * 30);
    numYears++;
}
  Input In [8]
    var numRabbits = 2;
        ^
SyntaxError: invalid syntax

3.10 Lists

Key Vocabulary

  • Indexing / List Index - The position of an element in a list, starting from 0
  • append, remove, pop - Various methods, append adds an element to the end, remove removes at an index, and pop removes the last item.
  • Elements [in a list] - An item in a list.
  • Nesting - Having one data type or function inside another data type or function, such as lists or loops.
  • array - Another name for a list, depends on the language

Lists

Methods affect variables directly. Lists mutate. To add to a list, .append .extend or .insert To remove from a list, .pop (removes last) or .remove

Adding

fruits = ["apple", "banana", "kiwi", "pomegranate"]

print(f"Fruits before append: {fruits}")

fruits.append("dragonfruit") # ADDS TO THE END OF THE LIST

print(f"Fruits after append: {fruits}")
Fruits before append: ['apple', 'banana', 'kiwi', 'pomegranate']
Fruits after append: ['apple', 'banana', 'kiwi', 'pomegranate', 'dragonfruit']
food = ["apple", "banana", "kiwi", "pomegranate"]
vegetables = ["carrot", "cucumber", "eggplant"]

print(f"Fruits before extend: {fruits}")

fruits.extend(vegetables) # adds the vegetable list to the end of the food list 

print(f"Fruits after extend: {fruits}")
Fruits before extend: ['apple', 'banana', 'kiwi', 'pomegranate', 'dragonfruit']
Fruits after extend: ['apple', 'banana', 'kiwi', 'pomegranate', 'dragonfruit', 'carrot', 'cucumber', 'eggplant']
fruits = ["apple", "banana", "kiwi", "pomegranate"]

print(f"Fruits before insert: {fruits}")

fruits.insert(1, "dragonfruit")

print(f"Fruits after insert: {fruits}")
Fruits before insert: ['apple', 'banana', 'kiwi', 'pomegranate']
Fruits after insert: ['apple', 'dragonfruit', 'banana', 'kiwi', 'pomegranate']

Removing

fruits = ["apple", "banana", "kiwi", "pomegranate"]

print(f"Fruits before pop: {fruits}")

fruits.pop()

print(f"Fruits after pop (no parameter): {fruits}")

fruits.pop(0)

print(f"Fruits after pop (specifying index 0): {fruits}")
Fruits before pop: ['apple', 'banana', 'kiwi', 'pomegranate']
Fruits after pop (no parameter): ['apple', 'banana', 'kiwi']
Fruits after pop (specifying index 0): ['banana', 'kiwi']
fruits = ["apple", "banana", "kiwi", "pomegranate"]

print(f"Fruits before remove: {fruits}")

fruits.remove("apple")

print(f"Fruits after remove (removing apple): {fruits}")

fruits.remove("kiwi")

print(f"Fruits after remove (removing kiwi): {fruits}")
Fruits before remove: ['apple', 'banana', 'kiwi', 'pomegranate']
Fruits after remove (removing apple): ['banana', 'kiwi', 'pomegranate']
Fruits after remove (removing kiwi): ['banana', 'pomegranate']

Nested List

Placing lists within lists allows you to have arrays of similar data together, and create complexity.

TwoDArray = [[1, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1]]
print(TwoDArray[0]) # print first sublist
print(TwoDArray[1]) # print second sublist
print(TwoDArray[2]) # print third sublist

# These 1s and 0s could represent anything. AMAZING DATA ABSTRACTION!
[1, 0, 1, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 1, 1]
[1, 1, 0, 0, 0, 1, 1, 1]

You can iterate over these using multiple loops. This is useful for algorithms

bin_0 = 0
bin_1 = 0
for array in TwoDArray:
    for bin in array:
        if bin == 0:
            bin_0 += 1
        elif bin == 1:
            bin_1 += 1

print(f"Num 0s: {bin_0}")
print(f"Num 1s: {bin_1}")
Num 0s: 17
Num 1s: 15

Sorting algorithms

Insertion Sort:

  1. Takes in an unsorted list with numerical elements and returns with numerical elements in order
  2. iterates through every element one at a time
  3. check if element before the selected element is greater than or less than the selected element and adjust accordingly
arr = [9,1,5,6,3,7,2,8]
print(f"array before sort {arr}")
def insertion_sort(arr):
    for index in range(1,len(arr)): # repeats through length of the array
        value = arr[index]
        i = index - 1
        while i >= 0:
            if value < arr[i]:
                arr[i+1] = arr[i] # shift number in slot i to the right
                arr[i] = value # shift value left into slot i
                i = i - 1
            else:
                break

IS = insertion_sort(arr)
print(f"array after sort {arr}")
array before sort [9, 1, 5, 6, 3, 7, 2, 8]
array after sort [1, 2, 3, 5, 6, 7, 8, 9]

Homework Hacks

Exercises

  • I learned that there is a function to actually reverse the whole list, listname.reverse
  • I also learned that you cannot print a function(list), it would not print the result and instead say None.
  • I learned that you have to iterate through a list using a for loop to swap the places of the elements in a list, and that there is no special code like .reverse to do it.

Multiple Choice Quiz

  • I keep mixing up a while loop for iterating for a set amount of time instead of until a condition is met.
  • I thought that "until a user inputs 'quit'" counted as some sort of condition to be met, so I just assumed it would be a while loop but it is a for loop.
  • There are three nested lists inside the big list. I again forgot that while loops are iterating over a certain interval until a condition is met. There are no conditions to be met in this list and loop, so they would be for loops.