I made a random number with this:
import random
number = random.randrange(0,100,2)
I want to iterate in it:
for i in number:
print(i)
or like that:
for number in range (50,100):
print number
I want to make a lists of random numbers, for example 50 random numbers between 0 and 100.
generate a sorted list of 50 different random numbers between 0 and 100 (not included) like this:
sorted(random.sample(range(0,100),50))
(pick 50 elements in the range object and sort them)
If you need/want repeats don't use sample just pick 50 numbers
sorted([random.randrange(0,100) for _ in range(50)])
or from python 3.6: sorted(random.choices(range(100),k=50))
For generating a list with n random numbers, you can use list comprehension. Such as,
lst = [random.randint(0,100) for _ in range(n)]
If you want to make a list of 50 random numbers between 1 and 100, you can do this:
import random
randlist = []
for i in range(50):
randlist += [random.randint(1, 100)]
Related
I am trying to generate 4-6 unique numbers in python but when I do uuid.uuuid4(), it generates something like 23dfsFe823FKKS023e343431. Is there a way I can achieve this, generate 4-6 unique numbers like 19391 or 193201.
NB: Beginner with python
yes, to make life easy lets use an easy example.
#lets import random, to generate random stuff
import random
#create a result string
result = ''
nums = [1,2,3,4,5,6,7,8,9,0]
for i in range(6):
result += str(random.choice(nums))
print(result)
UUID is for generating Universally Unique Identifiers, which have a particular structure and won't be what you're after.
You can use the random module as follows
import random
id = ''.join(str(random.randint(0,10)) for x in range(6))
print(id)
What does this do?
randint generates a random number between 0 inclusive and 10 exclusive, i.e. 0-9
calling this with for x in range(6) generates six random digits
str converts the digits to strings
''.join forms a single string from the digits
Try this:
import random
nums = set()
while len(nums) < 4: # change 4 to appropriate number
nums.add(random.randint(0, 1000000))
For example:
>>> nums
set([10928, 906930, 617690, 786206])
You can use random from standard python library
random.randint(a, b)
Return a random integer N such that a <= N <= b.
https://docs.python.org/3/library/random.html#random.randint
In [1]: from random import randint
In [2]: randint(1_000, 999_999)
Out[2]: 587848
In [3]: randint(1_000, 999_999)
Out[3]: 316441
To generate N number of a random number or token by specifying a length of Token this will be an easy and feasible solution.
import random
#num[]: by the combination of this, a random number or token will be generated.
nums = [1,2,3,4,5,6,7,8,9,0]
#all the tokens or random number will be stored in a set called tokens.
#here, we are using a set, because the set will never contain duplicate values.
tokens = set()
result='' #to store temporaray values
while len(tokens) < 10000: # change 10000 to the appropriate number to define the numbers of the random numbers you want to generate.
#change 6 to appropiate number to defined the length of the random number.
for i in range(6):
result+=str(random.choice(nums))
tokens.add(result)
result=''
print(tokens)
#print(len(tokens))
#print(type(tokens))
if you want to use uuid to generate number then you can code something like this
digit = 5 # digits in number
import uuid
for i in range(6):
print(uuid.uuid4().int[:digit])
Or
from uuid import uuid4
result = [ uuid4().int[:5] for i in range(6) ]
I'm new to Python and I am trying to generate a list of 4 random numbers with integers between 1 and 9. The list must contain no repeating integers.
The issue I am having is that the program doesn't output exactly 4 numbers everytime. Sometimes it generates 3 numbers or 2 numbers and I can't figure out how to fix it.
My code:
import random
lst = []
for i in range(5):
r = random.randint(1,9)
if r not in lst: lst.append(r)
print(lst)
Is there a way to do it without the random.sample? This code is part of a larger assignment for school and my teacher doesn't want us using the random.sample or random.shuffle functions.
Your code generates 5 random numbers, but they are not necessarily unique. If a 2 is generated and you already have 2 in list you don't append it, while you should really be generating an alternative digit that hasn't been used yet.
You could use a while loop to test if you already have enough numbers:
result = [] # best not to use list as a variable name!
while len(result) < 5:
digit = random.randint(1, 9)
if digit not in result:
result.append(digit)
but that's all more work than really needed, and could in theory take forever (as millions of repeats of the same 4 initial numbers is still considered random). The standard library has a better method for just this task.
Instead, you can use random.sample() to take 5 unique numbers from a range() object:
result = random.sample(range(1, 10), 5)
This is guaranteed to produce 5 values taken from the range, without duplicate digits, and it does so in 5 steps.
Use random.sample:
import random
random.sample(range(1, 10), 4)
This generates a list of four random values between 1 to 9 with no duplicates.
Your issue is, you're iterating 5 times, with a random range of 1-9. That means you have somewhere in the neighborhood of a 50/50 chance of getting a repeat integer, which your conditional prevents from being appended to your list.
This will serve you better:
def newRunLst():
lst = []
while len(lst) < 4:
r = random.randint(1,9)
if r not in lst: lst.append(r)
print lst
if random list needed is not too small (compared to the total list) then can
generate an indexed DataFrame of random numbers
sort it and
select from the top ... like
(pd.DataFrame([(i,np.random.rand()) for i in range(10)]).sort_values(by=1))[0][:5].sort_index()
how to print 100 random numbers of "set" in python, means I have to take 100 random numbers from given range and add it to an empty set(). I need solution in Python.I have tried in following way but its not taking 100 numbers exact.
import random
s=set()
for i in range(200):
s.add((random.randint(0,101)))
print(s)
print(len(s))
This will create a set that always has 100 elements (given the input range is equal to or larger than 100).
import random
set(random.sample(range(1337), 100))
as comments said the set can't contain duplicated numbers, so you need to execute a while loop until you get the number of elements you need in your set.
Then add a random number
import random
s=set()
while len(s) < 100:
s.add((random.randint(0,200)))
print(s)
print(len(s))
set() can only contain unique items. If you try adding an item to set() that already exists, it will be silently ignored:
>>> s = set()
>>> s.add(1)
>>> s
{1}
>>> s.add(1)
>>> s
{1}
In your original code you're actually trying to "Add 200 random numbers to a set from 0 to 100". Conceptually this is wrong, because it's not possible to get 200 unique random numbers from a range of 0 - 100. You can only get up to 100 unique random numbers from that range.
The other issue with your code is what you're randomly choosing the number in each iteration, without checking if it has been added before.
So, in order to take N random numbers from a range of 0 to M, you would have to do the following:
import random
s = set()
N = 100 # Number of items that will be appended to the set
M = 200 # Maximum random number
random_candidates = list(range(M))
for _ in range(N):
numbers_left = len(random_candidates)
# Choose a random number and remove it from the candidate list
number = random_candidates.pop(random.randrange(numbers_left))
s.add(number)
The above will work well for small ranges. If you expect M to be a large number, then generating a large random_candidates array will not be very memory effective.
In that case it would be better to randomly generate a number in a loop until you find one that was not chosen before:
import random
s = set()
N = 100 # Number of items that will be appended to the set
M = 2000 # Maximum random number
for _ in range(N):
random_candidate = random.randrange(M)
while random_candidate in s:
random_candidate = random.randrange(M)
s.add(random_candidate)
sets don't allow duplicate values (that's part of sets defininition...), and statically you will get duplicate values when calling random.randint(). The solution here is obviously to use a while loop:
while len(s) < 100:
s.add(random.randint(0, 101))
Note that with those values (100 ints in the 0..101 range) you won't get much variations since you're selecting 100 distinct values out of 102.
Also note that - as quamrana rightly mentions in a comment - if the range of possible values (randint() arguments) is smaller than the expected set length, the loop will never terminate.
For my IT class we need to do 10 different tasks and this is the last one that I'm completely stumped on. The goal is to make a list with 20 numbers between -500 and 500. We have two lines of code to sample off of and finish this with.
for i in range(10)
print(i)
and
import random
print (random.randint(0,100))
Please help me figure this out so I can get a better understanding of the code.
Building off of #COLDSPEED's comment, if you want a list of 20 number different random numbers between -500 and 500. You can use a while loop to build a set of the random numbers, then convert it to a list.
import random
rand_set = set()
while len(rand_set) < 20:
x = random.randint(-500,500)
if x not in rand_set:
rand_set.add(x)
rand_list = list(rand_set)
use this
import random
lst=[]
for i in range(20):
lst.append (random.randint(-500, 500))
print (lst)
I am new to programming and I got stuck with random number generation. I can simply generate random numbers using random function "randint" but could not generate set of random numbers. For instance i want to get 10 random numbers.
from random import randint
x = randint(1, 100)
y = randint(1, 100)
isFailedTest = (5<=x<=15) and (10<=y<=11)
selected_test = [x,y]
while (isFailedTest == False):
I can generate 1 random number at one time but not 10 at one time. Here 1 number mean 2 dimensional number example (x,y) = (10,20) I want to get 10 random numbers (x,y) after my while condition. How do I achieve that? I am very new to programming so could not figure out what could be done. All help/ suggestion/ recommendation is highly appreciated.Thank you.
Simple solution
array = [(randint(1, 100), randint(1, 100)) for i in range(10)]
Better solution
The following solution is more flexible and reusable.
from functools import partial
from random import randint
def randints(count, *randint_args):
ri = partial(randint, *randint_args)
return [(ri(), ri()) for _ in range(count)]
print(randints(10, 1, 100))
Requirement - "Here 1 number mean 2 dimensional number example (x,y) = (10,20) I want to get 10 random numbers (x,y)"
>>> from random import randint as r
>>> array = [ (r(1,100), r(1,100)) for i in xrange(10)]
from random import randint
r = []
N = 10
for x in range(N):
a = randint(5,15) # rand number between 5 and 15
b = randint(10,11) # rand number between 10 and 11
r.append((a,b))
# r <-- contains N tuples with random numbers
Why don't you just do:
from random import randint
randoms = []
for i in range(10):
randoms.append((randint(1,100),randint(1,100)))
Then randoms will be an array of 10 integers, randomly generated between 1 and 100 (inclusive).
To be quite clear: what is going on here is that you make an empty list called randoms. Then the for loop executes ten times, each time appending a new tuple of two random integers to the list randoms.
NumPy should do the job
np.random.randint(low=1, high=100, size=10)