Objectives:

Students will be able to...

  • Understand the concept of data structures, including lists, dictionaries, and 2D arrays
  • Learn how to iterate through data structures using loops
  • Able to visualize data structures and iteration processes
  • Able to apply their knowledge to build simulations/interactions using lists and iteration
  • Learn how to store list and dictionary content in databases

Lesson 1: Lists and Iteration

Lists (Ethan)

  • Lists are a type of data structure that can store multiple items in a single variable
  • Lists are defined using square brackets [ ]
  • Each item in a list is separated by a comma
  • Lists are indexed, starting at 0
fruits = ["apple", "banana", "orange", "grape"]
print(fruits)
['apple', 'banana', 'orange', 'grape']

Accessing Lists

  • To access individual items in a list, we use the index of the item.
  • Python uses zero-based indexing, which means the first item in the list has an index of 0, the second item has an index of 1, and so on.
print(fruits[0])   
print(fruits[2]) 
apple
orange

Slicing Lists

  • We can also extract a specific portion of a list using slicing.
  • We use the colon : operator to specify a range of indices to include.
print(fruits[0:2])    
['apple', 'banana']

Modifying List Items

  • Lists are mutable, meaning that we can change the value of an item in a list.
  • To change the value of an item in a list, we can use the indexing operator (square brackets) to access the item and then assign a new value to it.
fruits[2] = "pear"
print(fruits)
['apple', 'banana', 'pear', 'grape', 'kiwi']

Adding and Removing List Items

Adding

  • Use the append() method to add an item to the end of a list.
fruits.append("kiwi") # Adds 'kiwi' to the end of the list
print(fruits)
['apple', 'banana', 'pear', 'grape', 'kiwi', 'kiwi']
  • Use the insert() method to add an item to a specific index in a list.
fruits.insert(1, "peach") # Inserts "peach" at index 1
print(fruits)
['apple', 'peach', 'banana', 'pear', 'grape', 'kiwi', 'kiwi']

Removing

  • Use the remove() method to remove the first occurrence of an item from a list.
fruits.remove('pear') # Removes the first occurrence of 'pear'
print(fruits)
['apple', 'peach', 'banana', 'grape', 'kiwi', 'kiwi']
  • Use the pop() method to remove the item at a specific index from a list.
fruits.pop(2) # Removes the item at index 2
print(fruits)
['apple', 'peach', 'grape', 'kiwi', 'kiwi']
  • Use the clear() method to remove all items from a list.
fruits.clear() # Removes all items from the list
print(fruits)
[]

Function Explanation

InsertToList

  • This function is designed to insert a new item into a list at a specific index.
  • It first retrieves the new item to be added and the index at which to add it from the HTML document.
  • It checks if the retrieved values are both valid integers and if the index is within the range of the list.
  • If the values are valid, the function uses the splice() method to insert the new item into the list at the specified index.
  • In JavaScript, the splice() method modifies an array by removing, replacing, or adding elements.
  • The splice() method takes three arguments:the index at which to start changing the list, the number of elements to remove, and the new item to add. - The item is inserted without removing any elements, so we pass 0 as the second argument.
  • Finally, the function calls the visualizeList() function to display the updated list on the web page.
  // Get the value of the new item and the index where it should be inserted
  function insertToList() {
      let newItem = parseInt(document.getElementById("newItem").value);
      let index = parseInt(document.getElementById("index").value);
      if (!isNaN(newItem) && !isNaN(index) && index >= 0 && index <= myList.length) {
        // splice() method to insert the new item into the list
        myList.splice(index - 1, 0, newItem);
        // Call the visualizeList() function to update the display of the list
        visualizeList();
      }
    }

SortList

  • In JavaScript, sort() is a built-in method used to sort the elements of an array in place. The default sort order is ascending, but you can also specify a descending sort order.
  • In this case, the function sorts myList in ascending order based on their numerical value.
  // Sort myList array in ascending order     
  function sortList() {
      // The function a - b is used, which subtracts the second element b from the first element a. 
      // If the result is negative, a is sorted before b. If the result is positive, b is sorted before a. If the result is zero, the order of the elements is unchanged.
      myList.sort((a, b) => a - b);
      visualizeList();
    }

Applications of Lists

  • Data processing: Lists are commonly used to store and process large amounts of data. In data analysis and machine learning, lists are often used to store datasets.

  • Gaming: Lists are used extensively in game development to store game objects, player statistics, and game maps.

  • Finance: Lists are used in finance to store and process financial data, such as stock prices and market trends. The data from these lists can also be used to calculate financial metrics and to create financial models.

Hacks (0.3)

  • Make your own list and manipulate it via accessing specific elements, adding or removing elements, etc.
  • Extra: Make an interactable visualization that can manipulate elements in a list such as the one demonstrated in our flask repository
wimbledonWins = [2003, 2004, 2005, 2006, 2007, 2010, 2012, 2017]

print("Federer has", len(wimbledonWins), " Wimbledon wins")
for win in wimbledonWins:
    print("Federer won in", win)

print("There seems to have been an error; he did not win in 2010. Manipulating array...")
wimbledonWins.remove(2010)
wimbledonWins.append(2009)

print("Mistake corrected. Re-sorting list...")
wimbledonWins.sort()
for win in wimbledonWins:
    print("Federer won in", win)
Federer has 8  Wimbledon wins
Federer won in 2003
Federer won in 2004
Federer won in 2005
Federer won in 2006
Federer won in 2007
Federer won in 2010
Federer won in 2012
Federer won in 2017
There seems to have been an error; he did not win in 2010. Manipulating array...
Mistake corrected. Re-sorting list...
Federer won in 2003
Federer won in 2004
Federer won in 2005
Federer won in 2006
Federer won in 2007
Federer won in 2009
Federer won in 2012
Federer won in 2017

Iteration (Alex)

What is iteration?

  • In programming, iteration refers to the process of repeating a set of instructions until a specific condition is met. This can be achieved using loop structures like for loops and while loops.

For Loops

  • A for loop is used to iterate over a sequence (e.g. a list, tuple, string, etc.) and execute a set of statements for each item in the sequence. Here's the basic syntax of a for loop in Python:
sequence = [1,2,3,4,5,6,7]
for variable in sequence:
    print(variable)
1
2
3
4
5
6
7
my_string = "Hello, World!"

for character in my_string:
    print(character)
H
e
l
l
o
,
 
W
o
r
l
d
!

While Loops A while loop is used to repeat a set of statements as long as a condition is true. Here's the basic syntax of a while loop in Python:

num = 0

while num < 5:
    print(num)
    num += 1
0
1
2
3
4

Applications of Iteration

Iteration is a fundamental concept in computer programming and is used in a variety of real-life applications. Here are some examples:Data Processing

  • Data processing often involves iterating over large datasets to perform specific operations on each element. For example, in a data analysis task, you might iterate over a list of numbers to compute the average, or iterate over a list of strings to find the longest string.

User Interfaces

  • User interfaces often involve iteration to display and handle data from various sources. For example, in a web application, you might iterate over a list of users to display their information in a table. Similarly, in a desktop application, you might iterate over a list of files to display them in a file explorer.

Machine Learning

  • Machine learning algorithms often involve iterative processes to train models and improve their accuracy. For example, in a gradient descent algorithm, you might iterate over a set of training data to update the model's parameters and minimize the loss function.

Popcorn hack (0.3)

  • Make a list related to your CPT project
  • Make a while loop that will print each term in the list
  • Make a for loop that will print each term in the list
# hash map implemented as array
cpt = [["key1", "value1"], ["key2", "value2"]]

def get_item(hash_map, key):
    # loop over hash map
    for item in hash_map:
        # check whether key equals parameter
        if key == item[0]:
            # print value
            print(item[1])

get_item(cpt, "key1")
# instantiate an array
temp = [1, 2, 3, 4, 5]
# create a variable to represent the index of the current item in the temp array
index = 0
# while the index is less than the list length
while index < len(temp):
    # print item at index
    print(temp[index])
    # increment index
    index += 1
# instantiate an array
temp = [1, 2, 3, 4, 5]
# loop over each item in temp by value
for item in temp:
    # print item
    print(item)

Simulation mechanics

  • In Python, pop() is a method that is used to remove and return an element from a list. The syntax for using pop() is as follows:
my_list = [1, 2, 3, 4, 5]
print(my_list)
my_list.pop()
print(my_list)
my_list.pop(1)
print(my_list)
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 3, 4]

In Python, append() is a built-in method that is used to add an element to the end of a list. The syntax for using append() is as follows:

my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
print(my_list)
[1, 2, 3]

Dictionary Lesson / 2D Arrays

Lesson 2: Dictionary's and 2 Dimensional Arrays

Advay Shindikar and Amay Advani

Objective:

  • Understand the concept of dictionaries and how they can be applied
  • Learn how to add, modify, and delete entries in a dictionary using the assignment operator and the del keyword
  • Understand the concept of 2D arrays and how they can be used to store data in rows and columns
  • Learn how to create a 2D array in Python using a nested list
  • Understand how to access values in a 2D array using row and column indices
  • Learn how to use indexing and slicing to access a subset of a 2D array

student = {'name': 'Advay', 'age': 16, 'Sophomore'}
students = ['advay', 'amay', 'rohin', 'alex', 'ethan']

Check In:

  • Of the above code segments, which is a list and which is a dictionary? student is a dictionary, students is a list
  • What is a dictionary and how is it used? a dictionary is a collection of unique keys each associated with a single value
  • What is a 2D Array? a 2d array is an array with arrays as entries
  • How are 2D Arrays different from 1D Arrays or Lists and what can they be used for? 2d arrays are different from 1d arrays in that their entries are arrays rather than single values. they can be used for multi-dimensional data such as tables, images, framebuffers, etc.

Manipulating Dictionaries

grocery_dict = {
    "piiza": 10,
    "pasta": 20,
    "ramen": 6
}

# ask the user to enter grocery items and their prices
while True:
    item = input("Enter an item for your grocery list (or 'done' to exit): ")
    if item == "done":
        break
    else:
        price = float(input("Enter the price of {}: ".format(item)))
        grocery_dict[item] = price

# print the grocery list and total cost
total_cost = 0
while True:
    print("Your grocery list:")
    for item, price in grocery_dict.items():
        print("- {}: ${}".format(item, price))
    print("Total cost: ${}".format(total_cost))
    
    # ask the user to choose an action
    action = input("What would you like to do? (add/remove/done) ")
    
    # add a new item to the grocery list
    if action == "add":
        item = input("Enter the name of the item you would like to add: ")
        price = float(input("Enter the price of {}: ".format(item)))
        grocery_dict[item] = price
        total_cost += price
    
    # remove an item from the           j
        item = input("Enter the name of the item you would like to remove: ")
        if item in grocery_dict:
            total_cost -= grocery_dict[item]
            del grocery_dict[item]
        else:
            print("Item not found in grocery list!")
    
    # exit the loop and print the final grocery list and total cost
    elif action == "done":
        break

print("Final grocery list:")
for item, price in grocery_dict.items():
    print("- {}: ${}".format(item, price))
print("Total cost: ${}".format(total_cost))
Your grocery list:
- piiza: $10.0
- pasta: $6.0
- ramen: $6
Total cost: $0
Item not found in grocery list!
Your grocery list:
- piiza: $10.0
- pasta: $6.0
- ramen: $6
- pizza: $10.0
Total cost: $10.0
Final grocery list:
- piiza: $10.0
- pasta: $6.0
- ramen: $6
- pizza: $10.0
Total cost: $10.0
def display_ascii_table(dictionary):
    print("╔═════════════╦═════════════╗")
    print("║ Key         ║ Value       ║")
    print("╠═════════════╬═════════════╣")
    for key, value in dictionary.items():
        print(f"║ {key:<12}{value:<12}║")
    print("╚═════════════╩═════════════╝")

my_dictionary = {}

while True:
    print("Enter a key and value (both strings) to add to the dictionary. Type 'quit' to exit.")
    key = input("Key: ")
    if key.lower() == 'quit':
        break

    value = input("Value: ")
    if value.lower() == 'quit':
        break

    my_dictionary[key] = value
    display_ascii_table(my_dictionary)
Enter a key and value (both strings) to add to the dictionary. Type 'quit' to exit.
╔═════════════╦═════════════╗
║ Key         ║ Value       ║
╠═════════════╬═════════════╣
║ abc         ║ lol         ║
╚═════════════╩═════════════╝
Enter a key and value (both strings) to add to the dictionary. Type 'quit' to exit.
╔═════════════╦═════════════╗
║ Key         ║ Value       ║
╠═════════════╬═════════════╣
║ abc         ║ lol         ║
║ amay        ║ monkey      ║
╚═════════════╩═════════════╝
Enter a key and value (both strings) to add to the dictionary. Type 'quit' to exit.
╔═════════════╦═════════════╗
║ Key         ║ Value       ║
╠═════════════╬═════════════╣
║ abc         ║ lol         ║
║ amay        ║ monkey      ║
║ good        ║ boy         ║
╚═════════════╩═════════════╝
Enter a key and value (both strings) to add to the dictionary. Type 'quit' to exit.
import random
from PIL import Image, ImageDraw, ImageFont

def nd_array(n):
    array = [[random.randint(0, 255) for _ in range(n)] for _ in range(n)]
    return array

def nd_array_draw(array):
    cell_size = 50
    width = height = len(array) * cell_size

    image = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(image)

    for i, row in enumerate(array):
        for j, value in enumerate(row):
            x, y = j * cell_size, i * cell_size
            draw.rectangle([x, y, x + cell_size, y + cell_size], fill=(value, value, value))
            draw.text((x + cell_size // 2 - 8, y + cell_size // 2 - 8), f"{value:0>3}", fill=(255, 255, 255))

    return image

n = int(input("Enter the size of the 2D array: "))
array = nd_array(n)
image = nd_array_draw(array)

# Display the image
display(image)