1

I was doing some exercises on codewars and found this question:

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

after completing it and looking at others answers I found:

scramble=lambda a,b,c=__import__('collections').Counter:not c(b)-c(a)

Can someone explain what is happening here? Why is there a = after the declaration of lambda and how are the arguments being assigned???

I did not found much explanation on this.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
André
  • 23
  • 3
  • 1
    Beside the point, but just in case you weren't aware, [avoid named lambdas](/q/38381556/4518341), use a `def` instead. I suppose this is one reason why :) – wjandrea May 17 '23 at 03:33
  • 1
    BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea May 17 '23 at 03:34
  • 1
    Just to note, It's against PEP8 and not readable at all but a cool syntax useful for mini scripts in those websites. – S.B May 17 '23 at 04:06

1 Answers1

6

The equal sign is setting a default value for the c argument. The default value is __import__('collections').Counter.

The lambda is equivalent to

def scramble(a, b, c=__import__('collections').Counter):
    return not c(b)-c(a)

or, extracting the import,

import collections
def scramble(a, b, c=collections.Counter):
    return not c(b)-c(a)

except that __import__ doesn't assign the imported module to the collections variable.

user2357112
  • 260,549
  • 28
  • 431
  • 505
John Gordon
  • 29,573
  • 7
  • 33
  • 58