Created
April 9, 2019 08:28
-
-
Save haowen-xu/9b8e330129692cee28362ef23bfd86ea to your computer and use it in GitHub Desktop.
Random k unique numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def random_k(start, end, k): | |
seq = list(range(start, end)) | |
if len(seq) < k: | |
raise ValueError('k too large.') | |
n = len(seq) | |
for i in range(0, min(k + 1, n - 1)): | |
j = random.randint(i, n - 1) | |
if i != j: | |
seq[i], seq[j] = seq[j], seq[i] | |
return seq[:k] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment