如何在此特定功能中解决范围问题?
我正在实现一种洗牌算法,我需要检查我运行了多少次算法以获取原始数组。我已经尝试实施一段时间循环并启动计数器,但是范围有一些问题。数组ARR和ARR2具有相等的值。有人可以帮忙吗?
from random import randint, random
from math import floor
def shuffle(the_list):
amnt_to_shuffle = len(the_list)
while amnt_to_shuffle > 1:
i = int(floor(random() * amnt_to_shuffle))
amnt_to_shuffle -= 1
the_list[i], the_list[amnt_to_shuffle] = the_list[amnt_to_shuffle], the_list[i]
return the_list
arr = [i for i in range(1,11)]
original_arr = arr
k = 0
while 1:
arr2 = shuffle(arr)
if arr2 == original_arr:
break
else:
shuffle(arr)
k += 1
print(k)
I am implementing a shuffling algorithm and I need to check how many times I have ti run the algorithm to get the original array. I have tried implementing a while loop and initiating a counter but there is some problem with the scope. The arrays arr and arr2 have equal values. Can someone help?
from random import randint, random
from math import floor
def shuffle(the_list):
amnt_to_shuffle = len(the_list)
while amnt_to_shuffle > 1:
i = int(floor(random() * amnt_to_shuffle))
amnt_to_shuffle -= 1
the_list[i], the_list[amnt_to_shuffle] = the_list[amnt_to_shuffle], the_list[i]
return the_list
arr = [i for i in range(1,11)]
original_arr = arr
k = 0
while 1:
arr2 = shuffle(arr)
if arr2 == original_arr:
break
else:
shuffle(arr)
k += 1
print(k)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码仅具有一个列表。
arr
,ointer_arr
,arr2
,...它们都是相同列表。您的shuffle
函数突变列表它作为参数。即使该函数返回列表,此是它作为参数传递的呼叫者列表,因此是 列表。不是 返回此
shuffle
函数中的列表,这将是更多的Pythonic。这也意味着您不需要arr2
。无关,但是您的循环应该只有一个呼叫
shuffle
,而不是两个。关键是使
ointer_arr
新列表是arr
的副本。您可以通过几种方式来执行此操作,例如Slice语法:Your code has only one list.
arr
,original_arr
,arr2
, ... they are all the same list. Yourshuffle
function mutates the list it gets as argument. Even though that function returns the list, this is the caller's list that it passed as argument, so it is that list that is shuffled.It would be more pythonic to not return the list in this
shuffle
function, so to make absolutely clear to the caller that their list is mutated (shuffled) by it. This also means you don't needarr2
.Unrelated, but your loop should just have one call to
shuffle
, not two.The key is to make
original_arr
a new list that is a copy ofarr
. You can do this in several ways, e.g. by slice syntax:通过编写
Original_arr = ARR
您将arr
的指针复制到oinder_arr
因此,其中任何一个的任何更改都会影响另一个。您可以导入
深层复制列表或使用copy.deepcopy.deepcopy
Original_arr = arr [:]
By writing
original_arr = arr
you copy the pointer ofarr
tooriginal_arr
hence any change in any one of them will effect the other.You can import
copy.deepcopy
to deep copy the list or to useoriginal_arr = arr[:]