我基本上想知道如何存储用户输入并按顺序从最小到最大,以帮助他们找到中间模式或范围。
from __future__ import division
amtnum = 0
sumofnums = 0
print "Hello, This program will help find the mean of as many numbers as you want."
useramtnum = input("How many numbers will you need to enter: ")#asks user to say how many numbers there are
while amtnum < useramtnum: #Tells program that while the amount of numbers is less than the users input amt of numbers to run.
amtnum = amtnum + 1 #Tells that each time program asks for number add one to amt of numbers
entnum = (int(raw_input("Enter a number:"))) #Asks user for number
sumofnums = entnum + sumofnums #Adds users number to all values
print "The amount of your numbers added up were:", sumofnums
print "The average/mean of your numbers were:", (sumofnums/useramtnum)
答案 0 :(得分:3)
将'em放在列表中并对其进行排序
mylist = []
while ...
mylist.append(entnum)
mylist.sort()
print mylist
答案 1 :(得分:1)
利用名为list的基本数据结构!
在while循环之前,创建一个列表(又名数组)
user_input_list = []
在while循环中获取用户的个人号码后,将输入添加到列表中(在while循环中)
user_input_list.append(entnum)
在while循环之后,对列表进行排序(它将在适当的位置排序)
user_input_list.sort()
然后,列表按用户的排序顺序排列每个输入,最少到最大。
要访问列表中的最后一项,请使用数组访问器。
user_input_list[-1]
要访问中位数,请利用您可以使用列表长度的事实。访问长度(列表)/ 2项
user_input_list[int( len(user_input_list) / 2)] #int cast used to remove decimal points
答案 2 :(得分:0)
我绝不是Python专家(就像我的第三个python程序一样),但我认为通常更容易调用函数,无论是Python还是其他任何语言。它使代码更具可读性。
这些都是基本的数学函数,所以我不会因为写这些函数而剥夺了你的知识。但是,我确实留下了range
函数给你写了。 (由于mylist
已排序,我确定您可以解决它。)
这允许用户连续输入数字并将平均值,中位数和模式吐回来。它不处理非整数输入。
from collections import Counter
from decimal import *
def getMode(l):
data = Counter(l)
mode = data.most_common(1)
print "mode:", mode
def getMean(l):
length = len(l)
total = 0
for x in l:
total = total + x
mean = Decimal(total) / Decimal(length)
print "mean:", mean
def getMedian(l):
median = 0
length = len(l)
if (length % 2 == 0):
median = (l[length/2] + l[length/2 - 1])/2.0
else:
median = l[length/2]
print "median:", median
mylist = []
print "Enter numbers to continually find the mean, median, and mode"
while True:
number = int(raw_input("Enter a number:"))
mylist.append(number)
mylist.sort()
getMean(mylist)
getMedian(mylist)
getMode(mylist)
答案 3 :(得分:0)
解决问题的解决方案:
示例:
numbers = []
while amount < counter:
...
numbers.append(num)
print sorted(numbers)
您可以在下面看一下代码的修改。
numbers = []
print "Hello, This program will help find the \
mean of as many numbers as you want."
while True:
try:
counter = input("How many numbers will you need to enter: ")
except:
print "You haven't entered a number."
else:
break
amount = 0
while amount < counter:
try:
num = input("Enter a number: ")
except:
print "You haven't entered a number."
else:
amount += 1
numbers.append(num)
print "The amount of your numbers added up were:", (sum(numbers))
print "The average/mean of your numbers were:", ( (sum(numbers)) / counter)
print "My list not in order:", numbers
print "My list in order:", sorted(numbers)