Kaggle Python练习:使用外部库(Exercise: Working with External Libraries)

发布于:2024-10-18 ⋅ 阅读:(38) ⋅ 点赞:(0)

问题1:坐标轴及标签显示

正如你所看到的,他最近运气不佳。他想用一些精选的表情符号沿着在推特上发布这条消息,但是,就像现在看起来的那样,他的追随者可能会觉得很困惑。他问你是否可以帮助他做出以下改变:

添加标题“500次老虎机抽奖的结果”
使y轴从0开始。
将标签“Balance”添加到y轴
在调用type(graph)之后,您可以看到Jimmy的图是类型 matplotlib.axes._subplots.AxesSubplot 。嗯,这是新的。通过调用dir(graph),您会发现三个看起来很有用的方法:.set_title()、.set_ylim()和.set_ylabel()。

使用这些方法根据Jimmy的请求完成函数prettify_graph。我们已经为您检查了第一个请求(设置标题)。

(记住:如果你不知道这些方法的作用,请使用help()函数!)

  • .set_title():设置标题
  • .set_ylim():设置y轴
  • .set_ylabel():设置y轴标签
def prettify_graph(graph):
    """Modify the given graph according to Jimmy's requests: add a title, make the y-axis
    start at 0, label the y-axis. (And, if you're feeling ambitious, format the tick marks
    as dollar amounts using the "$" symbol.)
    """
    graph.set_title("Results of 500 slot machine pulls")
    # Complete steps 2 and 3 here
#     graph.set_title("Results of 500 slot machine pulls")
    graph.set_ylim(0)
    graph.set_ylabel("Balance")

graph = jimmy_slots.get_graph()
prettify_graph(graph)
graph

在这里插入图片描述
额外好处:您可以对y轴上的数字进行格式设置,使它们看起来像美元金额吗?例如,200美元而不是200美元。

def prettify_graph(graph):
    graph.set_title("Results of 500 slot machine pulls")
    # Make the y-axis begin at 0
    graph.set_ylim(bottom=0)
    # Label the y-axis
    graph.set_ylabel("Balance")
    # Bonus: format the numbers on the y-axis as dollar amounts
    # An array of the values displayed on the y-axis (150, 175, 200, etc.)
    ticks = graph.get_yticks()
    # Format those values into strings beginning with dollar sign
    new_labels = ['${}'.format(int(amt)) for amt in ticks]
    # Set the new labels
    graph.set_yticklabels(new_labels)
    
    
graph = jimmy_slots.get_graph()
prettify_graph(graph)
graph

在这里插入图片描述

问题2:赢得比赛的最佳项目并计数

Luigi正试图进行分析,以确定在Mario Kart赛道上赢得比赛的最佳项目。他有一些字典列表形式的数据,看起来像…

[
{‘name’: ‘Peach’, ‘items’: [‘green shell’, ‘banana’, ‘green shell’,], ‘finish’: 3},
{‘name’: ‘Bowser’, ‘items’: [‘green shell’,], ‘finish’: 1},
# Sometimes the racer’s name wasn’t recorded
{‘name’: None, ‘items’: [‘mushroom’,], ‘finish’: 2},
{‘name’: ‘Toad’, ‘items’: [‘green shell’, ‘mushroom’], ‘finish’: 1},
]
“items”是参赛者在比赛中获得的所有能量提升物品的列表,“finish”是他们在比赛中的位置(1代表第一名,3代表第三名,等等)。

他写了下面的函数来获取这样的列表,并返回一个字典,将每个条目映射到第一名完成者拾取的次数。

def best_items(racers):
    # 创建空字典用于存储第一名完成者拾取的次数
    winner_item_counts = {}
    for i in range(len(racers)):
        # 对于列表中每个字典进行操作
        racer = racers[i]
        # 如果是第一名
        if racer['finish'] == 1:
            # 获取第一名的项目
            for item in racer['items']:
                # 如果结果字典中没有该元素,进行创建
                if item not in winner_item_counts:
                    winner_item_counts[item] = 0
                # 有该元素则次数加1
                winner_item_counts[item] += 1
        # 如果名字未记录,发出警告
        if racer['name'] is None:
            print("警告:{}/{}名字为空,未记录! (racer = {})".format((i+1),len(racers),racer['name']))
    return winner_item_counts 

sample = [
    {'name': 'Peach', 'items': ['green shell', 'banana', 'green shell',], 'finish': 3},
    {'name': 'Bowser', 'items': ['green shell',], 'finish': 1},
    {'name': None, 'items': ['mushroom',], 'finish': 2},
    {'name': 'Toad', 'items': ['green shell', 'mushroom'], 'finish': 1},
]
best_items(sample)

问题3:21点游戏

假设我们想创建一个新类型来表示21点中的手牌。我们可能想对这种类型做的一件事是重载比较运算符,如>和<=,以便我们可以使用它们来检查一只手是否击败另一只手。如果我们能做到这一点,那就太酷了:

hand1 = BlackjackHand([‘K’, ‘A’])
hand2 = BlackjackHand([‘7’, ‘10’, ‘A’])
hand1 > hand2
True

好吧,我们不会在这个问题中完成所有这些(定义自定义类有点超出了这些课程的范围),但是我们要求您在下面的函数中编写的代码与我们定义自己的BlackjackHand类时必须编写的代码非常相似。(We我把它放在__gt__magic方法中,为>定义我们的自定义行为。)

根据文档字符串填充blackjack_hand_greater_than函数体

方法1:把超过21点的最后记为0

1、首先定义一个21点的计数函数BlackjackHand(hand)

def BlackjackHand(hand):
    count = 0
    A_count = 0
    # 进行遍历,如果为A,J,Q,K中的其中一个,加各自对应的数
    # 若为1~10,则加int(x)
    for x in hand:
        if x == 'A':
            A_count = A_count + 1
            count = count + 11
            continue
        if (x == 'J' or  x == 'Q' or x == 'K'):
            count = count + 10
            continue
        else:
            count = count + int(x)
    
    # 判断        
    if A_count == 0 and count <= 21:
        count = count
    elif A_count == 0 and count > 21:
        count = 0
    elif A_count > 0 and count <= 21:
        count = count
    elif A_count > 0 and count > 21:
        for i in range(A_count):
            count = count - 10
            if count <= 21:
                count = count
        if count > 21:
            count = 0
    return count

# 测试
print(BlackjackHand(['K']))
print(BlackjackHand(['3', '4']))
print(BlackjackHand(['10']))
print(BlackjackHand(['K', 'K', '2']))
print(BlackjackHand(['A', 'A', '9']))
print(BlackjackHand(['A', 'A', '9', '3']))
print(BlackjackHand(['9','Q',' 8','A']))

在这里插入图片描述
2、最终代码

def blackjack_hand_greater_than(hand_1, hand_2):
    """
    Return True if hand_1 beats hand_2, and False otherwise.
    
    In order for hand_1 to beat hand_2 the following must be true:
    - The total of hand_1 must not exceed 21
    - The total of hand_1 must exceed the total of hand_2 OR hand_2's total must exceed 21
    
    Hands are represented as a list of cards. Each card is represented by a string.
    
    When adding up a hand's total, cards with numbers count for that many points. Face
    cards ('J', 'Q', and 'K') are worth 10 points. 'A' can count for 1 or 11.
    
    When determining a hand's total, you should try to count aces in the way that 
    maximizes the hand's total without going over 21. e.g. the total of ['A', 'A', '9'] is 21,
    the total of ['A', 'A', '9', '3'] is 14.
    
    Examples:
    >>> blackjack_hand_greater_than(['K'], ['3', '4'])
    True
    >>> blackjack_hand_greater_than(['K'], ['10'])
    False
    >>> blackjack_hand_greater_than(['K', 'K', '2'], ['3'])
    False
    """
    if BlackjackHand(hand_1) > BlackjackHand(hand_2):
        return True
    else:
        return False
    

def BlackjackHand(hand):
    count = 0
    A_count = 0
    for x in hand:
        if x == 'A':
            A_count = A_count + 1
            count = count + 11
            continue
        if (x == 'J' or  x == 'Q' or x == 'K'):
            count = count + 10
            continue
        else:
            count = count + int(x)
            
    if A_count == 0 and count <= 21:
        count = count
    elif A_count == 0 and count > 21:
        count = 0
    elif A_count > 0 and count <= 21:
        count = count
    elif A_count > 0 and count > 21:
        for i in range(A_count):
            count = count - 10
            if count <= 21:
                count = count
        if count > 21:
            count = 0
    return count

方法2:把超过21点在最后进行判断

1、首先定义一个21点的计数函数BlackjackHand(hand)

def BlackjackHand(hand):
    count = 0
    A_count = 0
    for x in hand:
        if x == 'A':
            A_count = A_count + 1
            count = count + 11
            continue
        if (x == 'J' or  x == 'Q' or x == 'K'):
            count = count + 10
            continue
        else:
            count = count + int(x)
            
    if A_count > 0 and count > 21:
        for i in range(A_count):
            count = count - 10
            if count <= 21:
                count = count
        if count > 21:
            count = count
    return count

# 测试
print(BlackjackHand(['K']))
print(BlackjackHand(['3', '4']))
print(BlackjackHand(['10']))
print(BlackjackHand(['K', 'K', '2']))
print(BlackjackHand(['A', 'A', '9']))
print(BlackjackHand(['A', 'A', '9', '3']))
print(BlackjackHand(['9','Q',' 8','A']))

超过21点不变,等到最后进行判断为False
在这里插入图片描述
2、最终代码

def blackjack_hand_greater_than(hand_1, hand_2):
    """
    如果hand_1打败hand_2返回True,否则返回False。
    为了使hand_1打败hand_2,以下条件必须成立:
    —hand_1的总数不能超过21
    —hand_1的总和必须大于hand_2的总和,或者hand_2的总和必须大于21
    手牌被表示为一张牌的列表。每张卡片由一个字符串表示。
    当把一手牌的总牌数加起来时,带有数字的牌就会得到相应的点数。脸
    卡片(“J”、“Q”和“K”)值10分。“A”可以数1或11。
    当决定一手牌的总数时,你应该尝试用下面的方法来计算a
    在不超过21的情况下最大化手牌总数。例如,['A', 'A', '9']的总数是21,
    ['A', 'A', '9', '3']的总数是14。
    
    Examples:
    >>> blackjack_hand_greater_than(['K'], ['3', '4'])
    True
    >>> blackjack_hand_greater_than(['K'], ['10'])
    False
    >>> blackjack_hand_greater_than(['K', 'K', '2'], ['3'])
    False
    """  
    if (BlackjackHand(hand_1)<=21) and (BlackjackHand(hand_1) > BlackjackHand(hand_2)) or (BlackjackHand(hand_1)<=21 and BlackjackHand(hand_2)>21):
        return True
    else:
        return False
    
    
def BlackjackHand(hand):
	# 定义总数和'A'的数量
    count = 0
    A_count = 0
    # 
    for x in hand:
        if x == 'A':
            A_count = A_count + 1
            count = count + 11
            continue
        if (x == 'J' or  x == 'Q' or x == 'K'):
            count = count + 10
            continue
        else:
            count = count + int(x)
    
    # 判断        
    if A_count > 0 and count > 21:
        for i in range(A_count):
            count = count - 10
            if count <= 21:
                count = count
        if count > 21:
            count = count
    return count

方法3:官方代码与方法2相似

def hand_total(hand):
    """Helper function to calculate the total points of a blackjack hand.
    """
    total = 0
    # 计算a的数量,并在最后处理如何使用它们
    aces = 0
    for card in hand:
        if card in ['J', 'Q', 'K']:
            total += 10
        elif card == 'A':
            aces += 1
        else:
            # Convert number cards (e.g. '7') to ints
            total += int(card)
    # At this point, total is the sum of this hand's cards *not counting aces*.

    # 添加a,现在把它们记为1。这是我们从这只手能得到的最小的总数
    total += aces
    # 把a从1 “升级”到11只要它能帮我们接近21
    # without busting
    while total + 10 <= 21 and aces > 0:
        # Upgrade an ace from 1 to 11
        total += 10
        aces -= 1
    return total

def blackjack_hand_greater_than(hand_1, hand_2):
    total_1 = hand_total(hand_1)
    total_2 = hand_total(hand_2)
    return total_1 <= 21 and (total_1 > total_2 or total_2 > 21)

简化:

  • if card in ['J', 'Q', 'K']:
  • 在这里插入图片描述