This question already has answers here:
Convert binary (0|1) numpy to integer or binary-string?
(5 answers)
Closed 1 year ago.
I have task of converting an array with binary numbers into a decimal number.
My array code looks like this:
koo = np.random.randint(2, size=10)
print(koo)
Example of the output is:
[1 0 1 0 0 0 0 0 1 0]
And what I'm supposed to do is to turn it into a string (1010000010), in order to then turn it into a decimal number (642). What could be a way to do this?
For this task I have to create it with the array, I cannot use np.binary_repr()
I have tried solving it with the solution offered here, but when working on it the numbers would be wildly different from what's true (i.e.: 1011111010 was 381 according to the program, while in reality it's 762)
Anybody knows how to solve this problem? Thank you in advance!
At first, convert Numpy array to string by simply appending elements.
Then, using int(), recast the string using base of 2.
koo = np.random.randint(2, size=10)
print(koo)
binaryString = ""
for digit in koo:
binaryString += str(digit)
print(binaryString)
decimalString = int(binaryString, base=2)
print(decimalString)
An example run:
[0 0 1 0 1 0 0 0 0 0]
0010100000
160
you can use a list comprehension to enumerate the digits from end to beginning and then calculate the numbers in base ten, then sum. for example:
np.sum([digit * 2 ** i for i, digit in enumerate(koo[::-1])])
>>> koo = np.random.randint(2, size=10)
>>> koo
array([1, 1, 0, 0, 0, 0, 1, 1, 1, 1])
>>> binary_string = ''.join(koo.astype('str').tolist())
>>> binary_string
'1100001111'
>>> binary_val = int('1100001111', 2)
>>> binary_val
783
Related
I want to create a function which will convert the binary numbers in list array to the decimal numbers. For that I have reversed a list and used for loop to iterate the list items. However I am unable to get correct result. Can anyone help me where am I committing the mistake?
def binary_array_to_number(arr):
#arr = arr.reverse()
arr = arr [::-1]
new_num = 0
for item in arr:
for i in range(len(arr)):
new_num = new_num+item*(2**i)
print(new_num)
binary_array_to_number(arr= [0, 0, 0, 1])
Python has built-in conversion from binary to base-10 numbers using the int() constructor. By converting the array to a string representing the binary number, you can use int to convert it to decimal:
binary_arr = [0, 0, 0, 1]
binary_string = ''.join(str(digit) for digit in binary_arr) # this line simply converts the array to a string representing the binary number [0, 0, 0, 1] -> '0001'
decimal_number = int(binary_string, 2) # the 2 here represents the base for the number - base 2 means binary.
print(decimal_number) # prints '1'
You're not checking if the current bit is 1 or not, so you'll always generate 2**n - 1. Also, you've got two loops running instead of one, which will also lead to an incorrect result.
def binary_array_to_number(arr):
#arr = arr.reverse()
arr = arr [::-1]
new_num = 0
for i in range(len(arr)):
if arr[i]:
new_num += (2**i)
print(new_num)
binary_array_to_number(arr= [0, 1, 0, 1])
hi i have this code by which my output comes in binary.
b=np.array(np.zeros((1000,4)))
for i in range(1000):
n = "{0:04b}".format(int(Y[i]))
digits = [int(x) for x in str(n)]
b[i] = digits
this gives an output like this:
[0, 0, 0, 1]
please ignore the commas.. read it like [0 0 0 1]---binary number.
im trying to change it such that it gives integers like:
1
can anyone help me with this.. how to edit my code to bring out integers rather than binary numbers.?
Python's built-in int() will do this for you:
binary_num = ''.join(arr)
regular_num = int(binary_num, 2) # 2 is the base
This question already has answers here:
How can I multiply all items in a list together with Python?
(15 answers)
Closed 3 years ago.
I am trying to build a program which calculates the factorial of number num1. The question is: how can I multiply all the digits in i?
Here I have used a for loop for generating numbers backward from 5: 5,4,3,2,1,0
But is there any way I can multiply all the digits of the variable i?
for i in range(0,5,-1):
print(i)
The result was as follows:
5
4
3
2
1
Is there any way I can get the product of the numbers. I expect the output to be 120.
Your for-loop is wrong.
range(start, end, step): to get all numbers from 5 down to 1, you need range(5, 0, -1)
You can accumulate the result in a variable within the loop. Start with 1 since that's the multiplicative identity.
retval = 1
for i in range(5, 0, -1):
retval *= i
print(retval)
Note that you can easily compute the product of items in a list using reduce:
>> from functools import reduce
>> numbers = list(range(5,0,-1))
[5, 4, 3, 2, 1]
>> reduce((lambda x, y: x * y), numbers)
120
This question already has answers here:
Displaying python 2d list without commas, brackets, etc. and newline after every row
(6 answers)
Closed 6 years ago.
I am trying to create a matrix and then print it using python with the following expected output:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
The code follows:
matrix=[[]]
matrix = [[0 for x in range(4)] for x in range(4)]
print matrix
But the output comes as:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Please tell me why I'm getting this type of output and help with the correct one
What you are getting is the correct representation of a matrix. You have created a list that contains 4 lists, each list containing 4 '0's. If you want to print it differently then you have some options, but what you are printing is the representation of the above mentioned data structure.
for row in matrix:
print ' '.join(map(str,row))
this should work for you.
Try this:
matrix = "\n".join([" ".join(["0" for x in range(4)]) for x in range(4)])
print matrix
The thing is that you're trying to print a list object instead of a string. This way you join all of the numbers into 1 large string separated with spaces for columns and \n (line endings) for rows.
Keep in mind this method will not work for 2 digit numbers unless you pad the 1 digit with a leading zero or space. In order for it to work in all cases, I suggest using the Tabulate module.
Maybe something like this:
matrix=[[]]
matrix = [[0 for x in range(4)] for x in range(4)]
for a in matrix:
ln = ""
for i in a:
ln += str(i) + " "
print(ln)
for programming the Hamming cod in sage ( a compiler based on python) I need to create a matrix in which each column is a binary representation of a number
say Hamming(3) the matrix should look like this
0 0 0 1 1 1 1
0 1 1 0 0 1 1
1 0 1 0 1 0 1
which is the binary represenation of numbers from 1 to 7.
so what i did till now is to convert any given number to it's binary representation:
i made this little function it take two values n and r
and repserent n over r bits
binrep(n,r)
x=n
L=[]
LL=[]
while (n>0):
a=int(float(n%2))
L.append(a)
n=(n-a)/2
while (len(L)<r):
L.append(0)
#print(L)
LL=L[::-1]
return LL
so now i want to collect all the LL i got and make them in one big matrix like the one above
In addition to the other ones, an answer using numpy:
import numpy as np
# we're creating the binary representation for all numbers from 0 to N-1
N = 8
# for that, we need a 1xN matrix of all the numbers
a = np.arange(N, dtype=int)[np.newaxis,:]
# we also need a log2(N)x1 matrix, for the powers of 2 on the numbers.
# floor(log(N)) is the largest component that can make up any number up to N
l = int(np.log2(N))
b = np.arange(l, dtype=int)[::-1,np.newaxis]
# This step is a bit complicated, so I'll explain it below.
print np.array(a & 2**b > 0, dtype=int)
This prints:
[[0 0 0 0 1 1 1 1]
[0 0 1 1 0 0 1 1]
[0 1 0 1 0 1 0 1]]
The line
print np.array(a & 2**b > 0, dtype=int)
does a few things at once. I'll split it up into simpler steps:
# this takes our matrix b and creates a matrix containing the powers of 2
# up to 2^log2(N) == N
# (if N is a power of 2; otherwise, up to the next one below)
powers = 2**b
# now we calculate the bit-wise and (&) for each combination from a and b.
# because a has one row, and b as one column, numpy will automatically
# broadcast all values, so the resulting array has size log2(N)xN.
u = a & powers
# this is almost what we want, but has 4's in the first row,
# 2's in the second row and 1's in the last one.
# one method of getting 1's everywhere is to divide by powers:
print u / powers
# another way is to check where u > 0, which yields an array of bools,
# which we then convert to numbers by turning it into an array of ints.
print np.array(u > 0, dtype=int)
You just have to convert all those binary representations to lists of integers, collect them in a list of lists, and finally transpose that list of lists to get the desired output.
n = 3
binary = []
for i in range(1, 2**n):
s = binrep(i, n)
binary.append(map(int, s))
matrix = zip(*binary)
Or in one line: matrix = zip(*(map(int, binrep(i, n)) for i in range(1, 2**n)))
Result is
[(0, 0, 0, 1, 1, 1, 1),
(0, 1, 1, 0, 0, 1, 1),
(1, 0, 1, 0, 1, 0, 1)]
Also note that there are other ways to convert numbers to binary, e.g. using str.format:
def binrep(n,r):
return "{0:0{1}b}".format(n, r)
Like zoosuck mentioned, I would suggest the bin() function in replacement to your code. To print them in a sequence, assuming that the format is similar:
L = ['10101010', '10101010']
for i in L:
print ' '.join([j for j in i])
In a similar manner, you can append it to a list or a dictionary.