題目鏈接
from operator import add, sub
def a_plus_abs_b(a, b):
"""在不使用abs()函數(shù)的前提下,返回a + abs(b)的和"""
if b < 0:
f = sub
else:
f = add
return f(a, b)
def two_of_three(a, b, c):
"""
返回a, b, c中最大2個(gè)數(shù)的平方和
假設(shè)a, b, c為正數(shù)
"""
# 方法一
# return max(a*a + b*b, a*a + c*c, b*b + c*c)
# 方法二
return a*a + b*b + c*c - (min(a, b, c))**2
def largest_factor(n):
"""
求n的最大公約數(shù)
利用枚舉法,從n-1開(kāi)始,第一個(gè)符合條件的即為最大公約數(shù)。
如果n除以factor余數(shù)為0,說(shuō)明factor為n的最大公約數(shù),否則factor-1繼續(xù)循環(huán)
"""
factor = n - 1
while True:
if n % factor == 0:
return factor
else:
factor -= 1
本題的用意在于區(qū)別with_if_statement()和with_if_function()執(zhí)行的結(jié)果
if_statement()只有在滿足該條件的時(shí)候,才會(huì)檢查該分支是否有誤
而if_function()在執(zhí)行的時(shí)候,就會(huì)檢查各個(gè)參數(shù)是否有誤
所以在極端的情況下with_if_statement()會(huì)返回1
而with_if_function()會(huì)出現(xiàn)ZeroDivisionError: division by zero
def c():
return False
def t():
return 1 / 0
def f():
return 1
def hailstone(n):
"""
初始化長(zhǎng)度為1,因?yàn)槿绻鹡=1, 則不進(jìn)入循環(huán)直接打印n,返回length
在while循環(huán)里,根據(jù)定義對(duì)滿足條件的n進(jìn)行處理
"""
length = 1
while n != 1:
print(n)
if n % 2 == 0:
n = n // 2 # 得到整數(shù)n
else:
n = n*3 + 1
length += 1
print(n)
return length
def multiple(a, b):
"""
求a,b的最小公倍數(shù)(lowest common multiple)
思路和求最大公約數(shù)差不多,最小公倍數(shù)除以被除數(shù),余數(shù)為0
利用枚舉法,先從a,b兩個(gè)數(shù)中選出大的那個(gè)數(shù)作為初始的lcm,
每次循環(huán)lcm加上1,滿足條件則return lcm
"""
if a > b:
lcm = a
else:
lcm = b
while True:
if lcm % a == 0 and lcm % b == 0:
return lcm
else:
lcm += 1
def unique_digits(n):
"""
返回正整數(shù)n里不重復(fù)的數(shù)字的個(gè)數(shù)
先把n的類型從不可迭代的int轉(zhuǎn)換為可迭代的str,
利用set的特性去除重復(fù)的元素,最后返回set集合的長(zhǎng)度
"""
return len(set(str(n)))
最后編輯于 :2017.12.07 01:12:21
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者 【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。 平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。