[英]I want to separate numbers whose last digits is same
我通过以下方式定义了 function:
input : two numbers l,k
output: the number k in base l
代码
def base(k,l):
result=''
while k!=0:
remainder = k%l
k=k//l
result= result + str(remainder)
return result
n=3
t=10
for i in range(n**t):
print(base(i,n).zfill(t))
循环生成以 n 为底的数字。 现在我想用相同的最后一位数字分隔数字。
例如:如果循环将 output 提供为01,10,11
,则它将数字01 and 11
分开。 我想对 n 个相同的最后一位数字做同样的事情。 换句话说,我想用最后一位0,1,2
等分隔数字
我无法将这些值存储在数组中,因为我想要进行非常大的迭代。
尝试这个:
# Creating a blank map from 0-9 to empty arrays(to store numbers)
MAP = {str(i):[] for i in range(10)}
# Then populate the dictionary like so
for i in range(n**t):
num = base(i,n).zfill(t)
MAP[num[-1]].append(num)
注意: num[-1] 将给出 num 的最后一位数字。
一个懒惰的版本(使用itertools.product
)将是:
from itertools import product
base = 3
n_digits = 5
last_digits = list(range(base)) # [0, 1, 2]
remaining_digits = product(range(base), repeat=n_digits - 1)
for digits in remaining_digits:
print(digits)
# (0, 0, 0, 0)
# (0, 0, 0, 1)
# (0, 0, 0, 2)
# ...
# (2, 2, 2, 0)
# (2, 2, 2, 1)
# (2, 2, 2, 2)
对于任何可能的last_digits
,您都会得到remaining_digits
的数字,您可以将其添加到它们之前。 这里的remaining_digits
数字是一个迭代器 - 它不会将所有元素存储在 memory 中。
然后,您可以根据需要以任何方式组合last_digits
和remaining_digits
(例如,根据需要将它们组合成一个str
或int
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.