February 02, 2012
Calculating the product of a Python list
I came across a stackoverflow question about multiplying the numbers in a Python list. Suggestions there included:
def product(list):
p = 1
for i in list:
p *= i
return p
and
from operator import mul
reduce(mul, list)
You can also do:
import math
math.exp(sum(map(math.log, list)))
It's not as readable as the reduce-based solution, though if you're a mathematician who isn't familiar with reduce() the opposite might be true!
I wouldn't advise using the log-based solution under normal circumstances. But if you're ever in a situation where you risk overflow or overflow, such as in
>>> reduce(mul, [10.]*309)
inf
and your purpose is to compare the products of different sequences rather than to know what the products are, then
>>> sum(map(math.log, [10.]*309))
711.49879373515785
is the way to go because it's virtually impossible to have a real-world problem in which you would overflow or underflow with this approach. (The larger the result of that calculation is, the larger the product would be if you could calculate it.)
February 2, 2012 in Python | Permalink | Comments (0)
October 17, 2009
Non-blocking raw_input for Python
[Edited Aug. 30, 2010 to fix a typo in the function name and generally improve formatting]
I needed a way to allow a raw_input() call to time out. In case it's useful to anyone, I wrote this solution which works under Unix-like OS's.
import signal
class AlarmException(Exception):
pass
def alarmHandler(signum, frame):
raise AlarmException
def nonBlockingRawInput(prompt='', timeout=20):
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(timeout)
try:
text = raw_input(prompt)
signal.alarm(0)
return text
except AlarmException:
print '\nPrompt timeout. Continuing...'
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return ''
October 17, 2009 in Python, Web/Tech | Permalink | Comments (2)
March 18, 2004
One line Python Web server
[Most recently updated: Aug 11, 2010.]
if you have python installed, go to your terminal. Go to the directory you want to serve HTML files from, then type one of the following, depending on your python version:
Python 2.x:
python -m SimpleHTTPServer
Python 3.x:
python -m http.server 8000
Either one should start up a web server on port 8000 to serve your files.
[I haven't verified the Python 3 version; it was contributed by duffy in one of the comments. The previous version I had for Python 3 was "python3.0 -c ‘import http.server as h; h.test(HandlerClass=h.SimpleHTTPRequestHandler)’"]
This post has been updated a few times to include improved one-liners pointed out by readers. I've deleted the original text since it's quite obsolete now. That might make some of the comments indecipherable because of the lack of context, but it's all for the greater good. If you have any comments/suggests/observations, please speak up!
March 18, 2004 in Python | Permalink | Comments (9)