在int中找到双打

时间:2016-03-11 03:56:28

标签: python

如果我有整数,1988,怎么可以通过它迭代看看是否有双打?在python中。

我知道我不能像这样迭代:

userInt = 1988
for i in userInt:
    print(i)

2 个答案:

答案 0 :(得分:2)

您可以将其转换为字符串:

userInt = 1988
for i in str(userInt):
    print(i)

如果您想查看是否有双打,请执行以下操作:

has_doubles = len(set(str(userInt))) == len(str(userInt))

答案 1 :(得分:1)

如果以下测试用例正确:

tests = {1: False, 
         11: True, 
         00: False, 
         12344: True, 
         1202: False, 
         9999: True, 
         1234: False, }

然后,以下内容应该有效:

def has_doubles(val):
    as_string = str(val)
    if len(as_string) < 2:
        return False
    for x in range(len(as_string) - 1):
        if as_string[x] == as_string[x+1]:
            return True
    return False

请注意,1202没有“double”,如果有,则其他答案应该有效。此外,由于范围(0)为空,因此不一定严格需要开头的长度检查,但显式无害。 for循环只查看相邻字符并测试是否相等。

相关问题