i confused how to print every greatest per rows in array 2d python. my code so far walking properly but i can't get the right result. the program wants output like:
input:
2 - for how much array need to create
2 -> for how much size array(rows default = 3)
1 2 3
4 5 6
3
0 0 0
2 3 4
5 6 7
so far i get this right on input. and output:
in array 1 is : 2(represent row) -> (4+5+6) is greatest than (1+2+3)
in array 2 is : 3 (represent row) -> (5+6+7) is greatest
only (in array 1 is : 2 (and so on depending on the number of arrays or matrices created))` which will be displayed on the screen
i confused how to implementing that.
this my code:
import sys
print("Enter the number of arrays:")
K = int(input())
array = []
for i in range(K):
print("Enter the number of rows and columns you want:")
rows = int(input())
columns = 3
matrix = []
print("Start entering the rows:")
for j in range(rows):
matrix.append(list(map(int, input().split())))
array.append(matrix)
rows2 = len(matrix)
column2 = len(matrix[0])
idx = -1
maxi = -sys.maxsize
for r in range(0, rows2):
rowtotal=0
for s in range(0, column2):
rowtotal=rowtotal+int(matrix[r][s])
if (rowtotal > maxi):
maxi = rowtotal
idx = i
where should i put print to get the output and do i have to loop again?. and what is the syntax for displaying the output?. thanks.
You do not need array outside the for loop, since you just need to evaluate row-wise in matrix.
As user inputs the row, you can already just calculate the sum of the row using sum(). If that row's sum is bigger than the previously biggest sum (or sentinel value -999999), we set it as the biggest_row_sum and remember the biggest_row_index. At the end of the building of a full matrix, we just print out biggest_row_sum and biggest_row_index.
print("Enter the number of arrays:")
K = int(input())
for i in range(K):
print("Enter the number of rows you want:")
rows = int(input())
columns = 3
matrix = []
biggest_row_sum = -999999
biggest_row_index = -1
print("Start entering the rows:")
for j in range(rows):
this_row = list(map(int, input().split()))
matrix.append(this_row)
this_row_sum = sum(this_row)
if this_row_sum > biggest_row_sum:
biggest_row_index = j
biggest_row_sum = this_row_sum
print(matrix)
print("in array " + str(i+1) + " is : " + str(biggest_row_index+1))
Output:
Enter the number of arrays:
2
Enter the number of rows you want:
2
Using default number of columns = 3
Start entering the rows:
1 2 3
4 5 6
[[1, 2, 3], [4, 5, 6]]
in array 1 is : 2
Enter the number of rows you want:
3
Using default number of columns = 3
Start entering the rows:
0 0 0
2 3 4
5 6 7
[[0, 0, 0], [2, 3, 4], [5, 6, 7]]
in array 2 is : 3
Updated with OP's comment below
To only print out at the end of user input for all matrixes, we can simply store the final results into a list of tuples containing (matrix_no, matrix_greatest_sum) in answers, then print out at the end:
print("Enter the number of arrays:")
K = int(input())
answers = []
for i in range(K):
print("Enter the number of rows you want:")
rows = int(input())
columns = 3
matrix = []
biggest_row_sum = -999999
biggest_row_index = -1
print("Start entering the rows:")
for j in range(rows):
this_row = list(map(int, input().split()))
matrix.append(this_row)
this_row_sum = sum(this_row)
if this_row_sum > biggest_row_sum:
biggest_row_index = j
biggest_row_sum = this_row_sum
answers.append((i+1, biggest_row_index+1))
# Print final answer
for matrix_no, matrix_greatest_sum in answers:
print("in array " + str(matrix_no) + " is : " + str(matrix_greatest_sum))
import sys
print("Enter the number of arrays:")
K = int(input())
array = []
for i in range(K):
print("Enter the number of rows and columns you want:")
rows = int(input())
columns = 3
matrix = []
print("Start entering the rows:")
for j in range(rows):
matrix.append(list(map(int, input().split())))
array.append(matrix) # we also do not need this line
# we do not need to save matrix to array just for calculating the max row
# we can do it inside the loop using the matrix variable
greatest_row = 0 # initially let's say the greatest row is the first row
current_sum = 0 # initial sum 0
for j in range(rows):
a_row_sum = sum(matrix[j])
if a_row_sum > current_sum:
current_sum = a_row_sum
greatest_row = j
# everything is 0 based indexed
# so we add one while outputting the result
print("in array {0} is : {1}".format(i + 1, greatest_row + 1))
output
Enter the number of arrays:
2
Enter the number of rows and columns you want:
2
Start entering the rows:
1 2 3
4 5 6
in array 1 is : 2
Enter the number of rows and columns you want:
3
Start entering the rows:
0 0 0
2 3 4
5 6 7
in array 2 is : 3
Related
I need to make a square matrix of size M*M (which is an user input value) and after that, I should make a matrix out of a line of space-seperated numbers.
sizeOfMatrix = int(input())
matrix_input = input()
matrix = [[]*3]*3
for i in range(sizeOfMatrix):
for j in range (sizeOfMatrix):
# And this is where I got stuck
matrix[i][j].append()
You could try this - it's following original PO, but don't need two loops.
[Notes] it's based on the sample input as PO indicated - collect the matrix_input (numbers) in one line (as the Problem Title says).
size = int(input('Enter the size of this Square Matrix: ')) # eg. 3; R == C
numbers = list(map(int, input(f' Enter {size*size} numbers: ').split())) # all 3x3 numbers
matrix = [] # [[]*3]*3
for i in range(0, len(numbers), size):
matrix.append(numbers[i: i+size])
print(matrix)
Running interactively and Output:
Enter the size of this Square Matrix: 3
Enter 9 numbers: 1 2 3 4 5 6 7 8 9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Or goes with fancier one-line for this Square Matrix:
M = []
while not M or len(M) < len(M[0]):
M.append(list(map(int, input('Enter the number for a row: ').split())))
Running:
Enter the number for a row: 1 2 3
Enter the number for a row: 4 5 6
Enter the number for a row: 7 8 9
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
if you want square matrix make R=C
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
# For user input
for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
a.append(int(input()))
matrix.append(a)
For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()
This is how you create a Square Matrix.
sizeOfMatrix = int(input('Matrix Size: '))
mat = []
for i in range(sizeOfMatrix):
rows = list(map(int, input('Enter space separated values: ').split()))[:sizeOfMatrix]
mat.append(rows)
print(f'\nMatrix:')
for i in mat:
print(*i)
Matrix Size: 3
Enter space separated values: 2 1 6
Enter space separated values: 0 21 8
Enter space separated values: 6 9 7
Matrix:
2 1 6
0 21 8
6 9 7
so basically, I want to make an automatic matrix input and generate the output but the second part of the input shows up with the same output as the first one. is there any wrong logic behind my code? here's my code (im sorry for bad english):
#input menu 2 :
def prgmatriks2() :
ct = 2
for a in range(ct):
m = int (input("input row "+str (a)+": "))
n = int (input("input column"+str (a)+": "))
# initialization matriks
matrix = []
print("Matriks input: ")
#Input :
for x in range(ct) :
for i in range(m): #rows loop
a =[]
for j in range(n): #column loop
a.append(int(input()))
matrix.append(a)
# Print Matriks
for x in range(ct) :
for i in range(m):
for j in range(n):
print(matrix[i][j], end = " ")
print()
and for the output:
output
text version:
Pilihan menu(1-2):
2
input row 0: 2
input column0: 2
input row 1: 2
input column1: 2
Matriks input:
3
2
4
1
6
5
2
1
3 2
4 1
3 2
4 1
instead generate :
3 2
4 1
6 5
2 1
the program repeat the first output :
3 2
4 1
3 2
4 1
print(matrix[i][j], end=" ") replace here i with i+x*n.
So logic for printing Matrices will be like this code :
# Print Matrices
for x in range(ct):
for i in range(m):
for j in range(n):
print(matrix[x*n+i][j], end=" ")
print()
print()
print(matrix)
OUTPUT :
3 2
4 1
6 5
2 1
I am new to python and I submitted this code for a Hackerrank problem Arrays and Simple Queries, but for a large number of test cases the program is 'terminated due to timeout'. How can I make this more efficient?
I've pasted the main swap function below.
(Repeats M times)
temp = input()
temp = temp.split(" ")
i = int(temp[1])-1
j = int(temp[2])-1
rep = (i-1)+1
if(temp[0]=='1') :
rep = (i-1)+1
while(i<=j) :
count = i-1
ex1 = count
ex2 = i
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1-1
ex2 = ex2-1
i = i+1
else :
rep = (N-(j+1))
while(j>=i) :
count = j+1
ex1 = count
ex2 = j
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1+1
ex2 = ex2+1
j=j-1
Instead of using many loops, you can try simply concatenating slices:
def query(lst, t, start, end):
# Convert to proper zero-indexed index
start -= 1
if t == '1':
return lst[start:end] + lst[:start] + lst[end:]
elif t == '2':
return lst[:start] + lst[end:] + lst[start:end]
# Get the input however you want
N, M = map(int, input().split())
arr = list(map(int, input().split()))
assert len(arr) == N
for _ in range(M):
t, start, end = input().split()
arr = query(arr, t, int(start), int(end))
print(abs(arr[0] - arr[N - 1]))
print(*arr)
Input:
8 4
1 2 3 4 5 6 7 8
1 2 4
2 3 5
1 4 7
2 1 4
Output:
1
2 3 6 5 7 8 4 1
def sum_2_array(list1):
item = 10
numlist = list()
for i in list1:
num = list1.pop()
diff = item-num
if diff in list1:
return num, diff
print sum_2_array([2,3,5,8,7])
This function computes the minimum absolute diff between the elements of an array.The error is that it is returning just one value .
Can anayone please check and tell me where I am going wrong
Please run below code & see if it works. I have Used simple logic
def sum_2_array(list1):
item = 10
j = 0
for i in list1:
print "this is value of J = ", j
num = list1[j]
print "this is value of num = ", num
diff = item - num
print "this is vale of diff = ", diff
if diff in list1:
print num
print diff
j += 1
print sum_2_array([2, 3, 5, 8, 7])
Code you were running in that when it comes to third item in the list i.e 5. At the same time it pops out this item from the list. Because you are using list1.pop(). So it unable to find 5 in the list that's why you are getting only two values. Use code I gave & check if it works.
I got following result from that
this is value of J = 0
this is value of num = 2
this is vale of diff = 8
2
8
this is value of J = 1
this is value of num = 3
this is vale of diff = 7
3
7
this is value of J = 2
this is value of num = 5
this is vale of diff = 5
5
5
this is value of J = 3
this is value of num = 8
this is vale of diff = 2
8
2
this is value of J = 4
this is value of num = 7
this is vale of diff = 3
7
3
I have implemented the Kadane's algorithm for a 2D array in Python 2 with known boundaries, but I'm using the implementation for an online contest and the time it takes is more than the time given.
So that made me think if there is maybe another algorithm similar to Kadane's that has a smaller complexity, or if my code can be optimized in a way. My implementation works for any array with dimensions N x M and a subarray with dimensions maxRows x maxCols.
maxSumSubarray.py
import numpy as np
# returns the maximum sum for the given vector using kadane's algorithm, with
# maxRows maximum members in the sum
def kadane1DwithBounds(maxRows):
global temp
m = s = sum(temp[i] for i in xrange(maxRows))
k = 0
for i in xrange(1, N - maxRows + 1):
s -= temp[k]
s += temp[maxRows + i - 1]
k += 1
m = max(m, s)
return m
# prints the maximum "area" given by the values of an NxM array inside a
# subarray with dimensions maxRows x maxCols. temp holds the latest vector to be
# given to kadane1DwithBounds()
def kadane2DwithBounds(maxRows, maxCols):
global temp
for i in xrange(N):
temp[i] = sum(table[i][j] for j in xrange(maxCols))
m = kadane1DwithBounds(maxRows)
k = 0
for j in xrange(1, M - maxCols + 1):
for i in xrange(N):
temp[i] -= table[i][k]
temp[i] += table[i][maxCols + j - 1]
k += 1
m = max(m, kadane1DwithBounds(maxRows))
print m
line = map(int, raw_input().split())
N = line[0]
M = line[1]
maxRows = line[2]
maxCols = line[3]
table = []
temp = np.empty(N, dtype = int)
for _ in xrange(N):
table.append(map(int, raw_input().split()))
kadane2DwithBounds(maxRows, maxCols)
test.txt
4 8 2 3
1 1 2 3 3 1 1 1
2 2 2 2 2 2 2 2
3 3 3 1 1 3 3 4
0 0 1 1 3 2 2 1
Run with
python maxSumSubarray.py < test.txt
it gives
16
which is correct and is the following rectangle:
2 2 2
3 3 4
I've tried with other dimensions too and I'm pretty sure it works fine. Only problem is time/complexity. Any help would be appreciated! Thanks for your time.