Sunday, July 16, 2017

Add Alternate Elements of 2-Dimensional Array- Practice Problem from HackerEarth and solution using python 2.7.6

Problem Statement:

You are given a two-dimensional 3*3 array starting from A [0][0]. You should add the alternate elements of the array and print its sum. It should print two different numbers the first being sum of A 0 0, A 0 2, A 1 1, A 2 0, A 2 2 and A 0 1, A 1 0, A 1 2, A 2 1.
Input Format
First and only line contains the value of array separated by single space.
Output Format
Output Format
First line should print sum of A 0 0, A 0 2, A 1 1, A 2 0, A 2 2
Second line should print sum of A 0 1, A 1 0, A 1 2, A 2 1

Programming using python 2.7.6:

Add all value which are on even index and add all value which are in odd index in list. 

num = map(int,raw_input().split())
OddSum =0
EvenSum =0
for i in range(len(num)):
    if (i+1)%2 !=0
        OddSum +=num[i]
    else:
        EvenSum +=num[i]
print OddSum
print EvenSum

No comments:

Post a Comment