The Trip problem (uva 10137) is a very interesting mathematical operation problem, which can be stated as (from onlinejudge)
A number of students are members of a club group agrees in advance to share expenses equally, but it is not practical to have them share every expense as it occurs. So individuals in the group pay for particular things, like meals, hotels, taxi rides, plane tickets, etc. After the trip, each student’s expenses are tallied and money is exchanged so that the net cost to each is the same, to within one cent. Challenge is to find minimum amount required to exchange so that total spend can be equally divided.
Sample Input
3
10.00
20.00
30.00
0
Sample output
$10.00
Explanation
For given first lined input, number of students followed by their spends, we have to sum up all and find the minimum amount which can be exchanged in order to equally distribute it among students. Pretty straight forward solution given as
Code
main_list = []
l1 = []
l2 = []
avg = 0
total = 0
n = int(input())
if(n%2==0):
m = n/2
for i in range(0,n):
l1.append(float(input()))
avg+=l1[i]
avg = avg/n
def diff(x,n):
if(x>n):
return x-n
else:
return n-x
for i in range(0,n):
difference = diff(l1[i],avg)
if difference in l2:
continue
else:
l2.append(difference)
for i in l2:
total = total + i
if(n%2==0):
total = total / m
print("amount of exchange = ",total)
First, we accept all the inputs from user(i.e spends by each student) then we calculate average and store it in variable 'avg'. Now, for each spend we calculate difference between spend and average and append difference into the list L2.
If we found difference is already exists in list, then we skip that itteration and move to next. If you observe this ensures that if someone spended extra X amount then someone spended less X amount.
Finally we sum up all differences in list L2 and add them, after divide the result by total number of students to get minimum amount of exchange.
Related keywords: uva the trip, the trip uva solution, the trip problem inpython, the trip problem solution, the trip problem hackerrank, uva 10137 problem explanation, uva 10137 the trip problem source code.
Hey there but there in online judge shows an wrong answer after submission.Please help
ReplyDeleteIt is wrong because it doesn't accurately calculate the decimal numbers
Delete