查找字符串中使用过的数字组合

问题描述 投票:0回答:1

我想在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. 当用户输入新密钥 1,2 时,程序会打印“密钥已存在”。 (正确,可以使用字符串中的数字组成 1,2 组合。)

  2. 当用户输入新密钥 1,9 时,程序会打印“密钥已接受”。 (正确,不能使用字符串中的数字组成 1,9 组合。)

这就是问题所在。

  1. 当用户输入新密钥 1,3 时,程序会打印 keyaccepted 。(不正确,程序必须打印 key已经存在,可以使用字符串中的数字组成 1,3 组合。)
python string sequence
1个回答
0
投票

假设密钥唯一,用

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.
© www.soinside.com 2019 - 2024. All rights reserved.