简体   繁体   中英

How to choose a random input from 7 given input?

I'm creating a lottery hack machine which gets the winning numbers of the last 7 days and tries to select a winner from the the 7 and shuffle the numbers of that selection and print the result. All this occurs at random.

#lottery hack

print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [float(x.strip()) for x in input_list]

elif today>31:
    print "A month has only 31 days ;P"

You can use the random.choice function for this. It returns a random element from the sequence you pass it.

import random
print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [float(x.strip()) for x in input_list]
    print random.choice(numbers)

elif today>31:
    print "A month has only 31 days ;P"

If you want to shuffle the entire list in place instead of printing random elements from it one at a time, you can use the random.shuffle function.

import random
print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [float(x.strip()) for x in input_list]
    random.shuffle(numbers)
    print numbers

elif today>31:
    print "A month has only 31 days ;P"

As clarified in the comments, you need an approach that combines these two approaches.

import random
print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [list(x.strip()) for x in input_list]
    choice = random.choice(numbers)
    random.shuffle(choice)
    print ''.join(choice)

elif today>31:
    print "A month has only 31 days ;P"

Python has a module for random. Here's how you could use it :

import random
print(random.choice(numbers))

The choice method does the job for you of getting a random element from a sequence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM