Python 3.x 我在从函数中获取返回时遇到问题
我正在编写一个程序来比较排序方法。我正在使用所做的比较来跟踪每个项目的效率。我已经能够跟踪进行了多少次比较,但是我无法将比较从函数返回到原始变量中Python 3.x 我在从函数中获取返回时遇到问题,python-3.x,Python 3.x,我正在编写一个程序来比较排序方法。我正在使用所做的比较来跟踪每个项目的效率。我已经能够跟踪进行了多少次比较,但是我无法将比较从函数返回到原始变量中 import random # allows user to create a set of numbers, at their desiered length setSize = int(input('How many numbers are we sorting today?')) # creates a random list of numb
import random
# allows user to create a set of numbers, at their desiered length
setSize = int(input('How many numbers are we sorting today?'))
# creates a random list of numbers between 0 and 999,999
numbers = random.sample(range(0, 999999), setSize)
SelectionCount = 0
def sort (arr, a, b, i, j, count):
while j < a:
while i < a:
if arr[b] > arr[i]:
b = i
count += 1
i += 1
arr[j], arr[b] = arr[b], arr[j]
j += 1
i = j
b = i
sort(numbers, setSize, 0, 0, 0, SelectionCount)
print("The sort has been completed, there were " + str(SelectionCount) + " comparisons made!")
随机导入
#允许用户按设计长度创建一组数字
setSize=int(输入('我们今天要排序多少个数字?'))
#创建介于0和999999之间的随机数字列表
数字=随机。样本(范围(0,999999),设置大小)
SelectionCount=0
def排序(arr、a、b、i、j、计数):
而jarr[i]:
b=i
计数+=1
i+=1
arr[j],arr[b]=arr[b],arr[j]
j+=1
i=j
b=i
排序(数字、设置大小、0、0、0、SelectionCount)
打印(“排序已完成,有”+str(SelectionCount)+“已进行比较!”)
您可以从函数返回计数。此外,您不必将a、b、i、j
作为函数参数,只需在函数内部初始化它们即可
例如:
import random
# allows user to create a set of numbers, at their desiered length
setSize = int(input('How many numbers are we sorting today?'))
# creates a random list of numbers between 0 and 999,999
numbers = random.sample(range(0, 999999), setSize)
def sort (arr):
a, b = len(arr), 0
i, j = 0, 0
count = 0
while j < a:
while i < a:
if arr[b] > arr[i]:
b = i
count += 1
i += 1
arr[j], arr[b] = arr[b], arr[j]
j += 1
i = j
b = i
return count
SelectionCount = sort(numbers)
print("The sort has been completed, there were " + str(SelectionCount) + " comparisons made!")
好的,那起作用了。我早些时候尝试过使用return,但我不知道它是如何工作的,所以它没有做我需要的事情。非常感谢。
How many numbers are we sorting today?10
The sort has been completed, there were 12 comparisons made!