Hacker Rank Python Challenges

Python Version 3

Problems

  1. Introduction to Sets
  2. No Idea
  3. Symmetric Difference
  4. Set .add()
  5. Set .discard(), .remove() & .pop()
  6. Set .union() Operation
  7. Set .intersection() Operation
  8. Set .difference() Operation
  9. Set .symmetric_difference() Operation
  10. Set Mutations
  11. The Captain’s Room
  12. Check Subset
  13. Check Strict Superset

Introduction to Sets

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Validate user input, constraints 0 < len(string) <= 100.
  3. Convert given list to set to get distinct values.
  4. Calculate the length of set.
  5. Calculate the sum of set.
  6. Finally, calculate and return average.

Solution:

def is_valid_input(N):
    if(N > 0 and N <= 100):
        return True
    return False


def average(array):
    length = len(array)
    if(is_valid_input(length)):
        distinct_items = set(array)
        distinct_items_length = len(distinct_items)
        return sum(distinct_items)/distinct_items_length
        

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

No Idea!

Problem -> URL
Difficulty Level: Medium

Pseudocode:

  1. Read input from user.
  2. Get the user input and build the input_list, set_a and set_b.
  3. Instantiate a variable result with 0.
  4. For each number in the input_list,
    • If number in set_a then we will add 1 to our result.
    • If number in set_b then we will subtract 1 from our result.
    • Finally, print the result.

Solution:

def solution(set_a, set_b, input_list):
    result = 0
    for i in input_list:
        if i in set_a:
            result += 1
        elif i in set_b:
            result -= 1
    return result
        
if __name__ == '__main__':
    n, m = map(int, input().split(" "))
    input_list = map(int, input().split(" "))
    set_a = set(map(int, input().split(" ")))
    set_b = set(map(int, input().split(" ")))
    result = solution(set_a, set_b, input_list)
    print(result)

Symmetric Difference

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Create a list of int for the two given input strings.
  3. Instantiate an empty set.
  4. Convert both list to set.
  5. Update the empty set with difference of set_a and set_b.
  6. Update the empty set with difference of set_b and set_a.
  7. Finally, sort the result set and print the result.

Solution:

def solution(list_a, list_b):
    result = set()
    set_a = set(list_a)
    set_b = set(list_b)
    result.update(set_a.difference(set_b))
    result.update(set_b.difference(set_a))
    for i in sorted(result):
        print(i)

if __name__ == '__main__':
    n1 = int(input())
    list_a = map(int, input().split(" "))
    n2 = int(input())
    list_b = map(int, input().split(" "))
    solution(list_a, list_b)

Set .add()

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Vaidate user input, constraints 0 < N < 1000.
  3. Instantiate a empty set.
  4. For each user input add the name to the set.
  5. Finally, print the length of set.

Solution:

def is_valid_input(N):
    if(N > 0 and N < 1000):
        return True
    return False


def solution(N):
    if(is_valid_input(N)):
        my_set = set()
        for i in range(N):
            my_set.add(input())
        print(len(my_set))
        
        
if __name__ == '__main__':
    N = int(input())
    solution(N)

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

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Vaidate user input, constraints 0 < n, N < 20.
  3. Iterate thru range of N, get input from user and apply the operations.
  4. Finally, print sum of values for the set.

Solution:

def is_valid_input(n, N):
    if((n > 0 and n < 20) and (N > 0 and N < 20)):
        return True
    return False


def solution(n, input_set, N):
    if(is_valid_input(n,N)):
        for i in range(N):
            user_input = input().split(" ")
            operation = user_input[0].strip().lower()
            if(operation == "pop" and len(input_set) != 0):
                input_set.pop()
            elif(operation == "remove" and (int(user_input[1]) in input_set)):
                input_set.remove(int(user_input[1]))
            elif(operation == "discard" and (int(user_input[1]) in input_set)):
                input_set.discard(int(user_input[1]))
    print(sum(input_set))

if __name__ == '__main__':
    n = int(input())
    input_set = set(map(int, input().split(" ")))
    N = int(input())
    solution(n, input_set, N)

Set .union() Operation

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Create a set out of students subscribed to english paper.
  3. Create a set out of students subscribed to french paper.
  4. Do union of students subscribed to english paper and french paper.
  5. Finally, print length of the unioned set.

Solution:

if __name__ == '__main__':
    n = int(input())
    e_students = set(map(int, input().split(" ")))
    N = int(input())
    f_students = set(map(int, input().split(" ")))
    union_students = e_students.union(f_students)
    print(len(union_students))

Set .intersection() Operation

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Create a set out of students subscribed to english paper.
  3. Create a set out of students subscribed to french paper.
  4. Do intersection of sets to get students subscribed to both english and french paper.
  5. Finally, print length of the resultant set.

Solution:

if __name__ == '__main__':
    n = int(input())
    e_students = set(map(int, input().split(" ")))
    N = int(input())
    f_students = set(map(int, input().split(" ")))
    e_f_students = e_students.intersection(f_students)
    print(len(e_f_students))

Set .difference() Operation

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Create a set out of students subscribed to english paper.
  3. Create a set out of students subscribed to french paper.
  4. Do difference on sets to get students who only subscribed to english paper.
  5. Finally, print length of the resultant set.

Solution:

if __name__ == '__main__':
    n = int(input())
    e_students = set(map(int, input().split(" ")))
    N = int(input())
    f_students = set(map(int, input().split(" ")))
    only_e_students = e_students - f_students
    print(len(only_e_students))

Set .symmetric_difference() Operation

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Create a set out of students subscribed to english paper.
  3. Create a set out of students subscribed to french paper.
  4. Do symmetric_difference on sets to get students who only subscribed either english or french paper and not both.
  5. Finally, print length of the resultant set.

Solution:

if __name__ == '__main__':
    n = int(input())
    e_students = set(map(int, input().split(" ")))
    N= int(input())
    f_students = set(map(int, input().split(" ")))
    only_e_or_f_students = e_students.symmetric_difference(f_students)
    print(len(only_e_or_f_students))

Set Mutations

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Create a set_a out of input provided by user.
  3. For i in range of N operations, get the operation and new set from user.
  4. Perform operations.
  5. Print sum of resultant set.

Solution:

if __name__ == '__main__':
    n = int(input())
    set_a = set(map(int, input().split(" ")))
    N = int(input())
    for i in range(N):
        user_operation = None
        other_set = None
        for j in range(2):
            if j == 0:
                user_operation = input().split(" ")
            else:
                other_set = set(map(int, input().split(" ")))
        operation = user_operation[0].strip().lower()
        other_set_length = int(user_operation[1])
        if operation == "intersection_update" :
            set_a.intersection_update(other_set)
        elif operation == "symmetric_difference_update" : 
            set_a.symmetric_difference_update(other_set)
        elif operation == "difference_update":
            set_a.difference_update(other_set)
        elif operation == "update":
            set_a.update(other_set)
    print(sum(set_a))      

The Captain’s Room

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. Iterate through member list.
  3. Instanitate an empty dictionary.
  4. For each member in the list,
    • If member’s room not in dict add room number as key and instantiate count by 1.
    • If member’s room in dict increase the count by 1.
    • If count of member’s in a room is equal to K we can drop the room from the dict.
    • Finally, the dict will contain only room details for caption.
    • We can popitem from the dict and return the room number for captain.

Solution:

def solution(k, members):
    rooms = {}
    for i in members:
        if i not in rooms:
            rooms[i] = 1
        else:
            rooms[i] += 1
        if rooms[i] == k:
            del rooms[i]
    result = rooms.popitem()
    return result[0]
            
if __name__ == '__main__':
    k = int(input())
    members = list(map(int, input().split(" ")))
    result = solution(k, members)
    print(result)   

Check Subset

Problem -> URL
Difficulty Level: Easy

Pseudocode:

  1. Read input from user.
  2. For each Test case, we need to get two sets from user.
  3. Get the intersecting set for set_a and set_b.
  4. Compare the intersecting set with set_a.
  5. If both are same, print True else print False.

Solution:

if __name__ == '__main__':
    T = int(input())
    for i in range(T):
        set_a_length = None
        set_a = None
        set_b_length = None
        set_b = None
        for j in range(4):
            if j == 0:
                set_a_length = int(input())
            elif j == 1:
                set_a = set(map(int, input().split()))
            elif j == 2:
                set_b_length = int(input())
            elif j == 3:
                set_b = set(map(int, input().split()))
        if (set_a.intersection(set_b)) == set_a:
            print(True)
        else:
            print(False)

Check Strict Superset

Problem -> URL
Difficulty Level: Easy

Check Superset definition here.

Pseudocode:

  1. Read input from user.
  2. Create a set for user input,
  3. Iterate n times and for each iteration get new input set from user.
  4. For each new set,
    • If len(input_set - new_set) == 0 and len(new_set - input_set) != 0, then new_set is subset of input_set and input_set is super set of new_set.
    • If any one of the new_set doesn’t satisfies the above condition then we will return False.
    • If all new_set satisfies the above condition then we will return True.

Solution:

def solution(input_set, n):
    for i in range(n):
        new_set = set(map(int, input().split(" ")))
        if not((len(new_set.difference(input_set)) == 0) and (len(input_set.difference(new_set)) != 0)):
            return False
    return True
        

if __name__ == '__main__':
    input_set = set(map(int, input().split(" ")))
    n = int(input())
    result = solution(input_set, n)
    print(result)