Discussion 4: Mutability
Mutability
Some objects in Python, such as lists and dictionaries, are mutable, meaning that their contents or state can be changed. Other objects, such as numeric types, tuples, and strings, are immutable, meaning they cannot be changed once they are created.
There are many list mutation methods:
append(elem): Addelemto the end of the list. ReturnNone.extend(s): Add all elements of iterablesto the end of the list. ReturnNone.insert(i, elem): Insertelemat indexi. Ifiis greater than or equal to the length of the list, thenelemis inserted at the end. This does not replace any existing elements, but only adds the new elementelem. ReturnNone.remove(elem): Remove the first occurrence ofelemin list. ReturnNone. Errors ifelemis not in the list.pop(i): Remove and return the element at indexi.pop(): Remove and return the last element.
Dictionaries also have item assignment and pop.
>>> d = {2: 3, 4: 16}
>>> d[2] = 4
>>> d[3] = 9
>>> d
{2: 4, 4: 16, 3: 9}
>>> d.pop(4)
16
>>> d
{2: 4, 3: 9}
Q1: Apply in Place
Implement apply_in_place, which takes a one-argument function fn and a list s. It modifies s so that each element is the result of applying fn to that element. It returns None.
for i in range(...) to iterate over the indices (positions) of s.
Q2: Shuffle
Define a function shuffle that takes a sequence with an even number of
elements (cards) and creates a new list that interleaves the elements
of the first half with the elements of the second half.
To interleave two sequences s0 and s1 is to create a new sequence such that the new sequence contains (in this order) the first element of s0, the first element of s1, the second element of s0, the second element of s1, and so on.
Run in 61A CodeNote: If you're running into an issue where the special heart / diamond / spades / clubs symbols are erroring in the doctests, feel free to copy paste the below doctests into your file as these don't use the special characters and should not give an "illegal multibyte sequence" error.
Q3: Happy Givers
In a certain discussion section, some people exchange gifts for the holiday season.
We call two people happy givers if they give gifts to each other.
Implement a function happy_givers, which takes in a gifts dictionary that maps
people in the section to the person they gave a gift to. happy_givers outputs a list of
all the happy givers in the section. The order of the list does not matter.
Note that if someone received but did not give a gift, they will not appear in the gifts
dictionary as a key. (They'll appear only as a value.)
You can assume that no one gives themself a gift.
Once you've found a solution, as a challenge, attempt to implement your solution in one line using a list comprehension.
Run in 61A Code