模数如何与列表一起使用?
此函数返回一个新的分布q
,由U
单位向右移动。如果U = 0
,q
应该与p
相同。
p = [0, 1, 0, 0, 0]
def move(p, U):
U = U % len(p)
q = p[-U:] + p[:-U]
return q
print(move(p, 1))
代码输出是正确的:[0, 0, 1, 0, 0]
如何用外行的术语描述这个python代码的数学步骤?
解决了。
为了更好地理解Modulo如何工作,我编写了这段代码并检查了输出:
for i in range(40):
print('the number : ', i)
print('number % 5 : ', i%5)
Modulo是余数,但不仅仅是余数。另一位用户以这种鼓舞人心的方式表达了它:
想一天24小时,
你可以把历史上的所有时间都想象一遍又一遍地围绕着24小时的圈子,而当天的当前时刻就是无限长的数字模型24.它是一个更为深刻的概念,而不仅仅是一个余数,它是一种数学方式处理周期,这在计算机科学中非常重要。它还用于环绕数组,允许您在到达数组末尾后增加索引并使用模数回绕到开头。
p=[0, 1, 0, 0, 0] # asign a list to the variable p
def move(p, U): # define a new function. Its name is 'move'. It has 2 parameters p and U
q = [] # Assign an empty list to the variable q
# len(p) returns the size of the list. In your case: 5
# You calculate the remainder of U / len(p) ( this is what modulo does)
# The remainder is assigned to U
U = U % len(p)
# p[-U:] gets U items from the list and beginning from the end of the lis
# e.g. [1,2,3][-2:] --> [2,3]
# the second part returns the other side of the list.
# e.g. [1,2,3][:-2] --> [1]
# These two lists are concatenated to one list, assigned to q
q = p[-U:] + p[:-U]
# The new list is returned
return q
print(move(p, 1))
如果您需要对一个部分进行任何进一步的解释,请告诉我
Modulo不能与列表一起使用,modulo只影响索引值U.U用于将列表拆分为两个:
p[-U:] + p[:-U]
modulo为你做的是确保U保持在0和len(p)-1之间,没有它你可以为U输入一个非常大的值并得到一个索引错误。
还要注意,在你的代码中,该行
q = []
在步骤中再次创建q时不执行任何操作:
q = p[-U:] + p[:-U]