How can I make this code more simpler? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How can I make this code more simpler?

Task: . Complete the following function that returns true if a list lst contains duplicate elements; it returns false if all the elements in lst are unique. For example, the list [2, 3, 2, 1, 9] contains duplicates (2 appears more than once), but the list [2, 1, 0, 3, 8, 4] does not (none of the elements appear more than once). An empty list has no duplicates. The function does not affect the contents of the list. My code: def has_duplicates(lst): n = len(lst) count = 0 for i in range(n): same = i for j in range(i+1, n): if lst[same] == lst[j]: count += 1 if count == 0: return False else: return True def main(): a = [1,3,4,5,6,7,7,8] b = [1,2,3,4,5,6,8,7,9] print(has_duplicates(a)) print(has_duplicates(b)) main() Question: Is there a way that this code can be made better if we used binary search?

19th May 2020, 1:37 PM
Sherlock 1247
Sherlock 1247 - avatar
3 Answers
+ 4
dup_a = set(a) if len(dup_a) < a: print('it has duplicates') else: print('no duplicates) same goes for b list because a set does not allow duplicates, you can verify the length of both variables. if dup_a is smaller than list a, it means the duplicates were removed, therefore it had duplicates
19th May 2020, 1:43 PM
Sebastian Pacurar
Sebastian Pacurar - avatar
+ 4
set() is a constructor and converts the list into a set of values. just like list() converts other types into a list of values. the syntactic sugar for empty list is like this a = [] while for an empty set is like this: a = set() because even though it has curly braces instead of brackets, if you do this: a = {} => it is an empty dictionary
19th May 2020, 1:47 PM
Sebastian Pacurar
Sebastian Pacurar - avatar
+ 1
When you talk about simplifying it, you can use set. def has_duplicates(lst): return len(lst) != len(set(lst)) Binary search needs sorted lists. So it does not help us: a) If we have to sort it, we have to look at each entry also. b) If it is sorted, then we need no search. We can just check if the next element is equal to the current one in a loop. You can make it more performant by creating an empty set and adding via a loop which breaks when adding had no effect.
19th May 2020, 1:46 PM
Manu_1-9-8-5
Manu_1-9-8-5 - avatar