Richard C
Richard C

Reputation: 783

create a unique set of values length L using Python

I need to create a list of values of a specified length which are unique. The way i am doing this currently is using

[str(i+1).ljust(subscriber_length, "0") for i in range(count)]

However this does not give unique numbers as if subscriber length is > 9 then n, n0 and n00 all give the same value eg, 1, 10 and 100 all give 100 as a value.

I know there must be a better way of doing this.

The expected output needs to be a string of digits (at the moment numbers is fine) of Length (subscriber_length) this is inserted into a CSV file and processed so preceding 0's don't work.

as an example if subscriber_length was 7 an acceptable range would be

|ID     |
|1000000|
|1000001|
|1000002|

as this is test data what the values are isn't important, what is important is they are unique and there is no possibility of preceding 0's being stripped.

Upvotes: 1

Views: 79

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55884

The range function supports setting a starting value, so you can set that to a suitable value and then just cast each value to str.

If you want identifiers to be seven characters long, set the start value to 1000000 (10 ** 6):

>>> count = 100
>>> subscriber_length = 7
>>> start = 10 ** (subscriber_length -1)
>>> end = start + count
>>> L = [str(i) for i in range(start, end)]

# There's no duplication
>>> len(L) == len(set(L)) == count
True

# All the values are the correct length
>>> all(len(x) == subscriber_length for x in L)
True

The code still works for lengths greater than nine.

>>> count = 100
>>> subscriber_length = 12
>>> start = 10 ** (subscriber_length -1)
>>> end = start + count
>>> L = [str(i) for i in range(start, end)]
>>> len(L) == len(set(L)) == count
True
>>> all(len(x) == subscriber_length for x in L)
True

Upvotes: 3

Related Questions