开发一个模块以帮助在 python 中生成彩票

Develop a module to help generate lottery tickets in python

我已经为主要功能制作了两个模块(我猜是不完整的)但是无法制作主要功能

为您当前 workspace/directory 中的模块创建一个名为 lottohelper_using_getopt.py 的脚本文件。

定义一个名为 lotto649 的函数(在 script/module 文件中),它可以在范围 [1] 的列表中生成和 return 六个不同的随机整数,49]。 (1 分)

定义一个名为 lottomax 的函数(在 script/module 文件中),它可以在范围 [1] 的列表中生成和 return 七个不同的随机整数,50]。 (1 分)

在Jupyter notebook中导入lottohelper_using_getopt模块,调用lotto649和lottomax这两个函数,并在Jupyter notbook cell中报告结果。 (1 分)

您必须使用随机模块 https://docs.python.org/3/library/random.html 中的 randrange() 或 randint() 函数。

定义主要功能(在script/module文件中),它允许您通过getopt模块提供选项,(3分)例如

说明如何使用的帮助信息, 在 649 和 MAX 之间选择类型, 使用 -v 或 --verbose 来控制冗长。 您需要使用位置参数来指定您希望它生成多少票。

在main函数中,解析完参数后,需要写代码生成多张票。 (1 分)

运行 命令行中的 lottohelper_using_getopt.py (或在 Jupyter 实验室单元中使用 !python lottohelper_using_getopt.py ),例如python lottohelper_using_getopt.py -v 1 --type MAX 4 这意味着您告诉脚本生成 4 张 LottoMax 彩票(即屏幕上打印的四组随机数)。在笔记本原始单元格中报告您的结果。 (1 分)

这是应该的输出

# The running of your script (using getopt package should look like the following:

$ python lottohelper_using_getopt.py -h
lottohelper.py [-h|--help] [-v|--verbose] <0/1> [-t|--type] <649/MAX> <integer>
$ python lottohelper_using_getopt.py -v 1 --t 649 3
Ticket Type: 649
Number of Tickets: 3
[24, 26, 27, 35, 39, 43]
[12, 19, 20, 31, 44, 49]
[2, 3, 11, 16, 22, 31]
$ python lottohelper_using_getopt.py --verbose 0 --type MAX 3
[2, 11, 17, 18, 25, 32, 34]
[10, 24, 25, 29, 31, 32, 39]
[3, 4, 5, 6, 23, 43, 44]

lottohelper_using_getopt 模块

#!/usr/bin/env python

import random
import getopt
import sys

def lotto649():
    '''
    Generate six different integers from range 1,2,...,49. 
    '''
    ticket=[] 
    # the list to save the six numbersa while loop below to add the generated numbers to the list ticket, make sure not add same numbers in the ticket
    i=1
    while i<=50:
        for x in range (6):
            ticket.append(x)
                
    # sort ticket
    ticket.sort()
    
    return ticket

def lottomax():
    '''
    Generate seven different integers from range 1,2,...,50. 
    '''
    ticket=[] # the list to save the seven numbers
    
    # you will need to write a for loop below to add the generated numbers to the list ticket, make sure not add same numbers in the ticket
    x=[random.randint(1, 51) for i in range(7)]
    ticket.append(x)
        
    # sort ticket
    ticket.sort()
    
    # return your result below
    return ticket


def usage():
    print("lottohelper.py [-h|--help] [-v|--verbose] <0/1> [-t|--type] <649/MAX> <integer>")

    
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) # students: complete this statement
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    
    
    # get optional arguments
    tp='649' # initialize type of ticket
    ver=False # verbose
    
    for k,v in opts:
        pass
    
    # get positional argument
    N=int(args[0])
    
    # do actual work here
    # generate N tickets
    tickets=[]
    for n in range(N):
        pass
    
    if ver:
        print('Ticket Type:', tp)
        print('Number of Tickets:', N)
        
    for t in tickets:
        print(t)
        
    
if __name__=='__main__':
    main()

如果有人能解释如何解决这个问题,我将不胜感激

这应该可以做到。我添加了一些评论以获取更多信息,如果您还不知道它们是如何工作的,请在您最喜欢的引擎中搜索它们。

import random, getopt, sys



def make_ticket(length, maximum):
    """
    Generate a ticket of a given length using numbers from [1, maximum]
    return random.sample(range(1, maximum+1), length) would be the best way
    """
    ticket = []
    while len(ticket) < length:
        num = random.randint(1, maximum)
        if not num in ticket:
            ticket.append(num)
    return ticket

def usage():
    print("lottohelper.py [-h|--help] [-v|--verbose] <0/1> [-t|--type] <649/MAX> <integer>")


def main(args):
    try:
        opts, args = getopt.getopt(args, "ht:v:", "help type= verbose=".split()) # students: complete this statement
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    
    # get optional arguments
    # this approach intentionally breaks if the user misses an option
    for k, v in opts:
        if k in '--help':
            usage()
        elif k in '--type':
            tp = {
                '649': (6, 49),
                'MAX': (7, 50)
            }[v] # dict-based ternary operator
        elif k in '--verbose':
            ver = {
                '0': False, 
                '1': True
            }[v] # dict-based ternary operator
    
    # get positional argument
    N = eval(args[0]) # causes an exception if anything other than an integer is given; a float will not be converted
    
    # do actual work here
    tickets = [make_ticket(*tp) for i in range(N)] # list comprehension
    
    if ver:
        print(f'Ticket Type:\t{649 if tp[0]==6 else "MAX"}') # format string
        
    for i, t in enumerate(tickets, 1):
        print(f'Ticket #{i}:\t{t}') #format string
        
    
if __name__=='__main__':
    args = sys.argv[1:]
    # args = '-v 1 --t 649 3'.split()
    # main(args)
    # args = '--verbose 1 --type MAX 3'.split()
    main(args)