Issue
I am confused when running the following code which was an exercise on sets. The elements in the set name 's' contains Boolean value True. But, its is not recognized or printed always. Please see the comments for details. The same is not the case for the second set 's1'. Can someone try to tell me what is wrong here .
This is the code :
s = {1,2,32,2,True,"Trial"}
s1 = { 5, False, True, 32}
print("s is : ", s) # Element True is missing in the output
print("s1 is : ", s1)
print("Union : ",s.union(s1)) # Element True is missing in the output
print("Difference : ",s.difference(s1))
print("Intersection : ", s.intersection(s1)) # Element True is present in the output
print("Elements in s : ",*s) # Element True is missing in the output of s
print("Elements in s1 : ",*s1) # Element True is printed in the output of s1
if (True in s ) :
print("True is truely in s")
else:
print("True not found in s")
if (False in s ) :
print("False is truely in s")
else:
print("Fasle not found in s")
for itm in s :
print(itm, " : ", type(itm)) # Element True is missing in the output
# *** ??? the elemment True in s is printed only in the intersection
The output I got is this
s is : {32, 1, 2, 'Trial'}
s1 is : {False, True, 32, 5}
Union : {32, 1, 2, False, 5, 'Trial'}
Difference : {2, 'Trial'}
Intersection : {32, True}
Elements in s : 32 1 2 Trial
Elements in s1 : False True 32 5
True is truely in s
Fasle not found in s
32 : <class 'int'>
1 : <class 'int'>
2 : <class 'int'>
Trial : <class 'str'>
[Done] exited with code=0 in 0.144 seconds
Solution
The reason is that (for largely historical reasons) True
in Python is a sort of synonym for 1
. So True
and 1
have the same value, and a set can't contain duplicate values.
>>> {1} == {True}
True
>>> len({1, True})
1
>>> True in {1}
True
>>> 1 in {True}
True
True
appears the intersection because the representation of the value 1
that you see depends on the order of evaluation of the expression.
>>> s.intersection(s1)
{32, True}
>>> s1.intersection(s)
{32, 1}
You will get the same sort of behaviour if you try to create a set with the two values 0
and False
(result {0}
or {False}
depending on the order of the expression) or a set with the two values 1
and 1.0
(result {1}
or {1.0}
depending on the order of the expression).
Answered By - BoarGules Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.