【剑指offer】——【python中return函数中的and和or表达式的返回值】
生活随笔
收集整理的這篇文章主要介紹了
【剑指offer】——【python中return函数中的and和or表达式的返回值】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
1、# and 結果為真,返回最后一個表達式的結果,若結果為假返回第一個為假的表達式的結果
2、# or 結果為真,返回第一個為真的表達式的結果,若結果為假,返回最后一個表達式的結果
3、應用[劍指 Offer 64. 求1+2+…+n]
1、# and 結果為真,返回最后一個表達式的結果,若結果為假返回第一個為假的表達式的結果
def test_and(a,b):return a and b # 0 表示FALSE,非0表示True print(test_and(0,1)) # and -> False -> 0(a) print(test_and(1,0)) # and -> False -> 0(b) print(test_and(False,0)) # and -> False -> False(a) print(test_and(0,False)) # and -> False -> 0(a) print(test_and(1,2)) # and -> True -> 2(b) print(test_and(2,1)) # and -> True -> 1(b)2、# or 結果為真,返回第一個為真的表達式的結果,若結果為假,返回最后一個表達式的結果
def test_or(a,b):return a or b # 0 表示FALSE,非0表示True print(test_or(0,1)) # or -> True -> 1(a) print(test_or(1,0)) # or -> True -> 1(b) print(test_or(2,1)) # or -> True -> 1(b) print(test_or(1,2)) # or -> True -> 2(b) print(test_or(False,0)) # or -> False -> 0(b) print(test_or(0,False)) # or -> False -> False(b)3、應用[劍指 Offer 64. 求1+2+…+n]
求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。
for 循環用遞歸代替
if 用return 的and屬性來表示
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/5/20 12:54 # @Author : @linlianqin # @Site : # @File : 劍指 Offer 64. 求1+2+…+n.py # @Software: PyCharm # @description: ''' 求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。 限制:1 <= n <= 10000'''class Solution:'''遞歸'''def sumNums(self, n: int) -> int:return n and n + self.sumNums(n - 1)print(Solution().sumNums(3))?
總結
以上是生活随笔為你收集整理的【剑指offer】——【python中return函数中的and和or表达式的返回值】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SHA256算法详解及python实现
- 下一篇: 超级强大的socket工具ss,替代ne