Slide 1: Introduction
Today, we are going to walk through six Python functions that perform various tasks involving integers, lists, and text files. Each function demonstrates different ways to manipulate data, including string formatting, list processing, and reading from files.
Slide 2: Function 1 - f1(m, n)
The first function, f1, generates a simple string pattern. Here’s how it works:
1 | def f1(m, n): |
- The function takes two integer arguments, m and n. Both are assumed to be at least 0.
- It constructs a pattern consisting of vertical bars (|) enclosing underscores (_), repeated m times. The number of underscores between the bars is determined by n.
- For example, if m = 3 and n = 4, the output would be:
1
|____||____||____|
Slide 3: Function 2 - f2(n)
The second function, f2, creates a square pattern made up of digits. Here’s the function:
1 | def f2(n): |
- This function takes an integer n and generates a square of n rows, where each row contains the digit n repeated n times.
- The pattern ends with a newline after each row.
- For example, if n = 3, the output will be:
1
2
3333
333
333
Slide 4: Function 3 - f3(L)
Next, we have f3, which works on a list of integers:
1 | def f3(L): |
- This function removes elements from the start of the list until the first two consecutive elements are in non-decreasing order.
- The process continues as long as the first element is strictly greater than the second element.
- Once the list is stable, it prints the modified list.
- For example, if L = [9, 8, 7, 10], the function will remove 9, 8, and 7, leaving [10].
Slide 5: Function 4 - f4(D, n)
The fourth function, f4, works with dictionaries:
1 | def f4(D, n): |
- This function takes a dictionary D and an integer n. It generates a strictly increasing sequence of integers based on the relationships defined in the dictionary.
- Starting from n, it appends D[n], D[D[n]], and so on to the list, as long as each subsequent value is greater than the previous one.
- For example, if D = {1: 2, 2: 3, 3: 5} and n = 1, the function will return [1, 2, 3, 5].
Slide 6: Function 5 - f5(filename)
The fifth function, f5, reads from a file and processes each line:
1 | def f5(filename): |
- This function reads a text file, where each line consists of a name and a count separated by a comma.
- The function multiplies the count by 1000 and prints the result in the format: “X people named Y”.
- For example, if the file contains a line “John,5”, it will print:
1
5000 people named John
Slide 7: Function 6 - f6(filename)
The final function, f6, also reads from a text file, but with a different format:
1 | def f6(filename): |
- This function reads lines that contain an integer followed by a symbol (e.g., “5 *”).
- It multiplies the symbol by the integer and prints the result.
- For example, if the file contains the line “3 # “, the function will print:
1
###