forked from ayusharma/Hackerrank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset_discard_pop.py
115 lines (92 loc) · 2.15 KB
/
set_discard_pop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""
Problem Statement
.remove(x)
This operation removes element x from set.
If element x is not in the set, it raises a KeyError.
.remove(x) operation returns None.
Example
>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.remove(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.remove(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.remove(0)
KeyError: 0
.discard(x)
This operation also removes element x from set.
But if element x is not in the set, it does not raises a KeyError.
.discard(x) operation returns None.
Example
>>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> s.discard(5)
>>> print s
set([1, 2, 3, 4, 6, 7, 8, 9])
>>> print s.discard(4)
None
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
>>> s.discard(0)
>>> print s
set([1, 2, 3, 6, 7, 8, 9])
.pop()
This operation removes and return an arbitrary element from set.
If there are no elements to remove, it raises a KeyError.
Example
>>> s = set([1])
>>> print s.pop()
1
>>> print s
set([])
>>> print s.pop()
KeyError: pop from an empty set
Task
You have a non-empty set s and you have to execute N commands given in N lines.
Commands will be pop, remove and discard.
Input Format
First line contains integer n, number of elements in set.
Second line contains space separated elements of set s. All elements are non-negative integers, less than or equal to 9.
Third line contains integer N, number of commands.
Next N lines contains pop, remove and discard commands.
Constraints
0<n<20
0<N<20
Output Format
Print sum of elements of set 's' in output.
Sample Input
9
1 2 3 4 5 6 7 8 9
10
pop
remove 9
discard 9
discard 8
remove 7
pop
discard 6
remove 5
pop
discard 5
Sample Output
4
Explanation
On application of these 10 operations on set, we get set([4]). Hence, sum is 4.
Note : Convert elements of set s to integers while assigning. To ensure proper input of set we have added, first two lines of code to the editor.
"""
n = input()
s = set(map(int, raw_input().split()))
a = input()
for i in xrange(a):
k = []
k = raw_input().split()
if k[0] == 'pop':
s.pop()
elif k[0] == 'remove':
s.remove(int(k[1]))
elif k[0] == 'discard':
s.discard(int(k[1]))
else:
print 'not a command'
print sum(s)