195k views
0 votes
Write a function named surveys that finds the sum of unique answers given to a collection of surveys as described below. Your function accepts a string representing a file name as a parameter where the file data consists of groups of lines separated by a blank line. Each non-empty line contains some subset of the lowercase letters a-z. Your goal is to find the total number of distinct letters used by each blank-lineseparated group, sum them, and return this sum. For example, if the file named surveys, txt contains the following: ab ac xy y k The first clump contains 3 unique letters: a,b, and c. The second clump contains 4 unique letters: x,y,z, and k. So the call of surveys ("surveys, txt") should return 3+4=7. You may assume that the file exists and is readable, that it follows the format described above, and that there will be at least one clump of surveys in the file.

User Hrobky
by
8.8k points

1 Answer

5 votes

Answer:

Here's the code for the surveys function:

```

def surveys(file_name):

with open(file_name, 'r') as file:

groups = file.read().split('\\\\') # split the file into groups

total = 0

for group in groups:

letters = set() # use a set to store unique letters

for line in group.split('\\'):

letters.update(set(line)) # add the letters to the set

total += len(letters) # add the number of unique letters to the total

return total

```

This function reads in the contents of the file using a with statement, then splits the file into groups using the `split` method with the argument `'\\\\'`. It then iterates over each group and uses a set to store the unique letters in that group. The `update` method of the set is used to add the letters from each line to the set. Finally, the length of the set is added to the total, and the function returns the total.

User Cybujan
by
7.7k points