Python 如何使用数组跟踪不同的数字?
我已经生成了从1到10的随机数,但不知道如何在出现特定数字时跟踪它们 作业表: 具体来说,编写一个程序(一个“助手函数”)来模拟它 试用获得一套完整的交易卡。如何?生成一个 1到10之间的随机整数,用于模拟盒子中的卡。 每次生成一个数字时,递增一个计数器,这是 我必须买的盒子数量。每次我得到一张新卡, 增加另一个计数器这是不同卡的数量I 有。完成集合后停止。必须使用数组来保留 不同卡片的轨迹。此数组可以包含整数或 布尔值 我当前的代码:Python 如何使用数组跟踪不同的数字?,python,arrays,Python,Arrays,我已经生成了从1到10的随机数,但不知道如何在出现特定数字时跟踪它们 作业表: 具体来说,编写一个程序(一个“助手函数”)来模拟它 试用获得一套完整的交易卡。如何?生成一个 1到10之间的随机整数,用于模拟盒子中的卡。 每次生成一个数字时,递增一个计数器,这是 我必须买的盒子数量。每次我得到一张新卡, 增加另一个计数器这是不同卡的数量I 有。完成集合后停止。必须使用数组来保留 不同卡片的轨迹。此数组可以包含整数或 布尔值 我当前的代码: import random def box():
import random
def box():
startbox = 0
cards = [1,2,3,4,5,6,7,8,9,10]
random = random.randrange(0,10)
while random == cards:
startbox = startbox + 1
请参阅下面慷慨注释的代码以获得一些启示
def boxes_to_buy():
cards = [] # At the beginning we have no cards
boxes_opened = 0 # No box is yet opened
while len(cards) < 10: # As long as we don't have 10 cards
boxes_opened += 1 # Open another box
card_in_box = random.randint(1,10) # Get a random card 1-10
if card_in_box not in cards: # Do we already own this card?
cards.append(card_in_box) # If we do not already own it add it to our list of cards
return boxes_opened # How many boxes were opened in the process of completing the whole set
def box_to_buy():
卡片开始时我们没有卡片
已打开的盒子=0#尚未打开任何盒子
而len(cards)<10:#只要我们没有10张卡
盒子_打开+=1#打开另一个盒子
卡在盒子里=随机。随机数(1,10)#得到一张随机卡1-10
如果卡盒中的卡不在卡中:#我们已经拥有这张卡了吗?
卡片。附加(卡片在卡片盒中)#如果我们还没有拥有它,将其添加到我们的卡片列表中
退货箱(u打开#在完成整套产品的过程中打开了多少箱
我真的不理解作业表,特别是需要购买的箱子,它们总是会返回10个,但我认为这就是它所要求的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
def box():
startbox = 0
allcards = 0
cards = [1,2,3,4,5,6,7,8,9,10]
curcards = []
while True:
randomn = random.randrange(0,10)
allcards = allcards+1
if str(cards[randomn]) not in curcards:
cards[randomn]
startbox = startbox + 1
curcards.append(str(cards[randomn]))
if len(curcards) == 10:
break
return 'Boxes to buy: ' + str(startbox) + ' Cards Found: ' + '; '.join(curcards) + ' Total amount of cards: ' + str(allcards)
#print box()
box()
返回:
Boxes to buy: 10 Cards Found: 9; 1; 2; 8; 5; 7; 10; 6; 4; 3 Total Amount Of Cards: 31
您应该为随机数使用不同的名称,例如
random\u number
。如果将其命名为random
,则会覆盖随机生成器模块的名称,并且不能多次使用。您的代码实际上包含多个错误:您的函数缩进错误(def框),您需要使用“in”not==检查一个列表,while循环实际上是无限的(random是一个介于1和10之间的数字,而random在列表中是1到10),并且random正在覆盖random模块,因此需要重命名。