A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
首先就想一下180°转了之后能够凑成一样的数字是什么。0,1,8,6-9。其中6-9必须是成对的,不要问为什么。
这题很像那些问你回文的题目,二分之后对称位置的数字的组合必须是符合"00","11","88","69","96"。
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
for i in range(len(num)/2+1):
if num[i] + num[-i-1] not in "696001188":
return False
return True
因为只要是对称位置上下调转相同,或者是"69","96"对,就满足要求。所以只需要取对称位,然后判断是否是那些数字即可。因为会全部取到,所以并不担心取到"60"这样的数字,之后的反取"06"会false掉。
======================
很赞的方法
def isStrobogrammatic(self, num):
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num)/2+1))
其中的num[~i],index位取反是亮点。
Some others:
def isStrobogrammatic(self, num):
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num)))
def isStrobogrammatic(self, num):
return all(map('696 00 11 88'.count, map(operator.add, num, num[::-1])))
def isStrobogrammatic(self, num):
return all(p in '696 00 11 88' for p in map(operator.add, num, num[::-1]))
def isStrobogrammatic(self, num):
return set(map(operator.add, num, num[::-1])) <= set('69 96 00 11 88'.split())
def isStrobogrammatic(self, num):
return set(map(operator.add, num, num[::-1])) <= {'69', '96', '00', '11', '88'}
def isStrobogrammatic(self, num):
return set(map(''.join, zip(num, num[::-1]))) <= {'69', '96', '00', '11', '88'}