kenwoodjw / python_interview_question Goto Github PK
View Code? Open in Web Editor NEW关于python的面试题
关于python的面试题
使用glob模块可以更简单地完成任务:
def print_directory_contents(sPath):
from os.path import join
from glob import iglob
for p in iglob(join(sPath, "**/*), recursive=True):
print(p)
使用Python3
提供的Pathlib
包操作
def print_directory_contents(s_path):
from pathlib import (Path, PosixPath)
origin_path = Path(s_path) if not isinstance(s_path, PosixPath) else s_path
for s_child in origin_path.iterdir():
if not s_child.is_dir():
print(s_child)
continue
print_directory_contents(s_child)
例如#4.5
作为教程。。还是把装饰器写完整一点吧。。。把wraps和参数加上。。。
import time
from functools import wraps
def timeit(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.clock()
ret = func(*args, **kwargs)
end = time.clock()
print('used:',end-start)
return ret
return wrapper
@timeit
def foo():
print('in foo()')
class APP:
_instance = None
def __new__(cls, *args, **kwargs):
print("new")
if cls._instance is None:
print("Create")
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
print("init")
self.prop = None
app = APP()
app2 = APP()
能否优化下排版 很多问题答案可以拆分成列表
再说一种方法:
先用glob.glob("父/.pyc")找父目录的,后os.walk 获取dirs后遍历然后用glob.glob("子/.pyc")。
原代码与结果为:
N =100
print ([[x for x in range(1,100)] [i:i+3] for i in range(0,100,3)])
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],... [97, 98, 99], []]
=100
可以更改为:
s=[[ m for m in range(j+1,j+4)] for j in [ i for i in range(0,97,3)]]
print(s)
else部分和size = size +1 应该是与第一个if对齐的,不然 d会永远是装不进值,while循环也永远不会停止。
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
with Singleton._instance_lock:
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Foo(Singleton):
pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True
while循环第一个if后加个else
class Solution: def twoSum(self,nums,target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d = {} size = 0 while size < len(nums): if target-nums[size] in d: if d[target-nums[size]] < size: return [d[target-nums[size]],size] else: d[nums[size]] = size size = size +1 else: d[target-nums[size]] = nums[size] solution = Solution() list = [2,9,11,15,7] target = 9 nums = solution.twoSum(list,target) print(nums)
代码块最好使用高亮,看起来会方便一些。
def f():
return
两行代码实现:
from functools import reduce
reduce(lambda a,u: a if u in a else a+[u], l1, [])
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Foo(object):
pass
foo1 = Foo()
foo2 = Foo()
print foo1 is foo2 #True
这么一个全局大字典,不怕内存泄露的么
原题 72.map(lambda x:xx,[y for y in range(3)])的输出?
应该更新为 72.map(lambda x:x*x,[y for y in range(3)])的输出?
结果为
[0,1,4]
保持源代码不动的情况,while循环第一个if后加个else赋值?
else:
d[target-nums[size]] = nums[size]
HI,机器之心想向读者介绍您的Python面试题项目,希望获得您的授权~
都用eval为啥不用到底
isinstance(eval("123"+"+4-4"),int) # true
Jython
确实没有,但PyPy
依然存在GIL
,下面引用一段PyPy官方文档的内容:
Does PyPy have a GIL? Why?
Yes, PyPy has a GIL. Removing the GIL is very hard. On top of CPython, you have two problems: (1) GC, in this case reference counting; (2) the whole Python language.
For PyPy, the hard issue is (2): by that I mean issues like what occurs if a mutable object is changed from one thread and read from another concurrently. This is a problem for any mutable type: it needs careful review and fixes (fine-grained locks, mostly) through the whole Python interpreter. It is a major effort, although not completely impossible, as Jython/IronPython showed. This includes subtle decisions about whether some effects are ok or not for the user (i.e. the Python programmer).
CPython has additionally the problem (1) of reference counting. With PyPy, this sub-problem is simpler: we need to make our GC multithread-aware. This is easier to do efficiently in PyPy than in CPython. It doesn’t solve the issue (2), though.
Note that since 2012 there is work going on on a still very experimental Software Transactional Memory (STM) version of PyPy. This should give an alternative PyPy which works without a GIL, while at the same time continuing to give the Python programmer the complete illusion of having one. This work is currently a bit stalled because of its own technical difficulties.
还有一个方法
a = -123
stra = str(a)
if a >= 0:
print(int(stra[::-1]))
else:
print(int(stra[0]+stra[1:][::-1]))
a = 10
b = 20
c = [a]
a = 15
print(type(c),c)
这个输出的应该是个list了,不是数值10了。
<class 'list'> [10]
经典的谬误之一
** 4.GET方式提交的数据最多只能有1024字节,而POST则没有限制 安全性问题,正如在(2)中提到,使用GET的时候,参数会显示在地址栏上,而POST不会**
可能并不知道 ES 的 Query 查询是把请求体写在 Get 的 body 中的?
建议读一下 RFC 2616
如题,我的微信:W_2015_
包括但不限于以下问题
.format
OR %
OR f-string#1.1
第一个案例这个答案为啥要append啊,循环里yield eachline,不就好了吗,这不多此一举吗。。。
第二个案例这个答案是搞笑的吧?根本就是错的。。。
看到64
时,个人觉得带参数的装饰器
指的应该是装饰器本身可以传参的情况:
def dec(text):
def decorator(func):
def wrapper(*args, **kw):
print(text)
return func(*args, **kw)
return wrapper
return decorator
@dec('Hello')
def func():
pass
#4.10
N是否能被3整除?如果不能整除,要怎么处理?
样例:
n = 21
print([list(range(i,i+3)) for i in range(1,n,3)])
12,14重复了
def get_lines():
with open('file.txt','rb') as f:
records = iter(partial(file.read,4096),b'')
for r in records:
yield r.decode('utf-8')
if name == 'main':
for e in get_lines():
process(e) # 处理每一行数据
生成器(Generator)是创建迭代器的简单而强大的工具
很好奇这样的结论是怎么来的
使用itemgetter 更优雅
from operator import itemgetter
alist = [{'name': 'a', 'age': 20}, {'name': 'b', 'age': 30}, {'name': 'c', 'age': 25}]
alist_sorted = sorted(alist, key=itemgetter('age'), reverse=True)
37.给定一个任意长度数组,实现一个函数
让所有奇数都在偶数前面,而且奇数升序排列,偶数降序排序,如字符串'1982376455',变成'135798642'
"1982376455"
不是应该得到 "1355798642"
吗?string
或者说 List[char]
,为什么变为了 List[int]
?按照题目所解释那样,如果输入有大写字母,那么最后返回也是应该去除掉这个大写字母对应的小写字母的,所以应先对输入进行小写字母转换再进行后续操作, 即 s2 = set(a.lower())
Number: a. 整型 int、 长整型 long、浮点型 float、 复数 complex
Number 不包含长整型long 包含bool
#4.5 这题第二个方法太牵强了 性能也不行还 不如用glob (大哥你喜欢用append的习惯得改。。。
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)
def get_lines():
l = []
with open('test/1.py','rb') as f:
data = f.readlines(60000)
l.append(data)
yield l
def my_get_lines(num_lines=1):
with open(r'test/1.py', 'r', encoding="utf-8") as file:
while True:
data = file.readlines(num_lines)
if not data:
break
yield data
file.read([size])
从文件读取指定的字节数(size),如果未给定或为负则读取所有。
file.readline([size])读取整行,包括 "\n" 字符。
file.readlines([sizeint])
读取所有行并返回列表,若给定sizeint>0,则是设置一次读多少字节,这是为了减轻读取压力。
直接看官方的介绍吧。。iterators
3.4给的答案有问题
for iterms in str1.split('|'):
key, value = iterms.split(':'):
dict1[key] = value
iterms.split(':')后面就不应该有冒号了,下一行的存进dict1操作应该是依次进行的,而不是在它下一级,去掉冒号少一级缩进就OK了
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.