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
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
2-
Consider the following Python dictionary:
{'Wednesday': 'Wednesday', 'Thursday': 'chilly'}
Using the in keyword, would 'Wednesday' be considered a member of this dictionary? Ensure that you select the answer which also includes a correct explanation.
a.
No, because it is not a value in the dictionary.
b.
Yes, because it is a value in the dictionary.
c.
No, because it is not a key in the dictionary.
d.
No, because it is not both a key and a value in the dictionary (not just one or the other).
e.
Yes, because it is a key in the dictionary.
f.
Yes, because it is both a key and a value in the dictionary (not just one or the other).
arrow_forward
True/False 9. A Python dictionary is a kind of sequence.
arrow_forward
need help with python code. can you please keep it simple, I mean can you not use high-level python codes to answer this.
arrow_forward
Answer both questions must else downvote
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
Python
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 the ques in python with showing the code
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
1. Create a python dictionary dict that maps each (lower case) character of the basic Latin alphabet to another. Make sure no one letter is mapped to itself. Do not use a simple ordering, such as reversing the alphabet. This will act as your cipher.
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
Want python Program
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
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
Function in python thst inverts the key and value in a dictionary
If dictionary encounters more than one of the same key when trying to invert dictionary. Raise a key error
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
PYTHON!!!!
Write a function that takes two dictionaries as arguments and merges them into a new dictionary and returns this new dictionary. If the same key exists in both dictionaries, then the larger value is stored as the value of the key in the new dictionary. You can assume that all values are comparable.
"""
def mergeDicts(dict1, dict2):
arrow_forward
Answer both must else downvote
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
Python
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
5
arrow_forward
12
Language Python
arrow_forward
Describe the time complexity of common dictionary operations in Python, such as inserting, deleting, and searching for a key-value pair.
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
Python
arrow_forward
Question 4
Full explain this question and text typing work only
arrow_forward
Use python, import sys, 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. Your program should print in the form:
My GPA is x
Where x is equal to the GPA calculation
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
solution in python language
arrow_forward
Python
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
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
- 2- Consider the following Python dictionary: {'Wednesday': 'Wednesday', 'Thursday': 'chilly'} Using the in keyword, would 'Wednesday' be considered a member of this dictionary? Ensure that you select the answer which also includes a correct explanation. a. No, because it is not a value in the dictionary. b. Yes, because it is a value in the dictionary. c. No, because it is not a key in the dictionary. d. No, because it is not both a key and a value in the dictionary (not just one or the other). e. Yes, because it is a key in the dictionary. f. Yes, because it is both a key and a value in the dictionary (not just one or the other).arrow_forwardTrue/False 9. A Python dictionary is a kind of sequence.arrow_forwardneed help with python code. can you please keep it simple, I mean can you not use high-level python codes to answer this.arrow_forward
- Answer both questions must else downvotearrow_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_forwardPythonarrow_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_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_forwardPlease answer the ques in python with showing the codearrow_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_forward1. Create a python dictionary dict that maps each (lower case) character of the basic Latin alphabet to another. Make sure no one letter is mapped to itself. Do not use a simple ordering, such as reversing the alphabet. This will act as your cipher.arrow_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_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