zoukankan      html  css  js  c++  java
  • python小例子

    1,使用Python解决数学问题。

    ABCD乘9 = DBCA    那么 A=?,B=?,C? D=? 

    for A in range(1,10):
        for B in range(0,10):
            for C in range(0,10):
                for D in range(1,10):
                    if (A*1000 + B * 100 + C * 10 +D)* 9 == (D*1000 + C*100 +B*10 + A):
                        print('{0}{1}{2}{3}*9 == {3}{2}{1}{0}'.format(A,B,C,D))
    

      

    2,使用python求阶乘的和。

    0!+1!+2!+3!+4!+....+n!

    def fact(n):
        if n == 0:
            return 1
        return n * fact(n-1)
    
    while True:
        result = 0
        n  = input('Please input number:')
        if not n.isdigit():
            print('你输入的不是纯数字,请重新输入!')
            continue
        for i in range(0,int(n)+1):
            result+=fact(i)
        print(result)
    

      

     3,计算输入字符串有多少个空格、字符串、数字、特殊符号的个数。

    while True:
        n  = input('pelase input somthing:')
        num = strings = space = other = 0
        for i in n:
            if str(i).isalpha():
                strings+=1
            elif str(i).isdigit():
                num +=1
            elif str(i).isspace():
                space +=1
            else:
                other+=1
        print('数字有{0}个,字母有{1}个,空格有{2}个,其他字符{3}个'.format(num,strings,space,other))
    

      

    4,乘法口诀

    for h in range(1,10):
            for l in range(1,h+1):
                print('{0}*{1} = {2} '.format(l,h,l*h),end = '')
            if h == l:
                print('')
    

      

    5,/etc/passwd排序,按照uid排序(思路:创建2个列表,一个列表存放所有的uid并排序,一个存放所有的行,然后存放uid的列表排序,最后将文件中uid与uid比较,追加到新的文件即可。)

    import codecs
    file = 'passwd'
    sortfile = 'sortpasswd'
    filecontext = []
    sortuid = []
    with codecs.open('sortfile','wb') as fd:
        with codecs.open(file,encoding='utf-8') as f:
            filecontext +=  f.readlines()
            for line in filecontext:
                sortuid.append(int(line.split(':')[2]))
            sortuid.sort()
            for uid in sortuid:
                for line in filecontext:
                    if str(uid) == line.split(':')[2]:
                        fd.write(line.encode('utf-8'))
    

      

    
    
  • 相关阅读:
    今日总结
    今日总结
    今日总结
    本周总结
    今日总结
    今日总结
    今日总结
    今日总结
    今日总结
    vue3函数setUp和reactive函数详细讲解
  • 原文地址:https://www.cnblogs.com/lin1/p/8336823.html
Copyright © 2011-2022 走看看