mburhm (07-02-2021)
Coded in IDLE. Project was to create a program that read the contents of a .txt file and calculated the avg of all numbers in the file. This was to be done using 2 Higher - Order Functions (mapping and reducing) of your choice. I've test ints and decimals with this program and it has worked perfectly, have not tried putting strings into the test file but I'd assume it wouldn't work for obvious reasons.
Code:import functools input_File = input('Name of file: ') #ask user for name of file file = open(input_File, 'r') #open file file = file.read() #read file file = file.split() #put numbers into list file = list(map(float, file)) #convert list into floats file_Sum = functools.reduce(lambda x, y: x + y, list(file)) #grabs sum of file print(file_Sum / len(file)) #average function using file sum from reduce fuction
mburhm (07-02-2021)
You can to implement a Try/Except block inside your map function at the point it does the data type conversion. If it throws an exception then just return null or 0 and suppress the error message.Code:file = list(map(float, file)) #convert list into floats
Matthew (02-08-2021)
Code:sum = 0 input_File = input('Name of file: ') file = open(input_File, 'r') file = file.read() file = file.split() total = len(file) for num in file: sum += int(num) print (f"Average number in {file} is {sum/total}")
MPGH's Rules | Marketplace | How IM works | Report Scam Attempt
In case you need me : IM | PM
Middleman from 29/01/2021 - present
Minion+ from 12/04/2020 - present.
Minion from 09/01/2020 - 12/04/2020.
MPGH News Force from 02/11/2019 - not sure anymore.
Resource Team from 02/11/2019 - 12/04/2020.
Premium Member since 16/09/2019.
Member since 13/10/2015.
Yo I like this ,very nice !