Reputation: 75
I am creating a program to find Mean,Median,Mode, or Range. When I run this it works fine until it gets to the part of calculating the answer. It gives me a "cannot preform reduce with flexible type" error. I have searched this error but could not find what I needed to fix. This is my first time using numpy so any help would be great.
import sys
import numpy as np
welcomeString = input("Welcome to MMMR Calculator\nWhat would you like to calculate(Mean,Median,Mode,Range):")
if welcomeString.lower() == "mean":
meanNumbers = input("What numbers would you like to use?:")
print (np.average(meanNumbers))
stop = input()
if welcomeString.lower() == "median":
medianNumbers = input("What numbers would like to use?:")
print (np.median(medianNumbers))
stop = input()
if welcomeString.lower() == "mode":
modeNumbers = input("What numbers would you like to use?:")
print (np.mode(modeNumbers))
stop = input()
if welcomeString.lower() == "range":
rangeNumbers = input("What numbers would you like to use?:")
print (np.arange(rangeNumbers))
stop = input()
Upvotes: 7
Views: 26777
Reputation: 48745
This is not an answer (see @Sukrit Kalra's response for that), but I see an opportunity to demonstrate how to write cleaner code that I cannot pass up. You have a large amount of code duplication that will result in difficult to maintain code in the future. Try this instead:
import sys
import numpy as np
welcomeString = input("Welcome to MMMR Calculator\nWhat would you like to calculate(Mean,Median,Mode,Range):")
welcomeString = welcomeString.lower() # Lower once and for all
# All averages need to do this
numbers = input("What numbers would you like to use?:")
numbers = list(map(float, numbers.split(','))) # As per Sukrit Kalra's answer
# Use a map to get the function you need
average_function = { "mean": np.average,
"median": np.median,
"mode": np.mode,
"range": np.arange,
}
# Print the result of the function by passing in the
# pre-formatted numbers from input
try:
print (average_function[welcomeString](numbers))
except KeyError:
sys.exit("You entered an invalid average type!")
input() # Remove when you are done with development
Upvotes: 6
Reputation: 34493
You are passing a string to the functions which is not allowed.
>>> meanNumbers = input("What numbers would you like to use?:")
What numbers would you like to use?:1 2 3 4 5 6
>>> np.average(meanNumbers)
#...
TypeError: cannot perform reduce with flexible type
You need to make an array or a list out of them.
>>> np.average(list(map(float, meanNumbers.split())))
3.5
IF you're seperating the elements by commas, split on the commas.
>>> np.average(list(map(float, meanNumbers.split(','))))
3.5
Upvotes: 7