Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

python - I want to separate numbers whose last digits is same

I defined a function by:

input : two numbers l,k   
output: the number k in base l

Code

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)) 

The loop generates numbers in base n. Now I want to separate the numbers with same last digit.
For ex: If the loop gives output as 01,10,11 then it separates numbers 01 and 11. I want to do the same for n same last digits. In other words, I want to separate the numbers with last digit 0,1,2 and so on

I can't store these values in an array as I want to have very large iterations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

a lazy version of this (using itertools.product) would be:

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)

for any possible last_digits you get remaining_digits that you can prepend to them. the remaining_digits here is an iterator - it will not store all the elements in memory.

you can then combine last_digits and remaining_digits any way you want (e.g. combine them to a string or an integer as needed).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...