Saturday, January 9, 2016

Hacker Rank Python Number List Solution with 3.x and 2.x

Problem Statement
An array A consist of N positive integers. List all the subarrays of array and replaced all the subarrayswith the maximum element present in the respective sub array.
View Problem at Hacker Rank
def numberList(a ,k): result = 0 big = -1 alen=0 #print(a) for val in a: a[alen]=int(a[alen]) alen=alen+1 #print (alen) k=int(k); for i in range(alen): if a[i] > k: result += (i-big)*(alen-i) big = i return result if __name__ == '__main__': t = int(input()) for _ in range(t): n,k = input().split() a = input().split() print(numberList(a ,k))
Python 2.x Solution

def numberList(a ,k):
    result = 0
    big = -1
    alen = len(a)
    for i in xrange(alen):
        if a[i] > k:
            result += (i-big)*(alen-i)
            _big = i
    return result
if __name__ == '__main__':
    t = int(raw_input())
    for _ in xrange(t):
        n,k = map(int, raw_input().split())
        a = map(int, raw_input().split())
        print numberList(a ,k)

Differences of Syntax

1. print on Python 3.x uses ()
2. xrange() of Python changed to range()
3. python 3.x renamed raw_input() to input() in 3.x

No comments:

Post a Comment