Last active
March 27, 2020 06:47
-
-
Save tomschr/ae928412d0ec3eaad9be0a18480ec86e to your computer and use it in GitHub Desktop.
Python Simplifcation Exercises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Task | |
| # Combine the two lists so you can iterate in the for loop at once | |
| # Tip: you need to find two builtin functions which helps with this task | |
| names = ('Tux', 'Wilber', 'Geeko') | |
| ages = (2020-1996, 2020-1995, 2020-1992) | |
| for i in range(len(names)): | |
| name = names[i] | |
| age = ages[i] | |
| print(f"#{i+1}: {name} is {age} old") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Task | |
| # Simplify the if expressions | |
| lst = [] | |
| if len(lst) == 0: | |
| print("List is empty") | |
| dct = {'a': 1} | |
| if len(dct) != 0: | |
| print("Dict is not empty") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Task | |
| # Simplify the following for loop to make it more pythonic | |
| snacks = [('backon', 350), ('donut', 240), ('muffin', 190)] | |
| for i in range(len(snacks)): | |
| item = snacks[i] | |
| name = item[0] | |
| calories = item[1] | |
| print(f'#{i+1}: {name} has {calories} calories') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Task | |
| # Implement the function "to_bytes" | |
| def to_bytes(bytes_or_str, encoding="utf-8"): | |
| """ | |
| Convert a byte or a string to an byte instance | |
| :param bytes_or_str: the string as str or byte type | |
| :param encoding: the encoding to use when encode a string | |
| :return: a byte string | |
| :rtype: bytes | |
| """ | |
| # add here your implementation | |
| return ... | |
| print(repr(to_bytes(b'hello'))) | |
| print(repr(to_bytes('world'))) | |
| # Result should be (for both): | |
| # 'hello' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment