How would i generate a random 4 digit number without any duplicates in Python, sure i could just do:

How would i generate a random 4 digit number without any duplicates in Python, sure i could just do:
str(random.randint(0000,9999))
but then id get a number with duplicates for example 3445
Any ideas?
Thanks in advance

Attached: 1_PPIp7twJJUknfohZqtL8pQ.png (601x203, 9K)

Other urls found in this thread:

google.lu/search?q=generate a random 4 digit number without any duplicates in Python&oq=generate a random 4 digit number without any duplicates in Python&aqs=chrome..69i57&sourceid=chrome&ie=UTF-8
users.telenet.be/vdmoortel/dirk/Maths/PermVarComb.html
lmgtfy.com/?q=generate variation without repetition
twitter.com/SFWRedditGifs

google.lu/search?q=generate a random 4 digit number without any duplicates in Python&oq=generate a random 4 digit number without any duplicates in Python&aqs=chrome..69i57&sourceid=chrome&ie=UTF-8

keep running it until you don't have duplicates

create a loop and append the random numbers with a while loop.

I forgot python formating but basically

A = []
while length(A)

luxembourg?
>what is a 10-choose-4 variation
direct brainlet algorithm:
get a random first digit D1, then get a random next digit from the {0-9}\D1 set (e.g. D1=8, thus choose from {0-7,9}), and so on for the other digits

>def randint(): return 4
not guaranteed to terminate

You're looking for a variation without repetition of 4 digits from the 0-9 set:
users.telenet.be/vdmoortel/dirk/Maths/PermVarComb.html

Novices want to do the weirdest things. Easiest thing would be to just check for duplicates afterwords and loop until you get what you want

import random
bag = range(10)
random.shuffle(bag)
result = "".join(str(i) for i in bag[:4])

gb2loo, pajeet
this is babby-tier DS&A shit - variations without repetition
literally taught to jr high schoolers in shithole countries, ffs

ayy
gets the job done

>generate random list
>if duplicate replace exists, replace duplicate with rand with same distribution
>loop through until no duplicates

Not random

lmgtfy.com/?q=generate variation without repetition

>shuffling is not random
what are you on about

uhh

You're not generating a random number. You're generating a random sequence of numbers. OP didn't really specify though

As a string:
import random
"".join(map(str, random.sample(range(10),4)))

If you want strictly integers:
import random
reduce(lambda x,y: y+x*10, random.sample(range(10),4))

You need to check for leading zeros, thats your homework.

autism
also
>numbers
digits
FTFY

dumbass solution

>generate an array from 0 to 9
>define a variable "u = 9"
>draw a random number n from 0 to 9, this will be your index
>swap the nth element with the uth element
>decrease u by 1
>now your array may look like [0, 1, 2, 9, 4, 5, 6, 7, 8, 3]
>draw a random number n from 0 to u (8)
>swap the nth element with the uth element and store the nth element somewhere
>now your array may look like this [8, 1, 2, 9, 4, 5, 6, 7, 0, 3]
>repeat two more times
>retrieve the last 4 numbers of the array in verse order

actually thinking about it you could define u to be 0 and then start to increase it, drawing a random number from u+1 to 9, so you get your number in order at the start of your array at the end.

finally I see a python programmer who use lambda in his code.

>You need to check for leading zeros
brain's fried, why?

0123 isn't a 4 digit number

bleh, right
sounds like he actually needs
digits 1-3 in 1..9, digit 4 in 0..9

>How would i generate a random 4 digit number without any duplicates in Python, sure i could just do:
>str(random.randint(0000,9999))
Is 0328 (note leading zero) considered a 4 digit number for this homework assignment?

everyone ITT has forgotten about sets

im doing this hw assignment too

good luck on finals

>everyone ITT has forgotten about Dre
>Ctrl+F set: 3/3

Nice runtime complexity faggot.

I mean, who doesn't love O(potentially INF)

1) Generate list of numbers from 0-9999
2) Random shuffle indexe a couple of times

This is brainlet tier easy

>shuffle indexe a couple
omlette du fromage

>Random shuffle indexe a couple of times
and pythonjeets wonder why no one is taking them seriously

brainlet here in javascript I'd
while loop
generate random, multiply by 10000, truncate off decimals
conditional, regex check, if 1{2,} or 2{2,}... etc returns true, if so, Continue
Else, Break and Return number

>there's a O(1) solution
>99% of pythonlets will give a O(lolrandom) "solution"

import random

arr = random.sample(range(10), 4)
num = 0
for i in range(4):
num += arr[i]*10**i
print(num)

>muh big oh notation

Its great for simple shit like this.

The problem was not clearly specified.
Ofc a plain random.sample(range(10),4) could do too.

random.sample(range(10), k=4)
as string
''.join(map(str, random.sample(range(10), k=4)))

arr = [ 0,1,2,3,4,5,6,7,8,9 ]
str = ""
for i in range (0,4)
index = random.randit( len(arr))
digit = arr[index]
str += str(digit))
arr -= [ digit ]

Which O(1) solution?

you're a retard, but tht's not surprising since they only teqch stats in college in America

it's O(n) you dumb cunt. Besides who gives a shit, it's python

L = list(range(10))
random.shuffle(L)
return L[:4]

>it's O(n) you dumb cunt.
No, it isn't. O(n) means the worst case scenario is a+b*n where n is the length required, so in this case a+b*4. Your worst case scenario is not being able to generate another random number different than the digits already in the number, so it's O(infinity).

I like this one.

what would be the time complexity of this

Jow Forums eternally btfo
import random

a = []
for i in range(1000):
a.append(i)

for i in range(len(a)):
print(a[random.randint(0,len(a) -1)])

except your worse case scenario can n e ve r happen. Statically it mostly takes less than 8 so it's O(n).

what the

the array-swap solution doesn't need to walk through the sequence from 0 to 9 to check for repetition or anything like that, but I guess you should call it O(n), n being the number of digits you're drawing.

import random
print random.sample(range(0000, 9999), 100)


This should return 100 random non-repeating 4 digit numbers.

sorry bb I forgot the pop
import random

a = []
for i in range(10000):
a.append(i)

for i in range(len(a)):
print(a.pop(random.randint(0,len(a) -1)))


however Jow Forums still btfo

return 1234

fucking this

zero padding:
import random
for i in random.sample(range(0000, 9999), 100):
print str(i).zfill(4)

bikeshedding: the thread
>the average idiot is more likely to provide his special olympics tier opinion on babby tier topics, compared to ones where any level of non-retardation is required

>muh hacker news buzzwords
kys nigger faggot

>take an array with values 0-9
>shuffle the array
>take the last (or first) 4 items and concat them together into a string
>convert that to an int

which part of that was a webshit buzzword, you literal faggot

>t. webshit who thinks HN invented a term from the 60s
how many cocks are you gagging on right now, you useless piece of JS-shitting cartilage?

In the interest of saving some space at the cost of the worst case time being very bad,

def random_no_reps(sample_range=None):
"""
random number generator for given range with no repetition
defaults to [1000,9999]
"""
if sample_range is None:
sample_range = range(1000, 10000)

found = set()

while len(found) < len(sample_range) - 1:
choice = random.choice(sample_range)
while choice in found:
choice = random.choice(sample_range)
found.add(choice)
yield choice

>except your worse case scenario can n e ve r happen
But the definition of O is the worst-case complexity. If you don't care about the worse-case scenarion, then don't use O notation.
>Statically it mostly takes less than 8 so it's O(n).
I'm not sure what this means. If you meant to say "statistically", then this makes no sense: O has absolutely nothing to do with the statistical mean. If you want to talk about average-case complexity, then talk about that instead of O.

Your solution is O(infinity), congrats.

You mean this ? Yes, it's O(n) where n is the length of the string you're trying to generate I guess. But considering every single other is O(inf) it's pretty good.

O(infinity) in the worst case

import os

def gen_rand_num_unique_digits(digits):
if digits > 10:
raise ValueError('only 10 unique digits possible')
_bytes = os.urandom(1)
str_n = str(int.from_bytes(_bytes, 'little'))[:digits]
while len(str_n) < digits or len(str_n) != len(set(str_n)):
_bytes = os.urandom(1) + _bytes
str_n = str(int.from_bytes(_bytes, 'little'))[:digits]
return int(str_n)
Anyone smarter than me tell me if there's any bias in this (besides filtering for unique digits)?

the shuffle probably works like this internally, not sure won't look up

>O(infinity) in the worst case
Wet water.

A note, I would use this if I were expecting to use this fewer n/4 times where n is the length of the sample_range. Beyond that it starts becoming likely that the random.choice loop will go multiple times and the found set will have also grown to the point where the space savings over just doing a shuffle won't be worth it.

You're all retarded, 4 digits isn't enough to even have an impact on memory use

numbers = list(range(1000, 9999))
random.shuffle(numbers)

# Then when you want a unique 'random' number
whatever = numbers.pop()

Loop with a random number generator and store each random in a hashset and if you get a collision just try again. Faggot

import random
nums = [str(i) for i in range(0,10)]
random.shuffle(nums)
"".join(l[:4])
# or int("".join(l[:4]))

But you get numbers like 1552, which are not allowed.

You're shuffling 8999 numbers (forgetting range doesn't include the last one lel) when you you only need to shuffle 10 and pick 4 from it (plus taking care of leading zero but whatever)
Actually you don't even need to shuffle all of them, since you only need to pick 4.

It doesn't matter if it doesn't matter, there are cases and different version of the same problem when it will matter.

So, in a more readable format:
arr = [ ... ]
index = len(arr) -1
for range( len(array)):
x = random.randint(index)
swap = arr[x]
arr[x] = arr[index]
arr[index] = swap
index -= 1

May have fucked

pickone(range(10000).filter(doesn't have a repeated digit or leading zero))

>people using anything other than /dev/urandom

Attached: vomiting.jpg (300x300, 32K)

constant time complexity, bravo!

shuffle an array containing 0 to 9 and get the first/last 4

Explain the difference.

yeah that's the whole shuffling

oh okay, OP meant generate a number with no repeated digits. "duplicate" implied to me (and most of this thread) that we were talking about generating unique random numbers.

from random import choice, sample

def random_no_repeated_digits(digits=4):
if digits < 1:
raise ValueError("digits must be positive")

first_digit = choice([1, 2, 3, 4, 5, 6, 7, 8, 9])
following_digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
following_digits.remove(first_digit)

n = first_digit * (10 ** (digits - 1))
p = digits - 2
if digits > 1:
for g in sample(following_digits, digits - 1):
n += g * 10 ** p
p -= 1

return n

I learned that you can't do a random.choice from a set which is dumb. Also I'm too used to immutable collections and my initial code was followind_digits = {0, 1, 2, ..., 9}.remove(first_digit) which doesn't work at all in python.

Also I wonder how multiplying by powers of 10 to build the number compares with just building a string.

from random import randint

gen_digits = lambda: randint(1000,9999)
chk_digits = lambda n: len(set(`n`)) < len(str(n))

while True:
number = gen_digits()
if not chk_digits(number):
print number
break

Updated to support any number of digits:

from random import randint

gen_digits = lambda n: randint(10**(n-1), (10**n)-1)
chk_digits = lambda n: len(set(`n`)) < len(str(n))

while True:
number = gen_digits(5)
if not chk_digits(number):
print number
break

Answer given in like 30 post, people still arguing...

from random import randint

gen_digits = lambda n: randint(10**(n-1), (10**n)-1)
chk_digits = lambda n: len(set(`n`)) < len(`n`)

while True:
number = gen_digits(4)
if not chk_digits(number):
print number
break

I didn't know lambda supported random numbers like that

there's no such thing as random anyways

isnt it funny that the only time Jow Forums posts actual code is when it's for an effortless code 101 homework question by a high school kid like this? and even then it's all shit answers

Yes there is.

:^)
(0..9).to_a.sample(4).join.to_i

no, there isn't

if it were random, it would be infinite. if it were deterministic, it would be finite, but absolutely retarded and probably beyond O(n!)

Using reduce, see me after class

the expected number of times he'd have to generate a random number from 1000 to 9999 until getting one without repeating digits is 2.3

How do you think python on linux generates random numbers faggot

A great number of quantum physicists would disagree with you.

print 1234


* it's provably random
* it's O(1)
* function is 1 symbol and 4 bytes.
* it's completely native

>/dev/urandom

hello from the NSA

No reason the second or third digit can't be zero. 1024 meets the criteria, for example.

>the absolute state of Jow Forums
from random import randint

l = range(0,9)
c = n = 0
while c < 4:
tmp = len(l)-1
i = randint(0, tmp)
n *= 10
n += l.pop(i)
c += 1

print(n)

Man, your anger is funny. Just isin() is O(n) and you loop a minimum of n times. Replace it with a constant time lookup(cough dictionary or hash table) and maybe you can achieve it in linear time.