Assignment 3(1)
.docx
keyboard_arrow_up
School
University of Texas, Dallas *
*We aren’t endorsed by this school
Course
4381
Subject
Computer Science
Date
May 5, 2024
Type
docx
Pages
7
Uploaded by AmbassadorMonkeyPerson711 on coursehero.com
ITSS 4381.001 Spring 2024 – Assignment 3
Part 1 – Multiple Choice [40 Points]
Each question is 5 points. Highlight your answer.
1. What happens when you add a key that already exists to a Python dictionary?
A) A duplicate key-value pair is created, allowing multiple values for the same key.
B) Python raises a KeyError, indicating that duplicate keys are not allowed.
C) The value associated with the existing key is updated to the new value.
D) The dictionary remains unchanged, ignoring the new key-value pair.
2. Which method allows you to safely remove a key from a dictionary and specify a default return value if the key does not exist, thereby avoiding a KeyError
?
A) pop()
B) del()
C) popitem()
D) remove()
3. What is a key characteristic that distinguishes tuples from lists in Python?
A) Tuples can contain elements of different types, while lists cannot.
B) Tuples are immutable, meaning once a tuple is created, its contents cannot be changed.
C) Tuples are used exclusively for numerical data, while lists can contain any type of data.
D) Tuples do not support indexing and slicing operations, unlike lists.
4. When using the open() function in Python to perform file operations, which of
the following is the recommended way to handle exceptions, such as attempting
to open a file that does not exist?
A) Use a conditional statement to check if the file exists before attempting to open
it.
B) Utilize a try-except
block, catching the FileNotFoundErro
r exception to handle cases where the file does not exist.
C) Ignore error handling; Python automatically creates the file if it does not exist, regardless of the operation.
D) Call the os.exit()
function if a FileNotFoundError
is encountered to gracefully exit the program.
5. Which of the following best describes the role of the self
parameter in the __init__
method of a Python class?
A) It refers to the class itself and is used to define class variables.
B) It is a placeholder for future arguments that might be passed to the method.
C) It represents the instance of the class and is used to access attributes and methods.
D) It specifies that the method should be automatically called when the class is first defined.
6. When creating a child class in Python, what is the correct way to call a method from the parent class within the child class
?
A) Use the super() function followed by the method name to call the parent class's
method.
B) Use the method directly as if it were defined within the subclass itself.
C) Prefix the method name with the parent class's name followed by a dot (.) operator.
D) It's not possible to call a method from the parent class within the subclass; methods must be redefined.
7. In Python, how does method overriding work when dealing with inheritance?
A) By declaring a method in the subclass with a different name but the same functionality as the one in the parent class.
B) By defining a method in the subclass that has the same name as a method in the parent class, thus replacing the parent class's method when called on an instance of the subclass.
C) By using the override keyword before a method in the subclass to explicitly indicate that it should replace a parent class method.
D) Method overriding is not supported in Python; each subclass method must have a unique name.
8. Why is data normalization considered an important step in data preprocessing
before applying machine learning algorithms?
A) It converts all data to binary format, making it easier for algorithms to process the data.
B) It reduces the data to a simpler form where all features contribute equally, preventing biases in the machine learning model.
C) Normalization applies different scaling factors to each feature to enhance their original variance, making them more distinct.
D) It ensures that all data points are limited to a specific range, such as 0 to 1, which helps in speeding up calculations and improving algorithm performance.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
True/False 9. A Python dictionary is a kind of sequence.
arrow_forward
python code. instructions are given within the code.
1) def invert_dict(d): """ Given a dictionary d, create the invert of the dictionary where the key is a value v in d, and v is mapped to a set of keys in original d whose values are equal to v. Return the inverted dictionary mapping value to set of keys """
return {1:1}
2) def histogram(words):
""" Given a list of words, create a histogram dictionary where the key is the length of a word and the value is the count of how many words in the list are of that length. Return the histogram dictionary mapping length to word counts """
return {1:1}
3) def max_kv(d):
""" Given a dictionary, return a tuple of key value pair where the key is the largest in d. """
return (1, {1})
arrow_forward
Displays a rank in the defined dictionary.a) Create a dictionary, rank = {1:"Freshman", 2:"Sophmore", 3:"Junior", 4:"Senior"}b) Request a user input for a number of years.c) Print the value of the matching key in the dictionary.d) Print the error message if input is invalid.
In actual code and psuedocode. Using python programming language.
arrow_forward
Please answer with Python
Question 1: write a program that keeps a dictionary in which both keys and values are strings, names of students and their courses grades. Prompt the user of the program to add or remove students, to modify grades, or to print all grades. The printout should be sorted by name and formatted like this:Carl: B+Joe: CSarah: AFrancine: A
Current Code:
# Manage student grades.
# Use a dictionary to track student grades.grades = {}
# Loop until the user chooses to quit.choice = ""while choice != "Q" :choice = input("(A)dd, (R)emove, (M)odify, (P)rint all, or (Q)uit? ")choice = choice.upper()# write your code here
arrow_forward
python code. define the run function. Instructions are given within the quotations.
1)def invert_dict(d):
"""
Given a dictionary d, create the invert of the dictionary where
the key is a value v in d, and v is mapped to a set of keys in original
d whose values are equal to v.
Return the inverted dictionary mapping value to set of keys
"""
2)def histogram(words):
"""
Given a list of words, create a histogram dictionary where the key
is the length of a word and the value is the count of how many
words in the list are of that length.
Return the histogram dictionary mapping length to word counts
"""
3)def max_kv(d):
"""
Given a dictionary, return a tuple of key value pair where the key
is the largest in d.
"""
4)def run():
"""
Get words list from the file listed in argv[1];
create histogram of count of each word length;
create invert dictionary that maps count to list of word length;
use invert dictionary to find the list of word length with the
most popular word count (use max_kv)
"""…
arrow_forward
Create a dictionary in Python that contains the details of one customer in a bank. Display the complete dictionary. The perform the following operations on it:
a)Randomly pop a value from the dictionary.
b) Add a new key and value to the dictionary.
c) Update the value of a key in the dictionary and delete one key from the dictionary. d)Print the length of the dictionary.
e) Print the keys and values of the dictionary separately.
arrow_forward
Dictionary & Tuple
1. Write a Python program to combine two dictionaries into one by adding values for
common keys. Input contains two comma separated dictionaries. Print the new
dictionary and create a tuple which contains unique values in sorted order.
Sample Input
а: 100, b: 100, с: 200, d: 300
а: 300, b: 200, d: 400, e: 200
Sample Output
{'a': 400, 'b': 300, 'c': 200,'d': 700, 'e': 200}
Values: (200, 300, 400, 700)
6.
2. Write a python program which prints the frequency of the numbers that were
given as input by the user. Stop taking input when you find the string "STOP". Do
not print the frequency of numbers that were not given as input. Use a dictionary
to solve the problem
Sample Input
Sample Output
10 - 2 times
10
20
20 - 2 times
20
30 - 1 times
50 - 1 times
90 - 1 times
30
10
50
90
STOP
arrow_forward
answer the following questions:
1: A dictionary is an unordered collection of key-value pairs. True or False
2: What is printed by the following statements?
mydict = {"cat":12, "dog":6, "elephant":23}
print (mydict ["dog"])
3: What is printed by the following statements?
mydict = {"cat":12, "dog":6, "elephant":23}
mydict ["mouse"] = mydict ["cat"] + mydict ["dog"]
print (mydict ["mouse"])
4: What is printed by the following statements?
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
print (inventory.get("apples"))
print (inventory.get("cherries"))
(inventory.get("cherries", 0))
5: What is printed by the following statements?
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
for akey in inventory.keys ():
print("Got key", akey, "which maps to value", inventory [akey])
ks list (inventory.keys ())
=
print (ks)
# the order in which we get the keys is not defined
arrow_forward
Please help me with my assignment I need to submit it today.
Create a Python dictionary that returns a list of values for each key. The key can be whatever type you want.
Design the dictionary so that it could be useful for something meaningful to you. Create at least three different items in it. Invent the dictionary yourself. Do not copy the design or items from some other source.
Next consider the invert_dict function from Section 11.5 of your textbook.
# From Section 11.5 of: # Downey, A. (2015). Think Python: How to think like a computer scientist. Needham, Massachusetts: Green Tree Press.
def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = [key] else: inverse[val].append(key) return inverse
Modify this function so that it can invert your dictionary. In particular, the function will need to turn each of the list items into separate keys in the inverted…
arrow_forward
1. Using python, create a program that uses a dictionary that performs contact tracing of persons.
2. The key is the person number and the values is a list of person numbers who are close contacts of this
person.
3. The program inputs the person number and list of contacts for 3 persons.
4. Each person has 2 contacts.
5. This data is saved in a dictionary with the person numbers as keys, and the list of contacts as values.
6. The last input is the person number to query, and the program prints the list of close contacts. The
program also prints the list of close contacts of those in close contact to the person queried.
7. The program prints 'No Contact' if there is no person record for a contact.
8. There is exactly 10 input integers and the input are all positive integers.
9. For this program, use python Dictionary get() Method.
10. Take a screenshot of your codes on your python complier and the expected output as well.
SAMPLE INPUT 2
SAMPLE INPUT 1
# key person 1, person ID
# close…
arrow_forward
Python
Write a function print_dict to print all the key-values in a dictionary, for example: >>> d2 {'a': 'one', 'b': 'two', 'c': 'Three'} >>> print_dict(d2) a:one b:two c:Three
arrow_forward
Estimated Completion Time: 2 minutes
You are now working for Prof. Midas on a research project. You are given this piece of code to review which is
intended to be a better and faster implementation of a function that checks whether a given key is in a
dictionary (i.e., key lookup). You have to present your findings to
Prof. Midas. Select all the findings which you will NOT present (i.e., select all answers which are FALSE).
def key_in_dict(d, k):
for item in d:
if k == item:
return True
return False
This code would always be slower than the builtin key lookup Python provides.
O A key lookup in a dictionary in Python is generally faster than determining whether a value is in a list.
O This code is way faster and will be included in the next version of Python (version 4.1).
The code is incorrect from a functional perspective, the True and False should be switched.
This code could be replaced with one line: return k in d
O The code is correct and would always perform faster than the…
arrow_forward
python: answer in one line of code if possible, please
def traditions_dict(adict): """ Question 6 Given a dictionary that maps a person to a list of their favorite GT traditions, return a dictionary with the value being the list sorted by the last letter of each tradition. If two traditions have the same last letter, sort by the first letter.
HINT: This will require the use of lambda functions
Args: adict (dict) Returns: dict
>>> traditions_dict({"Jacob": ["The Horse", "Stealing the t", "Midnight Bud"], "Athena": ["Mini Five-Hundred", "Freshman Cake Race", "Buzzweiser Song"], "Liv": ["Freshman Cake Race", "George P. Burdell", "Buzzweiser Song"]})
{'Jacob': ['Midnight Bud', 'The Horse', 'Stealing the t'], 'Athena': ['Mini Five-Hundred', 'Freshman Cake Race', 'Buzzweiser Song'], 'Liv': ['Freshman Cake Race', 'Buzzweiser Song', 'George P. Burdell']}
>>>…
arrow_forward
Date: 26th April 2021
Course: BIT1054 Fundamental of Computational Thinking:
Python
d) Write a Python program that stores information below in a dictionary. Then, update the
age to 19 years old and add another entry named 'College' with value 'City University'.
Print out the age and college.
Name:
Lee Chong Wei
Age:
20
Course:
Computer Science
[5 marks]
Answer:
arrow_forward
Part 2
• Create a dictionary with at least five key-value pairs. Use strings for either the keys, the values, or both.
• On a single line, display your dictionary's keys and values, with a comma between each pair.
• Modify one of the values in your dictionary.
o On a single line, display your dictionary's keys and values, with a comma between each pair.
• Delete one of the key-value pairs from your dictionary.
o On a single line, display your dictionary's keys and values, with a comma between each pair.
Print a blank line.
• Display your dictionary's keys, one per line.
• Print a blank line.
• Display your dictionary's values, one per line.
Do not print curly braces, quotation marks, or colons.
Do not hard code anything in your print statements!
Do not use my key-value pairs. Choose your own!
For extra credit, do not print the trailing (final) comma on each of the first three lines of output.
Sample output:
Buffalo Sabres, Toronto Maple Leafs, Boston Bruins, Ottawa Senators, Montreal…
arrow_forward
1. Write a Python function called
add_daily_temp that is given a (possibly
empty) dictionary meant to hold the
average daily temperature for each day of
the week, a temperature value, and the day
of the week for the recorded
temperature. The function should then add
the temperature to the dictionary
only if it does not already contain a
temperature for that day. The function
should return the resulting dictionary,
whether it is updated or not.
arrow_forward
In python which of the following is true about dictionaries?
A. A dictionary can contain multiple items with the same key.
B. A key has to be mutable.
C. Values don’t have to be unique.
D. A key doesn’t have to be unique.
Which one?
arrow_forward
In python:
Problem Statement:The program takes a string and creates a dictionary with key as first character and value as thecount of letter in the string and also, sort the dictionary w.r.t the values of count in descendingorder.
Pseudocode:Start of build_dict function An empty dictionary is declared Start of for loop to traverse through the letters of the string If letter is not present as a key in the dictionary The letter is initialized as the key and assign 1 to it ( since initially the count would be 1) Else The value of the letter as key in the dictionary is increased by 1
End of build_dict function
Sort the dictionary and assign it back to the same dictionary variableStart of print_dict function Iterate over all the items of the dictionary Print the key and valueEnd of print_dict function
Start of main function User must enter a large string and store it in a variable Call the build_dict function with string parameter and return…
arrow_forward
1. Write a Python function called add_daily_temp that is given a (possiblyempty) dictionary meant to hold the average daily temperature for each day ofthe week, a temperature value, and the day of the week for the recordedtemperature. The function should then add the temperature to the dictionaryonly if it does not already contain a temperature for that day. The functionshould return the resulting dictionary, whether it is updated or not.
arrow_forward
Hashing Project in Python to Extract Features of Names
You are given the following three functions. They take plain text names and covert then into features vefctors so that you can work with them in a classification system.
Let's check your understanding of Python function. Add notes to each line describing what is happening in these functions.
FUNCTION ONE:
def hashfeatures(baby, B, FIX):
"""
Input:
baby : a string representing the baby's name to be hashed
B: the number of dimensions to be in the feature vector
FIX: the number of chunks to extract and hash from each string
Output:
v: a feature vector representing the input string
"""
v = np.zeros(B)
for m in range(FIX):
featurestring = "prefix" + baby[:m]
v[hash(featurestring) % B] = 1
featurestring = "suffix" + baby[-1*m:]
v[hash(featurestring) % B] = 1
return v
FUNCTION TWO:
def name2features(filename, B=128, FIX=3, LoadFile=True):
"""
Output:
X : n feature…
arrow_forward
1. Create a dictionary using java
arrow_forward
QUESTION 10
List is a collection of elements with the same type that can be accessed by index. The size of list can increase dynamically
O True
O False
QUESTION 11
In C#, Dictionary is used to store a collection of key-value pairs. Keys can be null or duplicated. Values must be unique and cannot be null.
O True
O False
QUESTION 12
https://wtclass.wtamu.edu/webapps/assessment/take/launch.jsp?course_assessment_id=_183007_1&course_id=_55233_1&content_id=_2535180_1&step=null
QUESTION 13
No matter how many objects of the class are created, there is only one copy of the static member belonging to the class.
O True
O False
4
Q Search
static elements can be accessed directly using the class name without an object.
O True
O False
W
67%
arrow_forward
Write a function, young_john(people), that returns True if the dictionary people contains the key "John" with a value of 19. It should return False otherwise.
like this
def young_john(people):
arrow_forward
Topic: Database
On my bookshelf of paper books, I have a dictionary that consists of multiple volumes, each of which is a book. One covers A-E, another F-J, another K-M, and so on. To find a word, I look at the alphabetic ranges to find the right volume. Then I use the ranges at the top of each page to turn to the proper page. Then I find the word on the page. Pick the correct answer.
A. Multi-level Indexes
B. Secondary indexes
C. None the above
arrow_forward
python:
def traditions_dict(adict): """ Question 6 Given a dictionary that maps a person to a list of their favorite traditions, return a dictionary with the value being the list sorted by the last letter of each tradition. If two traditions have the same last letter, sort by the first letter.
HINT: This will require the use of lambda functions
Args: adict (dict) Returns: dict
>>> traditions_dict({"Jacob": ["The Horse", "Stealing the t", "Midnight Bud"], "Athena": ["Mini Five-Hundred", "Freshman Cake Race", "Buzzweiser Song"], "Liv": ["Freshman Cake Race", "George P. Burdell", "Buzzweiser Song"]})
{'Jacob': ['Midnight Bud', 'The Horse', 'Stealing the t'], 'Athena': ['Mini Five-Hundred', 'Freshman Cake Race', 'Buzzweiser Song'], 'Liv': ['Freshman Cake Race', 'Buzzweiser Song', 'George P. Burdell']}
>>> traditions_dict({"Madison": ["The Horse", "Midnight Bud", "Buzzweiser…
arrow_forward
In python
without using pandas, .head, .iloc, or .select
create a function that returns a dictionary of only the columns specified from a data set
example
car = {suv, sedan, coupe}
speed = {10, 20, 30]
color = {green, white, black}
if given the parameter of "color" should return a table with all values in color dictionary
arrow_forward
gpacalc.py by using 'sys.argv"
● Use the following dictionary to complete this assignment: {'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0, 'B-':2.66, 'C+':2.33, 'C':2.0, 'C-':1.66, 'D+':1.33, 'D':1.00, 'D-':.66, 'F':0.00} ● Create a program, gpacalc.py, that takes four letter grade arguments and prints out the corresponding GPA, to two decimals. Your program should work both in arguments are upper-case and lower-case. The values should be to two decimal places. Your program should print in the form: “My GPA is x” Where x is equal to the GPA calculation
arrow_forward
185e
def find(self, key):
186e
187
188
Efficiency:
189
Finds and returns a copy of value in the set that matches key.
Use: value = source.find(key)
190
191
192
193
Parameters:
194
key
- a partial data element (?)
195
Returns:
196
value - a copy of the full value matching key, otherwise None (?)
197
198
199
200
# your code here
201
arrow_forward
1. Write a Python program to print every key-value pair of a dictionary line by line.
2. Write a Python program to merge two Python dictionaries.
arrow_forward
def invert_dict(d):
"""
Given a dictionary d, create the invert of the dictionary where
the key is a value v in d, and v is mapped to a set of keys in original
d whose values are equal to v.
Return the inverted dictionary mapping value to set of keys
"""
arrow_forward
def histogram(words):
"""
Given a list of words, create a histogram dictionary where the key
is the length of a word and the value is the count of how many
words in the list are of that length.
Return the histogram dictionary mapping length to word counts
"""
arrow_forward
Consider the following Python dictionary variable definition:
occupations = {'steve': 'plumber', 'mason': 'mason'}
Using the in keyword, would 'mason' be considered a member of occupations? Ensure that you select the answer which also includes a correct explanation.
a.
Yes, because it is a value in the dictionary.
b.
No, because it is not a value in the dictionary.
c.
Maybe, it depends on how the code is commented.
d.
Yes, because it is a key in the dictionary.
e.
No, because it is not a key in the dictionary.
arrow_forward
Python
The program will create a quiz that will ask for the capital of a random state. Your program will repeat so that a total of 5 random states are presented to the user
Write a program that creates a dictionary containing the U.S. states as keys, and their capitals asvalues. (Use the Internet to get a list of the states and their capitals.) The program should then randomly quiz the user by displaying the name of a state and asking the user to enter that state’s capital. The program should keep a count of the number of correct and incorrect responses. (As an alternative to the U.S. states, the program can use the names of countries and their capitals.)
arrow_forward
Implement the function common_players. The common_players function takes in a roster dictionary and identifies which
keys share the same values. The function returns a new dictionary of this structure:
Keys: The values from the roster dictionary
Values: A list of keys from roster that share that same value.
def common_players (roster):
"""Returns a dictionary containing values along with a corresponding
list of keys that had that value from the original dictionary.
>>> full_roster = {"bob": "Team A", "barnum": "Team B", "beatrice": "Team C", "bernice": "Team B", "b
>>> player_dict = common_players (full_roster)
>>> dict(sorted (player_dict.items()))
{'Team A': ['bob', 'belle', 'baxter'], 'Team B': ['barnum', 'bernice', 'bill', 'bernie'], 'Team C': [
||||||
"*** YOUR CODE HERE ***"
S
O
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education
Related Questions
- True/False 9. A Python dictionary is a kind of sequence.arrow_forwardpython code. instructions are given within the code. 1) def invert_dict(d): """ Given a dictionary d, create the invert of the dictionary where the key is a value v in d, and v is mapped to a set of keys in original d whose values are equal to v. Return the inverted dictionary mapping value to set of keys """ return {1:1} 2) def histogram(words): """ Given a list of words, create a histogram dictionary where the key is the length of a word and the value is the count of how many words in the list are of that length. Return the histogram dictionary mapping length to word counts """ return {1:1} 3) def max_kv(d): """ Given a dictionary, return a tuple of key value pair where the key is the largest in d. """ return (1, {1})arrow_forwardDisplays a rank in the defined dictionary.a) Create a dictionary, rank = {1:"Freshman", 2:"Sophmore", 3:"Junior", 4:"Senior"}b) Request a user input for a number of years.c) Print the value of the matching key in the dictionary.d) Print the error message if input is invalid. In actual code and psuedocode. Using python programming language.arrow_forward
- Please answer with Python Question 1: write a program that keeps a dictionary in which both keys and values are strings, names of students and their courses grades. Prompt the user of the program to add or remove students, to modify grades, or to print all grades. The printout should be sorted by name and formatted like this:Carl: B+Joe: CSarah: AFrancine: A Current Code: # Manage student grades. # Use a dictionary to track student grades.grades = {} # Loop until the user chooses to quit.choice = ""while choice != "Q" :choice = input("(A)dd, (R)emove, (M)odify, (P)rint all, or (Q)uit? ")choice = choice.upper()# write your code herearrow_forwardpython code. define the run function. Instructions are given within the quotations. 1)def invert_dict(d): """ Given a dictionary d, create the invert of the dictionary where the key is a value v in d, and v is mapped to a set of keys in original d whose values are equal to v. Return the inverted dictionary mapping value to set of keys """ 2)def histogram(words): """ Given a list of words, create a histogram dictionary where the key is the length of a word and the value is the count of how many words in the list are of that length. Return the histogram dictionary mapping length to word counts """ 3)def max_kv(d): """ Given a dictionary, return a tuple of key value pair where the key is the largest in d. """ 4)def run(): """ Get words list from the file listed in argv[1]; create histogram of count of each word length; create invert dictionary that maps count to list of word length; use invert dictionary to find the list of word length with the most popular word count (use max_kv) """…arrow_forwardCreate a dictionary in Python that contains the details of one customer in a bank. Display the complete dictionary. The perform the following operations on it: a)Randomly pop a value from the dictionary. b) Add a new key and value to the dictionary. c) Update the value of a key in the dictionary and delete one key from the dictionary. d)Print the length of the dictionary. e) Print the keys and values of the dictionary separately.arrow_forward
- Dictionary & Tuple 1. Write a Python program to combine two dictionaries into one by adding values for common keys. Input contains two comma separated dictionaries. Print the new dictionary and create a tuple which contains unique values in sorted order. Sample Input а: 100, b: 100, с: 200, d: 300 а: 300, b: 200, d: 400, e: 200 Sample Output {'a': 400, 'b': 300, 'c': 200,'d': 700, 'e': 200} Values: (200, 300, 400, 700) 6. 2. Write a python program which prints the frequency of the numbers that were given as input by the user. Stop taking input when you find the string "STOP". Do not print the frequency of numbers that were not given as input. Use a dictionary to solve the problem Sample Input Sample Output 10 - 2 times 10 20 20 - 2 times 20 30 - 1 times 50 - 1 times 90 - 1 times 30 10 50 90 STOParrow_forwardanswer the following questions: 1: A dictionary is an unordered collection of key-value pairs. True or False 2: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23} print (mydict ["dog"]) 3: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23} mydict ["mouse"] = mydict ["cat"] + mydict ["dog"] print (mydict ["mouse"]) 4: What is printed by the following statements? inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print (inventory.get("apples")) print (inventory.get("cherries")) (inventory.get("cherries", 0)) 5: What is printed by the following statements? inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} for akey in inventory.keys (): print("Got key", akey, "which maps to value", inventory [akey]) ks list (inventory.keys ()) = print (ks) # the order in which we get the keys is not definedarrow_forwardPlease help me with my assignment I need to submit it today. Create a Python dictionary that returns a list of values for each key. The key can be whatever type you want. Design the dictionary so that it could be useful for something meaningful to you. Create at least three different items in it. Invent the dictionary yourself. Do not copy the design or items from some other source. Next consider the invert_dict function from Section 11.5 of your textbook. # From Section 11.5 of: # Downey, A. (2015). Think Python: How to think like a computer scientist. Needham, Massachusetts: Green Tree Press. def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = [key] else: inverse[val].append(key) return inverse Modify this function so that it can invert your dictionary. In particular, the function will need to turn each of the list items into separate keys in the inverted…arrow_forward
- 1. Using python, create a program that uses a dictionary that performs contact tracing of persons. 2. The key is the person number and the values is a list of person numbers who are close contacts of this person. 3. The program inputs the person number and list of contacts for 3 persons. 4. Each person has 2 contacts. 5. This data is saved in a dictionary with the person numbers as keys, and the list of contacts as values. 6. The last input is the person number to query, and the program prints the list of close contacts. The program also prints the list of close contacts of those in close contact to the person queried. 7. The program prints 'No Contact' if there is no person record for a contact. 8. There is exactly 10 input integers and the input are all positive integers. 9. For this program, use python Dictionary get() Method. 10. Take a screenshot of your codes on your python complier and the expected output as well. SAMPLE INPUT 2 SAMPLE INPUT 1 # key person 1, person ID # close…arrow_forwardPython Write a function print_dict to print all the key-values in a dictionary, for example: >>> d2 {'a': 'one', 'b': 'two', 'c': 'Three'} >>> print_dict(d2) a:one b:two c:Threearrow_forwardEstimated Completion Time: 2 minutes You are now working for Prof. Midas on a research project. You are given this piece of code to review which is intended to be a better and faster implementation of a function that checks whether a given key is in a dictionary (i.e., key lookup). You have to present your findings to Prof. Midas. Select all the findings which you will NOT present (i.e., select all answers which are FALSE). def key_in_dict(d, k): for item in d: if k == item: return True return False This code would always be slower than the builtin key lookup Python provides. O A key lookup in a dictionary in Python is generally faster than determining whether a value is in a list. O This code is way faster and will be included in the next version of Python (version 4.1). The code is incorrect from a functional perspective, the True and False should be switched. This code could be replaced with one line: return k in d O The code is correct and would always perform faster than the…arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education