how to get a list of 1000 random float numbers without dublicates and find their mean value in python?
import random
rnd_number=random.random()
def a():
l=[]
m=1
for i in range(1000):
l.append(rnd_number)
return l
for i in l:
m=m+i
return m//b
print (a())
i am probably wrong with returning l before the other operation but when the code works there are 1000 of the same float numbers on the screen
Hope this would help!
import numpy as np
import random
N=10
# number of digits you want after the .dot sign
# more digits .dot ensure mo duplication
Npts=1000
# number of random numbers
num=[]
# initialize the array
for m in range(1000):
nm=round(random.random(), N)
# local variable to take the random numbers
num.append(nm)
# append the random number nm to the original num array
print(num)
# printing the random numbers
# Let's check is there is a duplication or not
my_num=set(num)
if len(num)!=len(my_num):
print("Duplication in the array")
else:
print("NO duplication in the array")
# Calculating mean
avg=sum(num)/Npts
print(avg)
If you want to have distinct random numbers, you have to draw number on every loop iteration. To avoid duplicates you can use set, which stores unique values.
import random
def a():
mySet = set()
while len(mySet) < 1000:
mySet.add(random.random())
return mySet
print(a())
import random
def a():
s=0
m=0
l=[]
for i in range(1000):
rnd_number=random.random()
l.append(rnd_number)
for n in l:
m=m+n
m=m/len(l)
for k in l:
s=s+(k-m)**2
s=(s/len(l))**(1/2)
return l,m,s
print (a())
i did like this and got the right answers for both the mean and standart devaiation of 1000 random float numbers
(i checked it with 4 actually but i think it is gonna work for 1000 too)
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) ]
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.
I tried to create a function for generating a set number (numbersToChoose) of values between two other values (startFrom and stopAt) but for some reason the iterator (?) in the second for-loop (line 7), in this case a seems to be randomly generated even though I don't see any reason for that.
def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):
numbers = [(randrange(startFrom, stopAt))] # initialize empty list of numbers
for n in range(numbersToChoose-1): # choose random number from 1 to 49 a total of 7 times
x = randrange(startFrom, stopAt+1)
for a in numbers: # check for already existing elements in "numbers"
if x == numbers[a]: # if new random number already exists in "numbers" discard and run loop again
n -= 1 # decreases n by 1 so a new (hopefully not already existing) number can be generated
else: # generated numbers does not exist in "numbers" yet
numbers.append(x) # appends randomly chosen number to list "numbers"
return numbers # returns said list "numbers"
Any advice on how to deal with this is greatly appreciated.
Also please tell me if possible anything else bad in the code (just started python).
Your code to check if generated number is already in the list is wrong.
for a in numbers, in this loop, you are using numbers[a] while a is a member of list but not the index of the member.
use in to test if a number is in list:
from random import randrange
def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):
numbers = []
for n in range(numbersToChoose):
x = randrange(startFrom, stopAt+1)
if not x in numbers:
numbers.append(x)
else:
n -= 1
return numbers
or simply:
from random import sample
def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):
return sample(range(startFrom,stopAt+1),numbersToChoose)
one more question. I am a first year CS student who has to do this on paper, so I am not able to import any programs to solve the problem.
I have been asked to create a psuedo-random set of integers, and then to multiply the products of the integers using a function def product (n). I know this code is really wrong but I'm not really sure what to do at all! Here is what I have so far:
def product(n):
product = j*i
for j in range (20):
i=random.randrange(1,4,1)
print ("The set of numbers is", i)
You didn't specify the range for the integers, but I think this does what you want:
import random
def product(n):
lower_bound = 1
upper_bound = 10
result = 1
for i in range(n):
result *= random.randint(lower_bound, upper_bound)
return result
I would go with
import random
def product(n):
return reduce(lambda x,y:x*y,(random.randint(1,3) for i in xrange(n)))
Several things:
you can't really generate random numbers without importing or writing your own pseudorandom generator
look up reduce. It's probably the preferred method here.
if you can import the operator module, use operator.mul instead of lambda x,y:x*y
If n is the number of generated numbers:
import random
def product(n):
random_list = [random.randint(0,n) for r in xrange(n)]
return reduce(lambda x,y : x*y, random_list)
What do you want? Multiply Integers and display their products? See this :
def product(numberOfIntegers) :
finalResult = 1
for i in range(1,numberOfIntegers) :
randomNumber = random.randrange(1,4,1)
finalResult = finalResult * randomNumber
return finalResult
Let's say I need a 3-digit number, so it would be something like:
>>> random(3)
563
or
>>> random(5)
26748
>> random(2)
56
You can use either of random.randint or random.randrange. So to get a random 3-digit number:
from random import randint, randrange
randint(100, 999) # randint is inclusive at both ends
randrange(100, 1000) # randrange is exclusive at the stop
* Assuming you really meant three digits, rather than "up to three digits".
To use an arbitrary number of digits:
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)
Output:
33
124
5127
If you want it as a string (for example, a 10-digit phone number) you can use this:
n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
If you need a 3 digit number and want 001-099 to be valid numbers you should still use randrange/randint as it is quicker than alternatives. Just add the neccessary preceding zeros when converting to a string.
import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros = '{:03}'.format(num)
# using string's zfill
num_with_zeros = str(num).zfill(3)
Alternatively if you don't want to save the random number as an int you can just do it as a oneliner:
'{:03}'.format(random.randrange(1, 10**3))
python 3.6+ only oneliner:
f'{random.randrange(1, 10**3):03}'
Example outputs of the above are:
'026'
'255'
'512'
Implemented as a function that can support any length of digits not just 3:
import random
def n_len_rand(len_, floor=1):
top = 10**len_
if floor > top:
raise ValueError(f"Floor '{floor}' must be less than requested top '{top}'")
return f'{random.randrange(floor, top):0{len_}}'
Does 0 count as a possible first digit? If so, then you need random.randint(0,10**n-1). If not, random.randint(10**(n-1),10**n-1). And if zero is never allowed, then you'll have to explicitly reject numbers with a zero in them, or draw n random.randint(1,9) numbers.
Aside: it is interesting that randint(a,b) uses somewhat non-pythonic "indexing" to get a random number a <= n <= b. One might have expected it to work like range, and produce a random number a <= n < b. (Note the closed upper interval.)
Given the responses in the comments about randrange, note that these can be replaced with the cleaner random.randrange(0,10**n), random.randrange(10**(n-1),10**n) and random.randrange(1,10).
You could write yourself a little function to do what you want:
import random
def randomDigits(digits):
lower = 10**(digits-1)
upper = 10**digits - 1
return random.randint(lower, upper)
Basically, 10**(digits-1) gives you the smallest {digit}-digit number, and 10**digits - 1 gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.
import random
fixed_digits = 6
print(random.randrange(111111, 999999, fixed_digits))
out:
271533
You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:
import random
def generate_random_number(length):
return int(''.join([str(random.randint(0,10)) for _ in range(length)]))
I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)
import random
first = random.randint(1,9)
first = str(first)
n = 5
nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs)) :
first += str(nrs[i])
print str(first)
From the official documentation, does it not seem that the sample() method is appropriate for this purpose?
import random
def random_digits(n):
num = range(0, 10)
lst = random.sample(num, n)
print str(lst).strip('[]')
Output:
>>>random_digits(5)
2, 5, 1, 0, 4
I know it's an old question, but I see many solutions throughout the years. here is my suggestion for a function that creates an n digits random string with default 6.
from random import randint
def OTP(n=6):
n = 1 if n< 1 else n
return randint(int("1"*n), int("9"*n))
of course you can change "1"*n to whatever you want the start to be.