I've an array arr = [4, 8, 2, 8, 9].
I want to print the elements that doesn't repeat.
i.e. 4, 2, 9
but my code is giving list index out of range even though the same logic is working in Java but not in my Python code. Here is my code:
def odd_occurring_num(arr):
count = 0
size = len(arr)
for i in arr:
for j in arr:
if (arr[i] == arr[j] and i != j):
break
if (j == size):
count += 1
return count
# driver Code
arr = [4, 8, 2, 8, 9]
print(odd_occurring_num(arr))
You don't even need to import modules, Python has it all built in
arr = [4, 8, 2, 8, 9]
def odd_occurring_num(arr):
return [i for i in arr if arr.count(i) < 2]
print(odd_occurring_num(arr))
what you did:
for i in arr:
arr[i] = ...
will actually iterate through the items of array, so you are getting arr[4] which is 9, then arr[8] which is not defined as you list is only 5 elements.
What you can do is:
for i, elem in enumerate(arr):
arr[i] = ...
which will iterate over the index i and the elements itself
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With