Skip to content Skip to sidebar Skip to footer

Bingo Number Check

So I build a tiny bingo program for my wife to use at her candle parties. The boards are already generated. This is just a program to call out the numbers. import random a = [] a

Solution 1:

I would accumulate the numbers called in a set which would get returned from pop. then I'd add a function to read in the "winning" numbers (into a set) and check if that new set is a subset of the numbers which were called:

import random
import ast

def pop(a,accumulated=None):
    print "type q to move on to verification"
    if accumulated is None:
        accumulated = set()
    v = 'I can put any string here, as long as it is not "q" :-)'
    while v.lower() != 'q':
        b = a.pop(0)
        if b <= 15:
            print 'b', b,
        elif b > 15 and b <=30:
            print 'i', b,
        elif b > 30 and b <=45:
            print 'n', b,
        elif b > 45 and b <=60:
            print 'g', b,
        else:
            print 'o', b,
        accumulated.add(b)
        v = raw_input('')
    return accumulated

def verify(numbers):
    new_nums = raw_input("enter numbers separated by ',': ")
    nums = ast.literal_eval(new_nums)
    assert( len(nums) == 5 ) #Need 5 numbers to win
    result = set(nums).issubset(numbers)
    print "Verified? ",result
    return result
    #alternatively, and probably slightly more efficient
    # print numbers.issuperset(nums)
    #I prefer the other though as `subset` is easier for me to remember


def robust_verify(numbers):
   """
   keep trying to verify the numbers until we succeed
   """
   try:
       verify(numbers)
   except (AssertionError,SyntaxError,TypeError):  #other error conditions might go here too, but these are the ones I can think of right now ...
       robust_verify(numbers)


def play_bingo(game_vals=None,accumulated=None):
    if game_vals is None:
        game_vals = list(range(1,76))  #list strictly not necessary here, but why not?
        random.shuffle(game_vals)

    nums = pop(game_vals,accumulated=accumulated)
    if not robust_verify(nums):
        play_bingo(game_vals=game_vals,accumulated=nums)


play_bingo()

This is made a little more robust by making sure that verify succeeds (e.g. that your user doesn't accidentally enter a number as 15a,17,22,...)

As a side note, your attempt at using a file failed because you were opening a file, writing a number to it and closing it each time you "draw" a new number. Since you're opening the file as 'w' any file that is already there gets clobbered -- and so you can only ever store the last number drawn by that method. You'd want to move your while loop into the with statement in order to get that method to work properly (or open the file for appending ('a'), but repeatedly opening a file for appending is typically not a good solution).


Post a Comment for "Bingo Number Check"