Convert Matrix to lower triangular without using numpy - python

My code had converted the matrix to lower Triangular Matrix but I need to eliminate the space after the last element in a row. My code is
matrix = [
[2, 9, 9],
[5, 6, 9],
[7, 6, 5]
]
n = len(matrix)
for i in range(n):
for j in range(n):
if(i<j):
print("0",end=" ")
else:
print(matrix[i][j],end=" ")
if(i!=n-1):
print()
Outut:
Expected Output Actual Output
2 0 0\n 2 0 0 \n
5 6 0\n 5 6 0 \n
7 6 5 7 6 5

Replace your inner loop with an expression that builds the row you want. You can combine the loop body into a single line, if you like.
for i in range(n):
row = ' '.join(str(matrix[i][j]) if i >= j else "0"
for j in range(n))
Note that this removes the need for your final if/print.

n=int(input())
matrix=[]
for k in range(n):
lst=list(map(int,input().split()))
matrix.append(lst)
for i in range(n):
for j in range(n):
if(i
else:
if(j==(n-1)):
print(matrix[i][j],end='')
else:
print(matrix[i][j],end=" ")
if(i!=n-1):
print()

n=int(input())
matrix=[]
for k in range(n):
lst=list(map(int,input().split()))
matrix.append(lst)
for i in range(n):
for j in range(n):
if(i<j):
if(j==(n-1)):
print("0",end='')
else:
print("0",end=" ")
else:
if(j==(n-1)):
print(matrix[i][j],end='')
else:
print(matrix[i][j],end=" ")
if(i!=n-1):
print()

Related

How can i print matrix[i][j] in python?

how can i print the matrix[i][j]?
from array import *
class Sudoku :
matrix = []
x = -1
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a)
except:
matrix.append(x)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])
error is :
print(matrix[i][j])
TypeError: 'int' object is not subscriptable
You can use this code if you want to complete the code with minimum number of lines but it sure is a bit complex.
m,n=input("Enter num of rows and columns:").split()
matrix=[[int(input()) for y in range(int(n))]for x in range(int(m))]
[[[print(matrix[i][j], end=" ") for j in range(int(n))] and print(" ") ]for i in range(int(m))]
The output looks like this:
Enter num of rows and columns: 3 3
1
2
3
4
5
6
7
8
9
1 2 3
4 5 6
7 8 9
from array import *
class Sudoku:
matrix = []
x = -1 # <--- 4
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a) # <--- 11
except: # <--- 12
matrix.append(x) # <--- 13
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j]) # <--- 16
Let's look at the code. If except at L12 is catched, x, which is -1 (L4) is appended. So at L16, when matrix[i] evaluates to -1, -1[j] is an error.
There's also another problem -- L11 will never be executed, because a is always a list, not int.
matrix = [] is declaring matrix to be a list. But you are thinking of the matrix as having i,j locations like in math.
You have two options:
Option1: Map the list to a matrix
If you have a 3x3 matrix you have 9 locations, so
matrix = [0, 1, 2, 3, 4, 5, 6, 7, 8] is equivalent to
0 1 2
matrix = 3 4 5
6 7 8
so if wanted to print out this matrix you have to do some math to access the elements
for i in range(3): # i = 0, 1, 2
for j in range(3): # j = 0, 1, 2
print(matrix[3*i + j], end=" ")
print("")
Option2: Make matrix be a nested list
have matrix becomes a list of row, and each row is a list of elements
matrix = []
x = -1
for i in range(0, 10):
row = []
for j in range(0, 10):
while True:
x = int(input(f"Enter matrix[{i}][{j}]} element: "))
if (isinstance(x, int)) == True :
row.append(x)
break;
matrix.append(row)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])

How do I fix this program that adds up all the integers in a list except the one that equals said sum?

I am trying to solve a problem where I have to enter several integers as an input (seperated by a whitespace), and print the integer that is the sum of all the OTHER integers.
So e.g.:
1 2 3 would give: 3, because 3 = 1 + 2
1 3 5 9 would give: 9, because 5 + 3 + 1 = 9
This is the code I currently have:
x = input().split(" ")
x = [int(c) for c in x]
y = 0
for i in range(len(x)-1):
y += x[i]
del x[i]
z = sum(x)
if y == z:
print(y)
break
else:
x.insert(i,y)
As the output, it just gives nothing no matter what.
Does anyone spot a mistake? I'd be ever greatful as I'm just a beginner who's got a lot to learn :)
(I renamed your strange name x to numbers.)
numbers = input().split()
numbers = [int(i) for i in numbers]
must_be = sum(numbers) / 2
if must_be in numbers:
print(int(must_be))
The explanation:
If there is an element s such that s = (sum of other elements),
then (sum of ALL elements) = s + (sum of other elements) = s + s = 2 * s.
So s = (sum of all elements) / 2.
If the last number entered is always the sum of previous numbers in the input sequence. Your problem lies with the x.insert(i, y) statement. For example take the following input sequence:
'1 2 5 8'
after the first pass through the for loop:
i = 0
z = 15
x = [1, 2, 5, 8]
y = 1
after the second pass through the for loop:
i = 1
z = 14
x = [1, 3, 5, 8]
y = 3
after the third pass through the for loop:
i = 2
z = 12
x = [1, 3, 8, 8]
y = 8
and the for loop completes without printing a result
If it's guaranteed that one of the integers will be the sum of all other integers, can you not just sort the input list and print the last element (assuming positive integers)?
x = input().split(" ")
x = [int(c) for c in x]
print(sorted(x)[-1])
I think this is a tricky question and can be done in quick way by using a trick
i.e create a dictionary with all the keys and store the sum as value like
{1: 18, 3: 18, 5: 18, 9: 18}
now iterate over dictionary and if val - key is in the dictionary then boom that's the number
a = [1, 3, 5, 9]
d = dict(zip(a,[sum(a)]*len(a)))
print([k for k,v in d.items() if d.get(v-k, False)])

How do i loop over a geometric sequence. i need to loop some function over 1, 2, 4, 8, 16

My code is
T=np.empty()
for N in range ("some gemetric numbers: 1,2,4,8,16):
T[N]= trap(f1,a,b,N)
This is what the program looks like
With generators:
def geom_generator(max_number):
i = 1
while i < max_number:
yield i
i = i*2
for i in geom_generator(max_number=1000): # just a random sample
# do something
print (i)
Output:
1
2
4
8
16
32
64
128
256
512
You can either loop over a fixed sequence:
for n in [1, 2, 4, 8, 16]:
# do stuff with n
or you can generate the sequence dynamically:
n = 1
while True:
# do stuff with n
n *= 2
Be careful as the 2nd example will loop forever unless you break on a particular condition.
a tricky approach:
from math import log
x = 1
coeff = 2
for i in range(0, int(log(1000, coeff)) + 1):
print(x)
x *= coeff

How to input element in 2d array

Like below C++ Code, how could I use Python to input elements in 2d array? Please, help in writing the same program in Python3.
int main()
{
int s = 3;
int a[s][s];
cout<<"Enter 9 Element in Square Matrix";
for(int i =0;i<s;i++)
{
for(int j =0; j<s;j++)
{
cin>>a[i][j];
}
}
cout<<"You Entered";
for(int i =0;i<s;i++)
{
for(int j =0; j<s;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
return 0;
}
Output:
Enter 9 Elements in Square Matrix
1
2
3
4
5
6
7
8
9
You Entered:
1 2 3
4 5 6
7 8 9
If there is a mistake in the program, please don't try to correct it.
Thank you.
Am gonna use list to store the 2D array here. There are many other structures you can use for storing a 2D array, but for basic needs, this will suffice.
n=int(input("Enter N for N x N matrix : ")) #3 here
l=[] #use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
for i in range(n):
row_list=[] #temporary list to store the row
for j in range(n):
row_list.append(int(input())) #add the input to row list
l.append(row_list) #add the row to the list
print(l)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
for i in range(n):
for j in range(n):
print(l[i][j], end=" ")
print() #new line
'''
1 2 3
4 5 6
7 8 9
'''
s = 3
a = [x[:] for x in [[0] * s] * s]
print("Enter 9 Element in Square Matrix")
for i in range(0, s):
for j in range(0, s):
a[i][j] = input()
print("You Entered")
for i in range(0, s):
line = ''
for j in range(0, s):
line += a[i][j] + ' '
print(line)
If you are not familiar with python, you should create a file called, for example, matrix.py and then add the following content:
matrix_size = 3
matrix = []
print("Enter {} Elements in Square Matrix:".format(matrix_size))
for i in range(0, matrix_size):
row = []
for j in range(0, matrix_size):
row.append(input())
matrix.append(row)
print("You entered:")
for i in range(0, matrix_size):
print(" ".join(matrix[i]))
After saving the file, you can execute this file this way:
python3 matrix.py
Here is a sample output:
[martin#M7 tmp]$ python3 matrix.py
Enter 3 Elements in Square Matrix:
1
2
3
1
2
3
7
5
4
You entered:
1 2 3
1 2 3
7 5 4
Say you want to create a 3*3 matrix:
Initialize the matrix as follows:
matrix = [x[:] for x in [[0] * 0] * 0]
Then take the matrix elements as input from the user:
for i in range(0,3):
row_list = []
for j in range(0,3):
row_list.append(int(input()))
matrix.append(row_list)

How to do this program without a counter?

lista = []
for i in range(5):
i = int(input("Digite um valor para o vetor: "))
lista = lista + [i]
x = int(input("Digite um valor para ver sua posição: "))
counter = 0
for j in range(5):
if lista[j] == x:
counter =+ 1
print(j)
if counter == 0:
print(x-1)
In the above program you put any 5 numbers in the list, then you look for the position of the number you inputted in the list, if the number inputted is not in the list it will print x-1.
For example List = [1, 2, 3, 4, 5]
x = 5 then it will print 5
x = 7 it will print 6
How do I make it print x-1 without counter? I tried using:
else:
print(x-1)
but then it will print x-1 5 times, I only want to print it once.
You don't need a counter at all, as you're only using it to check that there were no matches. You can use the for..else structure to check whether the loop completed without exiting from a break.
for j in range(5):
if lista[j] == x:
print(j)
break
else:
print(x-1)
If you want to print each index that matches your search query, I would move to a different approach:
>>> x = 1
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
1 1 1 1 1
0 1 2 3 4
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
2 2 1 10 1
2 4
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
2 2 1 10
2

Categories