Here is a set of 4 practice problems covering content spanning variables, strings, and lists. We've prepared a slideshow presentation that walks through how to decompose the problems and arrive at a solution step by step. We hope you find this helpful!
Problem 1: Print in Frame
Write a console program that asks the user for some text and prints that text out in a "frame". The "frame" will look like this:
If the user's input is CS106A, the "framed input" will be:
**********
* CS106A *
**********
A full run of this program would look like:
Enter the text to frame: Hello
*********
* Hello *
*********
"""
File: print_in_frame.py
------------------------
This program takes in a user's textual input
and frames it as follows:
CS106A
would become
**********
* CS106A *
**********
"""
def print_message_in_frame(s):
print(f"* {s} *")
def print_border(length):
border = ""
for i in range(length + 4):
border += "*"
print(border)
def main():
user_input = input("Enter some text to frame: ")
length = len(user_input)
print_border(length)
print_message_in_frame(user_input)
print_border(length)
if __name__ == "__main__":
main()
Problem 2: 24-hour time
Write a console program that asks the user for a time formatted in 12-hour time, converts that input to 24-hour time, and prints the new value out to the console. An example of 12-hour time is 07:15PM. That value in 24-hour time would be 19:15.
You may assume that the user's input will always be in the format HH:MMAM or HH:MMPM where H is a single digit of the hour value and M is a single digit of the minute value. The hours and minutes value will always be two-digit (i.e. 3PM will be represented as 03:00PM).
An example run of this program is shown below:
What time is it? 10:42PM
22:42
"""
File: 24hour_time.py
---------------------
This program asks the user for a time in
"12-hour time", with the format "11:15PM"
and converts it to "24-hour time". 11:15PM
would be 23:15.
"""
def convert_time(time):
"""
The input time is formatted as "12 hour" time (e.g. 11:45PM)
and this function returns the equivalent "24 hour" time (e.g. 23:45).
Doctests:
>>> convert_time("11:59PM")
'23:59'
>>> convert_time("12:01PM")
'12:01'
>>> convert_time("12:15AM")
'00:15'
>>> convert_time("01:15AM")
'01:15'
>>> convert_time("11:14AM")
'11:14'
"""
# Find the start of AM / PM
suffix_index = len(time) - 2
# Find the colon character
colon_index = time.find(":")
# Slice our the hour and minute portions
hour = time[:colon_index]
minute = time[colon_index + 1 : suffix_index]
# If this is a PM time
if time[suffix_index] == "P":
if int(hour) == 12:
return f"{hour}:{minute}"
return f"{int(hour) + 12}:{minute}"
else:
# This is a morning (AM) time
if int(hour) == 12:
return f"00:{minute}"
return f"{hour}:{minute}"
def main():
twelve_hour_time = input("What time is it? ")
twenty_four_hour_time = convert_time(twelve_hour_time)
print(twenty_four_hour_time)
if __name__ == "__main__":
main()
Problem 3: Average Word Length
Write a console program that asks the user for a sentence and prints out the average word-length in that sentence. You may assume the user's input is non-empty.
A sample run of this program is shown below:
Enter some text: CS106A is so awesome
The average word length is: 4.25
In this example, CS106A is of length 5, is is of length 2, so is of length 2, and awesome is of length 7. The average of those lengths is 4.25.
"""
File: average_length_word.py
-----------------------------
This program takes in user input and
computes the average length of the
individual words in the input. Words
are determined as tokens separated
by spaces.
"""
def compute_average_word_length(s):
"""
Takes in a sentence and finds the average word length.
>>> compute_average_word_length("")
0
>>> compute_average_word_length("hey mom")
3.0
>>> compute_average_word_length("CS106A is so awesome")
4.25
"""
words = s.split()
if len(words) == 0:
return 0
total_length = 0
for word in words:
total_length += len(word)
return total_length / len(words) # len(words) is the total number of words in the sentence
def main():
user_input = input("Enter a sentence: ")
avg = compute_average_word_length(user_input)
print(f"The average word length is {avg}")
if __name__ == "__main__":
main()
Problem 4: Remove Max
Write a function remove_max(lst) which takes a list of positive integers as a parameter and returns the list with the maximal integer removed. In the case that lst was originally [1, 2, 5, 3, 4], remove_max(lst) would return [1, 2, 3, 4].
Note: The input parameter lst can change over the course of this function call. Your only requirement is that the returned list has the maximal element from the original list removed. You may assume that lst only contains positive integers.
Here are sample runs of this function expressed as doctests:
def remove_max(lst):
"""
This function takes in a list of positive integers and returns
the list with the maximal element returned.
>>> remove_max([1, 2, 5, 3, 4])
[1, 2, 3, 4]
>>> remove_max([100, 3, 9])
[3, 9]
>>> remove_max([])
[]
>>> remove_max([5])
[]
"""
pass
"""
File: remove_max.py
--------------------
This program implements the function `remove_max`
that removes the maximal number from a list of
positive integers.
"""
def remove_max(lst):
"""
This function takes in a list of positive integers and returns
the list with the maximal element returned.
>>> remove_max([1, 2, 5, 3, 4])
[1, 2, 3, 4]
>>> remove_max([100, 3, 9])
[3, 9]
>>> remove_max([])
[]
>>> remove_max([5])
[]
"""
current_max = -1
for num in lst:
if num > current_max:
current_max = num
if current_max != -1:
lst.remove(current_max)
def main():
lst = [3, 8, 20, 5, 1]
remove_max(lst)
if __name__ == "__main__":
main()