0

I am using the current function to make sure that none of the array elements start with specific 2 variables:

def checkDuplicates(x, y, array):
    for l in array:
        match l:
            case [x, y]:
                return False
            case [x, y, _]:
                return False
            case other:
                return True

and at some point, I had x as 1, y as 2, and l as [1,2]. There it matched the first case and returned false. However, when I used x as 1, y as 3 and l as [1,2], it for some reason changed y to 2 once it got to the first case statement, and didn't return True when it had to. Why could that be?

I learned about this concept on this website

hellwraiz
  • 359
  • 2
  • 13
  • Could you comment on what you think `case [x, y]:` does? – Brian61354270 Jul 26 '23 at 14:24
  • @Brian61354270 I assumed that it would work like in the second case of the "Patterns in Python structural pattern matching" part in the https://www.infoworld.com/article/3609208/how-to-use-structural-pattern-matching-in-python.html website . Actually, I think that it would be a good idea to add that website to the question. – hellwraiz Jul 26 '23 at 14:27
  • 1
    See https://stackoverflow.com/questions/66159432/how-to-use-values-stored-in-variables-as-case-patterns – Anentropic Jul 26 '23 at 14:27
  • @Anentropic I looked at that post, and there they are having a different error of something not being recognised. Here however, the value is recognised, but gets changed. So not sure if that helps. – hellwraiz Jul 26 '23 at 14:33
  • @DarkKnight I thought so too. However, when debugging, I saw that it would change the y value from 3 to 2 right after the case [x, y] statement. – hellwraiz Jul 26 '23 at 14:35
  • 1
    @hellwraiz the variables that you use in `case [x, y]` will **catch** the values in `l` and eventually overwrite them. Try to define `checkDuplicates(array)` and keep the rest of the code, `x`/`y` will still be defined, because that's what `case` does ;) – mozway Jul 26 '23 at 14:37
  • Btw, the error in the [linked Q/A](https://stackoverflow.com/q/66159432/16343464) is due to the fact that the code uses semantically 3 times the same `case` (`case X` / `case Y` / `case _` is semantically the same thing "catch the full value in the variable"). If you keep only one `case`, this goes back to your issue. – mozway Jul 26 '23 at 14:41
  • 1
    @hellwraiz what the existing SO question I sent shows is that you can't use variables in your match case... `case [x, y]` does not use the values of `x` and `y` but instead creates two new variables to use in the body of the case. See the answers on the other question for ways to work around this – Anentropic Jul 26 '23 at 14:57
  • ah, I see now. Tried using a case[var1, var2] if var1 == x and var2 == y statement, and it worked, thanks! – hellwraiz Jul 26 '23 at 16:14

0 Answers0