给定一个句子,请按字母升序对其进行排序。
例子:
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. join()
- 用单词拆分句子。
- 按字母顺序对单词进行排序
- 按字母顺序将排序的单词连接起来以形成新的句子。
以下是上述想法的实现。
# 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