For Loops with sets

def all_pairs(sentence):
    """Return a set containing all neighboring pairs of letters.
    
    Args:
        sentence (string): Any string

    Returns:
        set: A set containing all unique pairs of neighboring letters.
    """
    all_pairs = set()
    for i in range(len(sentence) - 1):  # Stop one index *before* the end.
        letter = sentence[i]
        next_letter = sentence[i + 1]
        all_pairs.add(letter + next_letter)
    return all_pairs

print(all_pairs("abbbbcbcbcab"))

output is
{'bc', 'ca', 'cb', 'ab', 'bb'}

Concepts

  • None
    • is an object
    • function: return None or return or no return
    • can be used to set a variable
      • is not the same as zero or blank
    • can be as default for function argument
      • this is beyond what we have covered in class.
        • if parameter is mutable, does not retain the paramter value
  • homeworks with docstrings

While Loops

  • loop body
  • expression
    • evaluated before entering the loop body
  • iteration
  • loop should terminate eventually
    • boolean expression evaluates to false
    • sentinel value

While Loops

  • how are while loops different from for loops?
    • fixed number of times?
  • infinite loop
    • boolean expression never evaluates to false
  • some execution must occur in the loop body to cause evalution to false
count = int(input("enter an integer number: "))
while count < 10 and count % 7 != 0:
    print(count)
    count += 1
  • compare to
count = int(input("enter an integer number: "))
while count < 10 and count % 7 != 0:
    print(count)
count += 1

While loop and validating user input

amount = float(input("Enter Withdrawl Amount: "))

while (amount < 1.0 or amount > 300.0):
   print("Amount must be $1.00 - $300.00.")
   amount = float(input("Enter Withdrawl Amount: "))


print(f"Here is what you entered {amount:.2f}")

Overview containers: REVIEW THIS!

Name Create empty Operators Important methods
List [] or list() [i], in, +, * append, count, index, insert, pop, remove
Tuple () or tuple() [i], in, +, * count, index
Set set() only in add, pop, remove
Dict {} or dict() [k], in get, items, pop

For loops and dictionary: REVIEW THIS!

def dict_example(some_dict):
    for key, value in some_dict.items():
       print(key, "->", value)
       
dict_example({"color": "blue", "fruit": "apple", "pet": "dog"})
dict_example({1234:"Sharon", 3450:"Ann", 6901:"Robert"})

How many times is the loop body executed?

How many times is the boolean expression executed?

What is the output?

grades = [93, 82, 67, 99]
while len(grades) > 1:
    min_grade = min(grades)
    print(min_grade)
    grades.remove(min_grade)
print(grades[0])

Tracing output

Predict what happens by tracing on paper

# Problem 1
count = 1
while count <= 3:
    count += 1
    print(count)
# Problem 2
count = 7
while count > 3:
    print(count)
    count -= 2
# Problem 3
count = 10
while count > 0:
    count += 1
    print(count)

More tracing

  • Greatest common divisor
    • Euclidean algorithm
      Execute by hand and predict the output for the input 16, 3
x = int(input("Larger number: "))
y = int(input("Smaller number: "))
while y != 0:
    temp = y
    y = x % y
    x = temp
print("The GCD is", x)

Tracing ...

  • consider different input
  • how many times does the loop body execute?
print("Give me some numbers...")
number = None
while number != 0:
    number = float(input())
    if number > 0:
        print(number, "is positive")
    elif number < 0:
        print(number, "is negative")
print("Have a nice day!")

Number of iterations

# Iterating some determined amount of times using a loop variable
count = 1
while count < limit:
    # Loop body statements go here
    count += 1

OR

for count in range(1, limit)
    # Loop body
  • for loops: less likely to enter an infinite loop
    • while loop: remember to increment sentinel value
  • while loop: number of iterations is not known prior to execution

Review of for loops:

predict the behavior

# Problem 1
for row in range(10):
    print(row, end="\t")
    print("#" * row)

#Problem 2
cities = ["boise", "omaha", "tulsa", "utica"]
result = []
for city in cities:
    result.append(city.upper())
print(result)

# Problem 3
word = "onomatopoeia"
locs = []
for i in range(len(word)):
    if word[i] in ('a', 'e', 'i', 'o', 'u'):
        locs.append(i)
print("Locations:", locs)

Another for loop

Notice split()

name = "James Madison University"
words = name.split()
acronym = ""
for word in words:
    letter = word[0]
    print(letter, "is for", word)
    acronym += letter
print(acronym)

Go to exercises on the web page

def get_short(words):
    short = []
    for word in words:
        if len(word) <= 5:
            short.append(word)
    return short

print(get_short(["hello", "goodbye", "hi", "another", "day"]))

Thonny debugger

n = int(input("Enter a positive integer: "))
while n != 1:
    print(n)
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3*n + 1
print("n is now 1!")

Thonny debugger

  • Convert decimal number to binary
n = int(input("Enter a positive integer: "))
print(n, "in binary is", end=" ")
binary = ""
while n > 0:
    r = n % 2
    n = n // 2
    binary = str(r) + binary
print(binary)

Random numbers

  • want to generate pseudo random numbers
    • seed based on current time
  • random module
  • random.random(): returns a float from 0.0(inclusive) to 1.0 (exclusive)
  • random.randrange(x): returns an integers from 0 to x-1
  • random.randrange(min, max): returns an integer from min to max-1
  • random.randint(min, max): returns an integer from min to max
  • random.seed(number): can reproduce the series of random numbers

Thonny debugger

  • Examples using random
import random

health = 5
while health > 0:
    print("Your health is", health)
    move = input("Attack or Dodge? ")
    move = move[0].upper()

    if move == "A":
        if random.random() < 0.33:
            print("Hit! Your health increases by 1.")
            health += 1
        else:
            loss = random.randint(1, 4)
            print("Miss! You lost", loss, "health.")
            health -= loss
    elif move == "D":
        if random.random() < 0.50:
            print("Good dodge. You're still alive.")
        else:
            loss = random.randint(2, 3)
            print("Oops! You lost", loss, "health.")
            health -= loss
    else:
        print("Invalid move...you're now dead.")
        health = 0
    print()

print("Game over")
# coin toss
import random

heads = 0
tails = 0
times = 1000000

for _ in range(times):
    if random.random() < 0.5:
        heads += 1
    else:
        tails += 1

heads = round(heads / times * 100, 2)
tails = round(tails / times * 100, 2)

print(f"Head: {heads}%, Tail: {tails}%")

Nested Loops

  • inner loop, outer loop
  • nested for loops
for m1 in range(1,11):
    for m2 in range(1,6):
        print(f' {m1} x {m2} = {m1*m2}')
    print(f'______________________')

Break and Continue

  • break : exits loop immediatley
  • continue : jump to loop header statement
  • can be used in both while and for loops
for num in range(5):
    if num == 3:
        break
    print(num)
print("done")

for num in range(5):
    if num == 3:
        continue
    print(num)
print("again")