python-2.x

Python 2.x sorted puzzlement

霸气de小男生 提交于 2019-12-07 22:37:44
问题 I have a partially sorted tuple in Python 2.x. Why Python reverse it instead of sort it? >>> data = (u'a', (1,), 'b ', u'b', (2,), 'c ', u'c', (3,), 'd ', u'd', (4,), 'e') >>> sorted(data) == list(reversed(data)) True I look forward to Python 3. 回答1: It fails because the sorting algorithm depends on a total ordering of the elements, which implies transitive < . The ordering of unicode strings, tuples, and strings isn't transitive: >>> a = 'x' >>> b = (1,) >>> c = u'x' >>> a < b True >>> b < c

Do variables defined inside list comprehensions leak into the enclosing scope? [duplicate]

穿精又带淫゛_ 提交于 2019-12-07 18:57:29
问题 This question already has answers here : List comprehension rebinds names even after scope of comprehension. Is this right? (5 answers) Closed last year . I can't find anywhere that defines this behaviour: if [x for x in [0, 1, -1] if x > 0]: val = x How safe is this code? Will val always be assigned to the last element in the list if any element in the list is greater than 0? 回答1: In Python 2.x, variables defined inside list comprehensions leak into their enclosing scope, so yes, val will

How to find my IDLE's Python, then apply pip upgrade to a package it uses?

谁都会走 提交于 2019-12-07 17:08:59
问题 I have two python 2.7's of interest: version with IDLE that came from https://www.python.org/downloads/ anaconda 2.7 installation I use MacOS. (I understand I'm overdue to switch to Python 3) I'd like to apply pip install --upgrade PackageName to a package that IDLE's Python uses, but when I type that in my terminal it tries to apply it to my anaconda version. Is there a way I can find my IDLE's python, point to it, then apply the pip command to it? Here's what I have: $ which python /Users

binary search implementation with python

我怕爱的太早我们不能终老 提交于 2019-12-07 15:33:28
I think I did everything correctly, but the base case return None, instead of False if the value does not exists. I cannot understand why. def binary_search(lst, value): if len(lst) == 1: return lst[0] == value mid = len(lst)/2 if lst[mid] < value: binary_search(lst[:mid], value) elif lst[mid] > value: binary_search(lst[mid+1:], value) else: return True print binary_search([1,2,4,5], 15) You need to return the result of the recursive method invocation: def binary_search(lst, value): #base case here if len(lst) == 1: return lst[0] == value mid = len(lst)/2 if lst[mid] < value: return binary

Calling Method with and without Parentheses in Python

若如初见. 提交于 2019-12-07 13:18:47
问题 I've realized that some methods should be called with () , while others can't. How can I check, using IPython e.g., whether to use parentheses or not? For example the following file scratch.py import numpy as np arr = np.random.randn(5) print arr.sort, "\n" print arr.sort(), "\n"; print arr.shape, "\n"; print arr.shape(), "\n"; produces this output: <built-in method sort of numpy.ndarray object at 0x7fb4b5312300> None (5,) Traceback (most recent call last): File "scratch.py", line 8, in

Can someone explain this recursive for me?

白昼怎懂夜的黑 提交于 2019-12-07 03:26:58
问题 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.

How to redirect the raw_input to stderr and not stdout?

萝らか妹 提交于 2019-12-07 02:48:00
问题 I want to redirect the stdout to a file. But This will affect the raw_input . I need to redirect the output of raw_input to stderr instead of stdout . How can I do that? 回答1: Redirect stdout to stderr temporarily, then restore. import sys old_raw_input = raw_input def raw_input(*args): old_stdout = sys.stdout try: sys.stdout = sys.stderr return old_raw_input(*args) finally: sys.stdout = old_stdout 回答2: The only problem with raw_input is that it prints the prompt to stdout. Instead of trying

Python's hasattr sometimes returns incorrect results

半城伤御伤魂 提交于 2019-12-07 01:47:23
问题 Why does hasattr say that the instance doesn't have a foo attribute? >>> class A(object): ... @property ... def foo(self): ... ErrorErrorError ... >>> a = A() >>> hasattr(a, 'foo') False I expected: >>> hasattr(a, 'foo') NameError: name 'ErrorErrorError' is not defined` 回答1: The python2 implementation of hasattr is fairly naive, it just tries to access that attribute and see whether it raises an exception or not. Unfortunately, this means that any unhandled exceptions inside properties will

remove escape character from string [closed]

不羁岁月 提交于 2019-12-07 00:39:20
问题 Closed . This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 3 years ago . 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 回答1: The character '\a' is the ASCII BEL character, chr(7). To

Asynchronous background processes with web2py

青春壹個敷衍的年華 提交于 2019-12-06 23:01:36
问题 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. 回答1: Assuming you'll need to start multiple, possibly simultaneous, instances