Symmetric Difference

Received via email a message regarding the following HackerRank challenge: https://www.hackerrank.com/challenges/symmetric-difference?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign

I liked that a refresher / tutorial preceded the actual challenge.

If interested use the above mentioned link and read the requirements.

Following is a screen capture from the Python console from the Spider 3 IDE:

4 <== M

2 4 5 9

4 <== N

2 4 11 12

5

9

11

12

The first line contains the number of elements in the subsequent line. I did not use M to read the four integers. The next line contains the number of elements in the subsequent line. I did not use N to read the next four integers. I used M and N to verify that the program read the proper number of integers.

My code in Python follows:

# -*- coding: utf-8 -*-

import sys

# **** solution ****

M = int(input())

#print(“M:”, M)

# **** input a set of values ****

line = input()

#print(“line:”, line)

# **** split the values into a list ****

l = list(line.split())

#print(“l:”, l)

# **** check the number of elements read ****

if (len(l) != M):

    print(“len(l):”, len(l), “!=”, M)

    print(“<<< bye bye !!!”)

    sys.exit(-1)

# **** ****

l1 = list(map(int, l))

#print(“l1:”, l1)

# **** ****

N = int(input())

#print(“N:”, N)

# **** input a set of values ****

line = input()

#print(“line:”, line)

# **** split the values into a list ****

l = list(line.split())

#print(“l:”, l)

# **** check the number of elements read ****

if (len(l) != N):

    print(“len(l):”, len(l), “!=”, N)

    print(“<<< bye bye !!!”)

    sys.exit(-1)

# **** ****

l2 = list(map(int, l))

#print(“l2:”, l2)

# **** convert lists to sets ****

s1 = set(l1)

#print(“s1:”, s1)

s2 = set(l2)

#print(“s2:”, s2)

# **** get the symetric differences ****

sd = s1.difference(s2)

#print(“sd:”, sd)

dif = set(sd)

#print(“dif:”, dif)

sd = s2.difference(s1)

#print(“sd:”, sd)

dif = dif.union(sd)

#print(“dif:”, dif)

#print(“type(dif):”, type(dif))

# **** convert set to list ****

l = list(dif)

#print(“l:”, l)

# **** sort the list ****

l.sort()

# **** print the sorted list ****

for e in l:

print(e)

# **** reverse the list ****

#l.reverse()

#print(“l:”, l)

The code passed the 10 test cases.

If you have comments or questions regarding this or any other entry in this blog, please do not hesitate and send me a message. Will reply ASAP and will not use your name unless you explicitly allow me to do so.

John

john.canessa@gmail.com

Follow me on Twitter: #john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *