rsokl / Learning_Python

Source material for Python Like You Mean it
https://www.pythonlikeyoumeanit.com/
Other
166 stars 54 forks source link

Needs Reading Comprehension Questions #22

Closed rsokl closed 6 years ago

rsokl commented 6 years ago

Module 2

Module 3

rsokl commented 6 years ago

@Anonymission If you are interested, it would be helpful for you to cook up some simply reading comprehension questions for these sections, similar to other ones found in the text. You can just write questions and answers in markdown here in this thread. Again, no worries at all if you don't want to.

petarmhg commented 6 years ago

What do you think about these for the itertools section?

Question

Using the combinations function, find the probability that two randomly drawn items from the list ["apples", "bananas", "pears", "pears", "oranges"] would yield a combination of "apples" and "pears".

Solution

>>> from itertools import combinations
>>> ls = ["apples", "bananas", "pears", "pears", "oranges"]
>>> comb_ls = list(combinations(ls, 2))
>>> comb_ls.count(("apples", "pears")) / len(comb_ls)
0.2

Question

Given the list of zipped tuples [(1, 4), (2, 5), (3, 6)], use the zip function and variable unpacking to recover the initial tuples of (1, 2, 3) and (4, 5, 6). Note that an iterable can be unpacked by using the '' operator (e.g. [1, 2, 3] -> 1 2 3).

Solution

>>> a, b = zip(*[(1, 4), (2, 5), (3, 6)])
>>> print(a)
(1, 2, 3)
>>> print(b)
(4, 5, 6)
rsokl commented 6 years ago

These rock :)

One note, the use of the console notation means that we do not need to include print. In the same way you can just execute a jupyter cell and it will automatically print the content of a variable, the same works for the console:

>>> x = 2 + 3
>>> x
5
petarmhg commented 6 years ago

Accessing Array Dimensions

Question

Images can be represented in Python by 3-dimensional ndarrays: one dimension for height, one dimension for width, and one dimension for color (these would be the 'sheets' of a 3D array). Color channels are not always consistant, however. Given a 3D array representing a BGR image (bgr[0] is the blue channel, bgr[1] is green, bgr[2] is red), reverse the channels to produce an RGB image. Hint: you do not need to do this.

Solution

>>> rgb = bgr[::-1]

Question

With the ndarray:

>>> arr = np.arange(27).reshape(3, 3, 3)
>>> arr
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

find the slices that return the following arrays:

array([[ 2,  5,  8],
       [11, 14, 17],
       [20, 23, 26]])
array([[ 3,  4,  5],
       [12, 13, 14]])
array([2, 5])
array([[11, 10,  9],
       [14, 13, 12],
       [17, 16, 15]])
array([4, 3])

Solution

arr[:,:,2]
arr[0,:2,2]
arr[0:2,1]
arr[1,:,::-1]
arr[0,1,1::-1]
petarmhg commented 6 years ago

Sets and Collections

Question

Write a function that takes a two iterables as a parameters and that returns a list of all values that appear only once in one of the iterables. Assume all the objects within the iterables passed to the function are hashable. You can use the lists:

[1, frozenset(("hello", 2, 5)), 9., "moo", 9, "hello", "hi", 13.8, 2, frozenset(("hello", 2, 5)), (12.12, 7), "python", 13.8, "rawr", 1, 19]

[1, "moo", 9, "hi", (12, 1), 14.8, 2, frozenset(("hello", 2, 5)), "python", 13.8, 19, frozenset([96, "python"])]

to test your function.

Solution

def unique(ls1, ls2):
    return(list(set(ls1) ^ set(ls2)))
>>> test_ls1 = [1, frozenset(("hello", 2, 5)), 9., "moo", 9, "hello", "hi", 13.8, 2, frozenset(("hello", 2, 5)), (12.12, 7), "python", 13.8, "rawr", 1, 19]
>>> test_ls2 = [1, "moo", 9, "hi", (12, 1), 14.8, 2, frozenset(("hello", 2, 5)), "python", 13.8, 19, frozenset([96, "python"])]
>>> filtered = unique(test_ls1, test_ls2)
>>> filtered
[(12, 1), (12.12, 7), 'rawr', 14.8, frozenset({96, 'python'}), 'hello']

Question

Determine the frequency of words in the following corpus of text (punctuation has already been removed):

text = Those obligations were said to be no different in principle to any other interlocutory procedural order of the court whether made pretrial or during a trial requiring parties to swear affidavits to answer questions in crossexamination and to provide documentation On the question of what constitutes substantial injustice for the purposes of determining an application for leave to appeal counsel for the Music companies placed particular reliance upon the decision of the Full Federal Court delivered earlier in the primary proceedings which denied leave to appeal from a decision by Wilcox J refusing to set aside Anton Piller orders that his Honour had earlier made Brilliant Digital Entertainment Pty Ltd v Universal Music Australia Pty Ltd 2004 63 IPR 373 I will refer further to that authority shortly 9 The Sharman applicants sought to emphasise the existence of practical burdens imposed by the orders made by Moore J on 17 November 2005 although in reality it was principally with respect to the order for crossexamination of Ms Hemming to which that assertion was directed They maintained that the requirement to appear for crossexamination was not analogous to the routine steps of swearing an affidavit during the normal course of a trial and entering the witness box to answer questions related to its contents Rather the requirement to be crossexamined on an asset disclosure affidavit was said to be at the extreme end of the Courts armoury by virtue of the fact that the making of an order for crossexamination on an affidavit of this kind is predicated upon the Court having implicitly found the deponent of that affidavit to be in contempt of court I was referred by the Sharman applicants to an earlier Full Federal Court decision in Minister for Immigration amp Multicultural amp Indigenous Affairs v Wong 2002 FCAFC 327 in support of their submission that since the present circumstances give rise to an important question of principle leave to appeal should be readily granted The parties respective submissions concerning material matters bearing upon the justification or otherwise for the grant of orders ancillary to the Mareva relief and my incidental observations 10 The affidavit filed in support of the application for leave to appeal by Mr Rohan Higgins the solicitor for the Sharman applicants contained the following broad submission under the heading injustice if leave is refused If leave to appeal is not granted then the orders of Moore J will operate and will have to be complied with Any subsequent challenge to those orders would then be futile and academic The orders are interlocutory in form but final in the result in relation to the issues raised So much is correct as a general statement as to the consequences of his Honours orders However the nature and context of the application for leave here involved in practical terms an appeal or virtually so as will hereafter emerge 11 The Music companies contended that the Sharman applicants submissions proceeded in reality on the erroneous basis that every interlocutory decision that requires a party to do an act will be automatically susceptible to leave to appeal and to being stayed The Music companies position was that the orders requiring Ms Hemming to file an affidavit disclosing the assets of Sharman Networks and to attend for crossexamination on the affidavit she had earlier sworn as to disclosure of her assets were merely procedural in nature and therefore incapable as such of determining any final rights of the parties So much accorded with Moore Js understanding of the nature of those orders as indicated in 30 of his Honours reasons for judgment 12 The primary submission made by the Music companies as to why leave to appeal ought not to be granted related to the failure of the Sharman applicants to adduce evidence demonstrative of the claim that they would suffer substantial injustice should leave be refused The Music companies rejected any notion to the effect that the mere fact of Ms Hemming being compelled to swear an affidavit as to disclosure of Sharman Networks assets and to attend for crossexamination upon her own disclosure affidavits without more amounted to substantial injustice in the sense that such expression has been used in numerous authorities concerned with the grant of leave to appeal Reference was made to Gerlach v Clifton Bricks Pty Ltd 2002 HCA 22 2002 209 CLR 478 in which Gaudron McHugh and Hayne JJ in a different context considered that the bare proposition that an order mandating trial by judge alone as opposed to trial by judge and jury can amount without more to a substantial wrong to a party or to a miscarriage of justice was a startling proposition The reality of the dilemma in which the Court is placed by the present application is the need for consideration in some depth of the matters to which attention has been drawn by the Sharman applicants before determining whether leave to appeal ought formally to be granted to appeal in the first place

What are the five most common words? How often do they appear?

Solution

>>> from collections import Counter
>>> text = text.lower().split()
>>> freq = Counter(text)
>>> freq.most_common(5)
[('the', 69), ('to', 56), ('of', 36), ('in', 22), ('that', 16)]
rsokl commented 6 years ago

@Anonymission how would you like to be acknowledged in the Contributor's section? Real name? First name? GitHub handle? A mix?

petarmhg commented 6 years ago

Dictionaries

Question

The following is a dictionary of the ten highest rated movies on IMDb, mapped to a list of their IMDb rating, year of release, and MPAA rating:

movies = {"The Shawshank Redemption":[9.3, 1994, "R"], 
         "The Godfather":[9.2, 1972, "R"], 
         "The Dark Knight":[9., 2008, "PG-13"], 
         "The Godfather: Part II":[9., 1974, "R"], 
         "Schindler's List":[8.9, 1993, "R"], 
         "Pulp Fiction":[8.9, 1994, "R"], 
         "The Lord of the Rings: The Return of the King":[8.9, 2003, "PG-13"], 
         "12 Angry Men":[8.9, 1957, "N/A"], 
         "The Good, the Bad, and the Ugly":[8.9, 1966, "R"], 
         "The Lord of the Rings: The Fellowship of the Ring":[8.8, 2001, "PG-13"]}

Given the following dictionary of genres, append the genre of each movie to its corresponding list in movies:

genres = {"Crime":("The Shawshank Redemption", 
                   "The Godfather", 
                   "The Godfather: Part II", 
                   "Pulp Fiction", 
                   "12 Angry Men"), 
         "Action":("The Dark Knight",),
         "Drama":("Schindler's List",),
         "Adventure":("The Lord of the Rings: The Return of the King", 
                      "The Lord of the Rings: The Fellowship of the Ring"),
         "Western":("The Good, the Bad, and the Ugly",)}

Solution

for genre in genres:
    for movie in genres[genre]:
        movies[movie].append(genre)
# or
for genre, movie_tuples in genres.items():
    for movie in movie_tuples:
        movies[movie].append(genre)
>>> movies
{'12 Angry Men': [8.9, 1957, 'N/A', 'Crime'],
 'Pulp Fiction': [8.9, 1994, 'R', 'Crime'],
 "Schindler's List": [8.9, 1993, 'R', 'Drama'],
 'The Dark Knight': [9.0, 2008, 'PG-13', 'Action'],
 'The Godfather': [9.2, 1972, 'R', 'Crime'],
 'The Godfather: Part II': [9.0, 1974, 'R', 'Crime'],
 'The Good, the Bad, and the Ugly': [8.9, 1966, 'R', 'Western'],
 'The Lord of the Rings: The Fellowship of the Ring': [8.8,
  2001,
  'PG-13',
  'Adventure'],
 'The Lord of the Rings: The Return of the King': [8.9,
  2003,
  'PG-13',
  'Adventure'],
 'The Shawshank Redemption': [9.3, 1994, 'R', 'Crime']}
petarmhg commented 6 years ago

@rsokl

A mix of real name and GitHub handle would be nice. Also, I should have questions for Data Structures (Part 1) soon.

petarmhg commented 6 years ago

Data Structures Introduction

The 4th answer should be double-checked, as I'm not completely sure about it.

Question

In big-O notation, what are the run time complexities of the following blocks of code:

if item in seq:
    print(seq.count(item))
seq.append(item)
seq.sort()
seq.sort()

for item in seq:
    seq.pop(0)
    print(seq)
for item in seq:
    print(seq.index(item))
for i, item in enumerate(seq):
    print(i)

Solution

O(n2)

O(nlog(n))

O(n2)

O(n2)

O(n)

rsokl commented 6 years ago

I've incorporated a number of these into the 0.10.0 release of PLYMI. Others I will be including into "problem" sections at the end of the respective modules. Thank you so much, @Anonymission !