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

如何基于用户输入单词的字母生成符合指定约束的有效单词

问题解决代码

核心逻辑补充了「候选词所有字符均来自输入单词、且字符使用数量不超过输入单词对应字符数量」的校验规则,同时优化了原有代码的异常处理和校验准确性,修改后完整代码如下:

from collections import Counter

word = input("Word: ").lower()
# 统计输入单词的各字符出现次数,处理重复字符校验场景
input_char_count = Counter(word)

savedwords = [] 
# 计算输入单词的中间字符:单数长度取正中间1个,偶数长度取中间2个
middle_char = word[(len(word)-1)//2:(len(word)+2)//2] 
count = 0
usedwords =[] 

# 用with语法自动管理文件关闭,避免异常场景下资源泄漏
with open("svenskaord.txt", "r", encoding="utf-8") as file:
    # 读取时统一转小写、去除首尾空白,避免格式问题影响校验
    nonempty_lines = [line.strip().lower() for line in file if line.strip()]

for line in nonempty_lines:
    line_char_count = Counter(line)
    # 四项校验规则:长度≥4、包含中间字符、未重复输出、字符来源合法且用量不超限
    if (len(line) >= 4 
        and middle_char in line 
        and line not in usedwords 
        and all(line_char_count[c] <= input_char_count.get(c, 0) for c in line_char_count)
    ):
        print(line)
        usedwords.append(line)
        count += 1
        if len(line) == 9:
            savedwords.append(line)

print(f"\n共找到符合要求的单词{count}个")
print(f"长度为9的完整字母组合单词:{savedwords}")

注意事项

如果你的需求是偶数长度输入时,仅要求返回单词包含任意一个中间字符而非连续的中间两个字符,可以将中间字符校验逻辑修改为:

# 把中间字符转为列表
middle_chars = list(word[(len(word)-1)//2 : (len(word)+2)//2])
# 校验条件改为判断任意一个中间字符存在
any(c in line for c in middle_chars)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:18:05