Home > Mobile >  fix a bug in a Python logical task
fix a bug in a Python logical task

Time:01-21

Task: The store wants to find out when it makes the most money during its open time during the day. Analysts have theorized that there are two intervals that bring the maximum profit.

For analysis, the sums of all checks were unloaded, including returns to the sequence of real numbers.

As the first step of the analysis, it is necessary to find the maximum sum of two consecutive non-empty sequences of receipts; it is not necessary to search for the receipts themselves.

Example 1 Input 1 2 3 -1 1 2 3 Conclusion 12

Example 2 Input 1 2 1 2 1 Conclusion 7

checks = list(map(float, input().split()))
max_profit = float('-inf')
current_profit = 0
for check in checks:
    current_profit  = check
    max_profit = max(max_profit, current_profit)
    if current_profit < 0:
        current_profit = 0
print(max_profit)

I got this code and I can't figure out the error. On the first test, it outputs 11, but it needs 12. The second test passes

CodePudding user response:

The checks on current_profit reset the current_profit when they are negative. Instead of resetting the current_profit, set the current_profit to the max_profit.

if current_profit < max_profit:
        current_profit = max_profit

Also, I suggest not using max_profit = float('-inf'). Consider: max_profit = 0.

CodePudding user response:

This is because you enter -1 number after another numbers and the sum of the past numbers -1, is bigger than 0. So the first solution is changing the code as I write below:

checks = list(map(float, input().split()))
# max_profit = float('-inf')
max_profit = 0
current_profit = 0
for check in checks:
    if check < 0:
        check = 0
    current_profit  = check
    max_profit = max(max_profit, current_profit)
    # if current_profit < 0:
    #     current_profit = 0
print(max_profit)

Also you can enter negative numbers first and then enter other numbers in your code!

  • Related