以下是我对CodeAbbey - Blackjack计数的解决方案
我的代码通过了对code的所有测试,但是我认为我有一些很差的实现,特别是在我对Aces的处理方面,但是,否则,我认为我总体上使用了良好的实践和设计。
def calculate_player_hand(player_hand_input):
"""Return the score of a player hand"""
# Variable to hold score for a hand
total_player_hand_score = 0
# Dictionary mapping cards to their score value
card_values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 10, "K": 10, "Q": 10}
# Find score of cards except Aces
for card in player_hand_input:
if card == "A":
continue
else:
total_player_hand_score += card_values[card]
# Return player_hand_score not including Ace card(s)
return total_player_hand_score
# Return the total amount of Aces in a player's hand
def get_aces_count(player_hand_input):
"""Return the count of Aces"""
return player_hand_input.count("A")
# Read in test cases
test_cases = int(input())
# List to hold all total scores
total_scores = []
# Iterate through test cases
for i in range(test_cases):
# Read in player hand
player_hand = input().split()
# Variable to hold number of Aces in player hand
player_score_without_aces = calculate_player_hand(player_hand)
for j in range(get_aces_count(player_hand)):
if 21 - player_score_without_aces < 11:
player_score_without_aces += 1
else:
player_score_without_aces += 11
# Rename variable since value of Aces were added
total_player_score = player_score_without_aces
# Add total score to total_scores list
if total_player_score > 21:
total_scores.append("Bust")
else:
total_scores.append(total_player_score)
# Output all total scores
for total_score in total_scores:
print(total_score, end=" ")谢谢。
发布于 2020-02-28 09:09:28
如前所述--总是将实现和测试用例分离。
为了获得更好的/优化的功能,请考虑以下操作:
calculate_player_hand函数
card_values = {"2": 2, "3": 3, ...}更好地定义为顶级常量,称为CARDS:# Dictionary映射卡到其得分值卡= {"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"T":10,"J":10,"K":10,"Q":10}total_player_hand_score和for循环+ continue流,整个函数可以用简洁的sum +生成器表达式代替: def calculate_player_hand( player_hand_input ):“除Ace卡(S)”之外,返回玩家手牌的分数“#变量来保持一只手的退换和得分(CARDS.get(卡片)在player_hand_input中的牌!= 'A')迭代测试用例
if 21 - player_score_without_aces < 11:可以替换为一个较短的等效if score_without_aces >= 11: (player_score_without_aces重命名为score_without_aces):for j in range(get_aces_count(player_hand)):score_without_aces += 1 if score_without_aces >= 11 shorter 11total_player_score = score_without_aces重命名为score_without_aces,将包含上for循环的最后一个结果值:total_scores.append(如果score_without_aces > 21 upper score_without_aces,则为“total_scores.append”)发布于 2020-02-28 08:28:34
您没有提供一个可测试函数来执行为特定测试用例返回所需答案的任务。这是您在测试代码中插入的ace处理。程序结构的主要结构应该类似于
def calculate_player_hand(player_hand_input):
#[...]
return score
def read_tests():
#[...]
return testcases, answers
for test, answer in zip(read_tests()):
assert answer == calculate_player_hand(test)将您想要提供的功能与测试完全分开。甚至分成不同的文件。
https://codereview.stackexchange.com/questions/238077
复制相似问题