Home > OS >  Number of distinct elements in python list (without set function)
Number of distinct elements in python list (without set function)

Time:10-22

I have the exercise below, but I cannot work it out, the code below is only the demostrate an attempt, I have tried several others. Maybe someone can shed some light. If I use a nested for loop it only procudes the cartesian product with all possible combinations. But obviously I am missing something

Given a sequence of numbers with all of its elements in ascending order, returns the quantity of distinct elements in it.

Input: 1 1 2 3 3

Output: 3

and you cannot use set:


my_list=[1, 1, 2, 2, 2, 3, 5 ,6]
count=0
for x in my_list:
  if x ==2:
    count = count  1

print (count)

CodePudding user response:

Thanks to Mahrkeenerh, I think this works and it is simple

my_list=[2, 2, 2, 2, 2, 2, 3,3 ,2]
new_list=[]
for x in my_list:
   if x not in new_list:
    new_list.append(x)
count=0
for k in new_list:
  count = count 1
print (count)

CodePudding user response:

my_list = [1, 1, 2, 2, 2, 3, 5, 6]
count = 0
n = len(my_list)
i = 0
while i < n:
    while (i < n - 1 and my_list[i] == my_list[i   1]): # Move ahead if there are duplicates
        i  = 1
    count  = 1
    i  = 1

print(count)

CodePudding user response:

iterate though you list and add new values to another list then print the length of the new list

my_list = [1, 1, 2, 2, 2, 3, 5, 6]
unique_list = []
for i in my_list:
    if i not in un_l:
        unique_list.append(i)
print(len(unique_list))

CodePudding user response:

The key is all of its elements in ascending order, which means the list is already sorted and all you need to do is to compare element n and n 1.

my_list=[1, 1, 2, 2, 2, 3, 5, 6]

cur, total = None, 0

for i in my_list:
    if cur != i:
        cur = i
        total  = 1

print (total)
# 5

CodePudding user response:

Alternatively you could try this: (try to follow OP's logic and make minor tweaking to work) And this approach does not create extra data structure or need more space, in case the given list is huge. Also, we try to take advantage of the characteristic of this list - "with all of its elements in ascending order" to make the code simpler.

my_list=[1, 1, 1, 1, 2, 3, 4, 5]
count = 1              # init the counter as 1, assuming it's not an empty list

for x,y in  zip(my_list, my_list[1:]):
    if x != y:
        count  = 1
        

print (count)  # 5

More examples: lst = [1, 1, 1, 1, 1]

print(count)       #  1
  • Related