def flip(st):
return st[::-1].translate({ord('6'):ord('9'), ord('9'):ord('6')})
def is_strobo(st):
return flip(st) == st and all(c in "0125689" for c in st)
tests = (("69", "88"), ("99", "101"), ("999", "1001"), ("161", "181"), ("9987", "10001"), ("654321", "655559"),
("1260921", "1261921"), ("88888888", "88896888"),
("123456789", "125000521"), ("314159265359", "500000000005"),
("6920158510269", "6920160910269"), ("12688109960188921", "12688110001188921"))
def next_strobogrammatic(s):
_next = dict(zip("0123456789", "1255568890"))
l = len(s)
if l % 2 == 0:
st = s[:l // 2]
if all(c in '0125689' for c in st):
j = len(st) - 1
while j >= 0 and st[j] == '9':
j -= 1
if j == -1:
return '1' + '0' * (len(s) - 1) + '1'
else:
left = (st[:j] + _next[st[j]]).ljust(len(st), '0')
return left + flip(left)
else:
_j = next(j for j in range(len(st)) if not st[j] in '0125689')
left = (st[:_j] + _next[st[_j]]).ljust(len(st), '0')
return left + flip(left)
else:
st, mid = s[:l // 2], s[l // 2]
if all(c in '0125689' for c in st):
if mid <= '7':
return st + _next[mid] + flip(st)
else:
j = len(st) - 1
while j >= 0 and st[j] == '9':
j -= 1
if j == -1:
return '1' + '0' * (len(s) - 1) + '1'
else:
left = (st[:j] + _next[st[j]]).ljust(len(st), '0')
return left + '0' + flip(left)
else:
_j = next(j for j in range(len(st)) if not st[j] in '0125689')
left = (st[:_j] + _next[st[_j]]).ljust(len(st), '0')
return left + '0' + flip(left)
for s, r in tests:
res = next_strobogrammatic(s)
print("s :", s)
print(s, res, r)
print()
To embed this program on your website, copy the following code and paste it into your website's HTML: