简体   繁体   中英

what's the difference between iterator and array?

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.

I think Tim Roberts answer explains perfectly why your code is not working as you expect. I would like to complement the answer:

Answering your question

Arrays are similar to lists, one of the differences is that the former consists only of elements with the same data type. In the other hand, iterators are objects which you can iterate through, these objects must implement at least the following 2 methods on their respective classes: __iter__() and __next__()

Cool way to do what you want in 1 line

You can achieve what you want with this:

def differ(data):
    return len(set(data)) == len(data)


print(differ([1, 2, 3, 4]))  # True
print(differ([1, 23, 4, 1, 2, 3, 1, 2])) # False

So basically, the magic here happens when you use set() . Sets are similar to lists, but one of the main differences is that they can't have repeated elements. By transforming the list to a set you are removing every duplicated element, so if there is a difference in the length after casting to a set , it means there was at least one duplicated element.

The problem with your first attempt is that it will eventually compare the same number with itself.

In the sequence [1,2,3,4] the first function will start off with i=1 and j=1 . They are both looking at the first number in the list causing it to fail.

The second attempt avoids this by only looking at the numbers before it. range(i) doesn't actually include i , so j can only ever be less than i meaning they will never point to the same value in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM