Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- footer: © Informatik 1 - Fall 2017
- slidenumbers: true
- autoscale: true
- #[fit] Midterm Practice
- Giovanni Grano
- University of Zurich, Department of Informatics
- [.slidenumbers: false]
- ---
- # Logistic Information
- * 2 rooms: **Y04-G-30** and **Y04-G-60**
- * Filling the rooms from 30 minutes before
- * Bring you legi with you
- * We will check you legi at the entrance of the room!
- * When you are in, sit leaving 1 free space from you and the others
- * Bring as little as possible about backpacks and similar
- ---
- # Once sitted in the room
- * Wait for exam to begin, **silently**!
- * Eventually ask for the English version
- * We will distribute 3 A4 sheets per seat for notes
- * Raise you hand for questions, paper, bathroom
- * 1 at time to the bathroom, accompanied by a tutor
- * Announcements at 30 and 15 minutes left
- ---
- # At the end
- * Collect everything you want to be graded (no notes and others)
- * Drop you pen at the end! Do not talk with the other or continue to write
- * We will be **strict**! Please do not try to look at other exams after the end
- * Wait for the tutors to collect the exams
- * Bring some staplers!
- ---
- #[fit] Past year
- #[fit] Midterm
- #[fit] Explained
- [.slidenumbers: false]
- [.footer:]
- ---
- # 1 - Variable and Expressions
- Given the initialised variable german_word, print only the word *’gesellschaften’* using string slicing.
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- ```
- ---
- # 1 - Variable and Expressions
- Given the initialised variable german_word, print only the word *’gesellschaften’* using string slicing.
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- print(german_word[25:])
- # gesellschaften
- ```
- ---
- ## Common Mistakes - 1
- What does that print?
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- print(german_word[24:])
- ```
- ---
- ## Common Mistakes - 1
- Be careful with the index!
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- print(german_word[24:])
- #sgesellschaften
- ```
- ---
- ## Common Mistakes - 2
- What does that print?
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- german_word[25:]
- ```
- ---
- ## Common Mistakes - 2
- **Nothing!** Assume you are not typing in the Python interpreter!
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- german_word[25:]
- ```
- ---
- ## What if? - 1
- What does that print?
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- print(german_word[25:39])
- ```
- ---
- ## What if? - 1
- What does that print?
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- print(german_word[25:39])
- # gesellschaften
- ```
- ---
- ## What if? - 2
- I am smart, I want to slice from the tail 😎
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- print(german_word[:-14])
- ```
- ---
- ## What if? - 2
- 😓
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- print(german_word[:-14])
- # Rechtsschutzversicherungs
- ```
- ---
- ## What if? - 2
- 😓 - Do it right!
- ```python
- german_word = 'Rechtsschutzversicherungsgesellschaften'
- print(german_word[:-14])
- # Rechtsschutzversicherungs
- print(german_word[-14:])
- # gesellschaften
- ```
- ---
- # Mutable Objects
- Please explain what it is a mutable object.
- Give a couple of example of mutable Python objects.
- Let's see a simple example!
- ---
- ## Immutable
- Is the _id_ of the object still the same?
- ```python
- a = 10
- id_a = id(a)
- print(id_a)
- a += 10
- print(id_a == id(a))
- ```
- ---
- ## Mutable
- Is the _id_ of the object still the same?
- ```python
- my_list = [1, 2, 3]
- id_l = id(my_list)
- print(id_l)
- my_list += [4]
- print(id_l == id(my_list))
- ```
- ---
- # 2 - Control Flow & Iteration
- Print the minimum value of _a_ and _b_ using an _if_ instruction
- ---
- # 2 - Control Flow & Iteration
- Print the minimum value of _a_ and _b_ using an _if_ instruction
- ```python
- a = int(input('Type a number: '))
- b = int(input('Type a number: '))
- if a <= b:
- print('min = {0:d}'.format(a)
- else:
- print('min = {0:d}'.format(b))
- ```
- ---
- What if...
- ```python
- a = int(input('Type a number: '))
- b = int(input('Type a number: '))
- def my_smart_function(a, b):
- ...
- ```
- Yes! But remember:
- ```python
- my_smart_function()
- ```
- ---
- # 2 - Control Flow & Iteration
- Print the numbers from 1 to 100 using a _for_ loop
- ```python
- for n in range(..., ...):
- print(n)
- ```
- ---
- # 2 - Control Flow & Iteration
- Print the numbers from 1 to 100 using a _for_ loop
- ```python
- for n in range(1, 101):
- print(n)
- ```
- ---
- ## Common Mistakes
- Only prints from 1 to 99!
- ```python
- for n in range(1,100):
- print(n)
- ```
- ---
- # 3 - Functions
- Write a function that takes two arguments, _a_ and _b_ and returns $$a^b$$
- ---
- # 3 - Functions
- Write a function that takes two arguments, _a_ and _b_ and returns $$a^b$$
- ```python
- def power(a, b):
- return a ** b
- ```
- ---
- # 4 - Data Structures
- What is the difference between lists and dictionaries?
- - Lists contain values, dictionary contains key-value pairs
- - The values in the lists are accessed by an integer indeces, while the values in a dictionary though the corresponding key
- - Lists are ordered, dictionaries are not
- ---
- ## A simple task
- Create a dictionary with you name, birthdate and city you were born in.
- ---
- ## A simple task
- Create a dictionary with you name, birthdate and city you were born in.
- ```python
- thats_me = {
- 'fullname': 'Giovanni Grano',
- 'birth_year': 1990,
- 'birth_city': 'Bojano'
- }
- ```
- ---
- ## Alternatives
- Create a dictionary with you name, birthdate and city you were born in.
- ```python
- thats_me = {} # or thats_me = dict()
- thats_me['fullname'] = 'Giovanni Grano'
- thats_me['birth_year'] = 1990,
- thats_me['birth_city'] = 'Bojano'
- ```
- or
- ```python
- thats_me = {} # or thats_me = dict()
- thats_me.update(fullname,'Giovanni Grano')
- ...
- ```
- ---
- ## Common Mistakes - 1
- ```python
- thats_me = [
- 'fullname': 'Giovanni Grano',
- 'birth_year': 1990,
- 'birth_city': 'Bojano'
- ]
- ```
- ---
- ## Common Mistakes - 2
- ```python
- thats_me = {
- fullname: Giovanni Grano,
- birth_year: 1990,
- birth_city: Bojano
- }
- ```
- ---
- # 5 - Algorithms
- Write a function to check whether a provided password satisfies the following conditions:
- • has at **least 8** characters and at **most 16** characters;
- • contains at least **one uppercase** letter (A-Z);
- • contains at least **one digit** (0-9);
- • contains **only alphabetic characters** (A-Z, a-z) and **digits** (0-9).
- The function should have the following signature `validate_password(password)`and return `True` for a valid password and `False` otherwise.
- The function should also **print** a message saying why the password is not correct, or at the end that the password is valid.
- ---
- ## Solution
- ```python
- def validate_password(password):
- if len(password) < 8:
- print('The password is too short.')
- return False
- if len(password) > 16:
- print('The password is too long.')
- return False
- if not password.isalnum():
- print('The password contains an invalid character.')
- return False
- if password.islower():
- print('The password does not contain an uppercase letter.')
- return False
- if password.isalpha():
- print('The password does not contain digits')
- return False
- print('The password is valid')
- return True
- ```
- ---
- ## Solution explained
- * `isalnum()` : returns `True` if the pass contains only letters and digits
- If returns `False` we know that there are some special chars in the string
- * `islower()` : returns `True` if you only have lowerecase letters
- If returns `False` we know that an uppercase is missing
- * `isalpha()` : returns `True` if you have only alphabetic characters
- If returns `False` we know that a digit is missing
- ---
- ## Alternative solution
- ```python
- def validate_password(password):
- if len(password) < 8:
- print('The password is too short.')
- return False
- if len(password) > 16:
- print('The password is too long.')
- return False
- if not password.isalnum():
- print('The password contains an invalid character.')
- return False
- uppercase_count = 0
- digits_count = 0
- for ch in password:
- if ch in string.ascii_uppercase
- uppercase_count += 1
- if ch in string.digits:
- digits_count += 1
- if uppercase_count < 1:
- print('The password does not contain an uppercase letter.')
- return False
- if digits_count < 1:
- print('The password does not contain a digit.')
- return False
- print('The password is valid')
- return True
- ```
- ---
- # Task 6 - Recursion
- 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.
- ```python
- assert(recursive_sum([0, 1, 2]) == 3)
- assert(recursive_sum([1, 2, 3, [4, 5, 6]]) == 21)
- assert(recursive_sum([1, [1, 1], [1, 1, 1]]) == 6)
- ```
- ---
- ## A solution
- ```python
- def recursive_sum(x):
- if isinstance(x, int):
- return x
- sum = 0
- for el in x:
- sum += recursive_sum(el)
- return sum
- ```
- ---
- # Task 7 - Tuples, Lists and Dicts
- 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.
- A tweet has between 1 and 140 characters and all words which are preceded by the @ character are considered usernames
- ```python
- tweets = ['hi @me and @you','@me yesterday', 'i saw @you', '@yo @you there']
- print count_username_mentions(tweets) # {'yo': 1, 'me': 2, 'you': 3}
- ```
- ---
- ## A solution
- ```python
- def count_username_mentions(tweets):
- username_counts = {}
- for tweet in tweets:
- words = tweet.split(' ')
- for word in words:
- if word.startswith('@'):
- username = word[1:]
- username_counts[username] = username_counts.get(username, 0) +1
- return username_counts
- ```
- ---
- ## Common Mistakes - 1
- `@` contained in any position, not only at the beginning
- ```python
- for tweet in tweets:
- words = tweet.split(' ')
- for word in words:
- if '@' in word
- ```
- For instancen, also the string `my@name` will be counted!
- ---
- ## Common Mistakes - 2
- Proper usage of dictionaries
- ```python
- d = {}
- ...
- d.append(username, count)
- # AttributeError: 'dict' object has no attribute 'append'
- ```
- ---
- ## Common Mistakes - 3
- This gives a `KeyError`
- ```python
- for word in words:
- if word.startswith('@'):
- username = word[1:]
- username_counts[username] += 1
- ```
- With `get(key_name, default_value)` you can set the default value to assume for when the dictionary does not have the key!
- ```python
- username_counts[username] = username_counts.get(username, 0) +1
- ```
- ---
- ## Common Mistakes - 3
- Please do not fix it like this! 😪
- ```python
- for word in words:
- if word.startswith('@'):
- username = word[1:]
- username_counts[username] = 0
- username_counts[username] += 1
- ```
- In this way you will reset to 0 the value in the dictionary every time!
- You can do:
- ```python
- if username in username_counts:
- username_counts[username] += 1
- else:
- username_counts[username] = 0
- ```
- ---
- # Useful Advices
- - Read the assignment **carefully**: if the assignment says to *return* a value from a function, use `return` and not only print the result!
- - Useful Python functions at the bottom of the exams! You will find something useful for the exam!
- - **Really** understand these excercises: the midterm is very similar!
- ---
- #[fit] Good Luck 😉
- [.slidenumbers: false]
- [.footer:]
Add Comment
Please, Sign In to add comment