Title: Python101
Tags: Basics Python 01

Q: What is the difference between a statement and an expression
A: An expression has a value, and possibly some side effects.
A statement may only have side effects, it has no value.

Q: How do you get a list of lines from a multiline string s ?
A: 1 | s.split("\n")

Q: How do you get a list of integers from a multiline string s containing one integer per line ?
e.g.
1
2
3
s = '''42
12
-1'''
A: Using a for loop:
1
2
3
l = []
for line in s.split():
    l.append(int(line))
Using a list comprehension
1 | [int(line) for line in s.split()]

Q: Is
1 | a = 1
an expression or a statement ?
A: It is a statement, whose side-effect is to store the value 1 in the variable a. It has no value.

Q: Is
1 | a := 1
an expression or a statement ?
A: It is an expression with the same side effects as
1 | a = 1
but it has a value. Its value is the value being assigned to a, which here is 1.
This lets the programmer do things like:
1 | b = (a := 1)
which sets both a and b to 1, or
1
2
if a := some_test():
    do_something_with(a)

Q: How do you display some text for the user to see ?
A: Use the
1 | print()
function.

Q: How do you get a string from the user ?
A: Use the
1 | input()
function.

Q: How do you get an integer from the user ?
A: Wrap input into an call to int:
1 | int(input())

Q: How do you print the integers from 0 to 10, inclusive ?
A: 1
2
for i in range(11):
    print(i)

Q: Why doesn't
1 | print(map(int, ["0", "1", "2"]))
print [0, 1, 2] ?
A: Because map returns a lazy object, which will only evaluate its contents when actually iterated upon.

The following types are iterable:
- lists
- strings
- dicts
- tuples
- sets
- maps

The following basic operators and functions can be called on any iterable
- len
- max
- min
- sum
- sorted
- any
- all
- in

Q: What is the syntax for defining a function called times_two, that returns twice its only argument ?
A: 1
2
def times_two(x):
    return 2*x

Q: 1
2
3
4
while some_test_on(x):
    # HERE
    x = compute_something(x)
do_something_else(x)
What can be said of some_test_on(x) at the given point in the above snippet ?
A: It evaluates to True, otherwise the control flow would never have been inside the while block.

Q: 1
2
3
4
while some_test_on(x):
    x = compute_something(x)
    # HERE
do_something_else(x)
What can be said of some_test_on(x) at the given point in the above snippet ?
A: With the information available in the question, nothing.

Q: 1
2
3
4
while some_test_on(x):
    x = compute_something(x)
# HERE
do_something_else(x)
What can be said of some_test_on(x) at the given point in the above snippet ?
A: It must evaluate to False, otherwise we'd still be in the while block.

Q: Why doesn't
1 | (100000000000000002/2)%10
evaluate to 1 ?
A: Because
1 | (100000000000000002/2)
is too big and as a result is cast to a float, which lacks the precision to store the final 1 in 50000000000000001.

Q: How should you change
1 | (100000000000000002/2)%10
so that it evaluates to 1 ?
A: 1 | (100000000000000002//2)%10

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
SEVEN_DIRTY_WORDS = ("shit", "piss", "fuck", "cunt", "cocksucker", "motherfucker", "tits")
def censor(speech):
    """Basic implementation of a piss poor censor"""
    post_censor_words = []
    for word in speech.split():
        if word in SEVEN_DIRTY_WORDS:
            post_censor_words += ['[beep]']
        else:
            post_censor_words += [word]
    return ' '.join(post_censor_words)
censor(censor.__doc__)
# Evaluates to : 'Basic implementation of a [beep] poor censor'
Complete this implementation of a basic censorship function.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
SEVEN_DIRTY_WORDS = ("shit", "piss", "fuck", "cunt", "cocksucker", "motherfucker", "tits")
def censor(speech):
    """Basic implementation of a piss poor censor"""
    post_censor_words = []
    for word in speech.split():
        if word not in SEVEN_DIRTY_WORDS:
            post_censor_words += [word]
        else:
            post_censor_words += ['[beep]']
    return ' '.join(post_censor_words)
censor(censor.__doc__)
# Evaluates to : 'Basic implementation of a [beep] poor censor'
Complete this basic implementation of a censorship function.

Q: There are three kinds of data:
- [...]
- [...]
- [...]
A: Categorical; Discrete; Continuous

Q: Plot the distribution of flipper length for Adelie penguins (only the head is shown here, there are more rows, with other species, in the rest of the dataset).
 | species | island | bill_length_mm | bill_depth_mm | flipper_length_mm | body_mass_g | sex
0 | Adelie | Torgersen | 39.1 | 18.7 | 181.0 | 3750.0 | Male
1 | Adelie | Torgersen | 39.5 | 17.4 | 186.0 | 3800.0 | Female
2 | Adelie | Torgersen | 40.3 | 18.0 | 195.0 | 3250.0 | Female
3 | Adelie | Torgersen | NaN | NaN | NaN | NaN | NaN
4 | Adelie | Torgersen | 36.7 | 19.3 | 193.0 | 3450.0 | Female
A: 1 | sns.displot(data=df.query("species=='Adelie'"), x="flipper_length_mm")

Q: What well known and ubiquitous distribution would fit the following histogram quite well ?
A: The Gaussian distribution.

Q: On the titanic dataset, display the joint distribution of number of siblings on board (sibsp) and number of parents/children on board (parch)
 | survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone
0 | 0 | 3 | male | 22.0 | 1 | 0 | 7.2500 | S | Third | man | True | NaN | Southampton | no | False
1 | 1 | 1 | female | 38.0 | 1 | 0 | 71.2833 | C | First | woman | False | C | Cherbourg | yes | False
2 | 1 | 3 | female | 26.0 | 0 | 0 | 7.9250 | S | Third | woman | False | NaN | Southampton | yes | True
3 | 1 | 1 | female | 35.0 | 1 | 0 | 53.1000 | S | First | woman | False | C | Southampton | yes | False
4 | 0 | 3 | male | 35.0 | 0 | 0 | 8.0500 | S | Third | man | True | NaN | Southampton | no | True
A: 1 | sns.heatmap(df.reset_index().pivot_table(index="sibsp", columns="parch", values="index", aggfunc="count"))

Q: Plot the distribution of flipper length with respect to the species of penguin.
 | species | island | bill_length_mm | bill_depth_mm | flipper_length_mm | body_mass_g | sex
0 | Adelie | Torgersen | 39.1 | 18.7 | 181.0 | 3750.0 | Male
1 | Adelie | Torgersen | 39.5 | 17.4 | 186.0 | 3800.0 | Female
2 | Adelie | Torgersen | 40.3 | 18.0 | 195.0 | 3250.0 | Female
3 | Adelie | Torgersen | NaN | NaN | NaN | NaN | NaN
4 | Adelie | Torgersen | 36.7 | 19.3 | 193.0 | 3450.0 | Female
A: 1 | sns.violinplot(data=df, y="flipper_length_mm", x="species")

Q: Try to see if there is a relationship between flipper length and bill length.
 | species | island | bill_length_mm | bill_depth_mm | flipper_length_mm | body_mass_g | sex
0 | Adelie | Torgersen | 39.1 | 18.7 | 181.0 | 3750.0 | Male
1 | Adelie | Torgersen | 39.5 | 17.4 | 186.0 | 3800.0 | Female
2 | Adelie | Torgersen | 40.3 | 18.0 | 195.0 | 3250.0 | Female
3 | Adelie | Torgersen | NaN | NaN | NaN | NaN | NaN
4 | Adelie | Torgersen | 36.7 | 19.3 | 193.0 | 3450.0 | Female
A: 1 | sns.regplot(data=df, y="flipper_length_mm", x="bill_length_mm")

Q: Plot the distribution of flipper length with respect to the species of penguin, differentiating male and females.
 | species | island | bill_length_mm | bill_depth_mm | flipper_length_mm | body_mass_g | sex
0 | Adelie | Torgersen | 39.1 | 18.7 | 181.0 | 3750.0 | Male
1 | Adelie | Torgersen | 39.5 | 17.4 | 186.0 | 3800.0 | Female
2 | Adelie | Torgersen | 40.3 | 18.0 | 195.0 | 3250.0 | Female
3 | Adelie | Torgersen | NaN | NaN | NaN | NaN | NaN
4 | Adelie | Torgersen | 36.7 | 19.3 | 193.0 | 3450.0 | Female
A: 1 | sns.violinplot(data=df, y="flipper_length_mm", x="species", hue="sex", split=True)

Q: Try to see if there is a relationship between flipper length and bill length, each species should get its own color
 | species | island | bill_length_mm | bill_depth_mm | flipper_length_mm | body_mass_g | sex
0 | Adelie | Torgersen | 39.1 | 18.7 | 181.0 | 3750.0 | Male
1 | Adelie | Torgersen | 39.5 | 17.4 | 186.0 | 3800.0 | Female
2 | Adelie | Torgersen | 40.3 | 18.0 | 195.0 | 3250.0 | Female
3 | Adelie | Torgersen | NaN | NaN | NaN | NaN | NaN
4 | Adelie | Torgersen | 36.7 | 19.3 | 193.0 | 3450.0 | Female
A: 1 | sns.lmplot(data=df, y="flipper_length_mm", x="bill_length_mm", hue="species")

Q: You have the following list of dancers:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[('F', 'Stephanie Matthews'),
 ('F', 'Alisha Aguilar'),
 ('F', 'Kristin Smith MD'),
 ('F', 'Hannah Wright'),
 ('F', 'Victoria Young'),
 ('M', 'Kyle Romero'),
 ('M', 'Michael Baker'),
 ('M', 'Dean Schmidt'),
 ('F', 'Marissa Singh'),
 ('F', 'Tracy Bowen')]
Output all of the possible pairings of one male dancer and a female dancer.
A: 1 | list(itertools.product([d[1] for d in dancers if d[0] == "F"], [d[1] for d in dancers if d[0] == "M"]))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
[('Stephanie Matthews', 'Kyle Romero'),
 ('Stephanie Matthews', 'Michael Baker'),
 ('Stephanie Matthews', 'Dean Schmidt'),
 ('Alisha Aguilar', 'Kyle Romero'),
 ('Alisha Aguilar', 'Michael Baker'),
 ('Alisha Aguilar', 'Dean Schmidt'),
 ('Kristin Smith MD', 'Kyle Romero'),
 ('Kristin Smith MD', 'Michael Baker'),
 ('Kristin Smith MD', 'Dean Schmidt'),
 ('Hannah Wright', 'Kyle Romero'),
 ('Hannah Wright', 'Michael Baker'),
 ('Hannah Wright', 'Dean Schmidt'),
 ('Victoria Young', 'Kyle Romero'),
 ('Victoria Young', 'Michael Baker'),
 ('Victoria Young', 'Dean Schmidt'),
 ('Marissa Singh', 'Kyle Romero'),
 ('Marissa Singh', 'Michael Baker'),
 ('Marissa Singh', 'Dean Schmidt'),
 ('Tracy Bowen', 'Kyle Romero'),
 ('Tracy Bowen', 'Michael Baker'),
 ('Tracy Bowen', 'Dean Schmidt')]

Q: You have the following list of dancers:
1
2
3
4
5
[('F', 'Stephanie Matthews'),
 ('F', 'Alisha Aguilar'),
 ('F', 'Kristin Smith MD'),
 ('F', 'Hannah Wright'),
 ('F', 'Victoria Young')]
Output all the possible triplets (for the famed triangle dance). Genre does not matter for this dance.
A: 1 | list(itertools.combinations(dancers, 3))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
[(('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Kristin Smith MD')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Hannah Wright')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Victoria Young')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Kristin Smith MD'),
  ('F', 'Hannah Wright')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Kristin Smith MD'),
  ('F', 'Victoria Young')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Hannah Wright'),
  ('F', 'Victoria Young')),
 (('F', 'Alisha Aguilar'), ('F', 'Kristin Smith MD'), ('F', 'Hannah Wright')),
 (('F', 'Alisha Aguilar'), ('F', 'Kristin Smith MD'), ('F', 'Victoria Young')),
 (('F', 'Alisha Aguilar'), ('F', 'Hannah Wright'), ('F', 'Victoria Young')),
 (('F', 'Kristin Smith MD'), ('F', 'Hannah Wright'), ('F', 'Victoria Young'))]

Q: You have the following list of dancers in a competition.
1
2
3
4
5
[('F', 'Stephanie Matthews'),
 ('F', 'Alisha Aguilar'),
 ('F', 'Kristin Smith MD'),
 ('F', 'Hannah Wright'),
 ('F', 'Victoria Young')]
Output all the possible podiums (the first three dancers of the competition, in order).
A: 1 | list(itertools.permutations(dancers, 3))
 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
27
[(('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Kristin Smith MD')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Hannah Wright')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Victoria Young')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Kristin Smith MD'),
  ('F', 'Alisha Aguilar')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Kristin Smith MD'),
  ('F', 'Hannah Wright')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Kristin Smith MD'),
  ('F', 'Victoria Young')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Hannah Wright'),
  ('F', 'Alisha Aguilar')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Hannah Wright'),
  ('F', 'Kristin Smith MD')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Hannah Wright'),
  ('F', 'Victoria Young')),
etc...

Q: You have the following list of dancers.
1
2
3
4
5
[('F', 'Stephanie Matthews'),
 ('F', 'Alisha Aguilar'),
 ('F', 'Kristin Smith MD'),
 ('F', 'Hannah Wright'),
 ('F', 'Victoria Young')]
There are three special prizes (best outfit, best smile, best choreography). Any dancer may win one or more of those. Output all the possibilities of prize winners.
A: 1 | list(itertools.combinations_with_replacement(dancers, 3))
 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
27
28
29
30
[(('F', 'Stephanie Matthews'),
  ('F', 'Stephanie Matthews'),
  ('F', 'Stephanie Matthews')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Stephanie Matthews'),
  ('F', 'Kristin Smith MD')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Stephanie Matthews'),
  ('F', 'Hannah Wright')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Stephanie Matthews'),
  ('F', 'Victoria Young')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Alisha Aguilar')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Kristin Smith MD')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Hannah Wright')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Alisha Aguilar'),
  ('F', 'Victoria Young')),
 (('F', 'Stephanie Matthews'),
  ('F', 'Kristin Smith MD'),
  ('F', 'Kristin Smith MD')),
etc...