Vocabulary

  • Iteration - Repitition of a Process
  • For Loop - FOR LOOP repeats a function for a set number of times; I is the number of times repeated
  • While Loop - The while loop 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.
  • 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
  • Key - the unique identifier associated with a value in a dictionary, such as name
  • Value - the data associated with a key in a dictionary, such as age
  • Pair - a key-value combination in a dictionary, such as a person's name + age
  • Mutable - the ability to be changed or modified
  • Tuple - an immutable ordered sequence of elements, similar to a list
  • Insertion - the process of adding a new key-value pair to a dictionary
  • Deletion - the process of removing a key-value pair from a dictionary
  • Keys method/keys() - a built-in Python function that returns a list of all keys in a dictionary
  • Values method/values() - a built-in Python function that returns a list of all values in a dictionary
  • Items method/items() - a built-in Python function that returns a list of all key-value pairs in a dictionary as tuples
  • Update method/update() - a built-in Python function that updates a dictionary with key-value pairs from another dictionary or iterable
  • Clear method/clear() - a built-in Python function that removes all key-value pairs from a dictionary

Questions:

  1. Give an example of iteration.

One example of iteration is binary search, as the program has to go through/iterate through a list in order to find a target value. The maximum number of times or guesses it takes to find the number in the list is 2^n. For example, if an element had 82 elements, it would take a maximum of 2^7 (128) times to find the number, since 2^6 (64) would not be enough.

  1. What is the difference between a for loop and while loop? That is, when would you use a for loop and when would you use a while loop?

A for loop repeats a fixed number of times while a while loop repeats as many times as is necessary until a condition is met. You would you use a for loop if you want the program to iterate through a list the same number of times as there are elements. You would use a while loop if you want the program to keep going while a certain condition is true.

  1. In the APCSP AP exam, what number do indexes start with? important to know

In the APCSP exam, the indexes start with the number 1, which literally makes zero sense dsajkghfyskfyaedfgaidvdciyadgfiyasvblf.

  1. Are dictionaries and lists mutable?

Yes, lists and dictionaries are mutable. With dictionaries, you can add, modify, or even remove key-value pairs even after they have been created.

Simulations/Interactions

Building a simulation o#r interaction using lists and iteration in VS Code can be accomplished using a few simple steps:

  1. Define your data: First, you need to define the data that your simulation will be working with. This could be a list of numbers, a list of strings, or any other type of data that your simulation will be manipulating.

  2. Write your simulation code: Once you have defined your data, you can start writing the code for your simulation. This code will typically involve iterating over your list of data, performing some operation on each item in the list, and updating the list accordingly.

  3. Test your simulation: After you have written your simulation code, it is important to test it to make sure it is working as expected. You can do this by running your code and checking the output to see if it matches what you expect.

  4. Refine your simulation: Once you have tested your simulation, you may need to refine it based on the results. This could involve tweaking the code to make it more efficient, adding new features, or fixing any bugs that you have discovered.

Why use simulations?

  • Simulations can be useful because they can emulate real world situations without needing excessive resources (ex: money), time, or equipment. For example, a simulation of the effectiveness of a new seatbelt or airbag can be performed by simulating car crashes. This would be better than doing it in real life because you wouldn't want to place people in cars and then crash them for obvious reasons.
  • However, simulatins do assume things about the real world and can have biases. They can be oversimplified because the real world often has more complications and factors that can affect something. In the case of our car crash simulation, other things can have a big impact, such as the weather and experience of the driver. However, these things can sometimes be held constant in the simulations.

Questions:

  1. Explain an example of something you could simulate

One thing that I could simulate is an airplane flying from one airport to another using a variety of flight simulators that are available. I can change different variables such as the weather to see how an airplane would respond as it makes the route to its destination.

  1. Why are simulations useful and important?

Simulations are useful and important because they are very cost-efficient, meaning that we don't have to spend as much money on simulations as we do if we want to test something in real life. Additionally, simulations provide us with a realistic view of the real world and can be used to help make important decisions.

Here's a simple example of a simulation in Python that uses lists and iteration to calculate the average of a list of numbers:

numbers = [1, 2, 3, 4, 5]

# Initialize the sum and count variables
sum = 0
count = 0

# Iterate over the list of numbers, adding each number to the sum
for number in numbers:
    sum += number
    count += 1

# Calculate the average of the list of numbers
average = sum / count

# Print the average
print("The average of the list is:", average)
The average of the list is: 3.0

This code defines a list of numbers, iterates over the list to calculate the sum and count of the numbers, and then calculates the average by dividing the sum by the count. Finally, it prints the average to the console.

Lists

  • Iteration statements can be used to traverse a list
  • Knowldege of exisiting algorithms that use iteration can help in constructing new algorithms. Some are:
    • Determining a minimum or maximum value in a list
    • Computing a sum or average of a list of numbers

What are Lists?

  • Lists are a collection of multiple elements.
  • Each sequence is demarcated with an index, starting from 0. This is known as base 0 indexing
  • In memory, it is stored as a variable name with multiple pointers to each variable stored in a certain order
  • Lists can also be called arrays
  • Lists have methods that act upon the list and change them. This moves the pointers within RAM to change the parts of the list.

Nested Lists

Uses of Nested lists

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

Some uses include:

  • Creating 2d Arrays
  • Storing similar, but slightly different categories (sublists)
  • Create a matrix

Iteration

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

  • In College Board's Pseudocode, the first is a REPEAT n TIMES loop, where the n represents some number.

The second type of loop is a REPEAT UNTIL (condition) loop, where the loop will continue to run until a condition is met.

Conceptually, a while loop is very similar to an if conditional, except that a while is continually executed until it's no longer true and an if is only executed once.

Questions:

  1. Describe a situation where you would need iteration.

One situation where you would need iteration is binary search, as it requires one to iterate through a sorted list of elements in order to find the target value.

  1. Describe the difference between a "REPEAT n TIMES" loop VS a "REPEAT UNTIL (condition)" loop. it is important you know this for the AP Exam

REPEAT n TIMES describes a loop that is supposed to repeat itself a fixed and already predetermined number of times, while a REPEAT UNTIL (condition) loop describes a loop that needs to repeat itself as many times as necessary until the condition for stopping is met (it is not already predetermined)

Libaries

  • A software library contains procedures that may be used in creating new programs.
  • Existing code segments can come from internal or external sources, such as libaries or previously written code.
  • The use of libaries simplifies the task of creating complex programs.

APIs

Application program interfaces (APIs) are specifications for how the procedures in a libary behave and can be used as documentation for an API/libary is necessary in understanding the behaviors provided by the API and how to use them.

A file that contains procedures that can be used in a program is considered a libary.

  • API provides specifications for how procedures in a library behave and can be used.
  • Many companies use APIs for programmers to interact with their products.

Questions:

  1. What are some libraries that we've learned about? What are their advantages/disadvantages?

Some libraries that we have learned about include pandas, numpy, math, turtle, and many more. Some of their advantages are that we can use commands associated with that library, and some of their disadvantages include the fact that they can only do so much.

Dictionaries

What are Dictionaries?

  • an unordered collection of key-value pairs, where each key is assigned and associated with a specific value
  • known as associative arrays, maps, or hash tables in some programming languages
  • used to store and retrieve data efficiently, as they allow fast access to values based on their associated keys
  • useful for a wide range of tasks, such as storing, indexing, and counting

What are the types of Dictionaries?

Ordered Dictionaries

  • Iterates over keys and values in the same order that the keys were inserted
  • If an entry is deleted and reinserted, then it will be moved to the end of the dictionary
  • Specially designed to keep its items ordered
  • Useful in situations where the order of insertion is important and when you need to process data in a specific order
  • If the order of the data is important, an ordered dictionary is the better choice

How to create an ordered dictionary?

  1. Import OrderedDict from collections
  2. Create an empty ordered dictionary by instantiating OrderedDict without providing arguments to the constructor
  3. Add key-value pairs to the dictionary by providing a key in square brackets ([]) and assigning a value to that key.
  4. Print the ordered dictionary
  5. Iterate over the items in the ordered dictionary

Regular Dictionaries

  • Mutable; can add, remove, and modify key-value pairs after they have been created
  • Used to store data values in key:value pairs
  • Can be iterated over using loops
  • If order is not important, a regular dictionary may provide better performance

How to create a regular dictionary?

  1. Create a variable name which will be the name of the dictionary
  2. Assign the variable to an empty set of curly braces {}
  3. Create a dictionary with the dict() OR empty curly brackets

Questions:

  1. Compare and contrast lists and dictionaries.

Dictionaries have keys that are assigned to specific values while lists do not.

  1. Do dictionary keys need to be unique?

Yes, dictionary keys need to be unique.

folklore_album = {
    "title": "Folklore",
    "artist": "Taylor Swift",
    "year": 2020,
    "genre": ["Alternative/Indie", "Pop"],
    "tracks": {
        1: ["the 1", 7],
        2: ["cardigan", 9],
        3: ["the last great american dynasty", 7],
        4: ["exile (ft. Bon Iver)", 10],
        5: ["my tears ricochet", 7],
        6: ["mirrorball", 6],
        7: ["seven", 5],
        8: ["august", 7],
        9: ["this is me trying", 7],
        10: ["illicit affairs", 8],
        11: ["invisible string", 6],
        12: ["mad woman", 7],
        13: ["epiphany", 6],
        14: ["betty", 8],
        15: ["peace", 9],
        16: ["hoax", 7],
        17: ["the lakes", 6]
    }
}

# Printing the dictionary
print(folklore_album)
{'title': 'Folklore', 'artist': 'Taylor Swift', 'year': 2020, 'genre': ['Alternative/Indie', 'Pop'], 'tracks': {1: ['the 1', 7], 2: ['cardigan', 19], 3: ['the last great american dynasty', 7], 4: ['exile (ft. Bon Iver)', 10], 5: ['my tears ricochet', 7], 6: ['mirrorball', 6], 7: ['seven', 5], 8: ['august', 7], 9: ['this is me trying', 7], 10: ['illicit affairs', 8], 11: ['invisible string', 6], 12: ['mad woman', 7], 13: ['epiphany', 6], 14: ['betty', 8], 15: ['peace', 9], 16: ['hoax', 7], 17: ['the lakes', 6]}}
for i in folklore_album["tracks"]:
    print("track #" + str(i) + ": " + folklore_album["tracks"][i][0])
    print("    my rating: " + str(folklore_album["tracks"][i][1]) + "/10")
track #1: the 1
    my rating: 7/10
track #2: cardigan
    my rating: 19/10
track #3: the last great american dynasty
    my rating: 7/10
track #4: exile (ft. Bon Iver)
    my rating: 10/10
track #5: my tears ricochet
    my rating: 7/10
track #6: mirrorball
    my rating: 6/10
track #7: seven
    my rating: 5/10
track #8: august
    my rating: 7/10
track #9: this is me trying
    my rating: 7/10
track #10: illicit affairs
    my rating: 8/10
track #11: invisible string
    my rating: 6/10
track #12: mad woman
    my rating: 7/10
track #13: epiphany
    my rating: 6/10
track #14: betty
    my rating: 8/10
track #15: peace
    my rating: 9/10
track #16: hoax
    my rating: 7/10
track #17: the lakes
    my rating: 6/10

Code Examples

Reverse a list utilizing features of lists and iteration

original_list = [1, 2, 3, 4, 5]
print("List before reverse : ",original_list)
reversed_list = []
for value in original_list:
  reversed_list = [value] + reversed_list
# print("List after reverse : ", reversed_list)
List before reverse :  [1, 2, 3, 4, 5]

Similar to insertion sort, this algorithm takes an unsorted array and returns a sorted array. Unlike insertion sort where you iterate through the each element and move the smaller elements to the front, this algorithm starts at the beginning and swaps the position of every element in the array

list = [9, 8, 4, 3, 5, 2, 6, 7, 1, 0]
print(f"array before sort {list}")
def insertion_sort(list):
    for index in range(1,len(list)): # repeats through length of the array
        value = list[index]
        i = index - 1
        while i >= 0:
            if value < list[i]:
                list[i+1] = list[i] # shift number in slot i to the right
                list[i] = value # shift value left into slot i
                i = i - 1
            else:
                break

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

Here is a list comprehension example, using lists to create lists.

Below, only songs in the folklore album that have less than 7 characters in their titles are printed.

TS_folklore = ["exile", "my tears ricochet", "this is me trying", "illicit affairs", "august", "mirrorball", "betty", "mad woman", "epiphany", "peace", "cardigan"]

# this list is only songs that have less than 10 characters in the title
TS_folklore_updated = [x for x in TS_folklore if len(x) < 7]

print("These are the songs in Taylor Swift's folklore album that have less than 7 characters in their title")
print(TS_folklore_updated)
These are the songs in Taylor Swift's folklore album that have less than 7 characters in their title
['exile', 'august', 'betty', 'peace']

Below, only songs that have a rating greater than 7 will be printed.

TS_folklore_ratings = {"exile": 8, "my tears ricochet": 6, "this is me trying": 7, "illicit affairs": 8, "august": 4, "mirrorball": 3, "betty": 6, "mad woman": 6, "epiphany": 2, "peace": 10, "cardigan": 10}
TS_folklore_best = {k:v for (k,v) in TS_folklore_ratings.items() if v>7}

print("These are the songs in Taylor Swift's folklore album that I give a rating greater than 7")
print(TS_folklore_best)
These are the songs in Taylor Swift's folklore album that I give a rating greater than 7
{'exile': 8, 'illicit affairs': 8, 'peace': 10, 'cardigan': 10}

Questions:

  1. How is list comprehension similar to iteration?

List comprehension is similar to iteration in that they both involve repeating the same code as many times as is necessary until a specific condition is fulfilled.

Finished Hacks

Visual Comparing Dictionaries and Lists

from PIL import Image
proof = Image.open('../images/proconlist.png')

print("LISTS VS DICTIONARIES")
display(proof)
LISTS VS DICTIONARIES

Kahoot Score Out of Ten

I got a 7/10 on the Kahoot, which is not a terrible score but it can definitely be improved. Some resources that I will be using in order to study lists/dictionaries/interactions if necessary include this lesson, College Board practice MCQs, and creating flashcards for important vocabulary terms.

Sorting Algorithm on Dictionary/List

num_list = [3,11,6,1,5,10,8,4,0,2,7]

def bubble_sort(num_list):
    n = len(num_list)

    for i in range(n):

        already_sorted = True

        for j in range(n - i - 1):
            if num_list[j] > num_list[j + 1]:
                
                num_list[j], num_list[j + 1] = num_list[j + 1], num_list[j]

              
                already_sorted = False

       
        if already_sorted:
            break

    return num_list

bubble_sort(num_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11]

Explanation in Words

The bubble sorting algorithm, just like any other sorting algorithm, has to iterate through the list in order to output the list ordered from least to greatest. For the bubble sorting algorithm specifically, it compares two numbers (one left and one right). If the number on the left is greater than the number on the right, the sorting algorithm will switch the two and "bubbles" the smaller number to the beginning of the list so that it more accurately represents the list from least to greatest. If the number on the right is greater than the number on the left, the numbers are kept where they are. The bubble sorting algorithm repeats this process until the entire list is sorted from least to greatest. While the bubble sorting algorithm may not have the best time complexity (which is O(n^2)), personally, I have found myself being able to understand and code the bubble sorting algorithm the best.

Simulation Code with a List (Calculator)

def get_data():
  print(
    "Welcome to the data set calculator! Here you can input a set of data and find out all sorts of information about it!"
  )
  complete = False 
  while not complete: # the program will continue to ask the user to input data points while this is true
    try:
      data = float(input("Enter a data point: "))
      data_set.append(data)
    except:
      print("Invalid input. Please input a number")
    answer = input("Would you like to keep entering points? (y/n) ")
    if answer.upper() == "N":
      complete = True # if the user wishes to stop entering data points, the boolean variable complete evaluates to True

  return data_set


def mean(data_set):
  return sum(data_set) / len(data_set) # sum of all numbers in the data set divided by its length


def median(data_set):
  length = len(data_set)
  if length % 2 == 1: # if the length of the list is an odd number, just return the number in the middle of the list
    return data_set[length // 2]
  return (data_set[length // 2] + data_set[length // 2 - 1]) / 2 # if the length of the list is en even number, find the average of the two middle elements of the list


def mode(data_set):
  occurences = dict() 
  for num in data_set:
    if num in occurences.keys(): # mapping each number itself to the number of times that it occurs
      occurences[num] += 1 # if the number exists, add one more of it to the list
    else:
      occurences[num] = 1 # if the number is not already in the list, add it to the list

  mode, most_times = None, 0 # mode corresponds to the number that appears the most times
  for number, count in occurences.items():
    if count > most_times:
      mode, most_times = number, count
  return mode


# bubble sorting algorithm
def sort(data_set):
  length = len(data_set)

  for i in range(length):
    for j in range(0, length - i - 1):
      if data_set[j] > data_set[j + 1]:
        data_set[j], data_set[j + 1] = data_set[j + 1], data_set[j]

  return data_set


def main():
  data_set = get_data()
  print(f'Unsorted List: {data_set}')
  sorted_data_set = sort(data_set)
  print(f"Sorted list: {sorted_data_set}")
  print(f'The mean of your data set is {mean(data_set)}')
  print(f'The median of your data set is {median(data_set)}')
  print(f'The mode of your data set is {mode(data_set)}')

data_set = []

main()

Further Explanation of Above Code

The above code segment is a calculator that allows the user to find multiple statistical information about their data set. It allows them to input any number that they would like (positive, negative, decimal) and as many numbers as they would like until they type in "n" to indicate that they would like to stop entering data points. It uses a list called data_set, which is where all of the user's inputs is stored. The calculator uses two algorithms: one bubble sorting algorithm and one algorithm that calculates the mode of the data set. The bubble sorting algorithm (just as its name says) sorts the list of numbers that the user has inputted from least to greatest. This way, once the user has finished inputting all of their data points, they will be provided with both lists of numbers (one that lists them in the order the user entered them, one that lists them from least to greatest). The other algorithm, called mode, uses a dictionary that relates the numbers in the list to the number of times that they appear in the list. The "number" represents the key and the "count" represents the value of the dictionary. If the number that the user adds is already in the list, one will be added to the value "count", and if the number the user adds is n ot already in the list, the value "count" will be set equal to 1. If a number appears a higher number of times than the previously assigned mode did, the mode will be set to that new number and will be displayed in the output as the mode of the list.

This calculator demonstrates everything that we have learned this lesson, which includes simulations, interactions, lists, dictionaries, and sorting algorithms. This can be considered a simulation because the program can simulate a real-life scientific calculator and can also be used to perform multiple calculations on the data set. The calculator also has the list data_set as described above as well as the dictionary named occurrences with the key-value pair also being described above. The calculator is also interactive in that it allows the user to input whichever numbers that they want to, whether it is a ridiculously large number or a random decimal number. Finally, the calculator also includes a sorting algorithm, as it uses the bubble sorting algorithm in order to sort the data set into a list that is easier to understand since it goes from least to greatest.

Overall, while I was unable to implement UI into this simulation, I believe that it is still worthy of earning the extra 0.1 points, as it can actually be used for data entry from something such as a study or experiment involving numbers. For example, a teacher could use this calculator to input entries for scores that students earned on a math test. By allowing the teacher to calculate the mean, median, and mode score for the class, they can draw several conclusions about things such as their teaching style and adjust it accordingly so that the results obtained are improved for the next time they use the calculator.