我在这里需要一些帮助,这是基本的python编程,但在实现该功能时我遇到了困难。希望可以有人帮帮我!!提前谢谢^^
任务: 首先,我需要构建一个数组,A的2n交替'1'和'0'。即101010 然后,我需要按照所有0的顺序对它们进行排序,然后是所有1,即000111
为此,我需要构建一个函数Arrange_Disks(A,n)来接收数组A和n,并在完成2n个磁盘的必要移动后返回数组。主要功能应该在排列之前和之后显示阵列以及进行排列所需的移动次数。使用n的值在2到10的范围内。
以下是我到目前为止所做的功能:
A=[]
def Arrange_Disks(A,n):
moves=0
for i in xrange(n):
minn=i
for j in xrange(i+1,n):
if A[j]<A[minn]:
minn=j
moves+=minn-i
A[i],A[minn]=A[minn],A[i]
return A
return moves
def main():
n=input("Please enter a number between 2 to 10: ")
for disk in range (1,(2*n+1)):
if (disk%2) != 0:
A.append("1")
else:
A.append("0")
print "This is the original array: ", A
Arrange_Disks(A,n)
print "This is the sorted array: ", A
print "This is the number of moves required: ", moves
main()
当我运行此代码时,它只显示在此处:
>Please enter a number between 2 to 10: 3
>This is the original array: ['1', '0', '1', '0', '1', '0']
>This is the sorted array: ['0', '1', '1', '0', '1', '0']
>This is the number of moves required: 0
并且输出不反映移动次数......
所以我想知道是否有人可以启发我的代码。我知道这是一个很长的问题,非常感谢您阅读并花时间回答我的问题!!
ps我对这个问题进行了冒泡排序方法 我正在使用python 2.7
再次感谢^^
答案 0 :(得分:0)
如果我正确理解了您的问题,那么我猜你可以在这里使用Selection Sort:
def selection_sort(A,n):
moves=0
for i in xrange(n):
minn=i
for j in xrange(i+1,n):
if A[j]<A[minn]:
minn=j
moves+=minn-i
A[i],A[minn]=A[minn],A[i]
print moves,A
#examples:
selection_sort(['1', '0', '1', '0', '1', '0'],6)
selection_sort(['1', '0', '1', '1', '1', '1'],6)
<强>输出:强>
6 ['0', '0', '0', '1', '1', '1']
1 ['0', '1', '1', '1', '1', '1']
要生成那些交替的1
,0
列表,您可以使用itertools.cycle
:
>>> from itertools import cycle
>>> c=cycle(('1','0'))
>>> n=3
>>> [next(c) for _ in xrange(n*2)]
['1', '0', '1', '0', '1', '0']
代码的工作版本:
def Arrange_Disks(A):
length=len(A)
moves=0
for i in xrange(length):
minn=i
for j in xrange(i+1,length):
if A[j]<A[minn]:
minn=j
moves+=minn-i
A[i],A[minn]=A[minn],A[i]
return A,moves #returns a tuple containing both A and moves
def main():
n=input("Please enter a number between 2 to 10: ")
A=[]
for disk in range (1,(2*n+1)):
if (disk%2) != 0:
A.append("1")
else:
A.append("0")
print "This is the original array: ", A
A,moves=Arrange_Disks(A)
print "This is the sorted array: ", A
print "This is the number of moves required: ", moves
main()
<强>输出:强>
Please enter a number between 2 to 10: 3
This is the original array: ['1', '0', '1', '0', '1', '0']
This is the sorted array: ['0', '0', '0', '1', '1', '1']
This is the number of moves required: 6
Please enter a number between 2 to 10: 5
This is the original array: ['1', '0', '1', '0', '1', '0', '1', '0', '1', '0']
This is the sorted array: ['0', '0', '0', '0', '0', '1', '1', '1', '1', '1']
This is the number of moves required: 15