Python Q&A – Classes, Error Handling and I/O

Question 1: Accessing a Dictionary
Dictionaries are iterable objects that store associations between ‘keys’ and values, which allow extraction of specific data by entering the specific key of the dictionary. Let’s say a dictionary:

Meat = { ‘chicken’: 0, ‘beef’: 1, ‘pork’: 2}
To extract the value of chicken, we would type Meat[‘chicken’] to get 0.

Task: Write a function get_value(dictionary, key) which returns the value for the given key in the given dictionary. 
get_value({‘k’: 3}, ‘k’) -> 3
get_value({‘a’: 1, ‘b’: 2, ‘c’: 3}, ‘b’) -> 2

Answer:

Explanation: The get_value function will require two inputs – one is the dictionary and the other is the key, in order to the value associated with the key. All we have to do is return dictionary[key], which searches for the key in the dictionary to find the value associated with that key.

Question 2: Accessing a Dictionary Using Get
There is an in-built function in Python called get, which gets two inputs, where it will either get the value from a valid key in the dictionary. If the key inputted is not present in the dictionary, it will return a value that we designate (in this case, it will be -1).

Task: Write a function get_value(dictionary, key) which returns the value for the given key in the given dictionary, using the get method. If the key is not valid, your function should return -1. 

get_value({‘k’: 3}, ‘k’) -> 3
get_value({‘a’: 1, ‘b’: 2, ‘c’: 3}, ‘b’) -> 2
get_value({‘a’: 1, ‘b’: 2, ‘c’: 3}, ‘Not a key’) -> -1

Answer:

Explanation: Like the previous question, the get_value function requires two inputs. However, we use the .get function to get the dictionary’s value from the specified key. If the specified key is not in dictionary, it will return -1.

Question 3: Iterating over a Dictionary
A dictionary is an iterable object, which means for loops can be used to iterate over entries in a dictionary.

Task: Write a function big_keys that takes such a dictionary as the first argument and an integer as the second argument and returns the list of keys all of whose values are bigger than the second argument. 

big_keys({‘a’:24, ‘e’:30, ‘t’:12, ‘n’:10}, 15) -> [‘a’, ‘e’]
big_keys({‘a’:24, ‘e’:30, ‘t’:12, ‘n’:10}, 99) -> []
big_keys({}, 0) -> []

Answer:

Explanation: We first create an empty list to store the list of keys of all of whose values are bigger than integer (second input of the big_keys function). A for loop is then used to iterate over the dictionary to check each value associated with each key to see whether the value is larger than the integer. To simplify it, what it does, is that it checks the value of the first key, then it checks the value of the second key and so on. If the value is larger, then the key associated with that value is appended to the key_list variable we defined earlier.

Question 4: Updating a Dictionary
It is always important that we know how to update a value for a given key in a dictionary and vice versa, because it would be inefficient to create an entirely new dictionary.

Task: Write a function add_to_dict(d, key_value_pairs) which adds each given key/value pair to the given dictionary. The argument key_value_pairs will be a list of tuples in the form (key, value).
d = {}; add_to_dict(d, []) -> [], d -> {}
d = {}; add_to_dict(d, [(‘a’, 2)]) -> [], d -> {‘a’: 2}
d = {‘b’: 4}; add_to_dict(d, [(‘a’, 2)]) -> [], d -> {‘a’: 2, ‘b’: 4}
d = {‘a’: 0}; add_to_dict(d, [(‘a’, 2)]) -> [(‘a’, 0)], d -> {‘a’: 2}
d = {‘a’: 0, ‘b’: 1}; add_to_dict(d, [(‘a’, 2), (‘b’: 4)]) -> [(‘a’, 0), (‘b’: 1)], d -> {‘a’: 2, ‘b’: 4}
d = {‘a’: 0}; add_to_dict(d, [(‘a’, 1), (‘a’: 2)]) -> [(‘a’, 0), (‘a’: 1)], d -> {‘a’: 2}

Answer:

Explanation: A variable add_list is created as an empty list. By using a for loop that takes into consideration of two characters which associate with the key (k) and the value (v), we can append the key- values pair, and if the key is present in the specified key, then it is appended to the empty list. We also update the dictionary to add the new key-value pair. Then the list is returned.

Question 5: Exception Handling
Attempting to run certain code may cause errors. One common cause of errors is converting user input type to a useful type. For example, if u try to int(‘chicken’), it will come out with an error.

Task: Write a function try_int(string) which converts string into an integer if possible, and returns None otherwise.

try_int(‘2’) -> 2
try_int(‘banana’) -> None

Answer:

Explanation: Using the try and except statement, if the string input can be turned into an integer, then it is returned as an integer, else it will return None.

Question 6: Raising an Exception
The previous question deals with using try/except statement to catch an exception. In this question, we will need to raise an exception in the first place.

Task: Write a function validate_input(string) which takes a command string in the format ‘command arg1 arg2’ and returns the pair (‘command’, [arg1, arg2]), where arg1 and arg2 have been converted to floats. If the command is not one of ‘add’, ‘sub’, ‘mul’, or ‘div’, it must raise InvalidCommand. If the arguments cannot be converted to floats, it must raise InvalidCommand. 

validate_input(‘add 2 3’) -> (‘add’, [2., 3.])
validate_input(‘div 78 123’) -> (‘div’, [78., 123.])
validate_input(‘banana 2 3’) -> raises InvalidCommand()
validate_input(‘add thingy 3’) -> raises InvalidCommand()
validate_input(‘add’) -> raises InvalidCommand()
validate_input(‘add 2’) -> raises InvalidCommand()
validate_input(‘add 2 3 4’) -> raises InvalidCommand()

Answer:

, , , ,

No comments yet.

Leave a Reply

Powered by WordPress. Designed by WooThemes

Free WordPress Themes