andraskiss.hu

Home / Development / Software Development / Python / HackerRank Challenges

HackerRank Python Challenges

In this article I show how I solved HackerRank Python challenges. The main purpose of the content is to present my acquired experiences primarily for learning purposes.

Other categories:

Introduction
Basic Data Types
Strings
Sets
Itertools
Collections
Built-Ins
Numpy
Others

Sets

Introduction to Sets

Task:

Now, let's use our knowledge of sets and help Mickey. Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.

Solution:

def average(array):
    arrset = set(array)
    arrSum = 0
    for i in arrset:
        arrSum += i
    
    return arrSum / len(arrset)
    

if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    result = average(arr)
    print(result)

Introduction to Sets

Task:

Now, let's use our knowledge of sets and help Mickey. Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.

Solution:

def average(array):
    arrset = set(array)
    arrSum = 0
    for i in arrset:
        arrSum += i
    
    return arrSum / len(arrset)
    

if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    result = average(arr)
    print(result)

No Idea!

Task:

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 i integer in the array, if i is part of A, you add 1 to your happiness. If i is part of B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.

Solution:

nm = input()
arr = input()
a = input()
b = input()

nm = nm.split()
n_amount = int(nm[0])
m_amount = int(nm[1])

arr = arr.split()
a = set(a.split())
b = set(b.split())

intersect = a.intersection(b)
a = a.difference(intersect)
b = b.difference(intersect)

####################

result = 0

for i in arr:
    if i in a:
        result += 1
    if i in b:
        result -= 1

        
print(result)

Symmetric Difference

Task:

Given 2 sets of integers, M and N, print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either M or N but do not exist in both.

Solution:

# Enter your code here. Read input from STDIN. Print output to STDOUT
mNum = input()
m = input()
mList = m.split(' ')

nNum = input()
n = input()
nList = n.split(' ')

mSet = set()
nSet = set()

for i in mList:
    mSet.add(i)
    
for i in nList:
    nSet.add(i)

mSet.symmetric_difference_update(nSet)

mList = list(mSet)
mListInt = list()

for i in range(len(mList)):
    mListInt.append(int(mList[i]))

mListInt.sort()
for i in mListInt:
    print(i)

Set .add()

Task:

Apply your knowledge of the .add() operation to help your friend Rupal. Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of N country stamps. Find the total number of distinct country stamps.

Solution:

n = input()

countries = set()

for i in range(int(n)):
    countries.add(input())

print(len(countries))

Set .discard(), .remove() & .pop()

Task:

You have a non-empty set s, and you have to execute N commands given in N lines. The commands will be pop, remove and discard.

Solution:

n = int(input())
s = set(map(int, input().split()))

num_of_commands = int(input())

for i in range(num_of_commands):
    command = input()
    if command.startswith('pop'):
        s.pop()
    elif command.startswith('remove'):
        c = command.split(' ')
        s.remove(int(c[1]))
    elif command.startswith('discard'):
        c = command.split(' ')
        s.discard(int(c[1]))

s_sum = 0
for i in s:
    s_sum += i

print(s_sum)

Set .union() Operation

Task:

The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed to only French and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and the other set is subscribed to the French newspaper. The same student could be in both sets. Your task is to find the total number of students who have subscribed to at least one newspaper.

Solution:

# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
n_students = input()
b = int(input())
b_students = input()

print(len(set(n_students.split(' ')).union(set(b_students.split(' ')))))

Set .intersection() Operation

Task:

The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed only to French, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to both newspapers.

Solution:

n = input()
n_num = input()
b = input()
b_num = input()

print(len(set(n_num.split()).intersection(set(b_num.split()))))

Set .difference() Operation

Task:

Students of District College have a subscription to English and French newspapers. Some students have subscribed to only the English newspaper, some have subscribed to only the French newspaper, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to only English newspapers.

Solution:

count1 = input()
set1 = input()
count2 = input()
set2 = input()

print(len(set(set1.split()).difference(set(set2.split()))))

Set .symmetric_difference() Operation

Task:

Students of District College have subscriptions to English and French newspapers. Some students have subscribed to English only, some have subscribed to French only, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to either the English or the French newspaper but not both.

Solution:

n1 = input()
s1 = input()
n2 = input()
s2 = input()

print(len(set(s1.split()).symmetric_difference(set(s2.split()))))

Set Mutations

Task:

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.

Solution:

num_of_elements = int(input())
elements = set(input().split())
n = int(input())

for i in range(n):
    command = input().split()
    c = command[0]
    if c == 'intersection_update':
        elements.intersection_update(set(input().split()))
    elif c == 'update':
        elements.update(set(input().split()))
    elif c == 'symmetric_difference_update':
        elements.symmetric_difference_update(set(input().split()))
    elif c == 'difference_update':
        elements.difference_update(set(input().split()))

s = 0
for i in elements:
    s += int(i)

print(s)

The Captain's Room

Task:

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.

Solution:

k = input()
elements = input().split()

d = dict()

for i in elements:
    if d.get(i) == None:
        d[i] = 1
    else:
        d[i] += 1

for i in d:
    if d[i] == 1:
        print(i)
        break

Check Subset

Task:

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.

Solution:

t = int(input())

for i in range(t):
    num_of_elements_a = int(input())
    elements_a = input().split()
    num_of_elements_b = int(input())
    elements_b = input().split()
    
    for j in elements_a:
        subset = True
        found = False
        for k in elements_b:
            if j == k:
                found = True
                break
        if found == False:
            subset = False
            break
    print(subset)

Check Strict Superset

Task:

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.

Solution:

a = input().split()
n = int(input())

superset = True

for i in range(n):
    elements = input().split()

    for j in elements:
        element_found = False
        for k in a:
            if j == k:
                element_found = True
        
        if element_found == False:
            superset = False

print(superset)