问题描述
我已经为主函数制作了两个模块(我猜是不完整的)但无法制作主函数
为当前工作区/目录中的模块创建一个名为 lottohelper_using_getopt.py 的脚本文件。
定义一个名为 lotto649 的函数(在脚本/模块文件中),它可以在一个范围 [1,49] 的列表中生成并返回六个不同的随机整数。 (1 分)
定义一个名为 lottomax 的函数(在脚本/模块文件中),它可以在一个范围 [1,50] 的列表中生成并返回七个不同的随机整数。 (1 分)
在 Jupyter notebook 中导入 lottohelper_using_getopt 模块,并调用 lotto649 和 lottomax 两个函数,并在 Jupyter notbook 单元格中报告您的结果。 (1 分)
您必须使用随机模块 https://docs.python.org/3/library/random.html 中的 randrange() 或 randint() 函数。
定义 main 函数(在脚本/模块文件中),它允许您通过 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,17,18,25,32,34]
[10,24,29,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,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)