Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple set operations in python

I am new to python and learning it now. I am practicing it online and came across with the below problem. I tried to solve it, however, though I am getting the expected result the online validator is saying it as wrong. Please suggest where I am going wrong.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

In a school, there are total 20 students numbered from 1 to 20. You’re given three lists named ‘C’, ‘F’, and ‘H’, representing students who play cricket, football, and hockey, respectively. Based on this information, find out and print the following:

  • Students who play all the three sports
  • Students who play both cricket and football but don’t play hockey
  • Students who play exactly two of the sports
  • Students who don’t play any of the three sports

Format:

Input:

3 lists containing numbers (ranging from 1 to 20) representing students who play cricket, football and hockey respectively.

Output:

4 different lists containing the students according to the constraints provided in the questions.

Examples: Input:

[[2, 5, 9, 12, 13, 15, 16, 17, 18, 19]
[2, 4, 5, 6, 7, 9, 13, 16]
[1, 2, 5, 9, 10, 11, 12, 13, 15]] 

Expected Output:

[2, 5, 9, 13]
[16]
[12, 15, 16]
[3, 8, 14, 20]

Below is my code

C = set(input_list[0])
F = set(input_list[1])
H = set(input_list[2])
A= set(range(1, 21))

print(sorted(list(C & F & H)))
print(sorted(list((C & F) - H)))
print(sorted(list(((C-F)&H | (C-H)&F))))
print(sorted(list(A-(C|F|H))))

I am not sure if A is really needed or not.

Thanks,

like image 253
user1618711 Avatar asked Oct 01 '18 15:10

user1618711


2 Answers

You're correct on all but the students who play exactly two of the sports, which should be:

(C|F|H) - (C^F^H)
like image 87
blhsing Avatar answered Sep 21 '22 13:09

blhsing


import ast,sys

input_str = sys.stdin.read()
input_list = ast.literal_eval(input_str)

C = input_list[0]
F = input_list[1]
H = input_list[2]
C = set(input_list[0])
F = set(input_list[1])
H = set(input_list[2])

print(sorted(list(C & F & H)))
print(sorted(list((C & F) - (C & F & H))))
print(sorted(list(((C & F) | (F & H) | (C & H)) - (C & F & H))))
print(sorted(list(set(range(1,21)) - (C | F | H))))
like image 39
mohi1618 Avatar answered Sep 18 '22 13:09

mohi1618