python函數式
#用map格式化list中的字符串
list1 = ["ADMIN", "hello", "LinGe"]
maps = lambda l : map(lambda s : s[0].upper() + s[1:].lower(), l)
re = list(maps(list1))
print(re)
#用reduce求list中的乘積
from functools import reduce
list2 = [2,3,4,5]
re2 = lambda l : reduce(lambda x,y : x * y, l)
print(re2(list2))
#不使用int字符串轉數字或浮點
def str2float(s):
idx = -1
str1 = ''
for i,v in enumerate(s):
if v == '.':
idx = i
else:
str1 += v
re = 0
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
for i,v in enumerate(str1):
re = re + DIGITS[v] * 10**(len(str1) - (i+1))
if idx != -1:
return re / 10**len(s[idx+1:])
else:
return re
strs = "125.0"
print(str2float(strs))
#只能轉浮點
def str2float2(s):
def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
def zheng(x,y):
return x * 10 + y
def xiao(x,y):
return x / 10 + y
a=s.find('.')
s1=[]
s2=[]
for i in range(a):
s1.append(s[i])
for j in range(a+1,len(s)):
s2.append(s[j])
s2=s2[::-1]
return reduce(zheng,map(char2num,s1)) + reduce(xiao,map(char2num,s2))/10
print(str2float2(strs))
#filter回數(121,12321)
re3 = lambda n : filter(lambda v : v < 10 or str(v) == str(v)[::-1], range(n))
print(list(re3(10000)))