Introduction
Problem: Given a list of words, return the list of numbers which represents the number of letters in that word that is the same as its position in the alphabet. Source
Final solution:
def solve(arr):
return [sum(i == ord(c) - ord('a') for i, c in enumerate(s.lower())) for s in arr]
First attempt:
def solve(arr):
letters = "abcdefghijklmnopqrstuvwxyz"
def f(word):
c = 0
for (i, j) in enumerate(word):
if i > 25: return c
if letters[i] == j:
c+=1
return c
arr = map(lambda x: x.lower(), arr)
res = list(map(f, arr))
return res
solve(["encode","abc","xyzD","ABmD"]) // 1, 3, 1, 4
solve(["abode","ABc","xyzD"]) // 4, 3, 1
The lessons
Get rid of lambdas and map
arr = map(lambda x: x.lower(), arr)
# can always be replaced by
arr = [x.lower for x in arr]
A counter can be replaced with sum
c = 0
...
if cond: c+=1
...
# Can be replaced by
sum(cond for ...)
# e.g.
def f(word):
return sum(letters[i] == j for (i,j) in enumerate(word))
Trick for finding distance of letters
# Instead of hard coding letters, or numbers
letters = "abcd..."
letters[i] == j
# Replace it with
i == Ord(j) - Ord("a")
Conclusion
We have seen how we can use list comprehension to simplify our problem.