Monday 10/9¶
Exercise 1: While-Loop Tracing Practice¶
Determine what will be printed by each of the code snippets below.
Q1¶
count = 1
while count <= 3:
count += 1
print(count)
Q2¶
count = 7
while count > 3:
print(count)
count -= 2
Q3¶
count = 1
while count <= 6:
if count % 2 == 0:
count += 3
else:
count += 1
print(count)
Q4¶
count = 1
while count < 10 and count % 7 != 0:
print(count)
count += 1
Q5¶
count = 10
while count > 0:
count += 1
print(count)
Q6¶
grades = [93, 82, 67, 99]
while len(grades) > 1:
min_grade = min(grades)
print(min_grade)
grades.remove(min_grade)
Review of Containers¶
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() | in | add , pop , remove |
Dictionary | {} or dict() | [k] , in | get , items , pop |
Exercise 2: Short Words¶
Write a function named get_short(words)
that takes a list of words and
returns the words that have at most 5 letters. Do not change the list
you are given. Instead, follow these steps:
- Create an empty list.
- Write a for loop that adds one word at a time to the list.
- Return the resulting list. (At the end, not in the loop!)
Once this function is tested, create two new functions named
get_short_set(words)
and get_short_dict(words)
these should return
the short words in a set or dict respectively. For
get_short_dict(words)
use the word for the key and the length for
the value.
Exercise 3: Five Stars¶
Write a function named five_star(hotels)
that takes a list of tuples
as the input where the first entry in each tuple is the hotel name and
the second is the rating. Return a list of hotels that have a rating
of 4.5 or higher. For example
>>> five_star([("Ritz",5.0), ("Marriott", 4.5), ("Madison", 4.2)])
["Ritz", "Marriott"]
Once this is tested, create a new function named five_star_dict
that
takes a dictionary as input. For example, given {"Ritz": 5.0,
"Marriott": 4.5, "Madison": 4.2}
, return ["Ritz", "Marriott"]
.