hailstone(num)
Question:
hailstone(num) 10 pts
Returns the hailstone sequence starting at the given number until termination when num is 1. The hailstone sequence is generated as follows:
- If ???????????? is even, then the next number in the sequence is ????????????/2.
- If ???????????? is odd, then the next number in the sequence is 3∗ ???????????? + 1.
- Continue this process until ???????????? = 1
The use of type conversion such as int(), and list comprehension syntax are not allowed.
Preconditions and Postconditions num: int -> An positive integer Returns: list -> Hailstone sequence starting at num and ending at 1.
Examples:
>>> hailstone(5)
[5, 16, 8, 4, 2, 1]
>>> hailstone(6)
[6, 3, 10, 5, 16, 8, 4, 2, 1]
Question #5: selecting(employees, hired) 10 pts Given the dictionary employees and a list of keys hired, return a new dictionary that only consists of the key:value pairs whose key is in the hired list.
Preconditions and Postconditions employees: dict -> keys and values are both strings hired: list -> non-empty sequence of strings
Returns: dict -> key:value pairs from employees where key is in the list hired
Examples:
>>> employees = {"Alice": "Engineer", "Bob": "Manager", "Carol": "Sales"}
>>> hired = ["Alice", "Bob"]
>>> selecting(employees, hired)
{"Alice": "Engineer", "Bob": "Manager"}
>>> employees
{"Alice": "Engineer", "Bob": "Manager", "Carol": "Sales"}
Question #6: overloaded_add(d, key, value) 10 pts Given a dictionary d, a key, and a value, this function adds the key:value pair to the dictionary d. If the key doesn't already exist in the dictionary, this function should simply add it. However, if the key already exists, then rather than overriding the previous value, the dictionary should start keeping a list of values for that key, in the order they are added.
Preconditions and Postconditions d: dict -> You cannot make any assumptions about the size or contents of d key: any immutable type value: any
Returns: None
Examples:
>>> my_dict = {"Alice": "Engineer"}
>>> overloaded_add(my_dict, "Bob", "Manager")
>>> my_dict
{"Alice": "Engineer", "Bob": "Manager"}
>>> overloaded_add(my_dict, "Alice", "Sales")
>>> my_dict
{"Alice": ["Engineer", "Sales"], "Bob": "Manager"}
Allowed methods, operators, and libraries:
- type() or isinstance() methods
type([5.6]) == list returns True
isinstance([5.6], list) returns True
- list concatenation (+) or append()
Reading files
You will be required to read data from .txt files. The starter code already contains the code to open and close the txt file (Files will be closed automatically at the end of with statement block or if any exceptions or errors occur in the process), just make sure the file is in the same directory as your .py file.
The given code to read the txt file uses read(), but there are three different ways you can read a file. You might choose any of the other two if it fits the outline of your program better. If you are new to reading files in Python, I suggest you try them all first using the read_files.py file so you can decide which one to use.
Example using words.txt:
ball bats bird toys treat bin tree boy
Reading a text file using iteration
- The file is an iterable that generates one line at a time
- Each line generated is a string, ending with a newline (\n)
lines = [] with open(filename) as file: for line in file:
lines.append(line)
print(lines)
['ball\n', 'bats\n', 'bird\n', 'toys\n', 'treat\n', 'bin\n', 'tree\n', 'boy']
Reading a text file using read()
- Reads everything in the original file into one big string all the way to the end of the file.
with open(file) as f: contents = f.read() print(contents)
'ball\nbats\nbird\ntoys\ntreat\nbin\ntree\nboy'
Reading a text file using readlines()
- Reads everything in the original file into a list of lines (similar to iteration that appends to a list)
with open(filename) as file: contents = file.readlines() print(contents)
['ball\n', 'bats\n', 'bird\n', 'toys\n', 'treat\n', 'bin\n', 'tree\n', 'boy']
Question # 7 successors(file) 15 pts
Returns a dictionary whose keys are included words (as is), and values are lists of unique successors to those words. The first word of the txt file is always a successor to ".". Be careful with punctuation. You can assume the text in the txt file does not contain any contraction words (isn't, don't, I'm, etc) but you cannot make assumptions about the spacing or the presence of nonalphanumerical characters. The starter code already contains the code to read the txt file, just make sure the file is in the same directory as your .py file. You must write your code ,the file has been read to process the contents.
# Open the file and read the contents, the with statement ensures the fileproperly closed the file operation finishes with open(file) as f:
contents = f.read() # reads the entire file, saving data in contents as string
items.txt:
We came to learn,eat some pizza and to have fun. Maybe to learn how to make pizza too!
>>> print(contents)
'We came to learn,eat some pizza and to have fun.\nMaybe to learn how to make pizza too!'
Hints:
- The str.isalnum() method returns True if all characters in a string are alphanumeric.
- When x = 'We', the type conversion list(x) produces the list ['W', 'e']
Preconditions and Postconditions file: str -> A string that contains the name of a txt file that contains multiple strings
Returns: dict -> Keys are all included words and punctuation marks, values all successors of that key
Example:
Contents of items.txt: We came to learn,eat some pizza and to have fun. Maybe to learn how to make pizza too!
>>> out=successors('items.txt') >>> out.keys() dict_keys(['.', 'We', 'came', 'to', 'learn', ',', 'eat', 'some', 'pizza', 'and', 'have', 'fun', 'Maybe', 'how', 'make', 'too']) >>> out['.'] ['We', 'Maybe'] >>> out['to'] ['learn', 'have', 'make'] |
>>> out['fun']
['.']
>>> out[',']
['eat']
>>> out # Don't forget dictionaries are unsorted collections
{'.': ['We', 'Maybe'], 'We': ['came'], 'came': ['to'], 'to': ['learn', 'have',
'make'], 'learn': [',', 'how'], ',': ['eat'], 'eat': ['some'], 'some': ['pizza'],
'pizza': ['and', 'too'], 'and': ['to'], 'have': ['fun'], 'fun': ['.'], 'Maybe': ['to'], 'how': ['to'], 'make': ['pizza'], 'too': ['!']}
Allowed methods, operators, and libraries:
- str.split(sep) returns a list of the words in the string, using sep as the delimiter string o 'a b c'.split(' ') returns ['a', 'b', 'c'] o 'a,b,c'.split(',') returns ['a', 'b', 'c'] o 'a=b'.split('=') returns ['a', 'b']
- str.strip(), returns a copy of the string with the leading and trailing characters removed. o ' a , b '.strip() returns 'a , b' o ' a , b\n'.strip('\n') returns ' a , b'
- The str.join(iterable) method returns a string which is the concatenation of the strings in iterable o ''.join(['a', 'b', 'c']) returns 'abc' o '-'.join(['a', 'b', 'c']) returns 'a-b-c' o ' '.join(['a', 'b', 'c']) returns 'a b c'
- Loops and conditionals
- Append or list concatenation (+)
def hailstone(num):
"""
>>> hailstone(10)
[10, 5, 16, 8, 4, 2, 1]
>>> hailstone(1)
[1]
>>> hailstone(27)
[27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]
>>> hailstone(7)
[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
>>> hailstone(19)
[19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
"""
#- YOUR CODE STARTS HERE
pass
def selecting(employees, hired):
"""
Takes a dictionary of employees and a list of hired employees.
Returns a new dictionary with only the hired employees.
>>> employees = {"Alice": "Engineer", "Bob": "Manager", "Carol": "Sales"}
>>> hired = ["Alice", "Bob"]
>>> selecting(employees, hired) == {"Alice": "Engineer", "Bob": "Manager"}
True
>>> employees == {"Alice": "Engineer", "Bob": "Manager", "Carol": "Sales"}
True
"""
#- YOUR CODE STARTS HERE
pass
def overloaded_add(d, key, value):
"""
Adds the key value pair to the dictionary. If the key is already in the dictionary, the value is made a list and the new value is appended to it.
>>> d = {"Alice": "Engineer"}
>>> overloaded_add(d, "Bob", "Manager")
>>> overloaded_add(d, "Alice", "Sales")
>>> d == {"Alice": ["Engineer", "Sales"], "Bob": "Manager"}
True
"""
#- YOUR CODE STARTS HERE
pass
def successors(file):
"""
>>> expected = {'.': ['We', 'Maybe'], 'We': ['came'], 'came': ['to'], 'to': ['learn', 'have', 'make'], 'learn': [',', 'how'], ',': ['eat'], 'eat': ['some'], 'some': ['pizza'], 'pizza': ['and', 'too'], 'and': ['to'], 'have': ['fun'], 'fun': ['.'], 'Maybe': ['to'], 'how': ['to'], 'make': ['pizza'], 'too': ['!']}
>>> returnedDict = successors('items.txt')
>>> expected == returnedDict
True
>>> returnedDict['.']
['We', 'Maybe']
>>> returnedDict['to']
['learn', 'have', 'make']
>>> returnedDict['fun']
['.']
>>> returnedDict[',']
['eat']
"""
with open(file) as f:
contents = f.read()
# --- YOU CODE STARTS HERE