力扣题目练习 换水问题

1

很简单,就是直到你剩余的空水瓶不足以换一瓶水的时候,就停止

复制代码
class Solution(object):
    #我有这么多水,exchange个瓶子可以兑换一瓶水
    def numWaterBottles(self, numBottles, numExchange):
        """
        :type numBottles: int
        :type numExchange: int
        :rtype: int
        """
        count=numBottles
        now_exchange=numBottles
        while (now_exchange//numExchange)>=1:
            count+=(now_exchange//numExchange)
            #现在有的空瓶子的数目
            now_exchange=(now_exchange%numExchange)+(now_exchange//numExchange)
        return count
solution=Solution()
result=solution.numWaterBottles(15,4)
print(result)

然后我们看加大难度的等级

题目的意思是这样的:空水瓶换水,一次只能换一瓶水,换完之后剩余的空水瓶数目仅仅+1,并且下一次换一瓶水需要的空水瓶数目还要涨,我这个没有思考其他方法,还是沿袭问题1的,代码如下:

复制代码
class Solution(object):
    #我有这么多水,exchange个瓶子可以兑换一瓶水
    #意思就是numexchange的数量是会发生改变的
    #而且一次只可以交换一个满水瓶
    def numWaterBottles(self, numBottles, numExchange):
        """
        :type numBottles: int
        :type numExchange: int
        :rtype: int
        """
        count=numBottles
        now_exchange=numBottles
        while (now_exchange//numExchange)>=1:
            count+=1
            #现在有的空瓶子的数目
            print(now_exchange)
            print('1',numExchange)
            now_exchange=(now_exchange%numExchange)+((now_exchange//numExchange)-1)*(numExchange)+1
            numExchange+=1
        return count
solution=Solution()
result=solution.numWaterBottles(10,3)
print(result)

但是其实每次只置换一瓶,就没必要这个除法了 那么条件就是如果剩余空水瓶数目大于等于置换一瓶水需要的空水瓶数目,便可以继续,所以我们可以写出更简单的代码

如果喜欢这个帖子,欢迎点赞收藏

相关推荐
JieE2124 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵9 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1114 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0016 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵18 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf19 小时前
Agent 流程编排
后端·python·agent
copyer_xyf19 小时前
Agent RAG
后端·python·agent
copyer_xyf19 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf19 小时前
Agent 记忆管理
后端·python·agent