def counts_from_file(filename): Given filename as a string indicating the name o
ID: 3821055 • Letter: D
Question
def counts_from_file(filename): Given filename as a string indicating the name of a file in the current directory. In the file, every line will contain a single integer and nothing else. The last character will always be a newline. The function should construct and return a dictionary with integer values from the file as keys and # of occurrences of the integers as values. Assumption: file indicated by filename exists in the current directory; file can be empty. Non-empty file can contain one or more lines ending with a newline. Each line contains a single Integer and nothing else. Examples given files to the right: counts_from_file("filel.txt") rightarrow {100:3, 3:1, 9:2} counts_from_file("file2.txt") rightarrow {1:1, 2:1, 3:1, 4:1, 5:1} Your work will be graded for correctness by provided test cases. The fraction of cases you pass will determine your score. If you hardcode answers (try to trick the testing file rather than just solving the task), we reserve the right to deduct any or all points. Partial credit may be awarded for partial answers; having a file that can be run greatly increases your chances of partial credit. You may not import anything. All taught data structures and built-in are allowed. Ask if you are unsure!Explanation / Answer
def counts_from_file(file):
with open(file) as f:
l = f.read().splitlines()
print(dict((x,l.count(x)) for x in set(l)))
counts_from_file('file1.txt')
counts_from_file('file2.txt')
Sample Output required:
{'9': 2, '100': 3, '3': 1}
{'4': 1, '2': 1, '3': 1, '1': 1, '5': 1}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.