|
CS 116 Tutorial 4: Lists, Mutation
Reminders: Assignment 4 is due on Wed, Jun 12th at 10am
Questions 1, 2, and 3 use the following data definition:
A Card is a list of length 2 where
- the first item is an integer between 1 and 13, inclusive, representing the value of the card, and
- the second item is a string ("hearts", "spades", "clubs", or "diamonds") representing the suit of the card.
Example: [1, "hearts"] represents the ace of hearts
-
Write a function create_cards that consumes a list of card values (integers between 1 and 13),
and a list of suite values (one of the four suit strings),
and returns a list of cards created pair-wise from the consumed lists (values and suits ).
Example: create_cards([4,1,10], ["hearts","diamonds","clubs"]) =>[[4,"hearts"], [1, "diamonds"], [10, "clubs”]].
-
Write a function choose_by_colour that consumes a list of cards (hand ) and a
string "red" or "black" (colour ) and returns a list of the values of the cards in hand of
the appropriate colour (spades and clubs are "black" , hearts and diamonds are "red" ).
Example: choose_by_colour([[1,'hearts'], [9, 'spades'], [3,'diamonds']], 'red') => [1,3] .
Write this function twice. First, use explicit recursion. Then, use abstract list functions.
-
a) Write a function flip_colour that takes in a card, c , and mutates the
suit of that card to a different colour: if c is a heart, it is mutated to a spade (and vice versa),
while if c is a club, it is mutated to a diamond
(and vice versa).
b) Write a function flip_hand that reads in a list of cards (hand ),
and mutates the suit of each card in the list so that their colours are flipped in the same way as in
flip_colour .
-
Write a function modify_list that consumes a list of integers (nums )
and a single integer (n ). The function returns None , but mutates the list in the following way:
- If
n does not appear in nums then add it to the end of nums .
- If
n appears once, then remove n from nums
- If
n appears at least twice, removes the first and last occurrences of n .
For example:
If L = [], modify_list(L,10) => None, and L = [10]
If L = [1,2,3], modify_list(L,10) => None, and L = [1,2,3,10]
If L = [1,2,3,4], modify_list(L,4) => None, and L = [1,2,3]
If L = [1,5,2,1,7,1,9], modify_list(L,1) => None, and L = [5,2,1,7,9]
-
Write a function sanitize that consumes a string, s , and returns a
similar string but with any non-alphanumeric characters removed.
For example: sanitize("@Test@") => "Test"
-
Write a function reversed_list a list of string, L , and returns a
list containing the elements of L in reverse order. Write this function using
abstract list functions.
For example: reversed_list(["I","love","cs116"]) => ['cs116','love',I]
|