Guest User

Untitled

a guest
Oct 27th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.47 KB | None | 0 0
  1. footer: © Informatik 1 - Fall 2017
  2. slidenumbers: true
  3. autoscale: true
  4.  
  5. #[fit] Midterm Practice
  6.  
  7. Giovanni Grano
  8. University of Zurich, Department of Informatics
  9.  
  10. [.slidenumbers: false]
  11.  
  12. ---
  13.  
  14. # Logistic Information
  15.  
  16. * 2 rooms: **Y04-G-30** and **Y04-G-60**
  17. * Filling the rooms from 30 minutes before
  18. * Bring you legi with you
  19. * We will check you legi at the entrance of the room!
  20. * When you are in, sit leaving 1 free space from you and the others
  21. * Bring as little as possible about backpacks and similar
  22.  
  23. ---
  24.  
  25. # Once sitted in the room
  26.  
  27. * Wait for exam to begin, **silently**!
  28. * Eventually ask for the English version
  29. * We will distribute 3 A4 sheets per seat for notes
  30. * Raise you hand for questions, paper, bathroom
  31. * 1 at time to the bathroom, accompanied by a tutor
  32. * Announcements at 30 and 15 minutes left
  33.  
  34. ---
  35.  
  36. # At the end
  37.  
  38. * Collect everything you want to be graded (no notes and others)
  39. * Drop you pen at the end! Do not talk with the other or continue to write
  40. * We will be **strict**! Please do not try to look at other exams after the end
  41. * Wait for the tutors to collect the exams
  42. * Bring some staplers!
  43.  
  44. ---
  45.  
  46. #[fit] Past year
  47. #[fit] Midterm
  48. #[fit] Explained
  49.  
  50. [.slidenumbers: false]
  51. [.footer:]
  52.  
  53. ---
  54.  
  55. # 1 - Variable and Expressions
  56.  
  57. Given the initialised variable german_word, print only the word *’gesellschaften’* using string slicing.
  58.  
  59. ```python
  60. german_word = 'Rechtsschutzversicherungsgesellschaften'
  61. ```
  62.  
  63. ---
  64.  
  65. # 1 - Variable and Expressions
  66.  
  67. Given the initialised variable german_word, print only the word *’gesellschaften’* using string slicing.
  68.  
  69. ```python
  70. german_word = 'Rechtsschutzversicherungsgesellschaften'
  71. print(german_word[25:])
  72.  
  73. # gesellschaften
  74. ```
  75.  
  76. ---
  77.  
  78. ## Common Mistakes - 1
  79.  
  80. What does that print?
  81.  
  82. ```python
  83. german_word = 'Rechtsschutzversicherungsgesellschaften'
  84. print(german_word[24:])
  85. ```
  86.  
  87. ---
  88.  
  89. ## Common Mistakes - 1
  90.  
  91. Be careful with the index!
  92.  
  93. ```python
  94. german_word = 'Rechtsschutzversicherungsgesellschaften'
  95. print(german_word[24:])
  96.  
  97. #sgesellschaften
  98. ```
  99.  
  100. ---
  101.  
  102. ## Common Mistakes - 2
  103.  
  104. What does that print?
  105.  
  106. ```python
  107. german_word = 'Rechtsschutzversicherungsgesellschaften'
  108. german_word[25:]
  109. ```
  110.  
  111. ---
  112.  
  113. ## Common Mistakes - 2
  114.  
  115. **Nothing!** Assume you are not typing in the Python interpreter!
  116.  
  117. ```python
  118. german_word = 'Rechtsschutzversicherungsgesellschaften'
  119. german_word[25:]
  120. ```
  121.  
  122. ---
  123.  
  124. ## What if? - 1
  125.  
  126. What does that print?
  127.  
  128. ```python
  129. german_word = 'Rechtsschutzversicherungsgesellschaften'
  130. print(german_word[25:39])
  131. ```
  132.  
  133. ---
  134.  
  135. ## What if? - 1
  136.  
  137. What does that print?
  138.  
  139. ```python
  140. german_word = 'Rechtsschutzversicherungsgesellschaften'
  141. print(german_word[25:39])
  142.  
  143. # gesellschaften
  144. ```
  145.  
  146. ---
  147.  
  148. ## What if? - 2
  149.  
  150. I am smart, I want to slice from the tail 😎
  151.  
  152. ```python
  153. german_word = 'Rechtsschutzversicherungsgesellschaften'
  154. print(german_word[:-14])
  155. ```
  156.  
  157. ---
  158.  
  159. ## What if? - 2
  160.  
  161. 😓
  162.  
  163. ```python
  164. german_word = 'Rechtsschutzversicherungsgesellschaften'
  165. print(german_word[:-14])
  166.  
  167. # Rechtsschutzversicherungs
  168. ```
  169.  
  170. ---
  171.  
  172. ## What if? - 2
  173.  
  174. 😓 - Do it right!
  175.  
  176. ```python
  177. german_word = 'Rechtsschutzversicherungsgesellschaften'
  178. print(german_word[:-14])
  179.  
  180. # Rechtsschutzversicherungs
  181.  
  182. print(german_word[-14:])
  183.  
  184. # gesellschaften
  185. ```
  186.  
  187. ---
  188.  
  189. # Mutable Objects
  190.  
  191. Please explain what it is a mutable object.
  192. Give a couple of example of mutable Python objects.
  193.  
  194. Let's see a simple example!
  195.  
  196. ---
  197.  
  198. ## Immutable
  199.  
  200. Is the _id_ of the object still the same?
  201.  
  202. ```python
  203. a = 10
  204. id_a = id(a)
  205. print(id_a)
  206. a += 10
  207. print(id_a == id(a))
  208. ```
  209.  
  210. ---
  211.  
  212. ## Mutable
  213.  
  214. Is the _id_ of the object still the same?
  215.  
  216. ```python
  217. my_list = [1, 2, 3]
  218. id_l = id(my_list)
  219. print(id_l)
  220. my_list += [4]
  221. print(id_l == id(my_list))
  222. ```
  223.  
  224. ---
  225.  
  226. # 2 - Control Flow & Iteration
  227.  
  228. Print the minimum value of _a_ and _b_ using an _if_ instruction
  229.  
  230.  
  231. ---
  232.  
  233. # 2 - Control Flow & Iteration
  234.  
  235. Print the minimum value of _a_ and _b_ using an _if_ instruction
  236.  
  237. ```python
  238. a = int(input('Type a number: '))
  239. b = int(input('Type a number: '))
  240. if a <= b:
  241. print('min = {0:d}'.format(a)
  242. else:
  243. print('min = {0:d}'.format(b))
  244. ```
  245.  
  246. ---
  247.  
  248. What if...
  249.  
  250. ```python
  251. a = int(input('Type a number: '))
  252. b = int(input('Type a number: '))
  253.  
  254. def my_smart_function(a, b):
  255. ...
  256. ```
  257.  
  258. Yes! But remember:
  259.  
  260. ```python
  261. my_smart_function()
  262. ```
  263.  
  264. ---
  265.  
  266. # 2 - Control Flow & Iteration
  267.  
  268. Print the numbers from 1 to 100 using a _for_ loop
  269.  
  270. ```python
  271. for n in range(..., ...):
  272. print(n)
  273. ```
  274.  
  275. ---
  276.  
  277. # 2 - Control Flow & Iteration
  278.  
  279. Print the numbers from 1 to 100 using a _for_ loop
  280.  
  281. ```python
  282. for n in range(1, 101):
  283. print(n)
  284. ```
  285.  
  286. ---
  287.  
  288. ## Common Mistakes
  289.  
  290. Only prints from 1 to 99!
  291.  
  292. ```python
  293. for n in range(1,100):
  294. print(n)
  295. ```
  296.  
  297. ---
  298.  
  299. # 3 - Functions
  300.  
  301. Write a function that takes two arguments, _a_ and _b_ and returns $$a^b$$
  302.  
  303. ---
  304.  
  305. # 3 - Functions
  306.  
  307. Write a function that takes two arguments, _a_ and _b_ and returns $$a^b$$
  308.  
  309. ```python
  310. def power(a, b):
  311. return a ** b
  312. ```
  313.  
  314. ---
  315.  
  316.  
  317. # 4 - Data Structures
  318.  
  319. What is the difference between lists and dictionaries?
  320.  
  321. - Lists contain values, dictionary contains key-value pairs
  322. - The values in the lists are accessed by an integer indeces, while the values in a dictionary though the corresponding key
  323. - Lists are ordered, dictionaries are not
  324.  
  325. ---
  326.  
  327. ## A simple task
  328.  
  329. Create a dictionary with you name, birthdate and city you were born in.
  330.  
  331. ---
  332.  
  333. ## A simple task
  334.  
  335. Create a dictionary with you name, birthdate and city you were born in.
  336.  
  337. ```python
  338. thats_me = {
  339. 'fullname': 'Giovanni Grano',
  340. 'birth_year': 1990,
  341. 'birth_city': 'Bojano'
  342. }
  343. ```
  344.  
  345. ---
  346.  
  347. ## Alternatives
  348.  
  349. Create a dictionary with you name, birthdate and city you were born in.
  350.  
  351. ```python
  352. thats_me = {} # or thats_me = dict()
  353. thats_me['fullname'] = 'Giovanni Grano'
  354. thats_me['birth_year'] = 1990,
  355. thats_me['birth_city'] = 'Bojano'
  356. ```
  357.  
  358. or
  359.  
  360. ```python
  361. thats_me = {} # or thats_me = dict()
  362. thats_me.update(fullname,'Giovanni Grano')
  363. ...
  364. ```
  365.  
  366. ---
  367.  
  368. ## Common Mistakes - 1
  369.  
  370. ```python
  371. thats_me = [
  372. 'fullname': 'Giovanni Grano',
  373. 'birth_year': 1990,
  374. 'birth_city': 'Bojano'
  375. ]
  376. ```
  377.  
  378. ---
  379.  
  380. ## Common Mistakes - 2
  381.  
  382. ```python
  383. thats_me = {
  384. fullname: Giovanni Grano,
  385. birth_year: 1990,
  386. birth_city: Bojano
  387. }
  388. ```
  389.  
  390. ---
  391.  
  392. # 5 - Algorithms
  393.  
  394. Write a function to check whether a provided password satisfies the following conditions:
  395. • has at **least 8** characters and at **most 16** characters;
  396. • contains at least **one uppercase** letter (A-Z);
  397. • contains at least **one digit** (0-9);
  398. • contains **only alphabetic characters** (A-Z, a-z) and **digits** (0-9).
  399. The function should have the following signature `validate_password(password)`and return `True` for a valid password and `False` otherwise.
  400. The function should also **print** a message saying why the password is not correct, or at the end that the password is valid.
  401.  
  402. ---
  403.  
  404. ## Solution
  405.  
  406. ```python
  407. def validate_password(password):
  408. if len(password) < 8:
  409. print('The password is too short.')
  410. return False
  411. if len(password) > 16:
  412. print('The password is too long.')
  413. return False
  414. if not password.isalnum():
  415. print('The password contains an invalid character.')
  416. return False
  417. if password.islower():
  418. print('The password does not contain an uppercase letter.')
  419. return False
  420. if password.isalpha():
  421. print('The password does not contain digits')
  422. return False
  423. print('The password is valid')
  424. return True
  425. ```
  426.  
  427. ---
  428.  
  429. ## Solution explained
  430.  
  431. * `isalnum()` : returns `True` if the pass contains only letters and digits
  432. If returns `False` we know that there are some special chars in the string
  433. * `islower()` : returns `True` if you only have lowerecase letters
  434. If returns `False` we know that an uppercase is missing
  435. * `isalpha()` : returns `True` if you have only alphabetic characters
  436. If returns `False` we know that a digit is missing
  437.  
  438. ---
  439.  
  440. ## Alternative solution
  441.  
  442. ```python
  443. def validate_password(password):
  444. if len(password) < 8:
  445. print('The password is too short.')
  446. return False
  447. if len(password) > 16:
  448. print('The password is too long.')
  449. return False
  450. if not password.isalnum():
  451. print('The password contains an invalid character.')
  452. return False
  453. uppercase_count = 0
  454. digits_count = 0
  455. for ch in password:
  456. if ch in string.ascii_uppercase
  457. uppercase_count += 1
  458. if ch in string.digits:
  459. digits_count += 1
  460. if uppercase_count < 1:
  461. print('The password does not contain an uppercase letter.')
  462. return False
  463. if digits_count < 1:
  464. print('The password does not contain a digit.')
  465. return False
  466.  
  467. print('The password is valid')
  468. return True
  469. ```
  470.  
  471. ---
  472.  
  473. # Task 6 - Recursion
  474.  
  475. Write a function with the signature `recursive_sum` that accepts a nestd list of integers as an argument (e.g. `[1, 2 ,3, [4, 5, 6]]`) and returns the sum of each element of the list.
  476.  
  477. ```python
  478. assert(recursive_sum([0, 1, 2]) == 3)
  479. assert(recursive_sum([1, 2, 3, [4, 5, 6]]) == 21)
  480. assert(recursive_sum([1, [1, 1], [1, 1, 1]]) == 6)
  481. ```
  482.  
  483. ---
  484.  
  485. ## A solution
  486.  
  487. ```python
  488. def recursive_sum(x):
  489. if isinstance(x, int):
  490. return x
  491.  
  492. sum = 0
  493. for el in x:
  494. sum += recursive_sum(el)
  495. return sum
  496. ```
  497.  
  498. ---
  499.  
  500. # Task 7 - Tuples, Lists and Dicts
  501.  
  502. Write a function that receives a list of tweets as a parameter and returns a dictionary containing the names mentioned in a tweet as keys and the total number of times each name was mentioned in a tweet.
  503.  
  504. A tweet has between 1 and 140 characters and all words which are preceded by the @ character are considered usernames
  505.  
  506. ```python
  507. tweets = ['hi @me and @you','@me yesterday', 'i saw @you', '@yo @you there']
  508. print count_username_mentions(tweets) # {'yo': 1, 'me': 2, 'you': 3}
  509. ```
  510.  
  511. ---
  512.  
  513. ## A solution
  514.  
  515. ```python
  516. def count_username_mentions(tweets):
  517. username_counts = {}
  518. for tweet in tweets:
  519. words = tweet.split(' ')
  520. for word in words:
  521. if word.startswith('@'):
  522. username = word[1:]
  523. username_counts[username] = username_counts.get(username, 0) +1
  524. return username_counts
  525. ```
  526.  
  527. ---
  528.  
  529. ## Common Mistakes - 1
  530.  
  531. `@` contained in any position, not only at the beginning
  532.  
  533. ```python
  534. for tweet in tweets:
  535. words = tweet.split(' ')
  536. for word in words:
  537. if '@' in word
  538. ```
  539.  
  540. For instancen, also the string `my@name` will be counted!
  541.  
  542. ---
  543.  
  544. ## Common Mistakes - 2
  545.  
  546. Proper usage of dictionaries
  547.  
  548. ```python
  549. d = {}
  550. ...
  551. d.append(username, count)
  552. # AttributeError: 'dict' object has no attribute 'append'
  553. ```
  554.  
  555. ---
  556.  
  557. ## Common Mistakes - 3
  558.  
  559. This gives a `KeyError`
  560.  
  561. ```python
  562. for word in words:
  563. if word.startswith('@'):
  564. username = word[1:]
  565. username_counts[username] += 1
  566. ```
  567.  
  568. With `get(key_name, default_value)` you can set the default value to assume for when the dictionary does not have the key!
  569.  
  570. ```python
  571. username_counts[username] = username_counts.get(username, 0) +1
  572. ```
  573.  
  574. ---
  575.  
  576. ## Common Mistakes - 3
  577.  
  578. Please do not fix it like this! 😪
  579.  
  580. ```python
  581. for word in words:
  582. if word.startswith('@'):
  583. username = word[1:]
  584. username_counts[username] = 0
  585. username_counts[username] += 1
  586. ```
  587.  
  588. In this way you will reset to 0 the value in the dictionary every time!
  589.  
  590. You can do:
  591.  
  592. ```python
  593. if username in username_counts:
  594. username_counts[username] += 1
  595. else:
  596. username_counts[username] = 0
  597. ```
  598.  
  599. ---
  600.  
  601. # Useful Advices
  602.  
  603. - Read the assignment **carefully**: if the assignment says to *return* a value from a function, use `return` and not only print the result!
  604. - Useful Python functions at the bottom of the exams! You will find something useful for the exam!
  605. - **Really** understand these excercises: the midterm is very similar!
  606.  
  607. ---
  608.  
  609. #[fit] Good Luck 😉
  610. [.slidenumbers: false]
  611. [.footer:]
Add Comment
Please, Sign In to add comment