0% found this document useful (0 votes)
23 views

Lab01 Spring23

Uploaded by

acaliz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Lab01 Spring23

Uploaded by

acaliz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Lab 01: Functions, Conditionals, Loops

Due: Monday, April 10th, 11:59pm

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.

>>> python3 -i lab01.py

>>> concat_str_1(['Welcome', 'to', 'DSC', '20!'])


'Welcome to DSC 20!'

○ 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.

● -m doctest: Runs all doctests in a particular file. Doctests are surrounded by


triple quotes (""") within functions. Each test consists of >>> followed by
some Python code and the expected output. We have provided doctests for
you in the starter code, and you may add additional doctests if you wish.
>>> python3 -m doctest lab01.py

return and print inside a function

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

When Python executes a return statement, the function terminates immediately. If


Python reaches the end of the function body without executing a return statement,
it will automatically return None.

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:

Error Types Descriptions

SyntaxError Contained improper syntax (e.g.


missing a colon after an if statement or
forgetting to close parentheses/quotes)

IndentationError Contained improper indentation (e.g.


inconsistent indentation of a function
body)

TypeError Attempted operation on incompatible


types (e.g. trying to add a function and
a number) or called function with the
wrong number of arguments

ZeroDivisionError Attempted division by zero

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

>>> driver_age([19, 22, 21])


False
>>> driver_age([19, 23, 15, 27])
True
>>> driver_age([])
False
"""

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.

def team_captain(first_name, last_name):


"""
Concatenates the string parameters into the output string.
---
Parameters:
first_name: first name, as a string
last_name: last name, as a string
---
Returns a string who is a team's captain

>>> team_captain("Marina", "Langlois")


'Team captain is Marina Langlois'
>>> team_captain("Marina", "")
'Team captain is Marina '
>>> team_captain("the", "best")
'Team captain is the best'
"""

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

>>> names = ["Marina", "J", "Mike"]


>>> team_name(names)
'MaJ Me'
>>> names = ["Sheldon", "Leonard", "Raj", "Howard"]
>>> team_name(names)
'SnLdRjHd'
>>> names = ["Y", "J", "B"]
>>> team_name(names)
'Y J B '
"""

Question 5:

Sometimes it is motivating to have a slogan to keep your spirits up :) Write a function


that helps you to create a slogan for the trip. It takes two parameters: a list of words
and a single character, separator. Then it returns a string that concatenates the words
using the separator. If the list of words is empty, return an empty string.

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!)

Hint: There are two usual ways to do this:


● One is through string concatenation, which starts with an empty string, and
concatenates (add) each string in the list together.
● Another way to achieve the same result is to use the join() function.

You should use string concatenation in part 1 (team_slogan_concat) and join()


function in part 2 (team_slogan_join).

Question 5.1:

def team_slogan_concat(words, separator):


"""
Creates a slogan from the words, adding a separator between them.
---
Parameters:
words: list of words, as strings
separator: single character
---
Returns a string

>>> words = ["Let", "it", "be", "fun"]


>>> team_slogan_concat(words, " ")
'Let it be fun'
>>> words = ["Stay", "focused", "stay", "cool"]
>>> team_slogan_concat(words, "-")
'Stay-focused-stay-cool'
"""

Question 5.2:

def team_slogan_join(words, separator):


"""
Creates a slogan from the words, adding a separator between them.
---
Parameters:
words: list of words, as strings
separator: single character
---
Returns a string

>>> words = ["Let", "it", "be", "fun"]


>>> team_slogan_join(words, " ")
'Let it be fun'
>>> words = ["Stay", "focused", "stay", "cool"]
>>> team_slogan_join(words, "-")
'Stay-focused-stay-cool'
"""

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.

def drawing(symbol, repeat):


"""
Creates a string of symbols
---
Parameters:
symbol: a single character
repeat: positive integer
---
Returns a string of symbols 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

['-', '+'], [4, 5] ----+++++ ‘-’ is repeated 4 times, ‘+’ is repeated 5


times and everything is put together.

def drawing_longer(symbols, repeats):


"""
Creates a string of symbols
---
Parameters:
symbols: a list of single characters
repeat: a list of positive integers, has the same length
as symbols
---
Returns a string of symbols repeated a corresponding number of
times.

>>> drawing_longer(['-', '+'], [4, 5])


'----+++++'
"""

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.

Hint: Use round() built-in function.

Input Output Reason

[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

>>> hotel_rating_average([10, 10, 10])


10.0
>>> hotel_rating_average([10, 10, 1])
6.67
>>> hotel_rating_average([3, 2, 1])
0.0
"""

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

def hotel_rating_best_average(ratings, names):


"""
Finds the best route name based on the hotel averages
---
Parameters:
ratings: list of lists, where each list contains integers
ranging from 1 to 10
names: list of lists, where each list contains route names
---
Returns the best route name based on the hotel averages
as a string

>>> ratings = [[1, 10, 5], [4, 6, 9]]


>>> names = ["op1", "op2"]
>>> hotel_rating_best_average(ratings, names)
'op1'

>>> ratings = [[6, 10, 5], [10, 10, 9], [6, 6, 7]]
>>> names = ["op1", "op2", "op3"]
>>> hotel_rating_best_average(ratings, names)
'op2'

>>> hotel_rating_best_average([], [])


'No route to choose from'
"""

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.

Input Output Reason

"trip", "is", True 'ERROR!' The second parameter is not an integer

"car", 21, True 'rac20False' “car” is reversed: “rac”


21 is odd, we subtracted 1 to make it even
True become False
Then ‘rac’, 20, False were put in a string

def password(text, number, boolean):


"""
Creates a password based on the given parameters:
text is reversed, numbers becomes either even or odd, boolean
value is flipped
---
Parameters:
text: a string
number: an integer
boolean: a boolean value
---
Returns a password by adding altered components to the string.

>>> password("trip", "is", True)


'ERROR!'
>>> password(17, "is", True)
'ERROR!'
>>> password("trip", 18, 20)
'ERROR!'
>>> password("trip", 18, False)
'pirt19True'
>>> password("car", 21, True)
'rac20False'
"""

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”

Congratulations! You are done with Lab01 :)

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!

You might also like