0

I am writing python code for algebraic expansion and I am running into a major error, python is not able to recognize the existence of a conditional it seems and I cannot figure out why

The code is:

def This(String):
    ReturnList = [char for char in String]
    Returner = []
    Counter = 0
    while len(ReturnList) > 1:
        TempString = ""
        for x in range(len(ReturnList)):
            Counter += 1
            if ReturnList[x] != "+" or ReturnList[x] != "-":
                print(ReturnList[x])
                TempString += str(ReturnList[x])
            else:
                break
        for x in range(Counter):
            ReturnList.pop(0)
        Returner.append(TempString)
        Counter = 0
    return Returner


here = "a^3 + 3a^2b + 3ab^2 + b^3"
print(here)
print(This(here))

The code is suppose to take the string, and then return sections of it, like this:

["+a^3","+3a^2b","+3ab^2","+b^3"]

however it doesnt seem to recognize + or - in the list, and just ignores it to return the full string

This is the print statements output:

a
^
3
 
+
 
3
a
^
2
b
 
+
 
3
a
b
^
2
 
+
 
b
^
3
  • 2
    `here = a^3 + 3a^2b + 3ab^2 + b^3` doesn't set `here` to a string and is syntactically incorrect. – Michael Butscher Jun 24 '20 at 04:24
  • sorry I have a method that returns a string, I forgot to add in the parenthesis, one moment – ColorBand12 Jun 24 '20 at 04:25
  • Don't use `str(ReturnList[x])`, `ReturnList[x]` is already a character, so use: `TempString += ReturnList[x]` – RufusVS Jun 24 '20 at 04:31
  • 2
    `ReturnList[x] != "+" or ReturnList[x] != "-"` is always true because if it is `+`, it isn't `-` so at least one of the `or`ed parts is always true. You need `and` here. – Michael Butscher Jun 24 '20 at 04:33
  • Please use [python 's convention](https://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names) to name variables. They aren't classes, use lowercase and `_`. And use more meaningful names in general – Pynchia Jun 24 '20 at 04:50

1 Answers1

1

I think if you change if ReturnList[x] != "+" or ReturnList[x] != "-": to if ReturnList[x] != "+" and ReturnList[x] != "-":, it should work. The reason why the first one doesn't work is because it is always true, no matter what the character is.

JaysFTW
  • 101
  • 6