返回与随机整数对应的给定名称

2024-05-15 23:55:09 发布

您现在位置:Python中文网/ 问答频道 /正文

披露:我是一个Python(编码)婴儿。我刚开始做CS,我已经尽力了,但我还在挣扎。这是一道家庭作业题。我根据随机生成的整数(从0到3)来分配一套纸牌套装,s.t.0=黑桃,1=红桃,2=梅花,3=钻石。你知道吗

我得到的是:

def random_suit_number():
    ''' Returns a random integer N such that 0 <= N < 4. '''
    pass

def get_card_suit_string_from_number(n):
    ''' Returns the name of the suit that corresponds to the value n, or None if n is an invalid number. '''
    pass

这是我的观点:

def random_suit_number():
''' Returns a random integer N such that 0 <= N < 4. '''
    return random.randint(0, 3)

def get_card_suit_string_from_number(n):
''' Returns the name of the suit that corresponds to the value n, or None if n is an invalid number. '''
    n = random_suit_number()
    if n == 0: 
        get_card_suit_string_from_number(n) = 'Spades'

有人能帮我解释一下吗?很明显还没有完成,Repl告诉我“get \u card \u suit \u string \u from \u number(n)=‘Spades’”是无效的语法;我花了几个小时才到达这一点,所以我现在真的在水泥上拖拖拉拉。你知道吗


Tags: thefromnumbergetstringifthatdef
3条回答

你很接近。您可以按如下方式扩展您的函数。你知道吗

def get_card_suit_string_from_number(n):
    ''' Returns the name of the suit that corresponds to the value n, or None if n is an invalid number. '''
    n = random_suit_number()

    if n == 0: 
        return 'Spades'
    elif n == 1:
        return 'Hearts'
    elif n == 2:
        return 'Clubs'
    elif n == 3:
        return 'Diamonds'
    else:
        return None

您基本上只想返回名称,所以只需返回'Spades' or 'Clubs'。基本上,在你得到随机数n之后,你只需将它的值与0、1、2和3进行比较,然后return 'Clubs'

只需在dict中用name映射值:

def get_card_suit_string_from_number(n):
   ''' Returns the name of the suit that corresponds to the value n, or None if n is an invalid number. '''
    n = random_suit_number()
    return {
        0: 'Spades',
        1: 'Hearts',
        2: 'Clubs',
        3: 'Diamonds',
    }.get(n)

相关问题 更多 >