如何使用数组来跟踪不同的数字?

时间:2015-03-25 14:39:48

标签: python arrays

我已经生成了1到10的随机数字,但是当特定数字出现时,我们不知道如何跟踪它们。

作业单:

  

具体来说,编写一个模拟一个程序(一个“辅助函数”)   试用获得一整套交易卡。怎么样?生成一个   1到10之间的随机整数,以模拟框中的哪个卡。   每次生成一个数字时,递增一个计数器 - 这就是   我必须购买的盒子数量。每次我拿到一张新卡,   增加另一个计数器 - 这是我不同卡的数量   有。设置完成后停止。您必须使用数组来保留   跟踪不同的卡。该数组可以包含整数或   布尔值。

我当前的代码:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我真的不明白分配表,特别是需要购买的盒子,它总是会返回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