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

Python代码中best_key未按预期更新的原因排查求助

问题分析:迭代中未使用更新后的密钥

问题描述

预期逻辑:当找到分数更高的密钥k时,将其保存为best_key,后续外层循环调用key_swapper时使用这个更新后的best_key生成新的密钥置换。但实际代码始终基于初始的initial_key生成置换,无法延续优化结果。

相关代码

def potenza_bruttissima(corpus, msg, initial_key, max_lenght=None, attempts=10, correct_key=""):
    candidate_plaintext= key_application(msg, initial_key)
    if not max_lenght:
        max_lenght=len(candidate_plaintext)

    max_score= text_score(corpus,msg)
    best_key= initial_key
    permutations=math.factorial(len(initial_key))/math.factorial(len(initial_key)-2)
    
    for i in range(attempts):
        print("iter", i)
        p=list(key_swapper(initial_key))
        best_candidate=candidate_plaintext
        perc=[10,20,30,40,50,60,70,80,90]
        for idx, k in enumerate(p):
            advance=int(100*idx/permutations)
            if advance in perc:
                print(f'computed',advance, '% of the permutations')
                print('chiave:', k)
                perc.pop(0)
            candidate_plaintext= key_application(msg, k)
            score= candidatext_score_bigram(corpus, msg)
            
            if score>max_score:
                max_score=score
                best_key=k
                best_candidate=candidate_plaintext
                break 
                
    print(f'Candidate key:', best_key)
    print(f'Candidate plaintext:', best_candidate)

问题原因

外层循环中,每次调用key_swapper时传入的都是初始密钥initial_key,而非更新后的best_key。这导致每一轮迭代都从初始密钥的置换开始搜索,完全忽略了上一轮找到的更优密钥,自然无法实现“基于最优密钥继续优化”的逻辑。

修复方案

将外层循环中key_swapper的参数从initial_key改为best_key,让每一轮迭代都基于当前找到的最优密钥生成新的置换:

p=list(key_swapper(best_key))  # 替换原有的initial_key

另外注意代码中candidatext_score_bigram疑似拼写错误,建议修正为candidate_text_score_bigram(如果是函数名的笔误),避免运行时出现未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:21:39