1

maybe this is a rookie question, but how can i get a new random number everytime it repeats?

realport = random.randint(portstarts, portends)

liste = list(itertools.repeat('{}:{}:{}:{}'.format(hostname, realport, username, password), amount))
Woodford
  • 3,746
  • 1
  • 15
  • 29
DerApfel0
  • 13
  • 6
  • What do you mean by "repeats?" Is repetition described as consecutive random numbers with the same value, or just any two equal random numbers regardless of their positions in the sequence? – Michael Ruth Apr 13 '21 at 23:15
  • At the moment Two or more equal random numbers, but I need consecutive random numbers in the list :) – DerApfel0 Apr 14 '21 at 00:33
  • 1
    Is there some reason you need `itertools.repeat`? Because by definition, `itertools.repeat` always returns the *same* object (not a copy, not a newly created object, literally the exact same object you passed as the first argument to `repeat`). – ShadowRanger Apr 14 '21 at 04:16
  • Actually I don’t need itertools.repeat, but that was the first solution that came up to my head, then i later tried to add random, so yes I might need a new solution for this – DerApfel0 Apr 14 '21 at 09:22

1 Answers1

1

as ShadowRanger commented, itertools.repeat probably isn't what you want.

A "list comprehension" might be a nicer way of expressing what you want:

def getport():
    return random.randint(portstarts, portends)

liste = [
  '{}:{}:{}:{}'.format(hostname, getport(), username, password)
  for _ in range(amount)
]

if you want all of the ports to be unique, then you could instead use random.sample to "sample without replacement":

liste = [
  '{}:{}:{}:{}'.format(hostname, port, username, password)
  for port in random.sample(range(portstarts, portends+1), amount)
]

see, e.g. How to incrementally sample without replacement? for various ways to sample without replacement in Python

Sam Mason
  • 15,216
  • 1
  • 41
  • 60