Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Help with a practice Lottery

I have two function

Player picking the numbers and Computer randomlyy picking the numbers.

There will be a count counter.

I wanted the program to work in a way that after the player picks, the computer will generate the six random numbers, then compare to the numbers picked by players.

If the computer numbers are not the same with the numbers with the player, the computer will restart and generate a new set of numbers, and add 1 to the counter.

Once both players and computer numbers are the same, it will print out the numbers and how many tries it made before getting the same result.

import random


playerPick = []
lotteryPick = []
lottoDraw = 0
lottoNum = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
    21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
    31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49
]

def player_pick():

    print("Please pick six numbers for the lottery.")
    while True:
        if len(playerPick) < 6:
            pickNumber = int(input("> "))
            playerPick.append(pickNumber)            
            playerOrder = sorted(playerPick)

        else:
            print(playerOrder)
            print("Best of luck!")
            break

def lottery_pick():   
    while True:
        if len(lotteryPick) < 6:
            randomPick = random.choice(lottoNum)
            lotteryPick.append(randomPick)
            lottoNum.remove(randomPick)
            lotteryOrder = sorted(lotteryPick) 

        else:
            print(lotteryOrder)
            break


player_pick()
lottery_pick()

i tried different things but I just cant do it .

2 Answers

Lets work with your requirements:

I have two function

  • Player picking the numbers
def player_pick():
    print("pick a number")
    num = input()
    return num
  • and Computer randomlyy picking the numbers.
import random
def comp_pick():
    return random.randint(1, 50)
    #selecting random number between 1 and 50

There will be a count counter.

count =0 

I wanted the program to work in a way that after the player picks, the computer will generate the six random numbers, then compare to the numbers picked by players.

If the computer numbers are not the same with the numbers with the player, the computer will restart and generate a new set of numbers, and add 1 to the counter.

Once both players and computer numbers are the same, it will print out the numbers and how many tries it made before getting the same result.

player_num = []
comp_num = []
player_num.append(player_pick())
comp_num.append(comp_pick())

for num in player_num:
    if num in comp_num:
        if "this is the last element":
            #check if the current element is last element in player_num, you can use index for that purpose. (range(0, len(player_num))
            print("Number Matched")
    else:
        #increase the count only any element is not matched as in any case the collection of elements is not gonna match the set of other elements
        count += 1
        break;

This is a small code for one number, but you got that too.

I'd add more but it would be feeding, and you will hate it too.

so let me give you an idea and we'll take it from there.

if you can do it for one number you can do it for 6 numbers. Remember to check that each number from player_num list, is present in comp_num. (there are many possibilities that arises here but you can take care of them once you get a basic functionality.)

Also, i believe there should not be a need for sorting as it would just increase the complexity. But then again, it depends on your exact requirements. Some test cases: [(1, 12, 5, 49, 20, 1), (1, 12, 5, 20, 21, 49)] -> matched [(1, 2, 3, 4, 5, 6), (6, 5, 4, 3, 2, 1)] -> matched [(1, 2, 3, 4, 5, 6), (1, 2, 3, 4, 5, 1)] -> not matched.

Comment if there are further queries.

Krishna Pratap Chouhan

Thank you for the response haha :)

I see what you did.

This is what I did in regards to player_pick().

  1. I wanted it to work in a way that it will ask the user a number input 6 times from 1-49.
  2. If a user enters a non-integer, it will throw out the error message and asks for a new one
  3. If a user picks the same number, the program will not save that number and ask to choose a different one.
  4. All picked numbers would be added to the list and once there are 6 numbers, it will print out the full list to show to the player.
def player_pick():

    print("Please pick six numbers for the lottery.")
    while True:
        try:
            if len(playerPick) < 6:
                pickNumber = int(input("> "))

            if pickNumber in playerPick:
                print("You already chose that number, please choose a different one")
                playerPick.remove(pickNumber)

        except ValueError:            
                print("That is not a number! Try again!")

        else:
                playerPick.append(pickNumber)            


        if len(playerPick) == 6:
            print("Here are your chosen numbers:")
            print(playerPick)
            print("Best of luck!")
            break

If there are another way to make this shorter that would be great! :D

Regarding the computer_pick():

  1. It should choose 6 random numbers from only 1-49.
  2. The chosen numbers should not repeat itself from the list.
  3. Once there are 6 random numbers in the computer's list, the program should compare it to the player list.
  4. There would be a count counter and for everytime it doesn't match to the players list, it will add by 1
  5. If both numbers do not match, the computer will generate a new batch of 6 random numbers, non repeating. Until it matches.
  6. Once it matches, it should print out how many draws it took for it to match.

Here's what I did so far:

def lottery_pick():   
    while True:
        if len(lotteryPick) < 6:
            randomPick = random.randint(1, 49) #I did what you did, doing a random int, instead of creating a list 1-49
            lotteryPick.append(randomPick)
            #But now, I want something here that would not make the pick repetitive, just like the player_pick()

        else:
            print(lotteryPick)
            break

Now I cant find a way to use this to functions, and that the program will run steps 3 - 6.

ok first lets make the pick repetitive, just like the player_pick()

def lottery_pick():   
    lotteryPick = []
    while  len(lotteryPick) < 6:
        randomPick  = random.randint(1, 49) #I did what you did, doing a random int, instead of creating a list 1-49
        if randomPick not in lotteryPick:
            lotteryPick.append(randomPick)
            #But now, I want something here that would not make the pick repetitive, just like the player_pick()
    return lotteryPick

So now, you have a player-picker() and a computer_picker().

Next step compare the player_pick and computer_pick.

count = 0

while True:
    playerPick = player_pick()
    compuerPick = computer_pick()
    if compare(playerPick, computerPick):
        print(count)
        break;
    else:
        count += 1

Compare Function:

def compare( lis1, lis2):
    return isMembership(lis1, lis2) and isMembership(lis2, lis1)

def isMembership(lis1, lis2):
    for i in lis1:
        if i not in lis2:
            return False
    return True

Final code:

import random
def main():
    count = 0
    playerPick = []
    playerPick = player_pick()
    computerPick = []
    computerPick = lottery_pick()
    print(playerPick)
    print(computerPick)
    while True:
         if compare(playerPick, computerPick):
             print(count)
             break;
         else:
             print(count)
             count += 1



def player_pick():
    playerPick = []
    print("Please pick six numbers for the lottery.")
    while True:
        try:
            if len(playerPick) < 6:
                pickNumber = int(input("> "))
            if pickNumber in playerPick:
                print("You already chose that number, please choose a different one")
                playerPick.remove(pickNumber)
        except ValueError:            
                print("That is not a number! Try again!")
        else:
                playerPick.append(pickNumber)            
        if len(playerPick) == 6:
            print("Here are your chosen numbers:")
            print(playerPick)
            print("Best of luck!")
            return playerPick



def lottery_pick():   
    lotteryPick = []
    while  len(lotteryPick) < 6:
        randomPick  = random.randint(1, 49) #I did what you did, doing a random int, instead of creating a list 1-49
        if randomPick not in lotteryPick:
            lotteryPick.append(randomPick)
            #But now, I want something here that would not make the pick repetitive, just like the player_pick()
    return lotteryPick


def compare( lis1, lis2):
    return isMembership(lis1, lis2) and isMembership(lis2, lis1)

def isMembership(lis1, lis2):
    for i in lis1:
        if i not in lis2:
            return False
    return True

Do let me know if you find any other hurdle. or if i missed some point which i am sure i did :)

:sparkles:I hope you know how faint chances are there are for matching these two lists. :sparkles:

Thank you for the detailed response!

It does make sense, but I got lost with the compare function part. (Probably its something i still need to learn along the python tracks. Im only at the Python Basics: Creating a number Game 1.)

But aside from that, i picked up alot of points from this. Ill try the code myself once I get home haha ? Ill try to check the help function in python as well to see the library regarding what you did with the compare function.

I am sorry if understood your comment 'not' correctly but 'compare' function is not a pre-defined function. If you remember, you had a compare function tat sorted the list and compared them. But sorting a list has a complexity of nlogn. What we are trying to do here is, we are checking if list-1 has every element inside list-2 and list-2 has every element inside list-1. In this way we can confirm that there is no element that exists in either list which exists in one and not in other. Its similar to one-one Onto functions.

Hope this was helpful.