Python:基于值和频率输入的平均值

时间:2015-06-29 23:33:49

标签: python recursion input average computer-science

我正在尝试编写一个消耗自然正数n的python函数 number_pairs ,并从用户中读取n对自然正数。每对代表一个值及其频率。对于每对,该函数必须提示用户输入两个正整数值及其频率,同时指示预期对的索引。重复该过程直到输入所有n对。最后,函数应该打印n对数字的平均值(Float类型,如示例中的确切字符串消息),并返回平均值。您可以假设用户只输入有效数据 我在想,也许写一个辅助函数可以进行累积递归,但我错过了很多讲座,我不知道该怎么做。这就是我到目前为止所做的:

def averge_h(counter):
...

def number_pairs(n):
    prompt1 = "Enter value for pair number "
    prompt2 = "Enter its frequency:\n"
    pn = "{0}: ".format(n)
    res="Their average is: "
    v = int(input(prompt1+pn))
    f = int(input("Enter its frequency: "))

if n = 1:
    average = (v*f)/f
else:
    v = v+1

print res + str(average)
return average

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

def read_and_avg(sum_,n,left,i):  ## left is the number of times the input is to be taken
    if left == 0:
        print (sum_/float(n))
        return (sum_/float(n))
    else:
        i = i + 1
        print "Enter the values for pair number "+str(i)
        a = int(input())
        b = int(input())
        sum_ = sum_ + (a*b)                 ## Increment the sum 
        n = n + b                           ## Increment the total count 
        print sum_,n,left     
        return read_and_avg(sum_,n,left-1,i)  ## Decrease left by 1,


def func(n):
    read_and_avg(0,0,n,0)

答案 1 :(得分:0)

既然你说它只能有一个参数" n"看看这个:

def number_pairs(n):
    if n == 0:
        return 0
    else:
        average = number_pairs(n-1)

        print str(n) +  ("st" if n == 1 else ("nd" if n == 2 else ("d" if n == 3 else "th"))) + " pair"
        val = input("value: ")
        frq = input("frequency: ")
        print "" # added for new line

        return average + (val * frq)

n = input("Enter the number of pairs: ")
print "" # added for new line
print "The average is: " + str(number_pairs(n) / n)
Output:

Enter the number of pairs: 5

1st pair
value: 1
frequency: 2

2nd pair
value: 2
frequency: 2

3d pair
value: 3
frequency: 2

4th pair
value: 4
frequency: 2

5th pair
value: 5
frequency: 2

The average is: 6