18.反转一个整数,例如-123 --> -321
class Solution(object): def reverse(self,x): if -10<x<10: return x str_x = str(x) if str_x[0] !="-": str_x = str_x[::-1] x = int(str_x) else: str_x = str_x[1:][::-1] x = int(str_x) x = -x return x if -2147483648<x<2147483647 else 0 if __name__ == '__main__': s = Solution() reverse_int = s.reverse(-120) print(reverse_int)
结果为:-21
19.设计实现遍历目录与子目录,抓取.pyc文件
第一种方法:
import os def get_files(dir,suffix): res = [] for root,dirs,files in os.walk(dir): for filename in files: name,suf = os.path.splitext(filename) if suf == suffix: res.append(os.path.join(root,filename)) print(res) get_files("./",'.pyc')
结果为:[]
第二种方法:
import os def pick(obj): if ob.endswith(".pyc"): print(obj) def scan_path(ph): file_list = os.listdir(ph) for obj in file_list: if os.path.isfile(obj): pick(obj) elif os.path.isdir(obj): scan_path(obj) if __name__=='__main__': path = input('输入目录') scan_path(path)
第三种方法:
from glob import iglob def func(fp, postfix): for i in iglob(f"{fp}/**/*{postfix}", recursive=True): print(i) if __name__ == "__main__": postfix = ".pyc" func("K:Python_script", postfix)
20.一行代码实现1-100之和
count=sum(range(0,100)) print(count)
结果为:4950