Python中while的and和or

while A and B: 同时满足A和B条件
while A or B:满足A或B任意一条

以1768. 交替合并字符串官方答案为启发,以前没意识到while还可以用and和or。

其实无论用什么,只要看最后的结果是True或False

复制代码
class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        m, n = len(word1), len(word2)
        i = j = 0

        ans = list()
        while i < m or j < n:
            if i < m:
                ans.append(word1[i])
                i += 1
            if j < n:
                ans.append(word2[j])
                j += 1

        return "".join(ans)


print(Solution().mergeAlternately(word1="abcd", word2="pq"))
复制代码

 

posted @   你说夕阳很美  阅读(375)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示