Lab01 Spring23
Lab01 Spring23
Preview
Unlike DSC10, we will not be using any imported packages in the course. We have a
diverse background in terms of programming experience. Therefore, we will be
having a long but useful lab01 that prepares you to get used to Python built-in
methods and some structures you can use in future assignments! Please read every
single word in this lab! If you have any questions, please ask on ED Discussion!
Starter Files
Download lab01.zip. Inside the archive, you will find starter files for the questions in
this lab. You can't import anything to solve the problems. To unzip a file, simply just
double-click on the archive in the download folder, and it should populate a
lab01.py file. Move the lab01.py to your DSC20 folder manually.
Tip: You can comment out all questions first using “Ctrl + /” (Windows) or “Cmd +
/” (Mac). Once you finish one question, you can uncomment a new one. This way
doctests will give you a cleaner output.
Submission
By the end of this lab, you should submit the lab via Gradescope. You may submit
more than once before the deadline; only the final submission will be graded.
Logistics
Using Python
When running a Python file, you can use the options on the command line to
inspect your code further. Here are a few that will come in handy. If you want to
learn more about other Python command-line options, take a look at the
documentation.
● Disclaimer: If you are using Windows, you may need to type py, rather than
python3
● Using no command-line options will run the code in the file you provide and
return you to the command line.
>>> python3 lab01.py
● -i: The -i option runs your Python script, then opens an interactive session.
In an interactive session, you run Python code line by line and get immediate
feedback instead of running an entire file all at once.
● To exit, type exit() into the interpreter prompt. You can also use the
keyboard shortcut Ctrl-D on Linux/Mac machines or Ctrl-Z Enter on
Windows.
If you edit the Python file while running it interactively, you will need to exit
and restart the interpreter in order for those changes to take effect.
○ Using the interactive mode allows you to test individual doctests and
see their output, but you have to type or paste tests one at a time.
Most functions that you define will contain a return statement. The return
statement will give the result of some computation back to the caller of the function
and exit the function. For example, the function square below takes in a number x
and returns its square.
def square(x):
"""
>>> square(4)
16
"""
return x * x
In contrast, the print function is used to display values in the Terminal. This can
lead to some confusion between print and return because calling a function in the
Python interpreter will print out the function's return value.
However, unlike a return statement, when Python evaluates a print expression, the
function does not terminate immediately.
def what_prints():
print('Hello World!')
return 'Exiting this function.'
print('DSC20 is awesome!')
>>> what_prints()
Hello World!
'Exiting this function.'
Notice also that print will display text without the quotes, but return will
preserve the quotes. We will discuss the reason later in the quarter.
Error Messages
By now, you've probably seen a couple of error messages. They might look
intimidating, but error messages are very helpful for debugging code. The following
are some common types of errors:
Using these descriptions of error messages, you should be able to get a better idea
of what went wrong with your code. If you run into error messages, try to
identify the problem before asking for help. You can often Google unfamiliar
error messages to see if others have made similar mistakes to help you debug.
For example:
>>> square(3, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: square() takes 1 positional argument but 2 were given
Note:
● The last line of an error message tells us the type of the error. In the
example above, we have a TypeError.
● The error message tells us what we did wrong -- we gave square 2
arguments when it can only take in 1 argument. In general, the last line is
the most helpful.
● The second to last line of the error message tells us on which line the error
occurred. This helps us track down the error. In the example above,
TypeError occurred at line 1.
General Requirements:
● DO NOT IMPORT ANY PACKAGES. This includes numpy, babypandas, etc.
and this applies to ALL assignments in this class (unless specifically
instructed)
● Unless otherwise noted, you may use any Python built-in function if you know
how it works. If you’re not familiar with any function, the following are your
best friend:
1. Python’s official documentation;
2. Google: StackOverflow, w3schools, Programiz, RealPython, etc.
3. If you’re still confused, you may make an ED post.
Required Questions
In a few assignments we will take a road trip across the USA and will discover
different states and places. But first, we need to prepare for our trip.
Question 1:
You and your friends decided to rent a car but you quickly realized that it is not
cheap. The reason for it is because drivers under 25 tend to have more accidents
and accumulate more tickets than those who are older.
Write a function that takes a list of ages as positive integers and returns a boolean
(True or False) indicating whether there is at least one person who is 25 or older.
def driver_age(lst):
"""
Checks whether at least one driver is 25 or older in a given list
---
Parameters:
lst: a list of positive integers, might be empty
---
Returns True if at least one driver is 25 or older,
False otherwise
Question 2:
Now you need to find out how many drivers are 25 years old or older in your team
so that you can plan the trip better. Write a function that takes a list of ages as
positive integers and returns the number of drives whose age is 25 or older.
def over_25_counter_variable(lst):
"""
Counts how many ages are 25 or older in a given list.
---
Parameters:
lst: a list of positive integers, might be empty
---
Returns the number of drivers whose age is 25 or older.
>>> over_25_counter_variable([])
0
>>> over_25_counter_variable([12, 15])
0
>>> over_25_counter_variable([12, 25, 30])
2
>>> over_25_counter_variable([30, 15, 24])
1
"""
Question 3:
Now you need to decide who will be your team captain! Write a function that takes
in two parameters as strings: first and last name. Then your function should return
a new string by combining these two parameters. Check doctests for the exact
output.
Question 4:
Team captain decided that it’s be great to give a team a cool name. Write a function
that creates team names! Your function takes a list of names, as strings. Then it
creates a new string by adding first and last characters of each name. If a name
has one character, then add a space as the second one. Assume no name will be
empty. If the input list is empty, return an empty string.
Note: There is a difference between the list being empty and any name in the list
being empty.
def team_name(names):
"""
Creates the name for the team by putting together first and last
characters of each name. Adds a space if the input only has one
character.
---
Parameters:
names: list of names, as strings
---
Returns a team name, as a string
Question 5:
Note: In DSC 20, you have to learn how to read Python’s documentation about
built-in functions. For example, your task is to convert a list of words (as strings)
into a sentence, where there should be a separator added in between each pair of
words. If the list is empty, you should return an empty string. (Notice the given
doctest doesn’t test on this edge case, therefore it is always recommended to add
your own doctests to test for edge cases as the given doctests are always not
sufficient!)
Question 5.1:
Question 5.2:
Question 6:
You decided to make a map of your trip. You are not sure where you go yet so this
is just some practice.
Question 6.1:
Write a function that takes two parameters: a symbol (as a single-character string)
and a number of repetitions (a positive integer). Your function should return a
string that consists of given characters, repeated a given number of times.
>>> drawing("-", 4)
'----'
>>> drawing("+", 5)
'+++++'
"""
Question 6.2:
Write a function that takes two parameters: list of symbols (as characters) and a
list of repetitions (as positive integers), the lengths of these lists are the same. Your
function returns a string containing characters from the symbols list repeated the
corresponding number of times. If both lists are empty, return an empty string.
For example,
Input Output Reason
Question 7:
You have a really hard time deciding what route to take so you decided to check out
different hotels for different options. Each hotel has a rating ranging from 1 to 10
inclusively. You will stay in a hotel only if it is rated 5 or higher. For the hotels with
ratings lower than 5 you consider them to have a rating of 0.
Question 7.1:
Write a function that takes a non-empty list of actual hotel ratings and calculates
the average rating for the given list according to our definition of rating above.
Round the number to the second decimal place and return your answer.
[10, 10, 1] 6.67 Two hotels have ratings greater than 5 so we keep
their original ratings.
One hotel is below 5, so it gets a value of 0.
The average is (10 + 10 + 0)/3 = 6.6666…
Rounded to the second decimal place is 6.67
def hotel_rating_average(ratings):
"""
Finds average where numbers lower than 5 get a value of a 0
---
Parameters:
ratings: list of integers ranging from 1 to 10
---
Returns an average rounded to the second decimal place
Question 7.2:
Once you tested your function for a single hotel, you can use it now to solve a little
bit more involved problem. This time you are given a list of non-empty lists, where
each list represents a set of hotels along a route. You are also given a list of names
of your possible routes corresponding to the list of hotels. Write a function that
outputs a name of the route with the highest hotel average. You can assume that
the lengths of both lists are the same. If there is a tie, return the best route that
appears first. In case of an empty list, return “No route to choose from”. If all the
routes have average rating 0, treat 0 as the best rating and return the first route.
Hints:
● You may reuse the function from Question 7.1
● The list’s .index() might be helpful (look up the documentation!)
● Function max() might be helpful
>>> ratings = [[6, 10, 5], [10, 10, 9], [6, 6, 7]]
>>> names = ["op1", "op2", "op3"]
>>> hotel_rating_best_average(ratings, names)
'op2'
Question 8:
Your team captain decided to keep all your decisions password protected. Write a
function that takes three parameters: a string, a positive integer and a boolean.
Rules:
● If one or more inputs do not satisfy the specified type, return ‘ERROR!’.
● Reverse a given string.
● If a number is even, make it odd by adding 1
● If a number is odd, make it even by subtracting 1
● Flip the value of the boolean parameter.
Then put all these components together into a string and return it.
Hint:
● Look up: “How to check the type of a variable in Python”
● Look up: “How to reverse a string in Python”
● Look up: “How to convert an integer to a string in Python”
Submission
You need to submit lab01.py via Gradescope. Follow these steps to submit your
work.
Important Notes:
1. You may submit more than once before the deadline; only the final
submission will be graded;
2. We will be grading this lab solely based on hidden tests, so you should test
your code thoroughly by writing more test cases;
3. Unlike lab00, you should expect to see "-/10.0". You will see your score when
the grades are released;
4. You should wait for the Autograder to finish running before leaving the
site to ensure that the tests are properly run;
5. If your autograder fails to run, try to consult the Gradescope Common Errors
section on the course website before making an ED post;
6. If you have any other questions, please post to ED.
Warning: If you used Virtual Studio Code as your editor, please double check if
there are weird import statements that you don’t recognize before submitting. Make
sure to remove these as they will fail Gradescope runs!