如何解决测试以查看9位整数中的每个数字是否唯一
如何编写if语句来检查9位数字中的每个数字是否唯一?显然,我编写的if语句(见粗体)不起作用。不胜感激!
x_raw = int(input("Please input a 9 digit number where no digit appears twice"))
x_nexthighestnumber = x_raw + 1
x = str(x_nexthighestnumber)
number = "incorrect"
while (x_nexthighestnumber < 999999999 and number == "incorrect"):
**if (x[0] != x[1] != x[2] != x[3] != x[4] != x[5]!= x[6] != x[7] != x[8]):**
number = "correct"
print (x)
else:
number = "incorrect"
x_nexthighestnumber += 1
解决方法
我认为您可以使用set查找唯一字符
这是一个示例函数
def x_uniq(n):
if len(set(str(n)))<len(str(n)):
print(n,"is not unique")
else:
print(n,"is unique")
测试:
x_uniq(123446789)
123446789 is not unique
x_uniq(123456789)
123456789 is unique
如果由于某种原因您对set函数过敏或沉迷于numpy,则可以将数字映射到numpy数组,而改用numpy.unique。当然,您不会这样做,我只是在找一些乐趣:
import numpy as np
def x_uniq(n):
if len(np.unique(list(map(int,str(num)))))<len(str(n)):
print(n,"is unique")
ps:想出一种算法来查找数字而不必一次遍历一个值真的很酷……我敢肯定有一个简洁的解决方案……我睡着了的数学家醒了!
,请尝试以下操作:
x_raw = input("Please input a 9 digit number where no digit appears twice:")
if len(x_raw) != 9:
raise Exception('input len must be 9')
chars = set()
for x in x_raw:
if x.isnumeric():
chars.add(x)
else:
raise Exception(f'{x} is not numeric')
if len(chars) != 9:
raise Exception('duplicates not allowed')
num = int(x_raw)
print(f'input is {num}')
,
您无法像以下那样创建这些“逻辑链”:x[0] != x[1] != x[2] != x[3] != x[4] != x[5]!= x[6] != x[7] != x[8]
在每种编程语言中这都是无效的。
但是您可以执行以下操作:
替换为以下粗体行:
if (any(str(x).count(element) > 1 for element in str(x))):
但是,有很多方法可以更优雅地解决此问题,就像其他答案提出的一样。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。