-2
def duplicate_count(text):
  text = text.upper()
  duplicate_count = 0
  for i in set(text):
      if text.count(i)>1:
          duplicate_count +=1

  return duplicate_count        
     

in the for loop why only set is used and not list or dict? In the for loop i in the set(text) will have duplicates right ?

Aditya
  • 17
  • 3
  • No, you won't have duplicates, that's the point of using `set`. Have you tried to replace `set` by `dict` or `list`? You will notice that it will not work or give wrong results. That's why `set` is used. – mkrieger1 Apr 19 '21 at 13:59
  • can you help me out with this statement text.count(i) . Does that mean the values in text counts for every iteration in i and match the similar character/integer ? – Aditya Apr 19 '21 at 14:58

2 Answers2

1

Look here.

print(set([1,2,2]))

gives us {1,2}. Basically in the code, they iterate through the given iterable and for every number they find how many times it is repeated. But say you had [2,2]. Well the number 2 is repeated twice so. We'll go through two twice increasing duplicateCount by one TWO times, but we want it to increase it once. So set works the best in this case.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
  • can you help me out with this statement text.count(i) . Does that mean the values in text counts for every iteration in i and match the similar character/integer ? – Aditya Apr 19 '21 at 14:41
  • Yeah so, text is our set. The count function is applied on the [1,2,2]. Say we had text.count(2) it will give us ```2``` because clearlly there are two 2's in the list. – Buddy Bob Apr 19 '21 at 15:21
1

In set all duplicates are removed.

Sets are unordered collections of distinct objects.

The common approach to get a unique collection of items is to use set

for example,

l=[1,2,3,4,4,4,5,5]
l1=set(l)
print(l1)

here we will get output as

{1, 2, 3, 4, 5}

Sets are generally used to get unique values from lists.

for more details on different ways to remove dupliates from list refer-

https://www.geeksforgeeks.org/python-ways-to-remove-duplicates-from-list/

Prathamesh
  • 1,064
  • 1
  • 6
  • 16
  • can you help me out with this statement text.count(i) . Does that mean the values in text counts for every iteration in i and match the similar character/integer ? – Aditya Apr 19 '21 at 14:59
  • text.count(i) counts the occurrence's of 'i' in text and if count is more than 1 which means that there are duplicates the duplicate_count is incremented by 1 – Prathamesh Apr 19 '21 at 15:28