0

I tried to use a text file as an Input for my Quicksort Function in Python. As it turns out, I get this Error

TypeError: 'str' object does not support item assignment

I know the Error occurs because Strings in Python are immutable, therefore they cannot be changed. However, I am not sure how I can fix my code to make it run.

My Code (in Python 3)

import sys
f = open('C:/Users/.../.../Desktop/Test/test1.txt')
array = str(f.read())

def QuickSort(array, starting= 0, ending=len(array)-1):
   
    if starting < ending:
       
       p = Partition(array, starting, ending)
       
       QuickSort(array, starting, p-1)
       Quicksort(array, p+1, ending)
   
def Partition(array, starting, ending):
       Pivo_Index = starting
       Pivot = array[Pivot_Index]
   
       while starting < ending:
           while starting < len(array) and array[starting] <= Pivot:
               starting += 1
           
           while array[ending] > Pivot:
               ending -= 1
           
           if starting < ending:
               array[starting], array[ending] = array[ending], array[starting]
           
       array[ending], array[Pivot_Index] = array[Pivot_Index], array[ending]
       
       return ending

print(QuickSort(array))

My text file is the following

12.11.1990 a
01.01.1991 aa
02.02.1992 baa
02.02.1992 aaa
15.07.1999 ytyvm

Suggestions of how I can fix my code?

0

1 Answer 1

1

read() returns a string, which is immutable (and thus, can't be sorted, as you've seen). If you want to get a list of lines in the file and sort them, you could use array = f.readlines().

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.