GithubHelp home page GithubHelp logo

python_interview_question's Issues

2.补充缺失的代码

使用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)

遍历文件,可以考虑pathlib

使用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()

找.pyc文件

再说一种方法:
先用glob.glob("父/.pyc")找父目录的,后os.walk 获取dirs后遍历然后用glob.glob("子/.pyc")。

:octocat: From gitme Android

29题空格的问题

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

### 29.Given an array of integers 第一个例子死循环

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 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 题是错误的

原题 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]

获得授权

HI,机器之心想向读者介绍您的Python面试题项目,希望获得您的授权~

GIL锁不是只有CPython才有

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.

67-print c 输出是否有误

a = 10
b = 20
c = [a]
a = 15
print(type(c),c)
这个输出的应该是个list了,不是数值10了。
<class 'list'> [10]

[吐槽] post 和 get的区别?

经典的谬误之一

** 4.GET方式提交的数据最多只能有1024字节,而POST则没有限制 安全性问题,正如在(2)中提到,使用GET的时候,参数会显示在地址栏上,而POST不会**

可能并不知道 ES 的 Query 查询是把请求体写在 Get 的 body 中的?

建议读一下 RFC 2616

统一代码风格

包括但不限于以下问题

  • 代码块的前置缩进究竟要不要
  • 该加的空格(双目运算符, 注释前后等)和不需要的空格(行末, 空行中的空格)
  • 必要的空行
  • .format OR % OR f-string
  • 是用单引号还是双引号
  • 命名规则
  • import 位置

参考: https://www.python.org/dev/peps/pep-0008/

[吐槽] #1.1 错得最离谱的一题

#1.1
第一个案例这个答案为啥要append啊,循环里yield eachline,不就好了吗,这不多此一举吗。。。
第二个案例这个答案是搞笑的吧?根本就是错的。。。

  1. readlines返回的是列表,你append到另外一个list,
  2. 其实py3里面,for i in f已经是stream了,
  3. 最后你还yield?
    其实10G的文本读写除了for in ,还可以用mmap啊,

64.带参数的装饰器

看到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

[吐槽]新式类和旧式类

新式类和旧式类之间的差异有很多

听说你会 Python

我在这篇文章的第三题提到过一点

而这些差异都没法归结到所谓的“本质差异是 MRO 上”

建议重新斟酌一下

1.文件操作,这样是否可以?

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) # 处理每一行数据

9.请按alist中元素的age由大到小排序

使用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)

Q37 有问题啊...

37.给定一个任意长度数组,实现一个函数
让所有奇数都在偶数前面,而且奇数升序排列,偶数降序排序,如字符串'1982376455',变成'135798642'

  1. 为什么把重复的数去掉了?"1982376455" 不是应该得到 "1355798642" 吗?
  2. 原来是一个 string 或者说 List[char],为什么变为了 List[int] ?

22题疑问

按照题目所解释那样,如果输入有大写字母,那么最后返回也是应该去除掉这个大写字母对应的小写字母的,所以应先对输入进行小写字母转换再进行后续操作, 即 s2 = set(a.lower())

[吐槽] #4.5 第二个方法有点牵强

#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)

1.有一个jsonline格式的文件file.txt大小约为10K

def get_lines():
    l = []
    with open('test/1.py','rb') as f:
      data = f.readlines(60000)
    l.append(data)
    yield l

上面代码yield l结束是否只能读取文件6万行,可能读取不到文件末尾

下面是我的代码

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

53题解释不全

file.read([size])
从文件读取指定的字节数(size),如果未给定或为负则读取所有。

file.readline([size])读取整行,包括 "\n" 字符。

file.readlines([sizeint])
读取所有行并返回列表,若给定sizeint>0,则是设置一次读多少字节,这是为了减轻读取压力。

3.4 SyntaxError: invalid syntax

3.4给的答案有问题
for iterms in str1.split('|'):
key, value = iterms.split(':'):
dict1[key] = value
iterms.split(':')后面就不应该有冒号了,下一行的存进dict1操作应该是依次进行的,而不是在它下一级,去掉冒号少一级缩进就OK了

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.