1

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.

tommybee
  • 2,409
  • 1
  • 20
  • 23
srxprime13
  • 25
  • 1
  • 6

3 Answers3

1

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

pellucidcoder
  • 127
  • 3
  • 9
1

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:

ayplam
  • 1,943
  • 1
  • 14
  • 20
0

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
iamklaus
  • 3,720
  • 2
  • 12
  • 21