M
M
merkulov02018-12-14 18:57:41
Python
merkulov0, 2018-12-14 18:57:41

How to generate random character combinations without repeats in python?

There is a python code that gives random combinations of characters from a list:

import random
symbs = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M']
t = 80000
tt = 0
while (t != tt):
  x_ = 8
  cc = 0
  s = 8
  r = ""
  x = ""
  res = ""
  while (cc != s):
      res = ""
      x = str(symbs[random.randint(0,61)])
      r = r + x
      cc += 1
  t += 1
  print(r)

how to eliminate repetitions when generating such combinations?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aRegius, 2018-12-14
@mmerkulov0

All unique combinations of list elements (in the amount of all elements included in the list):

>>> import itertools
>>> values = list(range(1, 4))
>>> values
[1, 2, 3]
>>> list(itertools.permutations(values, 3))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

M
mentor2, 2018-12-15
@mentor2

sorry, but very non-pythonic, non-idiomatic code!!
When talking about uniqueness, non-repeatability of elements in the final
collection, then either use a set, or sample, like
>>> random.sample(symbs,k=8)
['z', 'h', 'V', 'T', 'l', 'j', 'g', 'c']
and why a list when you do everything in strings...
isn't it easier:
>>> import string
>>> symbs = string.digits + string.ascii_letters
>>> # and if you still need a list, then do the classic
>>> symbs = ','.join(symbs)
>>> symbs = symbs.split(sep =',')
>>>
and not at all understandable
"
inside the eights that are pulled out by a random int or repetitions from
the eights themselves in the eighty thousandth generated
combinations (from the first cycle)
what is the name x_ ?? why is it??
you increase t (in the penultimate line), but what the hell?, it is from 80000
and up and will never be equal to tt, i.e. no, you wrote it off badly.
I don’t make such decisions from my students .....
Ideally, such tasks are in 2-3 lines and through different comprehensions ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question