The challenge
Don Drumphet lives in a nice neighborhood, but one of his neighbors has started to let his house go. Don Drumphet wants to build a wall between his house and his neighbor’s, and is trying to get the neighborhood association to pay for it. He begins to solicit his neighbors to petition to get the association to build the wall. Unfortunately for Don Drumphet, he cannot read very well, has a very limited attention span, and can only remember two letters from each of his neighbors’ names. As he collects signatures, he insists that his neighbors keep truncating their names until two letters remain, and he can finally read them.
Your code will show Full name of the neighbor and the truncated version of the name as an array. If the number of the characters in name is less than or equal to two, it will return an array containing only the name as is"
Test cases
Test.describe("Basic tests")
Test.assert_equals(who_is_paying("Mexico"),["Mexico", "Me"])
Test.assert_equals(who_is_paying("Melania"),["Melania", "Me"])
Test.assert_equals(who_is_paying("Melissa"),["Melissa", "Me"])
Test.assert_equals(who_is_paying("Me"),["Me"])
Test.assert_equals(who_is_paying(""), [""])
Test.assert_equals(who_is_paying("I"), ["I"])
Test.describe("Random tests")
from random import randint
base="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
sol=lambda s: [s] if len(s)<3 else [s,s[:2]]
for _ in range(40):
s="".join(base[randint(0,len(base)-1)] for q in range(randint(1,20)))
Test.assert_equals(who_is_paying(s),sol(s),"It should work for random tests too")
The solution in Python
Initially we can write it out like this:
def who_is_paying(name):
if name=="":
return [""]
if len(name)<=2:
return [name]
return [name, name[0:2]]
But this is not very pythonic
. We can always shorten it to a single line!
def who_is_paying(name):
return ([""] if name=="" else ([name] if len(name)<=2 else [name, name[0:2]]))
Another alternative is to do it with a lambda
:
who_is_paying = lambda n: [n, n[:2]] if len(n)>2 else [n]