Generate a random number of len(10) containing digits only 0-1s - python

The question is self-explanatory.
I've tried this.
import random
number = "".join([str(random.randint(0,1)) for i in xrange(0,10)])
print number
Is there any in-built functionality for the same?

Either use:
''.join(random.choice('01') for _ in xrange(10))
Which avoids the int->str, or otherwise use randrange (to exclude a full bit set) with a range that's 2**10, then format as a binary string.
format(random.randrange(2**10), '010b')
Also, to avoid overflow, you can use getrandbits and specify 10 as the amount, eg:
format(random.getrandbits(10), '010b')

Choose a random int in the range 0 ti 1023 inclusive and format it in base 2 with a minimum width of 10 with leading 0s filled in.
format(random.randint(0,1023), '010b')

I’m going to throw in another solution that creates an actual (decimal) number containing only ones and zeros:
>>> import random, functools
>>> functools.reduce(lambda x, i: 10 * x + random.randrange(2), range(10), 0)
1011001010

OR, to skip the decimal-binary transition :
from random import randint
def repeat(n):
if(n<=0):
return ''
n -= 1
return str(randint(0,1))+repeat(n)
and at the end just call repeat(10) or whatever number of bits you want.

Related

How to convert a floating-point number to a fixed-width string?

I tried to find this question answered, but I haven't found anything related.
I have a variable that can be in a format like 50000.45 or in a format like 0.01.
I need to write this variable in a label that is 4 digits wide.
What is the best way to fit the label showing only the most significant digits?
To better explain, I would like to have for example:
for 50000.45: 50000
for 4786.847: 4786
for 354.5342: 354.5
for 11.43566: 11.43
and for 0.014556: 0.0145
Possibly without having to do:
if ... < variable < ...:
round(variable,xx)
for all cases.
In order to convert a number into a set number of digits, you can convert the number into only decimals (aka 0 <= n <= 1), then remove the last characters. You can do it like that:
from math import log10
number = 123.456789
n_digits = 4
log = int(log10(number) + 1)
number /= 10**log # convert the number into only decimals
number = int(number*10**n_digits)/10**n_digits # keep the n first digits
number *= 10**log # multiply the number back
Or a more compact form:
from math import log10
number = 123.456789
n_digits= 4
log = int(log10(number) + 1) - n_digits
number = int(number/10**log)*10**log
[Edit] You should use Python round() function in a simpler way:
number = round(number, n_digits-int(log10(number))-1)

Trunc a number and get removed value. Or cast to int?

I try to get the removed part of the math.trunc function.
Or a function supports this request.
import math
number = 1.9
newnumber, removed = math.trunc(number)
I need the number = 1 and also the removed 0.9
So basicly i need the integer and the removed float.
Obove example will not work :/
Any suggestions ?
You need to keep a handle on the truncated number, and subtract it from the original number:
import math
number = 1.9
truncated = math.trunc(number)
print(truncated, number - truncated)
If you use modf you can flip the order of your variables and get the result you want.
import math
number = 1.9
removed, newnumber = math.modf(number)
For a starting point, use modulus 1 get the removed part.
def truncate(n):
return math.trunc(n), n % 1
Then you want to consider how negative numbers are handled. Do they return a positive ‘removed’ value?
This method won’t work for negative numbers, instead you can subtract the truncates number from the original:
t = math.trunc(n)
return t, n - t

Generating a 10000 bit random sequence

Is there a more efficient way to generate a 10 kBit (10,000 bits) random binary sequence in Python than appending 0s and 1s in a loop?
If you want a random binary sequence then it's probably quickest just to generate a random integer in the appropriate range:
import random
s = random.randint(0, 2**10000 - 1)
After this it really depends on what you want to do with your binary sequence. You can query individual bits using bitwise operations:
s & (1 << x) # is bit x set?
or you could use a library like bitarray or bitstring if you want to make checking, setting slicing etc. easier:
from bitstring import BitArray
b = BitArray(uint=s, length=10000)
p, = b.find('0b000000')
if b[99]:
b[100] = False
...
The numpy package has a subpackage 'random' which can produce arrays of random numbers.
http://docs.scipy.org/doc/numpy/reference/routines.random.html
If you want an array of 'n' random bits, you can use
arr = numpy.random.randint(2, size=(n,))
... but depending on what you are doing with them, it may be more efficient to use e.g.
arr = numpy.random.randint(0x10000, size=(n,))
to get an array of 'n' numbers, each with 16 random bits; then
rstring = arr.astype(numpy.uint16).tostring()
turns that into a string of 2*n chars, containing the same random bits.
Here is a one liner:
import random
[random.randrange(2) for _ in range(10000)]

Python 3 os.urandom

Where can I find a complete tutorial or documentation on os.urandom? I need to get get a random int to choose a char from a string of 80 characters.
If you just need a random integer, you can use random.randint(a, b) from the random module.
If you need it for crypto purposes, use random.SystemRandom().randint(a, b), which makes use of os.urandom().
Example
import random
r = random.SystemRandom()
s = "some string"
print(r.choice(s)) # print random character from the string
print(s[r.randrange(len(s))]) # same
Might not exactly be on topic, but I want to help those coming here from a search engine. To convert os.urandom to an integer I'm using this:
import os
rand = int(int(str(os.urandom(4), encoding="UTF-8")).encode('hex'), 16)
# You can then 'cycle' it against the length.
rand_char = chars_list[rand % 80] # or maybe '% len(chars_list)'
Note: The range of the index here is up to that of a 4-byte integer. If you want more, change the 4 to a greater value.
The idea was taken from here: https://pythonadventures.wordpress.com/2013/10/04/generate-a-192-bit-random-number/

random Decimal in python

How do I get a random decimal.Decimal instance? It appears that the random module only returns floats which are a pita to convert to Decimals.
What's "a random decimal"? Decimals have arbitrary precision, so generating a number with as much randomness as you can hold in a Decimal would take the entire memory of your machine to store.
You have to know how many decimal digits of precision you want in your random number, at which point it's easy to just grab an random integer and divide it. For example if you want two digits above the point and two digits in the fraction (see randrange here):
decimal.Decimal(random.randrange(10000))/100
From the standard library reference :
To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error).
>>> import random, decimal
>>> decimal.Decimal(str(random.random()))
Decimal('0.467474014342')
Is this what you mean? It doesn't seem like a pita to me. You can scale it into whatever range and precision you want.
If you know how many digits you want after and before the comma, you can use:
>>> import decimal
>>> import random
>>> def gen_random_decimal(i,d):
... return decimal.Decimal('%d.%d' % (random.randint(0,i),random.randint(0,d)))
...
>>> gen_random_decimal(9999,999999) #4 digits before, 6 after
Decimal('4262.786648')
>>> gen_random_decimal(9999,999999)
Decimal('8623.79391')
>>> gen_random_decimal(9999,999999)
Decimal('7706.492775')
>>> gen_random_decimal(99999999999,999999999999) #11 digits before, 12 after
Decimal('35018421976.794013996282')
>>>
The random module has more to offer than "only returning floats", but anyway:
from random import random
from decimal import Decimal
randdecimal = lambda: Decimal("%f" % random.random())
Or did I miss something obvious in your question ?
decimal.Decimal(random.random() * MAX_VAL).quantize(decimal.Decimal('.01'))
Yet another way to make a random decimal.
import random
round(random.randint(1, 1000) * random.random(), 2)
On this example,
random.randint() generates random integer in specified range (inclusively),
random.random() generates random floating point number in the range (0.0, 1.0)
Finally, round() function will round the multiplication result of the abovementioned values multiplication (something long like 254.71921934351644) to the specified number after the decimal point (in our case we'd get 254.71)
import random
y = eval(input("Enter the value of y for the range of random number : "))
x = round(y*random.random(),2) #only for 2 round off
print(x)

Categories