+ 1

Code is for counting the no. Of elements ocuring once or more. I wan to ask why after the first element its counting wrong??Help

lst=eval(input('Enter a list:')) length=len(lst) uniq=[] dupl=[] count=0 i=0 while i<length: element=lst[i]#the first element at first count=1#counts itself if element not in uniq and element not in dupl:#will be true for the first time i=+1 for j in range(i,length):#starts from second element at first if element==lst[j]: count+=1 else: print('Element',element,'Frequency',count) if count==1: uniq.append(element) else: dupl.append(element) else: i+=1 print('Original list',lst) print('Unique elements list',uniq) print('Duplicate elements list',dupl)

8th Dec 2020, 3:01 PM
Yogesh
Yogesh - avatar
3 Respostas
+ 8
Yogesh , if you just wanted to get a kind of counter for the elements of an iterable like list of string, it is recommended to rewrite the code. I would recommend you to start with a for loop version: ( there are several ways to do this task in less code or more elegant, but try to start with a for loop version) - use a for loop to iterate through the input list, but to get only unique values you have to convert it to a set before - use each value you get in the loop to count (using count() function) how often it appears in the input iterable - use the number of counts and the value from the loop to generate the output with print. It may sounds s big of complicated, but it is not. Here are thd first 2 lines of code - try to do do the rest by yourself: inp = [1,3,6,9,0,4,9,2,1,4,9,0,1,2] for i in set(inp): ... # it needs 3 or 4 lines more to get this output: 0 occurs 2 x times 1 occurs 3 x times 2 occurs 2 x times 3 occurs 1 x times 4 occurs 2 x times 6 occurs 1 x times 9 occurs 3 x times
8th Dec 2020, 5:14 PM
Lothar
Lothar - avatar
+ 3
Yogesh U r repeatedly increasing the value of "i" so it was the bug.. https://code.sololearn.com/c52hDpHgI75v/?ref=app Check python dictionary.... https://www.sololearn.com/learn/Python/2450/?ref=app Example code to count duplicate elements of the list list=[2,2,2,4,5,6,8,8,6,5,4] dictionary={} for i in list: if i in dictionary: dictionary[i]+=1 else: dictionary[i]=1 print(dictionary)
8th Dec 2020, 4:05 PM
Ajith
Ajith - avatar
+ 2
Search "list comprehension with condition" and the "set" container, this task can be done with two lines of code.
8th Dec 2020, 4:20 PM
rodwynnejones
rodwynnejones - avatar