在本文中,您将会了解到关于pythongreenlet的新资讯,并给出一些关于centos下python多版本管理(pyenv+python+virtualenv+ipython)、Diffbetwe
在本文中,您将会了解到关于python greenlet的新资讯,并给出一些关于centos下python多版本管理(pyenv+python+virtualenv+ipython)、Diff between Python2 and Python3、Greenlet API的纯python实现、leetcode 496. Next Greater Element I(python)的实用技巧。
本文目录一览:- python greenlet
- centos下python多版本管理(pyenv+python+virtualenv+ipython)
- Diff between Python2 and Python3
- Greenlet API的纯python实现
- leetcode 496. Next Greater Element I(python)
python greenlet
greenlet: Lightweight concurrent programming
Motivation
The “greenlet” package is a spin-off of Stackless, a version of CPython that supports micro-threads called “tasklets”. Tasklets run pseudo-concurrently (typically in a single or a few OS-level threads) and are synchronized with data exchanges on “channels”.
A “greenlet”, on the other hand, is a still more primitive notion of micro-thread with no implicit scheduling; coroutines, in other words. This is useful when you want to control exactly when your code runs. You can build custom scheduled micro-threads on top of greenlet; however, it seems that greenlets are useful on their own as a way to make advanced control flow structures. For example, we can recreate generators; the difference with Python’s own generators is that our generators can call nested functions and the nested functions can yield values too. (Additionally, you don’t need a “yield” keyword. See the example in test/test_generator.py).
Greenlets are provided as a C extension module for the regular unmodified interpreter. Example
Let’s consider a system controlled by a terminal-like console, where the user types commands. Assume that the input comes character by character. In such a system, there will typically be a loop like the following one:
def process_commands(*args): while True: line = '''' while not line.endswith(''\n''): line += read_next_char() if line == ''quit\n'': print "are you sure?" if read_next_char() != ''y'': continue # ignore the command process_command(line)
Now assume that you want to plug this program into a GUI. Most GUI toolkits are event-based. They will invoke a call-back for each character the user presses. [Replace “GUI” with “XML expat parser” if that rings more bells to you :-)] In this setting, it is difficult to implement the read_next_char() function needed by the code above. We have two incompatible functions:
def event_keydown(key): ??
def read_next_char(): ?? should wait for the next event_keydown() call
You might consider doing that with threads. Greenlets are an alternate solution that don’t have the related locking and shutdown problems. You start the process_commands() function in its own, separate greenlet, and then you exchange the keypresses with it as follows:
def event_keydown(key): # jump into g_processor, sending it the key g_processor.switch(key)
def read_next_char(): # g_self is g_processor in this simple example g_self = greenlet.getcurrent() # jump to the parent (main) greenlet, waiting for the next key next_char = g_self.parent.switch() return next_char
g_processor = greenlet(process_commands) g_processor.switch(*args) # input arguments to process_commands()
gui.mainloop()
In this example, the execution flow is: when read_next_char() is called, it is part of the g_processor greenlet, so when it switches to its parent greenlet, it resumes execution in the top-level main loop (the GUI). When the GUI calls event_keydown(), it switches to g_processor, which means that the execution jumps back wherever it was suspended in that greenlet – in this case, to the switch() instruction in read_next_char() – and the key argument in event_keydown() is passed as the return value of the switch() in read_next_char().
Note that read_next_char() will be suspended and resumed with its call stack preserved, so that it will itself return to different positions in process_commands() depending on where it was originally called from. This allows the logic of the program to be kept in a nice control-flow way; we don’t have to completely rewrite process_commands() to turn it into a state machine. Usage Introduction
A “greenlet” is a small independent pseudo-thread. Think about it as a small stack of frames; the outermost (bottom) frame is the initial function you called, and the innermost frame is the one in which the greenlet is currently paused. You work with greenlets by creating a number of such stacks and jumping execution between them. Jumps are never implicit: a greenlet must choose to jump to another greenlet, which will cause the former to suspend and the latter to resume where it was suspended. Jumping between greenlets is called “switching”.
When you create a greenlet, it gets an initially empty stack; when you first switch to it, it starts the run a specified function, which may call other functions, switch out of the greenlet, etc. When eventually the outermost function finishes its execution, the greenlet’s stack becomes empty again and the greenlet is “dead”. Greenlets can also die of an uncaught exception.
For example:
from greenlet import greenlet
def test1(): print 12 gr2.switch() print 34
def test2(): print 56 gr1.switch() print 78
gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch()
The last line jumps to test1, which prints 12, jumps to test2, prints 56, jumps back into test1, prints 34; and then test1 finishes and gr1 dies. At this point, the execution comes back to the original gr1.switch() call. Note that 78 is never printed. Parents
Let’s see where execution goes when a greenlet dies. Every greenlet has a “parent” greenlet. The parent greenlet is initially the one in which the greenlet was created (this can be changed at any time). The parent is where execution continues when a greenlet dies. This way, greenlets are organized in a tree. Top-level code that doesn’t run in a user-created greenlet runs in the implicit “main” greenlet, which is the root of the tree.
In the above example, both gr1 and gr2 have the main greenlet as a parent. Whenever one of them dies, the execution comes back to “main”.
Uncaught exceptions are propagated into the parent, too. For example, if the above test2() contained a typo, it would generate a NameError that would kill gr2, and the exception would go back directly into “main”. The traceback would show test2, but not test1. Remember, switches are not calls, but transfer of execution between parallel “stack containers”, and the “parent” defines which stack logically comes “below” the current one. Instantiation
greenlet.greenlet is the greenlet type, which supports the following operations:
greenlet(run=None, parent=None) Create a new greenlet object (without running it). run is the callable to invoke, and parent is the parent greenlet, which defaults to the current greenlet. greenlet.getcurrent() Returns the current greenlet (i.e. the one which called this function). greenlet.GreenletExit This special exception does not propagate to the parent greenlet; it can be used to kill a single greenlet.
The greenlet type can be subclassed, too. A greenlet runs by calling its run attribute, which is normally set when the greenlet is created; but for subclasses it also makes sense to define a run method instead of giving a run argument to the constructor. Switching
Switches between greenlets occur when the method switch() of a greenlet is called, in which case execution jumps to the greenlet whose switch() is called, or when a greenlet dies, in which case execution jumps to the parent greenlet. During a switch, an object or an exception is “sent” to the target greenlet; this can be used as a convenient way to pass information between greenlets. For example:
def test1(x, y): z = gr2.switch(x+y) print z
def test2(u): print u gr1.switch(42)
gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch("hello", " world")
This prints “hello world” and 42, with the same order of execution as the previous example. Note that the arguments of test1() and test2() are not provided when the greenlet is created, but only the first time someone switches to it.
Here are the precise rules for sending objects around:
g.switch(*args, **kwargs) Switches execution to the greenlet g, sending it the given arguments. As a special case, if g did not start yet, then it will start to run now. Dying greenlet If a greenlet’s run() finishes, its return value is the object sent to its parent. If run() terminates with an exception, the exception is propagated to its parent (unless it is a greenlet.GreenletExit exception, in which case the exception object is caught and returned to the parent).
Apart from the cases described above, the target greenlet normally receives the object as the return value of the call to switch() in which it was previously suspended. Indeed, although a call to switch() does not return immediately, it will still return at some point in the future, when some other greenlet switches back. When this occurs, then execution resumes just after the switch() where it was suspended, and the switch() itself appears to return the object that was just sent. This means that x = g.switch(y) will send the object y to g, and will later put the (unrelated) object that some (unrelated) greenlet passes back to us into x.
Note that any attempt to switch to a dead greenlet actually goes to the dead greenlet’s parent, or its parent’s parent, and so on. (The final parent is the “main” greenlet, which is never dead.) Methods and attributes of greenlets
g.switch(*args, **kwargs) Switches execution to the greenlet g. See above. g.run The callable that g will run when it starts. After g started, this attribute no longer exists. g.parent The parent greenlet. This is writeable, but it is not allowed to create cycles of parents. g.gr_frame The current top frame, or None. g.dead True if g is dead (i.e. it finished its execution). bool(g) True if g is active, False if it is dead or not yet started. g.throw([typ, [val, [tb]]])
Switches execution to the greenlet g, but immediately raises the given exception in g. If no argument is provided, the exception defaults to greenlet.GreenletExit. The normal exception propagation rules apply, as described above. Note that calling this method is almost equivalent to the following:
def raiser():
raise typ, val, tb
g_raiser = greenlet(raiser, parent=g)
g_raiser.switch()
except that this trick does not work for the greenlet.GreenletExit exception, which would not propagate from g_raiser to g.
Greenlets and Python threads
Greenlets can be combined with Python threads; in this case, each thread contains an independent “main” greenlet with a tree of sub-greenlets. It is not possible to mix or switch between greenlets belonging to different threads. Garbage-collecting live greenlets
If all the references to a greenlet object go away (including the references from the parent attribute of other greenlets), then there is no way to ever switch back to this greenlet. In this case, a GreenletExit exception is generated into the greenlet. This is the only case where a greenlet receives the execution asynchronously. This gives try:finally: blocks a chance to clean up resources held by the greenlet. This feature also enables a programming style in which greenlets are infinite loops waiting for data and processing it. Such loops are automatically interrupted when the last reference to the greenlet goes away.
The greenlet is expected to either die or be resurrected by having a new reference to it stored somewhere; just catching and ignoring the GreenletExit is likely to lead to an infinite loop.
Greenlets do not participate in garbage collection; cycles involving data that is present in a greenlet’s frames will not be detected. Storing references to other greenlets cyclically may lead to leaks. Tracing support
Standard Python tracing and profiling doesn’t work as expected when used with greenlet since stack and frame switching happens on the same Python thread. It is difficult to detect greenlet switching reliably with conventional methods, so to improve support for debugging, tracing and profiling greenlet based code there are new functions in the greenlet module:
greenlet.gettrace() Returns a previously set tracing function, or None. greenlet.settrace(callback)
Sets a new tracing function and returns a previous tracing function, or None. The callback is called on various events and is expected to have the following signature:
def callback(event, args):
if event == ''switch'':
origin, target = args
# Handle a switch from origin to target.
# Note that callback is running in the context of target
# greenlet and any exceptions will be passed as if
# target.throw() was used instead of a switch.
return
if event == ''throw'':
origin, target = args
# Handle a throw from origin to target.
# Note that callback is running in the context of target
# greenlet and any exceptions will replace the original, as
# if target.throw() was used with the replacing exception.
return
For compatibility it is very important to unpack args tuple only when event is either ''switch'' or ''throw'' and not when event is potentially something else. This way API can be extended to new events similar to sys.settrace().
C API Reference
Greenlets can be created and manipulated from extension modules written in C or C++, or from applications that embed Python. The greenlet.h header is provided, and exposes the entire API available to pure Python modules. Types Type name Python name PyGreenlet greenlet.greenlet Exceptions Type name Python name PyExc_GreenletError greenlet.error PyExc_GreenletExit greenlet.GreenletExit Reference
PyGreenlet_Import() A macro that imports the greenlet module and initializes the C API. This must be called once for each extension module that uses the greenlet C API. int PyGreenlet_Check(PyObject *p) Macro that returns true if the argument is a PyGreenlet. int PyGreenlet_STARTED(PyGreenlet *g) Macro that returns true if the greenlet g has started. int PyGreenlet_ACTIVE(PyGreenlet *g) Macro that returns true if the greenlet g has started and has not died. PyGreenlet *PyGreenlet_GET_PARENT(PyGreenlet *g) Macro that returns the parent greenlet of g. int PyGreenlet_SetParent(PyGreenlet *g, PyGreenlet *nparent) Set the parent greenlet of g. Returns 0 for success. If -1 is returned, then g is not a pointer to a PyGreenlet, and an AttributeError will be raised. PyGreenlet *PyGreenlet_GetCurrent(void) Returns the currently active greenlet object. PyGreenlet *PyGreenlet_New(PyObject *run, PyObject *parent) Creates a new greenlet object with the callable run and parent parent. Both parameters are optional. If run is NULL, then the greenlet will be created, but will fail if switched in. If parent is NULL, the parent is automatically set to the current greenlet. PyObject *PyGreenlet_Switch(PyGreenlet *g, PyObject *args, PyObject *kwargs) Switches to the greenlet g. args and kwargs are optional and can be NULL. If args is NULL, an empty tuple is passed to the target greenlet. If kwargs is NULL, no keyword arguments are passed to the target greenlet. If arguments are specified, args should be a tuple and kwargs should be a dict. PyObject *PyGreenlet_Throw(PyGreenlet *g, PyObject *typ, PyObject *val, PyObject *tb) Switches to greenlet g, but immediately raise an exception of type typ with the value val, and optionally, the traceback object tb. tb can be NULL.
centos下python多版本管理(pyenv+python+virtualenv+ipython)
pyenv是个多版本python管理器,可以同时管理多个python版本共存,如pypy,miniconde等等
1 环境准备 安装相关软件和pyenv
1.1 安装相关软件
yum install -y readline readline-devel readline-static openssl openssl-devel openssl-static sqlite-devel bzip2-devel bzip2-libs
1.1 克隆pyenv
git clonehttps://github.com/yyuu/pyenv.git~/.pyenv
1.2 设置相关环境变量,使pyenv生效
echo ''export PYENV_ROOT="$HOME/.pyenv"'' >> ~/.bash_profile
echo ''export PATH="$PYENV_ROOT/bin:$PATH"'' >> ~/.bash_profile
echo ''eval "$(pyenv init -)"'' >> ~/.bash_profile
exec $SHELL -l
2 安装python
2.1 常用pyenv操作
pyenv install --list 查看可安装的python版本
pyenv install 3.5.0 安装python3.5.0
pyenv uninstall //卸载
2.2 更新pyenv
安装完之后,需要更新一下才能看到已经安装的版本
pyenv rehash
pyenv versions //查看已经安装好的版本,带*号的为当前使用的版本
2.3 选择python版本
pyenv global 3.5.0 //设置全局版本,即系统使用的将是此版本
pyenv local 3.5.0 //当前目录下的使用版本,有点类似virtualenv
补充:网络问题导致安装缓慢或无法进行
如anaconda之类大容量的版本,由于网络的问题,总是连接中断,安装失败。此时可以先从官方网站下载安装包,然后放在~/.pyenv/cache文件夹中,然后在pyenv install 此版本,pyenv会自动先从此文件夹中搜索
3 python virtualenv创建纯净虚拟环境
虽然直接安装pip安装virtualenv也行,但是通过pyenv插件的形式安装virtualenv的虚拟环境更加方便,因为之后的操作会比较方便。
3.1 安装插件pyenv-virtualenv
参考文章:http://www.tiny-coder.com/home-article-51.html
pyenv-virtualenv插件安装:项目主页:https://github.com/yyuu/pyenv-virtualenv
pyenv virtualenv是pyenv的插件,为UNIX系统上的Python virtualenvs提供pyenv virtualenv命令。
3.2 安装virtualenv
git clonehttps://github.com/yyuu/pyenv-virtualenv.git~/.pyenv/plugins/pyenv-virtualenv
echo ''eval "$(pyenv virtualenv-init -)"'' >> ~/.bash_profile
这个插件将安装在主文件夹下的.pyenv文件夹中。
3.3 创建一个2.7.13的虚拟环境
pyenv virtualenv 2.7.13 py27
source ~/.bash_profile
这条命令在本机上创建了一个名为env271的python虚拟环境,这个环境的真实目录位于:~/.pyenv/versions/
注意,命令中的 ‘2.7.13’ 必须是一个安装前面步骤已经安装好的python版本, 否则会出错。
然后我们可以继续通过 ‘pyenv versions’ 命令来查看当前的虚拟环境。
3.4 切换和使用新的python虚拟环境:
pyenv activate env271
这样就能切换为这个版本的虚拟环境。通过输入python查看现在版本,可以发现处于虚拟环境下了。
如果要切换回系统环境, 运行这个命令即可
pyenv deactivate
那如果要删除这个虚拟环境呢? 答案简单而且粗暴,只要直接删除它所在的目录就好:
rm -rf ~/.pyenv/versions/env271/
或者卸载:
pyenv uninstall env271
4 安装ipython
centos7 已经带有pip,不用安装pip(在centos6 叫python-pip,在centos7 叫pip)
yum install python-pip
进入python环境后, 安装ipython,若是python2+,需要指定ipython版本为ipython==1.2.1
pip install ipython
ps: 各个步骤的安装脚本,这里的脚本安装了python2.7.13和3.6.0,python安装方式为先下载,在安装
1 环境准备 安装相关软件和pyenv
[](javascript:void(0);)
#!/usr/bin/env bash
# 安装相关软件和pyenv
yum install -y readline readline-devel readline-static openssl openssl-devel openssl-static sqlite-devel bzip2-devel bzip2-libs # 克隆pyenv git clone https://github.com/yyuu/pyenv.git ~/.pyenv # 导出环境变量,使pyenv生效 echo ''export PYENV_ROOT="$HOME/.pyenv"'' >> ~/.bash_profile echo ''export PATH="$PYENV_ROOT/bin:$PATH"'' >> ~/.bash_profile echo ''eval "$(pyenv init -)"'' >> ~/.bash_profile exec $SHELL -l
[](javascript:void(0);)
2 安装python
[](javascript:void(0);)
#!/usr/bin/env bash
python2=2.7.13 python2_url="https://www.python.org/ftp/python/$python2/Python-${python2}.tar.xz" python3=3.6.0 python3_url="https://www.python.org/ftp/python/$python3/Python-${python3}.tar.xz"
test -e ~/.pyenv/cache || mkdir -p ~/.pyenv/cache cd ~/.pyenv/cache
if ! ls Python-${python2}.tar.xz &> /dev/null; then wget $python2_url fi pyenv install $python2 -v
if ! ls Python-${python3}.tar.xz &> /dev/null; then wget $python3_url fi pyenv install $python3 -v
git clone https://github.com/yyuu/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv echo ''eval "$(pyenv virtualenv-init -)"'' >> ~/.bash_profile source ~/.bash_profile
[](javascript:void(0);)
3 python virtualenv创建纯净虚拟环境
[](javascript:void(0);)
#!/usr/bin/env bash
python2=2.7.13 python3=3.6.0 pyenv virtualenv $python2 py27 pyenv virtualenv $python3 py35
echo ''alias py27="pyenv activate py27"'' >> ~/.bash_profile echo ''alias py35="pyenv activate py35"'' >> ~/.bash_profile echo ''alias pyd="pyenv deactivate"'' >> ~/.bash_profile
source ~/.bash_profile
[](javascript:void(0);)
4 安装ipython
#!/usr/bin/env bash
# 使用py27进入python环境后,进行以下操作。 # py27 yum install python-pip pip install ipython==1.2.1
#!/usr/bin/env bash
# 使用py35进入python环境后,进行以下操作。 # py35 yum install python-pip pip install ipython
Diff between Python2 and Python3
1.性能
Py3.0运行 pystone benchmark的速度比Py2.5慢30%。Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可
以取得很好的优化结果。
Py3.1性能比Py2.5慢15%,还有很大的提升空间。
2.编码
Py3.X源码文件默认使用utf-8编码,这就使得以下代码是合法的:
>>> 中国 = ''china''
>>>print(中国)
china
3. 语法
1)去除了<>,全部改用!=
2)去除``,全部改用repr()
3)关键词加入as 和with,还有True,False,None
4)整型除法返回浮点数,要得到整型结果,请使用//
5)加入nonlocal语句。使用noclocal x可以直接指派外围(非全局)变量
6)去除print语句,加入print()函数实现相同的功能。同样的还有 exec语句,已经改为exec()函数
例如:
2.X: print "The answer is", 2*2
3.X: print("The answer is", 2*2)
2.X: print x, # 使用逗号结尾禁止换行
3.X: print(x, end=" ") # 使用空格代替换行
2.X: print # 输出新行
3.X: print() # 输出新行
2.X: print >>sys.stderr, "fatal error"
3.X: print("fatal error", file=sys.stderr)
2.X: print (x, y) # 输出repr((x, y))
3.X: print((x, y)) # 不同于print(x, y)!
7)改变了顺序操作符的行为,例如x<y,当x和y类型不匹配时抛出TypeError而不是返回随即的 bool值
8)输入函数改变了,删除了raw_input,用input代替:
2.X:guess = int(raw_input(''Enter an integer : '')) # 读取键盘输入的方法
3.X:guess = int(input(''Enter an integer : ''))
9)去除元组参数解包。不能def(a, (b, c)):pass这样定义函数了
10)新式的8进制字变量,相应地修改了oct()函数。
2.X的方式如下:
>>> 0666
438
>>> oct(438)
''0666''
3.X这样:
>>> 0666
SyntaxError: invalid token (<pyshell#63>, line 1)
>>> 0o666
438
>>> oct(438)
''0o666''
11)增加了 2进制字面量和bin()函数
>>> bin(438)
''0b110110110''
>>> _438 = ''0b110110110''
>>> _438
''0b110110110''
12)扩展的可迭代解包。在Py3.X 里,a, b, *rest = seq和 *rest, a = seq都是合法的,只要求两点:rest是list
对象和seq是可迭代的。
13)新的super(),可以不再给super()传参数,
>>> class C(object):
def __init__(self, a):
print(''C'', a)
>>> class D(C):
def __init(self, a):
super().__init__(a) # 无参数调用super()
>>> D(8)
C 8
<__main__.D object at 0x00D7ED90>
14)新的metaclass语法:
class Foo(*bases, **kwds):
pass
15)支持class decorator。用法与函数decorator一样:
>>> def foo(cls_a):
def print_func(self):
print(''Hello, world!'')
cls_a.print = print_func
return cls_a
>>> @foo
class C(object):
pass
>>> C().print()
Hello, world!
class decorator可以用来玩玩狸猫换太子的大把戏。更多请参阅PEP 3129
4. 字符串和字节串
1)现在字符串只有str一种类型,但它跟2.x版本的unicode几乎一样。
2)关于字节串,请参阅“数据类型”的第2条目
5.数据类型
1)Py3.X去除了long类型,现在只有一种整型——int,但它的行为就像2.X版本的long
2)新增了bytes类型,对应于2.X版本的八位串,定义一个bytes字面量的方法如下:
>>> b = b''china''
>>> type(b)
<type ''bytes''>
str对象和bytes对象可以使用.encode() (str -> bytes) or .decode() (bytes -> str)方法相互转化。
>>> s = b.decode()
>>> s
''china''
>>> b1 = s.encode()
>>> b1
b''china''
3)dict的.keys()、.items 和.values()方法返回迭代器,而之前的iterkeys()等函数都被废弃。同时去掉的还有
dict.has_key(),用 in替代它吧
6.面向对象
1)引入抽象基类(Abstraact Base Classes,ABCs)。
2)容器类和迭代器类被ABCs化,所以collections模块里的类型比Py2.5多了很多。
>>> import collections
>>> print(''\n''.join(dir(collections)))
Callable
Container
Hashable
ItemsView
Iterable
Iterator
KeysView
Mapping
MappingView
MutableMapping
MutableSequence
MutableSet
NamedTuple
Sequence
Set
Sized
ValuesView
__all__
__builtins__
__doc__
__file__
__name__
_abcoll
_itemgetter
_sys
defaultdict
deque
另外,数值类型也被ABCs化。关于这两点,请参阅 PEP 3119和PEP 3141。
3)迭代器的next()方法改名为__next__(),并增加内置函数next(),用以调用迭代器的__next__()方法
4)增加了@abstractmethod和 @abstractproperty两个 decorator,编写抽象方法(属性)更加方便。
7.异常
1)所以异常都从 BaseException继承,并删除了StardardError
2)去除了异常类的序列行为和.message属性
3)用 raise Exception(args)代替 raise Exception, args语法
4)捕获异常的语法改变,引入了as关键字来标识异常实例,在Py2.5中:
>>> try:
... raise NotImplementedError(''Error'')
... except NotImplementedError, error:
... print error.message
...
Error
在Py3.0中:
>>> try:
raise NotImplementedError(''Error'')
except NotImplementedError as error: #注意这个 as
print(str(error))
Error
5)异常链,因为__context__在3.0a1版本中没有实现
8.模块变动
1)移除了cPickle模块,可以使用pickle模块代替。最终我们将会有一个透明高效的模块。
2)移除了imageop模块
3)移除了 audiodev, Bastion, bsddb185, exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2,
rexec, sets, sha, stringold, strop, sunaudiodev, timing和xmllib模块
4)移除了bsddb模块(单独发布,可以从http://www.jcea.es/programacion/pybsddb.htm获取)
5)移除了new模块
6)os.tmpnam()和os.tmpfile()函数被移动到tmpfile模块下
7)tokenize模块现在使用bytes工作。主要的入口点不再是generate_tokens,而是 tokenize.tokenize()
9.其它
1)xrange() 改名为range(),要想使用range()获得一个list,必须显式调用:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2)bytes对象不能hash,也不支持 b.lower()、b.strip()和b.split()方法,但对于后两者可以使用 b.strip(b’
\n\t\r \f’)和b.split(b’ ‘)来达到相同目的
3)zip()、map()和filter()都返回迭代器。而apply()、 callable()、coerce()、 execfile()、reduce()和reload()函数都被去除了
现在可以使用hasattr()来替换 callable(). hasattr()的语法如:hasattr(string, ''__name__'')
4)string.letters和相关的.lowercase和.uppercase被去除,请改用string.ascii_letters 等
5)如果x < y的不能比较,抛出TypeError异常。2.x版本是返回伪随机布尔值的
6)__getslice__系列成员被废弃。a[i:j]根据上下文转换为a.__getitem__(slice(I, j))或 __setitem__和
__delitem__调用
7)file类被废弃,在Py2.5中:
>>> file
<type ''file''>
在Py3.X中:
>>> file
Traceback (most recent call last):
File "<pyshell#120>", line 1, in <module>
file
NameError: name ''file'' is not defined
转自 https://www.cnblogs.com/codingmylife/archive/2010/06/06/1752807.html
Greenlet API的纯python实现
gevent和eventlet将greenlet包用于异步IO。它被编写为C扩展,因此不适用于Jython或IronPython。如果性能无关紧要,那么在纯Python中实现greenlet
API的最简单方法是什么。
一个简单的例子:
def test1():
print 12
gr2.switch()
print 34
def test2():
print 56
gr1.switch()
print 78
gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()
应该打印12、56、34(而不是78)。
leetcode 496. Next Greater Element I(python)
描述
You are given two integer arrays nums1 and nums2 both of unique elements, where nums1 is a subset of nums2.
Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, return -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 10^4
All integers in nums1 and nums2 are unique.
All the integers of nums1 also appear in nums2.
解析
根据题意,num1 是 num2 的子集,找出 num1 中每个元素在 num2 中的对应位置之后的第一个大于它的数,如果没有则结果为 -1 。我这里定义了一个方法 find ,就是为了在 num2 中的 idx 位置之后找比 nums2[idx] 大的数字。直接遍历 num1 ,得到元素在 num2 中的索引,然后使用我定义的 find 函数,得到的结果追加到 result 中,遍历结束即可得到结果。
解答
class Solution(object):
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
def find(A, idx):
result = -1
for i in range(idx, len(A)):
if A[i]>A[idx]:
result = A[i]
break
return result
result = []
for n in nums1:
idx = nums2.index(n)
result.append(find(nums2, idx))
return result
运行结果
Runtime: 80 ms, faster than 21.98% of Python online submissions for Next Greater Element I.
Memory Usage: 13.3 MB, less than 100.00% of Python online submissions for Next Greater Element I.
原题链接:https://leetcode.com/problems/next-greater-element-i
您的支持是我最大的动力
今天关于python greenlet的讲解已经结束,谢谢您的阅读,如果想了解更多关于centos下python多版本管理(pyenv+python+virtualenv+ipython)、Diff between Python2 and Python3、Greenlet API的纯python实现、leetcode 496. Next Greater Element I(python)的相关知识,请在本站搜索。
本文标签: