Last night, I was doing some code kata at codingbat.com when I was presented with the following problem:
Given a string and a non-negative int n,
we'll say that the front of the string is the
first 3 chars, or whatever is there
if the string is less than length 3.
Return n copies of the front;
front_times('Chocolate', 2) → 'ChoCho'
front_times('Chocolate', 3) → 'ChoChoCho'
front_times('Abc', 3) → 'AbcAbcAbc'
Pretty straightforward, right? The solution from the site was the following:
def front_times(str, n):
front_len = 3
if front_len > len(str):
front_len = len(str)
front = str[:front_len]
result = ""
for i in range(n):
result = result + front
return result
I went for a totally different solution though:
def front_times(str, n):
return n*(''.join([x for x in list(str[:3])]))
Is it something I’d use in production? Nope. It’s less readable and less pythonic, in my opinion, than the longer answer. (Although some would argue that you don’t get more pythonic than list comprehensions.)
Did it make me smile? Hell yes. Although ultimately, the most pythonic is probably:
def front_times(str, n):
return n*(str[:3])