How to print a matrix using Python [duplicate] - python

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)

Related

How to change a binary numpy array into an int? [duplicate]

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

Stuck converting binary to integers in python

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

Is there any way I can make this small piece of code shorter? (Python)

first = [0, 0, 0, 0]
second = [0, 0, 0, 0]
third = [0, 0, 0, 0]
fourth = [0, 0, 0, 0]
while 0 in first and 0 in second and 0 in third and 0 in fourth:
The lists at the top begin with each value holding 0. As the program progress' I plan to change the values in the list from 0 to other numbers. Effectively, I want to know if there is way to re-write the 'while' statement to check if 0 is in any list, WITHOUT the long chain of 'while not in __ and not in __' etc.
Cheers
while all(0 in i for i in [first,second,third,fourth]):
...
and If you want to check if any of the lists contain 0, do this:
while any(0 in i for i in [first,second,third,fourth]):
...
You can concatenate/combine all your lists and check truthyness:
while not all(first+second+third+fourth):
This checks for any False-y value and returns True if there is a 0.
while 0 in first + second + third + fourth:
# do stuff
You can also map
ls = [first, second, third, fourth]
func = lambda x: 0 in x
while all(map(func, ls)):
#dostuff
Use all if you want 0 in first and 0 in second and .... Use any if you want 0 in first or 0 in second etc
while not any(map(all, [first, second, ...])):

create a matrix of binary representation of numbers in python

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.

error in python: list assignment index out of range

I searched everywhere and even though there were a couple of questions and answers regarding this error I couldn't find a solution to fix my problem
I'm reading in from a file that contains letters and numbers and I'm populating my matrix depending on the values in that file.
ex: file
description of letters and numbers ...
table:
a b c d
a 1 2 5 6
b 5 6 3 4
c 3 2 1 4
d 2 4 6 8
Here's the code
matrix = [[0 for j in range(4)] for i in range(4)]
i = 0
j = 0
for line in file:
for a in line:
if is_number(a):
matrix[i][j] = int(a)
j+= 1
if matrix.count(0) < 2: #since matrix already populated with zeroes. it shouldn't have
#many per program specifications, that's why I use this
#conditional to increment i and reset j back to 0
i += 1
j = 0
file.close()
I don't understand why I keep getting that error.
I see two possible ways you could end up with an IndexError in your code.
The first problem occurs because of the way you are iterating through the file that you're reading. Your code:
for line in file:
for a in line:
if is_number(a):
# do stuff
Reads a line in the file into the variable line. Then, each character is stored in the variable a and you check if it is a number. If any of the integers you are reading in are greater than 9 you will see an IndexError since it will count each digit as a separate number, causing you to eventually run out of room in your pre-allocated array.
A possible fix would be to change the line:
for a in line:
to
for a in line.split()
which will split the line into a list of words (that is, a new entry for everything separated by whitespace). So, "6 12 4 5" will become [6,12,4,5], making it so that you don't count the 1 and 2 in 12 separately.
The second issue I see with your code is in the line:
if matrix.count(0) < 2:
If your input file ever contains a zero, it will cause this line to stay true for one iteration of the loop longer than you would like. A possible fix would be to change the line to:
if j == len(matrix[0]) - 1:
try something like this:
with open("data1.txt") as f:
next(f) #skip the first line
lis=[map(int,x.split()[1:]) for x in f] #use x.split()[1:] to remove the alphabet
print lis
output:
[[1, 2, 5, 6], [5, 6, 3, 4], [3, 2, 1, 4], [2, 4, 6, 8]]
If you know the input file already has the right matrix (line by line) layout you could use the following :
matrix = filter(lambda x: len(x)>0, [[int(a) for a in l.split() if is_number(a)] for l in file])
If you cannot expect anything from the input layout, you could try:
data = open("test").read()
l = filter(lambda x: is_number(x), data.replace("\n"," ").split())
width = int(math.sqrt(len(l)))
print [[int(l[i+width*j]) for i in range(width)] for j in range(width)]
You're constructing a 4x4 matrix in the first line of code, but your data is a 6x6 matrix. When you try to store an element at index 4 in row 0, you get an IndexError.
The problem is here:
matrix = [[0 for j in range(4)] for i in range(4)]
Your matrix is 6x6, but your code only compensates for a 4x4 matrix.

Categories

Resources