如何用python编写编码问题?



三个空罐子可以换一个新的。假设你有N罐苏打水,试着用这个程序来解决你最终能喝多少罐苏打水?

输入说明:输入正整数N. ex.5/ex.100

输出描述:可以喝的汽水的最大数量,并且必须在结尾有一个换行符。例7/例149'

n = int(input())
a = n-3 
sum = 0
while a > 2 :
sum += 1 
a -= 3 
print(f'{n+sum}')
if a == 2 :
print(f'{n+sum+1}')

我使用while来完成上面的代码,但我输入5并输出6,实际上它是7。另一边,输入100,输出132。实际上,正确答案是149。

你可以这样做-

def get_total_cans(n):
s = n # we can get at least n cans
while n > 2:
s += 1
n -= 3 # 3 exchanged
n += 1 # got 1 for the exchange
return s
n = int(input())
print(get_total_cans(n))

逻辑很简单,并添加了注释来解释。

在你的代码中,首先要注意的是当n小于3时它会产生错误的输出。例如,当n = 2时,你的输出是3,这是不可能的。同样,在while循环中,您将a减少3以换取交换,但您无法将a加1以换取可以交换3个空罐的汽水。这就是问题所在。我上面的代码解决了这些问题

这是一个递归方法:

def dr_cans(full, empty=0):
# if we have at least 3 empty cans, exchange them for a full one
if empty >=3:
return dr_cans(full+1,empty-3)
# no full cans, and not enough empty ones
if full == 0:
return 0
# at least one full can: drink it and gain an empty one
return 1 + dr_cans(full-1, empty+1)

如果我理解正确,问题如下:设k为交换过程的指标。因为不是所有的N都能被3整除,所以我们有N[k] = floor(M/3),每一步有M=N[k-1]+R[k-1]个新罐子。加上一些R[k] = M%3剩余的罐头,其中%是模算子…

有了这个应该很容易…

def compute_num_cans(empty_cans: int, exchange: int = 3) -> tuple:
"""
:param empty_cans: The number of cans to exchange
:return: tuple of (full_cans, empty_cans), where the empty cans are < exchange rate
"""
leftovers = empty_cans % exchange
full = empty_cans // exchange
return full, leftovers

EXCHANGE = 3
NUM_CANS = 51
print(f'Start with {NUM_CANS} and an exchange rate of {EXCHANGE}:1')
current_cans = NUM_CANS
drunk_cans = NUM_CANS
leftovers = 0
steps = 0
while current_cans >= EXCHANGE:
full, leftovers = compute_num_cans(current_cans, exchange=EXCHANGE)
current_cans = full + leftovers
drunk_cans += full
steps += 1
print(f'Cans drunk: {drunk_cans}, leftover cans: {leftovers}.')
print(f'A total of {steps} exchanges was needed.')

输出

# Start with 51 and an exchange rate of 3:1
# Cans drunk: 76, leftover cans: 0.
# A total of 4 exchanges was needed.

一般回答:- 如果我们改变numExchange也接受

代码:

def numWaterBottles(numBottles: int, numExchange: int) -> int:
ans=numBottles  #Initial bottles he/she will drink
while numBottles>=numExchange: #If numBottles<numExchange exit the while loop
remainder=numBottles%numExchange #remaining bottles which is not change
numBottles//=numExchange #The bottles which are changed
ans+=numBottles #The bottles which are changed added to the answer
numBottles+=remainder #Remaining bottles==The bottles which is not change+The bottles which are changed
return ans    #Return The answer

print(numWaterBottles(5,3))
print(numWaterBottles(100,3)) 
print(numWaterBottles(32,4)) #numexchange when different

输出: -

7
149
42

最新更新