def filter_list(values, min_value=None, max_value=None):
"""Filters a list of numbers to keep only the ones between one or two thresholds.
You need to set at least one of min_value or max_value!
Parameters
----------
values : list
a list of numbers (floats or ints)
min_value : float or int, optional
the minimum threshold to filter the data (inclusive)
max_value : float or int, optional
the maximum threshold to filter the data (inclusive)
Examples
--------
>>> a = [1, 3, 4, 2.2]
>>> filter_list(a, min_value=2)
[3, 4, 2.2]
>>> a # a is unchanged
[1, 3, 4, 2.2]
>>> filter_list(a, max_value=3)
[1, 3, 2.2]
>>> filter_list(a, min_value=2, max_value=3)
[3, 2.2]
>>> filter_list([1, 2, 3, 4])
Traceback (most recent call last):
...
ValueError: Need to set at least one of min_value or max_value!
"""
if min_value is None and max_value is None:
raise ValueError('Need to set at least one of min_value or max_value!')
output = []
# <your own code here>
return outputAssignment #04
Unit 4
Until the next session, study the provided lecture material and solve the following exercises.
Go back to the program you wrote for the previous exercise #03-04. Make your program code as organised and easy-to-read as possible. To do so, pack the language classification that selects the welcome message into a function welcome_message(name, language) that you use in the main part of your script.
years2days()
Today we coded a function years2days().
- So far, the error message (“traceback”) that we get when providing the function with a different data type other than
intorfloatis very cryptic and a user might not learn from the message what they did wrong or why the function fails. Modify the function, so that it prints a meaningful message when the user tries to executeyears2days("ten"). - So far,
n_leapyearsis simply added to the conversion result. The function would happily execute the statementyears2days(1, n_leapyears=2), which is obviously meaningless. Implement a check that prints a message and does not execute the conversion ifn_leapyearsis more thanyears.
Below, I pasted the skeleton of a function I want you to code. Most importantly, I provide you with the documentation of the function. We read function documentation in the past (using help()), and we learned how to write the docstrings for our own functions, too. Here, you see a more comprehensive example of a function documentation. Carefully read the documentation and try to understand what the function is supposed to do. The examples help illustrate the information provided by the docstring and the parameter definitions.
- None: We have not yet talked about the
Nonekeyword, but if you consult the Internet you will quickly see that it is easy to understand. - So far, we have used the
print()function to craft (“error”) messages to the user. In the function below, I demonstrate you how a “proper” error can be raised.
- You will have to iterate through the provided list of values …
- … and use a well-crafted conditional expression to decide which values …
- … need to be ‘added’ to the output list (find the right function yourself in our classroom material!)
Notebook
For the remaining two exercises, use the opportunity of solving the exercises in a notebook to familiarize yourself with the workflow of creating and deleting cells, writing markdown, and running code in a notebook. Download the file 04_some_tasks.ipynb to find a notebook that I prepared for you.
Code a function that accepts two arguments, first an arbitrary word or sentence (type str, e.g., "energy efficiency") then a character (also str, e.g., "e"). The function should return an integer of how many times the character appeared in the sentence. Write a comprehensive docstring for the function and test whether it performs as expected with a few test cases.
Consider this:
Code a function that accepts an arbitrary sentence as input and returns a list of strings containing the individual words, just like the example above. However, let’s imagine the .split() method does not exist and you have to find another way of achieving this. Does your function return the same result as the split method?
execute: eval: false echo: true highlight-style: github —
Solutions
def welcome_message(name, language):
"""
Generate a welcome message based on the chosen language.
"""
if language == "EN":
return f"How's it, {name}!"
elif language == "DE":
return f"Hallo, {name}!"
elif language == "XX":
return f"Greetings, {name}!"
else:
return "Unsupported language. Please choose EN, DE, or XX."
# Prompt the user for their name
name = input("Enter your name: ")
# Prompt the user for their preferred language
language = input("Enter your language (EN, DE, XX): ")
# Call the welcome_message function to generate the welcome message
message = welcome_message(name, language)
# Print the welcome message
print(message)years2days()
# Note that this solution implements a TypeError (instead of a simple print message),
# which we encountered later in this unit
def years2days(years, n_leapyears=0):
"""
Convert Years to Days
This function takes a number of years as input and calculates
the equivalent number of days.
"""
# Ensure meaningful parameter types
try:
years = float(years)
n_leapyears = int(n_leapyears)
except:
raise TypeError("years needs to be numeric, and n_leapyears needs to be an integer!")
# Ensure meaningful leap year logic
if n_leapyears > years:
print("`n_leapyears` cannot meaningfully be greater than `years`! Returning without result.")
return
else:
# finally, compute the conversion
days = (years * 365) + n_leapyears
return daysdef filter_list(values, min_value=None, max_value=None):
"""Filters a list of numbers to keep only the ones between one or two thresholds.
You need to set at least one of min_value or max_value!
Parameters
----------
values : list
a list of numbers (floats or ints)
min_value : float or int, optional
the minimum threshold to filter the data (inclusive)
max_value : float or int, optional
the maximum threshold to filter the data (inclusive)
Examples
--------
>>> a = [1, 3, 4, 2.2]
>>> filter_list(a, min_value=2)
[3, 4, 2.2]
>>> a # a is unchanged
[1, 3, 4, 2.2]
>>> filter_list(a, max_value=3)
[1, 3, 2.2]
>>> filter_list(a, min_value=2, max_value=3)
[3, 2.2]
>>> filter_list([1, 2, 3, 4])
Traceback (most recent call last):
...
ValueError: Need to set at least one of min_value or max_value!
"""
# ensure at least one filter threshold has been set
if min_value is None and max_value is None:
raise ValueError('Need to set at least one of min_value or max_value!')
output = []
# loop through all elements of the list
for element in values:
# check if the element passes the minimum and maximum conditions (if specified)
passes_min = (min_value is None) or (element >= min_value)
passes_max = (max_value is None) or (element <= max_value)
# append numbers that satisfy both conditions to the output list
if passes_min and passes_max:
output.append(element)
return outputThe first implementation of this function is great and does what we wanted it to do. In case you are interested to make this function more “waterproof”, have a look at the second version of the same function below. In this implementation I use strategies that you know already to enforce correct data types and make the function fail if the user provides input that the function was not designed for.
When checking for the data type of min_value and max_value, I use the function isinstance(). Feel free to read up on it. Conceptually, my check does something like (type(min_value) == int) or (type(min_value) == float).
def filter_list(values, min_value=None, max_value=None):
"""Filters a list of numbers to keep only the ones between one or two thresholds.
You need to set at least one of min_value or max_value!
Parameters
----------
values : list
a list of numbers (floats or ints)
min_value : float or int, optional
the minimum threshold to filter the data (inclusive)
max_value : float or int, optional
the maximum threshold to filter the data (inclusive)
Examples
--------
>>> a = [1, 3, 4, 2.2]
>>> filter_list(a, min_value=2)
[3, 4, 2.2]
>>> a # a is unchanged
[1, 3, 4, 2.2]
>>> filter_list(a, max_value=3)
[1, 3, 2.2]
>>> filter_list(a, min_value=2, max_value=3)
[3, 2.2]
>>> filter_list([1, 2, 3, 4])
Traceback (most recent call last):
...
ValueError: Need to set at least one of min_value or max_value!
>>> filter_list([1, 2, 3, "string"], min_value=2)
Traceback (most recent call last):
...
TypeError: All list elements need to be of type int or float!
>>> filter_list([1, 2, 3, 4], min_value="eins")
Traceback (most recent call last):
...
TypeError: min_value needs to be of type int or float!
"""
# ensure at least one filter threshold has been set
if min_value is None and max_value is None:
raise ValueError('Need to set at least one of min_value or max_value!')
# enforce correct data types of min/max_value
if min_value is not None and not isinstance(min_value, (int, float)):
raise TypeError("min_value needs to be of type int or float!")
if max_value is not None and not isinstance(max_value, (int, float)):
raise TypeError("max_value needs to be of type int or float!")
output = []
# loop through all elements of the list
for element in values:
# enforce correct data types of list elements
try:
element = float(element)
except:
raise TypeError("All list elements need to be of type int or float!")
# check if the element passes the minimum and maximum conditions (if specified)
passes_min = (min_value is None) or (element >= min_value)
passes_max = (max_value is None) or (element <= max_value)
# append numbers that satisfy both conditions to the output list
if passes_min and passes_max:
output.append(element)
return outputdef count_character(statement, character):
"""
Count the occurrences of a specific character in a given statement.
Parameters:
-----------
statement : str
The word or sentence in which to search for the character.
character : str
The character to count. Must be a single character.
Returns:
--------
int
The number of times the character appears in the statement.
Raises:
-------
ValueError
If `character` is not a single character.
Examples:
---------
>>> count_character("energy efficiency", "e")
4
>>> count_character("hello world", "o")
2
>>> count_character("Python programming", "m")
2
"""
if len(character) != 1:
raise ValueError("The `character` argument must be a single character.")
count = 0
for char in statement:
if char == character:
count += 1
return countdef split_sentence(sentence):
"""
Splits a given sentence into a list of words based on spaces.
Parameters:
-----------
sentence : str
The sentence to split. Must be a string.
Returns:
--------
list
A list of words extracted from the sentence.
Raises:
-------
ValueError
If `sentence` is not a string.
Examples:
---------
>>> split_sentence("Hello world!")
['Hello', 'world!']
>>> split_sentence("SingleWord")
['SingleWord']
>>> split_sentence(" ")
[]
"""
if not type(sentence) is str:
raise ValueError("`sentence` needs to be a string!")
word_list = []
word = ""
for i, char in enumerate(sentence):
if char == " ":
if word:
word_list.append(word)
word = ""
else:
word = f"{word}{char}"
if i == len(sentence)-1 and word:
word_list.append(word)
return word_listAlternatively, you can download the notebook that I solved for you (for the last two exercises).