python - Syntax explanation: .join(char for char in n if char.isalpha()), return n == n[::-1] -


def palindrome(n):     n = n.lower()     n = ''.join(char char in n if char.isalpha())     return n == n[::-1] 
  1. n = ''.join(char char in n if char.isalpha())

  2. return n == n[::-1]

can break syntax of these 2 lines down process process?

(char char in n if char.isalpha()) pretty says in almost-english: creates generator - kind of unrealised list, can 1 element @ time - yield every char char comes n, if char.isalpha() (i.e. char alphanumeric). thus, n = "the meth", t, h, e, m, e, t , h, in order (but not space, not alphanumeric).

string.join(iterable) can take iterable (like list, or generator), , slap string between each element. if provide empty string, smoosh elements of iterable without in between. themeth - original string cleared of not letter or number.

string[from:to:step] way of slicing substrings string (or subarrays array). can leave out part of it: "012345"[1::3] take every 3rd character staring 1st (well, 2nd if you're not computer), resulting in "14". if step negative, from , to defaults reversed, , n[::-1] means "every -1th character end start", word, reversed. "themeth"[::-1] "themeth"; "the meth" palyndrome.


*) meth bad, m'kay? don't smoke it, don't deal it, don't deal it; here easy palyndrome.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -