Lists and Iteration Homework and Challenges

Try to complete this to show understanding! Copy this into your notebook so you can also take notes as we lecture. Make a copy of this notebook to your own repository to take notes, do the class challenges, and to access the homework.

  • title:Lists and Iteration Homework- toc: true
  • permalink: /homework/

Overview and Notes: 3.10 - Lists

  • Make sure you complete the challenge in the challenges section while we present the lesson!

Add your OWN Notes for 3.10 here:

Lists

  • Lists are collections of data
  • Can be used to store unlimited amounts of data
  • Lists are a good way to organize and collect data in a program, as they allow a set of potentially very different items to be found within one object
  • Using functions like append(), pop(), and insert(), you can add new things to a list or remove them.

Fill out the empty boxes:

Pseudocode Operation Python Syntax Description
aList[i] aList[i] Accesses the element of aList at index i
x ← aList[i] x = aList(i) Assigns the element of aList at index i
to a variable 'x'
aList[i] ← x aList(i) = x Assigns the value of a variable 'x' to
the element of a List at index i
aList[i] ← aList[j] aList[i] = aList[j] Assigns value of aList[j] to aList[i]
INSERT(aList, i, value) aList.insert(i, value) value is placed at index i in aList. Any
element at an index greater than i will shift
one position to the right.
APPEND(aList, value) aList.append(value) value is added as an element to the end of aList and length of aList is increased by 1
REMOVE(aList, i) aList.pop(i)
OR
aList.remove(value)
Removes item at index i and any values at
indices greater than i shift to the left.
Length of aList decreased by 1.

Overview and Notes: 3.8 - Iteration

Iteration

  • Iteration is the repetition of a function
  • Allowing a function to repeat on its own based on various conditions can vastly optimize a program
  • Iteration is most often done with loops, typically in combination with lists and/or dictionaries.
  • There are multiple types of loops, and while most types can, in some way, do the same thing as other types, some things are simpler to do with certain loops than others.
  • Iteration and loops go together like bread and butter.

Homework Assignment

Instead of us making a quiz for you to take, we would like YOU to make a quiz about the material we reviewed.

We would like you to input questions into a list, and use some sort of iterative system to print the questions, detect an input, and determine if you answered correctly. There should be at least five questions, each with at least three possible answers.

You may use the template below as a framework for this assignment.

import random

def question_and_answer(prompt):
    print("Question:" +prompt)
    msg = input("Question:" +prompt)
    print("Answer:" +msg)
## defines the format of how the question will be asked
def question_with_response(prompt):
    print("Question: " + prompt)
    msg = input("Question: " + prompt)
    return msg

questions_list = ["What is the purpose of lists in code?\n1. To store multiple variables in one variable\n2. To store and organize unlimited amounts of data\n3. Lists don't do an efficient job of managing complexity", 
             "What operation is used to add something as an element to the end of a list?\n1. pop(i, value)\n2. insert(i, value)\n3. append(i,value)",
             "Why is iteration useful when it comes to coding?\n1. It makes written code look more professional\n2. It doesn't force you to copy and paste the same lines of code many times\n3. Both of these answers",
             "What operation is used to remove something from a list?\n1. pop(i,value)\n2. insert(i, value)\n3. Either of these operations work",
             "Iteration and loops go together like what?\n1. Oil and water\n2. Bread and butter\n3. Vinegar and baking soda"
            ]       

answers_list = [
    "2",
    "3",
    "3",
    "1",
    "2"
]

questions = len(questions_list)
correct = 0

for i in range(len(questions_list)):
        user_response = question_with_response(questions_list[i])
        if user_response == answers_list[i]:
            print(user_response + " is correct! Yay!")
            correct += 1
## If the answer the user inputted doesn't match any of the answers on the list (again depending on question), they will get a message saying they are wrong.
        else:
            print(user_response + " is incorrect! Sorry!")

## After completing the quiz, the user will get their score out of 6 and the percentage
print("You scored " + str(correct) +"/" + str(questions) + ", which is " + str((correct / questions) * 100) + "%")
Question: What is the purpose of lists in code?
1. To store multiple variables in one variable
2. To store and organize unlimited amounts of data
3. Lists don't do an efficient job of managing complexity
1 is incorrect! Sorry!
Question: What operation is used to add something as an element to the end of a list?
1. pop(i, value)
2. insert(i, value)
3. append(i,value)
3 is correct! Yay!
Question: Why is iteration useful when it comes to coding?
1. It makes written code look more professional
2. It doesn't force you to copy and paste the same lines of code many times
3. Both of these answers
3 is correct! Yay!
Question: What operation is used to remove something from a list?
1. pop(i,value)
2. insert(i, value)
3. Either of these operations work
2 is incorrect! Sorry!
Question: Iteration and loops go together like what?
1. Oil and water
2. Bread and butter
3. Vinegar and baking soda
2 is correct! Yay!
You scored 3/5, which is 60.0%

Hacks

Here are some ideas of things you can do to make your program even cooler. Doing these will raise your grade if done correctly.

  • Add more than five questions with more than three answer choices
  • Randomize the order in which questions/answers are output
  • At the end, display the user's score and determine whether or not they passed

Challenges

Important! You don't have to complete these challenges completely perfectly, but you will be marked down if you don't show evidence of at least having tried these challenges in the time we gave during the lesson.

3.10 Challenge

Follow the instructions in the code comments.

grocery_list = ['apples', 'milk', 'oranges', 'carrots', 'cucumbers']

# Print the fourth item in the list
print(grocery_list[3])


# Now, assign the fourth item in the list to a variable, x and then print the variable
x = grocery_list[3] 
print(x)

# Add these two items at the end of the list : umbrellas and artichokes

# works too, but below is another possible answer

# grocery_list.insert(5,"umbrellas")
# grocery_list.insert(6,"artichokes")

grocery_list.append("umbrellas")
grocery_list.append("artichokes")


# Insert the item eggs as the third item of the list 
grocery_list.insert(2,"eggs")


# Remove milk from the list 
# grocery_list.pop(1)

grocery_list.remove("milk")


# Assign the element at the end of the list to index 2. Print index 2 to check
grocery_list[2] = grocery_list[6]
print(grocery_list[2])


# Print the entire list, does it match ours ? 
print(grocery_list)


# Expected output
# carrots
# carrots
# artichokes
# ['apples', 'eggs', 'artichokes', 'carrots', 'cucumbers', 'umbrellas', 'artichokes']
carrots
carrots
artichokes
['apples', 'eggs', 'artichokes', 'carrots', 'cucumbers', 'umbrellas', 'artichokes']

3.8 Challenge

Create a loop that converts 8-bit binary values from the provided list into decimal numbers. Then, after the value is determined, remove all the values greater than 100 from the list using a list-related function you've been taught before. Print the new list when done.

Once you've done this with one of the types of loops discussed in this lesson, create a function that does the same thing with a different type of loop.

binarylist = [
    "01001001", "10101010", "10010110", "00110111", "11101100", "11010001", "10000001"
]

def decimal_to_binary_converter(binary):
    return int(binary,2)

for binvalue in range(0, len(binarylist)):
    binarylist[binvalue] = decimal_to_binary_converter(binarylist[binvalue])

list_final = []

for binvalue in range(0, len(binarylist)):
    if(binarylist[binvalue]<100):
        list_final.append(binarylist[binvalue])
print("Below are a list of numbers converted from binary into decimal AND less than 100")
print(list_final)



    #use this function to convert every binary value in binarylist to decimal
    #afterward, get rid of the values that are greater than 100 in decimal

#when done, print the results
Below are a list of numbers converted from binary into decimal AND less than 100
[73, 55]

What Went Wrong (And What I Tried To Do)

  • I was not sure how to make the binary to decimal converter, as even after one person talked about how they went about, I still was confused about how to implement what they said into my code
  • I tried to use a for loop and use the "int" type in order to convert every binary value in the list to a decimal value, but when I ran the code, nothing showed up in the output (no error messages)
  • I tried using for "bin" in binarylist, but I still was not getting anything in the output
  • I hope that eventually, all of the concepts that we learned in this lesson will become clear to me and that I will be able to go back to this code and improve myself

Updates as of 12/6/22

  • I finally figured out how to write out the code for the binary to decimal program
  • Things that I realized:
    • In order to convert the binary to decimal, I had to make sure that I used "return" along with the int type in order to get the binary value as its decimal
    • I had to make a for loop that converted every element that was in the list into binary, which relates back to using "return" in order to get its decimal value
    • Once I figured out how to do that, I could use an if statement such that the program only printed out binary values who decimals came out to be less than 100, which in this case was 73 and 55