softbass
BAN USERPython Code
def getChineseNum(n):
if "4" in str(n):
return "illegal"
i=len(str(n))-1
digitList=[int(x) for x in str(n)]
for i, d in enumerate(digitList):
if d>4:
digitList[i]-=1
digit=len(digitList)-1
out=0
for d in digitList:
out+=d*9**digit
digit-=1
return out
Based on:
ex 1: 562
if any of the digit is greater than 4 then subtract that digit by 1, so this will become now 455
now convert this number to base 9
9^2*4 + 9^1*5 + 9^0*2
324 + 45 + 2
371
ex 2: 123 (none of the digits are greater than 4, so no need to subtract by 1)
9^2*1 + 9^1*2 + 9^0*3
81 + 18 + 3
102
ex 3: 456
any of the digits contains 4 then return -1 as this is illegal
I did it recursively in Python:
def isAgg(n, path=[]):
#if the input is an integer change it into a string
n=str(n)
#if 1+1=2 in 112358
if len(path)==3 and sum(path[:2]) == path[2]:
#if a+b=c and there is nothing left, return True
if len(n)==0:
#print path, n
return True
#if a+b=c and there is leftover
else:
#print path, n
path.pop(0)
return True and isAgg(n, list(path) )
#if the sum of first two numbers is not the third number, discard the current path
elif len(path)>3:
return False
#for check all possible permutations: 112358 -> isAgg(1, 12358), isAgg(11, 2358), isAgg(112, 358),...
out=False
for i in range(1, len(n)+1):
out |= isAgg(n[i:], path + [int(n[:i])])
return out
print isAgg(112112224)
- softbass November 20, 2012