Codewars Vasya - Clerk--6 kyu--Python解法

本文介绍了如何解决Codewars上的Vasya - Clerk问题,这是一个6 kyu级别的Python编程挑战。Vasya是一名售票员,他需要处理顾客用不同面额的美元购买25美元电影票的情况。文章提供了简洁的Python代码示例来解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Codewars Vasya - Clerk–6 kyu–Python解法


Codewars 是一个跟LeetCode类似的结题网站。
Codewars题解专栏:Codewars题解


题目地址:Train: Vasya - Clerk | Codewars


The new “Avengers” movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollar bill. An “Avengers” ticket costs 25 dollars.

Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.

Can Vasya sell a ticket to every person and give change if he initially has no money and sells the tickets strictly in the order people queue?

Return YES, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Otherwise return NO.

Examples:

tickets([25, 25, 50]) # => YES 
tickets([25, 100]) # => NO. Vasya will not have enough money to give change to 100 dollars
tickets([25, 25, 50, 50, 100]) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)

这道题目是6kyu难度的,比较简单。
Python解法如下:

def tickets(people):
    l=[0,0]
    for i in people:
        if i==25:
            l[0]+=1
        elif i==50:
            if l[0]==0:
                return "NO"
            else:
                l[0]-=1
                l[1]+=1
        else:
            if l[1]>=1:
                if l[0]==0:
                    return "NO"
                else:
                    l[0]-=1
                    l[1]-=1
            else:
                if l[0]<3:
                    return "NO"
                else:
                    l[0]-=3
    return "YES"

上面的解法是比较啰嗦的,简化后别人的解法参考如下:

def tickets(a):
    n25 = n50 = n100 = 0
    for e in a:
        if   e==25            : n25+=1
        elif e==50            : n25-=1; n50+=1
        elif e==100 and n50>0 : n25-=1; n50-=1
        elif e==100 and n50==0: n25-=3
        if n25<0 or n50<0:
            return 'NO'
    return 'YES'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值