Practice: Built-in Modules
Q1. Factorial of six
Use the math module to print the factorial of 6.
Goal: Use math.
Q2. Greatest common divisor
Print the greatest common divisor of 48 and 36.
Goal: Use math.gcd.
Q3. Days between dates
Print how many days there are from 2024-02-01 to 2024-03-01.
Goal: Use datetime.
Q4. Count words
Use Counter to print the count of 'to' in the list ['to','be','or','not','to','be'].
Goal: Use Counter.
Q5. Dictionary to JSON
Print the JSON text of the dictionary {'a': 1, 'b': [2, 3]}.
Goal: Use json.
Q6. Float comparison
Print whether 0.1 + 0.2 is close to 0.3 using the right function.
Goal: Compare floats safely.
Q7. Pairs from a list
Use itertools.combinations to print all pairs from ['x','y','z'] as a list.
Goal: Use itertools.
Q8. Rounding negatives
What does this print?
import math
print(math.floor(-1.2), math.ceil(-1.2))Goal: Know floor and ceil.
Q9. Date plus days
What does this print?
from datetime import date, timedelta
print(date(2023, 12, 25) + timedelta(days=10))Goal: Add timedelta.
Q10. Most common
What does this print?
from collections import Counter
print(Counter('banana').most_common(1))Goal: Read Counter.
Q11. JSON round trip
What does this print?
import json
data = json.loads('{"x": [1, 2, 3], "ok": true}')
print(data['ok'], sum(data['x']))Goal: Read JSON.
Q12. Chain joins
What does this print?
from itertools import chain
print(list(chain('ab', [1, 2])))Goal: Use chain.
Q13. Seeded safety
What does this print?
import random
random.seed(3)
print(random.randint(5, 5))Goal: Know randint ends.
Q14. Floats with ==
This code prints False. Change only the comparison so it prints True.
print(0.1 + 0.2 == 0.3)Goal: Fix float comparison.
Q15. dump versus dumps
This code raises an error because json.dumps is used with a file argument. Fix it so it prints the JSON text.
import json
print(json.dumps([1, 2], 'out.json'))Goal: Know dump vs dumps.
Q16. Missing import
This code raises NameError. Fix it so it prints 3.
print(Counter('aaabb')['a'])Goal: Import names.
Q17. Choose a module
Which module would you use to count the most common words in a text and which to find the number of days between two dates?
Goal: Pick the right module.
Q18. Random for passwords?
Why should random not be used to create passwords?
Goal: Know security limits.
Q19. Next birthday gap
Today is replaced by date(2024, 6, 1) and the birthday by date(2024, 12, 25). Print the number of days left.
Goal: Compute date gaps.