Python-programming-exercises问题10
- 问题:
编写一个程序,该程序接受由空格分隔的单词序列作为输入,并在删除所有重复的单词并将其按字母数字顺序排序后打印这些单词。
假设将以下输入提供给程序: - 输入:
hello world and practice makes perfect and hello world again - 输出:
again and hello makes perfect practice world - 我的:
s = list(input().split())
a = s[:]
l = len(s)
print(l)
for i in range(0,l-1):
for j in range(i+1,l-1):
if s[i] == s[j]:
a.remove(s[j])
a.sort()
print(' '.join(a))
- Solution:
s = input()
words = [word for word in s.split(" ")]
print (" ".join(sorted(list(set(words)))))
- 问题:
一开始没有考虑到remove()后列表长度减小,导致"index out of the range"。
解决:利用切片复制一个相同的列表,在该列表上做remove(),原列表循环找到相同的单词 - 题目来源:
https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt