I want Python to sort the vertical numbers in the text file in descending order and print the results to a command prompt.

Asked 2 years ago, Updated 2 years ago, 32 views

I'm a Python beginner.
I practice putting two functions in a program to load a text file and eventually aligning the numbers in the text files arranged vertically in order of separation from the top to the bottom to output the results to the command line.
However, no matter how many times I try, only error messages appear in the command, and the program does not work well.
Below are the contents of the code, text file, and the original output, so please let me know if there are any mistakes in the code.

 from sys import argv

def divide(p,r):
    x = A[r]
    i=p-1

    for jinlen(p,r-1):
        if(A[j]<=x):
            i+=1
            A[i], A[j] = A[j], A[i]

    A[i+1], A[r] = A[r], A[i+1] 
    return(i+1)



default 205(p,r):
    if(p<r):
        q = divide(p,r)
        sort205(p,q-1)
        sort205(q+1,r)




A = [ ]
p = 0




iflen(argv) == 1:
    print("Type argument/filename.") 
else:
    filename = argv[1]
    try:
        with open(filename) as file:
            contents=file.read()
    except IOError:
        print("No File Found")
    else:
        file=open(filename)



        For line in file: 
            line = line.rstrip()
          A.append(line)
        r=len(A)
        sort205(p,r)
        
        print(A)

255
49152
128
64
4
20
500

4
20
64
128
255
500
49152
File "RecursionLab.py", line 52, in<module>
    sort205(p,r)
  File "RecursionLab.py", line 22, in sort 205
    q = divide(p,r)
  File "RecursionLab.py", line 6, inside
    x = A[r]
IndexError:list index out of range

python

2022-09-30 21:45

1 Answers

Based on what you told me in the comments, I will list the programs that have come to work safely below.

 from sys import argv


def divide(p,r):
    x = A[r]
    i=p-1

    for jin range(p,r):
        if(A[j]<=x):
            i+=1
            A[i], A[j] = A[j], A[i]


    A[i+1], A[r] = A[r], A[i+1]

    return(i+1)



default 205(p,r):
    if(p<r):
        q = divide(p,r)
        sort 205 (p, q-1)
        sort205(q+1,r)


p = 0


iflen(argv) == 1:
    print("Type argument/filename.") 
else:
    filename = argv[1]
    try:
        with open(filename) as file:
            contents=file.read()
    except IOError:
        print("No File Found")
    else:
        file=open(filename, "r")
        A = file.readlines()

        for line in range(0,len(A)): 
            A[line] = int(A[line])
        r=len(A)
        sort 205(0,r-1)

        print(A)


2022-09-30 21:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.