Solve in Python:
=====Function Descriptions=====
We have seen the applications of union, intersection, difference and symmetric difference operations, but these operations do not make any changes or mutations to the set.

We can use the following operations to create mutations to a set:

.update() or |=
Update the set by adding elements from an iterable/another set.

>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.update(R)
>>> print H
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])

.intersection_update() or &=
Update the set by keeping only the elements found in it and an iterable/another set.

>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.intersection_update(R)
>>> print H
set(['a', 'k'])

.difference_update() or -=
Update the set by removing elements found in an iterable/another set.

>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.difference_update(R)
>>> print H
set(['c', 'e', 'H', 'r'])

.symmetric_difference_update() or ^=
Update the set by only keeping the elements found in either set, but not in both.

>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.symmetric_difference_update(R)
>>> print H
set(['c', 'e', 'H', 'n', 'r', 'R'])

=====Problem Statement=====
You are given a set A and N number of other sets. These N number of sets have to perform some specific mutation operations on set A.

Your task is to execute those operations and print the sum of elements from set A.

=====Input Format=====
The first line contains the number of elements in set A.
The second line contains the space separated list of elements in set A.
The third line contains integer N, the number of other sets.
The next 2 * N lines are divided into N parts containing two lines each.
The first line of each part contains the space separated entries of the operation name and the length of the other set.
The second line of each part contains space separated list of elements in the other set.

=====Constraints=====
0<len(set(A))<1000
0<len(otherSets)<100
0<N<100

=====Output Format=====
Output the sum of elements in set A.

#!/usr/bin/env python3

def __starting_point():
    n = int(input())
    s = set(map(int, input().split()))
    num_cmds = int(input())

    for _i in range(num_cmds):
        cmd = list(input().strip().split(' '))
        if cmd[0] == 'intersection_update':
            get_set = set(map(int, input().split(' ')))
            s &= get_set
        elif cmd[0] == 'update':
            get_set = set(map(int, input().split(' ')))
            s |= get_set
        elif cmd[0] == 'difference_update':
            get_set = set(map(int, input().split(' ')))
            s -= get_set
        elif cmd[0] == 'symmetric_difference_update':
            get_set = set(map(int, input().split(' ')))
            s ^= get_set

    print((sum(s)))

__starting_point()


Solve in Python:
=====Function Descriptions=====
any()
This expression returns True if any element of the iterable is true. If the iterable is empty, it will return False.

Code
>>> any([1>0,1==0,1<0])
True
>>> any([1<0,2<1,3<2])
False

all()
This expression returns True if all of the elements of the iterable are true. If the iterable is empty, it will return True.

Code
>>> all(['a'<'b','b'<'c'])
True
>>> all(['a'<'b','c'<'b'])
False

=====Problem Statement=====
You are given a space separated list of integers. If all the integers are positive, then you need to check if any integer is a palindromic integer.

=====Input Format=====
The first line contains an integer N. N is the total number of integers in the list. The second line contains the space separated list of N integers.

=====Constraints=====
0<N<100

=====Output Format=====
Print True if all the conditions of the problem statement are satisfied. Otherwise, print False.

def __starting_point():
    num_cnt = int(input().strip())
    arr = list(input().strip().split())
    print(all([all([int(x) > 0 for x in arr]), any([x == x[::-1] for x in arr])]))
__starting_point()


Solve in Python:
=====Function Descriptions=====
collections.Counter()
A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.

Sample Code
>>> from collections import Counter
>>>
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
>>> print Counter(myList).items()
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>>
>>> print Counter(myList).keys()
[1, 2, 3, 4, 5]
>>>
>>> print Counter(myList).values()
[3, 4, 4, 2, 1]

=====Problem Statement=====
Raghu is a shoe shop owner. His shop has X number of shoes.
He has a list containing the size of each shoe he has in his shop.
There are N number of customers who are willing to pay x_i amount of money only if they get the shoe of their desired size. Your task is to compute how much money Raghu earned.

=====Input Format=====
The first line contains X, the number of shoes.
The second line contains the space separated list of all the shoe sizes in the shop.
The third line contains N, the number of customers.
The next N lines contain the space separated values of the shoe size desired by the customer and x_i, the price of the shoe.

=====Constraints=====
0<X<10^3
0<N≤10^3
0<x_i<100
2<shoe size<20

=====Output Format=====
Print the amount of money earned by Raghu.

x = int(input())
shoe_size = list(map(int,input().split()))
n = int(input())
sell = 0
for i in range(n):
    s, p = list(map(int,input().split()))
    if s in shoe_size:
        sell = sell + p
        shoe_size.remove(s)
print(sell)


Solve in Python:
=====Function Descriptions=====
collections.OrderedDict

An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.

Example
Code
>>> from collections import OrderedDict
>>>
>>> ordinary_dictionary = {}
>>> ordinary_dictionary['a'] = 1
>>> ordinary_dictionary['b'] = 2
>>> ordinary_dictionary['c'] = 3
>>> ordinary_dictionary['d'] = 4
>>> ordinary_dictionary['e'] = 5
>>>
>>> print ordinary_dictionary
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>>
>>> ordered_dictionary = OrderedDict()
>>> ordered_dictionary['a'] = 1
>>> ordered_dictionary['b'] = 2
>>> ordered_dictionary['c'] = 3
>>> ordered_dictionary['d'] = 4
>>> ordered_dictionary['e'] = 5
>>>
>>> print ordered_dictionary
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

=====Problem Statement=====
You are the manager of a supermarket.
You have a list of N items together with their prices that consumers bought on a particular day.
Your task is to print each item_name and net_price in order of its first occurrence.

item_name = Name of the item.
net_price = Quantity of the item sold multiplied by the price of each item.

=====Input Format=====
The first line contains the number of items, N.
The next N lines contains the item's name and price, separated by a space.

=====Constraints=====
0<N≤100

=====Output Format=====
Print the item_name and net_price in order of its first occurrence.

from collections import OrderedDict

def __starting_point():
    num = int(input().strip())
    history = OrderedDict()

    for _ in range(num):
        get_log = input().strip().split()
        good = " ".join(get_log[:-1])
        sold = int(get_log[-1])
        if good not in list(history.keys()):
            history[good] = sold
        else:
            history[good] += sold

    for key in list(history.keys()):
        print(("{} {}".format(key, history[key])))

__starting_point()


Solve in Python:
=====Function Descriptions=====
collections.deque()
A deque is a double-ended queue. It can be used to add or remove elements from both ends.

Deques support thread safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

Example
Code
>>> from collections import deque
>>> d = deque()
>>> d.append(1)
>>> print d
deque([1])
>>> d.appendleft(2)
>>> print d
deque([2, 1])
>>> d.clear()
>>> print d
deque([])
>>> d.extend('1')
>>> print d
deque(['1'])
>>> d.extendleft('234')
>>> print d
deque(['4', '3', '2', '1'])
>>> d.count('1')
1
>>> d.pop()
'1'
>>> print d
deque(['4', '3', '2'])
>>> d.popleft()
'4'
>>> print d
deque(['3', '2'])
>>> d.extend('7896')
>>> print d
deque(['3', '2', '7', '8', '9', '6'])
>>> d.remove('2')
>>> print d
deque(['3', '7', '8', '9', '6'])
>>> d.reverse()
>>> print d
deque(['6', '9', '8', '7', '3'])
>>> d.rotate(3)
>>> print d
deque(['8', '7', '3', '6', '9'])

=====Problem Statement=====
Perform append, pop, popleft and appendleft methods on an empty deque d.

=====Input Format=====
The first line contains an integer N, the number of operations.
The next N lines contains the space separated names of methods and their values.

=====Constraints=====
0<N≤100

=====Output Format=====
Print the space separated elements of deque d.

#!/usr/bin/env python3

from collections import deque

def __starting_point():
    num = int(input().strip())
    deq = deque()

    for _ in range(num):
        args = input().strip().split()

        if args[0] == 'append':
            deq.append(args[1])
        elif args[0] == 'appendleft':
            deq.appendleft(args[1])
        elif args[0] == 'pop':
            deq.pop()
        elif args[0] == 'popleft':
            deq.popleft()

    out = []
    for el in deq:
        out.append(el)

    print(" ".join(map(str, out)))
__starting_point()


Solve in Python:
=====Function Descriptions=====
dot

The dot tool returns the dot product of two arrays.

import numpy

A = numpy.array([ 1, 2 ])
B = numpy.array([ 3, 4 ])

print numpy.dot(A, B)       #Output : 11

cross

The cross tool returns the cross product of two arrays.

import numpy

A = numpy.array([ 1, 2 ])
B = numpy.array([ 3, 4 ])

print numpy.cross(A, B)     #Output : -2

=====Problem Statement=====
You are given two arrays A and B. Both have dimensions of NXN.
Your task is to compute their matrix product.

=====Input Format=====
The first line contains the integer N.
The next N lines contains N space separated integers of array A.
The following N lines contains N space separated integers of array B.

=====Output Format=====
Print the matrix multiplication of A and B.

import numpy as np

n = int(input().strip())
arr1 = np.array([[int(x) for x in input().strip().split()] for _ in range(n)])
arr2 = np.array([[int(x) for x in input().strip().split()] for _ in range(n)])

print(np.dot(arr1, arr2))


Solve in Python:
=====Function Descriptions=====
floor
The tool floor returns the floor of the input element-wise.
The floor of x is the largest integer i where i≤x.

import numpy

my_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
print numpy.floor(my_array)         #[ 1.  2.  3.  4.  5.  6.  7.  8.  9.]

ceil
The tool ceil returns the ceiling of the input element-wise.
The ceiling of x is the smallest integer i where i≥x.

import numpy

my_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
print numpy.ceil(my_array)          #[  2.   3.   4.   5.   6.   7.   8.   9.  10.]

rint
The rint tool rounds to the nearest integer of input element-wise.

import numpy

my_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
print numpy.rint(my_array)          #[  1.   2.   3.   4.   6.   7.   8.   9.  10.]

=====Problem Statement=====
You are given a 1-D array, A. Your task is to print the floor, ceil and rint of all the elements of A.

=====Input Format=====
A single line of input containing the space separated elements of array A.

=====Output Format=====
On the first line, print the floor of A.
On the second line, print the ceil of A.
On the third line, print the rint of A.

import numpy
np_ar = numpy.array(list(map(float,input().split())),float)
print((numpy.floor(np_ar)))
print((numpy.ceil(np_ar)))
print((numpy.rint(np_ar)))


Solve in Python:
=====Function Descriptions=====
group()

A group() expression returns one or more subgroups of the match.
Code

>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.group(0)       # The entire match
'username@hackerrank.com'
>>> m.group(1)       # The first parenthesized subgroup.
'username'
>>> m.group(2)       # The second parenthesized subgroup.
'hackerrank'
>>> m.group(3)       # The third parenthesized subgroup.
'com'
>>> m.group(1,2,3)   # Multiple arguments give us a tuple.
('username', 'hackerrank', 'com')

groups()

A groups() expression returns a tuple containing all the subgroups of the match.
Code

>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.groups()
('username', 'hackerrank', 'com')

groupdict()

A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
Code

>>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','myname@hackerrank.com')
>>> m.groupdict()
{'website': 'hackerrank', 'user': 'myname', 'extension': 'com'}

=====Problem Statement=====
You are given a string S.
Your task is to find the first occurrence of an alphanumeric character in (read from left to right) that has consecutive repetitions.

=====Input Format=====
A single line of input containing the string S.

=====Constraints=====
0<len(S)<100

=====Output Format=====
Print the first occurrence of the repeating character. If there are no repeating characters, print -1.

#!/usr/bin/env python3

import re

def __starting_point():
    string = input()

    match = re.search(r'([a-zA-Z0-9])\1+', string)

    print((match.group(1) if match else -1))

__starting_point()


Solve in Python:
=====Function Descriptions=====
identity

The identity tool returns an identity array. An identity array is a square matrix with all the main diagonal elements as 1 and the rest as 0. The default type of elements is float.

import numpy
print numpy.identity(3) #3 is for  dimension 3 X 3

#Output
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]

eye

The eye tool returns a 2-D array with 1's as the diagonal and 0's elsewhere. The diagonal can be main, upper or lower depending on the optional parameter k. A positive k is for the upper diagonal, a negative k is for the lower, and a 0 k (default) is for the main diagonal.

import numpy
print numpy.eye(8, 7, k = 1)    # 8 X 7 Dimensional array with first upper diagonal 1.

#Output
[[ 0.  1.  0.  0.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  1.  0.  0.]
 [ 0.  0.  0.  0.  0.  1.  0.]
 [ 0.  0.  0.  0.  0.  0.  1.]
 [ 0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.]]

print numpy.eye(8, 7, k = -2)   # 8 X 7 Dimensional array with second lower diagonal 1.

=====Problem Statement=====
Your task is to print an array of size NXM with its main diagonal elements as 1's and 0's everywhere else.

=====Input Format=====
A single line containing the space separated values of N and M.
N denotes the rows.
M denotes the columns.

=====Output Format=====
Print the desired NXM array.

import numpy
n,m = list(map(int,input().split()))
print((numpy.eye(n,m,k=0)))


Solve in Python:
=====Function Descriptions=====
inner

The inner tool returns the inner product of two arrays.

import numpy

A = numpy.array([0, 1])
B = numpy.array([3, 4])

print numpy.inner(A, B)     #Output : 4

outer

The outer tool returns the outer product of two arrays.

import numpy

A = numpy.array([0, 1])
B = numpy.array([3, 4])

print numpy.outer(A, B)     #Output : [[0 0]
                            #          [3 4]]

=====Problem Statement=====
You are given two arrays: A and B.
Your task is to compute their inner and outer product.

=====Input Format=====
The first line contains the space separated elements of array A.
The second line contains the space separated elements of array B.

=====Output Format=====
First, print the inner product.
Second, print the outer product.

import numpy as np

arr1 = np.array(list(map(int, input().strip().split())))
arr2 = np.array(list(map(int, input().strip().split())))

print((np.inner(arr1, arr2)))
print((np.outer(arr1, arr2)))


Solve in Python:
=====Function Descriptions=====
input()
In Python 2, the expression input() is equivalent to eval(raw _input(prompt)).

Code
>>> input()
1+2
3
>>> company = 'HackerRank'
>>> website = 'www.hackerrank.com'
>>> input()
'The company name: '+company+' and website: '+website
'The company name: HackerRank and website: www.hackerrank.com'

=====Problem Statement=====
You are given a polynomial P of a single indeterminate (or variable), x. You are also given the values of x and k. Your task is to verify if P(x) = k.

=====Output Format=====
Print True if P(x) = k. Otherwise, print False.

#!/usr/bin/env python3

def __starting_point():
    x, k = map(int, input().strip().split())
    string = input().strip()

    if eval(string) == k:
        print(True)
    else:
        print(False)
__starting_point()


Solve in Python:
=====Function Descriptions=====
itertools.combinations(iterable, r)
This tool returns the r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Sample Code

>>> from itertools import combinations
>>>
>>> print list(combinations('12345',2))
[('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]
>>>
>>> A = [1,1,3,3,3]
>>> print list(combinations(A,4))
[(1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 3, 3, 3), (1, 3, 3, 3)]

=====Problem Statement=====
You are given a string S.
Your task is to print all possible combinations, up to size k, of the string in lexicographic sorted order.

=====Constraints=====
0<k≤len(S)

=====Input Format=====
A single line containing the string S and integer value k separated by a space.

=====Output Format=====
Print the different combinations of string S on separate lines.

from itertools import *
s,n = input().split()
n = int(n) + 1
s = sorted(s)
for i in range(1,n):
    for j in combinations(s,i):
        print((''.join(j)))


Solve in Python:
=====Function Descriptions=====
itertools.combinations_with_replacement(iterable, r)
This tool returns

length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Sample Code

>>> from itertools import combinations_with_replacement
>>>
>>> print list(combinations_with_replacement('12345',2))
[('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '2'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '3'), ('3', '4'), ('3', '5'), ('4', '4'), ('4', '5'), ('5', '5')]
>>>
>>> A = [1,1,3,3,3]
>>> print list(combinations(A,2))
[(1, 1), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (3, 3), (3, 3), (3, 3)]

=====Problem Statement=====
You are given a string S.
Your task is to print all possible size k replacement combinations of the string in lexicographic sorted order.

=====Input Format=====
A single line containing the string S and integer value k separated by a space.

=====Constraints=====
0<k≤len(S)
The string contains only UPPERCASE characters.

=====Output Format=====
Print the combinations with their replacements of string S on separate lines.

#!/usr/bin/env python3

from itertools import combinations_with_replacement

def __starting_point():
    in_data = list(input().strip().split(' '))

    for el in combinations_with_replacement(sorted(in_data[0]), int(in_data[1])):
        print("".join(el))
__starting_point()


Solve in Python:
=====Function Descriptions=====
itertools.permutations(iterable[, r])

This tool returns successive rlength permutations of elements in an iterable.
If r is not specified or is None, then r defaults to the length of the iterable, and all possible full length permutations are generated.
Permutations are printed in a lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be produced in a sorted order.

Sample Code
>>> from itertools import permutations
>>> print permutations(['1','2','3'])
<itertools.permutations object at 0x02A45210>
>>>
>>> print list(permutations(['1','2','3']))
[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
>>>
>>> print list(permutations(['1','2','3'],2))
[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]
>>>
>>> print list(permutations('abc',3))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

=====Problem Statement=====
You are given a string S.
Your task is to print all possible permutations of size k of the string in lexicographic sorted order.

=====Input Format=====
A single line containing the space separated string S and the integer value k.

=====Output Format=====
Print the permutations of the string S on separate lines.

#!/usr/bin/env python3

from itertools import permutations

def __starting_point():
    in_data = list(input().strip().split(' '))

    for el in permutations(sorted(in_data[0]), int(in_data[1])):
        print("".join(el))
__starting_point()


Solve in Python:
=====Function Descriptions=====
itertools.product()

This tool computes the cartesian product of input iterables.
It is equivalent to nested for-loops.
For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

Sample Code

>>> from itertools import product
>>>
>>> print list(product([1,2,3],repeat = 2))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
>>>
>>> print list(product([1,2,3],[3,4]))
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
>>>
>>> A = [[1,2,3],[3,4,5]]
>>> print list(product(*A))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)]
>>>
>>> B = [[1,2,3],[3,4,5],[7,8]]
>>> print list(product(*B))
[(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

=====Problem Statement=====
You are given a two lists A and B. Your task is to compute their cartesian product AXB.
Example
A = [1, 2]
B = [3, 4]

AxB = [(1, 3), (1, 4), (2, 3), (2, 4)]
Note: A and B are sorted lists, and the cartesian product's tuples should be output in sorted order.

=====Input Format=====
The first line contains the space separated elements of list A.
The second line contains the space separated elements of list B.
Both lists have no duplicate integer elements.

=====Constraints=====
0<A<30
0<B<30

=====Output Format=====
Output the space separated tuples of the cartesian product.

#!/usr/bin/env python3

from itertools import product

def __starting_point():
    arr1 = list(map(int, input().strip().split(' ')))
    arr2 = list(map(int, input().strip().split(' ')))

    for el in product(arr1, arr2):
        print("{} ".format(el), end='')

__starting_point()


Solve in Python:
=====Function Descriptions=====
mean

The mean tool computes the arithmetic mean along the specified axis.

import numpy

my_array = numpy.array([ [1, 2], [3, 4] ])

print numpy.mean(my_array, axis = 0)        #Output : [ 2.  3.]
print numpy.mean(my_array, axis = 1)        #Output : [ 1.5  3.5]
print numpy.mean(my_array, axis = None)     #Output : 2.5
print numpy.mean(my_array)                  #Output : 2.5

By default, the axis is None. Therefore, it computes the mean of the flattened array.

var

The var tool computes the arithmetic variance along the specified axis.

import numpy

my_array = numpy.array([ [1, 2], [3, 4] ])

print numpy.var(my_array, axis = 0)         #Output : [ 1.  1.]
print numpy.var(my_array, axis = 1)         #Output : [ 0.25  0.25]
print numpy.var(my_array, axis = None)      #Output : 1.25
print numpy.var(my_array)                   #Output : 1.25

By default, the axis is None. Therefore, it computes the variance of the flattened array.

std

The std tool computes the arithmetic standard deviation along the specified axis.

import numpy

my_array = numpy.array([ [1, 2], [3, 4] ])

print numpy.std(my_array, axis = 0)         #Output : [ 1.  1.]
print numpy.std(my_array, axis = 1)         #Output : [ 0.5  0.5]
print numpy.std(my_array, axis = None)      #Output : 1.118033988749895
print numpy.std(my_array)                   #Output : 1.118033988749895

By default, the axis is None. Therefore, it computes the standard deviation of the flattened array.

=====Problem Statement=====
You are given a 2-D array of size NXM.
Your task is to find:
The mean along axis 1
The var along axis 0
The std along axis None

=====Input Format=====
The first line contains the space separated values of N and M.
The next N lines contains M space separated integers.

=====Output Format=====
First, print the mean.
Second, print the var.
Third, print the std.

import numpy as np

n, m = [int(x) for x in input().strip().split()]
array = np.array([[int(x) for x in input().strip().split()] for _ in range(n)], dtype = float)
print(np.mean(array, axis = 1))
print(np.var(array, axis = 0))
print(np.std(array))


Solve in Python:
=====Function Descriptions=====
poly

The poly tool returns the coefficients of a polynomial with the given sequence of roots.

print numpy.poly([-1, 1, 1, 10])        #Output : [  1 -11   9  11 -10]

roots

The roots tool returns the roots of a polynomial with the given coefficients.

print numpy.roots([1, 0, -1])           #Output : [-1.  1.]

polyint

The polyint tool returns an antiderivative (indefinite integral) of a polynomial.

print numpy.polyint([1, 1, 1])          #Output : [ 0.33333333  0.5         1.          0.        ]

polyder

The polyder tool returns the derivative of the specified order of a polynomial.

print numpy.polyder([1, 1, 1, 1])       #Output : [3 2 1]

polyval

The polyval tool evaluates the polynomial at specific value.

print numpy.polyval([1, -2, 0, 2], 4)   #Output : 34

polyfit

The polyfit tool fits a polynomial of a specified order to a set of data using a least-squares approach.

print numpy.polyfit([0,1,-1, 2, -2], [0,1,1, 4, 4], 2)
#Output : [  1.00000000e+00   0.00000000e+00  -3.97205465e-16]

The functions polyadd, polysub, polymul, and polydiv also handle proper addition, subtraction, multiplication, and division of polynomial coefficients, respectively.

=====Problem Statement=====
You are given the coefficients of a polynomial P.
Your task is to find the value of P at point x.

=====Input Format=====
The first line contains the space separated value of the coefficients in P.
The second line contains the value of x.

=====Output Format=====
Print the desired value.

import numpy
p = numpy.array(list(map(float,input().split())),float)
x = float(input())
print((numpy.polyval(p,x)))


Solve in Python:
=====Function Descriptions=====
re.findall()

The expression re.findall() returns all the non-overlapping matches of patterns in a string as a list of strings.
Code

>>> import re
>>> re.findall(r'\w','http://www.hackerrank.com/')
['h', 't', 't', 'p', 'w', 'w', 'w', 'h', 'a', 'c', 'k', 'e', 'r', 'r', 'a', 'n', 'k', 'c', 'o', 'm']

re.finditer()

The expression re.finditer() returns an iterator yielding MatchObject instances over all non-overlapping matches for the re pattern in the string.
Code

>>> import re
>>> re.finditer(r'\w','http://www.hackerrank.com/')
<callable-iterator object at 0x0266C790>
>>> map(lambda x: x.group(),re.finditer(r'\w','http://www.hackerrank.com/'))
['h', 't', 't', 'p', 'w', 'w', 'w', 'h', 'a', 'c', 'k', 'e', 'r', 'r', 'a', 'n', 'k', 'c', 'o', 'm']

=====Problem Statement=====
You are given a string S. It consists of alphanumeric characters, spaces and symbols(+,-).
Your task is to find all the substrings of S that contains 2 or more vowels.
Also, these substrings must lie in between 2 consonants and should contain vowels only.

Note :
Vowels are defined as: AEIOU and aeiou.
Consonants are defined as: QWRTYPSDFGHJKLZXCVBNM and qwrtypsdfghjklzxcvbnm.

=====Input Format=====
A single line of input containing string S.

=====Constraints=====
0<len(S)<100

=====Output Format=====
Print the matched substrings in their order of occurrence on separate lines.
If no match is found, print -1.

import re
s = input()
result = re.findall(r'(?<=[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm])([AEIOUaeiou]{2,})(?=[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm])',s)
if result:
    for i in result:
        print(i)
else:
    print((-1))


Solve in Python:
=====Function Descriptions=====
shape

The shape tool gives a tuple of array dimensions and can be used to change the dimensions of an array.

(a). Using shape to get array dimensions

import numpy

my__1D_array = numpy.array([1, 2, 3, 4, 5])
print my_1D_array.shape     #(5,) -> 5 rows and 0 columns

my__2D_array = numpy.array([[1, 2],[3, 4],[6,5]])
print my_2D_array.shape     #(3, 2) -> 3 rows and 2 columns

(b). Using shape to change array dimensions

import numpy

change_array = numpy.array([1,2,3,4,5,6])
change_array.shape = (3, 2)
print change_array

#Output
[[1 2]
[3 4]
[5 6]]

reshape

The reshape tool gives a new shape to an array without changing its data. It creates a new array and does not modify the original array itself.

import numpy

my_array = numpy.array([1,2,3,4,5,6])
print numpy.reshape(my_array,(3,2))

#Output
[[1 2]
[3 4]
[5 6]]

=====Problem Statement=====
You are given a space separated list of nine integers. Your task is to convert this list into a 3X3 NumPy array.

=====Input Format=====
A single line of input containing 9 space separated integers.

=====Output Format=====
Print the 3X3 NumPy array.

import numpy
ar = list(map(int,input().split()))
np_ar = numpy.array(ar)
print((numpy.reshape(np_ar,(3,3))))


Solve in Python:
=====Function Descriptions=====
start() & end()

These expressions return the indices of the start and end of the substring matched by the group.

Code

>>> import re
>>> m = re.search(r'\d+','1234')
>>> m.end()
4
>>> m.start()
0

=====Problem Statement=====
You are given a string S.
Your task is to find the indices of the start and end of string k in S.

=====Input Format=====
The first line contains the string S.
The second line contains the string k.

=====Output Format=====
Print the tuple in this format: (start_index, end_index)

If no match is found, print (-1, -1).

import re
s = input().strip()
k = input().strip()
s_len = len(s)
found_flag = False
for i in range(s_len):
    match_result = re.match(k,s[i:])
    if match_result:
        start_index = i+match_result.start()
        end_index = i+match_result.end()-1
        print((start_index,end_index))
        found_flag = True
if found_flag == False:
    print('(-1, -1)')


Solve in Python:
=====Function Descriptions=====
sum

The sum tool returns the sum of array elements over a given axis.

import numpy

my_array = numpy.array([ [1, 2], [3, 4] ])

print numpy.sum(my_array, axis = 0)         #Output : [4 6]
print numpy.sum(my_array, axis = 1)         #Output : [3 7]
print numpy.sum(my_array, axis = None)      #Output : 10
print numpy.sum(my_array)                   #Output : 10

By default, the axis value is None. Therefore, it performs a sum over all the dimensions of the input array.

prod

The prod tool returns the product of array elements over a given axis.

import numpy

my_array = numpy.array([ [1, 2], [3, 4] ])

print numpy.prod(my_array, axis = 0)            #Output : [3 8]
print numpy.prod(my_array, axis = 1)            #Output : [ 2 12]
print numpy.prod(my_array, axis = None)         #Output : 24
print numpy.prod(my_array)                      #Output : 24

By default, the axis value is None. Therefore, it performs the product over all the dimensions of the input array.

=====Problem Statement=====
ou are given a 2-D array with dimensions NXM.
Your task is to perform the sum tool over axis 0 and then find the product of that result.

=====Output Format=====
Compute the sum along axis 0. Then, print the product of that sum.

import numpy
n,m=list(map(int,input().split()))
ar = []
for i in range(n):
    tmp = list(map(int,input().split()))
    ar.append(tmp)
np_ar = numpy.array(ar)
s = numpy.sum(np_ar,axis=0)
print((numpy.prod(s)))


Solve in Python:
=====Function Descriptions=====
zeros

The zeros tool returns a new array with a given shape and type filled with 0's.

import numpy

print numpy.zeros((1,2))                    #Default type is float
#Output : [[ 0.  0.]]

print numpy.zeros((1,2), dtype = numpy.int) #Type changes to int
#Output : [[0 0]]

ones

The ones tool returns a new array with a given shape and type filled with 1's.

import numpy

print numpy.ones((1,2))                    #Default type is float
#Output : [[ 1.  1.]]

print numpy.ones((1,2), dtype = numpy.int) #Type changes to int
#Output : [[1 1]]

=====Problem Statement=====
You are given the shape of the array in the form of space-separated integers, each integer representing the size of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones.

=====Input Format=====
A single line containing the space-separated integers.

=====Constraints=====
1≤each integer≤3

=====Output Format=====
First, print the array using the numpy.zeros tool and then print the array with the numpy.ones tool.

import numpy
dims = [int(x) for x in input().strip().split()]

print(numpy.zeros(tuple(dims), dtype = numpy.int))
print(numpy.ones(tuple(dims), dtype = numpy.int))


Solve in Python:
=====Function Descriptions=====
zip([iterable, ...])

This function returns a list of tuples. The ith tuple contains the ith element from each of the argument sequences or iterables. If the argument sequences are of unequal lengths, then the returned list is truncated to the length of the shortest argument sequence.

Sample Code
>>> print zip([1,2,3,4,5,6],'Hacker')
[(1, 'H'), (2, 'a'), (3, 'c'), (4, 'k'), (5, 'e'), (6, 'r')]
>>>
>>> print zip([1,2,3,4,5,6],[0,9,8,7,6,5,4,3,2,1])
[(1, 0), (2, 9), (3, 8), (4, 7), (5, 6), (6, 5)]
>>>
>>> A = [1,2,3]
>>> B = [6,5,4]
>>> C = [7,8,9]
>>> X = [A] + [B] + [C]
>>>
>>> print zip(*X)
[(1, 6, 7), (2, 5, 8), (3, 4, 9)]

=====Problem Statement=====
The National University conducts an examination of N students in X subjects.
Your task is to compute the average scores of each student.

Average score = Sum of scores obtained in all subjects by a student / Total number of subjects

The format for the general mark sheet is:
Student ID -> ___1_____2_____3_____4_____5__
Subject 1   |  89    90    78    93    80
Subject 2   |  90    91    85    88    86
Subject 3   |  91    92    83    89    90.5
            |______________________________
Average        90    91    82    90    85.5

=====Input Format=====
The first line contains N and X separated by a space. The next X lines contains the space separated marks obtained by students in a particular subject.

=====Constraints=====
0<N≤100
0<X≤100

=====Output Format=====
Print the averages of all students on separate lines. The averages must be correct up to 1 decimal place.

n, x = list(map(int,input().split()))
ar = [0 for i in range(n)]
for i in range(x):
    temp_ar=list(map(float,input().split()))
    for j in range(n):
        ar[j] += temp_ar[j]
for i in range(n):
    print((ar[i]/x))


Solve in Python:
=====Problem Statement=====
A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a string s, which is the company name in lowercase letters, your task is to find the top three most common characters in the string.
Print the three most common characters along with their occurrence count.
Sort in descending order of occurrence count.
If the occurrence count is the same, sort the characters in alphabetical order.

For example, according to the conditions described above, GOOGLE would have it's logo with the letters G, O, E.

=====Input Format=====
A single line of input containing the string S.

=====Constraints=====
3≤len(S)≤10^4

#!/bin/python3

import sys
from collections import Counter

def __starting_point():
    s = input().strip()
    best = Counter(s)
    sortit = sorted(list(best.items()), key = lambda x: (-x[1], x[0]))[:3]

    print(("\n".join(x[0]+" "+str(x[1]) for x in sortit)))

__starting_point()


Solve in Python:
=====Problem Statement=====
A valid email address meets the following criteria:

It's composed of a username, domain name, and extension assembled in this format: username@domain.extension
The username starts with an English alphabetical character, and any subsequent characters consist of one or more of the following: alphanumeric characters, -,., and _.
The domain and extension contain only English alphabetical characters.
The extension is 1, 2, or 3 characters in length.

Given n pairs of names and email addresses as input, print each name and email address pair having a valid email address on a new line.

Hint: Try using Email.utils() to complete this challenge. For example, this code:

import email.utils
print email.utils.parseaddr('DOSHI <DOSHI@hackerrank.com>')
print email.utils.formataddr(('DOSHI', 'DOSHI@hackerrank.com'))

produces this output:

('DOSHI', 'DOSHI@hackerrank.com')
DOSHI <DOSHI@hackerrank.com>

=====Input Format=====
The first line contains a single integer, n, denoting the number of email address.
Each line i of the n subsequent lines contains a name and an email address as two space-separated values following this format:
name <user@email.com>

=====Constraints=====
0<n<100

=====Output Format=====
Print the space-separated name and email address pairs containing valid email addresses only. Each pair must be printed on a new line in the following format:
name <user@email.com>

You must print each valid email address in the same order as it was received as input.

import re

t = int(input().strip())
for _ in range(t):
    name, email = input().strip().split()

    if re.match(r'<[A-Za-z](\w|-|\.|_)+@[A-Za-z]+\.[A-Za-z]{1,3}>', email):
        print("{} {}".format(name, email))


Solve in Python:
=====Problem Statement=====
A valid postal code P have to fullfil both below requirements:

1. P must be a number in the range from 100000 to 999999 inclusive.
2. P must not contain more than one alternating repetitive digit pair.

Alternating repetitive digits are digits which repeat immediately after the next digit. In other words, an alternating repetitive digit pair is formed by two equal digits that have just a single digit between them.

For example:

121426 # Here, 1 is an alternating repetitive digit.
523563 # Here, NO digit is an alternating repetitive digit.
552523 # Here, both 2 and 5 are alternating repetitive digits.

Your task is to provide two regular expressions regex_integer_in_range and regex_alternating_repetitive_digit_pair. Where:

regex_integer_in_range should match only integers range from 100000 to 999999 inclusive

regex_alternating_repetitive_digit_pair should find alternating repetitive digits pairs in a given string.

Both these regular expressions will be used by the provided code template to check if the input string P is a valid postal code using the following expression:
(bool(re.match(regex_integer_in_range, P))
and len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2)

=====Input Format=====
Locked stub code in the editor reads a single string denoting P from stdin and uses provided expression and your regular expressions to validate if P is a valid postal code.

=====Output Format=====
You are not responsible for printing anything to stdout. Locked stub code in the editor does that.

import re
p = input().strip()
range_check = bool(re.match(r'^[1-9][0-9]{5}$',p))
repeat_check = len(re.findall(r'(?=([0-9])[0-9]\1)',p))
print((range_check == True and repeat_check<2))


Solve in Python:
=====Problem Statement=====
ABC is a right triangle, 90°, at B. Therefore, ANGLE{ABC} = 90°.
Point M is the midpoint of hypotenuse AC.
You are given the lengths AB and BC.
Your task is to find ANGLE{MBC} (angle θ°, as shown in the figure) in degrees.

=====Input Format=====
The first contains the length of side AB.
The second line contains the length of side BC.

=====Constraints=====
0<AB≤100
0<BC≤100
Lengths AB and BC are natural numbers.

=====Output Format=====
Output ANGLE{MBC} in degrees.
Note: Round the angle to the nearest integer.
Examples:
If angle is 56.5000001°, then output 57°.
If angle is 56.5000000°, then output 57°.
If angle is 56.4999999°, then output 56°.

import math
ab = float(input())
bc = float(input())
ac = math.sqrt((ab*ab)+(bc*bc))
bm = ac / 2.0
mc = bm
#let,
b = mc
c = bm
a = bc
#where b=c
angel_b_radian = math.acos(a / (2*b))
angel_b_degree = int(round((180 * angel_b_radian) / math.pi))
output_str = str(angel_b_degree)+'°'
print(output_str)


Solve in Python:
=====Problem Statement=====
ABCXYZ company has up to 100 employees.
The company decides to create a unique identification number (UID) for each of its employees.
The company has assigned you the task of validating all the randomly generated UIDs.

A valid UID must follow the rules below:

It must contain at least 2 uppercase English alphabet characters.
It must contain at least 3 digits (0-9).
It should only contain alphanumeric characters (a-z, A-Z & 0-9).
No character should repeat.
There must be exactly 10 characters in a valid UID.

=====Input Format=====
The first line contains an integer T, the number of test cases.
The next T lines contains an employee's UID.

=====Output Format=====
For each test case, print 'Valid' if the UID is valid. Otherwise, print 'Invalid', on separate lines. Do not print the quotation marks.

import re
n = int(input())
upper_check = r'.*([A-Z].*){2,}'
digit_check = r'.*([0-9].*){3,}'
alphanumeric_and_length_check = r'([A-Za-z0-9]){10}$'
repeat_check = r'.*(.).*\1'
for i in range(n):
    uid_string = input().strip()
    upper_check_result = bool(re.match(upper_check,uid_string))
    digit_check_result = bool(re.match(digit_check,uid_string))
    alphanumeric_and_length_check_result = bool(re.match(alphanumeric_and_length_check,uid_string))
    repeat_check_result = bool(re.match(repeat_check,uid_string))
    if upper_check_result and digit_check_result and alphanumeric_and_length_check_result and not repeat_check_result:
        print('Valid')
    else:
        print('Invalid')


Solve in Python:
=====Problem Statement=====
An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.

In the Gregorian calendar, three conditions are used to identify leap years:
    The year can be evenly divided by 4, is a leap year, unless:
        The year can be evenly divided by 100, it is NOT a leap year, unless:
            The year is also evenly divisible by 400. Then it is a leap year.

This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. Source

Task
Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False.
Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function.

=====Input Format=====
Read year, the year to test.

=====Constraints=====
1900≤year≤10^5

=====Output Format=====
The function must return a Boolean value (True/False). Output is handled by the provided code stub.

def is_leap(year):
    return (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0))


Solve in Python:
=====Problem Statement=====
CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB).

Specifications of HEX Color Code

It must start with a '#' symbol.
It can have 3 or 6 digits.
Each digit is in the range of 0 to F. (1, 2, 3, 4, 5, 6, 7, 8, 9, 0, A, B, C, D, E and F).
A – F letters can be lower case. (a, b, c, d, e and f are also valid digits).

Examples

Valid Hex Color Codes
#FFF
#025
#F0A1FB

Invalid Hex Color Codes
#fffabg
#abcf
#12365erff

You are given N lines of CSS code. Your task is to print all valid Hex Color Codes, in order of their occurrence from top to bottom.

CSS Code Pattern

Selector
{
        Property: Value;
}

=====Input Format=====
The first line contains N, the number of code lines.
The next N lines contains CSS Codes.

=====Constraints=====
0<N<50

=====Output Format=====
Output the color codes with '#' symbols on separate lines.

import re
n = int(input())
for t in range(n):
    s = input()
    match_result = re.findall(r'(#[0-9A-Fa-f]{3}|#[0-9A-Fa-f]{6})(?:[;,.)]{1})',s)
    for i in match_result:
        if i != '':
            print(i)


Solve in Python:
=====Problem Statement=====
Consider a list (list = []). You can perform the following commands:
1. insert i e: Insert integer e at position i.
2. print: Print the list.
3. remove e: Delete the first occurrence of integer e.
4. append e: Insert integer e at the end of the list.
5. sort: Sort the list.
6. pop: Pop the last element from the list.
7. reverse: Reverse the list.
Initialize your list and read in the value of n followed by n lines of commands where each command will be 7 of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.

=====Example=====
N = 4
append 1
append 2
insert 3 1
print
append 1: Append 1 to the list, arr = [1].
append 2: Append 2 to the list, arr = [1,2].
insert 3 1: Insert 3 at index 1, arr = [1,3,2].
print: Print the array
Output:
[1, 3, 2]

=====Input Format=====
The first line contains an integer, n, denoting the number of commands. Each line i of the subsequent n lines contains one of the commands described above.

=====Constraints=====
The elements added to the list must be integers

=====Output Format=====
For each command of type print, print the list on a new line.

# Enter your code here. Read input from STDIN. Print output to STDOUT
ar=[]
n=int(input())
for i in range(0,n):
    tmp_str=input()
    tmp_str_ar=tmp_str.strip().split(" ")
    cmd=tmp_str_ar[0]
    if(cmd=="print"):
        print(ar)
    elif(cmd=="sort"):
        ar.sort()
    elif(cmd=="reverse"):
        ar.reverse()
    elif(cmd=="pop"):
        ar.pop()
    elif(cmd=="count"):
        val=int(tmp_str_ar[1])
        ar.count(val)
    elif(cmd=="index"):
        val=int(tmp_str_ar[1])
        ar.index(val)
    elif(cmd=="remove"):
        val=int(tmp_str_ar[1])
        ar.remove(val)
    elif(cmd=="append"):
        val=int(tmp_str_ar[1])
        ar.append(val)
    elif(cmd=="insert"):
        pos=int(tmp_str_ar[1])
        val=int(tmp_str_ar[2])
        ar.insert(pos,val)


Solve in Python:
=====Problem Statement=====
Given a list of rational numbers,find their product.

Concept
The reduce() function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3] and you have to find its sum.

>>> reduce(lambda x, y : x + y,[1,2,3])
6

You can also define an initial value. If it is specified, the function will assume initial value as the value given, and then reduce. It is equivalent to adding the initial value at the beginning of the list. For example:

>>> reduce(lambda x, y : x + y, [1,2,3], -3)
3

>>> from fractions import gcd
>>> reduce(gcd, [2,4,8], 3)
1

=====Input Format=====
First line contains n, the number of rational numbers.
The ith of next n lines contain two integers each, the numerator (N_i) and denominator (D_i) of the ith rational number in the list.

=====Constraints=====
1≤n≤100
1≤N_i,D_i≤10^9

=====Output Format=====
Print only one line containing the numerator and denominator of the product of the numbers in the list in its simplest form, i.e. numerator and denominator have no common divisor other than 1.

from fractions import Fraction
from functools import reduce
def product(fracs):
    t = Fraction(reduce(lambda x,y : x*y,fracs))
    return t.numerator, t.denominator
def __starting_point():
    fracs = []
    for _ in range(int(input())):
        fracs.append(Fraction(*list(map(int, input().split()))))
    result = product(fracs)
    print((*result))

'''
3
1 2
3 4
10 6
'''

__starting_point()


Solve in Python:
=====Problem Statement=====
Given an integer, n, print the following values for each integer i from 1 to n:
1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary

The four values must be printed on a single line in the order specified above for each i from 1 to n. Each value should be space-padded to match the width of the binary value of n.

=====Input Format=====
A single integer denoting n.

=====Constraints=====
1 ≤ n ≤ 99

=====Output Format=====
Print n lines wehere each line i (in the range 1 ≤ i ≤ n) contains the respective decimal, octal, capitalized hexadecimal, and binary values of i. Each printed value must be formatted to the width of the binary value of n.

n = int(input().strip())
w = len(str(bin(n))[2:])
for i in range(1,n+1,1):
    o = str(oct(i))[2:]
    h = str(hex(i))[2:]
    h = h.upper()
    b = str(bin(i))[2:]
    d = str(i)
    print(('{:>{width}} {:>{width}} {:>{width}} {:>{width}}'.format(d,o,h,b,width=w)))


Solve in Python:
=====Problem Statement=====
Given the names and grades for each student in a class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
NOTE: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.

=====Example=====
records = [["chi",20.0],["beta",50.0],["alpha",50.0]]
The ordered list of scores is [20.0,50.0], so the second lowest score is 50.0. There are two students with that score: ["beta","alpha"]. Ordered alphabetically, the names are printed as:
alpha
beta

=====Input Format=====
The first line contains an integer, N, the number of students.
The 2N subsequent lines describe each student over 2 lines.
- The first line contains a student's name.
- The second line contains their grade.

=====Constraints=====
2≤N≤5
There will always be one or more students having the second lowest grade.

=====Output Format=====
Print the name(s) of any student(s) having the second lowest grade in. If there are multiple students, order their names alphabetically and print each one on a new line.

def __starting_point():
    students = []
    for _ in range(int(input())):
        name = input()
        score = float(input())

        students.append([name, score])

    lowest = min([el[1] for el in students])
    second_low = min(list([a for a in [el[1] for el in students] if a > lowest]))

    out = [el[0] for el in students if (el[1] == second_low)]
    out.sort()

    print(("\n".join(out)))

__starting_point()


Solve in Python:
=====Problem Statement=====
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given n scores. Store them in a list and find the score of the runner-up.

=====Input Format=====
The first line contains n. The second line contains an array A[] of n integers each separated by a space.

=====Constraints=====
2≤n≤10
-100≤A[i]≤ 100

=====Output Format=====
Print the runner-up score.

def __starting_point():
    n = int(input())
    arr = list(map(int, input().split()))
    first = max(arr)

    print((max(list([a for a in arr if a != first]))))

__starting_point()


Solve in Python:
=====Problem Statement=====
Here is a sample line of code that can be executed in Python:
print("Hello, World!")

You can just as easily store a string as a variable and then print it to stdout:
my_string = "Hello, World!"
print(my_string)

The above code will print Hello, World! on your screen. Try it yourself in the editor below!

=====Input Format=====
You do not need to read any input in this challenge.

=====Output Format=====
Print Hello, World! to stdout.

def __starting_point():
    print("Hello, World!")

__starting_point()


Solve in Python:
=====Problem Statement=====
In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.

NOTE: String letters are case-sensitive.

=====Input Format=====
The first line of input contains the original string. The next line contains the substring.

=====Constraints=====
1 ≤ len(string) ≤ 200
Each character in the string is an ascii character.

=====Output Format=====
Output the integer number indicating the total number of occurrences of the substring in the original string.

# Enter your code here. Read input from STDIN. Print output to STDOUT
s=input()
ss=input()
cnt=0
len_s=len(s)
len_ss=len(ss)
for i in range(0,len_s):
    tmp=s[i:i+len_ss]
    if(tmp==ss):
        cnt=cnt+1
print(cnt)


Solve in Python:
=====Problem Statement=====
In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools.
You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences of the character 'c' with (X, c) in the string.

=====Input Format=====
A single line of input consisting of the string S.

=====Output Format=====
A single line of output consisting of the modified string.

=====Constraints=====
All the characters of S denote integers between 0 and 9.
1≤|S|≤10^4

Sample Input

1222311

Sample Output

(1, 1) (3, 2) (1, 3) (2, 1)

Explanation

First, the character  occurs only once. It is replaced by . Then the character  occurs three times, and it is replaced by  and so on.

Also, note the single space within each compression and between the compressions.

import itertools
s = input().strip()
s_unique_element = list(set(s))
group = []
key = []
for k,g in itertools.groupby(s):
    group.append(list(g))
    key.append(k)
for i in range(len(group)):
    group_length = len(group[i])
    k = int(key[i])
    print(tuple((group_length,k)),end=' ')


Solve in Python:
=====Problem Statement=====
Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there is: 2^31 - 1 (c++ int) or 2^63 - 1 (C++ long long int).
As we know, a^b the result of grows really fast with increasing b.
Let's do some calculations on very large integers.
Task
Read four numbers, a, b, c, and d, and print the result of a^b + c^d.

=====Input Format=====
Integers a, b, c, and d are given on four separate lines, respectively.

=====Constraints=====
1≤a≤1000
1≤b≤1000
1≤c≤1000
1≤d≤1000

=====Output Format=====
Print the result of a^b + c^d on one line.

#!/usr/bin/env python3

def __starting_point():
    a = int(input().strip())
    b = int(input().strip())
    c = int(input().strip())
    d = int(input().strip())

    print(pow(a, b) + pow(c, d))
__starting_point()


Solve in Python:
=====Problem Statement=====
Kevin and Stuart want to play the 'The Minion Game'.

Game Rules

Both players are given the same string, S.
Both players have to make substrings using the letters of the string S.
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have made all possible substrings.

Scoring
A player gets +1 point for each occurrence of the substring in the string S.

=====Example=====
String S = BANANA
Kevin's vowel beginning word = ANA
Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points.

Your task is to determine the winner of the game and their score.

=====Input Format=====
A single line of input containing the string S.
Note: The string S will contain only uppercase letters: [A-Z].

=====Constraints=====
0 < len(S) < 10^6

=====Output Format=====
Print one line: the name of the winner and their score separated by a space.
If the game is a draw, print Draw.

vowels = ['A', 'E', 'I', 'O', 'U']

def minion_game(string):
    score_kevin = 0
    score_stuart = 0

    for ind in range(len(string)):
        if string[ind] in vowels:
            score_kevin += len(string) - ind
        else:
            score_stuart += len(string) - ind

    if score_kevin > score_stuart:
        return 'Kevin '+ str(score_kevin)
    elif score_kevin < score_stuart:
        return 'Stuart '+ str(score_stuart)
    else:
        return 'Draw'


Solve in Python:
=====Problem Statement=====
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.

One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.

The Captain was given a separate room, and the rest were given one room per group.

Mr. Anant has an unordered list of randomly arranged room entries. The list consists of the room numbers for all of the tourists. The room numbers will appear K times per group except for the Captain's room.

Mr. Anant needs you to help him find the Captain's room number.
The total number of tourists or the total number of groups of families is not known to you.
You only know the value of K and the room number list.

=====Input Format=====
The first consists of an integer, K, the size of each group.
The second line contains the unordered elements of the room number list.

=====Constraints=====
1<K<1000

=====Output Format=====
Output the Captain's room number.

k = int(input())
room_number_list = list(map(int,input().split()))
room_number_set = set(room_number_list)
room_number_list_sum = sum(room_number_list)
room_number_set_sum = sum(room_number_set) * k
diff = room_number_set_sum - room_number_list_sum
for i in room_number_set:
    if diff == ((k-1)*i):
        print(i)
        break


N, M = list(map(int,input().split())) # More than 6 lines of code will result in 0 score. Blank lines are not counted.
for i in range(1,N,2):
    print((int((M-3*i)/2)*'-'+(i*'.|.')+int((M-3*i)/2)*'-'))
print((int((M-7)/2)*'-'+'WELCOME'+int((M-7)/2)*'-'))
for i in range(N-2,-1,-2):
    print((int((M-3*i)/2)*'-'+(i*'.|.')+int((M-3*i)/2)*'-'))


Solve in Python:
=====Problem Statement=====
Neo has a complex matrix script. The matrix script is a NXM grid of strings. It consists of alphanumeric characters, spaces and symbols (!,@,#,$,%,&).
To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from top to bottom and starts reading from the leftmost column.

If there are symbols or spaces between two alphanumeric characters of the decoded script, then Neo replaces them with a single space '' for better readability.

Neo feels that there is no need to use 'if' conditions for decoding.

Alphanumeric characters consist of: [A-Z, a-z, and 0-9].

=====Input Format=====
The first line contains space-separated integers N (rows) and M (columns) respectively.
The next N lines contain the row elements of the matrix script.

=====Constraints=====
0<N,M<100
Note: A 0 score will be awarded for using 'if' conditions in your code.

=====Output Format=====
Print the decoded matrix script.

import re

n, m = input().strip().split(' ')
n, m = [int(n), int(m)]
matrix = []
for _ in range(n):
    matrix_t = str(input())
    matrix.append(matrix_t)

complete = ""
for el in zip(*matrix):
    complete += "".join(el)
print((re.sub(r'(?<=\w)([^\w]+)(?=\w)', " ", complete)))


Solve in Python:
=====Problem Statement=====
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't, set it to what you want.
For example:

from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
    print i

This prints:

('python', ['awesome', 'language'])
('something-else', ['not relevant'])

In this challenge, you will be given 2 integers, n and m. There are n words, which might repeat, in word group A. There are m words belonging to word group B. For each m words, check whether the word has appeared in group A or not. Print the indices of each occurrence of m in group A. If it does not appear, print -1.

=====Constraints=====
1≤n≤10000
1≤m≤100
1≤length of each word in the input≤100

=====Input Format=====
The first line contains integers, n and m separated by a space.
The next n lines contains the words belonging to group A.
The next m lines contains the words belonging to group B.

=====Output Format=====
Output m lines.
The ith line should contain the 1-indexed positions of the occurrences of the ith word separated by spaces.

#!/usr/bin/env python3

from collections import defaultdict

def __starting_point():
    n, m = list(map(int, input().strip().split(' ')))
    library = defaultdict(list)

    for ind in range(1, n + 1):
        word = input().strip()
        library[word].append(ind)

    for ind in range(m):
        word = input().strip()
        if len(library[word]) > 0:
            print((" ".join(map(str, library[word]))))
        else:
            print("-1")

__starting_point()


Solve in Python:
=====Problem Statement=====
The included code stub will read an integer, n, from STDIN.
Without using any string methods, try to print the following:
123...n
Note that "" represents the consecutive values in between.

=====Example=====
n = 5
Print the string 12345.

=====Input Format=====
The first line contains an integer n.

=====Constraints=====
1≤n≤150

=====Output Format=====
Print the list of integers from 1 through n as a string, without spaces.

n=int(input())
ar=range(1,n+1)
for i in ar:
    print(i,end="")


Solve in Python:
=====Problem Statement=====
The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python.

You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list.
Find the probability that at least one of the K indices selected will contain the letter: ''.

=====Input Format=====
The input consists of three lines. The first line contains the integer N, denoting the length of the list. The next line consists of N space-separated lowercase English letters, denoting the elements of the list.
The third and the last line of input contains the integer K, denoting the number of indices to be selected.

=====Output Format=====
Output a single line consisting of the probability that at least one of the K indices selected contains the letter: 'a'.
Note: The answer must be correct up to 3 decimal places.

=====Constraints=====
1≤N≤10
1≤K≤N

from itertools import combinations
n = int(input())
ar = input().split()
k = int(input())
comb_list = list(combinations(ar,k))
a_list = [e for e in comb_list if 'a' in e]
print((len(a_list) / len(comb_list)))


Solve in Python:
=====Problem Statement=====
The provided code stub reads and integer, n, from STDIN. For all non-negative integers i < n, print i^2.

=====Example=====
The list of non-negative integers that are less than n = 3 is [0,1,2]. Print the square of each number on a separate line.
0
1
4

=====Input Format=====
The first and only line contains the integer, n.

=====Constraints=====
1≤n≤20

=====Output Format=====
Print lines, one corresponding to each i.

# Enter your code here. Read input from STDIN. Print output to STDOUT
a=int(input())
for i in range(0,a):
    print((i*i))


Solve in Python:
=====Problem Statement=====
The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.

=====Example=====
a = 3
b = 5

Print the following:
8
-2
15

=====Input Format=====
The first line contains the first integer, a.
The second line contains the second integer, b.

=====Constraints=====
1≤a≤10^10
1≤b≤10^10

=====Output Format=====
Print the three lines as explained above.

# Enter your code here. Read input from STDIN. Print output to STDOUT
a=int(input())
b=int(input())
print((a+b))
print((a-b))
print((a*b))


Solve in Python:
=====Problem Statement=====
The provided code stub reads two integers, a and b, from STDIN.
Add logic to print two lines. The first line should contain the result of integer division,
a // b. The second line should contain the result of float division, a / b.
No rounding or formatting is necessary.

=====Example=====
a = 3
b = 5
The result of the integer division 3//5 = 0.
The result of the float division is 3/5 = 0.6.

Print:
0
0.6

=====Input Format=====
The first line contains the first integer, a.
The second line contains the second integer, b.

=====Output Format=====
Print the two lines as described above.

def __starting_point():
    a = int(input())
    b = int(input())

    print((a//b))
    print((a/b))

__starting_point()


Solve in Python:
=====Problem Statement=====
The re.sub() tool (sub stands for substitution) evaluates a pattern and, for each valid match, it calls a method (or lambda).
The method is called for all matches and can be used to modify strings in different ways.
The re.sub() method returns the modified string as an output.

Learn more about re.sub().

Transformation of Strings
Code

import re

#Squaring numbers
def square(match):
    number = int(match.group(0))
    return str(number**2)

print re.sub(r"\d+", square, "1 2 3 4 5 6 7 8 9")

Output

1 4 9 16 25 36 49 64 81

Replacements in Strings

Code

import re

html = """
<head>
<title>HTML</title>
</head>
<object type="application/x-flash"
  data="your-file.swf"
  width="0" height="0">
  <!-- <param name="movie"  value="your-file.swf" /> -->
  <param name="quality" value="high"/>
</object>
"""

print re.sub("(<!--.*?-->)", "", html) #remove comment

Output

<head>
<title>HTML</title>
</head>
<object type="application/x-flash"
  data="your-file.swf"
  width="0" height="0">

  <param name="quality" value="high"/>
</object>

=====Problem Statement=====
You are given a text of N lines. The text contains && and || symbols.
Your task is to modify those symbols to the following:
&& → and
|| → or

Both && and || should have a space " " on both sides.

=====Input Format=====
The first line contains the integer, N.
The next N lines each contain a line of the text.

=====Constraints=====
0<N<100
Neither && nor || occur in the start or end of each line.

=====Output Format=====
Output the modified text.

import re, sys
n = int(input())
for line in sys.stdin:
    remove_and = re.sub(r'(?<= )(&&)(?= )',"and",line)
    remove_or = re.sub(r'(?<= )(\|\|)(?= )',"or",remove_and)
    print(remove_or,end='')


Solve in Python:
=====Problem Statement=====
There is a horizontal row of n cubes. The length of each cube is given. You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube_i is on top of cube_j then sideLength_j ≥ sideLength_i.
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time. Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks.

=====Input Format=====
The first line contains a single integer T, the number of test cases.
For each test case, there are 2 lines.
The first line of each test case contains n, the number of cubes.
The second line contains n space separated integers, denoting the sideLengths of each cube in that order.

=====Constraints=====
1≤T≤5
1≤n≤10^5
1≤sideLength≤2^31

=====Output Format=====
For each test case, output a single line containing either "Yes" or "No" without the quotes.

from collections import deque
cas = int(input())
for t in range(cas):
    n = int(input())
    dq = deque(list(map(int,input().split())))
    possible = True
    element = (2**31)+1
    while dq:
        left_element = dq[0]
        right_element = dq[-1]
        if left_element>=right_element and element>=left_element:
            element = dq.popleft()
        elif right_element>=left_element and element>=right_element:
            element = dq.pop()
        else:
            possible = False
            break
    if possible:
        print('Yes')
    else:
        print('No')


Solve in Python:
=====Problem Statement=====
There is an array of n integers. There are also 2 disjoint sets, A and B, each containing m integers. You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. For each integer i in the array, if i ∈ A, you add 1 to your happiness. If i ∈ B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.

Note: Since A and B are sets, they have no repeated elements. However, the array might contain duplicate elements.

=====Constraints=====
1≤n≤10^5
1≤m≤10^5
1≤Any integer in the input≤10^9

=====Input Format=====
The first line contains integers n and m separated by a space.
The second line contains n integers, the elements of the array.
The third and fourth lines contain m integers, A and B, respectively.

=====Output Format=====
Output a single integer, your total happiness.

#!/usr/bin/env python3

def __starting_point():
    happiness = 0
    n, m = map(int, input().strip().split(' '))
    arr = list(map(int, input().strip().split(' ')))

    good = set(map(int, input().strip().split(' ')))
    bad = set(map(int, input().strip().split(' ')))

    for el in arr:
        if el in good:
            happiness += 1
        elif el in bad:
            happiness -= 1

    print(happiness)
__starting_point()


Solve in Python:
=====Problem Statement=====
We have seen that lists are mutable (they can be changed), and tuples are immutable (they cannot be changed).

Let's try to understand this with an example.

You are given an immutable string, and you want to make changes to it.
Task
Read a given string, change the character at a given index and then print the modified string.

=====Example=====
Example
>>> string = "abracadabra"

You can access an index by:

>>> print string[5]
a

What if you would like to assign a value?

>>> string[5] = 'k'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

How would you approach this?

    One solution is to convert the string to a list and then change the value.

Example

>>> string = "abracadabra"
>>> l = list(string)
>>> l[5] = 'k'
>>> string = ''.join(l)
>>> print string
abrackdabra

    Another approach is to slice the string and join it back.

Example

>>> string = string[:5] + "k" + string[6:]
>>> print string
abrackdabra

=====Input Format=====
The first line contains a string, S.
The next line contains an integer i, denoting the index location and a character c separated by a space.

=====Output Format=====
Using any of the methods explained above, replace the character at index i with character c.

def mutate_string(string, position, character):
    out = list(string)
    out[position] = character
    return "".join(out)


Solve in Python:
=====Problem Statement=====
When users post an update on social media,such as a URL, image, status update etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published, i.e, how many hours, minutes or seconds ago.
Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format:
Day dd Mon yyyy hh:mm:ss +xxxx
Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them.

=====Input Format=====
The first line contains T, the number of tescases.
Each testcase contains 2 lines, representing time t_1 and time t_2.

import datetime
cas = int(input())
for t in range(cas):
    timestamp1 = input().strip()
    timestamp2 = input().strip()
    time_format = "%a %d %b %Y %H:%M:%S %z"
    time_second1 = datetime.datetime.strptime(timestamp1,time_format)
    time_second2 = datetime.datetime.strptime(timestamp2,time_format)
    print((int(abs((time_second1-time_second2).total_seconds()))))


Solve in Python:
=====Problem Statement=====
You and Fredrick are good friends. Yesterday, Fredrick received

credit cards from ABCD Bank. He wants to verify whether his credit card numbers are valid or not. You happen to be great at regex so he is asking for your help!

A valid credit card from ABCD Bank has the following characteristics:

► It must start with a 4, 5 or 6.
► It must contain exactly 16 digits.
► It must only consist of digits (0-9).
► It may have digits in groups of 4, separated by one hyphen "-".
► It must NOT use any other separator like ' ' , '_', etc.
► It must NOT have 4 or more consecutive repeated digits.

=====Example=====

Valid Credit Card Numbers

4253625879615786
4424424424442444
5122-2368-7954-3214

Invalid Credit Card Numbers

42536258796157867       #17 digits in card number → Invalid
4424444424442444        #Consecutive digits are repeating 4 or more times → Invalid
5122-2368-7954 - 3214   #Separators other than '-' are used → Invalid
44244x4424442444        #Contains non digit characters → Invalid
0525362587961578        #Doesn't start with 4, 5 or 6 → Invalid

=====Input Format=====
The first line of input contains an integer N.
The next N lines contain credit card numbers.

=====Constraints=====
0<N<100

=====Output Format=====
Print 'Valid' if the credit card number is valid. Otherwise, print 'Invalid'. Do not print the quotes.

import re

def __starting_point():
    t = int(input().strip())

    for _ in range(t):
        num = "".join(input())
        if (re.match(r'^[456]', num) and
            (re.match(r'([\d]{4}-){3}[\d]{4}$', num) or
             re.match(r'[\d]{16}', num)) and
            not re.search(r'(\d)\1{3,}', num.replace("-", ""))):
            print("Valid")
        else:
            print("Invalid")

__starting_point()


Solve in Python:
=====Problem Statement=====
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.

alison heck => Alison Heck

Given a full name, your task is to capitalize the name appropriately.

=====Input Format=====
A single line of input containing the full name, S.

=====Constraints=====
0<len(S)<1000
The string consists of alphanumeric characters and spaces.

Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.

=====Output Format=====
Print the capitalized string, S.

s = input()
s_ar = s.split(' ')
final_ar = []
space = ' '
for w in s_ar:
    final_ar.append(w.capitalize())
print((space.join(final_ar)))


Solve in Python:
=====Problem Statement=====
You are given a function f(X) = X^2. You are also given K lists. The ith list consists of N_i elements.

You have to pick one element from each list so that the value from the equation below is maximized:
S = (f(X_1) + f(X_2) + ... + f(X_k))%M
X_i denotes the element picked from the ith list. Find the maximized value S_max obtained.
% denotes the modulo operator.
Note that you need to take exactly one element from each list, not necessarily the largest element. You add the squares of the chosen elements and perform the modulo operation. The maximum value that you can obtain, will be the answer to the problem.

=====Input Format=====
The first line contains 2 space separated integers K and M.
The next K lines each contains an integer N_i, denoting the number of elements in the ith list, followed by space separated integers denoting the elements in the list.

=====Constraints=====
1≤K≤7
1≤M≤1000
1≤N_i≤7
1≤Magnitude of elements in list≤10^9

=====Output Format=====
Output a single integer denoting the value S_max.

import itertools

k, m = list(map(int,input().split()))

main_ar = []
for i in range(k):
    ar = list(map(int,input().split()))
    main_ar.append(ar[1:])

all_combination = itertools.product(*main_ar)
result = 0
for single_combination in all_combination:
    result = max(sum([x*x for x in single_combination])%m,result)
print(result)


Solve in Python:
=====Problem Statement=====
You are given a positive integer N.
Your task is to print a palindromic triangle of size N.

For example, a palindromic triangle of size 5 is:
1
121
12321
1234321
123454321

You can't take more than two lines. The first line (a for-statement) is already written for you.
You have to complete the code using exactly one print statement.

Note:
Using anything related to strings will give a score of 0.
Using more than one for-statement will give a score of 0.

=====Input Format=====
A single line of input containing the integer N.

=====Constraints=====
0<N<10

=====Output Format=====
Print the palindromic triangle of size N as explained above.

for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also
    print(((10**i//9)**2))


Solve in Python:
=====Problem Statement=====
You are given a positive integer N. Print a numerical triangle of height N - 1 like the one below:
1
22
333
4444
55555
......

Can you do it using only arithmetic operations, a single for loop and print statement?

Use no more than two lines. The first line (the for statement) is already written for you. You have to complete the print statement.

Note: Using anything related to strings will give a score of 0.

=====Input Format=====
A single line containing integer, N.

=====Constraints=====
1≤N≤9

=====Output Format=====
Print N - 1 lines as explained above.

for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also
    print((10**i//9 * i))


Solve in Python:
=====Problem Statement=====
You are given a set A and n other sets.
Your job is to find whether set A is a strict superset of each of the N sets.
Print True, if A is a strict superset of each of the N sets. Otherwise, print False.
A strict superset has at least one element that does not exist in its subset.

=====Example=====
Set([1,3,4]) is a strict superset of set([1,3]).
Set([1,3,4]) is not a strict superset of set([1,3,4]).
Set([1,3,4]) is not a strict superset of set(1,3,5).

=====Input Format=====
The first line contains the space separated elements of set A.
The second line contains integer n, the number of other sets.
The next n lines contains the space separated elements of the other sets.

=====Constraints=====
0 < len(set(A)) < 501
0<N<21
0 < len(otherSets) < 101

=====Output Format=====
Print True if set A is a strict superset of all other N sets. Otherwise, print False.

A  = set(input().split())
n = int(input())
check = True
for i in range(n):
    s = set(input().split())
    if (s&A != s) or (s == A):
        check = False
        break
print(check)


Solve in Python:
=====Problem Statement=====
You are given a spreadsheet that contains a list of N athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the Kth attribute and print the final resulting table. Follow the example given below for better understanding.

image

Note that K is indexed from 0 to M-1, where M is the number of attributes.
Note: If two attributes are the same for different rows, for example, if two atheletes are of the same age, print the row that appeared first in the input.

=====Input Format=====
The first line contains N and M separated by a space.
The next N lines each contain M elements.
The last line contains K.

=====Constraints=====
1≤N,M≤1000
0≤K≤M
Each element ≤ 1000

=====Output Format=====
Print the N lines of the sorted table. Each line should contain the space separated elements. Check the sample below for clarity.

n, m = map(int,input().split())
ar = []
for i in range(n):
    ar.append(list(map(int,input().split())))
k = int(input())
ar = sorted(ar,key = lambda x:x[k])
for i in ar:
    [print(x,end=' ') for x in i]
    print('')


Solve in Python:
=====Problem Statement=====
You are given a string N.
Your task is to verify that N is a floating point number.

In this task, a valid float number must satisfy all of the following requirements:

> Number can start with +, - or . symbol.
For example:
✔+4.50
✔-1.0
✔.5
✔-.7
✔+.4
✖ -+4.5

> Number must contain at least 1 decimal value.
For example:
✖ 12.
✔12.0

Number must have exactly one . symbol.
Number must not give any exceptions when converted using float(N).

=====Input Format=====
The first line contains an integer T, the number of test cases.
The next T line(s) contains a string N.

=====Constraints=====
0<T<10

=====Output Format=====
Output True or False for each test case.

import re
n = int(input())
for i in range(n):
    s = input()
    search_result = re.search(r'^[+-]?\d*\.\d+$',s)
    print((bool(search_result)))


Solve in Python:
=====Problem Statement=====
You are given a string S and width w.
Your task is to wrap the string into a paragraph of width w.

=====Input Format=====
The first line contains a string, S.
The second line contains the width, w.

=====Constraints=====
0 < len(S) < 1000
0 < w < len(S)

=====Output Format=====
Print the text wrapped paragraph.

import textwrap
s = input()
w = int(input().strip())
print((textwrap.fill(s,w)))


Solve in Python:
=====Problem Statement=====
You are given a string S.
Your task is to find out whether is a valid regex or not.

=====Input Format=====
The first line contains integer T, the number of test cases.
The next T lines contains the string S.

=====Constraints=====
0<T<100

=====Output Format=====
Print "True" or "False" for each test case without quotes.

#!/usr/bin/env python3

import re

def __starting_point():
    t = int(input().strip())

    for _ in range(t):
        try:
            re.compile(input().strip())
            res = True
        except BaseException:
            res = False
        print(res)
__starting_point()


Solve in Python:
=====Problem Statement=====
You are given a string S. S contains alphanumeric characters only. Your task is to sort the string S in the following manner:
All sorted lowercase letters are ahead of uppercase letters.
All sorted uppercase letters are ahead of digits.
All sorted odd digits are ahead of sorted even digits.

=====Input Format=====
A single line of input contains the string S.

=====Constraints=====
0<len(S)<1000

=====Output Format=====
Output the sorted string S.

#!/usr/bin/env python3

def __starting_point():
    string = input().strip()

    print(*sorted(string, key = lambda x: (-x.islower(), x.isdigit() - x.isupper(), x in '02468', x)), sep='')
__starting_point()


Solve in Python:
=====Problem Statement=====
You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.

=====Example=====

Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2

=====Input Format=====
A single line containing a string S.

=====Output Format=====
Print the modified string S.

def swap_case(s):
    out = ''
    for ind, let in enumerate(s):
        if let.isalpha():
            if let.islower():
                out += s[ind].capitalize()
            else:
                out += s[ind].lower()
        else:
            out += let
    return out


Solve in Python:
=====Problem Statement=====
You are given a string s consisting only of digits 0-9, commas ,, and dots .

Your task is to complete the regex_pattern defined below, which will be used to re.split() all of the , and . symbols in s.

It’s guaranteed that every comma and every dot in s is preceeded and followed by a digit.

#!/usr/bin/env python3

import re

def __starting_point():
    out = list(re.split('[.,]', input()))
    print("\n".join(filter(lambda x: re.match('[0-9]+',x), out)))
__starting_point()


Solve in Python:
=====Problem Statement=====
You are given an HTML code snippet of N lines.
Your task is to detect and print all the HTML tags, attributes and attribute values.

Print the detected items in the following format:

Tag1
Tag2
-> Attribute2[0] > Attribute_value2[0]
-> Attribute2[1] > Attribute_value2[1]
-> Attribute2[2] > Attribute_value2[2]
Tag3
-> Attribute3[0] > Attribute_value3[0]

The -> symbol indicates that the tag contains an attribute. It is immediately followed by the name of the attribute and the attribute value.
The > symbol acts as a separator of attributes and attribute values.

If an HTML tag has no attribute then simply print the name of the tag.

Note: Do not detect any HTML tag, attribute or attribute value inside the HTML comment tags (<!-- Comments -->). Comments can be multiline.
All attributes have an attribute value.

=====Input Format=====
The first line contains an integer N, the number of lines in the HTML code snippet.
The next N lines contain HTML code.

=====Constraints=====
0<N<100

=====Output Format=====
Print the HTML tags, attributes and attribute values in order of their occurrence from top to bottom in the snippet.

Format your answers as explained in the problem statement.

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print(tag)
        for at in attrs:
            print(("-> {} > {}".format(at[0], at[1])))
    def handle_startendtag(self, tag, attrs):
        print(tag)
        for at in attrs:
            print(("-> {} > {}".format(at[0], at[1])))

html = ""
for i in range(int(input())):
    html += input().rstrip()
    html += '\n'

parser = MyHTMLParser()
parser.feed(html)
parser.close()


n = int(input().strip())
w = (n-1) * 2 + ((n * 2) - 1)
#upper half
for i in range(1,n,1):
    number_of_letter = (i*2) - 1
    s = ''
    letter_value = 97 + n - 1
    for i in range(0,number_of_letter):
        if(i != 0):
            s += '-'
        s += chr(letter_value)
        if(i<(number_of_letter-1) / 2):
            letter_value = letter_value - 1
        else:
            letter_value = letter_value + 1
    print((s.center(w,'-')))

#bottom half
for i in range(n,0,-1):
    number_of_letter = (i*2) - 1
    s = ''
    letter_value = 97 + n - 1
    for i in range(0,number_of_letter):
        if(i != 0):
            s += '-'
        s += chr(letter_value)
        if(i<(number_of_letter-1) / 2):
            letter_value = letter_value - 1
        else:
            letter_value = letter_value + 1
    print((s.center(w,'-')))


Solve in Python:
=====Problem Statement=====
You are given n words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.

Note: Each input line ends with a "\n" character.

=====Constraints=====
1≤n≤10^5
The sum of the lengths of all the words do not exceed 10^6
All the words are composed of lowercase English letters only.

=====Input Format=====
The first line contains the integer, n.
The next n lines each contain a word.

=====Output Format=====
Output 2 lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.

#!/usr/bin/env python3

from collections import OrderedDict

def __starting_point():
    num = int(input().strip())
    history = OrderedDict()

    for _ in range(num):
        word = str(input().strip().split())
        if word not in list(history.keys()):
            history[word] = 1
        else:
            history[word] += 1

    print((len(list(history.keys()))))
    print((" ".join(map(str, list(history.values())))))

__starting_point()


Solve in Python:
=====Problem Statement=====
You are given the firstname and lastname of a person on two different lines. Your task is to read them and print the following:

    Hello firstname lastname! You just delved into python.

=====Input Format=====
The first line contains the first name, and the second line contains the last name.

=====Constraints=====
The length of the first and last name ≤ 10.

=====Output Format=====
Print the output as mentioned above.

# Enter your code here. Read input from STDIN. Print output to STDOUT
fname=input()
lname=input()
print(("Hello "+fname+" "+lname+"! You just delved into python."))


Solve in Python:
=====Problem Statement=====
You are given two sets, A and B.
Your job is to find whether set A is a subset of set B.

If set A is subset of set B, print True.
If set A is not a subset of set B, print False.

=====Input Format=====
The first line will contain the number of test cases, T.
The first line of each test case contains the number of elements in set A.
The second line of each test case contains the space separated elements of set A.
The third line of each test case contains the number of elements in set B.
The fourth line of each test case contains the space separated elements of set B.

=====Constraints=====
0<T<21
0<Number of elements in each set<1001

=====Output Format=====
Output True or False for each test case on separate lines.

for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines won't be counted.
    a = int(input()); A = set(input().split())
    b = int(input()); B = set(input().split())
    print(((A & B) == A))


Solve in Python:
>
**Note**: This kata is a translation of this (Java) one: http://www.codewars.com/kata/rotate-array. I have not translated this first one as usual because I did not solved it, and I fear not being able to solve it (Java is **not** my cup of... tea). @cjmcgraw, if you want to use my translation on your kata feel free to use it.

Create a function named "rotate" that takes an array and returns a new one with the elements inside rotated n spaces.

If n is greater than 0 it should rotate the array to the right. If n is less than 0 it should rotate the array to the left. If n is 0, then it should return the array unchanged.

Example:
```python
data = [1, 2, 3, 4, 5];

rotate(data, 1) # => [5, 1, 2, 3, 4]
rotate(data, 2) # => [4, 5, 1, 2, 3]
rotate(data, 3) # => [3, 4, 5, 1, 2]
rotate(data, 4) # => [2, 3, 4, 5, 1]
rotate(data, 5) # => [1, 2, 3, 4, 5]

rotate(data, 0) # => [1, 2, 3, 4, 5]

rotate(data, -1) # => [2, 3, 4, 5, 1]
rotate(data, -2) # => [3, 4, 5, 1, 2]
rotate(data, -3) # => [4, 5, 1, 2, 3]
rotate(data, -4) # => [5, 1, 2, 3, 4]
rotate(data, -5) # => [1, 2, 3, 4, 5]
```

Furthermore the method should take ANY array of objects and perform this operation on them:
```python
rotate(['a', 'b', 'c'], 1)     # => ['c', 'a', 'b']
rotate([1.0, 2.0, 3.0], 1)     # => [3.0, 1.0, 2.0]
rotate([True, True, False], 1) # => [False, True, True]
```

Finally the rotation shouldn't be limited by the indices available in the array. Meaning that if we exceed the indices of the array it keeps rotating.

Example:
```python
data = [1, 2, 3, 4, 5]

rotate(data, 7)     # => [4, 5, 1, 2, 3]
rotate(data, 11)    # => [5, 1, 2, 3, 4]
rotate(data, 12478) # => [3, 4, 5, 1, 2]
```

from numpy import roll

def rotate(arr, n):
  return list(roll(arr, n))


Solve in Python:
> "7777...*8?!??!*", exclaimed Bob, "I missed it again!  Argh!"  Every time there's an interesting number coming up, he notices and then promptly forgets.  Who *doesn't* like catching those one-off interesting mileage numbers?

Let's make it so Bob **never** misses another interesting number.  We've hacked into his car's computer, and we have a box hooked up that reads mileage numbers.  We've got a box glued to his dash that lights up yellow or green depending on whether it receives a `1` or a `2` (respectively).

It's up to you, intrepid warrior, to glue the parts together.  Write the function that parses the mileage number input, and returns a `2` if the number is "interesting" (see below), a `1` if an interesting number occurs within the next two miles, or a `0` if the number is not interesting.

**Note:** In Haskell, we use `No`, `Almost` and `Yes` instead of `0`, `1` and `2`.

## "Interesting" Numbers

Interesting numbers are 3-or-more digit numbers that meet one or more of the following criteria:

```if-not:ruby,python
* Any digit followed by all zeros: `100`, `90000`
* Every digit is the same number: `1111`
* The digits are sequential, incementing†: `1234`
* The digits are sequential, decrementing‡: `4321`
* The digits are a palindrome: `1221` or `73837`
* The digits match one of the values in the `awesomePhrases` array
```
```if:ruby,python
* Any digit followed by all zeros: `100`, `90000`
* Every digit is the same number: `1111`
* The digits are sequential, incementing†: `1234`
* The digits are sequential, decrementing‡: `4321`
* The digits are a palindrome: `1221` or `73837`
* The digits match one of the values in the `awesome_phrases` array
```

> † For incrementing sequences, `0` should come after `9`, and not before  `1`, as in `7890`.
> ‡ For decrementing sequences, `0` should come after `1`, and not before  `9`, as in `3210`.

So, you should expect these inputs and outputs:

```python
# "boring" numbers
is_interesting(3, [1337, 256])    # 0
is_interesting(3236, [1337, 256]) # 0

# progress as...

def is_interesting(number, awesome_phrases):
    def check(n):
        nonlocal awesome_phrases
        n = str(n)
        test0 = lambda x: len(x) > 2
        test1 = lambda x: set(x[1:]) == set("0")
        test2 = lambda x: len(set(x)) == 1
        test3 = lambda x: all((int(b) or 10) - (int(a) or 10) == 1 for a, b in zip(x, x[1:]))
        test4 = lambda x: all(int(a) - int(b) == 1 for a, b in zip(x, x[1:]))
        test5 = lambda x: x == x[::-1]
        test6 = lambda x: int(x) in awesome_phrases
        return test0(n) and (test1(n) or test2(n) or test3(n) or test4(n) or test5(n) or test6(n))
    return int((check(number) and 2) or (check(number+1) or check(number+2)))


Solve in Python:
> If you've finished this kata, you can try the [more difficult version](https://www.codewars.com/kata/5b256145a454c8a6990000b5).

## Taking a walk
A promenade is a way of uniquely representing a fraction by a succession of “left or right” choices.

For example, the promenade `"LRLL"` represents the fraction `4/7`.

Each successive choice (`L` or `R`) changes the value of the promenade by combining the values of the
promenade before the most recent left choice with the value before the most recent right choice. If the value before the most recent left choice was *l/m* and the value before the most recent right choice
was r/s then the new value will be *(l+r) / (m+s)*.

If there has never been a left choice we use *l=1* and *m=0*;
if there has never been a right choice we use *r=0* and *s=1*.

So let's take a walk.

* `""` An empty promenade has never had a left choice nor a right choice. Therefore we use *(l=1 and m=0)* and *(r=0 and s=1)*.
So the value of `""` is *(1+0) / (0+1) = 1/1*.
* `"L"`. Before the most recent left choice we have `""`, which equals *1/1*. There still has never been a right choice, so *(r=0 and s=1)*. So the value of `"L"` is *(1+0)/(1+1) = 1/2*
* `"LR"` = 2/3 as we use the values of `""` (before the left choice) and `"L"` (before the right choice)
* `"LRL"` = 3/5 as we use the values of `"LR"` and `"L"`
* `"LRLL"` = 4/7 as we use the values of `"LRL"` and `"L"`

Fractions are allowed to have a larger than b.

## Your task

Implement the `promenade` function, which takes an promenade as input (represented as a string), and returns
the corresponding fraction (represented as a tuple, containing the numerator and the denominator).

```Python
promenade("") == (1,1)
promenade("LR") == (2,3)
promenade("LRLL") == (4,7)
```
```Java
Return the Fraction as an int-Array:
promenade("") == [1,1]
promenade("LR") == [2,3]
promenade("LRLL") == [4,7]
```

*adapted from the 2016 British Informatics Olympiad*

def promenade(choices):
    if not choices: return (1, 1)
    (a, b) = promenade(choices[1:])
    return (a, a + b) if choices[0] == 'L' else (a + b, b)


Solve in Python:
> In information theory and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (i.e. insertions, deletions or substitutions) required to change one word into the other.

(http://en.wikipedia.org/wiki/Levenshtein_distance)

Your task is to implement a function which calculates the Levenshtein distance for two arbitrary strings.

def levenshtein(s, t):
    v = range(len(t)+1)
    for i, si in enumerate(s):
        w = [i+1]
        for j, tj in enumerate(t):
            w.append(min(w[j]+1, v[j+1]+1, v[j]+(si!=tj)))
        v = w
    return w[-1]


Solve in Python:
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process  --myjinxin2015 said

# Description:

In this Kata, we have to try to create a mysterious pattern.

Given a positive integer `m`, you can generate a Fibonacci sequence with a length of `m`:
```
1 1 2 3 5 8 13 21 34 ...
```

Given a positive integer `n`, you need to execute `%` operation on each element of the Fibonacci sequence:

```
m = 9, n = 3
Fibonacci sequence: 1 1 2 3 5 8 13 21 34
               ---> 1%3 1%3 2%3 3%3 5%3 8%3 13%3 21%3 34%3
               --->  1   1   2   0   2   2    1    0    1
```
Finally, make `n` rows string to show the pattern:

```
112022101
|||||||||
   o   o
oo    o o
  o oo
```

Please note:
* Each row is separated by `"\n"`;
* You should trim the end of each row;
* If there are some empty rows at the start or end of string, you should trim them too. But, if the empty row is in the middle(see the last example), you should not trim it.

# Examples:

For m = 5, n = 5, the output should be:
```
    o
oo
  o
   o
```
For m = 12, n = 4, the output should be:
```
     o     o
oo  o oo  o
  o     o
   o     o
```
For m = 1, n = 1, the output should be:`"o"`

For: m = 6, n = 15, the output should be:
```
oo
  o
   o

    o

     o
```

from itertools import islice

def fib():
    a, b = 1, 1
    while True:
        yield a
        a, b = b, a+b

def mysterious_pattern(m, n):
    board = [[' '] * m for _ in range(n)]

    for i, x in enumerate(islice(fib(), m)):
        board[x % n][i] = 'o'
    return '\n'.join(''.join(row).rstrip() for row in board).strip('\n')