Skip to main content

Section 1.11 HW6

Lists

Exercises Exercises

1. Front Two.

Given a list, L, the function front_two creates a new list of length 2 out of the first two items in L as follows:
  • In the new list, the second item becomes the first item, and the first item becomes the second.
  • If L contains only one item, the first item in the new list should be the value None.
  • If L is empty, both items in the new list should be value None.
  • The function returns the new list.
For example:
Test Result
front_two(['a', 'b', 'c', 'd'])
['b', 'a']
front_to([])
[None, None]
front_two([5, 2])
[2, 5]
front_two([7])
[None, 7]

2. Print Reverse.

The function print_reverse takes one parameter, L, which is a list. Β The function then prints the items in the list in reverse order, one item per line, WITHOUT changing the value of L.
Write the function definition.
Note 1: This function does NOT get anything from standard input.
Note 2: This function DOES, however, print to standard output.
Note 3: You should NOT return anything from this function (let it return Noneby default).
For example:
Test Result
print_reverse(['apple', 'banana', 'cherry'])
cherry
banana
apple
print_reverse(['happy'])
happy
print_reverse([])

3. Sum Evens.

The function sum_evens takes a list of integers and returns the sum of all the even integers in the list.
For example:
Test Result
sum_evens([1, 5, 2, 5, 3, 5, 4])
sum_evens([5, 5, -5, -5])
sum_evens([16, 24, 30])

4. Count Contains ’og’.

The function count_contains_ogtakes a list of strings and returns how many strings in the list contain ’og’ / ’OG’ / ’oG’ / ’Og’ (check for ’og’, ignoring case).
Hint: Use the sequence membership operator in to help you check for ’og’ in the individual strings. Create a lower-cased version of the string (lower), then use the in operator.
For example:
Test Result
count_contains_og(['cat', 'dog', 'FROG', 'monkey'])
count_contains_og(["X", "x"])
count_contains_og(["Doggie"])

5. First Negative.

Define the function first_negative(nums) takes one parameter. nums, a possibly empty list of numbers. The function then returns the first negative item in numlist.
Note: if there are NO negative numbers in the list, the function returns the Python object None.
For example:
Test Result
first_negative([1, 3, 9, -2])
first_negative([1, 3, 9, 2])
None
first_negative([1, -3, -9, -2])
first_negative([0, -1.1, 0, -2.2, 0, -3.3, 0])
-1.1

6. Square Nums 1.

Define the function square_nums which takes a list of numbers, numlist, and returns a NEW list containing the squares of the numbers in the original list.Β  The given list, numlist, should not be changed.
Note: Use the accumulator pattern and newlist.append(item) to solve this problem.
  • The accumulator variable, newlist, should be initialized to an empty list.
  • Inside a for loop which iterates over numlist, use append to update the value of newlist.
For example:
Test Result
square_nums([1, 2, 3, 4, 5])
[1, 4, 9, 16, 25]
square_nums([-5, 0, 6])
[25, 0, 36]
square_nums([])

7. Make List Items Uppercase 2.

Define the function make_uppercase(mylist), which takes a list parameter mylist (a list of strings), mutates the list by uppercasing each string in mylist. The function returns None.
For example, if mylist is ['cat', 'Dog', 'frOG'], then the mutated list shouldΒ  be ['CAT', 'DOG', 'FROG'].
For example:
Test Result
make_uppercase(['cat', 'Dog', 'frOG'])
['CAT', 'DOG', 'FROG']
make_uppercase(['baNanas', 'appLes', 'pEAches', 'PEArs'])
['BANANAS', 'APPLES', 'PEACHES', 'PEARS']

8. Build List from Input.

Write a function, build_list(), to read words from standard input and store them in a list.
  • You may assume that there will be fewer than 100 words.
  • If the string "STOP" is given as input before 100 words have been added to the list, stop the for loop and return the accumulated list of strings
Hints:
- Use the accumulate-a-list pattern, with acc_list initialized to the empty list, [] - Use a for loop to iterate i over range(100) - When STOP is read from input, break from the for loop; otherwise, append the new word to acc_list before reading the next inputΒ  - Return acc_list
For example:
Test Input Result
build_list()
April
showers
bring
May
flowers
STOP
['April', 'showers', 'bring', 'May', 'flowers']

9. Final Substrings.

The function final_substrings takes a string parameter inString and returns a list of all the non-empty final substrings of inString (in order by their lengths).
For example:
Test Result
final_substrings("Python!")
['!', 'n!', 'on!', 'hon!', 'thon!', 'ython!', 'Python!']
final_substrings("dogs")
['s', 'gs', 'ogs', 'dogs']
final_substrings("")

10. Interleave Lists.

The function interleave_lists takes two parameters, L1 and L2, both lists. Notice that the lists may have different lengths.
The function accumulates a new list by appending alternating items from L1 and L2 until one list has been exhausted.Β  The remaining items from the other list are then appended to the end of the new list, and the new list is returned.
For example, if L1 = ["hop", "skip", "jump", "rest"] and L2 = ["up", "down"], then the function would return the list: ["hop", "up", "skip", "down", "jump", "rest"].
HINT:Python has a built-in functionmin()which is helpful here.
  • Initialize accumulator variable newlist to be an empty list
  • Set min_length = min(len(L1), len(L2)), the smaller of the two list lengths
  • Use a for loopto iterate k over range(min_length) to do the first part of this function’s work. On each iteration, append to newlist the item from index k in L1, and then append the item from index k in L2 (two appends on each iteration).
  • AFTER the loop finishes, append the remaining items (if any) to newlist; use a decision statement to determine which list has remaining items -- then it just takes one line of code to append those items to newlist (using a slice of L1 or L2)
  • return newlist
For example:
Test Result
L1 = ["hop", "skip", "jump"]
L2 = ["A", "B", "C", "D", "E"]
interleave_lists(L1, L2)
['hop', 'A', 'skip', 'B', 'jump', 'C', 'D', 'E']
L1 = ["dive"]
L2 = ["hop", "skip", "jump"]
interleave_lists(L1, L2)
['dive', 'hop', 'skip', 'jump']
cats = ["Ziggy", "Troll Boy"]
dogs = ["Ruthie", "Ame"]
interleave_lists(cats, dogs)
['Ziggy', 'Ruthie', 'Troll Boy', 'Ame']
You have attempted of activities on this page.