Skip to main content

Section 1.16 HW8 Practice

- while loops
- sets

Exercises Exercises

1. Build Num List.

Write a function, build_num_list, that has no parameters; the function reads integersfrom standard input,Β one at a time, stopping when a 0 is read.
Each number read, except the final 0, is appended to a new list (initially empty) created by the function. The function should return the accumulated list.
Hint:Use a while loop.
For example:
Test Input Result
build_num_list()
55
20
20
0
[55, 20, 20]
build_num_list()
0
1
1

2. Get Positive Input.

The function get_pos_input takes no parameters. Instead, it reads integers one at a time from standard input until a positive integer is read.Β Once a positive integer has been read, that integer is returned.
Add Python code to implement the get_pos_input function.
Hint: Use a while loop.
For example:
Test Input Result
get_pos_input()
-3
-352034
-42342
-42455222
17
25
3
-2
get_pos_input()
0
12

3. Sum Nonnegative Input.

The function sum_nonneg_input takes no parameters. Instead, it reads integersone at a time from standard input, maintaining a running sum of numbers entered, until a negative integer is read.Β Once a negative integer is read, the function returns the current sum. Note: the negative number is not included in the sum.
Write Python code to implement the sum_nonneg_input function.
Hint: Use a while loop.
For example:
Test Input Result
sum_nonneg_input()
3
35
42
-17
25
3
-2

4. Max Float Input.

The function max_float_input takes no parameters. Instead, it reads strings from standard input, one at a time, until the string "stop" is read.
  • If the string is not "stop", the string is converted to a floating point value (type float) and compared to the largest previous float value entered (if any).
  • Otherwise, the function stops and returns the largest floating point value that was entered so far.
Note: If the firststring entered is "stop", the function simply returns the Python object None.
Add Python code to implement the max_float_input function.
Hint: Use a while loop.
For example:
Test Input Result
max_float_input()
2938.3
294184.2
2982.003
3
-23482498.5
stop
294184.2
max_float_input()
stop
None

5. Multiplication Quiz.

The function multiplication_quiz(a, b) takes two integer parameters, a and b. The function prompts the user (just once) to enter the product of a times b, and uses a loop to keep checking the input for the correct answer.
The function keeps a count of how many attempts were needed to get the right answer.Β When the correct answer is read, the function returns the count.
Write the code needed to implement this function.
Hint: Use a while loop.
Note: You should assume that every input can be converted to an integer.
For example:
Test Input Result
multiplication_quiz(12, 7)
17
9
84
83
99
Printout: What is 12 times 7?
Returns: 3
multiplication_quiz(2, 3)
10
9
8
7
6
5
4
Printout: What is 2 times 3?
Returns: 5

6. List Has Repeat (using set).

Write a definition for the function has_repeat(L). The parameter L is a list of immutable items. The function returns True if L has at least one repeated item, otherwise it returns False.
Hint: If the set of items in L has a shorter length than L itself, return True; otherwise, return False.
For example:
Test Result
has_repeat(list('hello'))
True
has_repeat(list('Maybe'))
False

7. Number of Distinct Elements (using set).

Implement the function num_distinct_elements(C). The function takes the parameter C, a collection of type list, string, or tuple, and returns the number of distinct items in C. For example, if C is the list [1, 2, 3, 3, 2, 1, 2, 3, 3, 10], the return value would be 4 (since 1, 2, 3, 10 are the "distinct" elements).
HINT: The body of the function requires just one or two lines of code.
NOTE: Use set in your code.
For example:
Test Result
C = [1, 2, 3, 2, 2, 2, 1, 1, 1, 1]
num_distinct_elements(C)
C = "She sells sea shells by the sea shore."
num_distinct_elements(C)
C = ('b', 'a', 'b', 'b', 'l', 'e')
num_distinct_elements(C)

8. Get Distinct From Nested.

Write a definition for the function get_distinct_from_nested(C), where the parameter C is a sequence of sequences (e.g.,Β  a list of strings or a list of lists of integers). The job of the function is to use set operations to find and return the sortedlist of unique elements in the nested collection C.
Hint: If S is a set, sorted(S) is a sorted list of the elements in S.
Another Hint: Use set union to accumulate the set S of distinct inner elements using a single for loop:
  • iterate seqover the top-level elements of C
  • use S = S.union(seq) to update S with additional items from seq
This only requires about 5 lines of code.
For example:
Test Result
C = ['Java', 'Jumble', 'BlackJack']
get_distinct_from_nested(C)
['B', 'J', 'a', 'b', 'c', 'e',
 'k', 'l', 'm', 'u', 'v']
C = ['app', 'ban', 'can', 'def']
get_distinct_from_nested(C)
['a', 'b', 'c', 'd', 'e',
 'f', 'n', 'p']
C = ['!', '!!', '!!!', '!!!!', '!!!!!']
get_distinct_from_nested(C)
['!']

9. String Intersection.

Write the definition for a function string_intersection(str1, str2), which takes two string parameters and returns a sorted list of the characters the two strings have in common.
Hint: Use set intersection and the sorted() function.
For example:
Test Result
string_intersection("cats", "caterpillar")
['a', 'c', 't']
string_intersection("cats", "dogs")
['s']
string_intersection("banana", "xylem")

10. Write a Program to Check for Anagrams.

Write the code to read two strings (str1, str2) from standard input and print a message regarding whether or not the strings are anagrams (rearrangements) of each other.
Hint: Compare sorted lists of characters for the two strings.
In addition, if the strings are NOT anagrams of each other, give one of the following explanations: "They do not have the same character sets.", or "They do not have the same character frequencies."
For example, "DOGS" and "GODS" are anagrams. "DOGS" and "HANOVER" do not have the same character sets, while "HANOVER" and "HANOOOVER" do not have the same character frequencies.
Use set operations to determine if two non-anagrams have the same character set; if they do share the same set of characters, then you may conclude that their character frequencies are the only difference.
Your code might be about 12 lines long.
For example:
Input Result
pizzzzzza
piizzaaaa
pizzzzzza and piizzaaaa are NOT anagrams.
They do not have the same character frequencies.
pizza
pasta
pizza and pasta are NOT anagrams.
They do not have the same character sets.
maps
spam
maps and spam are anagrams!
You have attempted of activities on this page.