Problem Description: A wine dealer has 5 barrels of wine and 1 barrels of beer, 6 barrels in capacity of 30 liters, 32 liters, 36 liters, 38 liters, 40 liters and 62 liters,
And only sell the whole barrel of wine, not retail. The first customer bought 2 whole barrels of wine, and the second customer bought twice times as much wine as the first customer.
So, how many liters of beer would it have been?
Analysis: As the wine merchants only sell the whole barrel of wine, a few barrels of the capacity to analyze, the second customer must buy the remaining 3 barrels of wine can be twice times the first customer.
Assuming the first customer buys a total of L liters, the second customer buys 2L liters. In other words, the total number of wines should be divisible by 3. So, the solution is on the horizon.
Python Solution 1
1 buckets = {30,32,36,38,40,62}2 total = SUM (buckets) 3 for item in Buckets:4 if (total-item)% 3 = = 0:5 Print (item ) 6 Break
Although this can be easy to solve the problem, but consider a little more, attention to the topic "only sell the whole barrel" this restriction, more standardized solution is as follows (but it seems not necessary)
Solution 2
1 buckets = {30,32,36,38,40,62} 2 def solve (buckets): 3 Total = SUM (buckets) 4 for item in Buckets:5 Div,mod = Divmod ((total-item), 3) 6 if mod = = 0:7 for i in buckets:8 j = div-i 9 if J!=i and (J in Buckets): Return (item, (I,J)) return ' no answer ' print (Solve (buckets))
Line 8th of the code because the first customer bought 2 barrels of wine and the sum, so to verify the existence of the 2 barrels of wine, if not present return no answer.
Java implementation (Java base is relatively shallow, write code is very difficult to see, if there is a better way of writing to enlighten you)
1 public static int bear () {2 int buckets[] = {30,32,36,38,40,62}, 3 int sum = 0; 4 for (int bs:buckets) {5
sum + = BS; 6 } 7 for (int i=0;i<6;i++) {8 int rest = Sum-buckets[i]; 9 int mod = rest% 3;10 if (mod = = 0) {11
int div = rest/3;12 for (int j=0;j<6;j++) {int = Sep = div-buckets[j];14 if (Sep! = buckets[j] & ;& inbuckets (sep,buckets)) { return buckets[i];16}17}18}19 }20 return 0;21 }22 public static Boolean inbuckets (int x,int[] buckets) { 25 (int i=0;i<buckets.length;i++) if (x = = Buckets[i]) { true;27 }28 }29 return false;30 }
Reference number Python_xiaowu
Python solves beer problems (Ctrip 2016 questions)