-5

I want to print the top 10 distinct elements from a list:

top=10
test=[1,1,1,2,3,4,5,6,7,8,9,10,11,12,13]
for i in range(0,top):
    if test[i]==1:
        top=top+1
    else:
        print(test[i])

It is printing:

2,3,4,5,6,7,8

I am expecting:

2,3,4,5,6,7,8,9,10,11

What I am missing?

khelwood
  • 55,782
  • 14
  • 81
  • 108
NoobCoder
  • 625
  • 1
  • 5
  • 18
  • You are missing that the index `i` should take values `0, 1, ... ,9`, but your top 10 distinct elements have index values `0, 1,2,3,4,5,6,7,8,9,10,11,12,13`. – Micha Wiedenmann Dec 11 '18 at 12:32
  • If you want top 10 distinct value, then the output should be ```1, 2, 3, 4, 5, 6, 7, 8, 9, 10```. Why would it be ```2, 3, 4, 5, 6, 7, 8, 9, 10, 11```? – JiaHao Xu Dec 12 '18 at 02:08

3 Answers3

1

Since you code only executes the loop for 10 times and the first 3 are used to ignore 1, so only the following 3 is printed, which is exactly happened here.

If you want to print the top 10 distinct value, I recommand you to do this:

# The code of unique is taken from [remove duplicates in list](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists)
def unique(l):
    return list(set(l))

def print_top_unique(List, top):
    ulist = unique(List)

    for i in range(0, top):
        print(ulist[i])

print_top_unique([1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 10)
JiaHao Xu
  • 2,452
  • 16
  • 31
1

Using numpy

import numpy as np
top=10
test=[1,1,1,2,3,4,5,6,7,8,9,10,11,12,13]
test=np.unique(np.array(test))
test[test!=1][:top]

Output

array([ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
mad_
  • 8,121
  • 2
  • 25
  • 40
0

My Solution

test = [1,1,1,2,3,4,5,6,7,8,9,10,11,12,13]
uniqueList = [num for num in set(test)] #creates a list of unique characters [1,2,3,4,5,6,7,8,9,10,11,12,13]

for num in range(0,11):
    if uniqueList[num] != 1: #skips one, since you wanted to start with two
        print(uniqueList[num])
Community
  • 1
  • 1