简体   繁体   中英

blackjack game: for loops 'not in' vs 'in'

I have run into some trouble using for loops while making a blackjack game simulation. The function new_game simulates four cards being dealt, while new_card ensures no card is repeated in a game. I created two variations of the function new game and was wondering how they differ.

In Version 1, there were situations where the function only returned 3 cards, while Version 2 seems to work as expected.

Version 1:

def new_game():
game=[];
for x in range(4):
    n=new_card();
    if n not in game:
        game+=[n];
    else:
        new_game();
    print(game);
return game

Version 2:

def new_game():
game=[];
for x in range(4):
    n=new_card();
    if n in game:
        new_game();
        print(game);
    else:
        game+=[n];
return game

Calling new_game is not the best way to solve this project. You can try multiple ways , one of which I am showing. Rather than a constant for loop try to check the length of list until it is of desired length.

def new_game():
    game=[];
    while len(game)!=4:
        n = new_card()
        while(n in game):
            n = new_card()
        else:
            game.append(n)
    return game

print new_game()

I am not sure if this is a good design but still it works and you may modify it.

EDIT

Thanks to Blckknght for suggesting this.

def new_game():
    game=[]
    while len(game)!=4:
        n = new_card()
        if n not in game:
            game.append(n)
    return game

print new_game()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM