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 repeatedWhile 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:
- Give an example of iteration. An example of iteration is a for loop printing each integer in range 1-10.
- 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 iterates through a certain number of items in a list, but a while loop repeats until a condition is met.
- In the APCSP AP exam, what number do indexes start with? important to know It starts at 1.
- Are dictionaries and lists mutable? Yes, you can insert/append keys/values into dictionaries and values into lists.
Simulations/Interactions
Building a simulation o#r interaction using lists and iteration in VS Code can be accomplished using a few simple steps:
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.
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.
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.
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:
- Explain an example of something you could simulate. I could simulate the change of a world record in the future by using previous data of the record.
- Why are simulations useful and important? simulations are useful because you can test something without having to pay for the equipment to perform an actual test, can be performed much faster than an actual test, and can remove potentially dangerours factors of an actual test.
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)
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 groups of values.
- 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 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:
- Describe a situation where you would need iteration. A situation where you would need iteration is looking through a list of names to see if a certain name exists in the list.
- 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 The first loop repeats a certain (n) number of times, while the second loop repeats until the (condition) is met.
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:
- What are some libraries that we've learned about? What are their advantages/disadvantages? One library we have learned about is numpy. It is helpful because it can read and manipulate data. One disadvantage of the library is that you haveb to learn the syntax.
Dictionaries
What are Dictionaries?
- an unordered collection of key-value pairs, where each key is unique 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?
- Import OrderedDict from collections
- Create an empty ordered dictionary by instantiating OrderedDict without providing arguments to the constructor
- Add key-value pairs to the dictionary by providing a key in square brackets ([]) and assigning a value to that key.
- Print the ordered dictionary
- 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?
- Create a variable name which will be the name of the dictionary
- Assign the variable to an empty set of curly braces {}
- Create a dictionary with the dict() OR empty curly brackets
Questions:
- Compare and contrast lists and dictionaries. Lists have a single kind of data, values, while dictionaries have keys and values that are related.
- Do dictionary keys need to be unique? Yes, because otherwise the code would not know which key to get a value from.
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)
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")
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)
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}")
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)
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)
Questions:
- How is list comprehension similar to iteration? List comprehension can use iteration to look through a certain set of values. For example, a list comprehension procedure that prints all names in a list of names containing more than 5 letters would have to iterate through the list to look at each name.
Hacks
(0.1 points) Create a visual or written description. Objective is to compare lists and dictionaries.
Comparison | Lists | Dictionaries |
---|---|---|
Purpose | Stores data | Stores data |
Mechanism | Uses a list of values | Uses key, value pairs |
Nested | Allows use of nested lists | Allows use of nested dictionaries |
Syntax | ["a", "b", "c"] | {key:value} |
names = ["greeting", "ocean", "table", "computer", "elephant", "game"]
a = []
an = []
def vowelcheck(name):
vowels = ["a","e","i","o","u"]
for vowel in vowels:
if vowel == name[0]:
an.append(name)
return
a.append(name)
for name in names:
vowelcheck(name)
print("words to use 'a' with:")
print(a)
print("words to use 'an' with:")
print(an)
simulation
i created a simulation to simuluate gambling with a coin flip. If the coin lands on heads, the amount of money you bet doubles, but if the coin lands on tails, you lose all of your money. I added ui/html/sass to my game, so i think i deservethe extra 0.1. This can be applicable in the real world to recovering gambling addicts because they are not actually winning or losing real money. Furthermore, if they lose enough times, they will realize the dangers of gambling and quit for good.