Three empty cans can be exchanged for a new one. Suppose you have N cans of soda, try to use the program to solve how many cans of soda you can drink in the end?
Input description: Input a positive integer N. ex.5 / ex.100
Output description: The maximum number of sodas that can be drunk, and must have a newline character at the end. ex.7 / ex.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}')
`
I used while to finish the code which is on above, but I input 5 and output 6,and it is actually to be 7.The other side, I input 100 and output 132. Actually, the correct answer is 149.
>Solution :
You can try this way –
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))
The logic is simple and comments are added to explain.
In your code, the first thing to notice it generates wrong output when n is less than 3. For example for n = 2, your output is 3 which is not possible. Also in the while loop you are decrementing a by 3 for the exchange but you fail to add 1 to a for the one soda you can exchanging 3 empty cans. That is the issue. My above code addresses those issues