我正在尝试创建一个函数,它检查一个数字是否重复2次和3次,当它执行时它将返回0(未检测到重复)或1(输入的两个参数都重复)。但是由于某些原因,即使没有重复,1总是打印。有没有更简单的方法来执行此操作或修复我的代码?也忽略打印('t'),打印(“w”)和打印(“x”)。这些只是一种检查发生情况的方法。
def triple_double(num1, num2):
num1 = str(num1)
num2 = str(num2)
if ('111') or ('222') or ('333') or ('444') or ('555') or ('666') or ('777') or ('888') or ('999') in num1:
if ('11') or ('22') or ('33') or ('44') or ('55') or ('66') or ('77') or ('88') or ('99') in num2:
print('t')
print(1)
else:
print("w")
print(0)
else:
print("x")
print(0)
triple_double(0, 0)
答案 0 :(得分:0)
我只是翻转它并测试数字的任何字符串表示是否在包含您的三重和双精度的列表中。
from itertools import repeat
def triple_double(num1, num2):
# create triple and double lists
triples = [''.join(repeat(str(i), 3)) for i in list(range(1, 10))]
doubles = [''.join(repeat(str(i), 2)) for i in list(range(1, 10))]
num1 = str(num1)
num2 = str(num2)
# test if num1 in triples
if num1 in triples:
# test in num2 in doubles
if num2 in doubles:
print('t')
print(1)
else:
print("w")
print(0)
else:
print("x")
print(0)
triple_double(0, 0) # x, 0
答案 1 :(得分:0)
应该是:
def triple_double(num1, num2):
num1 = str(num1)
num2 = str(num2)
if ('111') in num1 or ('222') in num1 or ('333') in num1 or ('444') in num1 or ('555') in num1 or ('666') in num1 or ('777') in num1 or ('888') in num1 or ('999') in num1:
if ('11') in num2 or ('22') in num2 or ('33') in num2 or ('44') in num2 or ('55') in num2 or ('66') in num2 or ('77') in num2 or ('88') in num2 or ('99') in num2:
print('t')
print(1)
else:
print("w")
print(0)
else:
print("x")
print(0)
triple_double(0, 0)
否则,if条件将始终评估为True。