利用map和reduce編寫乙個str2float函式,把字串』123.456』轉換成浮點數123.456:
from functools import
reduce
# '123.456'
digits =
defstr2float
(s):
defchar2num
(s):
return digits[s]
n=s.index(
'.')
s1=s[
:n] s2=s[n+1:
]return
reduce
(lambda x,y: x*
10+y,
map(char2num,s1))+
(reduce
(lambda x,y: x*
10+y,
map(char2num,s2)))
/10**len
(s2)
print
('str2float(\'123.456\') ='
, str2float(
'123.456'
))
用filter求素數(埃氏篩法)
def
_odd_iter()
: n=
1while
true
: n=n+
2yield n
defprimes()
:yield
2 it = _odd_iter(
)while
true
: n=
next
(it)
yield n
it=filter
(lambda x:x%n>
0,it)
for n in primes():
if n <
1000
:print
(n)else
:break
回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()篩選出回數:
def
is_palindrome
(n):
strs =
list
(str
(n))
strs.reverse(
) afterstrs =
''.join(strs)
return
int(afterstrs)
==noutput =
filter
(is_palindrome,
range(1
,1000))
print
('1~1000:'
,list
(output)
)
python刷題題庫 python題庫刷題訓練
python 標準庫 math 中用來計算平方根的函式是.a sqrt b pow c power d abs c python 源 程式編譯後的擴充套件名為 a py b pdf c.python基礎100練習題 其它 工作范文 實用文件。例項 001 數字組合 python 期末試題題庫 c t...
Python3必備刷題基礎
list.insert index,obj 在index處插入物件 list.index obj,start,end 找出與obj第乙個匹配項的索引位置,start和end可選。list.remove obj 移除列表中某個物件的第乙個匹配項 list.pop index 1 obj移除乙個元素並返...
程式設計題彙總3
1.請寫出c c 語言實現矩陣乘法加速的常用方法for i 0 i i for j 0 j j sum 0 for k 0 k但是考慮了快取記憶體的問題後,其實有一種更好的實現方式 for i 0 i i for k 0 k r a i k for j 0 j細看一番就會發現這兩種實現語義是等價的,...