簡體   English   中英

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

[英]How to extract a sublist from a list where the last character of the previous element is the same as the first character of the last element? - python

該程序的目的是獲取單詞列表並打印單詞的最長“鏈”,其條件是每個單詞與其前面單詞的最后一個字符具有相同的第一個字符。

我用來測試這個程序的例子是動物列表:

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)

我想這會對你有所幫助:

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, []))

如果您的列表很小,請嘗試此操作:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM