Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number list with no repeats and ordered

Tags:

python

This code returns a list [0,0,0] to [9,9,9], which produces no repeats and each element is in order from smallest to largest.

def number_list():
    b=[]
    for position1 in range(10):
        for position2 in range(10):
            for position3 in range(10):
                if position1<=position2 and position2<=position3:
                    b.append([position1, position2, position3])

    return b

Looking for a shorter and better way to write this code without using multiple variables (position1, position2, position3), instead only using one variable i.

Here is my attempt at modifying the code, but I'm stuck at implementing the if statements:

def number_list():
    b=[]
    for i in range(1000):
        b.append(map(int, str(i).zfill(3)))
    return b
like image 644
QuantumTraveler Avatar asked Dec 03 '15 05:12

QuantumTraveler


People also ask

How do you randomize a list in Excel without repetition?

Select random rows in Excel without duplicates Only works in Excel 365 and Excel 2021 that support dynamic arrays. To select random rows with no repeats, build a formula in this way: INDEX(SORTBY(data, RANDARRAY(ROWS(data))), SEQUENCE(n), {1,2,…}) Where n is the sample size and {1,2,…} are column numbers to extract.


1 Answers

On the same note as the other itertools answer, there is another way with combinations_with_replacement:

list(itertools.combinations_with_replacement(range(10), 3))
like image 122
tijko Avatar answered Sep 29 '22 13:09

tijko