Python旧值重新出现

2024-05-01 22:00:07 发布

您现在位置:Python中文网/ 问答频道 /正文

当我告诉某人我将字典导出到数据库(将选择的字典HTML页面导出到数据库的简单python脚本)后,我遇到了一个挑战,那就是将没有空间的Morse码转换成单词

例如。 通常消息是:.- .--. .--. .-.. .(apple),每个字符之间有一个空格。 但是由于有一个数据库可以检查所有的可能性,新的输入将是:.-.--..--..-...(apple),中间没有空格

为此我编写了一个python脚本,但是我发现了一个非常奇怪的现象,旧的值(没有存储在任何变量中)又出现了

代码如下:

import sqlite3
conn = sqlite3.connect('english_dictionary.db')
c = conn.cursor()

#Morse code alphabet
mc = {'.-' : 'a', '-...' : 'b', '-.-.' : 'c', '-..' : 'd', '.' : 'e', '..-.' : 'f', '--.' : 'g', '....' : 'h', '..' : 'i', '.---' : 'j', '-.-' : 'k', '.-..' : 'l', '--' : 'm', '-.' : 'n', '---' : 'o', '.--.' : 'p', '--.-' : 'q', '.-.' : 'r', '...' : 's', '-' : 't', '..-' : 'u', '...-' : 'v', '.--' : 'w', '-..-' : 'x', '-.--' : 'y', '--..' : 'z'}

#Recursive function - input, current words, current index, current_word
def magic(inp, curwords=[''], curindex=0, current_word=''):
    #print 'inp: "%s", curwords = %s, curindex = %i, current_word = "%s"' % (inp, str(curwords), curindex, current_word)
    #If the function is being called with an empty input, then this word has been finished, so set it up for a new one
    if inp == "":
        curwords.append('')
        curindex += 1
        return curwords,curindex
    #Finding valid Morse code letters
    for i in range(1, len(inp)+1):
        #print 'Current: %i in (1, %i)' % (i, len(inp)+1)
        if inp[:i] in mc:
            #print 'Morse Code: "%s" -> %s in (1, %i)' % (inp[:i],mc[inp[:i]], len(inp)+1)
            curwords[curindex] = current_word + mc[inp[:i]]
            curwords,curindex = magic(inp[i:], curwords, curindex, current_word + mc[inp[:i]])
        #else:
            #print 'Not Morse Code: "%s" in (1, %i)' % (inp[:i], len(inp)+1)
    return curwords,curindex

while 1:
    x = raw_input('> ')
    mag = magic(x)[0]
    for row in c.execute('SELECT DISTINCT word FROM dictionary WHERE LOWER(word) IN %s' % (str(tuple(mag)))):
        print row[0]

(请询问是否需要更深入地解释部分代码)

问题是:

如果我输入..-,它返回It

如果我输入--.,它返回Me

(两者都正确)

但是,如果我做.-.--..--..-...,它返回Apple(同样正确,但这里是它中断的地方)

现在,如果我在检查Apple之后执行任何morse码,那么Apple将作为结果返回

例如

(按顺序运行)

> ..-->It

> --.->Me

> .-.--..--..-...->Apple

> ..-->Apple, It

> --.->Apple, Me

我让它在SQL语句之前输出mag,它拥有apple拥有的所有可能性+新输入的可能性(因此它不是由SQL引起的)

我尝试过在while循环的末尾添加mag = [],但仍然不起作用

我在另一种语言中经历过类似的奇怪行为,这是由于修改解析到函数中的参数的值引起的,所以我尝试将这些值复制到新变量中,但没有效果


Tags: in数据库appleinputmorselencurrentmc
1条回答
网友
1楼 · 发布于 2024-05-01 22:00:07

Python默认参数只计算一次。当您附加到作为默认参数的列表(如curwords)时,默认参数将在随后的函数调用中更改

如果要在调用函数时自动获取空列表而不提供curwords,请尝试以下操作:

def magic(curwords=None):
  if curwords is None: curwords = []
  # ...

有关详细信息,请参阅Python语言教程中的Default Argument Values

相关问题 更多 >