【发布时间】:2021-08-10 13:19:57
【问题描述】:
我尝试使用文本文件作为 Python 中快速排序函数的输入。事实证明,我得到了这个错误
TypeError: 'str' object does not support item assignment
我知道错误的发生是因为 Python 中的字符串是不可变的,因此它们无法更改。但是,我不确定如何修复我的代码以使其运行。
我的代码(在 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))
我的文本文件如下
12.11.1990 a
01.01.1991 aa
02.02.1992 baa
02.02.1992 aaa
15.07.1999 ytyvm
关于如何修复我的代码的建议?
【问题讨论】:
标签: python arrays string typeerror quicksort