I wrote this code for quicksort.
def partition(a,start = 0,end = len(a)-1):
pivot = a[0]
while start<end:
while a[start]<=pivot:
start+=1
while a[end]>pivot:
end-=1
a[start],a[end] = a[end],a[start]
pivot,a[end] = a[end],pivot
return end
def quicksort(a,lb =0,ub =len(a)-1):
if lb<ub:
loc = partition(a,lb,ub)
quicksort(a,lb,loc-1)
quicksort(a,loc+1,ub)
A = [3,5,1,7,9,6,2]
B = quicksort(A)
print(B)
I don't know why this is occuring NameError. a is a parameter of the function. Till its giving error.
Traceback (most recent call last):
File "/data/data/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/data/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 1, in <module>
NameError: name 'a' is not defined
[Program finished]
You cannot use a parameter in computing the default value of another because they are computed at method definition, not at method call, so the others can't be used, the default value should be immutable value
You can use None
as default value and check with it
def quicksort(a, lb=0, ub=None):
ub = len(a) - 1 if ub is None else ub
#...
def partition(a, start=0, end=None):
end = len(a) - 1 if end is None else end
#...
def quicksort(a,lb =0,ub =len(a)-1):
– yes, a
is a parameter and it will be defined in the body of quicksort
function, but at the moment you're trying to get len(a)
it is not defined yet. I suggest the following change:
def quicksort(a,lb=0,ub=None):
if ub is None:
ub = len(a)-1
and the rest of your code stays as it is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.