You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中检测字符串内已使用的非连续数字组合问题

解决Python中检测非连续数字组合是否已使用的问题

需求明确:我们需要检测输入的两位数字组合是否已被使用——只要组成该组合的两个数字都存在于指定的数字集合(示例为1,2,3,4,5,8)中,就判定该组合已被使用。

用户提供的原始代码如下:

# 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:正确输出Your chosen key (1,2) already exists.
  • 输入1,9:正确输出Key accepted.
  • 输入1,3:本该输出已存在,但当前错误输出Key accepted.

错误原因

原始代码只是简单判断输入的字符串是否直接作为子串存在于used_keys中。这种方式只能检测像1,2这样连续出现的数字组合,却无法识别1,3这类由集合中分散数字组成的组合——毕竟"1,3"并没有出现在"1,2,3,4,5,8"的字符串里。

修复方案

我们需要转换思路:先把已用数字转换成集合,再检查输入的两个数字是否都属于这个集合。同时可以增加输入格式校验,避免非法输入。

修改后的代码:

# 将已用数字字符串拆分为集合,方便快速查询
used_numbers = set('1,2,3,4,5,8'.split(','))

# 获取用户输入的密钥
user_key = input("Enter your new key: ")

# 先校验输入格式是否合规(必须是两位数字用逗号分隔)
try:
    num1, num2 = user_key.split(',')
    # 检查两个数字是否都在已用集合内
    if num1 in used_numbers and num2 in used_numbers:
        print(f"Your chosen key ({user_key}) already exists.")
    else:
        print("Key accepted.")
except ValueError:
    print("Invalid input format. Please enter a key like '1,2'.")

代码说明

  1. 集合转换:把used_keys按逗号拆分后转成集合,集合的成员查询效率远高于字符串匹配,且能自动去重(如果有重复数字的话)。
  2. 格式校验:用try-except捕获拆分失败的情况,比如用户输入了非逗号分隔的内容,直接提示格式错误。
  3. 组合判断:只要输入的两个数字都在已用集合中,就判定该组合已被使用,完美覆盖了非连续数字组合的检测需求。

内容的提问来源于stack exchange,提问作者Ostik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 17:27:47