-2

So, I have this:

while cancer[j] != ("l"or"r"or"c")

and it's stopping at the first "l" in the way when it has some r and c in between the string, its acting like there are not "or" and only the "l".

for example my string is this one:

c56r36c20l80c23l180c23l20c55r70

and it returns:

c56r36c20

It stops right at the first "l", skipping the "c" and "r" in the way.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
NachoLZ
  • 19
  • 3
  • 5
    `("l" or "r" or "c") == "l"`. You want `cancer not in {'l', 'r', 'c'}`. – Jeremy Mar 26 '16 at 00:35
  • please see in Python documentation how `or` operator works. `'l' or 'r' or 'c'` expression always have value `'l'`. You need the `not in` operator here. – m.wasowski Mar 26 '16 at 00:37
  • you need to learn what the `or` operator does logically. – n1c9 Mar 26 '16 at 00:37
  • 1
    @JeremyBanks wouldn't `not in "lrc"` work? – Reut Sharabani Mar 26 '16 at 00:38
  • @JeremyBanks never mind, sets are faster :) – Reut Sharabani Mar 26 '16 at 00:39
  • @ReutSharabani not in "lrc" worked like a charm! Thanks ! – NachoLZ Mar 26 '16 at 00:41
  • @NachoLZ - notice that looking in a set is actually faster, as Jeremy suggested, since it will be using hashes. No reason it shouldn't work. – Reut Sharabani Mar 26 '16 at 00:42
  • with 3 elements, i'd say looking over a tuple is faster, and should be lighter. But the lookup's so fast and the structure dies so quickly it barely matters. – Dleep Mar 26 '16 at 00:44
  • I still don't get what you are trying to extract from you string. You say that your program is skipping the c and the r. Do you want to extract each number that starts with c, r or l and stop if it starts with something else? – chapelo Mar 26 '16 at 00:48

2 Answers2

1

It's working properly; it just doesn't work how you think it should:

("l" or "r" or "c") 

returns the first nonfalse item (bool(item) is true) on that list, or false if there isn't any. That means it'll return "l".

So your while loop is actually:

while cancer[j] != "l":

What you want, instead, is something like:

while cancer not in ('l', 'r', 'c')

or

while not cancer in ('l', 'r', 'c')

Both are pretty much the same thing.

Dleep
  • 1,045
  • 5
  • 12
1

Usually, if one of the expressions in an 'or' statement evaluates to True, the rest of the expression is not evaluated at all. So when the first 'l' is encountered in the string, the while condition will break right there.

You should have something like:

while cancer[j] not in ('l', 'r', 'c'):