if and elif issue for modular calculator

Back to Problem Solutions forum

ryancurtisacosta     2019-01-15 20:35:22
def modular_calculator(nums):
    count=0
    total=int(nums[0])
    for num in range(len(nums)):
        if num == '+':
            total=total+int(nums[counter+1])%(nums[-1])
            count+=1
        elif num == '*':
            total=total*int(nums[counter+1])%(nums[-1])
            count+=1
        else:
            count+=1    
        print (count)
        print (total)

I am sure there are more sophisticated ways to write this solution but even this simple version is not working. My if and elif lines never trigger with the practice data set:

['5', '+', '3', '', '7', '+', '10', '', '2', '*', '3', '+', '1', '%', '11']

My final count = 15 and that is true even when I remove the count+=1 in both the if and elif lines meaning that every iteration is going to else.

Any and all advice would be very helpful.

Rodion (admin)     2019-01-16 05:06:02
User avatar

Hello!

I'm afraid this may be the consequence of more than one, well, mistake. The whole fragment probably is a bit messed up - similar happens with me when I'm tired :)

  1. Are count and counter supposed to be the same?
  2. Add print(num) to see why it always goes to else - supposedly you wanted something different :)

By the way it seems if count += 1 is used in all three branches of your if-elif-else then you can instead put it just once before or after the whole if/else chain.

ryancurtisacosta     2019-01-16 17:06:13
def modular_calculator(nums):
    # ... some code followed ...
        #print (count)
        print (total)
        #print (num)

Haha! Yes! Many thanks.
Not sure if this will completely work yet but the practice set works and at least it iterated through the data set correctly. Great tip on print(num) to see what was being iterated.

best,

ryancurtisacosta     2019-01-16 17:16:22
def modular_calculator(nums):
    # see by link below
    return (total)%int(nums[-1])

final product. thanks again!

Rodion (admin)     2019-01-16 21:06:48
User avatar

Not sure if this will completely work

you know, of course, that the most important skill for a programmer is not writing code, but debugging it - so I don't want to bereave people of this fun :)

If you won't mind now, I'll cut the solution out of forum page - it is anyway accessible at your profile and we don't want to spoil the pleasure for others, right :)

Please login and solve 5 problems to be able to post at forum