0

I have the exercise below, but I cannot work it out, the code below is only the demonstration attempt, I have tried several others. Maybe someone can shed some light. If I use a nested for loop it only produces 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 number 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)
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Emilia Delizia
  • 333
  • 3
  • 14

3 Answers3

2

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)
Emilia Delizia
  • 333
  • 3
  • 14
0
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)
Nitin Singla
  • 106
  • 2
  • 9
0

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))