import math import random import string def pr1(n): accu = 0 for i in range(1, n+1): accu += 1/math.log(i*i+1) return accu def pr1a(n): return sum([1/math.log(i*i+1) for i in range(1, n+1)]) def pr2(lista): return lista[random.randint(0, len(lista)-1)] def pr3(filename): #initialize a counting dictionary with the letters dic = {} for letter in string.ascii_letters: dic[letter]=0 #open the file and count ASCII letters only with open(filename) as inf: for line in inf: for letter in line: if letter in dic: dic[letter]+=1 #Now find the highest values by walking through the dictionary winner, runnerup = '', '' #initialize the winning letters winval, runupval = 0, 0 #initialize the winning frequency for key in dic: if dic[key] > winval: runnerup, runupval = winner, winval #demote current winner winner, winval = key, dic[key] #new one takes the lead elif dic[key] > runupval: runnerup, runupval = key, dic[key] return winner, runnerup, dic def pr4(lista): return len(lista), sum(lista) def pr5filegenerator(filename): """we need a file to test problem 5 on, so here we generate it""" with open(filename, "w") as outf: for _ in range(20): for i in range(random.randint(1, 5)): print(random.randint(1, 100), end=" ", file = outf) print(file = outf) #need to generate a new line def pr5(filename_in, filename_out): with open(filename_in) as inf, open(filename_out, "w") as outf: for line in inf: numbers = [int(number) for number in line.split()] print(sum(numbers), file=outf) def pr6(filename): count = 0 with open(filename) as infile: while True: try: line=infile.readline() if not line: break count += 1 except UnicodeDecodeError: count += 1 return count