3 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使用它collections.deque
來(lái)有效地實(shí)現(xiàn)您正在尋找的算法。這是因?yàn)殡p端隊(duì)列兩側(cè)的追加和彈出O(1)
在任一方向的復(fù)雜性下都是有效的。
利用:
from collections import deque
def word_magic(string):
tokens = deque(string.split())
words = []
while tokens:
curr_word = tokens.popleft()
if not tokens:
words.append(curr_word)
break
next_word = tokens[0]
if curr_word[-1] == next_word[0]:
tokens.popleft()
tokens.appendleft(next_word + curr_word)
continue
words.append(curr_word)
return words
調(diào)用函數(shù):
# Example 1
words = word_magic("are all levels lavendar lemon maverick king of gamblers")
print("\n".join(words))
# Example 2
words = word_magic("crab boy yesterday yellow wing game engine eat top")
print("\n".join(words))
這打?。?/p>
are
lemonlavendarlevelsall
kingmaverick
of
gamblers
boycrab
yellowyesterday
gamewing
eatengine
top

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
s = "are all levels lavendar lemon maverick king of gamblers".split()
words = list(reversed(s)) # Reverse the list because we're poping from the end
while words:
first = words.pop()
rest = []
while words and words[-1][0] == first[-1]:
rest.append(words.pop())
print("".join([*rest, first]))
對(duì)于每個(gè)單詞,當(dāng)您發(fā)現(xiàn)以與該單詞(您所在的單詞)結(jié)尾相同的字母開頭的單詞時(shí),請(qǐng)向前看。然后打印那些單詞(以字母開頭),然后是那個(gè)單詞(以字母結(jié)尾的單詞),然后跳到你找到的最后一個(gè)單詞之后的單詞。
您可以使用索引而不是編寫相同的代碼list.pop:
words = "are all levels lavendar lemon maverick king of gamblers".split()
i = 0
while i < len(words):
first = words[i]
i += 1
rest = []
while i < len(words) and words[i][0] == first[-1]:
rest.append(words[i])
i += 1
print("".join([*rest, first]))

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個(gè)贊
沒有對(duì)其進(jìn)行基準(zhǔn)測(cè)試,但我會(huì)嘗試fold。functools 模塊提供了reduce 功能:
>>> s = "are all levels lavendar lemon maverick king of gamblers"
在空格上拆分字符串:
>>> t = s.split(" ")
>>> t
['are', 'all', 'levels', 'lavendar', 'lemon', 'maverick', 'king', 'of', 'gamblers']
并折疊列表:
>>> import functools
>>> u = functools.reduce(lambda acc, x: acc[:-1] + [x+acc[-1]] if acc and x and acc[-1][-1] == x[0] else acc + [x], t, [])
>>> u
['are', 'lemonlavendarlevelsall', 'kingmaverick', 'of', 'gamblers']
我們從一個(gè)空列表開始[]。有兩種情況:如果前一個(gè)詞(或壓縮詞)的最后一個(gè)字母是當(dāng)前詞的第一個(gè)字母(acc[-1][-1] == x[0]),那么我們?cè)谇耙粋€(gè)詞(或壓縮詞)之前插入當(dāng)前詞:acc[:-1] + [x+acc[-1]]。否則,我們將當(dāng)前單詞添加到列表中。
現(xiàn)在只需打印結(jié)果:
>>> print("\\n".join(u))
are
lemonlavendarlevelsall
kingmaverick
of
gamblers
另一個(gè)版本,基于觀察如果我們有一個(gè)單詞w[i]的最后一個(gè)字母c=w[i][-1]so w[i+1][0] = c,那么我們構(gòu)建w[i+1]+w[i]并且最后一個(gè)字母將c再次出現(xiàn):我們只需要檢查下一個(gè)單詞是否w[i+2], w[i+3], ...以cetc 開頭。如果沒有,開始一個(gè)新的線。
s = "are all levels lavendar lemon maverick king of gamblers"
t = s.split(" ")
i = 0
while i < len(t):
c = t[i][-1]
j = i+1
cur = [t[i]]
while j<len(t) and t[j][0] == c:
cur.insert(0, t[j])
j += 1
print("".join(cur))
i = j
添加回答
舉報(bào)