Advertisement
Peaser

one line Anagram detector (Explained)

Sep 9th, 2014
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. isAnagram = lambda s1,s2 : False if False in map(lambda i: i in s1, s2) else True
  2.  
  3. print isAnagram("Hello", "ebola") # False
  4. print isAnagram("Hello", "olelH") # True
  5.  
  6. #### EXPLAINING BEGINS ####
  7.  
  8. # def isAnagram(s1,s2):
  9. ##Taking two arguments: s1, and s2, both being strings.
  10.  
  11. #return False if False in ... else True
  12. ##A clever one line solution as opposed to typing the following:
  13.  
  14. #if False in ...:
  15. #    return False
  16. #else:
  17. #    return True
  18.  
  19. #map(lambda i: i in s1, s2)
  20. #...
  21.  
  22.     #lambda i: i in ...
  23.     ##lambda is basically an on-the-go version of 'def' where 'i' is the argument of the function
  24.     ##You should know that 'x in y' returns True or False. This lambda function is basically saying:
  25.     #def function(i, ...): 
  26.     #    if i in ...:
  27.     #        return True
  28.     #    else:
  29.     #        return False
  30.    
  31.     #map(..., s2)
  32.     ##This is basically a 'zip()' but for functions.
  33.     ##It replaces the letters in s2 with the output of the 'lambda' function(which returns True or False).
  34.  
  35. #Now for an intentionally longer version...
  36.  
  37.  
  38. def isAnagram(s1, s2):
  39.  
  40.     confirmation = [] #blank list for later
  41.  
  42.     for i in s2:   #iterate over s1
  43.  
  44.         if i in s2:
  45.  
  46.             confirmation.append(True)
  47.  
  48.         else:
  49.  
  50.             confirmation.append(False)
  51.  
  52.     if True in confirmation:
  53.  
  54.         return True
  55.  
  56.     else:
  57.  
  58.         return False
  59.  
  60.  
  61.  
  62. #A shorter version:
  63.  
  64. def isAnagram2(s1, s2):
  65.  
  66.     confirmation = [] #blank list for later
  67.  
  68.     for i in s2:   #iterate over s1
  69.  
  70.         if i in s2:
  71.  
  72.             confirmation.append(True)
  73.  
  74.     if len(confirmation) > 0:  #True was the only thing we could have oppended to it
  75.     #So logically...
  76.  
  77.         return True
  78.  
  79.     else:
  80.  
  81.         return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement