-1

I have to solve this problem like below manner only, As you see in output, The only wrong thing in output I get is, 4 and 5 are count two times, How I can get rid of this, please improvise below code only. do not change the code completely.

n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
while i<len(n):
  a=0
  count=0
  while a<len(n):
    if n[i]==n[a]:
      count=count+1
    a=a+1
  print(n[i],"present",count,"times")
  i=i+1

output:

1 present 1 times
2 present 1 times
3 present 1 times
4 present 2 times
4 present 2 times
5 present 2 times
5 present 2 times
Random Davis
  • 6,662
  • 4
  • 14
  • 24

4 Answers4

1

you can use a Counter to do this efficiently https://docs.python.org/3/library/collections.html#collections.Counter

from collections import Counter

n = [1,2,3,4,4,5,5]

c = Counter(n)

for val, count in c.items():
   print(f"{val} present {count} times")

prints:

1 present 1 times
2 present 1 times
3 present 1 times
4 present 2 times
5 present 2 times
Anentropic
  • 32,188
  • 12
  • 99
  • 147
1

I purpose to use set to do so. Does it suit your needs?

n_list = [1,2,3,4,4,5,5]
n_set = set(n_list)
for i in n_set:
  print(i, " present ", n_list.count(i), "times")
1

Sticking to your original code and not the other many ways to solve this using libraries and dictionaries and whatnot.

You can check to see if you the item you are counting has already occurred in the list and skip processing it.

n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
while i<len(n):
  a=0
  count=0
  
  #check if this value has already been encountered in the list
  if n[i] not in n[:i]: 
    while a<len(n):
        if n[i]==n[a]:
            count=count+1
        a=a+1
    print(n[i],"present",count,"times")
  i=i+1

If that's too advanced (in the event this is homework). You could create a second list to keep track of the values you've already checked:

n=[1,2,3,4,4,5,5]
i=0
a=0
count=0
n2=[]
while i<len(n):
  a=0
  count=0
  if n[i] not in n2: 
    while a<len(n):
        if n[i]==n[a]:
            count=count+1
        a=a+1
    print(n[i],"present",count,"times")
    n2.append(n[i])
  i=i+1
JNevill
  • 46,980
  • 4
  • 38
  • 63
0

in general we should use a for loop if we iterate over a sequence because it's length is known. doing so avoids the need of helper variables. the code for this approach looks more clean and readable (2)

to get rid of the problem of duplicating outputs, we can use a list like seen (1). if a number is not in seen (3), we can print it out. to get the total number of occurrences of the number, we use nums.count(nums) (4). in the step after this, we add the current number used to the list 'seen' (5). if the number is already in the list 'seen', the loop will take the next number from the input list.

nums = [1,2,3,4,4,5,5]
seen = [] # (1)
for num in nums: # (2)
    if num not in seen: # (3)
        print(num,"present",nums.count(num),"times") # (4)
        seen.append(num) # (5)
lroth
  • 367
  • 1
  • 2
  • 4