题目
Sort a list of words based on number of characters
and ignore the asterisk separator between them
Example Input:
This*is*a***Hello**World***example**to*demo*your****coding*ability“
Example Output:
a is to This demo your Hello World coding ability example
参考实现
import re
from typing import List
SEP = re.compile('\*+')
def split_words(string: str) -> List[str]:
return re.split(SEP, string)
def sort_words(words: List[str]) -> List[str]:
if len(words) < 2:
return words
p = words[0]
longer = []
shorter = []
same_length = [p]
for word in words[1:]:
if len(word) > len(p):
longer.append(word)
elif len(word) < len(p):
shorter.append(word)
else:
same_length.append(word)
return sort_words(shorter) + sorted(same_length, key=lambda word: word) + sort_words(longer)
def solution(string: str) -> str:
words = split_words(string)
sorted_words = sort_words(words)
return ' '.join(sorted_words)
if __name__ == '__main__':
r = solution('This*is*a***Hello**World***example**to*demo*your****coding*ability')
print(r)
assert r == 'a is to This demo your Hello World coding ability example'
标签:__,面试题,word,words,demo,len,单词,str,排序
From: https://www.cnblogs.com/superhin/p/18514676