5
I like to do programming challenges in my free time to teach myself and keep fresh, this one I can't seem to optimize though and it's driving me insane.
The goal is essentially, "Given a number, return the numbers leading up to it as a palindrome."
For example if you are given the input 5
the answer your program should return is: 123454321
The catch? You have to solve it in as few characters as possible. The minimum needed seems to be 41 characters and I can't condense it past 76.
I have tried all sorts of solutions, here are a few:
# Note: "Palindromic_Number" is required. "def P(N):" will not work.
def Palindromic_Number(N):
a = ''
for x in range(1,N+1):
a += str(x)
return a + a[::-1][1:]
def Palindromic_Number(N):
a = ''.join(map(str, range(1,N+1)))
return a + a[::-1][1:]
def Palindromic_Number(N):
a = ''.join([str(x) for x in range(1, N+1)])
return a + a[::-1][1:]
# This one uses Python 2.7
Palindromic_Number = lambda N: ''.join(map(str, range(1,N+1) + range(1,N+1)[::-1][1:]))
Does anyone have any ideas as to how I could shorten my code? I'm just looking for a point in the right direction where to look as this point.
2
range(1,N)+range(N,0,-1)
should be shorter than usinga+a[::-1][1:]
afterwards as it allows you to not definea
at all. – 301_Moved_Permanently – 2015-10-06T21:44:08.550Forget it, it won't be so usefull. You can't add ranges in python 3. Only in python 2 where the builtin returns a list. – 301_Moved_Permanently – 2015-10-07T05:23:39.063
3What's the input range? 1 to 9? 0 to 9? – Martin Ender – 2015-10-07T11:33:08.770