[英]Reading in data to a bubble sort algorithm in Python
我的代碼段:
# BubbleSort in Python 3
def bubblesort(mylist):
for i in range (0, len(mylist) - 1):
for j in range (0 , len(mylist) - 1 - i):
if mylist[j] > mylist[j+1]:
mylist[j], mylist[j+1] = mylist[j+1], mylist[j]
return mylist
thelist = ['4','5','4','3','7','6','9','0']
print(bubblesort(thelist))
文件numbers.txt
包含數據:
2 5 32 6 4 7 9 8 6 34 1343 5 5343
我試圖從這些文本文件中將這些數字讀入變量thelist
。 我需要更改/編寫什么代碼才能實現此目的?
該代碼將從文件中讀取,然后進行排序,然后保存到文件中。 並打印排序列表
def bubblesort(mylist):
for i in range (0, len(mylist) - 1):
for j in range (0 , len(mylist) - 1 - i):
if mylist[j] > mylist[j+1]:
mylist[j], mylist[j+1] = mylist[j+1], mylist[j]
return mylist
def read():
#read from file
f = open("numbers.txt","r")
data = f.read().split()# convert string to list by split
f.close()
# for each element in list convert to int
for i in range(len(data)):
data[i] = int(data[i])
return data
def write(thelist):
#create edit the text file
file = open("numbers.txt", "wt")
# for each element in list write i value and add space between new value
for i in range(len(thelist)):
file.write(str(thelist[i]) + " ")
file.close()
thelist = read()
print(bubblesort(thelist))
write(thelist)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.