[英]Test to see if each digit in a 9-digit integer is unique
如何編寫 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 not unique")
else:
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))):
但是有很多更優雅的解決方案,就像其他答案提出的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.