3.8.1 - Iteration

Iteration - repeating portion of code (repeats a certain number of times until a certain condition is met) Iteration Statements - change the flow of control by repeating a set of statements a certain number of times until a condition is met Repeat Until - iteration that is repeated until a certain condition is met

Iterations are a series of checks to see if certain conditions are met

  • Here is an example of a repeating statement

  • Here the program is repeated but broken off early to stop the loop:

Hacks

Iteration - a looping portion of code that repeats until a certain condition is met

Example of Iteration:

  1. I have 10 tasks to complete
  2. start task “1” and finish it
  3. move to task “2” and repeat for “i” tasks
  4. if task “5” is reached, stop; that is enough for now
i = 1
while(i < 10):
  print(i)
  i = i + 1
  if (i == 5):
    print("5 = enough for now")
    break
1
2
3
4
5 = enough for now

Iteration Code:

colors = ["red", "orange", "yellow", "green", "blue", "purple"]

for i in colors:
  print(i)
red
orange
yellow
green
blue
purple

3.8.2 - Iteration Results With For and WHile Loops

Iteration Statements - causes statements to be repeated until the loop meets a criteria

Printing range of numbers:

for i in range(11):
    print(i)

# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10

Changing range to start at certain value:

for i in range(1,11):
    print(i)

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10

How to print a certain range with certain values:

for i in range(starting value, ending value, incremented value):
    print(i)

Another way to make a loop:

i=1
while i<=10:
	print(i)
	i=i+1

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10

Hacks

Iteration Statement - a statement in code that causes a section of code to repeat until a certain condition is met

Countdown:

for i in range(7, -1, -1):
  print(i + 1)
  i = i + 1
  if (i == 1):
    print("Reached End")
    break
8
7
6
5
4
3
2
1
Reached End

List of Numbers:

list = [3, 16, 29, 42, 55, 68, 81]
x = 0
y = 0
while x < len(list):
  print(list[y])
  x+=1
  y+=1
3
16
29
42
55
68
81

3.8.3 - Loop Types

For Loops - goes through list and for each item it does a check

pets = ["cat", "dog", "fish", "snake"]
for i in pets:
    if i == "fish":
        break
    print(i)

# cat
# dog

While Loops - goes through a list that while a certain condition is met, the loop runs

number = 0 
while number < 10:
    if number % 2 == 0:
        print(number)
    number += 1

# 0
# 2
# 4
# 6
# 8

Example of sum of numbers between a certain range of numbers:

minimum = int(input("please enter a minimum number you want your range to be"))
maximum = int(input("please enter a number that you want to be the maximum value"))
sum = 0
for i in range(minimum,maximum+1):
    if i % 2 == 0:
        sum += i
print("The sum of all the even numbers between", minimum, "and", maximum, ":", sum)
    
# The sum of all the even numbers between 1 and 3 : 2

3.10.1 - Lists Functions

APCSP Testing Reference Sheet

  • len() - returns the number of items in a list
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# find length of list
num_names = len(names)
print("There are" + str(num_names) + "names.")

# There are 5 names.
  • sort() - changes order of list permanently
  • sorted() - returns a copy of the list which leaves the original copy unchanged
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# sort permanently
names.sort()
# sort permanently in reverse alphabetical order
names.sort(reverse=True)
# temp. sort
print(sorted(names))
print(sorted(names, reverse=True))
# reversing the order of a list
names.reverse()

# ['ethan', 'luna', 'nikhil', 'parav', 'taiyo']
# ['taiyo', 'parav', 'nikhil', 'luna', 'ethan']
  • range() - use to work with number efficiently
# print numbers 0 to 10
for number in range(11):
    print(number)
# making list of numbers 1 to 10
# using the list() value can generate a large list of numbers
numbers = list(range(1, 10))

# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
  • min() - find the least value in list
nums = [10, 30, 40, 60, 70, 60]
least = min(nums)
print(min(nums))

# 10
  • max() - find the highest value in list
nums = [10, 30, 40, 60, 70, 60]
highest = max(nums)
print(max(nums))

# 70
  • sum() - sum of all in list
nums = [10, 30, 40, 60, 70, 60]
total = sum(nums)
print(sum(nums))

# 270

Hacks

Minimum Finder:

nums = ['38', '45', '67', '83', '78']

min = nums[0]

for i in nums:
  if i < min:
    min = i

print("This is the lowest number: " + str(min))
This is the lowest number: 38

Collegeboard Reference Sheet Notes:

  • a MOD b
    • Evaluates to the remainder when a is divided by b.
    • Ex. 17 MOD 5 evaluates to 2
  • aList[i]
    • accesses an element in a list based on indexing
  • PROCEDURE procName(parameter1…)
    • arg1 is assigned to parameter1
  • aList ← bList
    • aList becomes bList, assigning values from one list to another

3.10.2 - Traversal

Traversing - visiting each element of a list and making a decision based on the value

Traversing Lists:

  1. Complete Traversal: All elements in a list are assessed

  2. Partial Traversal: Only a given portion of elements are assessed

  3. Iterative Traversal: When loops are used to iterate through a list and to access each single element at a time.

Python Traversals:

  • append() - adds element to the end of the list
names = ['taiyo', 'ethan', 'parav', 'nikhil']
# add element to the end of the list
names.append('luna')
# start with empty list
names = []
names.append('taiyo')
names.append('ethan')
names.append('parav')
names. append('nikhil')
  • insert() - adds element to a specific position (indexing)
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# adding in a specific position
names.insert(0, 'taiyo')
names.insert(3, 'ethan')
  • remove() - removes item from list (indexing)
names = ['luna', 'taiyo', 'ethan', 'parav', 'nikhil']
# deleting by value
names.remove('parav')
# by position
del names[-1]
  • length() - returns the number of elements currently in a specific list

Hacks

import getpass, sys
import random

def ask_question (question, answer):

    print(question)
    ans = input(question)
    print(ans)
   
    if ans == answer:
        print("Correct!")
        return 1

    else:
        print("Wrong")
        return 0

question_list = ["What allows a value to be inserted into a list at index i?" , "What allows an element at index i to be deleted from a list?" , "What returns the number of elements currently in a specific list?" , "What allows a value to be added at the end of a list?"]
answer_list = ["index()", "remove()", "length()" , "append()"]

# Set points to 0 at the start of the quiz
points = 0

# If the length of the quiz is greater than 0, then random questions will be chosen from the "question_list" set
while len(question_list) > 0:
    index = random.randint(0, len(question_list) - 1)
    
# The points system where a point is rewarded for each correct answer    
    points = points + ask_question(question_list[index], answer_list[index])
    
# If a question or answer has already been used, then it shall be deleted    
    del question_list[index]
    del answer_list[index]

# Calculating score using the points system and dividing it by the total number of questions (6)
score = (points / 4)

# Calculating the percentage of correct answers by multiplying the score by 100
percent = (score * 100)

# Printing the percentage, and formatting the percentage in a way where two decimals can be shown (through "{:.2f}")
print("{:.2f}".format(percent) + "%")

# Adding final remarks based upon the users given scores
if points >= 5:
         print("Your total score is: ", points, "out of 4. Amazing job!")

elif points == 4:
         print("Your total score is: ", points, "out of 4. Not too bad, keep on studying! " )

else:
         print("Your total score is: ", points, "out of 4. Its alright, better luck next time!")
What allows a value to be added at the end of a list?
append()
Correct!
What allows an element at index i to be deleted from a list?
remove()
Correct!
What returns the number of elements currently in a specific list?
length()
Correct!
What allows a value to be inserted into a list at index i?
index()
Correct!
100.00%
Your total score is:  4 out of 4. Not too bad, keep on studying! 

3.9.1 - Algorithms

Three main parts: sequence, selection, iteration

Grade Analysis - if/then statements with comparisons:

print("What Grade Did You Get?")
grade = int(input("Enter Grade:"))
if grade >= 93:
        print("Wow! Good job!")
if 70 <= grade < 93:
        print("Nice!")
elif grade < 70:
        print("Do Better")

Small errors in logic can create a problem.

This is the same code as above, but with variables.

print("What Grade Did You Get?")
grade = int(input("Enter Grade:"))
A = grade >= 90
B = 70 <= grade < 90
C = grade < 70
if A:
        print("Wow! Good job!")
elif B:
        print("Nice!")
elif C:
        print("Do Better")

Using comments helps with debugging.

Nested Conditionals without boolean vs with boolean

# setting variables here
isHoliday = False
isWeekday = True

#if holiday, dont go to school
if isHoliday == True:
    print("don't go to school!")

# otherwise, if it is a weekday, go to school
else:
    if isWeekday == True:
        print("go to school!")
    # but if it is neither a weekday or holiday, don't go to school
    else:
        print("don't go to school")

This one uses nested conditional statements.

isHoliday = False
isWeekday = True

# setting variables here (same as above to make comparison easier)
driveSchool = not(isHoliday) and isWeekday
if driveSchool == False:
    print("don't go to school!")
if driveSchool == True:
    print("go to school!")
# now we can make a regular conditional/ if statement without having a nested conditional

This one uses booleans to express the outputs.

Hacks

It is important to know that functions can look different and still do the same things because there are many different ways to code something but the final products is still the exact same. This shows that some programs can be complex while other are simpler, allowing coders to eventually achieve the most simple way of coding a function. Some functions can look the same while completing entirely different things. This shows that code has similar parts that can be put together to complete entirely different things. This is also important to know because one piece of code that is wrong can look different from another piece that is correct.

Nested Conditionals:

x = True
y = False

if x == True:
  print("x = true")
elif y == True:
  print("y is true")
else:
  print("neither y or x are true")
x = true

Booleans:

x = True
y = False

xy = not(x) and y
if xy == True:
  print("y = true")
if xy == False:
  print("x = true")
else:
  print("neither y or x are true")
x = true

3.9.2 - Developing Algorithms

Developing allows for sequencing the algorithms correctly.

  • flowcharts - help with organization

Example with steps and then code (iteration):

  1. Start
  2. The number of pretzels in the pack is 6
  3. Eat one pretzels, number of pretzels in pack goes down by 1
  4. How many pretzels are left?
  5. Repeat step 3 until number of pretzels is 0
  6. Display that pack is empty
  7. Finish
pretzel = 6
while (pretzel > 0):
    pretzel -= 1
    print(pretzel)
    if pretzel == 0:
        print("All done!")

Example with predefined values (selection):

The parking rate for a garage is as follows:
Less than one hour: Free
1-2 hours: $5
2-3 hours: $8
3-4 hours: $10
4+ hours: $12

  1. Start
  2. Input number of hours parked
  3. If hours is less than 1, cost is free
  4. If hours is between 1 and 2, cost is $5
  5. If hours is between 2 and 3, cost is $8
  6. If hours is between 3 and 4, cost is $10
  7. If hours is more than 4, cost is $12
  8. Display cost and goodbye
  9. Finish
print("The parking rate is as follows: \n Less than one hour: Free \n 1-2 hours: $5 \n 2-3 hours: $8 \n 3-4 hours: $10 \n 4+ hours: $12")

time = float(input("How many hours have you parked at this garage?"))
print("How many hours have you parked at this garage?")
print(time, "hours costs:")

if time < 1 :
    print("Free")
elif time >= 1 and time < 2 :
    print("$5")
elif time >= 2 and time < 3 :
    print("$8")
elif time >= 3 and time < 4 :
    print("$10")
else:
    print("$12")

print("Have a good day!")

Hacks

Explanation:

  1. Start
  2. Homework to do?
  3. If homework to do is true, how many assignments are there?
    • Start first assignment and while assignments > 0, repeat.
    • When assignments = 0, go study.
  4. If homework to do it false, go study.
  5. How many classes to study for?
    • Start studying for first class while classes > 0, repeat.
    • When classes = 0, study.

Code:

hw = 6
classes = 5
hwdo = True

if hwdo == True:
  if hw > 0:  
    while hw > 0:
      if hw > 0:
        hw -= 1
      print("Homework left: ", hw)
      if hw == 0:
        hwdo = False
  if hwdo == False:
    print("No homework, go study!!!")
    while classes > 0:
      if classes > 0:
        classes -= 1
      print("Classes left to study for: ", classes)
      if classes == 0:
        print("Relax!!!")
Homework left:  5
Homework left:  4
Homework left:  3
Homework left:  2
Homework left:  1
Homework left:  0
No homework, go study!!!
Classes left to study for:  4
Classes left to study for:  3
Classes left to study for:  2
Classes left to study for:  1
Classes left to study for:  0
Relax!!!

3.9.3 - Using Preexisting Algorithms

Can be used to do math in coding, allows shorter code and less work. These already exist in programming language.

Example with even/odd:

if (n MOD 2 = 0)
{
    display("n is even")
}
else
{
    display("n is odd")
}

Hacks

Flowchart:

Code:

import random

#sets variables for the game
num_guesses = 0
user_guess = -1
upper_bound = 100
lower_bound = 0

#generates a random number
number = random.randint(0,100)

# print(number)     #for testing purposes

print(f"I'm thinking of a number between 1 and 100.")

#Write a function that gets a guess from the user using input()
def guess():
    num = input("Choose a number.")
    return num

#Change the print statements to give feedback on whether the player guessed too high or too low
def search(number, guess):
    global lower_bound, upper_bound
    if int(guess) < int(number):
        print("Your guess is too low.")
        lower_bound = guess
        return lower_bound, upper_bound
    elif int(guess) > int(number):
        print("Your guess is too high.")
        upper_bound = guess
        return lower_bound, upper_bound
    else:
        upper_bound, lower_bound = guess, guess
        return lower_bound, upper_bound

while user_guess != number:
    user_guess = guess()
    num_guesses += 1
    print(f"You guessed {user_guess}.")
    lower_bound, upper_bound = search(number, user_guess)
    if int(upper_bound) == int(number):
        break
    else:
        print(f"Guess a number between {lower_bound} and {upper_bound}.")

print(f"You guessed the number in {num_guesses} guesses!")
I'm thinking of a number between 1 and 100.
You guessed 50.
Your guess is too high.
Guess a number between 0 and 50.
You guessed 25.
Your guess is too high.
Guess a number between 0 and 25.
You guessed 12.
Your guess is too high.
Guess a number between 0 and 12.
You guessed 6.
Your guess is too high.
Guess a number between 0 and 6.
You guessed 2.
Your guess is too high.
Guess a number between 0 and 2.
You guessed 1.
You guessed the number in 6 guesses!

Repeatedly divides search interval in half.

  • allows to find certain parts of an array more efficiently than other methods is the list is sorted
  • works with branches, where there is a tree of the elements of an array, each section of the array being split in half each time

photo

  • can be anything including strings and integers

Hacks

num1 = [12,14,44,57,79,80,99]
num2 = [92,43,74,66,30,12,1]
num3 = [7,13,96,111,33,84,60]

numAll = [num1, num2, num3]

for x in range(len(numAll)):
  numAll[x].sort()
  mid = int(len(numAll[x])/2)
  print("Middle Index of Array ", x+1, "is", numAll[x][mid])
Middle Index of Array  1 is 57
Middle Index of Array  2 is 43
Middle Index of Array  3 is 60

Binary Trees:

Second Numbers Greater Than Middle Number:

  1. Number = 80
  2. Number = 74
  3. Number = 96

Which of the following lists can NOT a binary search be used in order to find a targeted value?

a. ["amy", "beverly", "christian", "devin"]

b. [-1, 2, 6, 9, 19]

c. [3, 2, 8, 12, 99]

d. ["xylophone", "snowman", "snake", "doorbell", "author"]

Answer: C would be the correct answer because it is unsorted, meaning that binary searching would not work. A and D are both sorted alphabetically either forwards or backwards and B is sorted numerically.