自己实现一些内建函数的部分功能
def my_abs(num):
if not isinstance(num,(int, float)):
print('false')
return False
if num < 0:
num *= -1
return num
print(my_abs(2))
print(my_abs(-2))
my_abs('tes')
def my_sum(lst):
sum = 0
if not isinstance(lst, list):return lst
for item in lst:
if isinstance(item,(int,float)):
sum += item
return sum
print(my_sum([1,2,'12',3]))
def my_max(seq):
max_seq = None
if not isinstance(seq,(list, tuple)):return max_seq
if len(seq) == 0:return max_seq
max_seq = seq[0]
for item in seq:
if not isinstance(item,(int, float)):continue
elif item > max_seq:
max_seq = item
return max_seq
print(my_max([1,2,3,'4']))
def my_min(seq):
min_seq = None
if not isinstance(seq, (list, tuple)): return min_seq
if len(seq) == 0: return min_seq
min_seq = seq[0]
for item in seq:
if not isinstance(item, (int, float)):
continue
elif item < min_seq:
min_seq = item
return min_seq
print(my_min([1, 2, 3, '4']))
str_int_dic = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9
}
def my_int(string):
res = 0
for item in string:
int_value = str_int_dic[item]
res = res*10 + int_value
return res
print(my_int('456'))
int_str_dict = {
0: '0',
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
7: '7',
8: '8',
9: '9',
}
def my_str(intnum):
if intnum == 0:
return '0'
lst = []
is_positive = True
if intnum < 0:
is_positive = False
intnum = abs(intnum)
while intnum:
number = intnum % 10
intnum //= 10
str_number = chr(number+48)
lst.append(str_number)
if not is_positive:
lst.append('-')
lst = lst[::-1]
return ''.join(lst)
print(my_str(9))
print(my_str(-123))
def my_float(string):
arrs = string.split('.')
int_value = my_int(arrs[0])
float_value = my_int(arrs[1])
while float_value > 1:
float_value *= 0.1
return int_value + float_value
print(my_float("42.0"))
print(type(my_float("42.22")))
from collections import Iterable
def my_len(obj):
if not isinstance(obj, Iterable):return None
length = 0
for item in obj:
length += 1
return length
print(my_len([1,2,]))
print(my_len((1,2)))
print(my_len({'a':2}))
def my_enumerate(lst):
for i in range(my_len(lst)):
yield i, lst[i]
lst = ['a', 'b', 'c']
for index,item in my_enumerate(lst):
print(index, item)
def my_all(lst):
for item in lst:
if not item:
return False
return True
lst1 = [True, False, True]
print(my_all(lst1))
print(all(lst1))
def my_any(lst):
for item in lst:
if item:
return True
return False
print(my_any(lst))