Skip to main content

Posts

Showing posts from November, 2015

Python program to find Matrix Diagonal Difference

Program Statement – Matrix Diagonal Difference You are given a square matrix of size  N × N . Can you calculate the absolute difference of the sums across the main diagonal and the secondary diagonal? https://www.hackerrank.com/challenges/diagonal-difference Program – Python 3 Version mat = [] nrow = int(input()) for i in range(nrow):   mat.extend(list(map(int,input().split()))) #keep extending the array #Main Diagonal Sum indx,pd_sum = 0,0 for i in range(nrow):   pd_sum += mat[indx]   indx += nrow + 1 #Secondary Diagonal Sum indx,sd_sum = nrow-1,0 for i in range(nrow):   sd_sum += mat[indx]   indx += nrow - 1 print(abs(pd_sum – sd_sum)) Input - 3 11 2 4 4 5 6 10 8 -12 Output - 15

Python List Comprehension

Program Statement – List Comprehension in Python https://www.hackerrank.com/challenges/list-comprehensions print a list of all possible coordinates on the three dimensional grid, such that at any point the sum X i  + Y i  + Z i  is not equal to N. Solution :- Python 3 Version xlist = range(int(input()) + 1) ylist = range(int(input()) + 1) zlist = range(int(input()) + 1) n = int(input()) complst = [[x,y,z] for x in xlist for y in ylist for z in zlist if x + y + z != n] print(complst) Input - 1 1 2 Output - [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]] References -  http://www.thelearningpoint.net/computer-science/learning-python-programming-and-data-structures/learning-python-programming-and-data-structures--tutorial-15--generators-and-list-comprehensions http://www.python-course.eu/list_comprehension.php

Python program to find Symmetric Difference between Sets

Problem statement -https://www.hackerrank.com/challenges/sets Program – Python 3 if int(input()) > 0 : x = set(list(map(int,input().split()))) if int(input()) > 0: y = set(list(map(int,input().split()))) z = sorted(x.symmetric_difference(y)) for i in z: print(i) sets – s ets are un ordered  collection of items. Every element is unique (no duplicates ) !! map() -> map will perform the particular action/function on a list of values.Here it converts to int. symmetric_difference () -> is function of sets which will return the elements which are  unique  in X and Y but not in both sets . Ex – x.symmetric_difference(y)