<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet href="http://www.pythonblogs.com/styles/rss.css" type="text/css"?>
<rss version="2.0">
 <channel>
  <title>Python Blogs</title>
  <description>Python Community Blogs</description>
  <link>http://www.pythonblogs.com/summary.php</link>
  <generator>LifeType 1.0</generator>
          
  <item>
   <title>Python vs. Haskell vs. PHP - real world performance</title>
   <description>&lt;p&gt;
Recently I had to optimize a legacy PHP cgi application, which worked fine but was too slow for its purpose. The main bottleneck was in selecting matching lines from a file containing about 15000 lines. Not finding a way to optimize PHP code I decided to change the language.&lt;br /&gt;
Two candidates were Python and Haskell. Knowing that Haskell is the only language out of three which compiles to machine code I expected it to be a clear winner, but I was up for a surprise...
&lt;/p&gt;
&lt;p&gt;
Benchmark results:
&lt;/p&gt;
&lt;p&gt;
PHP: 18ms (PHP 5.3.3)&lt;br /&gt;
Python: 4ms (Python 2.6)&lt;br /&gt;
Haskell: 38ms (compiled with ghc --make -dynamic -O2, ghc 6.12)
&lt;/p&gt;
&lt;p&gt;
Code of the fast cgi application I benchmarked in 3 languages: 
&lt;/p&gt;
&lt;p&gt;
PHP code: 
&lt;/p&gt;
&lt;p&gt;
[code php]&lt;br /&gt;
define(&#039;MAX_NAMES&#039;, 30);&lt;br /&gt;
$handle = fopen(&quot;names.dat&quot;, &quot;r&quot;);&lt;br /&gt;
&lt;br /&gt;
$name = strtoupper($_REQUEST[&#039;q&#039;]);&lt;br /&gt;
$res = array();&lt;br /&gt;
$size = 0;&lt;br /&gt;
&lt;br /&gt;
while (($customer_name = fgets($handle, 4096)) !== false) {&lt;br /&gt;
    if (strpos($customer_name, $bank_name) !== false) {&lt;br /&gt;
        $res[] = &quot;&#039;&quot; . trim($customer_name) . &quot;&#039;&quot;;&lt;br /&gt;
        $size += 1;&lt;br /&gt;
        if ($size &amp;gt; MAX_NAMES + 1) {&lt;br /&gt;
            break;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
fclose($handle);&lt;br /&gt;
print &#039;[&#039;.implode(&#039;,&#039;,$res).&#039;]&#039;;&lt;br /&gt;
[/code]
&lt;/p&gt;
&lt;p&gt;
Python code:&lt;br /&gt;
[code python]&lt;br /&gt;
import cgi&lt;br /&gt;
import sys, os&lt;br /&gt;
from flup.server.fcgi import WSGIServer
&lt;/p&gt;
&lt;p&gt;
MAX_NAMES = 30&lt;br /&gt;
&lt;br /&gt;
def app(environ, start_response):&lt;br /&gt;
    start_response(&#039;200 OK&#039;, [(&#039;Content-Type&#039;, &#039;text/html&#039;)])&lt;br /&gt;
    form = cgi.FieldStorage(fp=environ[&#039;wsgi.input&#039;], environ=environ)&lt;br /&gt;
    name = form[&quot;q&quot;].value.upper()&lt;br /&gt;
    output_names = []&lt;br /&gt;
    count = 0
&lt;/p&gt;
&lt;p&gt;
     with open(&quot;names.dat&quot;) as f:&lt;br /&gt;
        for line in f:&lt;br /&gt;
            if name in line:&lt;br /&gt;
                output_names.append(line.strip())&lt;br /&gt;
                count += 1&lt;br /&gt;
                if count &amp;gt; MAX_NAMES:&lt;br /&gt;
                    break
&lt;/p&gt;
&lt;p&gt;
      yield &quot;[&#039;&quot; + &quot;&#039;,&#039;&quot;.join(output_names) + &quot;&#039;]&quot;&lt;br /&gt;
&lt;br /&gt;
WSGIServer(app).run() &lt;br /&gt;
[/code] 
&lt;/p&gt;
&lt;p&gt;
Haskell code:&lt;br /&gt;
[code haskell]&lt;br /&gt;
import Control.Concurrent&lt;br /&gt;
import System.Posix.Process (getProcessID)&lt;br /&gt;
import Char&lt;br /&gt;
import Data.List&lt;br /&gt;
import Data.Maybe&lt;br /&gt;
&lt;br /&gt;
import Network.FastCGI&lt;br /&gt;
&lt;br /&gt;
compute :: CGI CGIResult&lt;br /&gt;
bankSuggest = do setHeader &quot;Content-type&quot; &quot;text/plain&quot;&lt;br /&gt;
                 q &amp;lt;- getInput &quot;q&quot;&lt;br /&gt;
                 let key = maybe &quot;&quot; (map Char.toUpper) q&lt;br /&gt;
                 let n = 30&lt;br /&gt;
                 fileContent &amp;lt;- liftIO $ readFile &quot;names.dat&quot;&lt;br /&gt;
                 let result = if key /= &quot;&quot;&lt;br /&gt;
                                    then take n $ filter (Data.List.isInfixOf key) $ lines fileContent&lt;br /&gt;
                                    else []&lt;br /&gt;
                 output $ &quot;[&#039;&quot; ++ intercalate &quot;&#039;,&#039;&quot; result ++ &quot;&#039;]&quot;&lt;br /&gt;
&lt;br /&gt;
main = runFastCGIConcurrent&#039; forkIO 1 compute &lt;br /&gt;
[/code] 
&lt;/p&gt;
&lt;p&gt;
Parameter q for this benchmark was selected to produce less than 30 entries, which is the most common case for this application. As a result lazy evaluation and early loop termination did not help the performance.
&lt;/p&gt;
&lt;p&gt;
To sum up Python version is 4.5 times faster than PHP and almost 10 times faster than Haskell, which is pretty amazing. 
&lt;/p&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Follow up: &lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
As Don Stewart pointed out String type is quite slow in Haskell and a faster alternative would be to use ByteString.&lt;br /&gt;
So I&#039;ve rewritten Haskell cgi using ByteString functions:
&lt;/p&gt;
&lt;p&gt;
[code haskell]&lt;br /&gt;
import Control.Concurrent&lt;br /&gt;
import System.Posix.Process (getProcessID)&lt;br /&gt;
import Char&lt;br /&gt;
import Data.Maybe&lt;br /&gt;
import Data.ByteString.Char8 as BS&lt;br /&gt;
&lt;br /&gt;
import Network.FastCGI&lt;br /&gt;
&lt;br /&gt;
bankSuggest :: CGI CGIResult&lt;br /&gt;
bankSuggest = do setHeader &quot;Content-type&quot; &quot;text/plain&quot;&lt;br /&gt;
                 q &amp;lt;- getInput &quot;q&quot;&lt;br /&gt;
                 let key = BS.pack (maybe &quot;&quot; (Prelude.map Char.toUpper) q)&lt;br /&gt;
                 let n = 30&lt;br /&gt;
                 fileContent &amp;lt;- liftIO $ BS.readFile &quot;names.dat&quot;&lt;br /&gt;
                 let result = if key /= &quot;&quot;&lt;br /&gt;
                                    then Prelude.take n $ Prelude.filter (BS.isInfixOf key) $ BS.lines fileContent&lt;br /&gt;
                                    else []&lt;br /&gt;
                 output $ &quot;[&#039;&quot; ++ BS.unpack (BS.intercalate &quot;&#039;,&#039;&quot; result) ++ &quot;&#039;]&quot;&lt;br /&gt;
&lt;br /&gt;
main = runFastCGIConcurrent&#039; forkIO 1 bankSuggest&lt;br /&gt;
[/code]
&lt;/p&gt;
&lt;p&gt;
New benchmark results:
&lt;/p&gt;
&lt;p&gt;
PHP: 18ms (PHP 5.3.3)&lt;br /&gt;
Python: 4ms (Python 2.6)&lt;br /&gt;
Haskell using String: 38ms&lt;br /&gt;
(compiled with ghc --make -dynamic -O2, ghc 6.12)&lt;br /&gt;
Haskell using ByteString: 8ms &lt;br /&gt;
(compiled with ghc -XOverloadedStrings --make -dynamic -O2, ghc 6.12)
&lt;/p&gt;
&lt;p&gt;
Indeed Haskell code using ByteString is 5 times faster than Haskell using String.&lt;br /&gt;
However it is still twice slower than Python! 
&lt;/p&gt;</description>
   <link>http://mypy.pythonblogs.com/12_mypy/archive/423_python_vs_haskell_vs_php-real_world_performance.html</link>
   <comments>http://mypy.pythonblogs.com/12_mypy/archive/423_python_vs_haskell_vs_php-real_world_performance.html</comments>
   <guid>http://mypy.pythonblogs.com/12_mypy/archive/423_python_vs_haskell_vs_php-real_world_performance.html</guid>
      <author>mypy</author>
   <category>
           General 
        </category>
   <source url="http://mypy.pythonblogs.com/12_mypy/feeds/rss20">mypy</source>
  </item>
          
  <item>
   <title>Extract comments in your python code</title>
   <description>&lt;p&gt;
Comments in your code are always good for new person to understand the logic and flow of program. I guess, people likes programming more, if they comment properly, same way as i do. Proper commenting will not allow you to read code line by line. The best way to comment is to comment in such a way, you can extract it easily. I do comments in my python code using &#039;##&#039; which makes me easy to extract them from script. Following code extracts my comment:
&lt;/p&gt;
&lt;p&gt;
&lt;br /&gt;
[code python]&lt;br /&gt;
import os&lt;br /&gt;
import sys&lt;br /&gt;
## python extract_comment.py filename comment_delimeter&lt;br /&gt;
filename = sys.argv[1]&lt;br /&gt;
sepr = sys.argv[2]&lt;br /&gt;
fl = open(filename,&#039;r&#039;)&lt;br /&gt;
fl_con = fl.readlines()&lt;br /&gt;
for row in fl_con:&lt;br /&gt;
    if sepr in row:&lt;br /&gt;
        ind = row.find(sepr)&lt;br /&gt;
        print row[ind:]&lt;br /&gt;
&lt;br /&gt;
fl.close()&lt;br /&gt;
[/code]&lt;br /&gt;
&lt;br /&gt;
copy the code in file extract_comment.py, filename is the python script from where you need to extract comments and comment_delimeter is &#039;##&#039; in my case.
&lt;/p&gt;</description>
   <link>http://pymantra.pythonblogs.com/90_pymantra/archive/427_extract_comments_in_your_python_code.html</link>
   <comments>http://pymantra.pythonblogs.com/90_pymantra/archive/427_extract_comments_in_your_python_code.html</comments>
   <guid>http://pymantra.pythonblogs.com/90_pymantra/archive/427_extract_comments_in_your_python_code.html</guid>
      <author>sharmavivek82</author>
   <category>
           python 
        </category>
   <source url="http://pymantra.pythonblogs.com/90_pymantra/feeds/rss20">PyMantra</source>
  </item>
          
  <item>
   <title>Script en bash para actualizar y limpiar el sistema con apt-get</title>
   <description>&lt;p&gt;
Ya tengo alg&amp;uacute;n tiempo con este peque&amp;ntilde;o script el cual en pocas palabras lo que hace es actualizarme la lista de paquetes en ubuntu e instalarme opcionalmente nuevos paquetes as&amp;iacute; como eliminarme paquetes en desuso y tratar de corregirme aquellos con dependecias incumplidas.
&lt;/p&gt;
&lt;p&gt;
Pueden apreciarlo aqu&amp;iacute;:
&lt;/p&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;code&gt;
&lt;p&gt;
#!/bin/bash&lt;br /&gt;
&lt;br /&gt;
# Actualiza el sistema y remueve paquetes no necesarios&lt;br /&gt;
update() {&lt;br /&gt;
    echo -e &quot;\n********** ACTUALIZANDO EL SISTEMA **********\n&quot;&lt;br /&gt;
    echo -e &quot;1. ACTUALIZANDO LA LISTA DE PAQUETES...\n&quot;&lt;br /&gt;
    sudo apt-get update 1&amp;gt; /dev/null &lt;br /&gt;
    echo -e &quot;2. ACTUALIZANDO...\n&quot;&lt;br /&gt;
    sudo apt-get upgrade&lt;br /&gt;
    echo -e &quot;\n3. CHECANDO DEPENDENCIAS INCUMPLIDAS...\n&quot;&lt;br /&gt;
    sudo apt-get check  1&amp;gt; /dev/null &lt;br /&gt;
    echo -e &quot;4. CORRIGIENDO DEPENDENCIAS INCUMPLIDAS...\n&quot;&lt;br /&gt;
    sudo apt-get install -fy 1&amp;gt; /dev/null &lt;br /&gt;
    echo -e &quot;********** ELIMINADO PAQUETES BASURA **********\n&quot;&lt;br /&gt;
    echo -e &quot;5. DESINSTALANDO PAQUETES EN DESUSO...\n&quot;&lt;br /&gt;
    sudo apt-get autoremove&lt;br /&gt;
    echo -e &quot;\n6. BORRANDO ARCHIVOS DESCARGADOS...\n&quot;&lt;br /&gt;
    sudo apt-get autoclean 1&amp;gt; /dev/null &lt;br /&gt;
    echo -e &quot;7. BORRANDO ARCHIVOS ANTIGUOS DESCARGADOS...\n&quot;&lt;br /&gt;
    sudo apt-get clean 1&amp;gt; /dev/null &lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
sudo true&lt;br /&gt;
update&lt;br /&gt;
echo -e &quot;********** ^^ LISTO ^^ **********&quot;&lt;br /&gt;
sleep 1&lt;br /&gt;
clear&lt;br /&gt;
&lt;br /&gt;
#mas info en [man apt-get] o [apt-get --help] (mas breve)
&lt;/p&gt;
&lt;/code&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
Por &amp;uacute;ltimo les recomiendo que cualquier script que hagan, lo guarden en un directorio que este incluido en el $PATH esto es en la variable de entorno para las rutas. Para que lo puedan ejecutar desde la terminal, p.e. yo nombre a mi script &quot;update&quot;, entonces cada vez que lo quiero ejecutar voy a la terminal y escribo:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;update  &lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
y me da la sig. salida:
&lt;/p&gt;
&lt;p&gt;
user@host:~$ update&lt;br /&gt;
[sudo] password for user: &lt;br /&gt;
&lt;br /&gt;
********** ACTUALIZANDO EL SISTEMA **********&lt;br /&gt;
&lt;br /&gt;
1. ACTUALIZANDO LA LISTA DE PAQUETES...&lt;br /&gt;
&lt;br /&gt;
2. ACTUALIZANDO...&lt;br /&gt;
&lt;br /&gt;
Leyendo lista de paquetes... Hecho&lt;br /&gt;
Creando &amp;aacute;rbol de dependencias       &lt;br /&gt;
Leyendo la informaci&amp;oacute;n de estado... Hecho&lt;br /&gt;
0 actualizados, 0 se instalar&amp;aacute;n, 0 para eliminar y 0 no actualizados.&lt;br /&gt;
&lt;br /&gt;
3. CHECANDO DEPENDENCIAS INCUMPLIDAS...&lt;br /&gt;
&lt;br /&gt;
4. CORRIGIENDO DEPENDENCIAS INCUMPLIDAS...&lt;br /&gt;
&lt;br /&gt;
********** ELIMINADO PAQUETES BASURA **********&lt;br /&gt;
&lt;br /&gt;
5. DESINSTALANDO PAQUETES EN DESUSO...&lt;br /&gt;
&lt;br /&gt;
Leyendo lista de paquetes... Hecho&lt;br /&gt;
Creando &amp;aacute;rbol de dependencias       &lt;br /&gt;
Leyendo la informaci&amp;oacute;n de estado... Hecho&lt;br /&gt;
0 actualizados, 0 se instalar&amp;aacute;n, 0 para eliminar y 0 no actualizados.&lt;br /&gt;
&lt;br /&gt;
6. BORRANDO ARCHIVOS DESCARGADOS...&lt;br /&gt;
&lt;br /&gt;
7. BORRANDO ARCHIVOS ANTIGUOS DESCARGADOS...&lt;br /&gt;
&lt;br /&gt;
********** ^^ LISTO ^^ **********
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Recomendaci&amp;oacute;n:&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Ejecuta este comando hasta que en todas las secciones te aparezca
&lt;/p&gt;
&lt;p&gt;
 0 actualizados, 0 se instalar&amp;aacute;n, 0 para eliminar y 0 no actualizados.
&lt;/p&gt;
&lt;p&gt;
Esto significa que ya no hay paquetes por actualizar, instalar, eliminar y actualizar, y que por lo tanto 0 paquetes se actualizaron. 
&lt;/p&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
Dudas?, comentarios? 
&lt;/p&gt;</description>
   <link>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/429_script_en_bash_para_actualizar_y_limpiar_el_sistema_con_apt-get.html</link>
   <comments>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/429_script_en_bash_para_actualizar_y_limpiar_el_sistema_con_apt-get.html</comments>
   <guid>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/429_script_en_bash_para_actualizar_y_limpiar_el_sistema_con_apt-get.html</guid>
      <author>pythonista</author>
   <category>
           bash 
           scripts 
           apt-get 
        </category>
   <source url="http://bytesofcode.pythonblogs.com/102_bytesofcode/feeds/rss20">bytesofcode</source>
  </item>
          
  <item>
   <title>A Quiet Sense of Accomplishment - First GAE Application Using Bottle.py</title>
   <description>&lt;p&gt;
&lt;strong&gt;Now We Have Working Code On GAE!&lt;/strong&gt; 
&lt;/p&gt;
&lt;p&gt;
I&#039;m going to bed slightly later than expected tonight, but with a quiet sense of accomplishment.
&lt;/p&gt;
&lt;p&gt;
As of about 30 minutes ago, I just uploaded and started a barebones version of my first &lt;a href=&quot;http://bottledemo.appspot.com/&quot; title=&quot;GAE Port of Website Revenue Calculator&quot;&gt;Google App Engine app&lt;/a&gt; - a lemonade stand revenue calculator (editorial update: was originally website revenue calculator, had a more creative idea this morning). Enter some assumptions about your lemonade stand and it will predict how much money per hour you should be making. I&#039;m using bottle.py as the framework behind the site and the application is a comic twist on my website revenue estimator (the original Non-GAE implementation is &lt;a href=&quot;http://www.marginhound.com/calculators/website-revenue-calculator&quot; title=&quot;website revenue calculator&quot;&gt;here&lt;/a&gt;, underlying business research is &lt;a href=&quot;http://www.marginhound.com/revenue-model-study-for-small-websites/&quot; title=&quot;revenue study&quot;&gt;here&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Why I&#039;m Interested In This...&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
My day job is in Analytics, where my team and I spend a lot of time coming up with &quot;the formula&quot; behind a business process. Once we have &quot;the formula&quot;, we have three challenges:
&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Make it simple enough for non-analyst to use&lt;/li&gt;
	&lt;li&gt;
	&lt;div&gt;
	Track formula predictions and decisions made (accept / reject our recommendations)
	&lt;/div&gt;
	&lt;/li&gt;
	&lt;li&gt;
	&lt;div&gt;
	Ensure the formula is protected from malicious use (loss to competitor, internal circumvention)
	&lt;/div&gt;
	&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Historically, analytics has always retreated &quot;to our mountain top&quot; to mine insights from data. Our ideas would then be shared with senior management, who would frequently broadcast them to their subordinates. Net result: everyone knows everything (fail goal #3), we track nothing everything is ad-hoc (fail #2), and we struggled with the first challenge.
&lt;/p&gt;
&lt;p&gt;
The irony is that we&#039;re only talking about a formula: something that can be implemented in a handful of lines of Python!
&lt;/p&gt;
&lt;p&gt;
Thus my interest in Python microframeworks. Bottle is a microframework that simplifies the task of setting up a basic web service. In simple terms, you define URL routes (http://mysite.com/path/variable) for a specific request; these are mapped to a python function (passing information from the request) which creates an appropriate response. Many microframeworks are very AJAX friendly (very easy to return data as JSON), opening the door to building simple web applications.
&lt;/p&gt;
&lt;p&gt;
So... if I can code the formula in Python, I can deliver it as a webservice (or simple AJAX application). This protects the formula and will make the formula&#039;s implementation easier to use and supervise. One little bonus for bottle and GAE - they have a &lt;a href=&quot;http://www.bottlepy.org/docs/dev/deployment.html#google-appengine&quot; title=&quot;gae adapter&quot;&gt;Google App Engine Adapter&lt;/a&gt;. This made the process a snap. Oh...and GAE has a free plan for smaller applications (see them for details). Which makes it attractive to students and hobbyist developers.
&lt;/p&gt;
&lt;p&gt;
I&#039;ve got a lot of polishing to do (particularly on the web design piece). Interestingly enough, the calculator framework has been relatively easy to edit - I was able to flip the application&#039;s entire purpose over lunch (from a website profit estimator into the lemonade stand version). It&#039;s just a form and a formula - very easy to edit!
&lt;/p&gt;</description>
   <link>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1259_a_quiet_sense_of_accomplishment-first_gae_application_using_bottlepy.html</link>
   <comments>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1259_a_quiet_sense_of_accomplishment-first_gae_application_using_bottlepy.html</comments>
   <guid>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1259_a_quiet_sense_of_accomplishment-first_gae_application_using_bottlepy.html</guid>
      <author>numbercruncher</author>
   <category>
           General 
           bottle.py 
           Google App Engine 
           calculators 
        </category>
   <source url="http://python-for-analysts.pythonblogs.com/211_python-for-analysts/feeds/rss20">python-for-analysts</source>
  </item>
          
  <item>
   <title>Código en python para hacer &quot;La criba de Eratóstenes&quot;</title>
   <description>&lt;p&gt;
Bueno como ya es de saberse en cada uno de los post donde exponga alg&amp;uacute;n c&amp;oacute;digo de python sera de la versi&amp;oacute;n 3.1 &amp;oacute; &amp;gt;, entonces no cabe la necesidad de estar mencionando la versi&amp;oacute;n del lenguaje en el t&amp;iacute;tulo del post.
&lt;/p&gt;
&lt;p&gt;
Les presento un par de algoritmos muy parecidos ya que los dos usan la llamada criba de Erat&amp;oacute;stenes para &quot;cribar&quot; los n&amp;uacute;meros primos de una sequencia de n&amp;uacute;meros. Ambos usan una sequencia 1..2000000.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;La criba de Erat&amp;oacute;stenes&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;div style=&quot;text-align: center&quot;&gt;
&lt;img src=&quot;http://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif&quot; width=&quot;445&quot; height=&quot;369&quot; /&gt;
&lt;/div&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Nota&lt;/strong&gt;:
&lt;/p&gt;
&lt;p&gt;
Si conoces alg&amp;uacute;n algoritmo m&amp;aacute;s eficiente tienes la libertad de comentarlo, gracias
&lt;/p&gt;
&lt;p&gt;
[code python]&lt;br /&gt;
#inicializamos el tamano de la sequencia de numeros&lt;br /&gt;
n = 2000000&lt;br /&gt;
#se usa un conjunto porque es mas eficiente&lt;br /&gt;
#(no hay numeros repetidos)&lt;br /&gt;
noprimos = set()&lt;br /&gt;
&lt;br /&gt;
#iteramos desde 2 hasta la raiz cuadrada de n&lt;br /&gt;
#y desde lo que lleva i, hasta n / i&lt;br /&gt;
#esto nos permite obtener todos los multiplos de i&lt;br /&gt;
#y agregarlos a el conjunto noprimos&lt;br /&gt;
for i in range(2, int(n ** .5) + 1):&lt;br /&gt;
    if i not in noprimos:&lt;br /&gt;
        for j in range(i, int(n / i) + 1): noprimos.add(i * j)&lt;br /&gt;
        &lt;br /&gt;
#por ultimo creamos una lista con todos los numeros&lt;br /&gt;
#primos desde 2 hasta n&lt;br /&gt;
primos = [p for p in range(2, n + 1) if p not in noprimos]&lt;br /&gt;
[/code] 
&lt;/p&gt;
&lt;strong&gt;Cr&amp;eacute;ditos&lt;/strong&gt;:
&lt;p&gt;
&lt;a href=&quot;http://es.wikipedia.org/wiki/Criba_de_Erat%C3%B3stenes&quot; title=&quot;Wikipedia - Criba de Erat&amp;oacute;stenes&quot;&gt;http://es.wikipedia.org/wiki/Criba_de_Erat&amp;oacute;stenes &lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
y aqu&amp;iacute; esta el otro que a mi parecer es m&amp;aacute;s eficiente
&lt;/p&gt;
[code python]&lt;br /&gt;
#inicializamos la criba como una lista con n elementos True
&lt;br /&gt;
criba = [True] * n&lt;br /&gt;
&lt;br /&gt;
#iteramos desde 2 hasta la raiz cuadrada de n&lt;br /&gt;
#y desde lo que lleva i, por i, hasta n&lt;br /&gt;
for i in range(2, int(n ** .5) + 1):&lt;br /&gt;
    for j in range(i * i, n + 1, i):&lt;br /&gt;
        #esto nos permite poner False en la posicion j - i de la criba&lt;br /&gt;
        #porque j es un multiplo de i y por lo tanto no es primo&lt;br /&gt;
        criba[j - 1] = False&lt;br /&gt;
&lt;br /&gt;
#por ultimo &quot;cribamos&quot; todos los numeros primos desde 2&lt;br /&gt;
#hasta la longitud de la criba&lt;br /&gt;
primos = [p for p in range(2, len(criba) + 1) if criba[p - 1])]&lt;br /&gt;
[/code]&lt;br /&gt;
&lt;p&gt;
&lt;strong&gt;Cr&amp;eacute;ditos&lt;/strong&gt;:
&lt;/p&gt;
&lt;p&gt;
&lt;a href=&quot;http://www.s-anand.net/euler.html&quot; title=&quot;S-anand - Euler&quot;&gt;http://www.s-anand.net/euler.html &lt;/a&gt;
&lt;/p&gt;</description>
   <link>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/431_cdigo_en_python_para_hacer_la_criba_de_eratstenes.html</link>
   <comments>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/431_cdigo_en_python_para_hacer_la_criba_de_eratstenes.html</comments>
   <guid>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/431_cdigo_en_python_para_hacer_la_criba_de_eratstenes.html</guid>
      <author>pythonista</author>
   <category>
           python 3 
           algoritmos 
           numeros primos 
           criba de eratostenes 
        </category>
   <source url="http://bytesofcode.pythonblogs.com/102_bytesofcode/feeds/rss20">bytesofcode</source>
  </item>
          
  <item>
   <title>Funciones para convertir de decimal a binario</title>
   <description>&lt;p&gt;
He encontrado 2 buenos algoritmos para convertir un numero decimal a binario a trav&amp;eacute;s de estas funciones que reciben el numero entero en base 10 a convertir y devuelven una cadena de caract&amp;eacute;res con los d&amp;iacute;gitos del mismo n&amp;uacute;mero ya convertido a base 2.
&lt;/p&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Python versi&amp;oacute;n 2.7 &lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
 
&lt;/p&gt;
[code python]
&lt;br /&gt;
def binario1(n):
&lt;br /&gt;
    &quot;&quot;&quot;este primer algoritmo utiliza la formula n = 2k + b&quot;&quot;&quot;
&lt;br /&gt;
    if n == 0 or n == 1: return str(n)
&lt;br /&gt;
    k = n / 2
&lt;br /&gt;
    E = binario1(k)
&lt;br /&gt;
    b = n % 2
&lt;br /&gt;
    return str(E) + str(b)
&lt;br /&gt;
&lt;br /&gt;
def binario2(n):
&lt;br /&gt;
    &quot;&quot;&quot;y este va recorriendo 1 bit hacia la derecha en cada iteracion&quot;&quot;&quot;
&lt;br /&gt;
    if n == 0: return str(n)
&lt;br /&gt;
    b = &#039;&#039;
&lt;br /&gt;
    while n &amp;gt; 0:
&lt;br /&gt;
        b = str(n % 2) + b
&lt;br /&gt;
        n &amp;gt;&amp;gt;= 1
&lt;br /&gt;
        #de esta forma el numero se va dividiendo entre 2 para llegar a 0
&lt;br /&gt;
        #y terminar el bucle
&lt;br /&gt;
        #tambien podria ser de esta forma
&lt;br /&gt;
        #n /= 2 
&lt;br /&gt;
    return b
[/code]
&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
Si&amp;eacute;ntente libre de comentar que te parecieron y si conoces alg&amp;uacute;n otro te invito a publicarlo, gracias 
&lt;/p&gt;</description>
   <link>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/519_funciones_para_convertir_de_decimal_a_binario.html</link>
   <comments>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/519_funciones_para_convertir_de_decimal_a_binario.html</comments>
   <guid>http://bytesofcode.pythonblogs.com/102_bytesofcode/archive/519_funciones_para_convertir_de_decimal_a_binario.html</guid>
      <author>pythonista</author>
   <category>
           python 
           algoritmos 
           python 2.7 
           binario 
           decimal 
           numeros 
           matematicas 
        </category>
   <source url="http://bytesofcode.pythonblogs.com/102_bytesofcode/feeds/rss20">bytesofcode</source>
  </item>
          
  <item>
   <title>Random Password Generation in Python</title>
   <description>&lt;h4 class=&quot;post-title&quot;&gt;&lt;a href=&quot;http://www.myspace.com/hayathms/blog/542645124&quot; title=&quot;Read Auto Password Generating In Python&quot; rel=&quot;bookmark&quot;&gt;Auto Password Generating In Python&lt;/a&gt;&lt;/h4&gt;
&lt;p&gt;
&lt;span style=&quot;font-size: small; color: #ff6600&quot;&gt;Here is the code for simple auto password generating in python using any string like first name, or username or anything .&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: medium; color: #339966&quot;&gt;import random&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;span style=&quot;font-size: medium; color: #339966&quot;&gt;&lt;br /&gt;
def gen_random_password(string_letters):&lt;br /&gt;
    string_letters = string_letters.replace(&#039; &#039;,&#039;&#039;)&lt;br /&gt;
    string_letters = string_letters.replace(&#039;.&#039;,&#039;&#039;)&lt;br /&gt;
    a = random.choice(string_letters)&lt;br /&gt;
    b = random.choice(string_letters)&lt;br /&gt;
    c = random.choice(string_letters)&lt;br /&gt;
    d = random.choice(string_letters)&lt;br /&gt;
    e = str(random.randint(100,500))&lt;br /&gt;
    f = str(random.randint(500,1000))&lt;br /&gt;
    return a+e+b+f+c+d]&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
And Please comment me how strong password can be generated using my above code. :) 
&lt;/p&gt;</description>
   <link>http://my-python-codes.pythonblogs.com/128_my_python_codes/archive/474_random_password_generation_in_python.html</link>
   <comments>http://my-python-codes.pythonblogs.com/128_my_python_codes/archive/474_random_password_generation_in_python.html</comments>
   <guid>http://my-python-codes.pythonblogs.com/128_my_python_codes/archive/474_random_password_generation_in_python.html</guid>
      <author>hayathms</author>
   <category>
           General 
        </category>
   <source url="http://my-python-codes.pythonblogs.com/128_my_python_codes/feeds/rss20">My Python Codes</source>
  </item>
          
  <item>
   <title>Python for Newbies: A Simple Anagram Finder</title>
   <description>&lt;p&gt;
Once you get past Hello World, there are a several good entry points for a new Python developer to get acquainted with the language.  Three areas which really helped me were simple math problems, the Python challenge, and writing some word game solvers. 
&lt;/p&gt;
&lt;p&gt;
The best source of basic math problems for a new python developer is &lt;a href=&quot;http://projecteuler.net/&quot; title=&quot;Project Euler&quot;&gt;Project Euler&lt;/a&gt;. This site is basically an online math test - where you need to write a small program to perform the required calculations. Most of these problems can be solved by a new developer in under an hour (some faster). It will broaden your understanding of mathematics and give you a good grounding in basic Python.
&lt;/p&gt;
&lt;p&gt;
The &lt;a href=&quot;http://www.pythonchallenge.com/&quot; title=&quot;Python Challenge&quot;&gt;Python Challenge &lt;/a&gt;is another good learning environment. The participant is presented with a web page that contains a riddle, with clues buried somewhere on the page. Your job is to use Python to solve the riddle. This generally requiring you to take a deep dive into one of the modules in the Standard Library. We&#039;ve used this as a warmup exercise in one of the meetups I attend - I can recall doing modules around regular expressions, urllib (simple web scraping), and image processing.
&lt;/p&gt;
&lt;p&gt;
My deepest dive into the language occured when I started doing some &quot;code doodling&quot; around solving word puzzles. For example, the script below takes a list of words and searches a dictionary to identify their anagrams. For a dictionary, I opted to use Enable (Google hosts a copy of it - look for enable.txt on the Google Code directory behind this &lt;a href=&quot;http://code.google.com/p/dotnetperls-controls/downloads/list&quot; title=&quot;Enable word list&quot;&gt;link&lt;/a&gt;). 
&lt;/p&gt;
&lt;p&gt;
A couple of insights made this script possible:
&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Exact anagrams of a word have the same number of letters - just in a different order.  If you sort the letters of each word in the dictionary into alphabetical order (eg. cart =&amp;gt; acrt), words that are anagrams of each other will have the same value.&lt;/li&gt;
	&lt;li&gt;This guides us towards a solution. Use Python&#039;s sort function to map the anagrams in a list of words into a common key; then construct a dictionary using this common key to accumulate a list of anagrams mapped to that value.&lt;/li&gt;
	&lt;li&gt;The anagrams for a particular word can be retrieved using the &quot;get&quot; method of the dictionary.&lt;/li&gt;
	&lt;li&gt;Finally - just for fun - we use Python&#039;s map function to demonstrate how you can run this check for a whole list of candidates&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Since it&#039;s five o&#039;clock somewhere, I opted to run this script against a list of beverages.
&lt;/p&gt;
&lt;p&gt;
[code python]
&lt;/p&gt;
&lt;p&gt;
testlist = [&quot;wine&quot;,&quot;beer&quot;,&quot;mead&quot;,&quot;liquor&quot;,&quot;scotch&quot;,&quot;gin&quot;,&quot;whiskey&quot;,&quot;rum&quot;]
&lt;/p&gt;
&lt;p&gt;
def gethandle(word):&lt;br /&gt;
    return (&quot;&quot;).join(sorted(word))
&lt;/p&gt;
&lt;p&gt;
anagrams={}
&lt;/p&gt;
&lt;p&gt;
wordlist =open(&quot;enable1.txt&quot;)&lt;br /&gt;
for item in wordlist:&lt;br /&gt;
     handle = gethandle(item.strip())&lt;br /&gt;
     if handle not in anagrams:&lt;br /&gt;
         anagrams[handle] = [item.strip()]&lt;br /&gt;
     else:&lt;br /&gt;
         anagrams[handle].append(item.strip())
&lt;/p&gt;
&lt;p&gt;
def testforanagrams(word):&lt;br /&gt;
    results = anagrams.get(gethandle(word),[])
&lt;/p&gt;
&lt;p&gt;
    if len(results)&amp;gt;1:&lt;br /&gt;
          print word, &quot;:&quot;,&quot;, &quot;.join([item for item in results if item != word])&lt;br /&gt;
    else:&lt;br /&gt;
          print word, &quot;:&quot;, &quot;None&quot;
&lt;/p&gt;
&lt;p&gt;
map(testforanagrams,testlist)
&lt;/p&gt;
&lt;p&gt;
[/code]
&lt;/p&gt;
&lt;p&gt;
producing the following output:
&lt;/p&gt;
&lt;p&gt;
[code python]
&lt;/p&gt;
&lt;p&gt;
wine : None&lt;br /&gt;
beer : bree&lt;br /&gt;
mead : dame, made&lt;br /&gt;
liquor : None&lt;br /&gt;
scotch : None&lt;br /&gt;
gin : None&lt;br /&gt;
whiskey : None&lt;br /&gt;
rum : None
&lt;/p&gt;
&lt;p&gt;
[/code]
&lt;/p&gt;
&lt;p&gt;
This is a fairly basic and slightly verbose script and there are a number of ways to improve upon it. I&#039;ll suggest a couple of the more obvious ones, the implementation of which is left as an exercise for the student. 
&lt;/p&gt;
&lt;p&gt;
First, it could benefit by reorganizing all of the code into proper functions. Several elements of the script execute sequentially with the script vs. being packaged into reusable functions. I&#039;d actually recommend reorganizing the entire script into a class object. This neatly encapsulates the above activities and helps you separate the act of loading the dataset from searching the dataset. From a performance perspective, you spend a lot of IO and CPU time parsing and loading the initial dictionary. If you operated this as some type of &quot;service&quot;, you should leverage this setup time across as many requests as possible.
&lt;/p&gt;
&lt;p&gt;
On a personal note, this little script actually got me started on a larger journey - involving two additional steps. 
&lt;/p&gt;
&lt;p&gt;
Once I had a basic anagram finder, I started looking at adding other word games into the package. This forced me to do some optimization around the underlying algorithm using several articles I found on Python data structures and processing performance. In the process, I was able to learn a lot about how to benchmark the memory usage and CPU speed for a Python program. While the final product was much more complicated, it was a lean, mean &quot;word searching machine&quot;.
&lt;/p&gt;
&lt;p&gt;
While I was building the class object, I was also learning about several python web frameworks for work and wanted to find a safe test project. Once I built the word search class object, I used a web framework to link a URL Route (/solveword) to a class method (solve-word function). This provided me with the server-side chassis for a word game solver website (the first &quot;production grade&quot; solver I wrote is &lt;a href=&quot;http://www.hanginghyena.com/hangmansolver&quot; title=&quot;Online Hangman Solver&quot;&gt;here&lt;/a&gt;, a fancier version of the solver is &lt;a href=&quot;http://www.hanginghyena.com/hanging-with-friends-solver&quot; title=&quot;hanging with friends solver&quot;&gt;here&lt;/a&gt;). I gave a talk on this project at my local Python meetup (overview and slides are &lt;a href=&quot;http://www.marginhound.com/pyatl-talk-building-websites-using-bottle-py/&quot; title=&quot;Building Websites With Bottle.py&quot;&gt;here&lt;/a&gt;). This series of steps actually prompted me to learn a lot more than Python - HTML, CSS, Jquery, basic devops, etc...
&lt;/p&gt;
&lt;p&gt;
Don&#039;t be afraid of taking little steps when learning a new language. Little steps and silly problems (eg. anagram finding, finding palindromes, many of the other Project Euler exercises) are frequently the gateway to working on more serious applications. Having &quot;code in production&quot; tends to prompt you to create more code - forcing you to learn more than you ever expected about topics you never knew existed until they were suddenly relevant to bringing your baby to life. Silly little steps sometimes can turn into respectable deliverables....
&lt;/p&gt;</description>
   <link>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1258_python_for_newbies_a_simple_anagram_finder.html</link>
   <comments>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1258_python_for_newbies_a_simple_anagram_finder.html</comments>
   <guid>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1258_python_for_newbies_a_simple_anagram_finder.html</guid>
      <author>numbercruncher</author>
   <category>
           Python 
           word games 
        </category>
   <source url="http://python-for-analysts.pythonblogs.com/211_python-for-analysts/feeds/rss20">python-for-analysts</source>
  </item>
          
  <item>
   <title>Comprehending List Comprehensions</title>
   <description>&lt;p&gt;
List comprehensions are often a bit intimidating to developers who are new to Python. They are really much friendlier than that :) It&#039;s just a way to repackage that pile of for-loops, if-then statements, and calculation logic which is littering your current code. Here&#039;s a simple example to put them in perspective. 
&lt;/p&gt;
&lt;p&gt;
Assume I have a list of data - (1,2,3,4,5,6....n). 
&lt;/p&gt;
&lt;p&gt;
Now, there are a couple of very common &quot;building block&quot; transformations which we can apply to this dataset. I can create a new list by doing each of the following (alone or in combinator with each other): 
&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Applying a specific transformation to each element of the existing list (eg. add one to each item, take the cosine of each item, etc.); you do this with a for-loop and some basic calculation logic in many languages....&lt;/li&gt;
	&lt;li&gt;Applying a Boolean test (also a mathematical operation, in a sense) to each element of the existing list and rejecting any element that does not pass that test. This is commonly handled by including an if-if statement in the for-loop...&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Notice something in common here? We&#039;re defining a mathematical operation and applying it to each element of a list. 
&lt;/p&gt;
&lt;p&gt;
What Python construct do we use to encapsulate mathematical operations? Yes, You in the back. Right, Functions... 
&lt;/p&gt;
&lt;p&gt;
What if there were a way to succinctly summarize a mathematical operation as a function and apply it to each element of a Python list. Guess what, you&#039;re in luck. This is where Python&#039;s functional programming constructs come into play - which include two functions that are designed to take a list and another function (as arguments) and create a new list by applying that function to every element of the intial list. These two functions are: 
&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Map (function, list) - takes a list, applies the function to each element of the list to get a new value, returns a list of those values&lt;/li&gt;
	&lt;li&gt;Filter (function, list) - applies a test function (returns True / False) to each element of the list, keeps only items that return true&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Entry level list comprehensions are just a one-liner way of expressing this. 
&lt;/p&gt;
&lt;p&gt;
Consider the following: 
&lt;/p&gt;
&lt;p&gt;
[code python] 
&lt;/p&gt;
&lt;p&gt;
initial_list = [1,2,3,4,5] 
&lt;/p&gt;
&lt;p&gt;
my_func  = lambda x: x * x 
&lt;/p&gt;
&lt;p&gt;
[/code] 
&lt;/p&gt;
&lt;p&gt;
We can use for-loops and if-then logic to create a new list using the following in Python or - with minor syntax edits - many other languages, such as Visual Basic and C / C++: 
&lt;/p&gt;
&lt;p&gt;
[code python] 
&lt;/p&gt;
&lt;p&gt;
new_list = [] 
&lt;/p&gt;
&lt;p&gt;
for element in initial_list: 
&lt;/p&gt;
&lt;p&gt;
   if element &amp;gt; 5: 
&lt;/p&gt;
&lt;p&gt;
       new_list.append(my_func(element)) 
&lt;/p&gt;
&lt;p&gt;
[/code] 
&lt;/p&gt;
&lt;p&gt;
There&#039;s nothing obviously wrong with this - I mean, we get to write lots of &quot;lines of code&quot; so the boss feels good, right?  
&lt;/p&gt;
&lt;p&gt;
If we wanted to take advantage of Python&#039;s functional programming tools, we could also write this as: 
&lt;/p&gt;
&lt;p&gt;
[code python] 
&lt;/p&gt;
&lt;p&gt;
new_list = map(my_func,filter(lambda x:x&amp;gt;5,  initial_list)) 
&lt;/p&gt;
&lt;p&gt;
[/code] 
&lt;/p&gt;
&lt;p&gt;
Yuck...we&#039;ve got it down to one line but now I have to think about it when I read it! 
&lt;/p&gt;
&lt;p&gt;
Or you could express it as a one line list comprehension: 
&lt;/p&gt;
&lt;p&gt;
[code python] 
&lt;/p&gt;
&lt;p&gt;
new_list = [my_func(item) for item in initial_list if item &amp;gt; 5] 
&lt;/p&gt;
&lt;p&gt;
[/code] 
&lt;/p&gt;
&lt;p&gt;
Ahh...much easier to parse. 
&lt;/p&gt;
&lt;p&gt;
The appeal of using a list comprehension is your code is more succinct and easy to read. 
&lt;/p&gt;
&lt;p&gt;
This is a simple example. I recommend you take a look at the Python docs on functional programming and list comprehensions for a much richer view of the many things you can do with this tool. But hopefully now you can map this concept back to a familiar technique. 
&lt;/p&gt;</description>
   <link>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1261_comprehending_list_comprehensions.html</link>
   <comments>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1261_comprehending_list_comprehensions.html</comments>
   <guid>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1261_comprehending_list_comprehensions.html</guid>
      <author>numbercruncher</author>
   <category>
           Python 
        </category>
   <source url="http://python-for-analysts.pythonblogs.com/211_python-for-analysts/feeds/rss20">python-for-analysts</source>
  </item>
          
  <item>
   <title>IDLE Easter Egg...</title>
   <description>&lt;p&gt;
Presented without comment, aside from the fact that this made me laugh on an otherwise frustrating day...  
&lt;/p&gt;
&lt;p&gt;
[code python] 
&lt;/p&gt;
&lt;p&gt;
import antigravity 
&lt;/p&gt;
&lt;p&gt;
[/code] 
&lt;/p&gt;
&lt;p&gt;
Update: I found an &lt;a href=&quot;http://python-history.blogspot.com/2010/06/import-antigravity.html&quot; title=&quot;import antigravity history&quot;&gt;article&lt;/a&gt; talking about this, with a comment from the BDFL... 
&lt;/p&gt;</description>
   <link>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1263_idle_easter_egg.html</link>
   <comments>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1263_idle_easter_egg.html</comments>
   <guid>http://python-for-analysts.pythonblogs.com/211_python-for-analysts/archive/1263_idle_easter_egg.html</guid>
      <author>numbercruncher</author>
   <category>
           Python 
        </category>
   <source url="http://python-for-analysts.pythonblogs.com/211_python-for-analysts/feeds/rss20">python-for-analysts</source>
  </item>
          
  <item>
   <title>Python Coding Standards</title>
   <description>&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
Coding standards is not only to avoid ugly code. It is very useful to get responses quickly.
&lt;/p&gt;
&lt;p&gt;
You can see the python coding standards in &lt;a href=&quot;http://www.python.org/dev/peps/pep-0008/&quot; title=&quot;PEP8&quot;&gt;PEP8&lt;/a&gt;. 
&lt;/p&gt;
&lt;p&gt;
There are many third party packages to test standards you used in your modules. Especially pylint package is very simple to use. 
&lt;/p&gt;
&lt;p&gt;
To install pylint follow the link &lt;a href=&quot;http://pypi.python.org/pypi/pylint&quot; title=&quot;Pylint&quot;&gt;http://pypi.python.org/pypi/pylint&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Examples:
&lt;/p&gt;
&lt;p&gt;
Here I write two modules having same logic. First one(ws.py) is written with standards and another one(wos.py) is not having standards. 
&lt;/p&gt;
&lt;p&gt;
#### With Standards (ws.py) ####
&lt;/p&gt;
&lt;p&gt;
&quot;&quot;&quot;&lt;br /&gt;
Test the coding standards&lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;
&quot;&quot;&quot; 
&lt;/p&gt;
&lt;p&gt;
from datetime import datetime, timedelta&lt;br /&gt;
 &lt;br /&gt;
def with_standard():&lt;br /&gt;
    &quot;&quot;&quot;
&lt;/p&gt;
&lt;p&gt;
    Test the coding standards&lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;
    &quot;&quot;&quot;
&lt;/p&gt;
&lt;p&gt;
    st_time = datetime.\&lt;br /&gt;
                now()&lt;br /&gt;
    data = {&#039;los&#039;:30,&lt;br /&gt;
            &#039;san&#039;:60,&lt;br /&gt;
            &#039;can&#039;:80,&lt;br /&gt;
            &#039;New&#039;:20}&lt;br /&gt;
    for city, provider_count in data.\&lt;br /&gt;
                                iteritems():&lt;br /&gt;
        if (city != &#039;&#039; and \&lt;br /&gt;
            provider_count &amp;lt; 100):&lt;br /&gt;
            pass&lt;br /&gt;
    end_time = (datetime.\&lt;br /&gt;
                now() - timedelta(hours=st_time.hour,&lt;br /&gt;
                                  seconds=st_time.second,&lt;br /&gt;
                                  microseconds=st_time.microsecond))&lt;br /&gt;
    print &quot;To get response the script took %s \&lt;br /&gt;
(Hour:Minutes:Seconds MicroSeconds)&quot; % (end_time.\&lt;br /&gt;
                                            strftime(&#039;%H:%M:%S %f&#039;))&lt;br /&gt;
    return ()&lt;br /&gt;
&lt;br /&gt;
if __name__ == &#039;__main__&#039;:&lt;br /&gt;
    with_standard()
&lt;/p&gt;
&lt;p&gt;
### End of Module ### 
&lt;/p&gt;
&lt;p&gt;
### Without standards (wos.py) ###
&lt;/p&gt;
&lt;p&gt;
from datetime import datetime,timedelta&lt;br /&gt;
 &lt;br /&gt;
def without_standard():&lt;br /&gt;
    st_time = datetime.now()&lt;br /&gt;
    data = {&#039;los&#039;:30,&#039;san&#039;:60,&#039;can&#039;:80,&#039;New&#039;:20}&lt;br /&gt;
    for key,value in data.iteritems():&lt;br /&gt;
        if key != &#039;&#039; and value &amp;lt; 100:&lt;br /&gt;
            pass&lt;br /&gt;
    end_time = datetime.now() - timedelta(hours=st_time.hour,seconds=st_time.second,microseconds=st_time.microsecond)&lt;br /&gt;
    print &quot;To get response the script took %s (Hour:Minutes:Seconds MicroSeconds)&quot; %(end_time.strftime(&#039;%H:%M:%S %f&#039;)) &lt;br /&gt;
    return ()&lt;br /&gt;
    &lt;br /&gt;
if __name__ == &#039;__main__&#039;:&lt;br /&gt;
    without_standard()
&lt;/p&gt;
&lt;p&gt;
### End of Module ### 
&lt;/p&gt;
&lt;p&gt;
Test standards:
&lt;/p&gt;
&lt;p&gt;
If we execute &lt;strong&gt;pylint ws.py&lt;/strong&gt; command from command line, it will give 10.00/10 as the standards rate.
&lt;/p&gt;
&lt;p&gt;
When we execute &lt;strong&gt;pylint wos.py&lt;/strong&gt; command, it will give 3.85/10 as the rate. 
&lt;/p&gt;
&lt;p&gt;
Now you can see a huge difference between standards&#039; rate. 
&lt;/p&gt;
&lt;p&gt;
So try to follow standards in your future modules :) 
&lt;/p&gt;</description>
   <link>http://my-blog.pythonblogs.com/214_my_blog/archive/1267_python_coding_standards.html</link>
   <comments>http://my-blog.pythonblogs.com/214_my_blog/archive/1267_python_coding_standards.html</comments>
   <guid>http://my-blog.pythonblogs.com/214_my_blog/archive/1267_python_coding_standards.html</guid>
      <author>ugkarthik</author>
   <category>
           Python 
        </category>
   <source url="http://my-blog.pythonblogs.com/214_my_blog/feeds/rss20">My Blog</source>
  </item>
          
  <item>
   <title>JQuery and python script</title>
   <description>&lt;p&gt;
&lt;br /&gt;
&lt;br /&gt;
Recently i have implemented JQuery in one of the site created through python CGI. I googled a lot about it and got very easy solution to this.&lt;br /&gt;
I guess, this can be used in any site where we need to call python script.
&lt;/p&gt;
&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
 [code python]
&lt;/p&gt;
&lt;p&gt;
$(&quot;#AnyID&quot;).click(function()&lt;br /&gt;
    {&lt;br /&gt;
        $.ajax({&lt;br /&gt;
            type: &quot;get&quot;,&lt;br /&gt;
            url: &quot;&amp;lt;your-python-script&amp;gt;.py&quot;,&lt;br /&gt;
            data: {&#039;param1&#039;:&#039;abc&#039;},&lt;br /&gt;
            datatype:&quot;script&quot;,&lt;br /&gt;
            async: false,&lt;br /&gt;
            success: function(response) {&lt;br /&gt;
            // response is string, convert it to json and apply conditions.&lt;br /&gt;
            var json_obj= eval(&#039;(&#039; + response + &#039;)&#039;);//$.parseJSON(&quot;&#039;&quot;+response+&quot;&#039;&quot;);&lt;br /&gt;
            if (json_obj.type == &#039;Error&#039;){&lt;br /&gt;
              alert(json_obj.msg);&lt;br /&gt;
            }&lt;br /&gt;
            else {&lt;br /&gt;
              alert(json_obj.msg);&lt;br /&gt;
            }// else closed&lt;br /&gt;
            }, // success closed&lt;br /&gt;
            error:function(xhr,err)&lt;br /&gt;
            {&lt;br /&gt;
                alert(&quot;Error connecting to server, please contact system administator.&quot;);&lt;br /&gt;
            }&lt;br /&gt;
        })//ajax closed&lt;br /&gt;
}&lt;br /&gt;
 [/code]&lt;br /&gt;
make sure that your python script is callable through url ex. www.example.com/&amp;lt;your-python-script&amp;gt;.py&lt;br /&gt;
What i did is, in my &amp;lt;your-python-script&amp;gt;.py script i return dictionary object like {&#039;type&#039;:&#039;Success&#039;, &#039;msg&#039;:&#039;Your message&#039;}.&lt;br /&gt;
If you have CGI script, dont return anything just print the dictionary.&lt;br /&gt;
&lt;br /&gt;
JQuery ajax for python only supports get method for now (i found somewhere, i tried with POST, not working).&lt;br /&gt;
here, in above code, you can see &quot;async:false&quot;, the purpose of it is very interesting.&lt;br /&gt;
While your JQuery run python script and fetch data for you, if you want to block any click event, use &quot;async:true&quot;, interesting.. isn&#039;t it?
&lt;/p&gt;</description>
   <link>http://pymantra.pythonblogs.com/90_pymantra/archive/1284_jquery_and_python_script.html</link>
   <comments>http://pymantra.pythonblogs.com/90_pymantra/archive/1284_jquery_and_python_script.html</comments>
   <guid>http://pymantra.pythonblogs.com/90_pymantra/archive/1284_jquery_and_python_script.html</guid>
      <author>sharmavivek82</author>
   <category>
           python 
        </category>
   <source url="http://pymantra.pythonblogs.com/90_pymantra/feeds/rss20">PyMantra</source>
  </item>
          
  <item>
   <title>Timer Help Python 2.5</title>
   <description>&lt;p&gt;
Does anyone know how to make a Timer function in Python 2.5. Cancel or .cancel() only stops the Timer while in execution, but how do you stop the Timer or threading after execution is finished.  This is what I made for a timer, but it locks up the program. 
&lt;/p&gt;
&lt;p&gt;
def main():&lt;br /&gt;
    import time&lt;br /&gt;
    import threading&lt;br /&gt;
    global time&lt;br /&gt;
    global threading&lt;br /&gt;
    global stoneskinT&lt;br /&gt;
    &lt;br /&gt;
    stoneskinT = threading.Timer(5.0, stoneskin)&lt;br /&gt;
    stoneskinT.start()&lt;br /&gt;
    string = raw_input (&quot;... &quot;)&lt;br /&gt;
    stoneskinT.cancel() 
&lt;/p&gt;
&lt;p&gt;
    while (string == &quot;&quot;):&lt;br /&gt;
        stoneskinT = threading.Timer(5.0, stoneskin)&lt;br /&gt;
        stoneskinT.start()&lt;br /&gt;
        string = raw_input (&quot;... &quot;)&lt;br /&gt;
        stoneskinT.cancel()&lt;br /&gt;
        &lt;br /&gt;
def stoneskin():&lt;br /&gt;
    global string&lt;br /&gt;
    global stoneskinT    &lt;br /&gt;
    print &quot;Potion of stoneskin has worn off.&quot;&lt;br /&gt;
    string = raw_input (&quot;... &quot;)&lt;br /&gt;
main() 
&lt;/p&gt;</description>
   <link>http://timer-help.pythonblogs.com/133_timer_help/archive/480_timer_help_python_25.html</link>
   <comments>http://timer-help.pythonblogs.com/133_timer_help/archive/480_timer_help_python_25.html</comments>
   <guid>http://timer-help.pythonblogs.com/133_timer_help/archive/480_timer_help_python_25.html</guid>
      <author>mike</author>
   <category>
           General 
        </category>
   <source url="http://timer-help.pythonblogs.com/133_timer_help/feeds/rss20">Timer Help</source>
  </item>
          
  <item>
   <title>Run Python script method using eval statement</title>
   <description>&lt;p&gt;
 
&lt;/p&gt;
&lt;p&gt;
Recently i did excellent work around to run python script using eval statement.&lt;br /&gt;
    [code python]p_obj = eval(&amp;lt;python script name&amp;gt;, globals()),&amp;lt;arguments passed to script&amp;gt; [/code]&lt;br /&gt;
    Now, you can run any method inside the script by calling p_obj.run()
&lt;/p&gt;</description>
   <link>http://pymantra.pythonblogs.com/90_pymantra/archive/1262_run_python_script_method_using_eval_statement.html</link>
   <comments>http://pymantra.pythonblogs.com/90_pymantra/archive/1262_run_python_script_method_using_eval_statement.html</comments>
   <guid>http://pymantra.pythonblogs.com/90_pymantra/archive/1262_run_python_script_method_using_eval_statement.html</guid>
      <author>sharmavivek82</author>
   <category>
           python 
        </category>
   <source url="http://pymantra.pythonblogs.com/90_pymantra/feeds/rss20">PyMantra</source>
  </item>
          
  <item>
   <title>Simple Web Server in python</title>
   <description>&lt;p&gt;
Recently, I was hanging arround flex codes which calls python script resides on other server through web services. I got confused, Is it a good idea to use web service just to call python script from other server? Why not to use cgi module or mod-python to get the same result as getting through web services?&lt;br /&gt;
&lt;br /&gt;
So i decided to write a simple web server which has some methods to be called as a URL. Got excellent help from &lt;br /&gt;
http://fragments.turtlemeat.com/pythonwebserver.php&lt;br /&gt;
then, i added some code.&lt;br /&gt;
[code python]
&lt;/p&gt;
&lt;p&gt;
&lt;br /&gt;
import string,cgi,time&lt;br /&gt;
from os import curdir, sep&lt;br /&gt;
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer&lt;br /&gt;
&lt;br /&gt;
class VivekServer(BaseHTTPRequestHandler):&lt;br /&gt;
&lt;br /&gt;
    def do_GET(self):&lt;br /&gt;
        try:&lt;br /&gt;
        if self.path == &#039;/fetch&#039;:&lt;br /&gt;
                self.send_response(200)&lt;br /&gt;
                self.send_header(&#039;Content-type&#039;,        &#039;text/html&#039;)&lt;br /&gt;
                self.end_headers()&lt;br /&gt;
                res = self.wcount()&lt;br /&gt;
                self.wfile.write(&quot;Number of count for &#039;anyword&#039; :&quot;)&lt;br /&gt;
                self.wfile.write(res[0])&lt;br /&gt;
                self.wfile.write(&quot; url is :&quot;)&lt;br /&gt;
                self.wfile.write(res[1])&lt;br /&gt;
                return&lt;br /&gt;
        if self.path == &#039;/calculate&#039;:            &lt;br /&gt;
                self.send_response(200)&lt;br /&gt;
                self.send_header(&#039;Content-type&#039;,        &#039;text/html&#039;)&lt;br /&gt;
                self.end_headers()&lt;br /&gt;
                res = self.calculate()&lt;br /&gt;
                for each in res:&lt;br /&gt;
                    self.wfile.write(each)&lt;br /&gt;
                    self.wfile.write(&#039;\n&#039;)&lt;br /&gt;
                    return&lt;br /&gt;
&lt;br /&gt;
                return&lt;br /&gt;
                &lt;br /&gt;
        except IOError:&lt;br /&gt;
            self.send_error(404,&#039;File Not Found: %s&#039; % self.path)&lt;br /&gt;
     &lt;br /&gt;
    def calculate(self):&lt;br /&gt;
         import random&lt;br /&gt;
         WORD = &#039;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#039;&lt;br /&gt;
         data = []&lt;br /&gt;
         for i in range(1, 100):&lt;br /&gt;
             data.append((random.randrange(0, 1000), random.sample(WORD, len(WORD))[0]))&lt;br /&gt;
         return data&lt;br /&gt;
&lt;br /&gt;
    def do_POST(self):&lt;br /&gt;
        pass&lt;br /&gt;
&lt;br /&gt;
    def wcount(self):&lt;br /&gt;
         from BeautifulSoup import BeautifulSoup as soup&lt;br /&gt;
         import urllib2&lt;br /&gt;
&lt;br /&gt;
         htm  = &#039;http://www.anyurl.com&#039;&lt;br /&gt;
         html_text = urllib2.urlopen( htm ) .read()&lt;br /&gt;
         sp = soup(html_text)&lt;br /&gt;
         idea = sp.findAll( &quot;anyword&quot; )    &lt;br /&gt;
         all_a = [ each.get(&#039;href&#039;) for each in sp.findAll(&#039;a&#039;) ]&lt;br /&gt;
         num = 0&lt;br /&gt;
         for each in all_a:&lt;br /&gt;
             if each.find(&quot;anyword&quot;) &amp;gt; 0:&lt;br /&gt;
                 num=num+1&lt;br /&gt;
         return (idea,num,htm)&lt;br /&gt;
&lt;br /&gt;
def main():&lt;br /&gt;
    try:&lt;br /&gt;
        server = HTTPServer((&#039;&#039;, 7999), VivekServer)&lt;br /&gt;
        print &#039;Server Started.....&#039;&lt;br /&gt;
        server.serve_forever()&lt;br /&gt;
    except KeyboardInterrupt:&lt;br /&gt;
        print &#039;Server Ends.....&#039;&lt;br /&gt;
        server.socket.close()&lt;br /&gt;
&lt;br /&gt;
if __name__ == &#039;__main__&#039;:&lt;br /&gt;
    main()
&lt;/p&gt;
&lt;p&gt;
&lt;br /&gt;
[/code]&lt;br /&gt;
&lt;br /&gt;
This is just a help to start a simple web server and call your method through url. 
&lt;/p&gt;
&lt;p&gt;
To run above code, just do, python abovecode.py&lt;br /&gt;
&lt;br /&gt;
open web browser, type url as&lt;br /&gt;
http://localhost:7999/fetch&lt;br /&gt;
http://localhost:7999/calculate 
&lt;/p&gt;</description>
   <link>http://pymantra.pythonblogs.com/90_pymantra/archive/422_simple_web_server_in_python.html</link>
   <comments>http://pymantra.pythonblogs.com/90_pymantra/archive/422_simple_web_server_in_python.html</comments>
   <guid>http://pymantra.pythonblogs.com/90_pymantra/archive/422_simple_web_server_in_python.html</guid>
      <author>sharmavivek82</author>
   <category>
           python 
        </category>
   <source url="http://pymantra.pythonblogs.com/90_pymantra/feeds/rss20">PyMantra</source>
  </item>
   </channel>
</rss>