Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在Python3中创建交换元素的函数的疑难解答_Python 3.x - Fatal编程技术网

Python 3.x 在Python3中创建交换元素的函数的疑难解答

Python 3.x 在Python3中创建交换元素的函数的疑难解答,python-3.x,Python 3.x,我很难理解创建一个交换Python列表中元素的函数所需的for循环 我试图使用一个for循环创建函数,但显然需要多个for循环 投入: n = int(input().strip()) a = list(map(int, input().strip().split(' '))) 我的方法: def count_swaps(a): total_swaps = 0 i = 0 if a[i + 1] > a[i]: total_swaps += 1

我很难理解创建一个交换Python列表中元素的函数所需的for循环

我试图使用一个for循环创建函数,但显然需要多个for循环

投入:

n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
我的方法:

def count_swaps(a):
    total_swaps = 0
    i = 0 
    if a[i + 1] > a[i]:
        total_swaps += 1   
        temp = a[i+1]
        a[i+1] = a[i]
        a[i] = temp
    return total_swaps



正确的解决方案:

def count_swaps(a):
    total_swaps = 0

    for i in range(n):
        swaps = 0
        for j in range(n-1):
            if a[j] > a[j+1]:
                temp = a[j+1]
                a[j+1] = a[j]
                a[j] = temp
                swaps += 1           
    total_swaps += swaps

    return total_swaps


我的问题是,为什么需要两个for循环,即范围(n-1)中的
j和范围(n)
中的
i?此外,两者的范围是否应该不相同?

似乎您正在进行气泡排序,以计算数组中的反转数。这意味着
total\u swaps
是数组中所有对的数目,使得
A[i]>A[j]
i
。您的函数只计算相邻元素之间所需的交换数,而正确的答案计算使数组排序所需的交换总数。请原谅我不理解(我是这方面的初学者),但我不确定相邻元素之间的交换数如何不等于所需的交换总数。我很难理解这里的
j
表示什么,而且
a[I]>a[I+1]
不够
a=[9,1,1,1]
。您计算的相邻掉期数量为
1
。然而,需要交换的总数量是
4
,您必须交换
9
,每个
1
,然后让它在数组中向上移动。非常感谢您,我现在明白了!