srxprime13
srxprime13

Reputation: 25

Trying to make a sorted list only have unique numbers

Here is my code:

def lotteryNumbers(m,n):
    newList = []
    uniqueList = []
    n=n+1
    for i in range(1, n):
        if i <= n:
            randomness = int(random.randint(1,m))         
            newList.append(int(randomness))
    for number in newList:
        if number not in newList:
         uniqueList.append(number)
    sortNewList = uniqueList.sort()
    print(newList)
    print(uniqueList)
    return uniqueList

but nothing is showing in uniqueList with the second for loop added. taken out, I get a list for newList, but the numbers aren't distinct. I'm trying to do it without using a set and more of a if item not in newList then append to uniqueList and return a sorted (ascending) list with unique numbers.

Upvotes: 1

Views: 179

Answers (3)

ayplam
ayplam

Reputation: 1953

Just to address some of OP's other questions since pellucidcoder's has provided a valid solution

Nothing shows up in uniqList because the second for loop:

  1. Loops through all items in newList
  2. Asks if the item is NOT in newList

Part 2 is never true because the item came from newList to start with so uniqList comes back empty. If you changed the order a little bit to:

Upvotes: 1

pellucidcoder
pellucidcoder

Reputation: 127

I would just do:

def lotteryNumbers(m,n):
    list = []
    counter = 0
    while (counter < n):
        r = int(random.randint(1,m))
        if (r not in list):
            list.append(r)
            counter+=1
    list.sort()
    return list

Or for a one-liner...

def lotteryNumbers(m,n):
    return random.sample(xrange(1, m), n)

https://docs.python.org/2/library/random.html

Upvotes: 1

iamklaus
iamklaus

Reputation: 3770

your statement if number not in newList is dubious since the numbers are in the list. So this is what I have done,just made a little change to your code. There are efficient ways to do this, which I think already has been posted

def lotteryNumbers(m,n):
    newList = []
    uniqueList = []
    n=n+1
    seen = 0
    for i in range(1, n):
        if i <= n:
            randomness = int(random.randint(1,m))         
            newList.append(int(randomness))
    for number in newList:
        if number is not seen:
            uniqueList.append(number)
            seen = number
    sortNewList = uniqueList.sort()
    print(newList)
    print(uniqueList)
    return uniqueList

Upvotes: 0

Related Questions