Reputation: 402
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
Upvotes: 1
Views: 202
Reputation: 17971
First of all, you can't return twice, change your code to this in order to return a tuple.
Also I fixed your math for calculating total cost. You were multiplying total students by total cost, you want to calculate each university separately. Students at CalTech are going to pay $37704, not the total cost of all universities.
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)
Then you could access them like this
>>>result = total_enrollment(usa_univs)
>>>print result[0]
77285
>>>print result[1]
3058581079
Upvotes: 2
Reputation: 5280
"Thanks for the clarification. I've made that change but the second answer still comes out wrong as 21014177925 instead of 3058581079. Any idea why that is the case?"
The error is here:
for e in a:
total_students = total_students + e[1]
costsum = costsum + e[2]
You are summing up the costs for every university and then multiplying this sum -- which is greater than the cost of an individual's education -- by every student. Think about whether or not this is what you really want to do.
Upvotes: 0
Reputation: 213193
You can't return twice from a function. You can rather return both the values as tuple
:
return total_students, all_in_all
And then unpack the return value in two variables.
E.g.:
>>> def func():
... return 1, 2
...
>>> v1, v2 = func()
>>> v1
1
>>> v2
2
Upvotes: 15