Python Lesson 6_reviewHW(Stani)
Python Lesson 6: Review and Homework
In this lesson, we will review and practice various Python programming concepts, including functions, loops, and conditional statements. We will also work on several homework exercises that will help us improve our coding skills.
Between Extremes
The first exercise is to write a function that takes an array of numbers as input and returns the difference between the largest and smallest values. This function is called between_extremes
.
def between_extremes(numbers):
if not numbers or len(numbers)==1:
return 0
return max(numbers)-min(numbers)
The function works by first checking if the input array is empty or contains only one element. If so, it returns 0, since there is no difference between the largest and smallest values. Otherwise, it returns the difference between the maximum and minimum values in the array.
Let's test the function with an example:
numbers = [23, 3, 19, 21, 16]
print(between_extremes(numbers))
This should output 20
, which is the difference between the largest and smallest values in the array.
Sum of Even Numbers
The next exercise is to write a function that takes a sequence of numbers as input and returns the sum of the even values. This function is called sum_even_numbers
.
def sum_even_numbers(seq):
if not seq:
return 0
return sum(list(filter(lambda x: x % 2 == 0, seq)))
The function works by first checking if the input sequence is empty. If so, it returns 0, since there are no even values to sum. Otherwise, it uses the filter
function to select only the even values from the sequence, and then uses the sum
function to calculate their sum.
Let's test the function with an example:
numbers = [4, 3, 1, 2, 5, 10, 6, 7, 9, 8]
print(sum_even_numbers(numbers))
This should output 36
, which is the sum of the even values in the array.
Largest Elements
The next exercise is to write a function that takes a list of numbers and an integer n
as input, and returns the top n
elements from the list. This function is called largest
.
def largest(n, xs):
new_arr = sorted(xs)
if n==0:
return []
return new_arr[-n:]
The function works by first sorting the input list in ascending order. If n
is 0, it returns an empty list, since there are no elements to return. Otherwise, it returns the last n
elements from the sorted list, which are the largest elements.
Let's test the function with an example:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(largest(3, numbers))
This should output [9, 6, 5]
, which are the top 3 elements from the list.
Breaking Down Money
The next exercise is to write a function that takes an integer amount of money as input and returns a list of the smallest number of bills as possible. This function is called give_change
.
def give_change(amount):
bills = [1, 5, 10, 20, 50, 100]
res = [0] * len(bills)
for i in range(len(bills)-1,-1,-1):
res[i] = amount // bills[i]
amount %= bills[i]
return tuple(res)
The function works by first initializing a list of zeros with the same length as the list of bills. It then iterates over the list of bills in reverse order, dividing the amount by each bill and updating the corresponding element in the result list. Finally, it returns the result list as a tuple.
Let's test the function with an example:
print(give_change(365))
This should output (1, 1, 1, 0, 1, 3)
, which is the smallest number of bills as possible to make up the amount of $365.
Consecutive Numbers
The next exercise is to write a function that takes an array of unique integers as input and returns the minimum number of integers needed to make the values of the array consecutive from the lowest number to the highest number. This function is called consecutive
.
def consecutive(arr):
if not arr:
return 0
new_arr = sorted(arr)
for i in range(min(arr)+1,max(arr)):
new_arr.append(i)
return len(set(new_arr))-len(arr)
The function works by first checking if the input array is empty. If so, it returns 0, since there are no integers to make consecutive. Otherwise, it sorts the input array and appends all missing integers to make the array consecutive. Finally, it returns the difference between the length of the new array and the length of the original array.
Let's test the function with an example:
print(consecutive([1, 3, 5, 7, 9]))
This should output 0
, since the input array is already consecutive.
Trimming a String
The next exercise is to write a function that takes a string and an integer as input, and returns the string trimmed to the specified length. If the string is longer than the specified length, it should be truncated and end with "...". This function is called trim
.
def trim(phrase, size):
if len(phrase) <= size:
return phrase
elif size <= 3:
return phrase[:size] + '...'
else:
return phrase[:size - 3] + '...'
The function works by first checking if the length of the input string is less than or equal to the specified length. If so, it returns the original string. Otherwise, it checks if the specified length is less than or equal to 3. If so, it returns the string truncated to the specified length and ending with "...". Otherwise, it returns the string truncated to the specified length minus 3 and ending with "...".
Let's test the function with an example:
print(trim("Creating kata is fun", 14))
This should output "Creating ka...", which is the input string trimmed to the specified length.
Find All Non-Consecutive Numbers
The final exercise is to write a function that takes an array of integers as input and returns a list of all non-consecutive numbers. This function is called all_non_consecutive
.
def all_non_consecutive(arr):
lst=[]
for i,n in enumerate(arr[1::]):
if n - arr[i]!=1:
lst.append({'i':i+1, 'n':n})
return lst
The function works by iterating over the input array starting from the second element, and checking if the difference between the current element and the previous element is not equal to 1. If so, it appends a dictionary containing the index and value of the current element to the result list.
Let's test the function with an example:
print(all_non_consecutive([1, 2, 3, 5, 6, 7, 9, 10]))
This should output [{'i': 2, 'n': 5}, {'i': 5, 'n': 9}]
, which are the non-consecutive numbers in the input array.
Python Lesson 6: Review and Homework Q&A
In this article, we will answer some common questions related to the Python programming concepts covered in the previous lesson.
Q: What is the difference between max()
and min()
functions in Python?
A: The max()
function returns the largest item in an iterable or the largest of two or more arguments. The min()
function returns the smallest item in an iterable or the smallest of two or more arguments.
Q: How do I use the filter()
function in Python?
A: The filter()
function takes a function and an iterable as arguments and returns an iterator that filters the elements of the iterable based on the function. For example, filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])
returns an iterator that yields only the even numbers from the list.
Q: What is the difference between sorted()
and list.sort()
functions in Python?
A: The sorted()
function returns a new sorted list from the elements of any sequence. The list.sort()
function sorts the elements of a list in place and returns the list.
Q: How do I use the enumerate()
function in Python?
A: The enumerate()
function takes an iterable as an argument and returns an iterator that yields tuples containing the index and value of each element in the iterable. For example, enumerate([1, 2, 3, 4, 5])
returns an iterator that yields tuples like (0, 1)
, (1, 2)
, (2, 3)
, (3, 4)
, (4, 5)
.
Q: What is the difference between set()
and list()
functions in Python?
A: The set()
function returns a new set from the elements of any iterable. The list()
function returns a new list from the elements of any iterable.
Q: How do I use the tuple()
function in Python?
A: The tuple()
function takes an iterable as an argument and returns a new tuple from the elements of the iterable. For example, tuple([1, 2, 3, 4, 5])
returns the tuple (1, 2, 3, 4, 5)
.
Q: What is the difference between +
and +=
operators in Python?
A: The +
operator returns a new string that is the concatenation of two strings. The +=
operator modifies the original string by appending another string to it.
Q: How do I use the join()
function in Python?
A: The join()
function takes an iterable of strings as an argument and returns a new string that is the concatenation of all the strings in the iterable, separated by a specified separator.
Q: What is the difference between split()
and splitlines()
functions in Python?
A: The split()
function takes a string and a separator as arguments and returns a list of substrings that are the result of splitting the string at the separator. The splitlines()
function takes a string as an argument and returns a list of substrings that are the result of splitting the string at newline characters.
Q: How do I use the strip()
function in Python?
A: The strip()
function takes a string as an argument and returns a new string that is the result of removing leading and trailing whitespace from the string.
Q: What is the difference between upper()
and lower()
functions in Python?
A: The upper()
function takes a string as an argument and returns a new string that is the result of converting all characters in the string to uppercase. The lower()
function takes a string as an argument and returns a new string that is the result of converting all characters in the string to lowercase.
Q: How do I use the replace()
function in Python?
A: The replace()
function takes a string, a substring to replace, and a replacement string as arguments and returns a new string that is the result of replacing all occurrences of the substring with the replacement string.
Q: What is the difference between len()
and count()
functions in Python?
A: The len()
function takes an iterable as an argument and returns the number of elements in the iterable. The count()
function takes a string and a substring as arguments and returns the number of occurrences of the substring in the string.
Q: How do I use the find()
function in Python?
A: The find()
function takes a string and a substring as arguments and returns the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.
Q: What is the difference between index()
and find()
functions in Python?
A: The index()
function takes a string and a substring as arguments and returns the index of the first occurrence of the substring in the string. If the substring is not found, it raises a ValueError
. The find()
function takes a string and a substring as arguments and returns the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.
Q: How do I use the split()
function with a separator in Python?
A: The split()
function takes a string and a separator as arguments and returns a list of substrings that are the result of splitting the string at the separator. For example, split(" ", "hello world")
returns the list ["hello", "world"]
.
Q: What is the difference between strip()
and lstrip()
functions in Python?
A: The strip()
function takes a string as an argument and returns a new string that is the result of removing leading and trailing whitespace from the string. The lstrip()
function takes a string as an argument and returns a new string that is the result of removing leading whitespace from the string.
Q: How do I use the rstrip()
function in Python?
A: The rstrip()
function takes a string as an argument and returns a new string that is the result of removing trailing whitespace from the string.
Q: What is the difference between upper()
and lower()
functions in Python?
A: The upper()
function takes a string as an argument and returns a new string that is the result of converting all characters in the string to uppercase. The lower()
function takes a string as an argument and returns a new string that is the result of converting all characters in the string to lowercase.
Q: How do I use the replace()
function in Python?
A: The replace()
function takes a string, a substring to replace, and a replacement string as arguments and returns a new string that is the result of replacing all occurrences of the substring with the replacement string.
Q: What is the difference between len()
and count()
functions in Python?
A: The len()
function takes an iterable as an argument and returns the number of elements in the iterable. The count()
function takes a string and a substring as arguments and returns the number of occurrences of the substring in the string.
Q: How do I use the find()
function in Python?
A: The find()
function takes a string and a substring as arguments and returns the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.
Q: What is the difference between index()
and find()
functions in Python?
A: The index()
function takes a string and a substring as arguments and returns the index of the first occurrence of the substring in the string. If the substring is not found, it raises a ValueError
. The find()
function takes a string and a substring as arguments and returns the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.
Q: How do I use the split()
function with a separator in Python?
A: The split()
function takes a string and a separator as arguments and returns a list of substrings that are the result of splitting the string at the separator. For example, split(" ", "hello world")
returns the list ["hello", "world"]
.
Q: What is the difference between strip()
and lstrip()
functions in Python?
A: The strip()
function takes a string as an argument and returns a new string that is the result of removing leading and trailing whitespace from the string. The lstrip()
function takes a string as an argument and returns a new string that is the result of removing leading whitespace from the string.
Q: How do I use the rstrip()
function in Python?
A: The rstrip()
function takes a string as an argument and returns a new string that is the result of removing trailing whitespace from the string.
Q: What is the difference between upper()
and lower()
functions in Python?
A: The upper()
function takes a string as an argument and returns a new string that is the result of converting all characters in the string to uppercase. The lower()
function takes a string as an argument and returns a new string that is the result of converting all characters in the string to lowercase.
Q: How do I use the replace()
function in Python?
A: The replace()
function takes a string, a substring to replace, and a replacement string as arguments and returns a new string that is the result of replacing all occurrences of the substring with the replacement string.
**Q: What is the difference between len()
and count()