Putting elements from file in descending order without built in functions

前端 未结 2 447
旧巷少年郎
旧巷少年郎 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:58

    Where you have this line:

    x = minimum
    

    I think you meant:

    minimum = x
    

    Seems like you just got the assignment order incorrect. Assigning to the variable x during your iteration of A wont have any side effects.

    EDIT

    Your problem as I discovered in the comments is that you are using the readlines() function, but only have a single line in your file. What you really want to do is read that line then use split() to generate a list:

    A = file.read().split()
    

    Keep in mind though that since you are using strings when comparing with '<', you will not get numerical order after your code running you will get lexicographic order.

    example:

    inputs:

    5 4 14 6 -1 2 0 9 8 7 3 4 -10 200
    

    output:

    ['-1']
    ['-1', '-10']
    ['-1', '-10', '0']
    ['-1', '-10', '0', '14']
    ['-1', '-10', '0', '14', '2']
    ['-1', '-10', '0', '14', '2', '200']
    ['-1', '-10', '0', '14', '2', '200', '3']
    ['-1', '-10', '0', '14', '2', '200', '3', '4']
    ['-1', '-10', '0', '14', '2', '200', '3', '4', '4']
    ['-1', '-10', '0', '14', '2', '200', '3', '4', '4', '5']
    ['-1', '-10', '0', '14', '2', '200', '3', '4', '4', '5', '6']
    ['-1', '-10', '0', '14', '2', '200', '3', '4', '4', '5', '6', '7']
    ['-1', '-10', '0', '14', '2', '200', '3', '4', '4', '5', '6', '7', '8']
    ['-1', '-10', '0', '14', '2', '200', '3', '4', '4', '5', '6', '7', '8', '9']
    

    Notice above how 200 is not at the end but comes after 2, to get numerical order you need to coerce the strings into a numeric data type, probably an int. You can easily do this when you read the numbers from the file using the map function:

    A = map(int, file.read().split())
    

    This will call the int cast function on every element returned by split before storing the element in A. After this change this is the output that I see from your program:

    inputs:

    5 4 14 6 -1 2 0 9 8 7 3 4 -10 200
    

    output:

    [-10]
    [-10, -1]
    [-10, -1, 0]
    [-10, -1, 0, 2]
    [-10, -1, 0, 2, 3]
    [-10, -1, 0, 2, 3, 4]
    [-10, -1, 0, 2, 3, 4, 4]
    [-10, -1, 0, 2, 3, 4, 4, 5]
    [-10, -1, 0, 2, 3, 4, 4, 5, 6]
    [-10, -1, 0, 2, 3, 4, 4, 5, 6, 7]
    [-10, -1, 0, 2, 3, 4, 4, 5, 6, 7, 8]
    [-10, -1, 0, 2, 3, 4, 4, 5, 6, 7, 8, 9]
    [-10, -1, 0, 2, 3, 4, 4, 5, 6, 7, 8, 9, 14]
    [-10, -1, 0, 2, 3, 4, 4, 5, 6, 7, 8, 9, 14, 200]
    

提交回复
热议问题