美文网首页
python小程序段

python小程序段

作者: Oneshot_fea8 | 来源:发表于2019-01-29 21:39 被阅读0次

自行书写python中将字符床转换为整数的函数:

from functools import reduce

def str2int(s):
    def fn(x, y):
        return x * 10 + y

    def char2num(s):
        return{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    return reduce(fn, map(char2num, s))
#或者使用lamda函数
"""
def str2int(s):
    return reduce(lamda x, y: x * 10 + y, map(char2num, s))
"""

print(str2int('13579'))   

13579

利用 map() 函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入: ['adam', 'LISA', 'barT'] ,输出:['Adam','Lisa', 'Bart'] :

def normalize(name):
    name = name.lower()
    return name[0].upper() + str(name[1:])


L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)    

['Adam', 'Lisa', 'Bart']

Python 提供的 sum() 函数可以接受一个 list 并求和,请编写一个 prod()函数,可以接受一个 list 并利用 reduce() 求积:

from functools import reduce

def prod(L):
    def mul(x, y):
        return x*y
    return reduce(mul, L)


print(prod([3, 5, 7, 9]))

945

利用 map 和 reduce 编写一个 str2float 函数,把字符串 '123.456' 转换成浮点数 123.456 :

from functools import reduce

def str2float(s):
    dot = False
    dit = 1

    def f(x, y):
        nonlocal dot
        nonlocal dit
        if y == '.':
            dot = True
            return x
        if dot:
            dit = dit/10
            return x + y*dit
        return x*10 + y

    def str2int(x):
        dict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}
        return dict[x]
    return reduce(f, map(str2int, s))


print('str2float(\'123.456\') =', str2float('123.456'))   

str2float('123.456') = 123.456

打印30以内的素数:

def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

def _not_divisible(n):
    return lambda x: x % n > 0

def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(_not_divisible(n), it)


for n in primes():
    if n < 30:
        print(n)
    else:
        break

2
3
5
7
11
13
17
19
23
29

利用filter滤掉非回数:

def is_palindrome(n):
    return str(n) == str(n)[::-1]


output = filter(is_palindrome, range(1, 1000))
print(list(output))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]

filter() 的作用是从一个序列中筛出符合条件的元素。由于 filter() 使用了惰性计算,所以只有在取 filter() 结果的时候,才会真正筛选并每次返回下一个筛出的元素。

用一组 tuple 表示学生名字和成绩,用 sorted() 对上述列表分别按名字和成绩排序:

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

def by_name(t):
    return t[0].lower()

def by_score(t):
    return t[1]


L1 = sorted(L, key=by_name)
L2 = sorted(L, key=by_score, reverse=True)
print(L1)
print(L2)   

[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]

闭包的应用:

def count():
    fs = []
    for i in range(1, 4):
        def f():
            return i*i
        fs.append(f)
    return fs


f1, f2, f3 = count()
print(f1(), f2(), f3())

def count2():
    def f1(j):
        def g():
            return j*j
        return g
    fs = []
    for i in range(1, 4):
        fs.append(f1(i))
    return fs


f4, f5, f6 = count2()
print(f4(), f5(), f6())

9 9 9
1 4 9

image

python中的private用处

image

相关文章

  • python小程序段

    自行书写python中将字符床转换为整数的函数: 13579 利用 map() 函数,把用户输入的不规范的英文名字...

  • 无标题文章

    在此记录下Python的某段小程序,以此证明python的简单实用性 < !/usr/bin/python Fil...

  • Python

    1. 有关main() python程序是顺序执行的,而C++中main()是程序的入口 一段python程序以p...

  • Python学习之路

    python 解释一段python程序时提示很特殊的错误: IndentationError: unexpecte...

  • 教你如何自动筛选显著变量

    以下stata源代码来自于宝器兄的分享,整个过程需要使用stata和Python小程序。其中Python小程序是为...

  • Python笔记——记录程序运行时间

    记录一个python中的小模块 在python程序中如何记录程序运行的时间呢? 可以借助python中的time模...

  • 想不想锁住别人的电脑?运用python成为黑客 !

    前言 一个可以套路别人的python小程序,该程序是用Python语言使用pycharm工具编写的。该程序由客户端...

  • 想不想锁住别人的电脑?运用python成为黑客 !

    前言 一个可以套路别人的python小程序,该程序是用Python语言使用pycharm工具编写的。该程序由客户端...

  • Python小程序

    今天在b站上看到一个小视频,介绍一个程序员表白的python小程序。不用纠结他说的到底准不准确,那个小程序跑出来的...

  • C语言为什么快

    同样一段打印程序的对比C Python python简洁的多,但是运行时间会比C慢;这个程序反应不出太多的时差;不...

网友评论

      本文标题:python小程序段

      本文链接:https://www.haomeiwen.com/subject/awefsqtx.html