我想在Python中检查非连续数字。
例如,在包含1,2,3,4,5,8的字符串中,我想检查是否使用了任何两位数字组合。 我可以找到 1,2 和 5,8,但找不到 1,3 或 4,8 或 3,1 等的组合。
下面是我的代码:
# An example of a single user key is 1,2 another example is 5,8
# Numbers used to make combinations of two digit keys so far.
used_keys = '1,2,3,4,5,8'
# User key input.
user_key =input("Enter your new key: ")
# Check if the key combination has been used before.
if user_key in used_keys:
print ("Your chosen key (" + user_key + ") already exists.")
else:
print("Key accepted.")
我的预期结果是:
当用户输入新密钥 1,2 时,程序会打印“密钥已存在”。 (正确,可以使用字符串中的数字组成 1,2 组合。)
当用户输入新密钥 1,9 时,程序会打印“密钥已接受”。 (正确,不能使用字符串中的数字组成 1,9 组合。)
这就是问题所在。
假设密钥唯一,用
set
解决这个问题很简单:
used_keys = '1,2,3,4,5,8'
keys = set(used_keys.split(','))
user_key = input("Enter your new key: ")
if set(used_keys.split(',')).issubset(keys):
print(f"Your chosen key ({user_key}) already exists.")
else:
print("Key accepted.")
示例:
Enter your new key: 1,3
Your chosen key (1,3) already exists.