简体   繁体   中英

Im trying to reduce brackets in math equations down to one number using a recursive function and I keep getting a list index out of range error

So what im trying to do is search for the inner most left hand bracket then find its partner and evaluate the expression in those brackets, after that replace the whole bracket and expression with one number and call the function again on the new list until im left with just one number after evaluating all brackets from most inward to most outward. Im sure theres a whole load of plugins i could get that just do that but this is trying to be a learning exercise so i dont think that would help me much.

def opperation(l):

  if l[1] == "+":
      return add(l[0], l[2])
  if l[1] == "-":
      return subtract(l[0], l[2])
  if l[1] == "*":
      return multiply(l[0], l[2])
  if l[1] == "/":
      return divide(l[0], l[2])
  if l[1] == "^":
      return power(l[0], l[2])

here opperation is handed a list of length 3 wich would be of the form "number" "opperation" "number"

def howdeep(l):
  level=0
  maxlevel=0
  for it in l:
      if it == "(":
          level=level+1
      if it == ")":
        level=level-1
      if level>maxlevel:
          maxlevel=level
  return maxlevel

how deep is just used to find how many brackets deep the program will have to go to find the bottom bracket

def condense(brackl):
  depth=howdeep(brackl)
  d=0
  index=0

  while d<depth:
      if(brackl[index]=="("):
          d=d+1
      index=index+1

  tempindex=index
  print(index)
  print(tempindex)
  print(brackl)

  while brackl[tempindex] != ")" or brackl[index] != "(":
      tempindex=tempindex+1
  tempindex=tempindex+1

  if len(brackl)>1:
      brackl[index]=opperation(brackl[index+1:index+4])
      del brackl[index+1:index+5]
      condense(brackl)
  else:
      return brackl[0]

condense is supposed to be the main part of the program to do all the reducing, but whenever i run it i get a list index out of range error on the line

    "while brackl[tempindex] != ")" or brackl[index] != "(":"

I tried to debug a little bit and when i print out the index at this point i get 9 which is one more than i expected but still shouldn't be out of bounds given the list i fed into it

main

l=["(","3","+","4","*","(","4","*","(","3","+","8",")",")",")"]

print (condense(l))

so to summarise I want to know

  1. Why its saying the indecie is out of range?
  2. And why it gets to 9 when it should stop at 8?

Your issue is that you add to index even after you have found a result which increases the number one more than it should be. As such, you should change your while loop to:

while d<depth:
    if(brackl[index]=="("):
        d=d+1
    index=index+1
index -= 1

Hope I helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM