1.编写一个程序打开文件romeo.txt并逐行读取。对于每一行,使用split函数将该行拆分为一个单词列表。对于每个单词,检查该单词是否已在列表中。如果单词不在列表中,请将其添加到列表中。程序完成后,按字母顺序对生成的单词进行sort和print。
<romeo.txt>
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
Enter file: romeo.txt
[‘Arise’, ‘But’, ‘It’, ‘Juliet’, ‘Who’, ‘already’, ‘and’, ‘breaks’, ‘east’, ‘envious’, ‘fair’, ‘grief’, ‘is’, ‘kill’, ‘light’, ‘moon’, ‘pale’, ‘sick’, ‘soft’, ‘sun’,‘the’, ‘through’, ‘what’, ‘window’, ‘with’, ‘yonder’]
file = input('Enter file:')
hand = open(file)
list = []
print('romeo.txt is split into four word lists:')
for line in hand:
row = line.split()
print(row)
for word in row:
if word not in list:
list.append(word)
print('Sorted word list:')
list.sort()
print(list)
2.重写程序,提示用户输入一个数字列表,并在用户输入“done”时打印出数字的最大值和最小值。编写程序来存储用户在列表中输入的数字,并使用max()和min()函数计算循环完成后的最大和最小数。
Enter a number: 6
Enter a number: 2
Enter a number: 9
Enter a number: 3
Enter a number: 5
Enter a number: done
Maximum: 9.0
Minimum: 2.0
print('Please follow the instructions below.')
num_list = []
while True:
number = input('Enter a number: ')
if number == 'done':
break
else:
try:
num_list.append(float(number))
except:
print('Invalid input')
print('Maximum: ',max(num_list))
print('Minimum: ',min(num_list))