0

I am taking some arbitrary expression like 6 ++++6, or 6+---+++9++5 and need to parse it into its simplest form (so eg 6+6 and 6-9+5) Why does the following code result in an infinite loop? From debugging I can see that the string is being successfully updated, but it's like the condition is not being reevaluated.

while "--" or "+-" or "-+" or "++" in user_input:
        user_input = user_input.replace("--", "+")
        user_input = user_input.replace("+-", "-")
        user_input = user_input.replace("-+", "-")
        user_input = user_input.replace("++", "+")
Wesley Cheek
  • 1,058
  • 12
  • 22
  • 1
    `while "foo" or "bar" in str:` is evaluated as `while ("foo") or ("bar" in str):`. Since `"foo"` is a truthy value, it's evaluated as `true` and the left or the condition isn't evaluated – Cid Jun 18 '20 at 10:47

2 Answers2

2

You can make use of any, to create a well defined break-condition for your while loop:

replacements = [
    ("--", "+"),
    ("+-", "-"),
    ("-+", "-"),
    ("++", "+")
]

user_input = '6+---+++9++5'
while any(pattern[0] in user_input for pattern in replacements):
    for pattern in replacements:
        user_input = user_input.replace(*pattern)
print(user_input)

Out:

6-9+5
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • I always love the use of fixed parameters as opposed to writing manually each line. A list of `(objects, methods, values)` is so fancy and practical to call `getattr(obj, method)(value)` on many items at once. – Guimoute Jun 18 '20 at 11:03
1

The way your check whether a string is in user_input is wrong because "--" or "+-" or "-+" or "++" in user_input evaluates to something true.

You need to do

while any(string in user_input for string in ("--", "+-", "-+", "++")):
    # Replacements.
Guimoute
  • 4,407
  • 3
  • 12
  • 28