Skip to main content
Code Review

Return to Revisions

2 of 9
added 559 characters in body
David Foerster
  • 1.7k
  • 10
  • 20

(削除) sample() (削除ここまで) is the wrong kind of randomness here since it draws N random samples from the given container without repetition. Instead you should should use choices() which allows repetition of the same item.

Normally you want as much entropy as possible in the given "space" (here: 15 items chosen from 62 Arabic digits and basic Latin letters). If you disallow repetitions you reduce the size of you key space significantly and risk more (frequent) collisions at no benefit and more costly sample computation1.

Additionally you should avoid unexplained "magic numbers" and allow parameters (with sensible defaults) for arbitrarily chosen values:

def generate_unique_key(length=15):
 array = # ... construct character set
 return "".join(random.choices(array, k=length))

For Python versions prior to 3.6 you can provide a simple implementations of choices() yourself:

import random
try:
 random_choices = random.choices
except AttributeError:
 def random_choices(population, *, k=1):
 return map(random.choice, itertools.repeat(population, k))

1 An optimal algorithm for random samples without repetition is more complex than one with repetition and either requires O(k) intermediate storage or O(k2) runtime (with k being the sample size).

David Foerster
  • 1.7k
  • 10
  • 20
default

AltStyle によって変換されたページ (->オリジナル) /