给定一个句子,按字母顺序升序排列。
null
例如:
Input : to learn programming refer geeksforgeeks Output : geeksforgeeks learn programming refer to Input : geeks for geeks Output : for geeks geeks
我们将使用内置的库函数按升序对句子中的单词进行排序。 先决条件: 1. split() 2 Python中的sort() 3. 加入
- 把句子分成几个字。
- 按字母顺序排列单词
- 按字母顺序将已排序的单词连成一个新句子。
下面是上述想法的实现。
# Function to sort the words # in ascending order def sortedSentence(Sentence): # Splitting the Sentence into words words = Sentence.split( " " ) # Sorting the words words.sort() # Making new Sentence by # joining the sorted words newSentence = " " .join(words) # Return newSentence return newSentence # Driver's Code Sentence = "to learn programming refer geeksforgeeks" # Print the sortedSentence print (sortedSentence(Sentence)) Sentence = "geeks for geeks" # Print the sortedSentence print (sortedSentence(Sentence)) |
输出:
geeksforgeeks learn programming refer to for geeks geeks
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END