0
def selectionSort(lst):
    with lst as f:
        nums = [int(line) for line in f]
    for i in range(len(nums) - 1, 0, -1):
       maxPos = 0
       for position in range(1, i + 1):
           if nums[position] > nums[maxPos]:
               maxPos = position

       value = nums[i]
       nums[i] = nums[maxPos]
       nums[maxPos] = value

def main():
    textFileName = input("Enter the Filename: ")
    lst = open(textFileName)
    selectionSort(lst)
    print(lst)

main()

Okay, thanks to hcwhsa for helping me out with the reading file and putting them all in one line.

When I run that code, i get this following error:

<_io.TextIOWrapper name='numbers.txt' mode='r' encoding='UTF-8'>

textfile:

67
7
2
34
42

Any help? Thanks.

1 Answer 1

3

You should return the list from the function and assign it to a variable and then print it.

def selectionSort(lst):
    with lst as f:
        nums = [int(line) for line in f]
    ...
    ...
    return nums

sorted_lst = selectionSort(lst)
print(sorted_lst)

Your code didn't work because instead of passing the list you passed the file object to the function. This version of your code passes the list to the function, so no return value is required as you're modifying the same list object:

def selectionSort(nums):

    for i in range(len(nums) - 1, 0, -1):
       maxPos = 0
       for position in range(1, i + 1):
           if nums[position] > nums[maxPos]:
               maxPos = position

       value = nums[i]
       nums[i] = nums[maxPos]
       nums[maxPos] = value


def main():
    textFileName = input("Enter the Filename: ")
    with open(textFileName) as f:
        lst = [int(line) for line in f]
    selectionSort(lst)
    print(lst)

main()
Sign up to request clarification or add additional context in comments.

1 Comment

i got it now I changed the last one to print(nums) instead of the print(lst). Thanks, i didn't realized that it was an object, that's why is reading that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.