0

I am new to programming and am trying to code a simple calculator. The code takes user input, generates a list of numbers and operators (eg. 1+2/3*4) and loops over the list to perform the calculation with operator precedence.

My logic is to search for operator, get index of the numbers before and after operator, perform calculation on numbers, delete numbers used in calculation from list, delete operator from list, insert result of calculation at index of operator.

all is working well except the delete part;

def calc():
    for combsym in comb:
        while combsym == '*':
            mulindex = comb.index(combsym)
            aindex = mulindex - 1
            a = comb.pop(aindex)
            mulindex = comb.index(combsym)
            bindex = mulindex + 1
            b = comb.pop(bindex)
            mul(a,b)
            mulindex = comb.index(combsym)
            comb.remove(mulindex)
            comb.insert(mulindex, result)

I get the following error: list.remove(x): x not in list

Any suggestions?

Alias
  • 3
  • 1

1 Answers1

0

Instead of remove use pop, which removes an object by index rather than by comparing value:

comb.pop(mulindex)
Or Y
  • 2,088
  • 3
  • 16
  • and just like that, it works. – Alias Jan 11 '21 at 16:07
  • This is likely to miss list elements due to things being removed from the list while iterating over it. See the answers to the duplicate question if you want to understand why this won't really work. – Tom Karzes Jan 12 '21 at 00:18