Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below:
1 2 3
4 5 6
9 8 9
The left-to-right diagonal =1 + 5 + 9 = 15 . The right to left diagonal =3+5+9=17 . Their absolute difference is |15-17|=2.
Function description
Complete the diagonalDifference function in the editor below. It must return an integer representing the absolute diagonal difference.
diagonalDifference takes the following parameter:
arr: an array of integers .
Input Format
The first line contains a single integer,n , the number of rows and columns in the matrix arr.
Each of the next n lines describes a row,arr[i] , and consists of n space-separated integers arr[i][j] .
Sample Input
3
11 2 4
4 5 6
10 8 -12
Sample Output
15
My code:
def diagonalDifference(arr):
i = 0
j = 0
left = 0
right = 0
for x in range(arr+1):
left += arr[0 + i][0 + j]
right += arr[0 + i][n - j]
i += 1
j += 1
return abs(left - right)
Here's my code. I don't know what's wrong. Please help.
The Question is "Diagonal Difference" on Hackerrank.
EDIT: Second attempt
def diagonalDifference(arr):
left = 0
right = 0
for x in range(len(arr)):
left += arr[0+x][0+x]
right += arr[0+x][len(arr)-x]
return abs(left-right)
I get following error:
right += arr[0+x][len(arr)-x]
IndexError: list index out of range
You cannot access len(arr)-x - for x == 0 this is IndexError :
def diagonalDifference(arr):
left = 0
right = 0
for x in range(len(arr)):
left += arr[0+x][0+x]
right += arr[0+x][len(arr)-x]
return abs(left-right)
arr = [[1,2],[3,4]]
len_arr = len(arr) # len(arr) is 2, you index into arr[0][2-0] fox x==0
# but arr only has arr[0][0] and arr[0][1] for x == 0
You need to sum over:
k[0][0], k[1][1], k[2][2], ..., k[n-1][n-1] where n = len(k) for the forward diag
and
k[0][n-1-0], k[1][n-1-1], k[2][n-1-2], ..., k[n-1][n-1-(n-1)] for the backward diag
Codewise:
def diag (data, reverse=False):
ld = len(data)
if reverse:
return sum(data[i][ld-i-1] for i in range(ld))
else:
return sum(data[i][i] for i in range(ld))
k = [[0,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[0,22,23,24,25]]
print (diag(k)) # 64
print(diag(k,True)) # 44
def absDiagDiff(data):
return abs(diag(data)-diag(data,True))
print(absDiagDiff(k)) # 20
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
diag1=0
diag2=0
for x in range(int(len(arr))):
y=list(reversed(list(range(len(arr[x])))))
diag1+=arr[x][x]
diag2+=arr[x][y[x]]
return abs(diag1-diag2)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
If that can help, here's how I would of done it :
n = int(input())
array = []
total1 = 0
total2 = 0
index = 0
for i in range(n):
array = [[] for n in range(n)]
for arrays in array:
arrays += map(int,input().split())
if len(arrays) != n:
print(f"Error, need to be {n} by {n}")
if index == 0:
for arrays in array:
total1 += arrays[index]
index += 1
elif index == n:
for arrays in array:
total2 += arrays[index-1]
index -= 1
print(abs(total1-total2))
Related
This is a program to print a matrix whose sum of each row , column or diagonal elements are equal.
I have a working code but my program gives same output each time i run it. I need a program to print different matrix output for same input.
def matrix(n):
m = [[0 for x in range(n)]for y in range(n)]
i = n // 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal : ",int(n*(n*n+1)/2),"\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of the matrix : "))
matrix(n)
I am unsure whether this is what you are looking for, but one solution is to add a random number to each value of the matrix, as this doesn't break the property
a matrix whose sum of each row, column or diagonal elements are equal.
Here is how you could do it:
add = random.randint(0, 50)
m = [[v+add for v in row] for row in m]
Moreover, you can rotate and add two magic squares without loosing their property. Therefore, you can rotate the magic square you have and add it to the original. This can add some nonlinearity to the results.
def rotate(m): # 90 degrees counter clockwise
return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1, -1, -1)]
# add the matrix with its rotated version
m = list(map(lambda e: [sum(x) for x in zip(*e)], zip(m, rotate(m))))
I hope this helps!
I want to find the number of ways, a given integer X can be decomposed into sums of numbers which are N-th powers and every summand must be unique. For example if X = 10 and N=3, I can decompose this number like that:
10 = 2^3+1^3+1^3 ,but this is not a valid decomposition, because the number 1 appears twice. A valid decomposition for X = 10 and N = 2 would be 10 = 3^2+1^2, since no summand is repeating here.
Now I tried it to use recursion and created the following Python Code
st = set(range(1,int(pow(X,1/float(N))))) # generate set of unique numbers
print(str(ps(X, N, st)))
def ps(x, n, s):
res = 0
for c in s:
chk = x-pow(c,n) # test validity
if chk > 0:
ns = s-set([c])
res += ps(chk,n,ns)
elif chk == 0:
res += 1 # one result is found
else:
res += 0 # no valid result
return res
I used a set called st and then I recursively called the function ps that includes the base case "decomposition found" and "decomposition not found". Moreover it reduces a larger number to a smaller one by considering only the ways how to decompose a given number into only two summands.
Unfortunately, I get completely wrong results, e.g.
X = 100, N = 3: Outputs 0, Expected 1
X = 100, N = 2: Outputs 122, Expected 3
X = 10, N = 2: Outputs 0, Expected 1
My thoughts are correct, but I think the Problem is anywhere in the recursion. Does anybody see what I make wrong? Any help would be greatly appreciated.
Hint:
>>> X = 100
>>> N = 3
>>> int(pow(X, 1/float(N)))
4
>>> list(range(1, 4))
[1, 2, 3]
The output is indeed correct for the input you are feeding it.
The problem is line res += 1 # one result is found in conjuction with res += ps(chk,n,ns) will make the algorithm add twice.
E.g X = 10, N = 2: Outputs 0, Expected 1 because:
c=1:
10 - 1^2 > 0 -> res += ps(chk,n,ns)
c=3:
9 - 3^2 == 0 -> res += 1 # one result is found ... return res
So, in c=3 res=1 is returned to the c=1 call, which will
res += ps(chk,n,ns), and ps(chk,n,ns) = 1, making res = 2 and doubling the result expected.
E.g. X = 29, N = 2.
29 = 2^2 + 3^2 + 4^2
Solving from bottom to top (the algorithm flow):
c=4 -> res += 1... return res
c=3 -> res += ps() -> res += 1 -> res = 2 ... return res
c=2 -> res += ps() -> res += 2 -> res = 4 ... return res
But res is supposed to be 1.
Solution: You cannot add res to res. And you must remove the previous iterated objects to avoid path repetition. Check the solution below (with prints for better understanding):
def ps(x, n, s):
print(s)
print("")
return ps_aux(x, n, s, 0) # level
def ps_aux(x, n, s, level):
sum = 0
for idx, c in enumerate(s):
print("----> " * level + "C = {}".format(c))
chk = x - pow(c,n) # test validity
if chk > 0:
ns = s[idx + 1:]
sum += ps_aux(chk,n,ns, level + 1)
elif chk == 0:
print("OK!")
sum += 1 # one result is found
else:
sum += 0 # no valid result
return sum
Try with:
X=10 # 1 solution
N=2
st = list(range(1,int(pow(X,1/float(N))) + 1 )) # generate set of unique numbers
print(str(ps(X, N, st)))
X=25 # 2 solutions [3,4], [5]
N=2
st = list(range(1,int(pow(X,1/float(N))) + 1 )) # generate set of unique numbers
print(str(ps(X, N, st)))
I'm making Bubble Sort in Python, but for a reason I don't know of yet, a "List index out of range" error happens when and only when I run the code, with line 6 (if array[n] > array[n+1]:) causing the error.
Here's the code:
n = 1
b = len(array)
while b > 1:
while n < b:
if array[n] > array[n+1]:
array[n], array[n+1] = array[n+1], array[n]
n += 1
b -= 1
n = 1
return print(array)
array = [5,4,3,2,1]
bubblesort(array)```
Working code with minimum changes:
def bubblesort(array):
n = 0 # Updated
b = len(array) - 1 # Updated
while b > 0: # Updated
while n < b:
if array[n] > array[n+1]:
array[n], array[n+1] = array[n+1], array[n]
n += 1
b -= 1
n = 0 # Updated
print(array) # Updated
array = [5,4,3,2,1]
bubblesort(array)
I am trying to calculate the number of trailing zeros in a factorial.
def count(x):
zeros = 0
for i in range (2,x+1):
print(i)
if x > 0:
if i % 5 == 0:
print("count")
zeros +=1
else:
("False")
print(zeros)
count(30)
I think the number of trailing zeros is incorrect.
When using count(30), there are 7 trailing 0's in 30. However it is returning 6.
def count (x):
i = 5
zeros = 0
while x >= i:
zeros += x // i
i *= 5
return zeros
print(count(30))
Wikipedia has a short article on this specific topic, which says that this can be computed with a straight-forward summation that counts factors of 5.
def trailing_zeros_of_factorial(n):
assert n >= 0, n
zeros = 0
q = n
while q:
q //= 5
zeros += q
return zeros
# 32! = 263130836933693530167218012160000000
print(trailing_zeros_of_factorial(32)) # => 7
We would first count the number of multiples of 5 between 1 and n (which is X ), then the number of multiples of 25 ( ~s ), then 125, and so on.
To count how many multiples of mare in n, we can just divide n by m
def countFactZeros(num):
count = 0
i = 5
if num < 0:
return False
while num//i > 0:
count = count + num//i
i = i * 5
return count
countFactZeros(10) # output should be 2
countFactZeros(100) # output should be 24
Your algorithm has problem:
import math
def count_zeroes(x):
zeroes = 0
if x <= 0:
return zeroes
for i in range(5, x+1, 5):
for base in range(int(math.log(i, 5)), 0, -1):
if i % pow(5, base) == 0:
zeroes += base
break
return zeroes
I'm trying to solve a problem I was given for homework and really feel like I'm overthinking the algorithm and hoping someone here can push me in the right direction.
I'm going to be given an input txt file which will look like this :
1 // n number of graphs
4 // n number of vertices for graph 1
4 // n number of edges for graph 1
1 2 // edges given in pairs
2 3
2 4
3 4
And I'm supposed to use this data to crate n number of adjacency matrices representing the graphs. I then need to implement 3 methods on the data in the adjacency matrices:
findLongestPath() which will return the longest path in the graph
findShortestPath() which will return the shortest path in the graph
totalNumberPaths() which will return distinct number of paths in graph
I'm having difficulty implementing the first two parts fine. This is what I have so far:
def main():
numGraphs = input()
for x in xrange(0, numGraphs):
numVerts = input()
numEdges = input()
adjMat = [[0 for x in xrange(numVerts)] for x in xrange(numVerts)]
for x in xrange(0, numEdges):
edges = raw_input()
i, padding, j = edges.rpartition(" ")
i = int(i)
j = int(j)
i -= 1
j -= 1
adjMat[i][j] = 1
numPaths = [0 for x in xrange(numVerts)]
numPaths[0] = 1
longest_path = 1
shortest_path = numVerts
for i in xrange(0, numVerts):
current_path = 0
for j in xrange(0, numVerts):
if adjMat[i][j] == 1:
numPaths[j] += numPaths[i]
current_path += 1
if current_path > longest_path:
longest_path = current_path
if current_path < shortest_path:
shortest_path = current_path
print "shortest: %d, longest: %d, total %d" % (shortest_path, longest_path, numPaths[numVerts-1])
if __name__ == "__main__":
main()
Obviously when it hits a row of 0s the shortest_path updates to 0 and doesn't work. Plus it won't work when initialized to a 0. If I could get some pseudo code or maybe help with the longer or shorter method I'm sure I could write the opposite or maybe I'm totally off base.
Thanks for any input.
Edit:
So i figured it out. Here's my finished code in case anyone has a similar problem and needs help.
numGraphs = input()
for x in xrange(0, numGraphs):
numVerts = input()
numEdges = input()
adjMat = [[0 for x in xrange(numVerts)] for x in xrange(numVerts)]
for x in xrange(0, numEdges):
edges = raw_input()
i, padding, j = edges.rpartition(" ")
i = int(i)
j = int(j)
i -= 1
j -= 1
adjMat[i][j] = 1
numPaths = [0 for x in xrange(numVerts)]
numPaths[0] = 1
currentPath = [0 for x in xrange(numVerts)]
maxPath = 1
minPath = numVerts -1
for i in xrange(0, numVerts):
for j in xrange(1, numVerts):
if adjMat[i][j] == 1:
numPaths[j] += numPaths[i]
currentPath[j-i] += 1
if (currentPath[j-i] is not 0):
minPath = currentPath[j-i]
maxPath = max(currentPath)
print "shortest: %d, longest: %d, total %d" % (minPath, maxPath, numPaths[numVerts-1])
Figured it out. Here is my final solution.
numGraphs = input()
for x in xrange(0, numGraphs):
numVerts = input()
numEdges = input()
adjMat = [[0 for x in xrange(numVerts)] for x in xrange(numVerts)]
for x in xrange(0, numEdges):
edges = raw_input()
i, padding, j = edges.rpartition(" ")
i = int(i)
j = int(j)
i -= 1
j -= 1
adjMat[i][j] = 1
numPaths = [0 for x in xrange(numVerts)]
numPaths[0] = 1
currentPath = [0 for x in xrange(numVerts)]
maxPath = 1
minPath = numVerts -1
for i in xrange(0, numVerts):
for j in xrange(1, numVerts):
if adjMat[i][j] == 1:
numPaths[j] += numPaths[i]
currentPath[j-i] += 1
if (currentPath[j-i] is not 0):
minPath = currentPath[j-i]
maxPath = max(currentPath)
print "shortest: %d, longest: %d, total %d" % (minPath, maxPath, numPaths[numVerts-1])