[英]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
The aim of this program is to take a list of words and print the longest possible 'chain' of the words, the conditions of which are that each word has the same first character as the last character of the word before it. 该程序的目的是获取单词列表并打印单词的最长“链”,其条件是每个单词与其前面单词的最后一个字符具有相同的第一个字符。
The example I used to test this program is the list of animals: 我用来测试这个程序的例子是动物列表:
giraffe
elephant
ant
tiger
raccoon
cat
hedgehog
mouse
The longest chain should read: 最长的链应该是:
hedgehog
giraffe
elephant
tiger
raccoon
However when I run the program below it returns: 但是,当我运行下面的程序时,它返回:
giraffe
elephant
tiger
raccoon
Please could someone help to identify the tiny issue with my program that might be causing this. 请有人帮助确定我的程序中可能导致此问题的微小问题。 It's probably obvious but I'm fresh out of ideas.
这可能是显而易见的,但我的想法很新鲜。
Here is the program: 这是程序:
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)
PLEASE IGNORE ANY INDENTATION ERRORS, THE PROGRAM WORKS WITHOUT AN ERROR, THERE IS AN ISSUE WITH COPY AND PASTE! 请忽略任何压痕错误,程序运行没有错误,有复制和粘贴的问题!
edit I believe the following fixes the indentation errors (in the sense of no compiler errors, and output is the same as OP had stated): 编辑我相信以下修复了缩进错误(在没有编译器错误的意义上,输出与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)
I think this will help you: 我想这会对你有所帮助:
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, []))
Try this if your list is small: 如果您的列表很小,请尝试此操作:
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]: [OUT]:
['hedgehog', 'giraffe', 'giraffe', 'elephant', 'tiger', 'raccoon']
NOTE: The list comprehension to get the longest
chain is the same as such a nested loop: 注意:获取
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.