Putting elements from file in descending order without built in functions

前端 未结 2 477
旧巷少年郎
旧巷少年郎 2021-01-25 21:06

I re-did the program following the bubble sort.

def main():
try:
    array=[]
    file=open(input(\"Please enter the name of the file you wish to open:\" ))
             


        
2条回答
  •  天涯浪人
    2021-01-25 21:50

    I finished it! I just had to figure out a different way to turn my list into integers. Here it is:

    def main():
    try:
        file=open(input("Please enter the name of the file you wish to open:" ))
        A = []
        #Here I convert the list to integers to separate as numbers in order to sort later
        for val in file.read().split():
            A.append(int(val))
        file.close()
        n = len(A)
        print ("These following", n,"numbers are in the inputted file:\n", A)
    
        for i in range(n):
            for j in range(1,n-i):
                if A[j-1] < A[j]:
                    (A[j-1], A[j]) = (A[j],A[j-1]) #swap
        print("We can now organize it in descending order:\n", A)
    
        Output_File = input("Where would you like to save this data?")
        fileObject = open(Output_File, 'a')
        fileObject.write(str(Output_File)+'\n')
        print("Your file is now saved as",Output_File,".\nHave a nice day!")
        fileObject.close()
    
    except IOError as e:
        print("({})".format(e))
    
    
    
    
    if __name__ == '__main__':
    main()
    

提交回复
热议问题