披露:我是Python(及编码)婴儿。我刚开始CS,我正在尽力而为,但是我很挣扎。这是一个作业问题。我根据随机生成的整数(从0到3)分配证卡套装。 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_card_suit_string_from_number(n)='Spades'”是无效的语法;我花了几个小时才能达到这一点,所以我现在真的在水泥上拖拉我的牙齿。
您接近。您可以按如下所示扩展功能。
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'
只需将值映射为字典中的名称:
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)