Skip to content

Update Python面试宝典-基础篇-2020.md #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion Python面试宝典-基础篇-2020.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,24 @@ foo()
运行结果:

```
# python3.8
True True
True False
True

# python3.7
True False
True False
True

# python3.6
True True
True False
True
```
> python的内存模型是一个金字塔,由底层c molloc创建分配内存,在上层维护一个小数据池,小数据池中包含常用短字符串,[-5,256]数字,用户创建变量在小数据池中将直接指向这块内存地址,而在小数据池外的部分是用户创建的变量,这里要使用代码块来区分内存地址,在同一代码块中,相同的整型内存地址不变(性能优化考虑),以及复制(深/浅)时,整型变量在使用(改变)前,内存地址仍然指向原来的地址,本段代码中foo函数属于另一个代码块,创建新的内存地址,`print(e is f, e is d)`结果必然是`True False`,`print(g is a)`中,g,a,b均是小数据池中数据,内存地址相同,

> 至于python3.7版本中`print(a is b, c is d)`输出`True False`的结果,可能是该版本优化问题,查询资料后会来补充

上面代码中`a is b`的结果是`True`但`c is d`的结果是`False`,这一点的确让人费解。CPython解释器出于性能优化的考虑,把频繁使用的整数对象用一个叫`small_ints`的对象池缓存起来造成的。`small_ints`缓存的整数值被设定为`[-5, 256]`这个区间,也就是说,在任何引用这些整数的地方,都不需要重新创建`int`对象,而是直接引用缓存池中的对象。如果整数不在该范围内,那么即便两个整数的值相同,它们也是不同的对象。

Expand Down Expand Up @@ -1332,4 +1346,4 @@ def find_dup(items: list):

> **点评**:这道题的解法和[计数排序](<https://www.runoob.com/w3cnote/counting-sort.html>)的原理一致,虽然元素的数量非常多,但是取值范围`[1000, 10000)`并不是很大,只有9000个可能的取值,所以可以用一个能够保存9000个元素的`dups`列表来记录每个元素出现的次数,`dups`列表所有元素的初始值都是`0`,通过对`items`列表中元素的遍历,当出现某个元素时,将`dups`列表对应位置的值加1,最后`dups`列表中值大于1的元素对应的就是`items`列表中重复出现过的元素。

更多的面试题,请移步到我的知乎专栏[《Python面试宝典》](https://zhuanlan.zhihu.com/c_1228980105135497216)。
更多的面试题,请移步到我的知乎专栏[《Python面试宝典》](https://zhuanlan.zhihu.com/c_1228980105135497216)。