首先题目大意是:
有两种杯子,一个是5L的容量,一个是3L的容量,如何得到4L的水.(水是无限的,可以适当的文字描述)
答案:
很显而易见是有两种情况
- 3+3-5+3
- 5+5-3
显然第二种的方法最好
我试想能不能用代码来实现
目前还有些缺陷....有好的方法可以留言... XD
2020.06.23留,此代码不是最佳选择...
例:
def run(a,b,target):
result_0 , times_0 = add(a,b,target)
result_1 , times_1 = sub(a,b,target)
result = ''
if times_0 > times_1:
result = 'RunTimes: {0}\nResult: {1}'.format(times_1,result_1)
elif times_0 < times_1:
result = 'RunTimes: {0}\nResult: {1}'.format(times_0,result_0)
else:
result = 'RunTimes: {0}\nResult: {1}'.format(times_0,result_0)
return result
def add(a,b,target):
box = {}
box['max_box'] = int(max(int(a),int(b)))
box['min_box'] = int(min(int(a),int(b)))
target = int(target)
if target > box['max_box']:
return 'False',0
elif target == box['min_box'] or target == box['max_box']:
print('run times: 1')
return target,1
add = box['min_box']
box['result'] = count = 0
result = '{0} = '.format(target)
while(box['result'] != target):
box['result'] += int(add)
result += ' +{} '.format(add)
count += 1
if box['result'] >= box['max_box'] :
box['result'] -= box['max_box']
result += ' -{} '.format(box['max_box'])
count += 2 #如果算上倒水的 则改为 2
return result , count
def sub(a,b,target):
box = {}
box['max_box'] = int(max(int(a),int(b)))
box['min_box'] = int(min(int(a),int(b)))
target = int(target)
if target > box['max_box']:
return 'False',0
elif target == box['min_box'] or target == box['max_box']:
print('run times: 1')
return target,1
sub = box['min_box']
box['result'] = box['max_box']
#box['tmp'] 剩余容量的变量
box['tmp'] = count = 0
result = '{0} ='.format(target)
while(box['result'] != target):
result += ' +{0} -{1}'.format(box['result'],sub)
box['result'] -= sub
count += 1
if box['result'] > 0 :
result += ' +{0} -{1} + {2}'.format(box['max_box'],box['min_box'],box['result'])
box['result'] = box['max_box'] - box['min_box'] + box['result']
count += 2 #如果算上倒水的 则改为 2
return result , count
a,b,target = input('Input a b target: ').split()
print(run(a,b,target))