【问题标题】:Python: replace list items and produce all possible permutationsPython:替换列表项并产生所有可能的排列
【发布时间】:2017-11-22 15:43:30
【问题描述】:

我正在尝试为部分莫尔斯电码实现莫尔斯解码。例如,莫尔斯电码中单词 TEST 的表示是 ['-','.','...','-'] 但是如果第一个每个莫尔斯电码字符串的字符都丢失并由 x 表示,那么 TEST 的部分莫尔斯电码将变为 ['x','x','x..','x']。因此为了解码这个部分消息,我们将不得不用任何一个替换 x 。或 - 对于上述部分莫尔斯电码中每次出现的 x。在“x”未知的情况下,解码时 TEST 字的排列将是 ETST、EEDT、ETSE 等。我已经实现了莫尔斯部分解码功能,如下所示:

def morsePartialDecode(inputStringList):
    with open('words.txt','a') as wordfile:
        dictionaryFileLoc = './dictionary.txt'
        message_received = inputStringList
        message_received = ' '.join(inputStringList)
        for i in range(len(message_received)):
            x = 'x'
            y = '.'
        message = message_received.replace(x, y)
        message1 = message.split(",")
        message_converted = morseDecode(message1)
        print message_converted
        print >> wordfile, (message_converted)
        for i in range(len(message_received)):
            x = 'x'
            y = '-'
        message = message_received.replace(x, y)
        message2 = message.split(",")
        message_converted = morseDecode(message2)
        print >> wordfile, (message_converted)
        elements = []
    wordfile.closed
    return message_converted

def partialMorseCodeTest():
    test = ['x', 'x', 'x..', 'x']
    print morsePartialDecode(test)  

partialMorseCodeTest()

Output:
EESE
TTDT

我需要 ['x','x','x..','x'] 的所有组合,其中 x 替换为 .或 -。我的 morseDecode() 会将每个组合转换为各自的单词,如 EESE、TTDT 等morsedecode) 怎么办。提前致谢!

【问题讨论】:

  • 所以,如果我理解正确,您需要将['x','x','x..','x']x 的所有组合替换为.-?而您的morseDecode() 会将每个组合转换为各自的单词,例如 EESE、TTDT 等?
  • 是的,你是对的!
  • 请相应地更新您的问题!
  • 部分代码中每个字母是否有单个替换的限制,或者您是否需要处理例如:['-', 'x.x', 'x']

标签: python-3.x python-2.7 list


【解决方案1】:

itertools 的绝佳案例

使用itertools.product的示例:

from itertools import product

def replace_x_with_all_combinations(morse):
    # only works with 1 and 1 only 'x' in each element
    all_perm = list()
    for v in morse:
        if 'x' in v:
            # create a list of permutations per element of the morse list
            # and append them to the all_perm list
            all_perm.append([v.replace('x','.'), v.replace('x','-')])
        else:
            # if no x found, then append the original element
            all_perm.append([v])
    # all_perm = [['.', '-'], ['.', '-'], ['...', '-..'], ['.', '-']]
    # the list all_perm needs to be unpacked before passing
    # to the product() generator, hence the *
    return list(product(*all_perm))

partial = ['x','x','x..','x']
result = replace_x_with_all_combinations(partial)
for e in result:
    print(e)

输出:

('.', '.', '...', '.')
('.', '.', '...', '-')
('.', '.', '-..', '.')
('.', '.', '-..', '-')
('.', '-', '...', '.')
('.', '-', '...', '-')
('.', '-', '-..', '.')
('.', '-', '-..', '-')
('-', '.', '...', '.')
('-', '.', '...', '-')
('-', '.', '-..', '.')
('-', '.', '-..', '-')
('-', '-', '...', '.')
('-', '-', '...', '-')
('-', '-', '-..', '.')
('-', '-', '-..', '-')

[编辑] 虽然我自己在上面的代码中设置了限制,但“仅适用于莫尔斯字符中的 1 个 x”让我感到困扰,所以下面的示例将在莫尔斯字符中丢失一个以上的数字,多个 'x'

from itertools import product


def replace_x_in_morse_charcter(morse_character):
    all_perm = [['.','-'] if c == 'x' else [c] for c in morse_character]
    p = list(product(*all_perm))
    return [''.join([v for v in e]) for e in p]


def replace_x_in_morse_word(morse):
    all_perm = [replace_x_in_morse_charcter(c) for c in morse]
    return list(product(*all_perm))


partial = ['x','x','x..','xx']
result = replace_x_in_morse_word(partial)
for e in result:
    print(e)

[编辑] 一个班轮的乐趣:

morse_word = ['x','x','x..','xx']
result = list(product(*[[''.join([v for v in e]) for e in list(product(*[['.','-'] if c == 'x' else [c] for c in cm]))] for cm in morse_word]))

【讨论】:

  • 你能解释一下这是做什么的吗? all_perm = [['.','-'] if c == 'x' else [c] for c in morse_character]
  • @Alligator :如果莫尔斯字符(包含点和破折号和 x)有一个 x,它将返回一个点和一个破折号代替 x,否则它将返回原始点或破折号.因此,它将返回可能的莫尔斯字符的所有排列,用点和破折号代替 x。我希望这能回答你的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
  • 2011-02-20
  • 1970-01-01
相关资源
最近更新 更多