python-2.x

Can someone explain this recursive for me?

自作多情 提交于 2019-12-05 07:26:15
I get this code from leetcode. class Solution(object): def myPow(self, x, n): if n == 0: return 1 if n == -1: return 1 / x return self.myPow(x * x, n / 2) * ([1, x][n % 2]) This code is used to implement poe(x, n) , which means x**n in Python. I want to know why it can implement pow(x, n) . It looks doesn't make sense... I understand if n == 0: and if n == -1: But the core code: self.myPow(x * x, n / 2) * ([1, x][n % 2]) is really hard to understand. BTW, this code only works on Python 2.7. If you want to test on Python 3, you should change myPow(x*x, n / 2) * ([1, x][n % 2]) to myPow(x*x, n /

What ordering does dict.keys() and dict.values() guarantee? [duplicate]

走远了吗. 提交于 2019-12-05 05:05:36
This question already has an answer here: Python dictionary: are keys() and values() always the same order? 8 answers This question arises from this answer where one user uses d.keys() and d.values() separately to initialise a dataframe. It's common knowledge that dictionaries in python versions under 3.6 are not ordered. Consider a generic dictionary of the form: d = {k1 : v1, k2 : v2, k3 : v3} Where the keys k* are any hashable objects, and the values v* being any object. Of course, order cannot be guaranteed, but what about the order of d.keys() and d.values() ? Python 2.x Both d.keys() and

Asynchronous background processes with web2py

半城伤御伤魂 提交于 2019-12-05 04:29:30
I need to to handle a large (time and memory-consuming) process asynchronously in a web2py application called inside a controller method. My specific use case is to call a process via stdlib.subprocess and wait for it to exit without blocking the web server, but I am open to alternative methods. Hands-on examples would be a plus. 3rd party library recommendations are welcome. CRON scheduling is not required/wanted. Assuming you'll need to start multiple, possibly simultaneous, instances of the background task, the solution is a task queue. I've heard good things about Celery and RabbitMQ, if

remove escape character from string [closed]

偶尔善良 提交于 2019-12-05 04:18:07
I would like to turn this string: a = '\\a' into this one b = '\a' It doesn't seem like there is an obvious way to do this with replace ? EDIT: To be more precise, I want to change the escaping of the backslash to escape the character a The character '\a' is the ASCII BEL character , chr(7). To do the conversion in Python 2: from __future__ import print_function a = '\\a' c = a.decode('string-escape') print(repr(a), repr(c)) output '\\a' '\x07' And for future reference, in Python 3: a = '\\a' b = bytes(a, encoding='ascii') c = b.decode('unicode-escape') print(repr(a), repr(c)) This gives

Catch Broken Pipe in Python 2 AND Python 3

好久不见. 提交于 2019-12-05 04:15:26
I try to write some code to catch a Broken Pipe Error. The code should run in Python 2.x and Python 3.x. In Python 2.x a broken pipe is represented by a socket.error socket.error: [Errno 32] Broken pipe This was changed in Python 3.x - a broken pipe now is a BrokenPipeError BrokenPipeError: [Errno 32] Broken pipe Also the syntax of exception handling has changed a bit (see https://stackoverflow.com/a/34463112/263589 ) so what I need to do would be something like: try: do_something() except BrokenPipeError as e: # implies Python 3.x resolve_for_python2() except socket.error as e: if sys.version

Why does this key class for sorting heterogeneous sequences behave oddly?

六眼飞鱼酱① 提交于 2019-12-05 02:59:58
Python 3.x's sorted() function cannot be relied on to sort heterogeneous sequences, because most pairs of distinct types are unorderable (numeric types like int , float , decimal.Decimal etc. being an exception): Python 3.4.2 (default, Oct 8 2014, 08:07:42) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> sorted(["one", 2.3, "four", -5]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: float() < str() In contrast, comparisons between objects that have no natural order are arbitrary but consistent

Returning the first N characters of a unicode string

▼魔方 西西 提交于 2019-12-05 02:14:39
I have a string in unicode and I need to return the first N characters. I am doing this: result = unistring[:5] but of course the length of unicode strings != length of characters. Any ideas? The only solution is using re? Edit: More info unistring = "Μεταλλικα" #Metallica written in Greek letters result = unistring[:1] returns-> ? I think that unicode strings are two bytes (char), that's why this thing happens. If I do: result = unistring[:2] I get M which is correct, So, should I always slice*2 or should I convert to something? Tendayi Mawushe Unfortunately for historical reasons prior to

Normalizing rows of a matrix python

陌路散爱 提交于 2019-12-05 01:43:05
问题 Given a 2-dimensional array in python, I would like to normalize each row with the following norms: Norm 1: L_1 Norm 2: L_2 Norm Inf: L_Inf I have started this code: from numpy import linalg as LA X = np.array([[1, 2, 3, 6], [4, 5, 6, 5], [1, 2, 5, 5], [4, 5,10,25], [5, 2,10,25]]) print X.shape x = np.array([LA.norm(v,ord=1) for v in X]) print x Output: (5, 4) # array dimension [12 20 13 44 42] # L1 on each Row How can I modify the code such that WITHOUT using LOOP, I can directly have the

Keyboard interruptable blocking queue in Python

跟風遠走 提交于 2019-12-05 00:36:04
It seems import Queue Queue.Queue().get(timeout=10) is keyboard interruptible (ctrl-c) whereas import Queue Queue.Queue().get() is not. I could always create a loop; import Queue q = Queue() while True: try: q.get(timeout=1000) except Queue.Empty: pass but this seems like a strange thing to do. So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()? Queue objects have this behavior because they lock using Condition objects form the threading module. So your solution is really the only way to go. However, if you really want a Queue method that does this,

Python futurize without replacing / with old_div

て烟熏妆下的殇ゞ 提交于 2019-12-05 00:25:32
I am using futurize --stage2 which aplies a number of source-source transformation to make the code python2 and python3 compatible. One of those fixes is that all divisions a/b are replaced by old_div(a/b) , which I would like to avoid (there is too many, and many of them are replaced unnecessarily, such as math.pi/2. . The documentation says that --nofix (or -x ) can be used to avoid running a certain fixes, but trying --nofix=fix_divison or --nofix=libfuturize.fixes.fix_divison has no effect with --stage2 . Can someone perhaps help how to ignore that particular fixer otherwise? Omit the