Я написал код, как вы можете видеть (я знаю, что он может быть написан лучше). Итак, мой вопрос, как я могу запустить этот код для нескольких файлов в папке? Могу ли я использовать "для l oop" для этого? Мои файлы находятся в папке с именем assignment1 , и я не могу понять, как это сделать. Спасибо, что потратили время на чтение.
bands = list()
filename = "file1000"
with open (filename) as fin:
for line in fin:
bands.append(line.strip())
def partition(bands, start, end):
pivot = bands[start]
low = start + 1
high = end
while True:
while low <= high and bands[high] >= pivot:
high = high - 1
while low <= high and bands[low] <= pivot:
low = low + 1
if low <= high:
bands[low], bands[high] = bands[high], bands[low]
else:
break
bands[start], bands[high] = bands[high], bands[start]
return high
def quick_sort(array, start, end):
if start >= end:
return
p = partition(array, start, end)
quick_sort(array, start, p-1)
quick_sort(array, p+1, end)
def heapify(bands, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and bands[i] < bands[l]:
largest = l
if r < n and bands[largest] < bands[r]:
largest = r
if largest != i:
bands[i], bands[largest] = bands[largest], bands[i]
heapify(bands, n, largest)
def heapSort(bands):
n = len(bands)
for i in range(n, -1, -1):
heapify(bands, n, i)
for i in range(n - 1, 0, -1):
bands[i], bands[0] = bands[0], bands[i]
heapify(bands, i, 0)
def mergeSort(bands):
if len(bands) > 1:
mid = len(bands) // 2
L = bands[:mid]
R = bands[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
bands[k] = L[i]
i += 1
else:
bands[k] = R[j]
j += 1
k += 1
while i < len(L):
bands[k] = L[i]
i += 1
k += 1
while j < len(R):
bands[k] = R[j]
j += 1
k += 1
def insertionSort(bands):
for i in range(1, len(bands)):
key = bands[i]
j = i - 1
while j >= 0 and key < bands[j]:
bands[j + 1] = bands[j]
j -= 1
bands[j + 1] = key
import time
start_time = time.time()
quick_sort(bands, 0, len(bands) - 1)
file = open("time.txt","a")
file.write(str(time.time() - start_time))
file.write(" ")
file.close()
start_time = time.time()
heapSort(bands)
file = open("time.txt","a")
file.write(str(time.time() - start_time))
file.write(" ")
file.close()
start_time = time.time()
mergeSort(bands)
file = open("time.txt","a")
file.write(str(time.time() - start_time))
file.write(" ")
file.close()
start_time = time.time()
insertionSort(bands)
file = open("time.txt","a")
file.write(str(time.time() - start_time))
file.write(" ")
file.close()