1

my study question is: Define a procedure, total_enrollment, that takes as an input a list of elements, where each element is a list containing three elements: a university name, the total number of students enrolled, and the annual tuition fees.

The procedure should return two numbers, not a string, giving the total number of students enrolled at all of the universities in the list, and the total tuition fees (which is the sum of the number of students enrolled times the tuition fees for each university).

the code given is:

usa_univs = [ ['California Institute of Technology',2175,37704],
          ['Harvard',19627,39849],
          ['Massachusetts Institute of Technology',10566,40732],
          ['Princeton',7802,37000],
          ['Rice',5879,35551],
          ['Stanford',19535,40569],
          ['Yale',11701,40500]  ]

my solution is:

def total_enrollment(a):
    total_students = 0
    costsum = 0
    for e in a:
        total_students = total_students + e[1]
        costsum = costsum + e[2]
    all_in_all = total_students * costsum
    return total_students
    return all_in_all

what I should see is: 77285,3058581079

What actually comes out is: 77285 - and no total number

4

3 回答 3

15

你不能从一个函数返回两次。您可以将这两个值都返回为tuple

return total_students, all_in_all

然后将返回值解压缩到两个变量中。

例如:

>>> def func():
...     return 1, 2
... 
>>> v1, v2 = func()
>>> v1
1
>>> v2
2
于 2013-07-22T18:28:00.873 回答
2

首先,您不能返回两次,将代码更改为此以返回一个元组。

我还修正了计算总成本的数学。您将学生总数乘以总成本,您想分别计算每所大学。加州理工学院的学生将支付 37704 美元,而不是所有大学的总费用。

def total_enrollment(a):
    total_students = 0
    all_in_all = 0
    for e in a:
        total_students = total_students + e[1]
        all_in_all += (e[1] * e[2])
    return (total_students, all_in_all)

然后你可以像这样访问它们

>>>result = total_enrollment(usa_univs)
>>>print result[0]
77285
>>>print result[1]
3058581079
于 2013-07-22T18:32:05.120 回答
0

“感谢您的澄清。我已经进行了更改,但第二个答案仍然是错误的 21014177925 而不是 3058581079。知道为什么会这样吗?”

错误在这里:

for e in a:
    total_students = total_students + e[1]
    costsum = costsum + e[2]

您将每所大学的成本相加,然后将这个总和(大于个人教育成本)乘以每个学生。想想这是否是你真正想做的。

于 2013-07-22T18:46:18.207 回答