Python help. Using ( Heapq ) sorting algothrim create only one function def sortstring(filename): that takes in a file which has a bunch of sentences, each line of sentence consting of different length. Sort the setences from the lower length senteces to the highest length sentence. Print it after ( DON'T USE ANY SORTING BULT-IN FUNCTION ). Note: Keep note of time complexity as it should be able to run few 10,000 lines of sentences in few seconds.
Python help. Using ( Heapq ) sorting algothrim create only one function def sortstring(filename): that takes in a file which has a bunch of sentences, each line of sentence consting of different length. Sort the setences from the lower length senteces to the highest length sentence. Print it after ( DON'T USE ANY SORTING BULT-IN FUNCTION ).
Note: Keep note of time complexity as it should be able to run few 10,000 lines of sentences in few seconds.
code-
filename = input()
def sortstring(filename):
o=open(filename, "r")
Lines = o.readlines()
li=[]
d={}
for i in Lines:
l=len(i.split())
d[l] = i
a = list(d.keys())
lis=heapSort(a)
for i in lis:
print(d[i])
def heapify(a, n, i):
lar = i
l = 2 * i + 1
r = 2 * i + 2
if r < n and a[lar] < a[r]:
lar = r
if l < n and a[i] < a[l]:
lar = l
if lar != i:
a[i],a[lar] = a[lar],a[i]
heapify(a, n, lar)
def heapSort(a):
n = len(a)
for i in range(n, -1, -1):
heapify(a, n, i)
for i in range(n-1, 0, -1):
a[i], a[0] = a[0], a[i]
heapify(a, i, 0)
return a
sortstring(filename)
Step by step
Solved in 3 steps with 2 images