0

Program to check if a list hasan element appearing more than once.Can someone explain the logic of this code?i

I don't understand how -if( t[i]==t[I+1])checks for every value.it will only check adjacent values ?can someone explain how it checks every value and please explain why can't I use t[i]==t[i:]? def has_duplicates(s): # make a copy of t to avoid modifying the parameter t = list(s) t.sort() # check for adjacent elements that are equal for i in range(len(t)-1): if t[i] == t[i+1]: return True return False print(has_duplicates([1,3,4,5,3]))

4th Nov 2018, 11:50 AM
Mara
2 Respostas
0
Remember a[start:end] # items start through end-1 a[start:] # items start through the rest of the array a[:end] # items from the beginning through end-1 a[:] # a copy of the whole array If you use t[i:] in this case you will check this values [3] [] [5, 3] Now you right about the code. This code only check with a adjacent value is duplicate. If you only want to check with a value is duplicate you can use set. set is and i quote " an unordered collection with no duplicate elements. " Python3 documentation. Using this you only needs to check with the length of list have the length of set. Look this code: https://code.sololearn.com/c6A5P4zBP86D/#py For more reference: https://docs.python.org/3/tutorial/datastructures.html. Python3 documentation
4th Nov 2018, 12:09 PM
Anya
Anya - avatar
0
You are righy in that it does only check adjacent values, but the reason it works lies a little above that: t.sort() This line means that all the elements in the list will be in numerical order (lowest to highest) so, if there are any repeated numbers in the list, they will be next to each other.
4th Nov 2018, 4:17 PM
Russ
Russ - avatar