Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Loops Loops Loops
#1
Thumbs Up 
Hey guys,
I have this empty port list that I want to fill with 10 random ports in a pre-defined range with a random N step so i've managed to, somehow, come up with that code:

    ports = []
    i = 0
    while i < 10:
        for p in range(5000, 65000, random.randint(1000, 10000)):
            print(p)
            ports.append(p)
            i += 1
            if i >= 20:
                break
This totaly works and do the job I wanted it to do.
My question is: are there any other ways to do it? if so, what are they? and if you can and there's a generator in your answer, save it for last :)


Thank you! (loops!!!! i'm stuck in a loop!!)
Reply
#2
Your first port will always be 5000 and 5000 may appear multiple times in the list. You could have more than 10 ports in the list. The step is randomly chosen, but it is not a randomly sized step (groups of steps will be the same). This doesn't match your description of what you want to do at all.

You can fix the length problem like this:
ports = []
while len(ports) < 10:
    for p in range(5000, 65000, random.randint(1000, 10000)):
       ports.append(p)
       if len(ports) >= 10:
           break
This code still has the problem that 5000 will always be the first port and it may appear in the list multiple times.

Would you rather have 10 random ports in the range 5000 to 65000? This is easily done:
ports = random.sample(range(5000, 65000), k=10)
If you want them in order:
ports = sorted(random.sample(range(5000, 65000), k=10))
Reply
#3
import random


def random_int_range(num, start, end, step=1):
    """
    Return a random integer sample of size `num` from `start` to `end` + 1 with given `step`.
    
    If too less results are in the range, an empty list is returned instead of throwing a `ValueError`
    """
    try:
        return random.sample(range(start, end + 1, step), k=num)
    except ValueError:
        return []
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
(Feb-22-2021, 05:24 AM)deanhystad Wrote: Your first port will always be 5000 and 5000 may appear multiple times in the list. You could have more than 10 ports in the list. The step is randomly chosen, but it is not a randomly sized step (groups of steps will be the same). This doesn't match your description of what you want to do at all.

You can fix the length problem like this:
ports = []
while len(ports) < 10:
    for p in range(5000, 65000, random.randint(1000, 10000)):
       ports.append(p)
       if len(ports) >= 10:
           break
This code still has the problem that 5000 will always be the first port and it may appear in the list multiple times.

Would you rather have 10 random ports in the range 5000 to 65000? This is easily done:
ports = random.sample(range(5000, 65000), k=10)
If you want them in order:
ports = sorted(random.sample(range(5000, 65000), k=10))

Thank you for taking the time to notice that.
I did noticed that as well but just before I logged in (I had to fix a list bug and then noticed the 5000 but I thought i'll get to it later.. thanks!)

It's my first time reading about the random.sample option. what is the "k" stands for?
this opens up alot more options for me so thanks again.
Reply
#5
(Feb-22-2021, 01:03 PM)Gilush Wrote: It's my first time reading about the random.sample option. what is the "k" stands for?
random.sample
Basically it picks k unique random elements(sample) from a sequence.
>>> import random
>>> 
>>> random.sample(range(1, 10), 5)
[5, 3, 1, 7, 9]
>>> random.sample(range(1, 10), 5)
[8, 9, 6, 1, 4]
>>> random.sample(range(1, 10), 11)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python39\lib\random.py", line 363, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative
If doing it like this there will not be unique elements.
>>> [random.randint(1, 10) for i in range(5)]
[5, 8, 8, 9, 5]
>>> [random.randint(1, 10) for i in range(5)]
[9, 1, 3, 5, 5]
Gilush likes this post
Reply
#6
(Feb-22-2021, 04:34 PM)snippsat Wrote:
(Feb-22-2021, 01:03 PM)Gilush Wrote: It's my first time reading about the random.sample option. what is the "k" stands for?
random.sample
Basically it picks k unique random elements(sample) from a sequence.
>>> import random
>>> 
>>> random.sample(range(1, 10), 5)
[5, 3, 1, 7, 9]
>>> random.sample(range(1, 10), 5)
[8, 9, 6, 1, 4]
>>> random.sample(range(1, 10), 11)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python39\lib\random.py", line 363, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative
If doing it like this there will not be unique elements.
>>> [random.randint(1, 10) for i in range(5)]
[5, 8, 8, 9, 5]
>>> [random.randint(1, 10) for i in range(5)]
[9, 1, 3, 5, 5]

Thank you.
That answer helps me understand generators better.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pyserial issues with proper loops and binary jttolleson 16 2,464 Nov-02-2023, 08:39 PM
Last Post: deanhystad
  for loops break when I call the list I'm looping through Radical 4 824 Sep-18-2023, 07:52 AM
Last Post: buran
  reduce nested for-loops Phaze90 11 1,757 Mar-16-2023, 06:28 PM
Last Post: ndc85430
  Need help with creating dynamic columns with for loops for stock prices PaDat 2 859 Feb-22-2023, 04:34 AM
Last Post: PaDat
  Why both loops don't work in python? nau 3 1,055 Sep-21-2022, 02:17 PM
Last Post: rob101
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,638 Aug-19-2022, 11:07 AM
Last Post: dm222
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,532 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  breaking out of nested loops Skaperen 3 1,174 Jul-18-2022, 12:59 AM
Last Post: Skaperen
  For Loops Driving Me Insane Guybrush3pwood 9 2,125 May-01-2022, 11:01 AM
Last Post: snippsat
  Definitions in User-Created Functions and For Loops new_coder_231013 6 2,027 Dec-29-2021, 05:51 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020