Skip to content

Latest commit

 

History

History
342 lines (242 loc) · 8.76 KB

202105W2.md

File metadata and controls

342 lines (242 loc) · 8.76 KB

@Author : Lewis Tian ([email protected])

@Link : github.com/taseikyo

@Range : 2021-05-09 - 2021-05-15

Weekly #28

readme | previous | next

本文总字数 2286 个,阅读时长约:4 分 22 秒,统计数据来自:算筹字数统计

*Photo by Igor Kyryliuk on Unsplash

Table of Contents

  • algorithm
    • 来,挑战一套Python面试题
    • 一道新浪面试题
  • review
    • 掌握 10 个有用的 Python 代码片段,编程像 Pro(:-1:)
    • 适用于日常编程的 11 个 Python 单行代码(:-1:)
    • 三分钟理解 Python 的 Lambdas 表达式(:-1:)
  • tip
    • Python async 异步编程
  • share
    • 学会爱自己,你值得

algorithm 🔝

1、下面的 Python 代码会输出什么

print([(x, y) for x, y in zip('abcd', (1, 2, 3, 4, 5))])
print({x: f'item{x ** 2}' for x in range(5) if x % 2})
print(len({x for x in 'hello world' if x not in 'abcdefg'}))
# [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# {1: 'item1', 3: 'item9'}
# 6
from functools import reduce

items = [11, 12, 13, 14]
print(reduce(int.__mul__, map(lambda x: x // 2,
                              filter(lambda x: x ** 2 > 150, items))))
# 42

2、写一个函数,该函数的参数是一个列表,如果列表中的有三个元素相加之和为 0,就将这个三个元素组成一个三元组,最后该函数返回一个包含了所有这样的三元组的列表。

def foo(array):
    for x in range(len(array)):
        for y in range(x+1, len(array)):
            for z in range(y+1, len(array)):
                if array[x] + array[y] + array[z] == 0:
                    print(x, y, z)

3、用 5 个线程,将 1 ~ 100 的整数累加到一个初始值为 0 的变量上,每次累加时将线程 ID 和本次累加后的结果打印出来。

import threading


class MyThread(threading.Thread):
    def __init__(self):
        super(MyThread, self).__init__()

    def run(self):
        print(sum(range(1, 100)) + self.ident)


for x in range(5):
    MyThread().start()
# 17862
# 16258
# 7678
# 9902
# 9334

2. 一道新浪面试题

func_list = [lambda x: x+i for i in range(10)]
v1 = func_list[0](100)
v2 = func_list[3](100)
print(v1, v2)

结果是 109 和 109,真有趣。

至于为啥是这样,查了一下,是因为只有在调用函数的时候才开始对内部的变量进行引用,对 i 来说, 当函数对它引用的时候, 它已经变为 9 了。

review 🔝

标题是 10 Useful Python Snippets To Code Like a Pro,我直接硬翻的。

1、交换两个变量的值

a = 1
b = 2
a, b = b, a

2、不用循环来复制字符串

name = "Banana"
print(name * 4)

3、反转字符串

sentence = "This is just a test"
reversed = sentence[::-1]

4、将字符串列表压缩为一个字符串

words = ["This", "is", "a", "Test"]
combined = " ".join(words)

5、合并比较操作(Comparison Chains)

x = 100
res = 0 < x < 1000

6、在列表中查找最频繁的元素

test = [6, 2, 2, 3, 4, 2, 2, 90, 2, 41]
most_frequent = max(set(test), key=test.count)

7、列表解包

arr = [1, 2, 3]
a,b,c = arr

8、一行的 if-else 语句

age = 30
age_group = "Adult" if age > 18 else "Child"

9、列表推导式

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num * num for num in numbers]

10、简化 if 语句

if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5:
    pass

if n in [0, 1, 2, 3, 4, 5]:
    pass

除了第六个是我没用过外,其他的都是老生常谈的东西,就这东西还要会员?

1、合并字典

我之前看到过这个例子,Python 3.9 之后才支持

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4, 'd': 5}
dict1 | dict2
# {'a': 1, 'b': 3, 'c': 4, 'd': 5}

2、自定义排序

sorted([-5, -1, 2, 3, 4], key=lambda x: abs(x))
# [-1, 2, 3, 4, -5]

3、将嵌套列表压平

nested_lists = [[1, 2], [3, 4, 5], [6]]
[item for inner_list in nested_lists for item in inner_list]
# [1, 2, 3, 4, 5, 6]

4、交换变量值

a = 10
b = 20
a, b = b, a

5、给多个变量赋值

a, b, c = 10, False, 'Hello World'

6、打开文件

with open('file.txt', 'r') as f:
    content = f.readlines()

7、格式化输出

n_processes = 1
f"{n_processes} process{' is' if n_processes == 1 else 'es are'} running"
# '1 process is running'
n_processes = 2
f"{n_processes} process{' is' if n_processes == 1 else 'es are'} running"
# '2 processes are running'

8、Lambda 函数

circle_area = lambda r: math.pi * (r ** 2)
circle_area(10)
# 314.1592653589793

9、Map 函数

nums = [1, 2, 3, 4, 5]
list(map(lambda n: n**2, nums))
# [1, 4, 9, 16, 25]

10、计算累积和

import itertools
list(itertools.accumulate([1, 2, 3, 4, 5]))

11、列表推导式

numbers = [1, 2, 3, 4, 5]
[num for num in numbers if num > 3]

这篇文章也是一样,都是些很常见的东西,收到一起就要开会员了,感觉跟 CSDN 也差不多嘛?

这篇文章其实啥都没讲,如果真奔着理解 Lambda 表达式去看它会发现看完根本没啥用。

在 Python 中 Lambda 函数就是一种匿名函数,它的语法很简单,但是用起来却可以花里胡哨的。

如下,关键字 lambda,冒号前面就是一系列的参数,后面就是返回的结果

lambda arguments : expression
(lambda x : x * x)(15.0) # returns 225.0

又是篇垃圾会员文章,我就不该点进去 :)

tip 🔝

1. Python async 异步编程

感觉讲得挺不错的,听下来对 Python 异步编程又有了更深的理解。

share 🔝

自从去年(2020)听过初中表弟的一节英语课,他们英语老师以一句 "Love your life; Love yourself." 结尾,之后我就将其作为微信签名了,不过将前后顺序改了下。

这篇文章也是讲的 "Love yourself",其中 10 点我最喜欢最后一点:And as bad as you have been, there is good in you. The lost get found. This is not the end of your story.

尽管你一直很糟糕,但你身上也有优点。丢失的东西终将被找到,这并不是你的故事的结束。

你丢失的(不曾拥有的),终将被你找到。

尽管有时候生活很苦,但是要爱自己,对自己好一点。

下面是原文:

Love Yourself

You deserve your own compassion.

  1. With arms wide open and a forgiving heart.
  2. When you think you’re not good enough for anyone.
  3. Through your seemingly endless mistakes, the crushing disappointments and your worst days.
  4. When the reflection staring back from the mirror doesn’t please you and there are no signs that it will tomorrow or the day after.
  5. Every time you fail to meet society’s standards of beauty or act contrary to its conventions and you’re judged for it.
  6. When cantankerous church folk whose pharisaic religiosity has made them incapable of kindness make you feel unworthy of God’s love.
  7. Even though it looks like everyone has left you behind and you cannot catch up.
  8. On mornings you feel like crap and nights you crave company but there’s no one around.
  9. Because this is your life. It may not seem like much but it is yours, no one else’s.
  10. And as bad as you have been, there is good in you. The lost get found. This is not the end of your story.

To myself, and you, with love.

readme | previous | next