+ 2

Why we use ^ operator

Arr=[1,2,1,5,5] Res=0 For i in arr: Res ^=I Print (res) Question is to find number which is only once repeated

1st Apr 2020, 11:10 AM
Sai Deepika Kathiri
Sai Deepika Kathiri - avatar
8 odpowiedzi
+ 3
With integers ^ is a "bitwise exclusive or" operation (xor). The result in each bit position is 1 if bits of operands are differ in that bit position and 0 if they are the same. If you do a xor operation on two equal numbers then the result will be zero. 2^2 = 0 If you do xor operation on any number and zero then the result will be the same number. 2^0 = 2 when you do xor operation in a loop on numbers which are duplicated even number of times, they all are zero out each other: 1^2^1^5^5 = (1^2^1)^5^5 xor is commutative operation 1^2^1 is the same as 1^1^2 ==> (1^1)^2 1^1 = 0 (1^1)^2 = 0^2 = 2 ==> (1^2^1)^5^5 = 2^5^5 2^5^5 is the same as 5^5^2 ==> (5^5)^2 5^5=0 (5^5)^2 = 0^2 = 2 so the result is 2, the number that appears in the list only once
1st Apr 2020, 12:31 PM
andriy kan
andriy kan - avatar
+ 4
This a quick try and not perfect. But it's doing the job: arr=[1,2,3,1,5,5,8] res = [] for i in arr: for j in arr: if i ^ j == 0: res.append(i) if len(res) == 1: print(f'number {res[0]} appears {len(res)} x') res = [] # result is: ''' number 2 appears 1 x number 3 appears 1 x number 8 appears 1 x '''
1st Apr 2020, 1:14 PM
Lothar
Lothar - avatar
+ 2
Thank you so much.... andriy kan For clear explanation.
1st Apr 2020, 1:12 PM
Sai Deepika Kathiri
Sai Deepika Kathiri - avatar
+ 2
Ok tq😊
1st Apr 2020, 1:15 PM
Sai Deepika Kathiri
Sai Deepika Kathiri - avatar
+ 2
Hima, from which approach are talking about? As we have multiple approaches here, it would be nice if you could specify it a bit. Thanks! BTW, arr[]={1,2,3,10,11} is not a valid python expression that causes a syntax error.
2nd Apr 2020, 10:26 AM
Lothar
Lothar - avatar
0
Well there's a problem with your approach if the array is arr[]={1,2,3,10,11} as 3 in binary is 011 and 2 in binary is 010 outputs:1
1st Apr 2020, 11:17 PM
Hima
Hima - avatar
0
Lothar taking xor with every array element. It's a C/C++ style array .
3rd Apr 2020, 4:19 AM
Hima
Hima - avatar
0
Xor operator works on bits If odd no of inputs are then the result is true otherwise false. Suppose you have two no 2 and 3 In binary , they are represented as 10 and 11 Now 10^11 2 = 10 3 = 11 01 Bit by bit manipulation takes place . That's why if there are two same no then there xor would be zero
17th Apr 2020, 1:13 PM
Digvijay Singh Rathore
Digvijay Singh Rathore - avatar