如何从列表中提取子列表,其中前一个元素的最后一个字符与最后一个元素的第一个字符相同? - 蟒蛇

时间:2014-01-04 20:04:06

标签: python python-3.x

该程序的目的是获取单词列表并打印单词的最长“链”,其条件是每个单词与其前一个单词的最后一个字符具有相同的第一个字符。

我用来测试这个程序的例子是动物名单:

giraffe
elephant
ant
tiger
raccoon
cat
hedgehog
mouse

最长链应该是:

hedgehog
giraffe
elephant
tiger
raccoon

然而,当我运行下面的程序时,它会返回:

giraffe
elephant
tiger
raccoon

请有人帮助确定我的程序中可能导致此问题的微小问题。这可能是显而易见的,但我的想法很新鲜。

以下是该计划:

from random import *


def legal_chain(word, chain):
    """Tests if a word can be 'legally' added to the end
of a chain"""
if word[0] == chain[-1][-1]:
        return True
else: 
    return False

def longest_chain(chain, V, longest):
 """ Returns the longest possible chain of strings where the
 starting character of each string is the same as the last
character from a given starting word and vocabulary V"""

 extended = False
 for word in V:
        if legal_chain(word, chain) is True:
        V.remove(word)
        chain.append(word)
        longest = longest_chain(chain, V, longest)
        extended = True
 if extended is False:
        if len(chain) > len(longest):
        longest = chain

 return longest

def find_longest(chain, V, longest):
    """Finds the longest chain for all possible starting words
   within a given vocabulary V"""
    longs = []
    i = 0
    for word in V:
        chain = [word]
        longer = longest_chain(chain, V, longest)
        longs.append(longer)
    if len(longs) == len(V):
    while len(longs) > 1:
        if len(longs[i]) < len(longs[i + 1]):
            del longs[i]
        elif len(longs[i]) > len(longs[i + 1]):
            del longs[i + 1]
        else:
            i += 1
    return longs

def print_longest(chain, V, longest):
    """Displays the longest chain of words with each word on a new line"""
    the_longest = find_longest(chain, V, longest)
    for list in the_longest:
        for word in list:
            print(word, '\n')




v = open('animals.txt', 'r').readlines()
V = [word.strip() for word in v]
longest = []
chain = []
print_longest(chain, V, longest)

请忽略任何压痕错误,程序运行没有错误,有复制和粘贴的问题!

编辑我认为以下修复了缩进错误(在没有编译器错误的意义上,输出与OP所说的相同):

from random import *


def legal_chain(word, chain):
  """Tests if a word can be 'legally' added to the end of a chain"""
  if word[0] == chain[-1][-1]:
    return True
  else:
    return False

def longest_chain(chain, V, longest):
 """ Returns the longest possible chain of strings where the
 starting character of each string is the same as the last
 character from a given starting word and vocabulary V"""

 extended = False
 for word in V:
    if legal_chain(word, chain) is True:
        V.remove(word)
        chain.append(word)
        longest = longest_chain(chain, V, longest)
        extended = True
    if extended is False:
        if len(chain) > len(longest):
          longest = chain

 return longest

def find_longest(chain, V, longest):
  """Finds the longest chain for all possible starting words
  within a given vocabulary V"""
  longs = []
  i = 0
  for word in V:
    chain = [word]
    longer = longest_chain(chain, V, longest)
    longs.append(longer)
    if len(longs) == len(V):
      while len(longs) > 1:
        if len(longs[i]) < len(longs[i + 1]):
            del longs[i]
        elif len(longs[i]) > len(longs[i + 1]):
          del longs[i + 1]
        else:
                i += 1
  return longs

def print_longest(chain, V, longest):
  """Displays the longest chain of words with each word on a new line"""
  the_longest = find_longest(chain, V, longest)
  for list in the_longest:
    for word in list:
        print(word, '\n')

v = open('animals.txt', 'r').readlines()
V = [word.strip() for word in v]
longest = []
chain = []
print_longest(chain, V, longest)

2 个答案:

答案 0 :(得分:3)

我认为这会对你有所帮助:

words_array = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgedog', 'mouse']

def longest_chain(words_array, current_chain):

    res_chain = list(current_chain)
    test_chain = []

    for s in words_array:
        temp_words_array = list(words_array)
        temp_words_array.remove(s)

        if len(current_chain) == 0:
            test_chain = longest_chain(temp_words_array, current_chain + [s])
        else:
            if s[0] == current_chain[-1][-1]:
                test_chain = longest_chain(temp_words_array, current_chain + [s])

        if len(test_chain) > len(res_chain):
            res_chain = list(test_chain)

    return res_chain


print(longest_chain(words_array, []))

答案 1 :(得分:0)

如果您的清单很小,请尝试此操作:

from itertools import permutations, chain

animals = """giraffe
elephant
ant
tiger
raccoon
cat
hedgehog
mouse"""


longest = sorted([[(j,k) for j, k in zip(i[:-1],i[1:]) if j[-1] == k[0]] \
for i in permutations([i for i in animals.split('\n')])], key=len)[-1]

print list(chain(*[longest[0], [i[1] for i in longest]]))

<强> [OUT]:

['hedgehog', 'giraffe', 'giraffe', 'elephant', 'tiger', 'raccoon']

注意:获取longest链的列表理解与此类嵌套循环相同:

animals = animals.split('\n')
animal_chains = []
# Loop through all possible permutations of the list.
for i in permutations(animals): 
    possible_chain = []
    # Reading two items at once in a list.
    for j, k in zip(i[:-1], i[1:]): 
        # Check if last character of the this animal == first character of the next.
        if j[-1] == k[0]:
            possible_chain.append((j,k))
    animal_chains.append(possible_chain)

# sort the animal_chains by length and get the longest.
longest = sorted(animal_chains, key=len)[-1]