我正在学习python,昨天开始冒泡排序,但我似乎找不到错误,我一直在试图找到错误,但我没有足够的知识来找到它。如果有人能给我指路就太好了:
class BubbleSort1:
def __init__(self) -> None:
pass
def read(self):
lst = None
lst = []
n1 = int(input('Enter the number of values to be sorted:'))
print('Enter the values to be sorted')
for i in range(0,n1):
ele = int(input())
lst.append(ele)
print('Unsorted list:')
print(lst)
def sort(self,lst):
for i in range(len(lst)-1,0,-1):
for j in range(i):
if lst[j] > lst[j+1]:
temp = lst[j]
lst[j] = lst[j+1]
lst[j+1] = temp
def display(self,lst):
print('sorted list')
print(len(lst))
object1 = BubbleSort1()
object1.read()
object1.sort()
object1.display()
错误是
> Enter the number of values to be sorted:5
> Enter the values to be sorted
> 5
> 4
> 3
> 2
> 1
> Unsorted list:
> [5, 4, 3, 2, 1]
> Traceback (most recent call last):
> File "c:UsersUser1OneDriveDesktopNew foldercopy", line 31, in <module>
> object1.sort()
> TypeError: BubbleSort1.sort() missing 1 required positional argument: 'lst'
您有两个选择:
- 从
read
返回lst
,将lst
传递给sort
,display
- 设置
lst
为self.lst
,并在self
的所有功能上使用该lst
。
Option_1您不将lst
传递给sort()
和display()
。你可以通过从read返回lst
并传递给sort()
和display()
来解决这个问题。
class BubbleSort1:
def __init__(self) -> None:
pass
def read(self):
lst = []
n1 = int(input('Enter the number of values to be sorted:'))
print('Enter the values to be sorted')
for i in range(0,n1):
ele = int(input())
lst.append(ele)
print('Unsorted list:')
print(lst)
return lst
def sort(self,lst):
for i in range(len(lst)-1,0,-1):
for j in range(i):
if lst[j] > lst[j+1]:
temp = lst[j]
lst[j] = lst[j+1]
lst[j+1] = temp
def display(self,lst):
print('sorted list')
print(lst)
object1 = BubbleSort1()
lst = object1.read()
object1.sort(lst)
object1.display(lst)
Option_2
class BubbleSort1:
def __init__(self) -> None:
self.lst = []
def read(self):
lst = []
n1 = int(input('Enter the number of values to be sorted:'))
print('Enter the values to be sorted')
for i in range(0,n1):
ele = int(input())
lst.append(ele)
print('Unsorted list:')
print(lst)
self.lst = lst
def sort(self):
lst = self.lst
for i in range(len(lst)-1,0,-1):
for j in range(i):
if lst[j] > lst[j+1]:
temp = lst[j]
lst[j] = lst[j+1]
lst[j+1] = temp
def display(self):
print('sorted list')
print(self.lst)
object1 = BubbleSort1()
object1.read()
object1.sort()
object1.display()
输出:
Enter the number of values to be sorted:3
Enter the values to be sorted
1
3
2
Unsorted list:
[1, 3, 2]
sorted list
[1, 2, 3]