I am trying to write a function that takes a sequence of numbers and determines if all the numbers are different from each other.
This was my first attempt
def differ(data):
for i in data:
print(i)
for j in data:
print(j)
if i==j:
return False
return True
print(differ([1,23,4,1,2,3,1,2]))
print(differ([1,2,3,4]))
1
1
False
1
1
False
Apparently, the for loop didn't loop over all the numbers in the data. Why did this happen?
I wrote another function using range().
def differ(data):
for i in range(1,len(data)):
print("i:",i)
for j in range(i):
print("j:",j)
if data[i]==data[j]:
return False
return True
print(differ([1,2,2,4,53]))
i: 1
j: 0
i: 2
j: 0
j: 1
False
It works, however, I don't understand why my first attempt didn't work.
Falseas soon as you have a match, and in your first snippet you have both loops start with the first element, Naturally, the first element is equal to itself.