body
stringlengths
144
5.53k
comments
list
meta_data
dict
question_id
stringlengths
1
6
yield
stringclasses
2 values
answers
list
<p>I have this prime factor generator for some number <code>n</code>. It returns list of all prime factors. In other words, product of the list equals <code>n</code>.</p> <pre><code>def prime_factors_generate(n): a = [] prime_list = sorted(primes()) pindex = 0 p = prime_list[pindex] num = n while p != num: if num % p == 0: a.append(p) num //= p else: pindex += 1 p = prime_list[pindex] return a </code></pre> <p>The <code>primes()</code> function uses the <a href="http://plus.maths.org/content/os/issue50/features/havil/index" rel="nofollow noreferrer">Sundaram Sieve</a> from <a href="https://stackoverflow.com/a/2073279/596361">here</a> and returns a <em>set</em> of all primes below some limit, by default 10<sup>6</sup>.</p> <p>How can I make this code functional? I want to get rid of the <code>while</code>-loop, list appending and mutated state.</p>
[]
{ "AcceptedAnswerId": "19523", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:46:03.297", "Id": "19509", "Score": "1", "Tags": [ "python", "algorithm", "functional-programming", "primes" ], "Title": "Functional prime factor generator" }
19509
accepted_answer
[ { "body": "<p>There are a few things you can do to make your code more functional. First note that it isn't necessary to have a list of primes beforehand. As you eliminate factors from the bottom up, there cannot be a composite \"false positive\" since its prime factors will have been accounted for already. </p>\n\n<p>Here is a more functional version of your code:</p>\n\n<pre><code>from math import ceil, sqrt\n\ndef factor(n):\n if n &lt;= 1: return []\n prime = next((x for x in range(2, ceil(sqrt(n))+1) if n%x == 0), n)\n return [prime] + factor(n//prime)\n</code></pre>\n\n<p><strong>Generator expression</strong></p>\n\n<p>This is a <a href=\"http://docs.python.org/3.3/tutorial/classes.html#generator-expressions\" rel=\"nofollow\">generator expression</a>, which is a <a href=\"http://docs.python.org/3.3/tutorial/classes.html#generators\" rel=\"nofollow\">generator</a> version of <a href=\"http://docs.python.org/3.3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehensions</a>:</p>\n\n<pre><code>(x for x in range(2, ceil(sqrt(n))+1) if n%x == 0)\n</code></pre>\n\n<p>Note that in Python 2.7.3, <code>ceil</code> returns a <code>float</code> and <code>range</code> accepts <code>ints</code>.</p>\n\n<p>Basically, for every number from 2 to <code>ceil(sqrt(n))</code>, it generates all numbers for which <code>n%x == 0</code> is true. The call to <code>next</code> gets the first such number. If there are no valid numbers left in the expression, <code>next</code> returns <code>n</code>.</p>\n\n<p><strong>Recursion</strong></p>\n\n<p>This is a <a href=\"http://en.wikipedia.org/wiki/Recursion_%28computer_science%29\" rel=\"nofollow\">recursive</a> call, that appends to our list the results of nested calls:</p>\n\n<pre><code>return [prime] + factor(n//prime)\n</code></pre>\n\n<p>For example, consider <code>factor(100)</code>. Note that this is just a simplification of the call stack.</p>\n\n<p>The first prime will be 2, so:</p>\n\n<pre><code>return [2] + factor(100//2)\n</code></pre>\n\n<p>Then when the first recursive call is to this point, we have:</p>\n\n<pre><code>return [2] + [2] + factor(50//2)\nreturn [2] + [2] + [5] + factor(25//5)\nreturn [2] + [2] + [5] + [5] + factor(5//5)\n</code></pre>\n\n<p>When <code>factor</code> is called with an argument of <code>1</code>, it breaks the recursion and returns an empty list, at <code>if n &lt;= 1: return []</code>. This is called a <a href=\"http://en.wikipedia.org/wiki/Base_case\" rel=\"nofollow\">base case</a>, a construct vital to functional programming and mathematics in general. So finally, we have:</p>\n\n<pre><code>return [2] + [2] + [5] + [5] + []\n[2, 2, 5, 5]\n</code></pre>\n\n<p><strong>Generator version</strong></p>\n\n<p>We can create a generator version of this ourselves like this: </p>\n\n<pre><code>from math import ceil, sqrt\n\ndef factorgen(n):\n if n &lt;= 1: return\n prime = next((x for x in range(2, ceil(sqrt(n))+1) if n%x == 0), n)\n yield prime\n yield from factorgen(n//prime)\n</code></pre>\n\n<p>The keyword <code>yield</code> freezes the state of the generator, until <code>next</code> is called to grab a value. The <code>yield from</code> is just syntactic sugar for</p>\n\n<pre><code>for p in factorgen(n//prime):\n yield p\n</code></pre>\n\n<p>which was introduced in <a href=\"http://docs.python.org/3/whatsnew/3.3.html\" rel=\"nofollow\">Python 3.3</a>.</p>\n\n<p>With this version, we can use a for loop, convert to a list, call <code>next</code>, etc. Generators provide <a href=\"http://en.wikipedia.org/wiki/Lazy_evaluation\" rel=\"nofollow\">lazy evaluation</a>, another important tool in a functional programmer's arsenal. This allows you to create the \"idea\" for a sequence of values without having to bring it into existence all at once, so to speak.</p>\n\n<p>Though I didn't use it here, I can't resist mentioning a very nice Python library named <a href=\"http://docs.python.org/3.3/library/itertools.html\" rel=\"nofollow\"><code>itertools</code></a>, which can help you immensely with functional-style programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T07:09:21.173", "Id": "19523", "ParentId": "19509", "Score": "2" } } ]
<p>I have a function for finding factors of a number in Python</p> <pre><code>def factors(n, one=True, itself=False): def factors_functional(): # factors below sqrt(n) a = filter(lambda x: n % x == 0, xrange(2, int(n**0.5)+1)) result = a + map(lambda x: n / x, reversed(a)) return result </code></pre> <p><code>factors(28)</code> gives <code>[2, 4, 7, 14]</code>. Now i want this function to also include 1 in the beginning of a list, if <code>one</code> is true, and 28 in the end, if <code>itself</code> is true.</p> <pre><code>([1] if one else []) + a + map(lambda x: n / x, reversed(a)) + ([n] if itself else []) </code></pre> <p>This is "clever" but inelegant.</p> <pre><code>if one: result = [1] + result if itself: result = result + [n] </code></pre> <p>This is straight-forward but verbose.</p> <p>Is it possible to implement optional one and itself in the output with the most concise yet readable code possible? Or maybe the whole idea should be done some other way - like the function <code>factors</code> can be written differently and still add optional 1 and itself?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T03:46:51.630", "Id": "31249", "Score": "0", "body": "The straight forward way isn't that verbose. I don't see a different way to do it the doesn't sacrifice readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T04:34:05.523", "Id": "31250", "Score": "0", "body": "You may think it is verbose but it is self explanatory and can easily be commented out without messing around with the core code." } ]
{ "AcceptedAnswerId": "19528", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T23:15:37.983", "Id": "19510", "Score": "3", "Tags": [ "python", "functional-programming" ], "Title": "Function to find factors of a number, optionally including 1 and the number itself" }
19510
accepted_answer
[ { "body": "<p>What about this?</p>\n\n<pre><code>[1] * one + result + [n] * itself\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T05:37:14.763", "Id": "31316", "Score": "1", "body": "I was thinking `[1]*int(one) + result + [n]*int(itself)`, scrolled down and saw this beauty. Didn't know this could be done. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:47:22.787", "Id": "31370", "Score": "0", "body": "interesting... but please don't actually do this. \"Programs must be written for people to read and only incidentally for machines to execute.\" This takes me way longer to read than the 4-liner." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T12:37:44.743", "Id": "19528", "ParentId": "19510", "Score": "5" } } ]
<p>I've got dictionary of lists of tuples. Each tuple has timestamp as first element and values in others. Timestamps could be different for other keys:</p> <pre><code>dict = { 'p2': [(1355150022, 3.82), (1355150088, 4.24), (1355150154, 3.94), (1355150216, 3.87), (1355150287, 6.66)], 'p1': [(1355150040, 7.9), (1355150110, 8.03), (1355150172, 8.41), (1355150234, 7.77)], 'p3': [(1355150021, 1.82), (1355150082, 2.24), (1355150153, 3.33), (1355150217, 7.77), (1355150286, 6.66)], } </code></pre> <p>I want this convert to list of lists:</p> <pre><code>ret = [ ['time', 'p1', 'p2', 'p3'], [1355149980, '', 3.82, 1.82], [1355150040, 7.9, 4.24, 2.24], [1355150100, 8.03, 3.94, 3.33], [1355150160, 8.41, 3.87, 7.77], [1355150220, 7.77, '', ''], [1355150280, '', 6.66, 6.66] ] </code></pre> <p>I'm making conversion with that dirty definition:</p> <pre><code>def convert_parameters_dict(dict): tmp = {} for p in dict.keys(): for l in dict[p]: t = l[0] - l[0] % 60 try: tmp[t][p] = l[1] except KeyError: tmp[t] = {} tmp[t][p] = l[1] ret = [] ret.append([ "time" ] + sorted(dict.keys())) for t, d in sorted(tmp.iteritems()): l = [] for p in sorted(dict.keys()): try: l.append(d[p]) except KeyError: l.append('') ret.append([t] + l) return ret </code></pre> <p>Maybe there is some much prettier way?</p>
[]
{ "AcceptedAnswerId": "19574", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:50:28.937", "Id": "19572", "Score": "6", "Tags": [ "python", "hash-map" ], "Title": "Convert dictionary of lists of tuples to list of lists/tuples in python" }
19572
accepted_answer
[ { "body": "<p>How about...</p>\n\n<pre><code>times = sorted(set(int(y[0] / 60) for x in d.values() for y in x))\ntable = [['time'] + sorted(d.keys())]\nfor time in times:\n table.append([time * 60])\n for heading in table[0][1:]:\n for v in d[heading]:\n if int(v[0] / 60) == time:\n table[-1].append(v[1])\n break\n else:\n table[-1].append('')\nfor row in table:\n print row\n</code></pre>\n\n<p>Or, less readable but probably faster if the dictionary is long (because it only loops through each list in the dictionary once):</p>\n\n<pre><code>times = sorted(set(int(v2[0] / 60) for v in d.values() for v2 in v))\nempty_row = [''] * len(d)\ntable = ([['time'] + sorted(d.keys())] + \n [[time * 60] + empty_row for time in times])\nfor n, key in enumerate(table[0][1:]):\n for v in d[key]:\n if int(v[0] / 60) in times:\n table[times.index(v[0] / 60) + 1][n + 1] = v[1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T09:28:07.727", "Id": "31324", "Score": "0", "body": "Thank you all. Stuart, I'll use your second solution. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T08:47:45.800", "Id": "19574", "ParentId": "19572", "Score": "1" } } ]
<p>This reads a list of points from a file with a certain format:</p> <blockquote> <pre><code>&lt;number of points&gt; x1 y1 x2 y2 </code></pre> </blockquote> <p>How I can make it better?</p> <pre><code>from collections import namedtuple Point = namedtuple('Point ', ['x', 'y']) def read(): ins = open("PATH_TO_FILE", "r") array = [] first = True expected_length = 0 for line in ins: if first: expected_length = int(line.rstrip('\n')) first = False else: parsed = line.rstrip('\n').split () array.append(Point(int(parsed[0]), int(parsed[1]))) if expected_length != len(array): raise NameError("error on read") return array </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T03:25:21.697", "Id": "31365", "Score": "0", "body": "If you're dealing with points you might want to use a library like Shapely, which will give you a nice Point object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T09:46:38.313", "Id": "31375", "Score": "0", "body": "@monkut, thx I'll see." } ]
{ "AcceptedAnswerId": "19602", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T19:52:28.513", "Id": "19588", "Score": "3", "Tags": [ "python", "file" ], "Title": "Reading data from file" }
19588
accepted_answer
[ { "body": "<p>Another improvement is to use <code>open</code> as a context manager so that you don't have to remember to <code>.close()</code> the file object even if there are errors while reading.</p>\n\n<pre><code>def read():\n with open(\"FILE\", \"r\") as f:\n array = []\n expected_length = int(f.next())\n for line in f:\n parsed = map(int, line.split())\n array.append(Point(*parsed))\n if expected_length != len(array):\n raise NameError('error on read')\n return array\n</code></pre>\n\n<p>See <a href=\"http://docs.python.org/2/library/stdtypes.html#file.close\" rel=\"nofollow\">http://docs.python.org/2/library/stdtypes.html#file.close</a> for more details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:28:24.557", "Id": "19602", "ParentId": "19588", "Score": "4" } } ]
<p>I have a nested <code>for</code>-loop that populates a list with elements:</p> <pre><code>a = [] for i in range(1, limit+1): for j in range(1, limit+1): p = i + j + (i**2 + j**2)**0.5 if p &lt;= limit: a.append(p) </code></pre> <p>I could refactor it into list comprehension:</p> <pre><code>a = [i + j + (i**2 + j**2)**0.5 for i in range(1, limit+1) for j in range(1, limit+1) if i + j + (i**2 + j**2)**0.5 &lt;= limit] </code></pre> <p>But now the same complex expression is in both parts of it, which is unacceptable. Is there any way to create a list in a functional way, but more elegantly?</p> <p>I guess in Lisp I would use recursion with <code>let</code>. How it is done in more functional languages like Clojure, Scala, Haskell?</p> <p>In Racket it's possible to <a href="https://stackoverflow.com/q/14979231/596361">bind expressions</a> inside a <code>for/list</code> comprehension. I've found one solution to my problem:</p> <pre><code>[k for i in range(1, limit+1) for j in range(1, limit+1) for k in [i + j + (i**2 + j**2)**0.5] k &lt;= limit] </code></pre> <p>I'm not sure how pythonic it is.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T18:56:55.870", "Id": "31637", "Score": "0", "body": "Just pointing out that you can divide limit by 2 in the range function (since you square the numbers anyway) and you'll still get the full set of results. Also, I would write a `transform` function that handled the math and run a list comprehension over it." } ]
{ "AcceptedAnswerId": "19948", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T14:31:14.840", "Id": "19611", "Score": "5", "Tags": [ "python", "combinatorics" ], "Title": "Finding perimeters of right triangles with integer-length legs, up to a limit" }
19611
accepted_answer
[ { "body": "<p>In the general case, Jeff's answer is the way to go : generate then filter.</p>\n\n<p>For your particular example, since the expression is increasing wrt both variables, you should stop as soon as you reach the limit.</p>\n\n<pre><code>def max_value(limit, i) :\n \"\"\"return max positive value one variable can take, knowing the other\"\"\"\n if i &gt;= limit :\n return 0\n return int(limit*(limit-2*i)/(2*(limit-i)))\n\ndef collect_within_limit(limit) :\n return [ i + j + (i**2 + j**2)**0.5\n for i in range(1,max_value(limit,1)+1)\n for j in range(1,max_value(limit,i)+1) ]\n</code></pre>\n\n<p>Now, providing this <code>max_value</code> is error prone and quite ad-hoc. We would want to keep the stopping condition based on the computed value. In your imperative solution, adding <code>break</code> when <code>p&gt;limit</code> would do the job. Let's find a functional equivalent :</p>\n\n<pre><code>import itertools\n\ndef collect_one_slice(limit,i) :\n return itertools.takewhile(lambda x: x &lt;= limit,\n (i + j + (i**2 + j**2)**0.5 for j in range(1,limit)))\n\ndef collect_all(limit) :\n return list(itertools.chain(*(collect_one_slice(limit, i)\n for i in range(1,limit))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T18:25:30.887", "Id": "19948", "ParentId": "19611", "Score": "3" } } ]
<p>Pythonic way of expressing the simple problem:</p> <blockquote> <p>Tell if the list <code>needle</code> is sublist of <code>haystack</code></p> </blockquote> <hr> <pre><code>#!/usr/bin/env python3 def sublist (haystack, needle): def start (): i = iter(needle) return next(i), i try: n0, i = start() for h in haystack: if h == n0: n0 = next(i) else: n0, i = start() except StopIteration: return True return False </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T03:27:04.163", "Id": "31422", "Score": "0", "body": "So, what's the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T12:30:16.977", "Id": "31427", "Score": "0", "body": "@JeffVanzella: Fair point. That's \"code review\". The question is: \"what do you think in general?\"." } ]
{ "AcceptedAnswerId": "19629", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T22:54:25.417", "Id": "19627", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Finding sub-list" }
19627
accepted_answer
[ { "body": "<h3>1. Bug</h3>\n\n<p>Here's a case where your function fails:</p>\n\n<pre><code>&gt;&gt;&gt; sublist([1, 1, 2], [1, 2])\nFalse\n</code></pre>\n\n<p>this is because in the <code>else:</code> case you go back to the beginning of the needle, but you keep going forward in the haystack, possibly skipping over a match. In the test case, your function tries matching with the alignment shown below, which fails at the position marked <code>X</code>:</p>\n\n<pre><code> X\nhaystack 1,1,2\nneedle 1,2\n</code></pre>\n\n<p>Then it starts over from the beginning of the needle, but keeps going forward in the haystack, thus missing the match:</p>\n\n<pre><code> X\nhaystack 1,1,2\nneedle 1,2\n</code></pre>\n\n<p>So after a mismatch you need to go <em>backward</em> an appropriate distance in the haystack before starting over again from the beginning of the needle.</p>\n\n<h3>2. A better algorithm</h3>\n\n<p>It turns out to be better to start matching from the <em>end</em> of the needle. If this fails to match, we can skip forward several steps: possibly the whole length of the needle. For example, in this situation:</p>\n\n<pre><code> X\nhaystack 1,2,3,4,6,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>we can skip forward by the whole length of the needle (because <code>6</code> does not appear in the needle). The next alignment we need to try is this:</p>\n\n<pre><code> O O O O O\nhaystack 1,2,3,4,6,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>However, we can't always skip forward the whole length of the needle. The distance we can skip depends on the item that fails to match. In this situation:</p>\n\n<pre><code> X\nhaystack 1,2,3,4,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>we should skip forward by 4, to bring the <code>1</code>s into alignment.</p>\n\n<p>Making these ideas precise leads to the <a href=\"http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm\" rel=\"nofollow\">Boyer–Moore–Horspool</a> algorithm:</p>\n\n<pre><code>def find(haystack, needle):\n \"\"\"Return the index at which the sequence needle appears in the\n sequence haystack, or -1 if it is not found, using the Boyer-\n Moore-Horspool algorithm. The elements of needle and haystack must\n be hashable.\n\n &gt;&gt;&gt; find([1, 1, 2], [1, 2])\n 1\n\n \"\"\"\n h = len(haystack)\n n = len(needle)\n skip = {needle[i]: n - i - 1 for i in range(n - 1)}\n i = n - 1\n while i &lt; h:\n for j in range(n):\n if haystack[i - j] != needle[-j - 1]:\n i += skip.get(haystack[i], n)\n break\n else:\n return i - n + 1\n return -1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:11:56.267", "Id": "31416", "Score": "0", "body": "@Lattyware: Generally I'd agree that you should use iterators wherever it makes sense, but this is one of the exceptional cases where iterators don't make much sense. A pure-iterator search runs in O(*nm*) whereas Boyer–Moore-Horspool is O(*n*). (In the average case on random text.) Sometimes you just have to get your hands grubby." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:29:05.937", "Id": "31420", "Score": "0", "body": "Scratch all my arguments, it's impossible to do this correctly the way I was doing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T12:38:21.643", "Id": "31428", "Score": "0", "body": "Accepted. The source is strong with this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T03:14:56.147", "Id": "70305", "Score": "0", "body": "Does the dict comprehension overwrite previous values? If not you'll skip too far when you see `e` while searching for `seven`. I'd bet it does but am not sure. I do miss Python for its elegance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T10:17:39.237", "Id": "70369", "Score": "0", "body": "Yes, later items in the dict comprehension override previous items, and so `find('seven', 'even')` → `1` as required." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:00:44.667", "Id": "19629", "ParentId": "19627", "Score": "5" } } ]
<p>I've written a script to generate DNA sequences and then count the appearance of each step to see if there is any long range correlation.</p> <p>My program runs really slow for a length 100000 sequence 100 times replicate. I already run it for more than 100 hours without completion.</p> <pre><code>#!/usr/bin/env python import sys, random import os import math length = 10000 initial_p = {'a':0.25,'c':0.25,'t':0.25,'g':0.25} tran_matrix = {'a': {'a':0.495,'c':0.113,'g':0.129,'t':0.263}, 'c': {'a':0.129,'c':0.063,'g':0.413,'t':0.395}, 't': {'a':0.213,'c':0.495,'g':0.263,'t':0.029}, 'g': {'a':0.263,'c':0.129,'g':0.295,'t':0.313}} def fl(): def seq(): def choose(dist): r = random.random() sum = 0.0 keys = dist.keys() for k in keys: sum += dist[k] if sum &gt; r: return k return keys[-1] c = choose(initial_p) sequence = '' for i in range(length): sequence += c c = choose(tran_matrix[c]) return sequence sequence = seq() # This program takes a DNA sequence calculate the DNA walk score. #print sequence #print len u = 0 ls = [] for i in sequence: if i == 'a' : #print i u = u + 1 if i == 'g' : #print i u = u + 1 if i== 'c' : #print i u = u - 1 if i== 't' : #print i u = u - 1 #print u ls.append(u) #print ls l = 1 f = [] for l in xrange(1,(length/2)+1): lchange =1 sumdeltay = 0 sumsq = 0 for i in range(1,length/2): deltay = ls[lchange + l ] - ls[lchange] lchange = lchange + 1 sq = math.fabs(deltay*deltay) sumsq = sumsq + sq sumdeltay = sumdeltay + deltay f.append(math.sqrt(math.fabs((sumsq/length/2) - math.fabs((sumdeltay/length/2)*(sumdeltay/length/2))))) l = l + 1 return f def performTrial(tries): distLists = [] for i in range(0, tries): fl() distLists.append(fl()) return distLists def main(): tries = 10 distLists = performTrial(tries) #print distLists #print distLists[0][0] averageList = [] for i in range(0, length/2): total = 0 for j in range(0, tries): total += distLists[j][i] #print distLists average = total/tries averageList.append(average) # print total return averageList out_file = open('Markov1.result', 'w') result = str(main()) out_file.write(result) out_file.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:26:31.680", "Id": "31452", "Score": "0", "body": "Could you explain what this is supposed to do in plain English? 1) At the moment, this is a bit long to read without explanation, 2) It may help you identify the problem yourself, and 3) Stop people taking a stab at stuff that looks like it *may* be wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:35:07.817", "Id": "31453", "Score": "0", "body": "Hi, the first function is seq(), it randomly generate DNA sequences based on the transition matrix follow markov chain, each step will be either a,c,t,or g. the length is ten thousands. after the dna sequence generated, the u will be calculated. u is the total score by DNA walk, for example, at each step, if there is a|g, u + 1, if there is a c|g, u -1. Therefore we will have u from step 1 to step 10 thousands. Then we calculate the fluctuation for u from l= 1 step to l =5000 step, to see if there is a long range correlation exist. The performTrial() is using to do replicate for fl() function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:38:30.300", "Id": "31454", "Score": "0", "body": "Then the main() calculate the average score from the replications output from performTrial()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:42:08.367", "Id": "31455", "Score": "0", "body": "The f value return from fl() is the root mean fluctuation calculated from u on different length(step) scale." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:52:36.157", "Id": "31456", "Score": "0", "body": "@Frank Is there a reason your `fl()` function only operates over half the random sequence and does nothing with the other half?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:20:57.837", "Id": "19654", "Score": "6", "Tags": [ "python", "beginner", "algorithm", "bioinformatics" ], "Title": "Generating DNA sequences and looking for correlations" }
19654
max_votes
[ { "body": "<p>Concerning just a little part of your code</p>\n\n<pre><code>u = 0\nls = []\nfor i in sequence:\n u += (1 if i in 'ag' else (-1))\n ls.append(u)\n\nprint ls\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>def gen(L,u = 0):\n for i in L:\n u += (1 if i in 'ag' else (-1))\n yield u\n\nprint list(gen(sequence))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T00:19:15.767", "Id": "19656", "ParentId": "19654", "Score": "1" } } ]
<p>Are there ways to avoid this triply nested for-loop?</p> <pre><code>def add_random_fields(): from numpy.random import rand server = couchdb.Server() databases = [database for database in server if not database.startswith('_')] for database in databases: for document in couchdb_pager(server[database]): if 'results' in server[database][document]: for tweet in server[database][document]['results']: if tweet and 'rand_num' not in tweet: print document tweet['rand_num'] = rand() server[database].save(tweet) </code></pre> <p><strong>Update</strong> </p> <p>People suggesting that I use a generator reminded me that I forgot to mention that <code>couchdb_pager</code> is a generator over the list <code>server[database]</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T05:37:54.397", "Id": "31467", "Score": "4", "body": "Fundamentally, you're descending through three separate levels of data. Unless you can flatten them or skip one, you have to use a for-loop for each level in the hierarchy. I'd suggest refactoring some of your loops out into their own functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T06:48:52.893", "Id": "31468", "Score": "0", "body": "Maybe using a generator or iterator?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T07:46:05.427", "Id": "31470", "Score": "3", "body": "As it is I don't see any problem with this code - it's readable and efficient. If you really don't like the nesting you could do something like `documents = (document for database in databases for document in couchdb_pager(server[database]) if 'results' in document)` then loop through the documents." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T05:07:32.170", "Id": "19657", "Score": "3", "Tags": [ "python" ], "Title": "Removing the massive amount of for-loops in this code" }
19657
max_votes
[ { "body": "<p>There are a few tweaks that can improve this code:</p>\n\n<pre><code>def add_random_fields():\n from numpy.random import rand\n server = couchdb.Server()\n databases = (server[database] for database in server if not database.startswith('_'))\n # immediately fetch the Server object rather then the key, \n # changes to a generator to avoid instantiating all the database objects at once\n for database in databases:\n for document in couchdb_pager(database):\n document = database[document] \n # same here, avoid holding keys when you can have the objects\n\n for tweet in document.get('results', []):\n # rather then checking for the key, have it return a default that does the same thing\n if tweet and 'rand_num' not in tweet:\n print document\n tweet['rand_num'] = rand()\n database.save(tweet)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:27:30.333", "Id": "19694", "ParentId": "19657", "Score": "3" } } ]
<p>What do you think about this?</p> <pre><code>#utils.py def is_http_url(s): """ Returns true if s is valid http url, else false Arguments: - `s`: """ if re.match('https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&amp;%?#-]{1,300})?',s): return True else: return False #utils_test.py import utils class TestHttpUrlValidating(unittest.TestCase): """ """ def test_validating(self): """ """ self.assertEqual(utils.is_http_url('https://google.com'),True) self.assertEqual(utils.is_http_url('http://www.google.com/r-o_ute?key=value'),True) self.assertEqual(utils.is_http_url('aaaaaa'),False) </code></pre> <p>Is this enough? I'm going to insert URLs into database. Are there other ways to validate it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T05:23:48.827", "Id": "64943", "Score": "0", "body": "I'd use [urlparse](http://docs.python.org/2/library/urlparse.html) in the standard library to check it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:58:55.057", "Id": "64944", "Score": "1", "body": "You can use the rfc3987 package. `rfc3987.match('http://http://codereview.stackexchange.com/', rule='URI')`" } ]
{ "AcceptedAnswerId": "19670", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T15:53:42.797", "Id": "19663", "Score": "3", "Tags": [ "python", "regex", "validation", "url", "http" ], "Title": "HTTP URL validating" }
19663
accepted_answer
[ { "body": "<p>I would check out <a href=\"https://github.com/django/django/blob/master/django/core/validators.py\" rel=\"nofollow\">Django's validator</a> - I'm willing to bet it's going to be decent, and it's going to be very well tested.</p>\n\n<pre><code>regex = re.compile(\n r'^(?:http|ftp)s?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|' # ...or ipv4\n r'\\[?[A-F0-9]*:[A-F0-9:]+\\]?)' # ...or ipv6\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n</code></pre>\n\n<p>This covers a few edge cases like IP addresses and ports. Obviously some stuff (like FTP links) you might not want to accept, but it'd be a good place to start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-04T20:48:21.603", "Id": "356316", "Score": "0", "body": "This code example seems mostly copied from that SO answer. I think it should have proper attribution. https://stackoverflow.com/a/7160778/172132\n(Unlike the original answer this checks for IPv6 URLs, though.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T20:06:23.763", "Id": "19670", "ParentId": "19663", "Score": "2" } } ]
<p>I have a Python file with several function definitions in it. One of the functions, named 'main' will be called as soon as the Python file is run.</p> <p>Example:</p> <pre><code>myFile.py import sys def main(arg1....): ---code--- --more functions-- main() </code></pre> <p>When a person wants to run my file they'll type:</p> <pre><code>python myFile.py arg1 arg2 ... </code></pre> <p>The main function is supposed to accept in x number of arguments, however, in case the user doesn't wish to pass in any arguments we're supposed to have default values.</p> <p>My program looks something like this and I'm hoping there is actually a better way to do this than what I have:</p> <pre><code>myFile.py import sys #Even though my function has default values, if the user doesn't wish #to input in any parameter values, they still must pass in the word False #otherwise, pls pass in parameter value def main(name = "Bill", age = 22, num_pets=5, hobby = "soccer"): if len(sys) &gt; 1: i =0 while i &lt; len(sys): if i == 0: if sys.argv[i] == "False": i += 1 continue else: name = sys.argv[i] i += 1 continue elif i == 1: if sys.argv[i] == "False": --------etc. etc.----------- </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T19:15:33.640", "Id": "19707", "Score": "3", "Tags": [ "python" ], "Title": "Python file with several function definitions" }
19707
max_votes
[ { "body": "<p>In case the number of arguments is really long then you can use **kwargs to avoid cluttering up arguments in function definition block. I would also avoid naming the function as \"main\" and replace it with something like \"execute\".</p>\n\n<pre><code>def execute(**kwargs):\n name = kwargs.get('name', 'Bill')\n # get other values\n pass\n\nif __name__ = \"__main__\":\n execute(*sys.argv[1:])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T09:26:06.103", "Id": "19725", "ParentId": "19707", "Score": "4" } } ]
<p>I had a question regarding my code which downloads a file from S3 with the highest (most recent) timedated filename format:</p> <p>YYYYMMDDHHMMSS.zip</p> <pre><code>from boto.s3.connection import S3Connection from boto.s3.key import Key import sys conn = S3Connection('____________________', '________________________________________') bucket = conn.get_bucket('bucketname') rs = bucket.list("FamilyPhotos") for key in rs: print key.name keys = [(key,datetime.strptime(key.name,'%Y%m%d%H%M%S.zip')) for key in rs] sorted(keys, key = lambda element : element[1]) latest = keys[0][1] latest.get_contents_to_filename() </code></pre> <p>I havent done a lot of python before so I would really appreciate some feedback.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:16:27.860", "Id": "31553", "Score": "0", "body": "What are you looking for specifically?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:34:22.500", "Id": "31555", "Score": "1", "body": "The part of the script that works out the most recently dated filename. I am sure there is a better way of doing it." } ]
{ "AcceptedAnswerId": "19768", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T09:37:04.007", "Id": "19727", "Score": "2", "Tags": [ "python", "amazon-s3" ], "Title": "Python Boto Script - Sorting based on date" }
19727
accepted_answer
[ { "body": "<p>The names will properly compare lexically even without converting them to datetimes, and you can just use the <a href=\"http://docs.python.org/2/library/functions.html#max\" rel=\"nofollow\"><code>max</code></a> function:</p>\n\n<pre><code>from boto.s3.connection import S3Connection\nfrom boto.s3.key import Key\n\nconn = S3Connection(XXX, YYY)\nbucket = conn.get_bucket('bucketname')\nrs = bucket.list(\"FamilyPhotos\")\nlatest = max(rs, key=lambda k: k.name)\nlatest.get_contents_to_filename()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T07:14:41.163", "Id": "19768", "ParentId": "19727", "Score": "3" } } ]
<p>I've been on stackoverflow looking for an alternative to the ugly if-elif-else structure shown below. The if-else structure takes three values as input and returns a pre-formatted string used for an SQL query. The code works right now, but it is difficult to explain, ugly, and I don't know a better way to do re-format it. </p> <p>I need a solution that is more readable. I was thinking a dictionary object, but I can't wrap my mind how to implement one with the complex if/else structure I have below. An ideal solution will be more readable. </p> <pre><code>def _getQuery(activity,pollutant,feedstock): if feedstock.startswith('CG') and pollutant.startswith('VOC'): pass if feedstock == 'FR' and activity == 'Harvest': return 'FR' elif feedstock == 'FR': return 'No Activity' elif(activity == 'Fertilizer' and pollutant != 'NOx' and pollutant != 'NH3'): return 'No Activity' elif(activity == 'Chemical' and pollutant != 'VOC'): return 'No Activity' elif( (feedstock == 'CS' or feedstock == 'WS') and (activity == 'Non-Harvest' or activity == 'Chemical')): return 'No Activity' elif( ( ( pollutant.startswith('CO') or pollutant.startswith('SO') ) and ( activity == 'Non-Harvest' or activity == 'Harvest' or activity == 'Transport' ) ) or ( pollutant.startswith('VOC') and not ( feedstock.startswith('CG') or feedstock.startswith('SG') ) ) ): rawTable = feedstock + '_raw' return """ with activitySum as (select distinct fips, sum(%s) as x from %s where description ilike '%s' group by fips), totalSum as (select distinct r.fips, sum(r.%s) as x from %s r group by r.fips), ratios as (select t.fips, (a.x/t.x) as x from activitySum a, totalSum t where a.fips = t.fips), maxRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x desc limit 1), minRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x asc limit 1) select mx.x, mn.x from maxRatio mx, minRatio mn; """ % (pollutant, rawTable, '%'+activity+'%', pollutant, rawTable) elif( (pollutant[0:2] == 'PM') and (activity == 'Non-Harvest' or activity == 'Harvest' or activity == 'Transport')): rawTable = feedstock + '_raw' return """ with activitySum as (select distinct fips, (sum(%s) + sum(fug_%s)) as x from %s where description ilike '%s' group by fips), totalSum as (select distinct r.fips, (sum(r.%s) + sum(r.fug_%s)) as x from %s r group by r.fips), ratios as (select t.fips, (a.x/t.x) as x from activitySum a, totalSum t where a.fips = t.fips), maxRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x desc limit 1), minRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x asc limit 1) select mx.x, mn.x from maxRatio mx, minRatio mn; """ % (pollutant, pollutant, rawTable, '%'+activity+'%', pollutant, pollutant, rawTable) . . . Lots more complex elif statements </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T21:03:41.157", "Id": "31588", "Score": "1", "body": "I'm not sure it's possible to answer this without knowing more about the range of possible parameters and return values. It might be worth creating more variables with meaningful names that would help make clear why certain combinations of parameter values result in a particular output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T22:19:50.857", "Id": "31590", "Score": "0", "body": "@Stuart, should I include the full if/elif structure in the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T00:03:34.130", "Id": "31594", "Score": "0", "body": "It might help if it's not *terribly* long. To start with, though, I would note that there is a lot of repetition in the long query string `\"\"\"with activitySum etc.` which appears twice with only minor changes. Maybe see if you can use the `if/elif` structure to set values of variables with meaningful names which are then sanitised and fed into a single 'template' query string at the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T16:24:03.633", "Id": "31630", "Score": "0", "body": "@Stuart, thanks for pointing out the code duplicate, by removing the duplicates, the code is looking more reasonable. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T20:40:02.157", "Id": "31639", "Score": "0", "body": "It can't be right to return a SQL query in some cases, and the string `'No Activity'` in others." } ]
{ "AcceptedAnswerId": "19756", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T19:54:14.617", "Id": "19753", "Score": "2", "Tags": [ "python", "sql" ], "Title": "Constructing an SQL expression from three parameters" }
19753
accepted_answer
[ { "body": "<p>My thought would be to create a collection of objects that can be iterated over. Each object would have an interface like the following.</p>\n\n<pre><code>def _getQuery(activity,pollutant,feedstock):\n for matcher in MATCHERS:\n if matcher.matches(activity,pollutant,feedstock):\n return matcher.get_result(activity,pollutant,feedstock)\n raise Exception('Not matched')\n</code></pre>\n\n<p>Then you build up the set of matcher classes for the various cases and ad an instance of each to <code>MATCHERS</code>. Just remember that earlier elements in the list take precedence to later ones. So the most specific cases should be first in the list ans the most general cases should be at the end.</p>\n\n<p><strong>NOTE</strong>: \nYour string building code is vulnerable to <a href=\"http://en.wikipedia.org/wiki/SQL_injection\">SQL-injection</a>. If you do go forward with manually building your selection strings, your input needs to be more thoroughly sanitized.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T16:24:51.607", "Id": "31631", "Score": "0", "body": "thanks for your comments, especially the part about SQL-injection! I was hoping for a more object-oriented approach and this seems quite reasonable!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T22:36:48.600", "Id": "19756", "ParentId": "19753", "Score": "6" } } ]
<p>I've written a couple of functions to check if a consumer of the API should be authenticated to use it or not.</p> <p>Have I done anything blatantly wrong here?</p> <p><strong>Config</strong></p> <pre><code>API_CONSUMERS = [{'name': 'localhost', 'host': '12.0.0.1:5000', 'api_key': 'Ahth2ea5Ohngoop5'}, {'name': 'localhost2', 'host': '127.0.0.1:5001', 'api_key': 'Ahth2ea5Ohngoop6'}] </code></pre> <p><strong>Exceptions</strong></p> <pre><code>class BaseException(Exception): def __init__(self, logger, *args, **kwargs): super(BaseException, self).__init__(*args, **kwargs) logger.info(self.message) class UnknownHostException(BaseException): pass class MissingHashException(BaseException): pass class HashMismatchException(BaseException): pass </code></pre> <p><strong>Authentication methods</strong></p> <pre><code>import hashlib from flask import request from services.exceptions import (UnknownHostException, MissingHashException, HashMismatchException) def is_authenticated(app): """ Checks that the consumers host is valid, the request has a hash and the hash is the same when we excrypt the data with that hosts api key Arguments: app -- instance of the application """ consumers = app.config.get('API_CONSUMERS') host = request.host try: api_key = next(d['api_key'] for d in consumers if d['host'] == host) except StopIteration: raise UnknownHostException( app.logger, 'Authentication failed: Unknown Host (' + host + ')') if not request.headers.get('hash'): raise MissingHashException( app.logger, 'Authentication failed: Missing Hash (' + host + ')') hash = calculate_hash(request.method, api_key) if hash != request.headers.get('hash'): raise HashMismatchException( app.logger, 'Authentication failed: Hash Mismatch (' + host + ')') return True def calculate_hash(method, api_key): """ Calculates the hash using either the url or the request content, plus the hosts api key Arguments: method -- request method api_key -- api key for this host """ if request.method == 'GET': data_to_hash = request.base_url + '?' + request.query_string elif request.method == 'POST': data_to_hash = request.data data_to_hash += api_key return hashlib.sha1(data_to_hash).hexdigest() </code></pre>
[]
{ "AcceptedAnswerId": "136029", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T19:10:36.143", "Id": "19786", "Score": "4", "Tags": [ "python", "authentication", "web-services", "flask" ], "Title": "Authentication for a Flask API" }
19786
accepted_answer
[ { "body": "<p>Building on @Drewverlee's answer, I would consider renaming <code>BaseException</code> to <code>APIException</code>, or something of the like.</p>\n\n<p>Also, I don't think passing app as an argument is best practice, I would recommend using the function as a decorator on your endpoints instead:</p>\n\n<pre><code># Your imports\nfrom application import app # Or whatever your non-relative reference is\n\ndef is_authenticated(func):\n def func_wrapper():\n # Your code here without the original def call\n return func_wrapper\n</code></pre>\n\n<p>You can then use this on each endpoint, adding the <code>@is_authenticated</code> decorator, to ensure the app is properly authenticated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-26T23:41:59.233", "Id": "136029", "ParentId": "19786", "Score": "4" } } ]
<p>I have view and it works correct, but very slow</p> <pre><code>class Reading(models.Model): meter = models.ForeignKey(Meter, verbose_name=_('meter')) reading = models.FloatField(verbose_name=_('reading')) code = models.ForeignKey(ReadingCode, verbose_name=_('code')) date = models.DateTimeField(verbose_name=_('date')) class Meta: get_latest_by = 'date' ordering = ['-date', ] def __unicode__(self): return u'%s' % (self.date,) @property def consumption(self): try: end = self.get_next_by_date(code=self.code, meter=self.meter) return (end.reading - self.reading) / (end.date - self.date).days except: return 0.0 @property def middle_consumption(self): data = [] current_year = self.date.year for year in range(current_year - 3, current_year): date = datetime.date(year, self.date.month, self.date.day) try: data.append(Reading.objects.get( date = date, meter = self.meter, code = self.code ).consumption) except: data.append(0.0) for i in data: if not i: data.pop(0) return sum(data) / len(data) class DataForDayChart(TemplateView): def get(self, request, *args, **kwargs): output = [] meter = Meter.objects.get(slug=kwargs['slug']) # TODO: Make it faster for reading in meter.readings_for_period().order_by('date'): output.append({ "label": reading.date.strftime("%d.%m.%Y"), "reading": reading.reading, "value": reading.consumption / 1000, "middle": reading.middle_consumption / 1000 }) return HttpResponse(output, mimetype='application/json') </code></pre> <p>What should I change to make it faster?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T08:18:32.167", "Id": "31790", "Score": "0", "body": "How slow it is? How many records the view returns?\nLooks like you have a loots of SQL Queries there, try to reduce amount of queries." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T06:24:10.340", "Id": "19886", "Score": "2", "Tags": [ "python", "django" ], "Title": "Django how to make this view faster?" }
19886
max_votes
[ { "body": "<p>There's nothing intrinsically time-consuming here code-wise - I think the best approach is to make sure that your database tables are set up correctly with the required indices. Perhaps create a view on the db to push some work onto that rather than select in code?</p>\n\n<p>I am a little puzzled however by your middle_consumption function. The inner loop contents do something like:</p>\n\n<pre><code>get a date, x years ago from present day\nget a reading on that date, or 0 on failure\nadd that reading to the results\ngo through the results\n if the current item is 0, delete the **first** item\n</code></pre>\n\n<p>This seems wrong.</p>\n\n<ol>\n<li>What happens on February 29th? It would be better to add 365 days if that's appropriate for your application.</li>\n<li><p>Why add a value only to (presumably want to) delete it again? Would something like this be better?</p>\n\n<pre><code>try:\n current_value = Reading.objects.get(\n date = date_of_reading,\n meter = self.meter,\n code = self.code\n ).consumption\nexcept Reading.DoesNotExist: # or suitable exception\n current_value = 0\nif current_value &gt; 0:\n anniversary_values.append( current_value )\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T08:57:33.763", "Id": "19887", "ParentId": "19886", "Score": "3" } } ]
<p>My solution to this feels 'icky' and I've got calendar math falling out of my ears after working on similar problems for a week so I can't think straight about this.</p> <p>Is there a better way to code this?</p> <pre><code>import datetime from dateutil.relativedelta import relativedelta def date_count(start, end, day_of_month=1): """ Return a list of datetime.date objects that lie in-between start and end. The first element of the returned list will always be start and the last element in the returned list will always be: datetime.date(end.year, end.month, day_of_month) If start.day is equal to day_of_month the second element will be: start + 1 month If start.day is after day_of_month then the second element will be: the day_of_month in the next month If start.day is before day_of_month then the second element will be: datetime.date(start.year, start.month, day_of_month) &gt;&gt;&gt; start = datetime.date(2012, 1, 15) &gt;&gt;&gt; end = datetime.date(2012, 4, 1) &gt;&gt;&gt; date_count(start, end, day_of_month=1) #doctest: +NORMALIZE_WHITESPACE [datetime.date(2012, 1, 15), datetime.date(2012, 2, 1), datetime.date(2012, 3, 1), datetime.date(2012, 4, 1)] Notice that it's not a full month between the first two elements in the list. If you have a start day before day_of_month: &gt;&gt;&gt; start = datetime.date(2012, 1, 10) &gt;&gt;&gt; end = datetime.date(2012, 4, 1) &gt;&gt;&gt; date_count(start, end, day_of_month=15) #doctest: +NORMALIZE_WHITESPACE [datetime.date(2012, 1, 10), datetime.date(2012, 1, 15), datetime.date(2012, 2, 15), datetime.date(2012, 3, 15), datetime.date(2012, 4, 15)] Notice that it's not a full month between the first two elements in the list and that the last day is rounded to datetime.date(end.year, end.month, day_of_month) """ last_element = datetime.date(end.year, end.month, day_of_month) if start.day == day_of_month: second_element = start + relativedelta(start, months=+1) elif start.day &gt; day_of_month: _ = datetime.date(start.year, start.month, day_of_month) second_element = _ + relativedelta(_, months=+1) else: second_element = datetime.date(start.year, start.month, day_of_month) dates = [start, second_element] if last_element &lt;= second_element: return dates while dates[-1] &lt; last_element: next_date = dates[-1] + relativedelta(dates[-1], months=+1) next_date = datetime.date(next_date.year, next_date.month, day_of_month) dates.append(next_date) dates.pop() dates.append(last_element) return dates </code></pre>
[]
{ "AcceptedAnswerId": "19907", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T19:49:00.440", "Id": "19903", "Score": "6", "Tags": [ "python", "datetime" ], "Title": "Building a list of dates between two dates" }
19903
accepted_answer
[ { "body": "<p>How about...</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n dates = [start]\n next_date = start.replace(day=day_of_month)\n if day_of_month &gt; start.day:\n dates.append(next_date)\n while next_date &lt; end.replace(day=day_of_month):\n next_date += relativedelta(next_date, months=+1)\n dates.append(next_date)\n return dates\n</code></pre>\n\n<p>And by the way it seems like a nice opportunity to use yield, if you wanted to.</p>\n\n<pre><code>def date_count2(start, end, day_of_month=1):\n yield start\n next_date = start.replace(day=day_of_month)\n if day_of_month &gt; start.day:\n yield next_date\n while next_date &lt; end.replace(day=day_of_month):\n next_date += relativedelta(next_date, months=+1)\n yield next_date\n</code></pre>\n\n<p>Another possibility - discard the first value if it is earlier than the start date:</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n dates = [start.replace(day=day_of_month)]\n while dates[-1] &lt; end.replace(day=day_of_month):\n dates.append(dates[-1] + relativedelta(dates[-1], months=+1))\n if dates[0] &gt; start:\n return [start] + dates\n else:\n return [start] + dates[1:]\n</code></pre>\n\n<p>Or use a list comprehension to iterate over the number of months between start and end.</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n round_start = start.replace(day=day_of_month)\n gap = end.year * 12 + end.month - start.year * 12 - start.month + 1\n return [start] + [round_start + relativedelta(round_start, months=i) \n for i in range(day_of_month &lt;= start.day, gap)]\n</code></pre>\n\n<p>Finally, I don't know dateutil but <a href=\"http://labix.org/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57\" rel=\"nofollow\">it seems you can use <code>rrule</code></a>:</p>\n\n<pre><code>from dateutil import rrule\ndef date_count(start, end, day_of_month=1):\n yield start\n for date in rrule(MONTHLY, \n dtstart=start.replace(day=day_of_month),\n until=end.replace(day=day_of_month)):\n if date &gt; start:\n yield date\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T22:38:05.560", "Id": "31862", "Score": "0", "body": "Excellent answer. Not sure which solution I will use, but thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T22:52:39.313", "Id": "19907", "ParentId": "19903", "Score": "3" } } ]
<p>I am working on a P2P streaming sim (which I think is correct), however I've discovered a huge bottleneck in my code. During the run of my sim, the function I've included below gets called about 25000 times and takes about 560 seconds from a total of about 580 seconds (I used pycallgraph).</p> <p>Can anyone identify any way I could speed the execution up, by optimizing the code (I think I won't be able to reduce the times it gets executed)? The basics needed to understand what the function does, is that the incoming messages consist of <code>[sender_sequence nr</code>, <code>sender_id</code>, <code>nr_of_known_nodes_to_sender</code> (or -1 if the sender departs the network), <code>time_to_live</code>], while the <code>mCache</code> entries these messages update, consist of the same data (except for the third field, which cannot be -1, instead if such a message is received the whole entry will be deleted), with the addition of a fifth field containing the update time.</p> <pre><code>def msg_io(self): # Node messages (not datastream) control # filter and sort by main key valid_sorted = sorted((el for el in self.incoming if el[3] != 0), key=ig(1)) self.incoming = [] # ensure identical keys have highest first element first valid_sorted.sort(key=ig(0), reverse=True) # group by second element grouped = groupby(valid_sorted, ig(1)) # take first element for each key internal = [next(item) for group, item in grouped] for j in internal: found = False if j[3] &gt; 0 : # We are only interested in non-expired messages for i in self.mCache[:]: if j[1] == i[1]: # If the current mCache entry corresponds to the current incoming message if j[2] == -1: # If the message refers to a node departure self.mCache.remove(i) # We remove the node from the mCache self.partnerCache = [partner for partner in self.partnerCache if not partner.node_id == j[1]] else: if j[0] &gt; i[0]: # If the message isn't a leftover (i.e. lower sequence number) i[:4] = j[:] # We update the relevant mCache entry i[4] = turns # We add the current time for the update found = True else: k = j[:] #k[3] -= 1 id_to_node[i[1]].incoming.append(k) # and we forward the message if not j[2] == -1 and not found and (len(self.mCache) &lt; maxNodeCache): # If we didn't have the node in the mCache temp = j[:] temp.append(turns) # We insert a timestamp... self.mCache.append(temp) # ...and add it to the mCache self.internal.remove(j) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T11:07:55.517", "Id": "19922", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "P2P streaming sim" }
19922
max_votes
[ { "body": "<p><code>valid_sorted</code> is created using <code>sorted</code> function, and then it is sorted again. I don't see how the first sort is helping in any way. Maybe I'm wrong..</p>\n\n<hr>\n\n<p>You create the iterator <code>grouped</code> with the function <code>groupby</code>, but then you turn it into list and then <strong>iterate over it</strong> again. instead - you can do this:</p>\n\n<pre><code>grouped = groupby(valid_sorted, ig(1))\nfor group, item in grouped:\n j = next(item)\n ...\n</code></pre>\n\n<p>That way - you only iterate over it once. :)</p>\n\n<hr>\n\n<p>The inner loop iterating over <code>self.mCache[:]</code> - I don't see why you can't just iterate over <code>self.mCache</code> and that's it. If its members are lists - it will change weither you use <code>[:]</code> or not.</p>\n\n<p>When you use <code>[:]</code> - you create a copy of the list, and that's why It can be bad for memory and speed.</p>\n\n<hr>\n\n<p>The <code>remove</code> function can be quite slow, if you can find a better way to implement your algorithm without using this function - it can be faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T16:22:00.390", "Id": "31851", "Score": "0", "body": "First of all, many thank! I can see the point in removing the sorted (I'm already applying some of the changes), however the reasoning behind the grouped() modifications eludes me...aren't we doing the iteration I'm doing via list comprehension, using an explicit for loop? Isn't that more inefficient?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T16:32:08.247", "Id": "31852", "Score": "0", "body": "Another thing that bothers me, is that since I use remove() on the mCache list, I wonder if it is safe to not slice it when I iterate over it, as you suggest. I think I saw a suggestion somewhere, about a reverse iteration, which should be removal safe" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T13:33:42.617", "Id": "31876", "Score": "0", "body": "As @winston's commet says - it seems like groupby doesn't do what we thought it does, so I guess it doesn't matter anymore :)\nAbout the `remove` use - I think it is ok to use it like you do, and if you'll reverse it - it will have the same effect in my opinion." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T13:43:19.413", "Id": "19924", "ParentId": "19922", "Score": "3" } } ]
<p>I'm currently using SciPy's mode function to find the most occurring item in different iterable objects. I like the mode function because it works on every object type I've thrown at it (strings, <code>float</code>s, <code>int</code>s).</p> <p>While this function seems reliable, it is very slow on bigger lists:</p> <pre><code>from scipy.stats import mode li = range(50000) li[1] = 0 %timeit mode(li) 1 loops, best of 3: 7.55 s per loop </code></pre> <p>Is there a better way to get the mode for a list? If so, would the implementation be different depending on the item type?</p>
[]
{ "AcceptedAnswerId": "20033", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T19:33:13.343", "Id": "20030", "Score": "3", "Tags": [ "python", "python-2.x" ], "Title": "Finding the mode of an array/iterable" }
20030
accepted_answer
[ { "body": "<p>Originally I thought you must have been doing something wrong, but no: the <code>scipy.stats</code> implementation of <code>mode</code> scales with the number of unique elements, and so will behave very badly for your test case.</p>\n\n<p>As long as your objects are hashable (which includes your three listed object types of strings, floats, and ints), then probably the simplest approach is to use <a href=\"http://docs.python.org/2/library/collections.html#counter-objects\" rel=\"noreferrer\">collections.Counter</a> and the <code>most_common</code> method:</p>\n\n<pre><code>In [33]: import scipy.stats\n\nIn [34]: li = range(50000); li[1] = 0\n\nIn [35]: scipy.stats.mode(li)\nOut[35]: (array([ 0.]), array([ 2.]))\n\nIn [36]: timeit scipy.stats.mode(li)\n1 loops, best of 3: 10.7 s per loop\n</code></pre>\n\n<p>but</p>\n\n<pre><code>In [37]: from collections import Counter\n\nIn [38]: Counter(li).most_common(1)\nOut[38]: [(0, 2)]\n\nIn [39]: timeit Counter(li).most_common(1)\n10 loops, best of 3: 34.1 ms per loop\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T22:00:26.980", "Id": "32001", "Score": "1", "body": "Wow! What an improvement!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T21:28:59.897", "Id": "20033", "ParentId": "20030", "Score": "5" } } ]
<p>At first I tried using a timedelta but it doesn't accept months as an argument, so my next working example is this:</p> <pre><code>from datetime import datetime current_date = datetime.now() months = [] for month_adjust in range(2, -3, -1): # Order by new to old. # If our months are out of bounds we need to change year. if current_date.month + month_adjust &lt;= 0: year = current_date.year - 1 elif current_date.month + month_adjust &gt; 12: year = current_date.year + 1 else: year = current_date.year # Keep the months in bounds. month = (current_date.month + month_adjust) % 12 if month == 0: month = 12 months.append(current_date.replace(year, month=month, day=1)) </code></pre> <p>Is there a cleaner way?</p>
[]
{ "AcceptedAnswerId": "20217", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T22:31:19.160", "Id": "20216", "Score": "1", "Tags": [ "python" ], "Title": "Is there a cleaner way of building a list of the previous, next months than this?" }
20216
accepted_answer
[ { "body": "<p>Based on <a href=\"https://stackoverflow.com/questions/546321/how-do-i-calculate-the-date-six-months-from-the-current-date-using-the-datetime\">this answer</a>, I would do something like :</p>\n\n<pre><code>from datetime import date\nfrom dateutil.relativedelta import relativedelta\ntoday = date.today()\nmonths = [today + relativedelta(months = +i) for i in range(2,-3,-1)]\n</code></pre>\n\n<p>It's always better not to have to play with the dates manually as so many things can go wrong.</p>\n\n<p>(I don't have access to a machine with relativedelta here so it's not tested but I'm pretty confident it should work)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T23:35:41.697", "Id": "32326", "Score": "0", "body": "That is wonderful, thanks! BTW you can drop the `+` in `+i`. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T23:41:46.643", "Id": "32327", "Score": "0", "body": "Also you don't need the `.month` in the list compression as I need the date object." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T23:33:25.933", "Id": "20217", "ParentId": "20216", "Score": "4" } } ]
<p>I wrote code that queries a data structure that contains various triples - 3-item tuples in the form subject-predicate-object. I wrote this code based on an exercise from <em><a href="http://shop.oreilly.com/product/9780596153823.do" rel="nofollow noreferrer">Programming the Semantic Web</a></em> textbook.</p> <pre><code>def query(clauses): bindings = None for clause in clauses: bpos = {} qc = [] for pos, x in enumerate(clause): if x.startswith('?'): qc.append(None) bpos[x] = pos else: qc.append(x) rows = list(triples(tuple(qc))) if bindings == None: # 1st pass bindings = [{var: row[pos] for var, pos in bpos.items()} for row in rows] else: # &gt;2 pass, eliminate wrong bindings for binding in bindings: for row in rows: for var, pos in bpos.items(): if var in binding: if binding[var] != row[pos]: bindings.remove(binding) continue else: binding[var] = row[pos] return bindings </code></pre> <p>The function invocation looks like:</p> <pre><code>bg.query([('?person','lives','Chiapas'), ('?person','advocates','Zapatism')]) </code></pre> <p>The function <code>triples</code> inside it accepts 3-tuples and returns list of 3-tuples. It can be found <a href="https://codereview.stackexchange.com/q/19470/12332">here</a>.</p> <p>The function <code>query</code> loops over each clause, tracks variables (strings that start with '?'), replaces them with None, invokes <code>triples</code>, receives rows, tries to fit values to existing bindings.</p> <p>How can I simplify this code? How can I make it more functional-style, without nested <code>for</code>-loops, <code>continue</code> keyword and so on?</p>
[]
{ "AcceptedAnswerId": "20295", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T16:48:24.977", "Id": "20278", "Score": "3", "Tags": [ "python", "functional-programming" ], "Title": "Querying a data structure that contains various triples" }
20278
accepted_answer
[ { "body": "<ol>\n<li>Your code would be helped by splitting parts of it out into functions.</li>\n<li>Your <code>continue</code> statement does nothing</li>\n<li>Rather then having a special case for the first time through, initialize <code>bindings</code> to <code>[{}]</code> for the same effect. </li>\n</ol>\n\n<p>My version:</p>\n\n<pre><code>def clause_to_query(clause):\n return tuple(None if term.startswith('?') else term for term in clause)\n\ndef compatible_bindings(clause, triples):\n for triple in triples:\n yield { clause_term : fact_term\n for clause_term, fact_term in zip(clause, row) if clause_term.startswith('?')\n }\n\ndef merge_bindings(left, right):\n shared_keys = set(left.keys()).intersection(right.keys)\n\n if all(left[key] == right[key] for key in shared_keys):\n bindings = left.copy()\n bindings.update(right)\n return bindings\n else:\n return None # indicates that a binding cannot be merged\n\n\ndef merge_binding_lists(bindings_left, bindings_right):\n new_bindings = []\n for left, right in itertools.product(bindings_left, bindings_right):\n merged_binding = merge_bindings(left, right)\n if merged_binding is not None:\n new_bindings.append( merged_binding )\n\n return new_bindings\n\n\ndef query(clauses):\n bindings = [{}]\n for clause in clauses:\n query = clause_to_query(clause)\n new_bindings = compatible_bindings(clause, triples(query))\n bindings = merge_binding_lists(bindings, new_bindings)\n\n return bindings\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T20:02:00.293", "Id": "20295", "ParentId": "20278", "Score": "4" } } ]
<p>I have a system that needs to be able to reboot a different piece of hardware partway through a script that programs it. It used to wait for me to come and reboot the hardware halfway through, but I've since automated that. I use <a href="http://code.google.com/p/usbnetpower8800/source/browse/trunk/usbnetpower8800.py" rel="nofollow">this</a> python script to control a USB Net Power 8800. </p> <p>I have two setups to show you: First is a system that I'm sure is secure, but is pretty annoying to maintain; I'm sure the second is insecure.</p> <h2>First:</h2> <h3>/usr/bin/power (not set-uid)</h3> <pre><code>#!/bin/sh if [ -e /opt/usbnetpower/_powerwrapper_$1 ] ; then /opt/usbnetpower/_powerwrapper_$1 else /opt/usbnetpower/_powerwrapper_ fi </code></pre> <h3>/opt/usbnetpower/_powerwrapper_reboot.c (The source code to one of six almost identical set-uid programs)</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; int main() { setuid( 0 ); system( "/usr/bin/python /opt/usbnetpower/usbnetpower8800.py reboot" ); return 0; } </code></pre> <p>The reason why there are six is that I didn't trust myself to write correct sanitization code in C that wasn't vulnerable to buffer overflows and the like. </p> <h3>/opt/usbnetpower/usbnetpower8800.py (not set-uid)</h3> <p>Essentially <a href="http://code.google.com/p/usbnetpower8800/source/browse/trunk/usbnetpower8800.py" rel="nofollow">this</a>, but modified to add a <code>reboot</code> command.</p> <p>This setup is what I am currently using.</p> <h2>Second:</h2> <h3>/opt/usbnetpower/usbnetpower8800.py (set-uid)</h3> <p>Much simpler, but I'm concerned that a vulnerability like this would apply. Also, suid python programs appear to be disabled on my system. (CentOS 6)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T22:37:27.413", "Id": "41046", "Score": "1", "body": "Personally I gradually abandon all set-uid things in my system. I primarily use daemons listening UNIX sockets which nonprivileged programs can connect to and ask commands. That way you control what exactly is being used (instead of just all user environment by default). I've developed [a program](https://vi-server.org/vi/dive) to start other programs over UNIX sockets in controlled way." } ]
{ "AcceptedAnswerId": "20307", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T23:16:59.930", "Id": "20304", "Score": "2", "Tags": [ "python", "c", "security", "linux" ], "Title": "Are these set-uid scripts/binaries secure?" }
20304
accepted_answer
[ { "body": "<p>Both of your programs are insecure. The problem is that I can set <code>PYTHONPATH</code> to anything I like before executing the program. I can set it to something so that it loads my own <code>usb</code> module which can execute whatever code I like. At that point, I'm executing code as the root user and can do whatever I please. That's why set-uid doesn't work on scripts, and your binary C program wrapper doesn't change that at all.</p>\n\n<p>For more information see: <a href=\"https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts\">https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts</a></p>\n\n<p>In your case, what you should be doing is changing the permissions so that your user has access to the USB device you are supposed to be controlling. That way you don't need to run the script as another user. That's what this portion of the script you are using is referring to:</p>\n\n<pre><code># If you have a permission error using the script and udev is used on your\n# system, it can be used to apply the correct permissions. Example:\n# $ cat /etc/udev/rules.d/51-usbpower.rules\n# SUBSYSTEM==\"usb\", ATTR{idVendor}==\"067b\", MODE=\"0666\", GROUP=\"plugdev\"\n</code></pre>\n\n<p>Discussion of how to adjust your system to give you permission to access the USB device is out of scope for this site. I'm also not really an expert on that. So you may need to ask elsewhere for that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T00:48:52.037", "Id": "38010", "Score": "0", "body": "`In your case, what you should be doing is changing the permissions so that your user has access to the USB device you are supposed to be controlling. ` This is what I ended up doing; [I open-sourced my changes](https://github.com/nickodell/usbnetpower)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T00:35:28.513", "Id": "20307", "ParentId": "20304", "Score": "3" } } ]
<p>This is a script to access the Stack Exchange API for the genealogy site and create a list of user dictionaries. It contains a snippet at end to validate. The data obtained is stored in YAML format in a file for use by other programs to analyze the data.</p> <pre><code>''' This is a script to access the stackexchange api for the genealogy site and create a list of user dictionaries ''' # use requests module # - see http://docs.python-requests.org/en/latest/user/install/#install import requests # use YAML to store output for use by other programs # see http://pyyaml.org/wiki/PyYAML import yaml OUTFILENAME = "users.yaml" # use se api and access genealogy site # see https://api.stackexchange.com/docs/users for api info URL ='https://api.stackexchange.com/2.1/users' url_params = { 'site' : 'genealogy', 'pagesize' : 100, 'order' : 'desc', 'sort' : 'reputation', } page = 1 not_done = True user_list = [] # replies are paginated so loop thru until none left while not_done: url_params['page'] = page # get next page of users api_response = requests.get(URL,params=url_params) json_data = api_response.json() # pull the list of users out of the json answer user_list.extend( json_data['items'] ) # show progress each time thru loop print api_response.url #note only so many queries allowed per day print '\tquota remaining: %s' % json_data['quota_remaining'] print "\t%s users after page %s" % (len(user_list),page) # prepare for next iteration if needed page += 1 not_done = json_data['has_more'] # output list of users to a file in yaml, a format easily readable by humans and parsed # note safe_dump is used for security reasons # since dump allows executable python code # Sidebenefit of safe_dump is cleaner text outFile = open(OUTFILENAME,"w") yaml.safe_dump(user_list, outFile) outFile.close() # validate it wrote correctly # note this shows example of how to read infile = open(OUTFILENAME) readList = yaml.safe_load(infile) infile.close() print 'wrote list of %d users as yaml file %s' % (len(readList),OUTFILENAME) </code></pre> <p>I wrote this code because I wanted the data it gets from the genealogy site but also:</p> <ul> <li>to learn APIs in general</li> <li>to learn the Stack Exchange API</li> <li>to get back into programming which I hadn't done much lately</li> <li>I thought I'd try YAML</li> </ul> <p>Since it's such a simple script I didn't bother with objects, but I would be interested in how it could be remade in the functional programming paradigm which I'm not as familiar with.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T12:43:43.470", "Id": "20323", "Score": "0", "Tags": [ "python", "stackexchange" ], "Title": "Script to access genealogy API for list of users and attributes" }
20323
max_votes
[ { "body": "<pre><code>'''\nThis is a script to access the stackexchange api\n for the genealogy site \n and create a list of user dictionaries\n'''\n\n# use requests module - see http://docs.python-requests.org/en/latest/user/install/#install\nimport requests\n\n# use pretty print for output\n</code></pre>\n\n<p>That's a pretty useless comment. It doesn't really tell me anything I didn't already know from the import</p>\n\n<pre><code>import pprint\n\n\n\n# save output in file in format compatable with eval\n# I didn't use json or yaml since my intent is to continue on using \n# the parsed output so saves a parse step\n</code></pre>\n\n<p><code>eval</code> also has a parse step. So you aren't saving anything by avoiding json.</p>\n\n<pre><code>pytFilename = \"users.pyt\"\n</code></pre>\n\n<p>python convention is for constants to be in ALL_CAPS</p>\n\n<pre><code># use se api and access genealogy site\n# see https://api.stackexchange.com/docs/users for api info\nurl='https://api.stackexchange.com/2.1/users'\nsite = 'genealogy'\n\nurlParams = {}\nurlParams['site'] = site\nurlParams['pagesize'] = 100\nurlParams['order'] = 'desc'\nurlParams['sort'] = 'reputation'\n</code></pre>\n\n<p>Why not put all these parameters into a single dict literal?</p>\n\n<pre><code>page = 1\nnotDone = True\nuserList = []\n</code></pre>\n\n<p>Python convention is for local variables to be mixed_case_with_underscores.</p>\n\n<pre><code># replies are paginated so loop thru until none left\nwhile notDone:\n urlParams['page'] = page\n # get next page of users\n r = requests.get(url,params=urlParams)\n</code></pre>\n\n<p>avoid single letter variable names. It makes it harder to figure out what you are doing. </p>\n\n<pre><code> # pull the list of users out of the json answer\n userList += r.json()['items']\n</code></pre>\n\n<p>I'd use <code>userList.extend( r.json()['items']). Also given the number of times you access the json, I'd have a</code>json = r.json()` line and access the json data through that.</p>\n\n<pre><code> # show progress each time thru loop, note only so many queries allowed per day\n print r.url\n print '\\tquota remaining: %s' % r.json()['quota_remaining'] \n print \"\\t%s users after page %s\" % (len(userList),page)\n\n # prepare for next iteration if needed\n page += 1\n notDone = r.json()['has_more']\n</code></pre>\n\n<p>I'd do: </p>\n\n<pre><code>json = {'has_more' : True}\nwhile json['has_more']:\n ...\n json = r.json()\n ...\n</code></pre>\n\n<p>As I think it's easier to follow then a boolean flag. </p>\n\n<pre><code># output list of users to a file in a format readable by eval\nopen(pytFilename,\"w\").write( pprint.pformat(userList) )\n</code></pre>\n\n<p>This isn't recommended practice. In CPython this will close the file, but it won't if you are using one of the other pythons. Instead, it's recommend to do:</p>\n\n<pre><code>with open(pytFilename, 'w') as output:\n output.write( pprint.pformat(userList) )\n</code></pre>\n\n<p>And that will close the file in all implementations of python.</p>\n\n<pre><code># validate it wrote correctly \n# note this shoasw example of how to read \nreadList = eval( open(pytFilename,\"r\").read() )\n\n\nprint 'wrote %s as python evaluatable list of users' % pytFilename\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:55:37.477", "Id": "20335", "ParentId": "20323", "Score": "2" } } ]
<p>I frequently run a script similar to the one below to analyze an arbitrary number of files in parallel on a computer with 8 cores. </p> <p>I use Popen to control each thread, but sometimes run into problems when there is much stdout or stderr, as the buffer fills up. I solve this by frequently reading from the streams. I also print the streams from one of the threads to help me follow the progress of the analysis.</p> <p>I'm curious on alternative methods to thread using Python, and general comments about the implementation, which, as always, has room for improvement. Thanks!</p> <pre><code>import os, sys import time import subprocess def parallelize(analysis_program_path, filenames, N_CORES): ''' Function that parallelizes an analysis on a list of files on N_CORES number of cores ''' running = [] sys.stderr.write('Starting analyses\n') while filenames or running: while filenames and len(running) &lt; N_CORES: # Submit new analysis filename = filenames.pop(0) cmd = '%s %s' % (analysis_program_path, filename) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sys.stderr.write('Analyzing %s\n' % filename) running.append((cmd, p)) i = 0 while i &lt; len(running): (cmd, p) = running[i] returncode = p.poll() st_out = p.stdout.read() st_err = p.stderr.read() # Read the buffer! Otherwise it fills up and blocks the script if i == 0: # Just print one of the processes sys.stderr.write(st_err) if returncode is not None: st_out = p.stdout.read() st_err = p.stderr.read() sys.stderr.write(st_err) running.remove((cmd, p)) else: i += 1 time.sleep(1) sys.stderr.write('Completely done!\n') </code></pre>
[]
{ "AcceptedAnswerId": "20514", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T12:47:40.057", "Id": "20416", "Score": "4", "Tags": [ "python", "multithreading" ], "Title": "Python parallelization using Popen" }
20416
accepted_answer
[ { "body": "<p>Python has what you want built into the standard library: see the <a href=\"http://docs.python.org/2/library/multiprocessing.html\" rel=\"noreferrer\"><code>multiprocessing</code> module</a>, and in particular the <a href=\"http://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map\" rel=\"noreferrer\"><code>map</code> method</a> of the <a href=\"http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool\" rel=\"noreferrer\"><code>Pool</code> class</a>.</p>\n\n<p>So you can implement what you want in one line, perhaps like this:</p>\n\n<pre><code>from multiprocessing import Pool\n\ndef parallelize(analysis, filenames, processes):\n '''\n Call `analysis` for each file in the sequence `filenames`, using\n up to `processes` parallel processes. Wait for them all to complete\n and then return a list of results.\n '''\n return Pool(processes).map(analysis, filenames, chunksize = 1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:23:54.503", "Id": "20514", "ParentId": "20416", "Score": "5" } } ]
<p>This morning I was trying to find a good way of using <code>os.path</code> to load the content of a text file into memory, which exists in the root directory of my current project.</p> <p><a href="http://halfcooked.com/blog/2012/06/01/python-path-relative-to-application-root/" rel="noreferrer">This approach</a> strikes me as a bit hackneyed, but after some thought it was exactly what I was about to do, except with <code>os.path.normpath(os.path.join(__file__, '..', '..'))</code> </p> <p>These relative operations on the path to navigate to a <em>static</em> root directory are brittle.</p> <p>Now, if my project layout changes, these associations to the (former) root directory change with it. I wish I could assign the path to find a target, or a destination, instead of following a sequence of navigation operations.</p> <p>I was thinking of making a special <code>__root__.py</code> file. Does this look familiar to anyone, or know of a better implementation?</p> <pre><code>my_project | | __init__.py | README.md | license.txt | __root__.py | special_resource.txt | ./module |-- load.py </code></pre> <p>Here is how it is implemented:</p> <pre><code>"""__root__.py""" import os def path(): return os.path.dirname(__file__) </code></pre> <p>And here is how it could be used:</p> <pre><code>"""load.py""" import __root__ def resource(): return open(os.path.join(__root__.path(), 'special_resource.txt')) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:41:47.363", "Id": "33095", "Score": "0", "body": "You should choose an answer or provide more information." } ]
{ "AcceptedAnswerId": "20449", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T15:09:55.653", "Id": "20428", "Score": "6", "Tags": [ "python" ], "Title": "Accessing the contents of a project's root directory in Python" }
20428
accepted_answer
[ { "body": "<p>I never heard of <code>__root__.py</code> and don't think that is a good idea.</p>\n\n<p>Instead create a <code>files.py</code> in a <code>utils</code> module:</p>\n\n<pre><code>MAIN_DIRECTORY = dirname(dirname(__file__))\ndef get_full_path(*path):\n return join(MAIN_DIRECTORY, *path)\n</code></pre>\n\n<p>You can then import this function from your <code>main.py</code>:</p>\n\n<pre><code>from utils.files import get_full_path\n\npath_to_map = get_full_path('res', 'map.png')\n</code></pre>\n\n<p>So my project directory tree looks like this:</p>\n\n<pre><code>project_main_folder/\n utils/\n __init__.py (empty)\n files.py\n main.py\n</code></pre>\n\n<p>When you import a module the Python interpreter searches if there's a built-in module with that name (that's why your module name should be different or you should use <a href=\"http://docs.python.org/2/tutorial/modules.html#intra-package-references\" rel=\"nofollow\">relative imports</a>). If it hasn't found a module with that name it will (among others in <code>sys.path</code>) search in the directory containing your script. You can find further information in the <a href=\"http://docs.python.org/2/tutorial/modules.html#the-module-search-path\" rel=\"nofollow\">documentation</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T03:17:33.217", "Id": "32884", "Score": "0", "body": "But how do you import `main` without knowing where the main directory is already?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T16:28:32.857", "Id": "32919", "Score": "0", "body": "I modified my answer to include the import line and also put the function in the module `utils.files`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T01:23:28.473", "Id": "32966", "Score": "0", "body": "My question remains the same: how do you import `utils.files` without knowing where `utils` is?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T15:54:35.510", "Id": "32994", "Score": "0", "body": "When you put the code that imports `utils.files` in `main.py` Python will automatically figure it out. I added further information to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T20:08:40.777", "Id": "33022", "Score": "0", "body": "Oh. What if I'm in `dir1/module1.py` and I want to `import dir2.module2`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T20:52:36.303", "Id": "33025", "Score": "0", "body": "Note that `dir1` and `dir2` need to contain an `__init__.py` to be considered as a module. Then you could probably (not tested) use relative imports: `from ..dir2.module2 import get_bla`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T21:26:20.993", "Id": "20449", "ParentId": "20428", "Score": "4" } } ]
<p>I'm tasked with getting emails from a .csv file and using them to submit a form. I am using the csv and mechanize Python libraries to achieve this.</p> <pre><code>import re import mechanize import csv def auto_email(email): br = mechanize.Browser() br.open("URL") br.select_form(name="vote_session") br['email_add'] = '%s' % (email) #email address br.submit() def csv_emails(): ifile = open('emails.csv', "rb") reader = csv.reader(ifile) rownum = 1 for row in reader: auto_email(row[0]) print "%d - %s processed" %(rownum, row[0]) rownum += 1 print 'List processed. You are done.' ifile.close() print csv_emails() </code></pre> <p>The code works, but I am very much a beginner in Python.</p> <p>I was wondering whether I have any inefficiencies that you can help me get rid of and optimize the script?</p>
[]
{ "AcceptedAnswerId": "20549", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T16:16:16.327", "Id": "20548", "Score": "3", "Tags": [ "python", "beginner", "python-2.x", "csv", "email" ], "Title": "CSV email script efficiency" }
20548
accepted_answer
[ { "body": "<p>I would suggest to use</p>\n\n<pre><code>with open('emails.csv', \"rb\") as ifile\n</code></pre>\n\n<p>see here for details: <a href=\"http://www.python.org/dev/peps/pep-0343/\">http://www.python.org/dev/peps/pep-0343/</a>\nin this case you don't need to do <code>ifile.close</code> at the end</p>\n\n<p>instead of incrementing rownum by yourself, you can use</p>\n\n<pre><code>for row, rownum in enumerate(reader):\n</code></pre>\n\n<p>I don't see the reason to do this</p>\n\n<pre><code>br['email_add'] = '%s' % (email) #email address\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>br['email_add'] = email\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:03:04.940", "Id": "32921", "Score": "0", "body": "`email` comes from a row returned by `csv.reader` so it's always a string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:04:55.650", "Id": "32922", "Score": "0", "body": "so in this case `br['email_add'] = email` is enough. I edited my answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:01:27.540", "Id": "20549", "ParentId": "20548", "Score": "6" } } ]
<p>I'm tasked with getting emails from a .csv file and using them to submit a form. I am using the csv and mechanize Python libraries to achieve this.</p> <pre><code>import re import mechanize import csv def auto_email(email): br = mechanize.Browser() br.open("URL") br.select_form(name="vote_session") br['email_add'] = '%s' % (email) #email address br.submit() def csv_emails(): ifile = open('emails.csv', "rb") reader = csv.reader(ifile) rownum = 1 for row in reader: auto_email(row[0]) print "%d - %s processed" %(rownum, row[0]) rownum += 1 print 'List processed. You are done.' ifile.close() print csv_emails() </code></pre> <p>The code works, but I am very much a beginner in Python.</p> <p>I was wondering whether I have any inefficiencies that you can help me get rid of and optimize the script?</p>
[]
{ "AcceptedAnswerId": "20549", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T16:16:16.327", "Id": "20548", "Score": "3", "Tags": [ "python", "beginner", "python-2.x", "csv", "email" ], "Title": "CSV email script efficiency" }
20548
accepted_answer
[ { "body": "<p>I would suggest to use</p>\n\n<pre><code>with open('emails.csv', \"rb\") as ifile\n</code></pre>\n\n<p>see here for details: <a href=\"http://www.python.org/dev/peps/pep-0343/\">http://www.python.org/dev/peps/pep-0343/</a>\nin this case you don't need to do <code>ifile.close</code> at the end</p>\n\n<p>instead of incrementing rownum by yourself, you can use</p>\n\n<pre><code>for row, rownum in enumerate(reader):\n</code></pre>\n\n<p>I don't see the reason to do this</p>\n\n<pre><code>br['email_add'] = '%s' % (email) #email address\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>br['email_add'] = email\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:03:04.940", "Id": "32921", "Score": "0", "body": "`email` comes from a row returned by `csv.reader` so it's always a string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:04:55.650", "Id": "32922", "Score": "0", "body": "so in this case `br['email_add'] = email` is enough. I edited my answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:01:27.540", "Id": "20549", "ParentId": "20548", "Score": "6" } } ]
<p>I have this code in a class that gets a string, parses it, and makes some adjustments to get a valid <code>datetime</code> format from the string.</p> <p>An input string for this function could be = "A0X031716506774"</p> <pre><code>import datetime def _eventdatetime(self, string): base_date = datetime.datetime.strptime("1980-1-6 0:0", "%Y-%m-%d %H:%M") weeks = datetime.timedelta(weeks = int(string[5:9])) days = datetime.timedelta(days = int(string[9])) seconds = datetime.timedelta(seconds = int(string[10:15])) stamp = base_date + weeks + days + seconds adjustUTC = datetime.timedelta(hours = 3) stamp = stamp - adjustUTC return str(stamp) </code></pre> <p>Total time: 0.0483931 s</p> <p>How can I improve the performance for this? The third line seems to be the slowest.</p>
[]
{ "AcceptedAnswerId": "20595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T17:45:56.693", "Id": "20593", "Score": "1", "Tags": [ "python", "performance", "datetime", "formatting" ], "Title": "Getting a valid datetime format from a string" }
20593
accepted_answer
[ { "body": "<pre><code>import datetime\ndef _eventdatetime(self, string):\n base_date = datetime.datetime.strptime(\"1980-1-6 0:0\", \"%Y-%m-%d %H:%M\")\n</code></pre>\n\n<p>Why are you specifying the date as a string only to parse it? Just do: <code>base_date = datetime.datetime(1980,1,6,0,0)</code>. You should also make it a global constant so as not to recreate it all the time.</p>\n\n<pre><code> weeks = datetime.timedelta(weeks = int(string[5:9]))\n days = datetime.timedelta(days = int(string[9]))\n seconds = datetime.timedelta(seconds = int(string[10:15]))\n</code></pre>\n\n<p>There is no need to create several timedelta objects, you can do <code>datetime.timedelta(weeks = ..., days = ..., seconds = ...)</code></p>\n\n<pre><code> stamp = base_date + weeks + days + seconds\n\n adjustUTC = datetime.timedelta(hours = 3) \n stamp = stamp - adjustUTC\n</code></pre>\n\n<p>I'd use <code>stamp -= datetime.timedelta(hours = 3) # adjust for UTC</code></p>\n\n<pre><code> return str(stamp)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T19:10:25.343", "Id": "33015", "Score": "0", "body": "Thanks for your time Winston! Your advise is very useful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:22:42.437", "Id": "20595", "ParentId": "20593", "Score": "3" } } ]
<p>I'm trying to improve some code in order to get a better perfomance, I have to do a lot of pattern matching for little tags on medium large strings, for example:</p> <pre><code>import re STR = "0001x10x11716506872xdc23654&amp;xd01371600031832xx10xID=000110011001010\n" def getID(string): result = re.search('.*ID=(\d+)', string) if result: print result.group(1) else: print "No Results" </code></pre> <p>Taking in mind the perfomance I rewrite it:</p> <pre><code>def getID2(string): result = string.find('ID=') if result: result += 3 print string[result:result+15] else: print 'No Results' </code></pre> <p>Are there a better way to improve these approaches? Any comments are welcome...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:17:23.493", "Id": "33093", "Score": "5", "body": "Is this the actual code that you are trying to improve the performance of? As it stands, `print` will be more expensive then anything else and relative to that no other change will really matter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:54:33.223", "Id": "33096", "Score": "0", "body": "This a getter from a class that get the string at the constructor" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T16:44:32.320", "Id": "33104", "Score": "1", "body": "If its a getter you should be referencing `self` and `return`ing the answer. If you want help you need to show your actual code! As it stands this is totally useless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-03T08:41:25.473", "Id": "39899", "Score": "0", "body": "Also, what performance improvement do you need? What are possible use cases? There's not much more you can do since find(\"ID=\") is O(n), n being the length of the string. You can get performance only by not traversing the whole string, which is not possible unless we know more about your date (ID always at the end?)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T13:42:52.693", "Id": "20632", "Score": "1", "Tags": [ "python", "regex" ], "Title": "Python pattern searching using re standard lib, str.find()" }
20632
max_votes
[ { "body": "<p>If you name your function <code>getSomething()</code>, I expect it to return a value with no side effects. I do not expect it to print anything. Therefore, your function should either return the found string, or <code>None</code> if it is not not found.</p>\n\n<p>Your original and revised code look for different things: the former wants as many digits as possible, and the latter wants 15 characters. Combining the two requirements, I take it that you want 15 digits.</p>\n\n<p><code>re.search()</code> lets the regular expression match any part of the string, rather than the entire string. Therefore, you can omit <code>.*</code> from the beginning of your regular expression.</p>\n\n<p>Here's how I would write it:</p>\n\n<pre><code>import re\nSTR = \"0001x10x11716506872xdc23654&amp;xd01371600031832xx10xID=000110011001010\\n\"\n\ndef getID(string):\n result = re.search('ID=(\\d{15})', string)\n return result and result.group(1)\n\nprint getID(STR) or \"No Results\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:43:02.430", "Id": "65214", "Score": "0", "body": "Out of interest, even though I prefer the look of your suggestion, do you think it will perform better than the `find(...)` option? My instinct is that RE's will be slower in general and the `\\d{15}` will do character-checking for digits which the find solution does not do..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:28:51.010", "Id": "38985", "ParentId": "20632", "Score": "2" } } ]
<p>I'm trying to improve some code in order to get a better perfomance, I have to do a lot of pattern matching for little tags on medium large strings, for example:</p> <pre><code>import re STR = "0001x10x11716506872xdc23654&amp;xd01371600031832xx10xID=000110011001010\n" def getID(string): result = re.search('.*ID=(\d+)', string) if result: print result.group(1) else: print "No Results" </code></pre> <p>Taking in mind the perfomance I rewrite it:</p> <pre><code>def getID2(string): result = string.find('ID=') if result: result += 3 print string[result:result+15] else: print 'No Results' </code></pre> <p>Are there a better way to improve these approaches? Any comments are welcome...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:17:23.493", "Id": "33093", "Score": "5", "body": "Is this the actual code that you are trying to improve the performance of? As it stands, `print` will be more expensive then anything else and relative to that no other change will really matter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:54:33.223", "Id": "33096", "Score": "0", "body": "This a getter from a class that get the string at the constructor" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T16:44:32.320", "Id": "33104", "Score": "1", "body": "If its a getter you should be referencing `self` and `return`ing the answer. If you want help you need to show your actual code! As it stands this is totally useless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-03T08:41:25.473", "Id": "39899", "Score": "0", "body": "Also, what performance improvement do you need? What are possible use cases? There's not much more you can do since find(\"ID=\") is O(n), n being the length of the string. You can get performance only by not traversing the whole string, which is not possible unless we know more about your date (ID always at the end?)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T13:42:52.693", "Id": "20632", "Score": "1", "Tags": [ "python", "regex" ], "Title": "Python pattern searching using re standard lib, str.find()" }
20632
max_votes
[ { "body": "<p>If you name your function <code>getSomething()</code>, I expect it to return a value with no side effects. I do not expect it to print anything. Therefore, your function should either return the found string, or <code>None</code> if it is not not found.</p>\n\n<p>Your original and revised code look for different things: the former wants as many digits as possible, and the latter wants 15 characters. Combining the two requirements, I take it that you want 15 digits.</p>\n\n<p><code>re.search()</code> lets the regular expression match any part of the string, rather than the entire string. Therefore, you can omit <code>.*</code> from the beginning of your regular expression.</p>\n\n<p>Here's how I would write it:</p>\n\n<pre><code>import re\nSTR = \"0001x10x11716506872xdc23654&amp;xd01371600031832xx10xID=000110011001010\\n\"\n\ndef getID(string):\n result = re.search('ID=(\\d{15})', string)\n return result and result.group(1)\n\nprint getID(STR) or \"No Results\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:43:02.430", "Id": "65214", "Score": "0", "body": "Out of interest, even though I prefer the look of your suggestion, do you think it will perform better than the `find(...)` option? My instinct is that RE's will be slower in general and the `\\d{15}` will do character-checking for digits which the find solution does not do..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:28:51.010", "Id": "38985", "ParentId": "20632", "Score": "2" } } ]
<p>My son (9) is learning Python and wrote this temperature conversion program. He can see that there is a lot of repetition in it and would like to get feedback on ways to make it shorter.</p> <pre><code>def get_temperature(): print "What is your temperature?" while True: temperature = raw_input() try: return float(temperature) except ValueError: print "Not a valid temperature. Could you please do this again?" print "This program tells you the different temperatures." temperature = get_temperature() print "This is what it would be if it was Fahrenheit:" Celsius = (temperature - 32)/1.8 print Celsius, "degrees Celsius" Kelvin = Celsius + 273.15 print Kelvin, "Kelvin" print "This is what it would be if it was Celsius." Fahrenheit = temperature * 9 / 5 + 32 print Fahrenheit, "degrees Fahrenheit" Kelvin = temperature + 273.15 print Kelvin, "Kelvin" print "This is what it would be if it was Kelvin" Celsius = temperature - 273.15 print Celsius, "degrees Celsius" Fahrenheit = Celsius * 9 / 5 + 32 print Fahrenheit, "degrees Fahrenheit" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T12:56:32.623", "Id": "33194", "Score": "0", "body": "Out of curiosity: why didn't your son ask here himself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T12:59:52.990", "Id": "33195", "Score": "5", "body": "[`Subscriber certifies to Stack Exchange that if Subscriber is an individual (i.e., not a corporate entity), Subscriber is at least 13 years of age`](http://stackexchange.com/legal#1AccesstotheServices)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T13:12:23.787", "Id": "33197", "Score": "0", "body": "@vikingosegundo I did not know that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T13:20:42.360", "Id": "33198", "Score": "2", "body": "@svick I think it is quite common to exclude kids younger than 13. So maybe this 9-yo is very clever and poses as his father :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T19:04:41.963", "Id": "33208", "Score": "0", "body": "Although the answers already given below are useful, I would say the first thing is to consider whether he really wants to print all possible conversions, or instead allow the user to specify a unit (which as it happens would avoid the need for most of the repetition). I.e. think about the aim of the programme before implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-20T02:09:36.030", "Id": "33224", "Score": "3", "body": "I just realized the delightful detail of not adding 'degrees' in front of 'Kelvin'! I've had professors in college doing it wrong all the time..." } ]
{ "AcceptedAnswerId": "20732", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T12:17:27.710", "Id": "20708", "Score": "3", "Tags": [ "python", "converting" ], "Title": "Temperature conversion program with a lot of repetition" }
20708
accepted_answer
[ { "body": "<p>The easiest way to remove repetition here is with nested <code>for</code> loops, going through all the combinations of units. In the code below I also use the fact that you can convert between any two scales in the following way:</p>\n\n<ol>\n<li>subtract something then divide by something to get back to Celsius, then</li>\n<li>multiply by something then add something to get to the desired unit</li>\n</ol>\n\n<p>The \"something\"s can be stored in a single tuple (list of values), making the conversions simpler.</p>\n\n<pre><code>scales = ('Celsius', 'degrees ', 1, 0), ('Farenheit', 'degrees ', 1.8, 32), ('Kelvin', '', 1, 273.15)\nvalue = get_temperature()\nfor from_unit, _, slope1, intercept1 in scales:\n print \"This is what it would be if it was\", from_unit\n celsius = (value - intercept1) / slope1\n for to_unit, prefix, slope2, intercept2 in scales:\n if to_unit != from_unit:\n print '{0} {1}{2}'.format(intercept2 + slope2 * celsius, degrees, to_unit)\n</code></pre>\n\n<p>Dividing code into functions is of course a good idea in general, but not that useful in this case. If he's interested in performing other operations on temperatures it might be interesting to go a step further and make a simple class like the following.</p>\n\n<pre><code>scales = {\n 'Celsius': ('degrees ', 1, 0),\n 'Farenheit': ('degrees ', 1.8, 32),\n 'Kelvin': ('', 1, 273.15)\n }\nclass Temperature: \n def __init__(self, value, unit = 'Celsius'):\n self.original_unit = unit\n _, slope, intercept = scales[unit]\n self.celsius = (value - intercept) / slope\n def to_unit(self, unit):\n _, slope, intercept = scales[unit]\n return slope * self.celsius + intercept\n def print_hypothetical(self):\n print \"This is what it would be if it was\", self.original_unit\n for unit, (prefix, _, _) in scales.iteritems():\n if unit != self.original_unit:\n print \"{0} {1}{2}\".format(self.to_unit(unit), prefix, unit)\nvalue = get_temperature()\nfor unit in scales:\n m = Temperature(value, unit)\n m.print_hypothetical()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T22:18:06.727", "Id": "20732", "ParentId": "20708", "Score": "4" } } ]
<p>This is my try at <a href="http://en.wikipedia.org/wiki/Proxy_pattern" rel="nofollow">the proxy pattern</a>.</p> <p>What do you Pythoneers think of my attempt?</p> <pre><code>class Image: def __init__( self, filename ): self._filename = filename def load_image_from_disk( self ): print("loading " + self._filename ) def display_image( self ): print("display " + self._filename) class Proxy: def __init__( self, subject ): self._subject = subject self._proxystate = None class ProxyImage( Proxy ): def display_image( self ): if self._proxystate == None: self._subject.load_image_from_disk() self._proxystate = 1 print("display " + self._subject._filename ) proxy_image1 = ProxyImage ( Image("HiRes_10Mb_Photo1") ) proxy_image2 = ProxyImage ( Image("HiRes_10Mb_Photo2") ) proxy_image1.display_image() # loading necessary proxy_image1.display_image() # loading unnecessary proxy_image2.display_image() # loading necessary proxy_image2.display_image() # loading unnecessary proxy_image1.display_image() # loading unnecessary </code></pre> <p>Output:</p> <pre><code>loading HiRes_10Mb_Photo1 display HiRes_10Mb_Photo1 display HiRes_10Mb_Photo1 loading HiRes_10Mb_Photo2 display HiRes_10Mb_Photo2 display HiRes_10Mb_Photo2 display HiRes_10Mb_Photo1 </code></pre>
[]
{ "AcceptedAnswerId": "20800", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T13:08:25.817", "Id": "20798", "Score": "3", "Tags": [ "python", "design-patterns" ], "Title": "proxy pattern in Python" }
20798
accepted_answer
[ { "body": "<p>It seems like overkill to implement a class to represent the proxy pattern. <em>Design patterns are patterns, not classes.</em> What do you gain from your implementation compared to a simple approach like the one shown below?</p>\n\n<pre><code>class Image(object):\n def __init__(self, filename):\n self._filename = filename\n self._loaded = False\n\n def load(self):\n print(\"loading {}\".format(self._filename))\n self._loaded = True\n\n def display(self):\n if not self._loaded:\n self.load()\n print(\"displaying {}\".format(self._filename))\n</code></pre>\n\n<p>Some other notes on your code:</p>\n\n<ol>\n<li><p>It doesn't follow <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>. In particular, \"Avoid extraneous whitespace [...] immediately inside parentheses.\"</p></li>\n<li><p>No docstrings.</p></li>\n<li><p>It makes more sense to use <code>True</code> and <code>False</code> for a binary condition than to use <code>None</code> and <code>1</code>.</p></li>\n<li><p>It's not necessary to append the class name to all the methods. In a class called <code>Image</code>, the methods should just be called <code>load</code> and <code>display</code>, not <code>load_image</code> and <code>display_image</code>.</p></li>\n<li><p>You should use new-style classes (inheriting from <code>object</code>) to make your code portable between Python 2 and 3.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T14:08:17.773", "Id": "33356", "Score": "0", "body": "I think it can make sense to have separate `Image` and `ImageProxy` objects (though a better name might be something like `LazyImage`), because of separation of concerns. And even better (assuming the added complexity would be worth it) would be some sort of generic `LazyLoadingProxy` class, which could work with `Image`s and also other objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T14:17:05.750", "Id": "33357", "Score": "1", "body": "It's possible, but we'd only know in the context of a whole application: if there really are several different types of assets that need to be lazily loaded, then it might make sense to have a class to handle the lazy loading, but it might still be simpler to implement that class as a mixin rather than a proxy. A proxy object is usually a last resort when you don't control the code for the class you are proxying." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T13:33:10.253", "Id": "20800", "ParentId": "20798", "Score": "7" } } ]
<p>This is my try at <a href="http://en.wikipedia.org/wiki/Proxy_pattern" rel="nofollow">the proxy pattern</a>.</p> <p>What do you Pythoneers think of my attempt?</p> <pre><code>class Image: def __init__( self, filename ): self._filename = filename def load_image_from_disk( self ): print("loading " + self._filename ) def display_image( self ): print("display " + self._filename) class Proxy: def __init__( self, subject ): self._subject = subject self._proxystate = None class ProxyImage( Proxy ): def display_image( self ): if self._proxystate == None: self._subject.load_image_from_disk() self._proxystate = 1 print("display " + self._subject._filename ) proxy_image1 = ProxyImage ( Image("HiRes_10Mb_Photo1") ) proxy_image2 = ProxyImage ( Image("HiRes_10Mb_Photo2") ) proxy_image1.display_image() # loading necessary proxy_image1.display_image() # loading unnecessary proxy_image2.display_image() # loading necessary proxy_image2.display_image() # loading unnecessary proxy_image1.display_image() # loading unnecessary </code></pre> <p>Output:</p> <pre><code>loading HiRes_10Mb_Photo1 display HiRes_10Mb_Photo1 display HiRes_10Mb_Photo1 loading HiRes_10Mb_Photo2 display HiRes_10Mb_Photo2 display HiRes_10Mb_Photo2 display HiRes_10Mb_Photo1 </code></pre>
[]
{ "AcceptedAnswerId": "20800", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T13:08:25.817", "Id": "20798", "Score": "3", "Tags": [ "python", "design-patterns" ], "Title": "proxy pattern in Python" }
20798
accepted_answer
[ { "body": "<p>It seems like overkill to implement a class to represent the proxy pattern. <em>Design patterns are patterns, not classes.</em> What do you gain from your implementation compared to a simple approach like the one shown below?</p>\n\n<pre><code>class Image(object):\n def __init__(self, filename):\n self._filename = filename\n self._loaded = False\n\n def load(self):\n print(\"loading {}\".format(self._filename))\n self._loaded = True\n\n def display(self):\n if not self._loaded:\n self.load()\n print(\"displaying {}\".format(self._filename))\n</code></pre>\n\n<p>Some other notes on your code:</p>\n\n<ol>\n<li><p>It doesn't follow <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>. In particular, \"Avoid extraneous whitespace [...] immediately inside parentheses.\"</p></li>\n<li><p>No docstrings.</p></li>\n<li><p>It makes more sense to use <code>True</code> and <code>False</code> for a binary condition than to use <code>None</code> and <code>1</code>.</p></li>\n<li><p>It's not necessary to append the class name to all the methods. In a class called <code>Image</code>, the methods should just be called <code>load</code> and <code>display</code>, not <code>load_image</code> and <code>display_image</code>.</p></li>\n<li><p>You should use new-style classes (inheriting from <code>object</code>) to make your code portable between Python 2 and 3.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T14:08:17.773", "Id": "33356", "Score": "0", "body": "I think it can make sense to have separate `Image` and `ImageProxy` objects (though a better name might be something like `LazyImage`), because of separation of concerns. And even better (assuming the added complexity would be worth it) would be some sort of generic `LazyLoadingProxy` class, which could work with `Image`s and also other objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T14:17:05.750", "Id": "33357", "Score": "1", "body": "It's possible, but we'd only know in the context of a whole application: if there really are several different types of assets that need to be lazily loaded, then it might make sense to have a class to handle the lazy loading, but it might still be simpler to implement that class as a mixin rather than a proxy. A proxy object is usually a last resort when you don't control the code for the class you are proxying." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T13:33:10.253", "Id": "20800", "ParentId": "20798", "Score": "7" } } ]
<p>This is my try at <a href="http://en.wikipedia.org/wiki/Proxy_pattern" rel="nofollow">the proxy pattern</a>.</p> <p>What do you Pythoneers think of my attempt?</p> <pre><code>class Image: def __init__( self, filename ): self._filename = filename def load_image_from_disk( self ): print("loading " + self._filename ) def display_image( self ): print("display " + self._filename) class Proxy: def __init__( self, subject ): self._subject = subject self._proxystate = None class ProxyImage( Proxy ): def display_image( self ): if self._proxystate == None: self._subject.load_image_from_disk() self._proxystate = 1 print("display " + self._subject._filename ) proxy_image1 = ProxyImage ( Image("HiRes_10Mb_Photo1") ) proxy_image2 = ProxyImage ( Image("HiRes_10Mb_Photo2") ) proxy_image1.display_image() # loading necessary proxy_image1.display_image() # loading unnecessary proxy_image2.display_image() # loading necessary proxy_image2.display_image() # loading unnecessary proxy_image1.display_image() # loading unnecessary </code></pre> <p>Output:</p> <pre><code>loading HiRes_10Mb_Photo1 display HiRes_10Mb_Photo1 display HiRes_10Mb_Photo1 loading HiRes_10Mb_Photo2 display HiRes_10Mb_Photo2 display HiRes_10Mb_Photo2 display HiRes_10Mb_Photo1 </code></pre>
[]
{ "AcceptedAnswerId": "20800", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T13:08:25.817", "Id": "20798", "Score": "3", "Tags": [ "python", "design-patterns" ], "Title": "proxy pattern in Python" }
20798
accepted_answer
[ { "body": "<p>It seems like overkill to implement a class to represent the proxy pattern. <em>Design patterns are patterns, not classes.</em> What do you gain from your implementation compared to a simple approach like the one shown below?</p>\n\n<pre><code>class Image(object):\n def __init__(self, filename):\n self._filename = filename\n self._loaded = False\n\n def load(self):\n print(\"loading {}\".format(self._filename))\n self._loaded = True\n\n def display(self):\n if not self._loaded:\n self.load()\n print(\"displaying {}\".format(self._filename))\n</code></pre>\n\n<p>Some other notes on your code:</p>\n\n<ol>\n<li><p>It doesn't follow <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>. In particular, \"Avoid extraneous whitespace [...] immediately inside parentheses.\"</p></li>\n<li><p>No docstrings.</p></li>\n<li><p>It makes more sense to use <code>True</code> and <code>False</code> for a binary condition than to use <code>None</code> and <code>1</code>.</p></li>\n<li><p>It's not necessary to append the class name to all the methods. In a class called <code>Image</code>, the methods should just be called <code>load</code> and <code>display</code>, not <code>load_image</code> and <code>display_image</code>.</p></li>\n<li><p>You should use new-style classes (inheriting from <code>object</code>) to make your code portable between Python 2 and 3.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T14:08:17.773", "Id": "33356", "Score": "0", "body": "I think it can make sense to have separate `Image` and `ImageProxy` objects (though a better name might be something like `LazyImage`), because of separation of concerns. And even better (assuming the added complexity would be worth it) would be some sort of generic `LazyLoadingProxy` class, which could work with `Image`s and also other objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T14:17:05.750", "Id": "33357", "Score": "1", "body": "It's possible, but we'd only know in the context of a whole application: if there really are several different types of assets that need to be lazily loaded, then it might make sense to have a class to handle the lazy loading, but it might still be simpler to implement that class as a mixin rather than a proxy. A proxy object is usually a last resort when you don't control the code for the class you are proxying." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T13:33:10.253", "Id": "20800", "ParentId": "20798", "Score": "7" } } ]
<p>Am supposed to capture user input as an integer, convert to a binary, reverse the binary equivalent and convert it to an integer.Am getting the right output but someone says the solution is wrong. Where is the problem?</p> <pre><code>x = 0 while True: try: x = int(raw_input('input a decimal number \t')) if x in xrange(1,1000000001): y = bin(x) rev = y[2:] print("the reverse binary soln for the above is %d") %(int('0b'+rev[::-1],2)) break except ValueError: print("Please input an integer, that's not an integer") continue </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T22:28:35.517", "Id": "33596", "Score": "2", "body": "If you are asking us to find an error in your code, then I'm afraid your question if off topic on Code Review. This is site is for reviewing code that you think is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T22:55:49.733", "Id": "33597", "Score": "1", "body": "I think ist's correct since it gives the required output, I just want to know if there's something I can do to make it work better" } ]
{ "AcceptedAnswerId": "20968", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T21:48:57.497", "Id": "20965", "Score": "3", "Tags": [ "python" ], "Title": "Python Reverse the binary equivalent of input and output the integer equivalent of the reverse binary" }
20965
accepted_answer
[ { "body": "<pre><code>x = 0\n</code></pre>\n\n<p>There is no point in doing this. You just replace it anyways</p>\n\n<pre><code>while True:\n\n try:\n x = int(raw_input('input a decimal number \\t'))\n\n\n if x in xrange(1,1000000001):\n</code></pre>\n\n<p>Probably better to use <code>if 1 &lt;= x &lt;= 100000000001:</code> although I'm really not sure why you are doing this check. Also, you should probably explain to the user that you've reject the number.</p>\n\n<pre><code> y = bin(x)\n\n rev = y[2:]\n</code></pre>\n\n<p>I'd use <code>reversed = bin(x)[:1::-1]</code> rather then splitting it out across the tree lines.</p>\n\n<pre><code> print(\"the reverse binary soln for the above is %d\") %(int('0b'+rev[::-1],2)) \n</code></pre>\n\n<p>I'd convert the number before the print to seperate output from the actual math.</p>\n\n<pre><code> break\n\n except ValueError:\n print(\"Please input an integer, that's not an integer\")\n continue\n</code></pre>\n\n<p>This continue does nothing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T23:45:58.330", "Id": "20968", "ParentId": "20965", "Score": "5" } } ]
<p>I've recently discovered how cool <code>reduce()</code> could be and I want to do this:</p> <pre><code>&gt;&gt;&gt; a = [1, 1] + [0] * 11 &gt;&gt;&gt; count = 1 &gt;&gt;&gt; def fib(x,n): ... global count ... r = x + n ... if count &lt; len(a) - 1: a[count+1] = r ... count += 1 ... return r &gt;&gt;&gt; &gt;&gt;&gt; reduce(fib,a,1) 610 &gt;&gt;&gt; a [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233] </code></pre> <p>But this just looks so messy and almost defeats the purpose of the last line:</p> <pre><code>reduce(fib,a,1) </code></pre> <p>What would be a better way to use Python to make a Fibonacci number with <code>reduce()</code>?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T16:14:07.087", "Id": "33681", "Score": "2", "body": "Why do you want to use reduce?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T16:18:40.630", "Id": "33682", "Score": "1", "body": "Because it seemed cool. I want to use something like reduce, or map. Because it seems like a challenge." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T23:06:09.840", "Id": "33722", "Score": "0", "body": "@CrisStringfellow It's not really the right tool for the job. A generator would be the best choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:39:31.140", "Id": "33738", "Score": "0", "body": "@Lattyware okay but a generator is just too easy." } ]
{ "AcceptedAnswerId": "21005", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T14:29:54.510", "Id": "20986", "Score": "4", "Tags": [ "python", "fibonacci-sequence" ], "Title": "Making this reduce() Fibonacci generator better" }
20986
accepted_answer
[ { "body": "<p>A <code>reduce</code> (that's it, a fold) is not exactly the abstraction for the task (what input collection are you going to fold here?). Anyway, you can cheat a little bit and fold the indexes even if you don't really use them within the folding function. This works for Python 2.x:</p>\n\n<pre><code>def next_fib((x, y), n):\n return (y, x + y)\n\nreduce(next_fib, xrange(5), (1, 1))[0]\n#=&gt; 8\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:46:05.433", "Id": "33740", "Score": "0", "body": "That is awesome." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T21:14:06.177", "Id": "21005", "ParentId": "20986", "Score": "4" } } ]
<p>I want to perform standard additive carry on a vector. The base is a power of 2, so we can swap modulus for bitwise AND.</p> <pre><code>def carry(z,direction='left',word_size=8): v = z[:] mod = (1&lt;&lt;word_size) - 1 if direction == 'left': v = v[::-1] accum = 0 for i in xrange(len(v)): v[i] += accum accum = v[i] &gt;&gt; word_size v[i] = v[i] &amp; mod print accum,v if direction == 'left': v = v[::-1] return accum,v </code></pre> <p>Is there any way to make this function even tinier? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:30:16.583", "Id": "33753", "Score": "0", "body": "It would be very handy if you include some `assert`s (3 ó 4) so people can test their refactors easily." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:53:27.187", "Id": "33755", "Score": "0", "body": "Good point. I will." } ]
{ "AcceptedAnswerId": "21029", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T09:46:03.803", "Id": "21019", "Score": "2", "Tags": [ "python", "converting" ], "Title": "Convert carry-add loop to a map or reduce to one-liner" }
21019
accepted_answer
[ { "body": "<ol>\n<li><p>Your code has a lot of copying in it. In the default case (where <code>direction</code> is <code>left</code>) you copy the array three times. This seems like a lot. There are various minor improvements you can make, for example instead of</p>\n\n<pre><code>v = v[::-1]\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>v.reverse()\n</code></pre>\n\n<p>which at least re-uses the space in <code>v</code>.</p>\n\n<p>But I think that it would be much better to reorganize the whole program so that you store your bignums the other way round (with the least significant word at the start of the list), so that you can always process them in the convenient direction.</p></li>\n<li><p>The parameters <code>direction</code> and <code>word_size</code> are part of the description of the data in <code>z</code>. So it would make sense to implement this code as a class to keep these values together. And then you could ensure that the digits always go in the convenient direction for your canonicalization algorithm.</p>\n\n<pre><code>class Bignum(object):\n def __init__(self, word_size):\n self._word_size = word_size\n self._mod = 2 ** word_size\n self._digits = []\n\n def canonicalize(self, carry = 0):\n \"\"\"\n Add `carry` and canonicalize the array of digits so that each\n is less than the modulus.\n \"\"\"\n assert(carry &gt;= 0)\n for i, d in enumerate(self._digits):\n carry, self._digits[i] = divmod(d + carry, self._mod)\n while carry:\n carry, d = divmod(carry, self._mod)\n self._digits.append(d)\n</code></pre></li>\n<li><p>Python already has built-in support for bignums, anyway, so what exactly are you trying to do here that can't be done in vanilla Python?</p>\n\n<p>Edited to add: I see from your comment that I misunderstood the context in which this function would be used (so always give us the context!). It's still the case that you could implement what you want using Python's built-in bignums, for example if you represented your key as an integer then you could write something like:</p>\n\n<pre><code>def fold(key, k, word_size):\n mod = 2 ** (k * word_size)\n accum = 0\n while key:\n key, rem = divmod(key, mod)\n accum += rem\n return accum % mod\n</code></pre>\n\n<p>but if you prefer to represent the key as a list of words, then you could still implement the key-folding operation directly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import izip_longest\n\nclass WordArray(object):\n def __init__(self, data = [], word_size = 8):\n self._word_size = word_size\n self._mod = 1 &lt;&lt; word_size\n self._data = data\n\n def fold(self, k):\n \"\"\"\n Fold array into parts of length k, add them with carry, and return a\n new WordArray. Discard the final carry, if any.\n \"\"\"\n def folded():\n parts = [xrange(i * k, min((i + 1) * k, len(self._data))) \n for i in xrange((len(self._data) + 1) // k)]\n carry = 0\n for ii in izip_longest(*parts, fillvalue = 0):\n carry, z = divmod(sum(self._data[i] for i in ii) + carry, self._mod)\n yield z\n return WordArray(list(folded()), self._word_size)\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:04:28.820", "Id": "33756", "Score": "0", "body": "Thanks a lot. I will make my way through it. Just quickly the objective is not bignum. I fold an array into parts of length k and add these together, but I preserve the length k, so I discard any carry that falls off one end. It's a mixing step in a key scheduling part of a crypto." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:32:41.510", "Id": "33758", "Score": "0", "body": "Your approach reminded me of this: http://pyvideo.org/video/880/stop-writing-classes 'the signature of *this shouldn't be a class* is that it has two methods, one of which is `__init__`, anytime you see this you should think \"hey, maybe I only need that one method!\"'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:35:26.843", "Id": "33759", "Score": "1", "body": "@Jaime: it should be clear, I hope, that my classes aren't intended to be complete. I believe that the OP has more operations that he hasn't told us about, that in a complete implementation would become methods on these classes. (Do you think I need to explain this point?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T08:59:44.737", "Id": "33804", "Score": "0", "body": "Had a closer, look @GarethRees -- that's awesome. I really like that. Very concise on the loops in the BigNum class. Looking at the next part now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T09:04:06.150", "Id": "33805", "Score": "0", "body": "You understood me perfectly on the second part. I am pretty shocked since I gave just a tiny description. That is really clever, too. You are amazing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:38:32.257", "Id": "33812", "Score": "0", "body": "Thanks for the edit. I generally write `//` for integer (floor) division so that code is portable between Python 2 and Python 3." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:01:20.173", "Id": "21029", "ParentId": "21019", "Score": "2" } } ]
<p>I'm trying to learn how to write functional code with Python and have found some tutorials online. Please note that I know Python is not a promoter for functional programming. I just want to try it out. <a href="http://anandology.com/python-practice-book/functional-programming.html">One tutorial</a> in particular gives this as an exercise:</p> <blockquote> <p>Write a function flatten_dict to flatten a nested dictionary by joining the keys with . character.</p> </blockquote> <p>So I decided to give it a try. Here is what I have and it works fine:</p> <pre><code>def flatten_dict(d, result={}, prv_keys=[]): for k, v in d.iteritems(): if isinstance(v, dict): flatten_dict(v, result, prv_keys + [k]) else: result['.'.join(prv_keys + [k])] = v return result </code></pre> <p>I'd like to know whether this is the best way to solve the problem in python. In particular, I really don't like to pass a list of previous keys to the recursive call. </p>
[]
{ "AcceptedAnswerId": "21035", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:08:41.920", "Id": "21033", "Score": "14", "Tags": [ "python", "functional-programming" ], "Title": "Flatten dictionary in Python (functional style)" }
21033
accepted_answer
[ { "body": "<p>Your solution really isn't at all functional. You should return a flattened dict and then merge that into your current dictionary. You should also not modify the dictionary, instead create it with all the values it should have. Here is my approach:</p>\n\n<pre><code>def flatten_dict(d):\n def items():\n for key, value in d.items():\n if isinstance(value, dict):\n for subkey, subvalue in flatten_dict(value).items():\n yield key + \".\" + subkey, subvalue\n else:\n yield key, value\n\n return dict(items())\n</code></pre>\n\n<p>Alternative which avoids yield</p>\n\n<pre><code>def flatten_dict(d):\n def expand(key, value):\n if isinstance(value, dict):\n return [ (key + '.' + k, v) for k, v in flatten_dict(value).items() ]\n else:\n return [ (key, value) ]\n\n items = [ item for k, v in d.items() for item in expand(k, v) ]\n\n return dict(items)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:39:53.393", "Id": "33764", "Score": "0", "body": "Thanks. I was trying to iterate through the result during each recursive step but it returns an error stating the size of the dictionary changed. I'm new to python and I barely understand yield. Is it because yield creates the value on the fly without storing them that the code is not blocked anymore?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:45:27.547", "Id": "33765", "Score": "0", "body": "One thing though. I did return a flattened dict and merged it into a current dictionary, which is the flattened result of the original dictionary. I'd like to know why it was not functional at all..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:05:55.500", "Id": "33767", "Score": "0", "body": "@LimH., if you got that error you were modifying the dictionary you were iterating over. If you are trying to be functional, you shouldn't be modifying dictionaries at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:07:34.050", "Id": "33769", "Score": "0", "body": "No, you did not return a flattened dict and merge it. You ignore the return value of your recursive function call. Your function modifies what is passed to it which is exactly that which you aren't supposed to do in functional style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:08:37.700", "Id": "33771", "Score": "0", "body": "yield does create values on the fly, but that has nothing to do with why this works. It works because it creates new objects and never attempts to modify the existing ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:09:11.227", "Id": "33772", "Score": "0", "body": "I see my mistakes now. Thank you very much :) I thought I was passing copies of result to the function. In fact, I think the author of the tutorial I'm following makes the same mistake, at least with the flatten_list function: http://anandology.com/python-practice-book/functional-programming.html#example-flatten-a-list" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:49:06.400", "Id": "33785", "Score": "0", "body": "Unfortunately, both versions are bugged for 3+ levels of recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:36:07.440", "Id": "33793", "Score": "2", "body": "@JohnOptionalSmith, I see the problem in the second version, but the first seems to work for me... test case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:17:53.050", "Id": "33807", "Score": "0", "body": "@WinstonEwert Try it with `a = { 'a' : 1, 'b' : { 'leprous' : 'bilateral' }, 'c' : { 'sigh' : 'somniphobia'} }` (actually triggers the bug with 2-level recursion)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:33:31.610", "Id": "33810", "Score": "0", "body": "My bad ! CopyPaste error ! Your first version is fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:01:49.873", "Id": "272490", "Score": "0", "body": "Thanks for this nice code snippet @WinstonEwert! Could you explain why you defined a function in a function here? Is there a benefit to doing this instead of defining the same functions outside of one another?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:20:31.280", "Id": "272493", "Score": "2", "body": "@zelusp, the benefit is organizational, the function inside the function is part of of the implementation of the outer function, and putting the function inside makes it clear and prevents other functions from using it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:33:43.197", "Id": "272496", "Score": "0", "body": "[This link](https://realpython.com/blog/python/inner-functions-what-are-they-good-for/) helped me understand better" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:20:49.623", "Id": "21035", "ParentId": "21033", "Score": "19" } } ]
<p>Could I code differently to slim down the point of this Python source code? The point of the program is to get the user's total amount and add it to the shipping cost. The shipping cost is determined by both country (Canada or USA) and price of product: The shipping of a product that is $125.00 in Canada is $12.00.</p> <pre><code>input ('Please press "Enter" to begin') while True: print('This will calculate shipping cost and your grand total.') totalAmount = int(float(input('Enter your total amount: ').replace(',', '').replace('$', ''))) Country = str(input('Type "Canada" for Canada and "USA" for USA: ')) usa = "USA" canada = "Canada" lessFifty = totalAmount &lt;= 50 fiftyHundred = totalAmount &gt;= 50.01 and totalAmount &lt;= 100 hundredFifty = totalAmount &gt;= 100.01 and totalAmount &lt;= 150 twoHundred = totalAmount if Country == "USA": if lessFifty: print('Your shipping is: $6.00') print('Your grand total is: $',totalAmount + 6) elif fiftyHundred: print('Your shipping is: $8.00') print('Your grand total is: $',totalAmount + 8) elif hundredFifty: print('Your shipping is: $10.00') print('Your grand total is: $',totalAmount + 10) elif twoHundred: print('Your shipping is free!') print('Your grand total is: $',totalAmount) if Country == "Canada": if lessFifty: print('Your shipping is: $8.00') print('Your grand total is: $',totalAmount + 8) elif fiftyHundred: print('Your shipping is: $10.00') print('Your grand total is: $',totalAmount + 10) elif hundredFifty: print('Your shipping is: $12.00') print('Your grand total is: $',totalAmount + 12) elif twoHundred: print('Your shipping is free!') print('Your grand total is: $',totalAmount) endProgram = input ('Do you want to restart the program?') if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'): break </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:48:53.977", "Id": "21113", "Score": "5", "Tags": [ "python" ], "Title": "Calculate shipping cost" }
21113
max_votes
[ { "body": "<p>I would not hard-code the fee logic, but instead store it as pure data. It's easier to maintain, even allowing to load it from a file.\nThen, it boils down to a range-based lookup, which is quite classical (cf <code>HLOOKUP</code> in spreadsheet software, with so called \"approximate search\").</p>\n\n<p>In Python, we can perform such a search via <code>bisect</code>, relying on lexicographic order (and infinity as an unreachable upper bound).</p>\n\n<p>Separated core logic would look like :</p>\n\n<pre><code>from bisect import bisect\n\n#For each country, list of (x,y) = (cost_threshold, fee)\n#For first x such cost &lt;= x, pick y for fee.\ninf = float(\"inf\")\nshippingFees = { 'USA' : [ (50, 6), (100, 8), (150, 10), (inf, 0) ],\n 'CANADA' : [ (50, 8), (100, 10), (150, 12), (inf, 0) ]\n }\n#Make sure it is sorted (required for lookup via bisect)\n#FIXME : Actually it would be better to assert it is already sorted,\n# since an unsorted input might reveal a typo.\nfor fee in shippingFees.values() : fee.sort()\n\ndef getShippingFee(amount, country):\n fees = shippingFees[country.upper()] #raise KeyError if not found.\n idx = bisect(fees, (amount,) )\n return fees[idx][1]\n</code></pre>\n\n<hr>\n\n<h2>Update</h2>\n\n<p>Here is a sample of \"working application\" using the helper function, assuming you have saved the code snippet above as <code>prices.py</code> (which should be stored in a module, but that's another story).</p>\n\n<p>NB : I have dropped the exit part, since I don't like to type <code>no</code> when I can hit CTRL+C.</p>\n\n<pre><code>#!/usr/bin/python2\n\"\"\" Your description here \"\"\"\n\nfrom prices import getShippingFee\n\nprint('This will calculate shipping cost and your grand total.')\n\nwhile True:\n\n #TODO : proper input processing, python3 compatible.\n totalAmount = float(raw_input('Enter your total amount: ').replace(',', '').replace('$', ''))\n country = raw_input('Type \"Canada\" for Canada and \"USA\" for USA: ').strip().upper()\n\n try : #TODO : proper country check.\n shippingFee = getShippingFee(totalAmount, country)\n grandTotal = totalAmount + shippingFee\n if shippingFee :\n print('Your shipping cost is: %.2f' % shippingFee)\n else :\n print('Your shipping is free!')\n print('Your grand total is: %.2f' % grandTotal)\n\n except KeyError :\n print (\"Sorry, we don't ship to this hostile country : %s\" % country)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:36:20.053", "Id": "33895", "Score": "0", "body": "Could you explain more into your script? I don't understand how to make it work into a working application." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T10:42:31.687", "Id": "33974", "Score": "0", "body": "This is a great answer especially in a production environment where the code is liable to be changed by someone other than the original author. Someone could easily guess how to add another country or modify the fees structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:04:48.813", "Id": "34015", "Score": "1", "body": "@sotapme Thank you ! The main benefit is that the very same data structure can be reused, to generate shipping cost table in web page for instance. This follows [DRY](http://c2.com/cgi/wiki?DontRepeatYourself) principle : _Every piece of knowledge must have a single, unambiguous, authoritative representation within a system._" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:17:57.743", "Id": "21108", "ParentId": "21113", "Score": "10" } } ]
<p>I am new to Python and I want to see how can I improve my code to make it faster and cleaner. Below you can see the code of Margrabe's Formula for pricing Exchange Options. </p> <p>I think the part where I check if the argument is None and if not take predetermined values, can be improved but i don't know how to do it. Is using scipy.stats.norm for calculating the pdf and cdf of the normal distribution faster than manually coding it myself?</p> <pre><code> from __future__ import division from math import log, sqrt, pi from scipy.stats import norm s1 = 10 s2 = 20 sigma1 = 1.25 sigma2 = 1.45 t = 0.5 rho = 0.85 def sigma(sigma1, sigma2, rho): return sqrt(sigma1**2 + sigma2**2 - 2*rho*sigma1*sigma2) def d1(s1, s2, t, sigma1, sigma2, rho): return (log(s1/s2)+ 1/2 * sigma(sigma1, sigma2, rho)**2 * t)/(sigma(sigma1, sigma2, rho) * sqrt(t)) def d2(s1, s2, t, sigma1, sigma2, rho): return d1(s1,s2,t, sigma1, sigma2, rho) - sigma(sigma1, sigma2, rho) * sqrt(t) def Margrabe(stock1=None, stock2=None, sig1=None, sig2=None, time=None, corr=None): if stock1 == None: stock1 = s1 if stock2 == None: stock2 = s2 if time == None: time = t if sig1 == None: sig1 = sigma1 if sig2 == None: sig2 = sigma2 if corr==None: corr = rho dd1 = d1(stock1, stock2, time, sig1, sig2, corr) dd2 = d2(stock1, stock2, time, sig1, sig2, corr) return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2) print "Margrabe = " + str(Margrabe()) </code></pre>
[]
{ "AcceptedAnswerId": "21140", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T22:01:59.283", "Id": "21139", "Score": "2", "Tags": [ "python" ], "Title": "Improving my code of Margrabe Formula in Python" }
21139
accepted_answer
[ { "body": "<p>First of all, when you compare to <code>None</code>, you are better off using <code>if stock1 is None:</code> - an object can define equality, so potentially using <code>==</code> could return <code>True</code> even when <code>stock1</code> is not <code>None</code>. Using <code>is</code> checks <em>identity</em>, so it will only return <code>True</code> in the case it really is <code>None</code>.</p>\n\n<p>As to simplifying your code, you can simply place the default values directly into the function definition:</p>\n\n<pre><code>def margrabe(stock1=s1, stock2=s2, sig1=t, sig2=sigma1, time=sigma2, corr=rho):\n dd1 = d1(stock1, stock2, time, sig1, sig2, corr)\n dd2 = d2(stock1, stock2, time, sig1, sig2, corr)\n return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2)\n</code></pre>\n\n<p>This makes your code significantly more readable, and much shorter.</p>\n\n<p>It is also worth a note that <code>CapWords</code> is reserved for classes in Python - for functions, use <code>lowercase_with_underscores</code> - this is defined in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP-8</a> (which is a great read for making your Python more readable), and helps code highlighters work better, and your code more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T22:06:25.540", "Id": "21140", "ParentId": "21139", "Score": "1" } } ]
<p>The problem with computing a radix using a non-imperative style of programming is you need to calculate a list of successive quotients, each new entry being the quotient of the last entry divided by the radix. The problem with this is (short of using despicable hacks like log) there is no way to know how many divisions an integer will take to reduce to 0. </p> <p>I'm fine with doing this with a generator :</p> <pre><code>def rep_div(n,r): while n != 0: yield n n /= r </code></pre> <p>But I don't like this for some reason. I feel there must be a clever way of using a lambda, or some functional construction, without building a list like is done here :</p> <pre><code>def rep_div2(n,r): return reduce(lambda v,i: v+[v[-1]/r],question_mark,[n]) </code></pre> <p>Once the repeated divisions can be generated radix is easy :</p> <pre><code>def radix2(n,r): return map(lambda ni: ni % r,(x for x in rep_div(n,r))) </code></pre> <p>So my question is : is it possible to rewrite <code>rep_div</code> as a more concise functional construction, on one line?</p>
[]
{ "AcceptedAnswerId": "21155", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T03:18:20.403", "Id": "21151", "Score": "2", "Tags": [ "python", "functional-programming" ], "Title": "Most concise Python radix function using functional constructions?" }
21151
accepted_answer
[ { "body": "<p>From my perspective, I'd say use the generator. It's concise and easily readable to most people familiar with Python. I'm not sure if you can do this in a functional sense easily without recreating some of the toolkit of functional programming languages. For example, if I wanted to do this in Haskell (which I am by no means an expert in, so this may be a horrible way for all I know), I'd do something like:</p>\n\n<pre><code>radix :: Int -&gt; Int -&gt; [Int]\nradix x n = takeWhile (&gt; 0) $ iterate (\\z -&gt; z `div` n) x\n</code></pre>\n\n<p>You can certainly recreate <code>takeWhile</code> and <code>iterate</code>, however, this only works due to lazy evaluation. The other option is, as you've said, using <code>log</code> and basically recreating <code>scanl</code>:</p>\n\n<pre><code>def scanl(f, base, l):\n yield base\n for x in l:\n base = f(base, x)\n yield base\n\ndef radix(n, r):\n return scanl(operator.__floordiv__, n, (r for x in range((int)(log(n, r)))))\n</code></pre>\n\n<p>So my answer is going to be \"No\" (predicated on the fact that someone smarter than me will probably find a way). However, unless you are playing Code Golf, I'd again suggest sticking with the generator version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:04:00.543", "Id": "21155", "ParentId": "21151", "Score": "1" } } ]
<p>I have a list of strings of variable lengths, and I want to pretty-print them so they are lining up in columns. I have the following code, which works as I want it to currently, but I feel it is a bit ugly. How can I simplify it/make it more pythonic (without changing the output behaviour)?</p> <p>For starters I think I could probably use the alignment <code>'&lt;'</code> option of the <a href="http://docs.python.org/2/library/string.html#formatstrings"><code>str.format</code></a> stuff if I could just figure out the syntax properly...</p> <pre><code>def tabulate(words, termwidth=79, pad=3): width = len(max(words, key=len)) ncols = max(1, termwidth // (width + pad)) nrows = len(words) // ncols + (1 if len(words) % ncols else 0) #import itertools #table = list(itertools.izip_longest(*[iter(words)]*ncols, fillvalue='')) # row-major table = [words[i::nrows] for i in xrange(nrows)] # column-major return '\n'.join(''.join((' '*pad + x.ljust(width) for x in r)) for r in table) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:20:20.877", "Id": "33959", "Score": "1", "body": "Not worth an answer, but you can get your rounded-up-not-down integer division to compute `nrows` in a much more compact form as `nrows = (len(words) - 1) // ncols + 1`. Seee e.g. http://en.wikipedia.org/wiki/Floor_and_ceiling_functions#Quotients" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T12:26:36.657", "Id": "33980", "Score": "0", "body": "Thanks, I knew there was a better way when I was writing that... I'd just forgotten the usual trick (which, actually, I usually used adding the denominator - 1 to the numerator, i.e. `(len(words) + ncols - 1) // ncols` ... it seems to be equivalent to your trick" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T02:26:45.017", "Id": "35302", "Score": "0", "body": "I found a nice alternative, after `pip install prettytable`. No need to reinvent the wheel I guess .." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T06:34:47.553", "Id": "21159", "Score": "5", "Tags": [ "python", "strings" ], "Title": "Nicely tabulate a list of strings for printing" }
21159
max_votes
[ { "body": "<p>A slightly more readable version:</p>\n\n<pre><code>def tabulate(words, termwidth=79, pad=3):\n width = len(max(words, key=len)) + pad\n ncols = max(1, termwidth // width)\n nrows = (len(words) - 1) // ncols + 1\n table = []\n for i in xrange(nrows):\n row = words[i::nrows]\n format_str = ('%%-%ds' % width) * len(row)\n table.append(format_str % tuple(row))\n return '\\n'.join(table)\n</code></pre>\n\n<p>Most notably, I've defined <code>width</code> to include padding and using string formatting to generate a format string to format each row ;).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T22:42:59.757", "Id": "22941", "ParentId": "21159", "Score": "3" } } ]
<p>The following functional program factors an integer by trial division. I am not interested in improving the efficiency (but not in decreasing it either), I am interested how it can be made better or neater using functional constructions. I just seem to think there are a few tweaks to make this pattern more consistent and tight (this is hard to describe), without turning it into boilerplate. </p> <pre><code>def primes(limit): return (x for x in xrange(2,limit+1) if len(factorization(x)) == 1) def factor(factors,p): n = factors.pop() while n % p == 0: n /= p factors += [p] return factors+[n] if n &gt; 1 else factors def factorization(n): from math import sqrt return reduce(factor,primes(int(sqrt(n))),[n]) </code></pre> <p>For example, <code>factorization(1100)</code> yields:</p> <pre><code>[2,2,5,5,11] </code></pre> <p>It would be great if it could all fit on one line or into two functions that looked a lot tighter -- I'm sure there must be some way, but I can not see it yet. What can be done?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:44:41.827", "Id": "33965", "Score": "0", "body": "so `factorization` is the function you want out of this? because you don't need `primes` to get it (note also that factorization calls primes and primes calls factorization, that does not look good)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:54:08.487", "Id": "33966", "Score": "0", "body": "Why would that not be good? I thought it looked cool. Please explain." } ]
{ "AcceptedAnswerId": "21168", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:58:40.743", "Id": "21165", "Score": "1", "Tags": [ "python", "functional-programming", "integer" ], "Title": "How to improve this functional python trial division routine?" }
21165
accepted_answer
[ { "body": "<p>A functional recursive implementation:</p>\n\n<pre><code>def factorization(num, start=2):\n candidates = xrange(start, int(sqrt(num)) + 1)\n factor = next((x for x in candidates if num % x == 0), None)\n return ([factor] + factorization(num / factor, factor) if factor else [num]) \n\nprint factorization(1100)\n#=&gt; [2, 2, 5, 5, 11]\n</code></pre>\n\n<p>Check <a href=\"https://github.com/tokland/pyeuler/blob/master/pyeuler/toolset.py\" rel=\"nofollow\">this</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:54:26.567", "Id": "33967", "Score": "0", "body": "Cool thanks. But I dislike recursion because of stack overflows or max recursion depth. I will try to understand your code though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:55:33.400", "Id": "33968", "Score": "0", "body": "I like get_cardinal_name !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:09:27.743", "Id": "33969", "Score": "0", "body": "Note that the function only calls itself for factors of a number, not for every n being tested, so you'll need a number with thousands of factor to reach the limit. Anyway, since you are learning on Python and functional programming, a hint: 1) lists (arrays) don't play nice with functional programming. 2) not having tail-recursion hinders functional approaches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:23:18.430", "Id": "33970", "Score": "0", "body": "Okay, cool tips about those things. Thanks. I will try to understand this better!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:43:23.810", "Id": "21168", "ParentId": "21165", "Score": "2" } } ]
<p>I have the following python functions for <a href="http://en.wikipedia.org/wiki/Exponentiation_by_squaring" rel="nofollow noreferrer">exponentiation by squaring</a> :</p> <pre><code>def rep_square(b,exp): return reduce(lambda sq,i: sq + [sq[-1]*sq[-1]],xrange(len(radix(exp,2))),[b]) def exponentiate(b,exp): return reduce(lambda res,(sq,p): res*sq if p == 1 else res,zip(rep_square(b,exp),radix(exp,2)),1) </code></pre> <p>They work. Calling <code>print exponentiate(2,10), exponentiate(3,37)</code> yields :</p> <pre><code>1024 450283905890997363 </code></pre> <p>as is proper. But I am not happy with them because they need to calculate a <strong>list</strong> of squares. This seems to be a problem that could be resolved by functional programming because : </p> <ol> <li>Each item in the list only depends on the previous one</li> <li>Repeated squaring is recursive</li> </ol> <p>Despite <a href="https://codereview.stackexchange.com/questions/21165/how-to-improve-this-functional-python-trial-division-routine#comment33965_21165">people mentioning that recursion is a good thing to employ in functional programming, and that lists are not good friends</a> -- I am not sure how to turn this recursive list of squares into a recursive generator of the values that would avoid a list. I know I could use a <em>stateful</em> generator with <code>yield</code> but I like something that can be written in one line. </p> <p>Is there a way to do this with tail recursion? Is there a way to make this into a generator expression? </p> <p>The only thing I have thought of is this <em>particularly ugly</em> and also broken recursive generator : </p> <pre><code>def rep_square(n,times): if times &lt;= 0: yield n,n*n yield n*n,list(rep_square(n*n,times-1)) </code></pre> <p>It never returns. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T10:16:07.310", "Id": "33973", "Score": "0", "body": "A bit of a naive question but why don't you just rewrite the definition of Function exp-by-squaring(x,n) from Wikipedia in proper python ? It seems fine as far as I can tell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:48:38.967", "Id": "35759", "Score": "0", "body": "@Josay because I want to make one myself." } ]
{ "AcceptedAnswerId": "21183", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:36:59.913", "Id": "21169", "Score": "1", "Tags": [ "python", "functional-programming", "recursion" ], "Title": "How to improve this functional python fast exponentiation routine?" }
21169
accepted_answer
[ { "body": "<p>You haven't said anything against <a href=\"http://docs.python.org/2/library/itertools.html\" rel=\"nofollow\"><code>itertools</code></a>, so here's how I'd do it with generators:</p>\n\n<pre><code>from itertools import compress\nfrom operator import mul\n\ndef radix(b) :\n while b :\n yield b &amp; 1\n b &gt;&gt;= 1\n\ndef squares(b) :\n while True :\n yield b\n b *= b\n\ndef fast_exp(b, exp) :\n return reduce(mul, compress(squares(b), radix(exp)), 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:17:53.700", "Id": "34011", "Score": "0", "body": "I like that. Both these answers are awesome. Showing the beautiful ways of looking at it from two different and complimentary perspectives. Coolness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:49:58.310", "Id": "35760", "Score": "0", "body": "I chose this as the answer because although we have a *tail recursion* version, as asked, and this *generator expression* as asked, I really liked the use of `compress` and the idea of selectors -- which was new for me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:35:54.627", "Id": "21183", "ParentId": "21169", "Score": "1" } } ]
<p>I have two classes with similar first checking codes, but different behaviors. I suppose there is a way to refactor the code, so I don't need to retype it every time. Is it possible to refactor this, or I must retype this code every time?</p> <pre><code># Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: </code></pre> <p>The code is simple. Forget about my way to render the page, is a method over my own <code>PageHandler</code> class that works.</p> <pre><code># Check for actual logged user def checkLoggedUser(): # Get actual logged user user = users.get_current_user() # Don't allow to register for a logged user if user: return True, "You are already logged in." else: return False, None # Get and post for the login page class Login(custom.PageHandler): def get(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: self.renderPage('login.htm') def post(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: # Make the login # bla, bla bla... code for login the user. # Get and post for the register page class Register(custom.PageHandler): def get(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: self.renderPage("registerUser.htm") def post(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: # Store in vars the form values # bla, bla bla... code for register the user. </code></pre>
[]
{ "AcceptedAnswerId": "21184", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:20:37.023", "Id": "21178", "Score": "1", "Tags": [ "python", "logging" ], "Title": "Checking for a logged user" }
21178
accepted_answer
[ { "body": "<p>Create a class</p>\n\n<pre><code>class MyPageHandler(custom.PageHandler):\n def veryUserNotLoggedIn(self):\n if users.getCurrentUser():\n self.renderPage(\"customMessage.htm\", custom_msg=msg)\n return False\n else:\n return True\n</code></pre>\n\n<p>Then you can write you class like</p>\n\n<pre><code>class Login(MyPageHandler):\n def get(self):\n if self.verifyUserNotLoggedIn():\n self.renderPage('login.htm')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:35:17.533", "Id": "34031", "Score": "0", "body": "you are a number one! :) 2 refactors, 2 new knowledges for me. Thank you a lot (I'm a little rusty, I come from VB6... but learning a lot now)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:00:58.667", "Id": "21184", "ParentId": "21178", "Score": "1" } } ]
<p>I've a web form that allows users to create clusters of three sizes: small, medium and large. The form is sending a string of small, medium or large to a message queue, were job dispatcher determines how many jobs (cluster elements) it should build for a given cluster, like that:</p> <pre><code># determine required cluster size if cluster['size'] == 'small': jobs = 3 elif cluster['size'] == 'medium': jobs = 5 elif cluster['size'] == 'large': jobs = 8 else: raise ConfigError() </code></pre> <p>While it works, its very ugly and non flexible way of doing it - in case I'd want to have more gradual sizes, I'd increase number of <code>elif</code>'s. I could send a number instead of string straight from the form, but I dont want to place the application logic in the web app. Is there a nicer and more flexible way of doing something like that? </p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T09:15:49.903", "Id": "21219", "Score": "2", "Tags": [ "python", "strings", "form" ], "Title": "Flexible multiple string comparision to determine variable value" }
21219
max_votes
[ { "body": "<p>I'd write:</p>\n\n<pre><code>jobs_by_cluster_size = {\"small\": 3, \"medium\": 5, \"large\": 8}\njobs = jobs_by_cluster_size.get(cluster[\"size\"]) or raise_exception(ConfigError())\n</code></pre>\n\n<p><code>raise_exception</code> is just a wrapper over <code>raise</code> (statement) so it can be used in expressions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:16:30.080", "Id": "34058", "Score": "1", "body": "I'm afraid that's not valid python" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:25:39.763", "Id": "34059", "Score": "0", "body": "@WinstonEwert: Oops, I had completely forgotten `raise` is an statement in Python and not a function/expression (too much Ruby lately, I am afraid). Fixed (kind of)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T12:49:52.837", "Id": "21227", "ParentId": "21219", "Score": "1" } } ]
<p>Below is the code for knowing all the prime factors of a number. I think there must be some better way of doing the same thing. Also, please tell me if there are some flaws in my code.</p> <pre><code>def factorize(num): res2 = "%s: "%num res = [] while num != 1: for each in range(2, num + 1): quo, rem = divmod(num, each) if not rem: res.append(each) break num = quo pfs = set(res) for each in pfs: power = res.count(each) if power == 1: res2 += str(each) + " " else: res2 += str(each) + '^' + str(power) + " " return res2 </code></pre>
[]
{ "AcceptedAnswerId": "21231", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T13:15:50.493", "Id": "21229", "Score": "2", "Tags": [ "python", "primes" ], "Title": "Code review needed for my Prime factorization code" }
21229
accepted_answer
[ { "body": "<pre><code>def factorize(num):\n res2 = \"%s: \"%num\n</code></pre>\n\n<p>You'd be much better off to put the string stuff in a seperate function. Just have this function return the list of factors, i.e. <code>res</code> and have a second function take <code>res</code> as a parameter and return the string. That'd make your logic simpler for each function.</p>\n\n<pre><code> res = []\n</code></pre>\n\n<p>Don't needlessly abbreviate. It doesn't save you any serious amount of typing time and makes it harder to follow your code.</p>\n\n<pre><code> while num != 1:\n for each in range(2, num + 1):\n</code></pre>\n\n<p>To be faster here, you'll want recompute the prime factors of the numbers. You can use the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a>. Just keep track of the prime factors found, and you'll just be able to look them up.</p>\n\n<pre><code> quo, rem = divmod(num, each)\n if not rem:\n res.append(each)\n break\n num = quo\n</code></pre>\n\n<p>Your function dies here if you pass it a zero.</p>\n\n<pre><code> pfs = set(res)\n</code></pre>\n\n<p>Rather than a set, use <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a>, it'll let you get the counts at the same time rather then recounting res.</p>\n\n<pre><code> for each in pfs:\n power = res.count(each)\n if power == 1:\n res2 += str(each) + \" \"\n else:\n res2 += str(each) + '^' + str(power) + \" \"\n</code></pre>\n\n<p>String addition is inefficient. I'd suggest using <code>\"{}^{}\".format(each, power)</code>. Also, store each piece in a list and then use <code>\" \".join</code> to make them into a big string at the end.</p>\n\n<pre><code> return res2\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:15:06.070", "Id": "21231", "ParentId": "21229", "Score": "6" } } ]
<p>I am in two minds about function calls as parameters for other functions. The doctrine that readability is king makes me want to write like this:</p> <pre><code>br = mechanize.Browser() raw_html = br.open(__URL) soup = BeautifulSoup(raw_html) </code></pre> <p>But in the back of my mind I feel childish doing so, which makes me want to write this:</p> <pre><code>br = mechanize.Browser() soup = BeautifulSoup(br.open(__URL)) </code></pre> <p>Would it actually look unprofessional to do it the first way? Is there any serious reason to choose one method over the other?</p>
[]
{ "AcceptedAnswerId": "21282", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T06:37:42.507", "Id": "21278", "Score": "3", "Tags": [ "python" ], "Title": "Function calls as parameters for other functions" }
21278
accepted_answer
[ { "body": "<p>I'm typically an advocate of liberal use of space, but in this situation, I'd go with the third option:</p>\n\n<pre><code>soup = BeautifulSoup(mechanize.Browser().open(__URL))\n</code></pre>\n\n<p>(I'm not actually sure if that's valid syntax or not. I'm not very familiar with Python [I think it's Python?].)</p>\n\n<p>I find that just as readable. There are of course situations where you must separate it though. The first thing that comes to mind is error handling. I suspect that <code>open</code> throws exceptions, but if it were to return boolean <code>false</code> on failure rather than a string, then I would be a fan of option two. Option two would still be brief, but would allow for properly checking for the <code>false</code> return.</p>\n\n<hr>\n\n<p>I think this really comes down to personal taste. There's no magical rule book for this type of thing (though I'm sure there are convoluted, borderline-dogmatic metrics somewhere that support one way or the other).</p>\n\n<p>I tend to just eyeball things like this and see if they make me visually uncomfortable or not.</p>\n\n<p>For example:</p>\n\n<pre><code>superLongVariableNameHere(someParamWithLongName, someFunctionLong(param1, param2), someFunc3(param, func4(param1, param2, func5(param)))\n</code></pre>\n\n<p>Makes me cry a little whereas:</p>\n\n<pre><code>func(g(x), y(z))\n</code></pre>\n\n<p>Seems perfectly fine. I just have some weird mental barrier of what length/nesting level becomes excessive.</p>\n\n<hr>\n\n<p>While I'm at it, I'd also disagree with Juann Strauss' dislike of JavaScript's practically idiomatic use of anonymous and inline-defined functions. Yes, people go overboard sometimes with a 30 line callback, but for the most part, there's nothing wrong with a 1-10 line anonymous function as long as it's used in one and only one place and it doesn't overly clutter its context.</p>\n\n<p>In fact, to have a closure, you often have to define functions in the middle of scopes (well, by definition you do). Often in that situation you might as well inline it within another function call rather than defining it separately (once again, provided the body is brief).</p>\n\n<p>If he means this though, then yeah, I'd agree 95% of the time:</p>\n\n<pre><code>f((function(x) { return x * x; }(5))\n</code></pre>\n\n<p>That gets ugly fast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T08:11:07.963", "Id": "34147", "Score": "1", "body": "+0.5 for pointing out that sometimes variables are necessary for error checking; +0.5 for disagreement with Juann's personal feelings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-02T00:03:56.510", "Id": "98050", "Score": "0", "body": "+1 This is the reverse of Introduce Explaining Variable and IMHO a good example of when the refactoring isn't needed. The raw HTML is used just once right away, and it's pretty clear that opening a URL would produce HTML. The one-line statement is clear and concise. Introducing temporary variables in this case could mislead the reader to think there's more going on here than there is." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T07:59:01.227", "Id": "21282", "ParentId": "21278", "Score": "5" } } ]
<p>I wanted to implemented an algorithm in Python 2.4 (so the odd construction for the conditional assignment) where given a list of ranges, the function returns another list with all ranges that overlap in the same entry.</p> <p>I would appreciate other options (more elegant or efficient) than the one I took. </p> <pre><code>ranges = [(1,4),(1,9),(3,7),(10,15),(1,2),(8,17),(16,20),(100,200)] def remove_overlap(rs): rs.sort() def process (rs,deviation): start = len(rs) - deviation - 1 if start &lt; 1: return rs if rs[start][0] &gt; rs[start-1][1]: return process(rs,deviation+1) else: rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] &lt; rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] &gt; rs[start][1]]) del rs[start] return process(rs,0) return process(rs,0) print remove_overlap(ranges) </code></pre>
[]
{ "AcceptedAnswerId": "21309", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T17:04:46.913", "Id": "21307", "Score": "9", "Tags": [ "python", "performance", "algorithm", "python-2.x", "interval" ], "Title": "Consolidate list of ranges that overlap" }
21307
accepted_answer
[ { "body": "<p>Firstly, modify or return, don't do both. </p>\n\n<p>Your <code>process</code> method returns lists as well as modify them. Either you should construct a new list and return that, or modify the existing list and return nothing.</p>\n\n<p>Your <code>remove_overlap</code> function does the same thing. It should either modify the incoming list, or return a new list not both. </p>\n\n<p>You index <code>[0]</code> and <code>[1]</code> on the tuples a lot to fetch the start and end. That's best avoided because its not easy to tell whats going on. </p>\n\n<p><code>rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] &lt; rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] &gt; rs[start][1]])</code></p>\n\n<p>Ouch! That'd be much better off broken into several lines. You shouldn't need to check which of the starts is lower because sorting the array should mean that the earlier one is always lower. I'd also use the <code>max</code> function to select the larger item, (if you don't have it in your version of python, I'd just define it)</p>\n\n<p>Your loop is backwards, working from the end. That complicates the code and makes it harder to follow. I'd suggest reworking it work from the front. </p>\n\n<pre><code>return process(rs,0)\n</code></pre>\n\n<p>You start the checking process over again whenever you merge two ranges. But that's not so great because you'll end up rechecking all the segments over and over again. Since you've already verified them you shouldn't check them again. </p>\n\n<p>Your recursion process can be easily rewritten as a while loop. All you're doing is moving an index forward, and you don't really need recursion.</p>\n\n<p>This is my implementation:</p>\n\n<pre><code>def remove_overlap(ranges):\n result = []\n current_start = -1\n current_stop = -1 \n\n for start, stop in sorted(ranges):\n if start &gt; current_stop:\n # this segment starts after the last segment stops\n # just add a new segment\n result.append( (start, stop) )\n current_start, current_stop = start, stop\n else:\n # segments overlap, replace\n result[-1] = (current_start, stop)\n # current_start already guaranteed to be lower\n current_stop = max(current_stop, stop)\n\n return result\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T11:18:12.577", "Id": "34223", "Score": "0", "body": "`remove_overlap([(-1,1)])` → `IndexError: list assignment index out of range`. Maybe start with `float('-inf')` instead of `-1`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T13:53:40.937", "Id": "34227", "Score": "0", "body": "@GarethRees, that'll work if you need negative ranges. I assumed the ranges were positive as typically negatives ranges are non-sensical (not always)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T18:09:21.930", "Id": "21309", "ParentId": "21307", "Score": "8" } } ]
<p>I am looking for a memory efficient python script for the following script. The following script works well for smaller dimension but the dimension of the matrix is 5000X5000 in my actual calculation. Therefore, it takes very long time to finish it. Can anyone help me how can I do that?</p> <pre><code>def check(v1,v2): if len(v1)!=len(v2): raise ValueError,"the lenght of both arrays must be the same" pass def d0(v1, v2): check(v1, v2) return dot(v1, v2) import numpy as np from pylab import * vector=[[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]] rav= np.mean(vector,axis=0) #print rav #print vector m= vector-rav corr_matrix=[] for i in range(0,len(vector)): tmp=[] x=sqrt(d0(m[i],m[i])) for j in range(0,len(vector)): y=sqrt(d0(m[j],m[j])) z=d0(m[i],m[j]) w=z/(x*y) tmp.append(w) corr_matrix.append(tmp) print corr_matrix </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:27:08.100", "Id": "34309", "Score": "0", "body": "\"... memory efficient ... very long time ...\" Do you want to optimize memory usage or runtime?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T18:24:46.373", "Id": "34329", "Score": "0", "body": "I am looking for both." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T02:19:53.197", "Id": "21362", "Score": "1", "Tags": [ "python" ], "Title": "Looking for efficient python program for this following python script" }
21362
max_votes
[ { "body": "<p>I noticed one of your issues is that you are calculating the same thing over and over again when it is possible to pre-calculate the values before looping. First of all:</p>\n<pre><code>x = sqrt(d0(m[i], m[i]))\n</code></pre>\n<p>and:</p>\n<pre><code>y = sqrt(d0(m[j], m[j]))\n</code></pre>\n<p>are doing the exact same thing. You are calculating the sqrt() of dot product of the entire length of the vector length^2 times! For your 5000 element vector list, that's 25,000,000 times.</p>\n<p>When it comes to iterating over giant mounds of data, try to pre-calculate as much as possible. Try this:</p>\n<pre><code>pre_sqrt = [sqrt(d0(elem, elem)) for elem in m]\npre_d0 = [d0(i, j) for i in m for j in m]\n</code></pre>\n<p>Then, to reduce the amount of repetitive calls to <code>len()</code> and <code>range()</code>:</p>\n<pre><code>vectorLength = len(vector)\niterRange = range(vectorLength)\n</code></pre>\n<p>Finally, this is how your for loops should look:</p>\n<pre><code>for i in iterRange:\n\n tmp = [] \n x = pre_sqrt[i]\n \n for j in iterRange:\n\n y = pre_sqrt[j]\n z = pre_d0[i*vectorLength + j]\n \n w = z / (x * y)\n\n tmp.append(w)\n\n corr_matrix.append(tmp)\n</code></pre>\n<p>When I timed your implementation vs mine these were the average speeds over 10000 repetitions:</p>\n<blockquote>\n<p><strong>Old:</strong> .150 ms</p>\n<p><strong>Mine:</strong> .021 ms</p>\n</blockquote>\n<p>That's about a 7 fold increase over your small sample vector. I imagine the speed increase will be even better when you enter the 5000 element vector.</p>\n<p>You should also be aware that there could be some Python specific improvements to be made. For example, using lists vs numpy arrays to store large amounts of data. Perhaps someone else can elaborate further on those types of speed increases.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T05:01:49.013", "Id": "21364", "ParentId": "21362", "Score": "4" } } ]
<p>Here's my attempt at Project Euler Problem #5, which is looking quite clumsy when seen the first time. Is there any better way to solve this? Or any built-in library that already does some part of the problem?</p> <pre><code>''' Problem 5: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 What is the smallest number, that is evenly divisible by each of the numbers from 1 to 20? ''' from collections import defaultdict def smallest_number_divisible(start, end): ''' Function that calculates LCM of all the numbers from start to end It breaks each number into it's prime factorization, simultaneously keeping track of highest power of each prime number ''' # Dictionary to store highest power of each prime number. prime_power = defaultdict(int) for num in xrange(start, end + 1): # Prime number generator to generate all primes till num prime_gen = (each_num for each_num in range(2, num + 1) if is_prime(each_num)) # Iterate over all the prime numbers for prime in prime_gen: # initially quotient should be 0 for this prime numbers # Will be increased, if the num is divisible by the current prime quotient = 0 # Iterate until num is still divisible by current prime while num % prime == 0: num = num / prime quotient += 1 # If quotient of this priime in dictionary is less than new quotient, # update dictionary with new quotient if prime_power[prime] &lt; quotient: prime_power[prime] = quotient # Time to get product of each prime raised to corresponding power product = 1 # Get each prime number with power for prime, power in prime_power.iteritems(): product *= prime ** power return product def is_prime(num): ''' Function that takes a `number` and checks whether it's prime or not Returns False if not prime Returns True if prime ''' for i in xrange(2, int(num ** 0.5) + 1): if num % i == 0: return False return True if __name__ == '__main__': print smallest_number_divisible(1, 20) import timeit t = timeit.timeit print t('smallest_number_divisible(1, 20)', setup = 'from __main__ import smallest_number_divisible', number = 100) </code></pre> <p>While I timed the code, and it came out with a somewhat ok result. The output came out to be:</p> <pre><code>0.0295362259729 # average 0.03 </code></pre> <p>Any inputs?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:07:04.760", "Id": "34279", "Score": "0", "body": "I think you can adapt [Erathosthenes' prime sieve](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to compute is_prime plus the amount of factors in one go." } ]
{ "AcceptedAnswerId": "21375", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T10:09:49.247", "Id": "21367", "Score": "5", "Tags": [ "python", "project-euler", "primes" ], "Title": "Any better way to solve Project Euler Problem #5?" }
21367
accepted_answer
[ { "body": "<p>You are recomputing the list of prime numbers for each iteration. Do it just once and reuse it. There are also better ways of computing them other than trial division, the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a> is very simple yet effective, and will get you a long way in Project Euler. Also, the factors of <code>n</code> are all smaller than <code>n**0.5</code>, so you can break out earlier from your checks.</p>\n\n<p>So add this before the <code>num</code> for loop:</p>\n\n<pre><code>prime_numbers = list_of_primes(int(end**0.5))\n</code></pre>\n\n<p>And replace <code>prime_gen</code> with :</p>\n\n<pre><code>prime_gen =(each_prime for each_prime in prime_numbers if each_prime &lt;= int(num**0.5))\n</code></pre>\n\n<p>The <code>list_of_primes</code> function could be like this using trial division :</p>\n\n<pre><code>def list_of_primes(n)\n \"\"\"Returns a list of all the primes below n\"\"\"\n ret = []\n for j in xrange(2, n + 1) :\n for k in xrange(2, int(j**0.5) + 1) :\n if j % k == 0 :\n break\n else :\n ret.append(j)\n return ret\n</code></pre>\n\n<p>But you are better off with a very basic <a href=\"http://numericalrecipes.wordpress.com/2009/03/16/prime-numbers-2-the-sieve-of-erathostenes/\" rel=\"nofollow\">sieve of Erathostenes</a>:</p>\n\n<pre><code>def list_of_primes(n) :\n sieve = [True for j in xrange(2, n + 1)]\n for j in xrange(2, int(sqrt(n)) + 1) :\n i = j - 2\n if sieve[j - 2]:\n for k in range(j * j, n + 1, j) :\n sieve[k - 2] = False\n return [j for j in xrange(2, n + 1) if sieve[j - 2]]\n</code></pre>\n\n<hr>\n\n<p>There is an alternative, better for most cases, definitely for Project Euler #5, way of going about calculating the least common multiple, using the greatest common divisor and <a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"nofollow\">Euclid's algorithm</a>:</p>\n\n<pre><code>def gcd(a, b) :\n while b != 0 :\n a, b = b, a % b\n return a\n\ndef lcm(a, b) :\n return a // gcd(a, b) * b\n\nreduce(lcm, xrange(start, end + 1))\n</code></pre>\n\n<p>On my netbook this gets Project Euler's correct result lightning fast:</p>\n\n<pre><code>In [2]: %timeit reduce(lcm, xrange(1, 21))\n10000 loops, best of 3: 69.4 us per loop\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:46:49.650", "Id": "34318", "Score": "0", "body": "I agree, using gcd is the easiest way here. I am quite sure it had to be written before or anywhere else anyway. (For very large numbers, this approach has some problems, but well, 20 is not a very large number)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:27:25.840", "Id": "34344", "Score": "0", "body": "Hello @Jaime. Thanks for your response. I tried to use your `list_of_prime` method, but the problem is: - `end ** 0.5` range generates just `[2, 3]` as prime numbers below `20`. So, it's not considering `5`, which is a valid prime diviser. Same in the case of `10`. It's not considering `5`. And hence I'm loosing some factors. Also, for numbers like `5`, or `7`, again it is not considering `5` and `7` respectively, which we should consider right? So, does that mean that `range(2, int(end**0.5))` is not working well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:30:09.453", "Id": "34345", "Score": "0", "body": "However, if I replace the range with `range(2, end)`, and in list comprehension also: - `each_prime <= num`, it's giving me correct result." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:24:13.717", "Id": "21375", "ParentId": "21367", "Score": "7" } } ]
<p>I am writing a program which calculates the scores for participants of a small "Football Score Prediction" game.</p> <p>Rules are:</p> <ol> <li>if the match result(win/loss/draw) is predicted correctly: 1 point</li> <li>if the match score is predicted correctly(exact score): 3 points (and +1 point because 1st rule is automatically satisfied)</li> </ol> <p>Score is calculated after every round of matches (10 matches in a round).</p> <p>The program I've written is as follows:</p> <pre><code>import numpy as np import re players = {0:'Alex',1:'Charlton',2:'Vineet'} results = np.array(range(40),dtype='a20').reshape(4,10) eachPrediction = np.array(range(20),dtype='a2').reshape(2,10) score = np.zeros(3) correctScore=3 correctResult=1 allPredictions = [] done = False def takeFixtures(): filename='bplinput.txt' file = open(filename) text = file.readlines() fixtures = [line.strip() for line in text] file.close() i=0 for eachMatch in fixtures: x=re.match("(.*) ([0-9]+) ?- ?([0-9]+) (.*)", eachMatch) results[0,i]=x.group(1) results[1,i]=x.group(2) results[2,i]=x.group(3) results[3,i]=x.group(4) i+=1 def takePredictions(noOfParticipants): for i in range(0,noOfParticipants): print("Enter predictions by "+players[i]+" in x-y format") for i in range(0,10): eachFixturePrediction = raw_input("Enter prediction for "+results[0,i]+" vs "+results[3,i]+": ") x=eachFixturePrediction.split('-') eachPrediction[0,i]=str(x[0]) eachPrediction[1,i]=str(x[1]) allPredictions.append(eachPrediction) def scoreEngine(): for i in range(0,len(players)): for j in range(0,10): resultH=int(results[1,j]) resultA=int(results[2,j]) result=resultH-resultA predictionH=int(allPredictions[i][0][j]) predictionA=int(allPredictions[i][1][j]) pResult = predictionH-predictionA if result == pResult or (result&lt;0 and pResult&lt;0) or (result&gt;0 and pResult&gt;0): score[i]+=correctResult if resultH==predictionH and resultA==predictionA: score[i]+=correctScore noOfParticipants=len(players) takeFixtures() takePredictions(noOfParticipants) scoreEngine() print("Scores are:") print(score) for player in players: print(players[player]+" has scored "+ str(score[player])+" points" ) </code></pre> <p>The file used to take list of fixtures looks like this:</p> <pre><code>West Bromwich Albion 0-1 Tottenham Hotspur Manchester City 2-2 Liverpool Queens Park Rangers 0-0 Norwich City Arsenal 1-0 Stoke City Everton 3-3 Aston Villa Newcastle United 3-2 Chelsea Reading 2-1 Sunderland West Ham United 1-0 Swansea City Wigan Athletic 2-2 Southampton Fulham 0-1 Manchester United </code></pre> <p>I want advice on how this program can be improved in any way (decreasing the code/ making it efficient).</p>
[]
{ "AcceptedAnswerId": "21416", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T05:51:57.967", "Id": "21408", "Score": "4", "Tags": [ "python", "optimization", "game" ], "Title": "Calculating scores for predictions of football scores" }
21408
accepted_answer
[ { "body": "<h2>Style</h2>\n\n<p>The first thing to do is to follow PEP 8: it's a style guide that says how you should indent your code, name your variables, and so on. For example, prefer <code>results[0, i] = x.group(1)</code> to <code>results[0,i]=x.group(1)</code>.</p>\n\n<h2>Files</h2>\n\n<p>Opening files in Python should be done using the <a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow\"><code>with</code> idiom</a>: your file is then guaranteed to be close correctly. <code>takeFixtures</code> now becomes:</p>\n\n<pre><code>def takeFixtures():\n with open('bplinput.txt') as file:\n for eachMath in file:\n x=re.match(\"(.*) ([0-9]+) ?- ?([0-9]+) (.*)\", eachMatch.strip)\n results[0,i]=x.group(1)\n results[1,i]=x.group(2)\n results[2,i]=x.group(3)\n results[3,i]=x.group(4)\n i+=1\n</code></pre>\n\n<h2>Data structures</h2>\n\n<p>I you didn't use numpy, you could have written <code>results[i] = x.groups()</code>, and then used <code>zip(*results)</code> to transpose the resulting matrix. More generally, as pointed out by Josay, you should use Python data structures, and only switch to numpy if you find out that this is where the inefficiency lies.</p>\n\n<h2>Formatting</h2>\n\n<p>The last thing that the other reviewers didn't mention is that concatenating strings is poor style, and <code>format()</code> should be preferred since it's more readable and more efficient:</p>\n\n<pre><code>for player in players:\n print(\"{} has scored {} points\".format(players[player], score[player]))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:29:14.560", "Id": "34409", "Score": "0", "body": "thanks,Can you give me suggestion on a better way to take input from all the players? right now I have to manually input the score predictions by all players, and if there is some mistake i have to do it all over again. ie. one mistake and i have to input 30 predictions all over again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T16:14:28.623", "Id": "34413", "Score": "1", "body": "You need to catch the [exception](http://docs.python.org/2/tutorial/errors.html) that comes out and ask the input to be made again. You would need some kind of loop to make the input until it worked correctly. This would be a good question on StackOverflow unless it has alread been asked." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:11:11.890", "Id": "21416", "ParentId": "21408", "Score": "6" } } ]
<p>Is there a better way of creating this terminal animation without having a series of conditional statements (i.e. <code>if ... elif ... elif...)</code>?</p> <pre><code>import sys, time count = 100 i = 0 num = 0 def animation(): global num if num == 0: num += 1 return '[= ]' elif num == 1: num += 1 return '[ = ]' elif num == 2: num += 1 return '[ = ]' elif num == 3: num += 1 return '[ = ]' elif num == 4: num += 1 return '[ = ]' elif num == 5: num += 1 return '[ = ]' elif num == 6: num += 1 return '[ =]' elif num == 7: num += 1 return '[ =]' elif num == 8: num += 1 return '[ = ]' elif num == 9: num += 1 return '[ = ]' elif num == 10: num += 1 return '[ = ]' elif num == 11: num += 1 return '[ = ]' elif num == 12: num += 1 return '[ = ]' elif num == 13: num = 0 return '[= ]' while i &lt; count: sys.stdout.write('\b\b\b') sys.stdout.write(animation()) sys.stdout.flush() time.sleep(0.2) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:06:17.480", "Id": "34488", "Score": "0", "body": "I guess that a progress bar, shouldn't you write \\b 9 times?" } ]
{ "AcceptedAnswerId": "21464", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:13:04.773", "Id": "21462", "Score": "9", "Tags": [ "python" ], "Title": "Python terminal animation" }
21462
accepted_answer
[ { "body": "<p>You can build up the string like this:</p>\n\n<pre><code>def animation(counter, length):\n stage = counter % (length * 2 + 2)\n if stage &lt; length + 1:\n left_spaces = stage\n else:\n left_spaces = length * 2 - 1 - stage\n return '[' + ' ' * left_spaces + '=' + ' ' * (length - left_spaces) + ']'\n\nfor i in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation(i, 6))\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>Alternatively store the animation strings in a tuple or list:</p>\n\n<pre><code>animation_strings = ('[= ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[ = ]', '[ =]', '[ =]',\n '[ = ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[= ]')\nfor i in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation_strings[i % len(animation_strings)])\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>You can replace the animation function with <a href=\"http://docs.python.org/2/library/itertools.html#itertools.cycle\"><code>cycle</code> from <code>itertools</code></a>:</p>\n\n<pre><code>import sys, time\nfrom itertools import cycle\nanimation = cycle('[= ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[ = ]', '[ =]', '[ =]',\n '[ = ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[= ]')\n# alternatively:\n# animation = cycle('[' + ' ' * n + '=' + ' ' * (6 - n) + ']' \n# for n in range(7) + range(6, -1, -1))\n\nfor _ in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation.next())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>Finally, you could make your own generator function.</p>\n\n<pre><code>def animation_generator(length):\n while True:\n for n in range(length + 1):\n yield '[' + ' ' * n + '=' + ' ' * (length - n) + ']'\n for n in range(length + 1):\n yield '[' + ' ' * (length - n) + '=' + ' ' * n + ']'\n\nanimation = animation_generator(6)\nfor _ in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation.next())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>EDIT: made the above suggestions less reliant on global variables</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T12:11:56.170", "Id": "34452", "Score": "3", "body": "+1 for `itertools.cycle`. (But I think you'd want to build up the animation programmatically so that it would be easy to change its length.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:42:39.453", "Id": "34531", "Score": "0", "body": "Alternatively, you could `sys.stdout.write('\\r')` instead of the `\\b\\b\\b`, since the animation steps have equal length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:12:38.307", "Id": "34551", "Score": "0", "body": "@AttilaO. thanks, I use IDLE and don't actually know how these terminal characters work but I'll take your word for it..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:41:43.353", "Id": "21464", "ParentId": "21462", "Score": "16" } } ]
<p>Is there a better way of creating this terminal animation without having a series of conditional statements (i.e. <code>if ... elif ... elif...)</code>?</p> <pre><code>import sys, time count = 100 i = 0 num = 0 def animation(): global num if num == 0: num += 1 return '[= ]' elif num == 1: num += 1 return '[ = ]' elif num == 2: num += 1 return '[ = ]' elif num == 3: num += 1 return '[ = ]' elif num == 4: num += 1 return '[ = ]' elif num == 5: num += 1 return '[ = ]' elif num == 6: num += 1 return '[ =]' elif num == 7: num += 1 return '[ =]' elif num == 8: num += 1 return '[ = ]' elif num == 9: num += 1 return '[ = ]' elif num == 10: num += 1 return '[ = ]' elif num == 11: num += 1 return '[ = ]' elif num == 12: num += 1 return '[ = ]' elif num == 13: num = 0 return '[= ]' while i &lt; count: sys.stdout.write('\b\b\b') sys.stdout.write(animation()) sys.stdout.flush() time.sleep(0.2) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:06:17.480", "Id": "34488", "Score": "0", "body": "I guess that a progress bar, shouldn't you write \\b 9 times?" } ]
{ "AcceptedAnswerId": "21464", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:13:04.773", "Id": "21462", "Score": "9", "Tags": [ "python" ], "Title": "Python terminal animation" }
21462
accepted_answer
[ { "body": "<p>You can build up the string like this:</p>\n\n<pre><code>def animation(counter, length):\n stage = counter % (length * 2 + 2)\n if stage &lt; length + 1:\n left_spaces = stage\n else:\n left_spaces = length * 2 - 1 - stage\n return '[' + ' ' * left_spaces + '=' + ' ' * (length - left_spaces) + ']'\n\nfor i in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation(i, 6))\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>Alternatively store the animation strings in a tuple or list:</p>\n\n<pre><code>animation_strings = ('[= ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[ = ]', '[ =]', '[ =]',\n '[ = ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[= ]')\nfor i in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation_strings[i % len(animation_strings)])\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>You can replace the animation function with <a href=\"http://docs.python.org/2/library/itertools.html#itertools.cycle\"><code>cycle</code> from <code>itertools</code></a>:</p>\n\n<pre><code>import sys, time\nfrom itertools import cycle\nanimation = cycle('[= ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[ = ]', '[ =]', '[ =]',\n '[ = ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[= ]')\n# alternatively:\n# animation = cycle('[' + ' ' * n + '=' + ' ' * (6 - n) + ']' \n# for n in range(7) + range(6, -1, -1))\n\nfor _ in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation.next())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>Finally, you could make your own generator function.</p>\n\n<pre><code>def animation_generator(length):\n while True:\n for n in range(length + 1):\n yield '[' + ' ' * n + '=' + ' ' * (length - n) + ']'\n for n in range(length + 1):\n yield '[' + ' ' * (length - n) + '=' + ' ' * n + ']'\n\nanimation = animation_generator(6)\nfor _ in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation.next())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>EDIT: made the above suggestions less reliant on global variables</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T12:11:56.170", "Id": "34452", "Score": "3", "body": "+1 for `itertools.cycle`. (But I think you'd want to build up the animation programmatically so that it would be easy to change its length.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:42:39.453", "Id": "34531", "Score": "0", "body": "Alternatively, you could `sys.stdout.write('\\r')` instead of the `\\b\\b\\b`, since the animation steps have equal length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:12:38.307", "Id": "34551", "Score": "0", "body": "@AttilaO. thanks, I use IDLE and don't actually know how these terminal characters work but I'll take your word for it..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:41:43.353", "Id": "21464", "ParentId": "21462", "Score": "16" } } ]
<p>I'm trying to learn Python by working my way through problems on the Project Euler website. I managed to solve problem #3, which is </p> <blockquote> <p>What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <p>However, my code looks horrible. I'd really appreciate some advice from experienced Python programmers.</p> <pre><code>import math import unittest def largestPrime(n, factor): """ Find the largest prime factor of n """ def divide(m, factor): """ Divide an integer by a factor as many times as possible """ if m % factor is 0 : return divide(m / factor, factor) else : return m def isPrime(m): """ Determine whether an integer is prime """ if m is 2 : return True else : for i in range(2, int(math.floor(math.sqrt(m))) + 1): if m % i is 0 : return False return True # Because there is at most one prime factor greater than sqrt(n), # make this an upper limit for the search limit = math.floor(math.sqrt(n)) if factor &lt;= int(limit): if isPrime(factor) and n % factor is 0: n = divide(n, factor) if n is 1: return factor else: return largestPrime(n, factor + 2) else: return largestPrime(n, factor + 2) return n </code></pre>
[]
{ "AcceptedAnswerId": "21507", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T06:35:13.020", "Id": "21497", "Score": "4", "Tags": [ "python", "project-euler", "primes" ], "Title": "Largest Prime Factor" }
21497
accepted_answer
[ { "body": "<p>Some thoughts:</p>\n\n<p><code>Divide</code> function has been implemented recursively. In general, recursive implementations provide clarity of thought despite being inefficient. But in this case, it just makes the code cumbersome.</p>\n\n<pre><code>while m % factor == 0:\n m /= factor\nreturn m\n</code></pre>\n\n<p>should do the job.</p>\n\n<hr>\n\n<p>A lot of computational work is done by <code>isPrime</code> which is unnecessary. Eg: when <code>factor</code> 15 is being considered, the original n would've been already <code>Divide</code>d by 3 and 5. So, if <code>factor</code> is not a prime then n%factor will not be 0.</p>\n\n<hr>\n\n<p>So, the following should do:</p>\n\n<pre><code>import math\ndef largestPF(n):\n limit = int(math.sqrt(n)) + 1\n for factor in xrange(2, limit+1):\n while n % factor == 0:\n n /= factor\n if n == 1:\n return factor\n return n\n</code></pre>\n\n<p>You can of course, include the 'run through factors in steps of 2' heuristic if you want.</p>\n\n<hr>\n\n<p>PS: Be careful with the <code>is</code> statement for verifying equality. It might lead to unexpected behaviour. Check out <a href=\"https://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why\">https://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T10:04:35.397", "Id": "21507", "ParentId": "21497", "Score": "5" } } ]
<p>My data is in this format:</p> <blockquote> <p>龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\n</p> </blockquote> <p>And I want to return:</p> <pre><code>('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/') </code></pre> <p>In C I could do this in one line with <code>sscanf</code>, but I seem to be f̶a̶i̶l̶i̶n̶g̶ writing code like a schoolkid with Python:</p> <pre><code> working = line.rstrip().split(" ") trad, simp = working[0], working[1] working = " ".join(working[2:]).split("]") pinyin = working[0][1:] english = working[1][1:] return trad, simp, pinyin, english </code></pre> <p>Can I improve?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:04:27.373", "Id": "34604", "Score": "0", "body": "This is a little hard to parse because the logical field separator, the space character, is also a valid character inside the last two fields. This is disambiguated with brackets and slashes, but that obviously make the parse harder and uglier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T16:08:16.803", "Id": "34615", "Score": "1", "body": "If your code doesn't work correctly, then this question is off topic here. See the [FAQ]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:07:16.690", "Id": "34616", "Score": "3", "body": "@svick it works perfectly - by \"failing\" I meant \"failing to write neat code\"" } ]
{ "AcceptedAnswerId": "21543", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T12:37:25.733", "Id": "21539", "Score": "3", "Tags": [ "python", "strings", "parsing", "unicode" ], "Title": "String parsing with multiple delimeters" }
21539
accepted_answer
[ { "body": "<p>You can use <a href=\"https://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow\">Regular Expressions</a> with <a href=\"http://docs.python.org/2.7/library/re.html\" rel=\"nofollow\">re</a> module. For example the following regular expression works with binary strings and Unicode string (I'm not sure which version of Python you use).</p>\n\n<p>For Python 2.7.3:</p>\n\n<pre><code>&gt;&gt;&gt; s = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; u = s.decode(\"utf-8\")\n&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", s).groups()\n('\\xe9\\xbe\\x8d\\xe8\\x88\\x9f', '\\xe9\\xbe\\x99\\xe8\\x88\\x9f', 'long2 zhou1', '/dragon boat/imperial boat/')\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", u).groups()\n(u'\\u9f8d\\u821f', u'\\u9f99\\u821f', u'long2 zhou1', u'/dragon boat/imperial boat/')\n</code></pre>\n\n<p>For Python 3.2.3:</p>\n\n<pre><code>&gt;&gt;&gt; s = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; b = s.encode(\"utf-8\")\n&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", s).groups()\n('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/')\n&gt;&gt;&gt; re.match(br\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", b).groups()\n(b'\\xe9\\xbe\\x8d\\xe8\\x88\\x9f', b'\\xe9\\xbe\\x99\\xe8\\x88\\x9f', b'long2 zhou1', b'/dragon boat/imperial boat/')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T18:21:43.390", "Id": "34619", "Score": "0", "body": "`groups()` and `groupdict()` are great!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T14:05:11.600", "Id": "21543", "ParentId": "21539", "Score": "5" } } ]
<p>I'm trying to see if there is a better way to design this. I have a class Animal that is inherited by Male and Female classes (Female class has an additional attribute). I also have a class called Habitat, an instance of each would contain any number of Animals including 0.</p> <pre><code>class Animal: def __init__(self, life_span=20, age=0): self.__life_span = life_span self.__age = age def get_life_span(self): return self.__life_span def get_age(self): return self.__age def age(self): self.__age += 1 class Female(Animal): __gender = 'female' def __init__(self, pregnant=False): self.__pregnant = pregnant def impregnate(self): self.__pregnant = True class Male(Animal): __gender = 'male' class Habitat: def __init__(self, list_of_animals=[Male(), Female()]): self.__list_of_animals = list_of_animals def __add_male(self): self.__list_of_animals.append(Male()) def __add_female(self): self.__list_of_animals.append(Female()) def add_animal(self): if random.choice('mf') == 'm': self.__add_male() else: self.__add_female() def get_population(self): return self.__list_of_animals.__len__() </code></pre> <p>Before I add any more functionality, I would like to find out if that's a proper way to design these classes. Maybe there is a design pattern I can use? I'm new to OOP, any other comments/suggestions are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:40:10.843", "Id": "34636", "Score": "2", "body": "FWIW, don't call `obj.__len__()`, use `len(obj)` instead. Also, no need to use name mangling (double leading underscores): Just use `self.age` or `self._age`, especially use the former in favor of trivial getters (you can later replace them with a `property`, *if* you need that extra power, without changing the way client code works with your objects)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:41:06.173", "Id": "34637", "Score": "0", "body": "@tallseth: already flagged as such. OP: if the moderators agree, your question will be automatically migrated for you. Please do not double-post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:41:05.957", "Id": "34638", "Score": "0", "body": "It would appear you're new to OOP in general - what's your experience?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:46:59.060", "Id": "34639", "Score": "0", "body": "@JonClements somehow I managed to avoid the whole thing and it's been bugging me for years, so now I'm trying to get a grip of it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:48:45.100", "Id": "34640", "Score": "0", "body": "@MartijnPieters thanks, can I do it myself without waiting for moderators?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:49:17.600", "Id": "34641", "Score": "0", "body": "Good first attempt - but IMHO - not correct - an Animal is either Male or Female (possibly both given some species), no need to subclass a Gender" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:53:20.873", "Id": "34642", "Score": "0", "body": "@dfo: No, you can't. It is a moderator-level descision I'm afraid." } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:37:16.780", "Id": "21559", "Score": "0", "Tags": [ "python", "object-oriented", "design-patterns" ], "Title": "Instance of one class to contain arbitrary number of instances of another class in Python" }
21559
max_votes
[ { "body": "<p>In <code>Habitat.__init__</code>, you've committed a classic beginner's fallacy: using a list as a default argument.</p>\n\n<p>In Python, every call to a function with a default argument will use the same default object. If that object is mutable (e.g. a list) any mutations to that object (e.g. <code>.append</code>) will affect that one object. In effect, all your <code>Habitat</code>s will end up using the exact same list unless you specify a non-default argument.</p>\n\n<p>Instead, use <code>None</code> as the default argument, and test for it:</p>\n\n<pre><code>def __init__(self, animals=None):\n if animals is None:\n animals = [Male(), Female()]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:40:46.243", "Id": "21560", "ParentId": "21559", "Score": "4" } } ]
<p>I have a web scraping application that contains long string literals for the URLs. What would be the best way to present them (keeping in mind that I would like to adhere to <a href="http://www.python.org/dev/peps/pep-0008/#maximum-line-length" rel="nofollow">PEP-8</a>.</p> <pre><code>URL = "https://www.targetwebsite.co.foo/bar-app/abc/hello/world/AndThen?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea" br = mechanize.Browser() br.open(URL) </code></pre> <p>I had thought to do this:</p> <pre><code>URL_BASE = "https://www.targetwebsite.co.foo/" URL_SUFFIX = "bar-app/abc/hello/world/AndThen" URL_ARGUMENTS = "?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea" br = mechanize.Browser() br.open(URL_BASE + URL_SUFFIX + URL_ARGUMENTS) </code></pre> <p>But there are many lines and it's not a standard way of representing a URL.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T14:25:55.910", "Id": "96329", "Score": "1", "body": "I would put the URLS in a config file, or take them as a parameter." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T12:57:03.020", "Id": "21658", "Score": "5", "Tags": [ "python", "url" ], "Title": "Presenting long string literals (URLs) in Python" }
21658
max_votes
[ { "body": "<p>You could use continuation lines with <code>\\</code>, but it messes the indentation:</p>\n\n<pre><code>URL = 'https://www.targetwebsite.co.foo/\\\nbar-app/abc/hello/world/AndThen\\\n?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea'\n</code></pre>\n\n<p>Or you could use the fact that string literals next to each other are automatically concatenated, in either of these two forms:</p>\n\n<pre><code>URL = ('https://www.targetwebsite.co.foo/'\n 'bar-app/abc/hello/world/AndThen'\n '?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea')\n\nURL = 'https://www.targetwebsite.co.foo/' \\\n 'bar-app/abc/hello/world/AndThen' \\\n '?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea'\n</code></pre>\n\n<p>I often use the parenthesized version, but the backslashed one probably looks cleaner.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T14:23:01.137", "Id": "21660", "ParentId": "21658", "Score": "5" } } ]
<p>This is a Python module I have just finished writing which I plan to use at Project Euler. Please let me know how I have done and what I could do to improve it.</p> <pre><code># This constant is more or less an overestimate for the range in which # n primes exist. Generally 100 primes exist well within 100 * CONST numbers. CONST = 20 def primeEval(limit): ''' This function yields primes using the Sieve of Eratosthenes. ''' if limit: opRange = [True] * limit opRange[0] = opRange[1] = False for (ind, primeCheck) in enumerate(opRange): if primeCheck: yield ind for i in range(ind*ind, limit, ind): opRange[i] = False def listToNthPrime(termin): ''' Returns a list of primes up to the nth prime. ''' primeList = [] for i in primeEval(termin * CONST): primeList.append(i) if len(primeList) &gt;= termin: break return primeList def nthPrime(termin): ''' Returns the value of the nth prime. ''' primeList = [] for i in primeEval(termin * CONST): primeList.append(i) if len(primeList) &gt;= termin: break return primeList[-1] def listToN(termin): ''' Returns a list of primes up to the number termin. ''' return list(primeEval(termin)) def lastToN(termin): ''' Returns the prime which is both less than n and nearest to n. ''' return list(primeEval(termin))[-1] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-15T08:24:01.633", "Id": "34936", "Score": "0", "body": "It is a good idea to always follow PEP-0008 style guidolines: http://www.python.org/dev/peps/pep-0008/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-03T13:04:28.620", "Id": "161558", "Score": "0", "body": "See [this answer](http://codereview.stackexchange.com/a/42439/11728)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T13:38:43.503", "Id": "21659", "Score": "3", "Tags": [ "python", "programming-challenge", "primes" ], "Title": "Project Euler: primes in Python" }
21659
max_votes
[ { "body": "<pre><code># This constant is more or less an overestimate for the range in which\n# n primes exist. Generally 100 primes exist well within 100 * CONST numbers.\nCONST = 20\n\ndef primeEval(limit):\n</code></pre>\n\n<p>Python convention says that functions should named lowercase_with_underscores</p>\n\n<pre><code> ''' This function yields primes using the\n Sieve of Eratosthenes.\n\n '''\n if limit:\n</code></pre>\n\n<p>What is this for? You could be trying to avoid erroring out when limit=0, but it seems to me that you still error at for limit=1.</p>\n\n<pre><code> opRange = [True] * limit\n</code></pre>\n\n<p>As with functions, lowercase_with_underscore</p>\n\n<pre><code> opRange[0] = opRange[1] = False\n\n for (ind, primeCheck) in enumerate(opRange):\n</code></pre>\n\n<p>You don't need the parens around <code>ind, primeCheck</code></p>\n\n<pre><code> if primeCheck:\n yield ind\n for i in range(ind*ind, limit, ind):\n opRange[i] = False\n\n\ndef listToNthPrime(termin):\n ''' Returns a list of primes up to the nth\n prime.\n '''\n primeList = []\n for i in primeEval(termin * CONST):\n primeList.append(i)\n if len(primeList) &gt;= termin:\n break\n return primeList\n</code></pre>\n\n<p>You are actually probably losing out by attempting to stop the generator once you pass the number you wanted. You could write this as:</p>\n\n<pre><code> return list(primeEval(termin * CONST))[:termin]\n</code></pre>\n\n<p>Chances are that you gain more by having the loop be in the loop function than you gain by stopping early. </p>\n\n<pre><code>def nthPrime(termin):\n ''' Returns the value of the nth prime.\n\n '''\n primeList = []\n for i in primeEval(termin * CONST):\n primeList.append(i)\n if len(primeList) &gt;= termin:\n break\n return primeList[-1]\n\ndef listToN(termin):\n ''' Returns a list of primes up to the\n number termin.\n '''\n return list(primeEval(termin))\n\ndef lastToN(termin):\n ''' Returns the prime which is both less than n\n and nearest to n.\n\n '''\n return list(primeEval(termin))[-1]\n</code></pre>\n\n<p>All of your functions will recalculate all the primes. For any sort of practical use you'll want to avoid that and keep the primes you've calculated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T23:39:43.093", "Id": "34831", "Score": "0", "body": "Are you suggesting that I just omit the loop within the functions nthPrime and listToNthPrime, or that I change the function primeEval to include a parameter which will allow it to terminate early? I just tested the calling functions without the loop. I was surprised the loop provides only 3% increase in speed. Also, what do you mean by \"keep primes you've calculated\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T23:43:04.793", "Id": "34832", "Score": "0", "body": "@JackJ, I'm suggesting you omit the loop. By keeping the primes, I mean that you should run sieve of erasthones once to find all the primes you need and use that data over and over again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-14T00:57:53.387", "Id": "34837", "Score": "0", "body": "@JackJ, store it in a variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-14T00:58:23.293", "Id": "34838", "Score": "0", "body": "Sorry, but how would I reuse that data? By saving the output of the sieve to a file? Also, is the reason for omitting the loop to increase readability?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T22:51:07.823", "Id": "21682", "ParentId": "21659", "Score": "2" } } ]
<p>I have to define a lot of values for a Python library, each of which will represent a statistical distribution (like the Normal distribution or Uniform distribution). They will contain describing features of the distribution (like the mean, variance, etc). After a distribution is created it doesn't really make sense to change it.</p> <p>I also expect other users to make their own distributions, simplicity is an extra virtue here.</p> <p>Scala has really nice syntax for classes in cases like this. Python seems less elegant, and I'd like to do better. </p> <p>Scala:</p> <pre><code>class Uniform(min : Double, max : Double) { def logp(x : Double) : Double = 1/(max - min) * between(x, min, max) def mean = (max + min)/2 } </code></pre> <p>Python:</p> <pre><code>class Uniform(object): def __init__(self, min, max): self.min = min self.max = max self.expectation = (max + min)/2 def logp(self, x): return 1/(self.max - self.min) * between(x, self.min, self.max) </code></pre> <p>It's not <em>terrible</em>, but it's not great. There are a lot of extra <code>self</code>s in there and the constructor part seems pretty boilerplate.</p> <p>One possibility is the following nonstandard idiom, a function which returns a dictionary of locals:</p> <pre><code>def Uniform(min, max): def logp(x): return 1/(max - min) * between(x, min, max) mean = (max + min)/2 return locals() </code></pre> <p>I like this quite a bit, but does it have serious drawbacks that aren't obvious?</p> <p>It returns a dict instead of an object, but that's good enough for my purposes and <a href="https://stackoverflow.com/questions/1305532/convert-python-dict-to-object">would be easy to fix with a that made it return an object</a>.</p> <p>Is there anything better than this? Are there serious problems with this?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T05:55:06.033", "Id": "21666", "Score": "10", "Tags": [ "python", "scala" ], "Title": "Scala inspired classes in Python" }
21666
max_votes
[ { "body": "<p>You might prefer to use <a href=\"http://docs.python.org/2/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a> for the attributes, and the <a href=\"http://docs.python.org/2/library/functions.html#property\" rel=\"nofollow noreferrer\"><code>property</code></a> decorator for <code>mean</code>. Note that <code>mean</code> is now computed every time it's accessed - maybe you don't want this, or maybe it makes sense since <code>max</code> and <code>min</code> are mutable.</p>\n\n<pre><code>from collections import namedtuple\n\nclass Uniform(namedtuple('Uniform', ('min', 'max'))):\n\n def logp(self, x):\n return 1/(self.max - self.min) * between(x, self.min, self.max)\n\n @property\n def mean(self):\n return 0.5*(self.min + self.max)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-14T17:17:47.343", "Id": "82630", "Score": "1", "body": "+1 but it's nicer to pass in the field names as a list of names though, not as a space separated string :) in fact I don't even know why the latter \"syntax\" is allowed in Python in the first place." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-02-13T06:18:37.220", "Id": "21668", "ParentId": "21666", "Score": "9" } } ]
<p>I have written a piece of python code in response to the following question and I need to know if it can be "tidied up" in any way. I am a beginner programmer and am starting a bachelor of computer science.</p> <blockquote> <p><strong>Question:</strong> Write a piece of code that asks the user to input 10 integers, and then prints the largest odd number that was entered. if no odd number was entered, it should print a message to that effect.</p> </blockquote> <p>My solution:</p> <pre><code>a = input('Enter a value: ') b = input('Enter a value: ') c = input('Enter a value: ') d = input('Enter a value: ') e = input('Enter a value: ') f = input('Enter a value: ') g = input('Enter a value: ') h = input('Enter a value: ') i = input('Enter a value: ') j = input('Enter a value: ') list1 = [a, b, c, d, e, f, g, h, i, j] list2 = [] # used to sort the ODD values into list3 = (a+b+c+d+e+f+g+h+i+j) # used this bc all 10 values could have used value'3' # and had the total value become an EVEN value if (list3 % 2 == 0): # does list 3 mod 2 have no remainder if (a % 2 == 0): # and if so then by checking if 'a' has an EVEN value it rules out # the possibility of all values having an ODD value entered print('All declared variables have even values') else: for odd in list1: # my FOR loop to loop through and pick out the ODD values if (odd % 2 == 1):# if each value tested has a remainder of one to mod 2 list2.append(odd) # then append that value into list 2 odd = str(max(list2)) # created the variable 'odd' for the highest ODD value from list 2 so i can concatenate it with a string. print ('The largest ODD value is ' + odd) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T21:02:21.650", "Id": "35021", "Score": "0", "body": "Thanks everyone for your input, i really appreciate that ! i will take a look at the extra code and try to understand how, where and why it fits in. !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T21:09:03.643", "Id": "35024", "Score": "17", "body": "If you have 10 lines that are pretty much the same chances are good that you are doing it wrong and want a loop instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T21:28:17.270", "Id": "35026", "Score": "1", "body": "great site great people ! :) whoever cant become a skilled programmer these days with all this help deserves to sit and wonder why they not moving forward.. thank you !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T02:00:32.880", "Id": "35040", "Score": "4", "body": "You seem to have a logic problem is your solution. Entering `2,1,1,2,2,2,2,2,2,2` returns `All declared variables have even values`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T07:21:04.357", "Id": "35049", "Score": "0", "body": "AHA . never saw that ! thought i had removed the logic error... good eye!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T11:07:09.847", "Id": "35057", "Score": "0", "body": "@Caramdir: I think this kind of comments should be answers. I'd upvote it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-19T04:16:35.020", "Id": "35170", "Score": "1", "body": "@palacsint at least we can up vote the comments 0:)" } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T19:07:26.577", "Id": "22784", "Score": "28", "Tags": [ "python", "beginner" ], "Title": "Asks the user to input 10 integers, and then prints the largest odd number" }
22784
max_votes
[ { "body": "<p>Here are a couple of places you might make your code more concise:</p>\n\n<p>First, lines 2-11 take a lot of space, and you repeat these values again below when you assign list1. You might instead consider trying to combine these lines into one step. A <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\">list comprehension</a> might allow you to perform these two actions in one step:</p>\n\n<pre><code>&gt;&gt;&gt; def my_solution():\n numbers = [input('Enter a value: ') for i in range(10)]\n</code></pre>\n\n<p>A second list comprehension might further narrow down your results by removing even values:</p>\n\n<pre><code> odds = [y for y in numbers if y % 2 != 0]\n</code></pre>\n\n<p>You could then see if your list contains any values. If it does not, no odd values were in your list. Otherwise, you could find the max of the values that remain in your list, which should all be odd:</p>\n\n<pre><code> if odds:\n return max(odds)\n else:\n return 'All declared variables have even values.'\n</code></pre>\n\n<p>In total, then, you might use the following as a starting point for refining your code:</p>\n\n<pre><code>&gt;&gt;&gt; def my_solution():\n numbers = [input('Enter a value: ') for i in range(10)]\n odds = [y for y in numbers if y % 2 != 0]\n if odds:\n return max(odds)\n else:\n return 'All declared variables have even values.'\n\n\n&gt;&gt;&gt; my_solution()\nEnter a value: 10\nEnter a value: 101\nEnter a value: 48\nEnter a value: 589\nEnter a value: 96\nEnter a value: 74\nEnter a value: 945\nEnter a value: 6\nEnter a value: 3\nEnter a value: 96\n945\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T21:35:24.023", "Id": "35028", "Score": "2", "body": "Good answer, but `if len(list2) != []:` is not really pythonic. You could simply do: `if len(list2):`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T22:18:00.027", "Id": "35030", "Score": "1", "body": "Welcome to Code Review and thanks for the excellent answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T22:34:17.333", "Id": "35031", "Score": "0", "body": "Thanks to you both for sharing your knowledge and improvements. I updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T23:37:45.727", "Id": "35034", "Score": "8", "body": "@Zenon couldn't you just do `if list2:`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T08:08:14.357", "Id": "35050", "Score": "1", "body": "@SnakesandCoffee yes you could and shouldd, because it's much better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T10:27:11.087", "Id": "35110", "Score": "0", "body": "@user1775603 A micro optimization to test whether a number is odd is y & 1 == 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:35:10.643", "Id": "58320", "Score": "0", "body": "For further optimisation, generators and trys could replace lists and conditionals: `n = (input('Enter..') for i in xrange(10))` and `o = (y for y in n if n%2)`. `try: return max(o)` `except ValueError: return 'All declared...'`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:42:03.050", "Id": "58324", "Score": "0", "body": "This gist shows the above changes. https://gist.github.com/ejrb/7581712" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T20:55:48.690", "Id": "22793", "ParentId": "22784", "Score": "31" } } ]
<p>I have been trying to make a simple "quiz" program in Python. What I plan to make is, say, a quiz of 3 rounds and each round having 3 questions. And at the end of the every round, the program will prompt the user to go for the "bonus" question or not.</p> <pre><code>print("Mathematics Quiz") question1 = "Who is president of USA?" options1 = "a.Myslef\nb. His dad\nc. His mom\nd. Barack Obama\n" print(question1) print(options1) while True: response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n") if response == "d": break else: print("Incorrect!!! Try again.") while True: response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n") if response == "d": stop = True break else: print("Incorrect!!! You ran out of your attempts") stop = True break if stop: break # DO the same for the next questions of your round (copy-paste-copy-paste). # At the end of the round, paste the following code for the bonus question. # Now the program will ask the user to go for the bonus question or not while True: bonus = input("Would you like to give a try to the bonus question?\nHit 'y' for yes and 'n' for no.\n") if bonus == "y": print("Who invented Facebook?") print("a. Me\nb. His dad\nc. Mark Zuckerberg\nd. Aliens") while True: response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n") if response == "c": break else: print("Incorrect!!! Try again.") while True: response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n") if response == "c": stop = True break else: print("Incorrect!!! You ran out of your attempts") stop = True break if stop: break break elif bonus == "n": break else: print("INVALID INPUT!!! Only hit 'y' or 'n' for your response") # Now do the same as done above for the next round and another bonus question. </code></pre> <p>Now this code is very long for a single question and I don't think this is the "true" programming. I don't want to copy-paste it again and again. I was wondering is there any way to shorten the code using <code>class</code> or defining functions or something like that?</p>
[]
{ "AcceptedAnswerId": "22825", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T12:25:37.470", "Id": "22822", "Score": "3", "Tags": [ "python", "quiz" ], "Title": "Simple quiz program" }
22822
accepted_answer
[ { "body": "<pre><code>import string\n\nNUMBER_OF_ATTEMPTS = 2\nENTER_ANSWER = 'Hit %s for your answer\\n'\nTRY_AGAIN = 'Incorrect!!! Try again.'\nNO_MORE_ATTEMPTS = 'Incorrect!!! You ran out of your attempts'\n\ndef question(message, options, correct, attempts=NUMBER_OF_ATTEMPTS):\n '''\n message - string \n options - list\n correct - int (Index of list which holds the correct answer)\n attempts - int\n '''\n optionLetters = string.ascii_lowercase[:len(options)]\n print message\n print ' '.join('%s: %s' % (letter, answer) for letter, answer in zip(optionLetters, options))\n while attempts &gt; 0:\n response = input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 3\n #response = raw_input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 2\n if response == optionLetters[correct]:\n return True\n else:\n attempts -= 1\n print TRY_AGAIN\n\n print NO_MORE_ATTEMPTS\n return False\n\n\nprint(\"Mathematics Quiz\")\n\n# question1 and question2 will be 'True' or 'False' \nquestion1 = question('Who is president of USA?', ['myself', 'His Dad', 'His Mom', 'Barack Obama'], 3)\nquestion2 = question('Who invented Facebook?', ['Me', 'His Dad', 'Mark Zuckerberg', 'Aliens', 'Someone else'], 2)\n</code></pre>\n\n<p>I'm not sure which python you are using. Try both line 20 or line 21 to see which works best for you. </p>\n\n<p>Overall this function allows you to enter in questions with as many responses as you want and it will do the rest for you.</p>\n\n<p>Good luck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T14:32:26.023", "Id": "35070", "Score": "0", "body": "Thank you. It worked. Only I had to change `string.lowercase` to `string.ascii_lowercase` since I am using Python 3x. I think I need some good practice with defining functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T14:56:31.683", "Id": "35071", "Score": "0", "body": "Good spot, I updated my answer. Seems both Python 2 and 3 have ascii_lowercase, but lowercase got removed in 3. Indeed use functions where ever you can." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T16:03:20.920", "Id": "35074", "Score": "0", "body": "You still skipped the print parentheses at these places: \n`print(message)`, `print` statement below that, `print` statements after `attempts -=1`. I apologize for not mentioning them before." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T14:13:41.547", "Id": "22825", "ParentId": "22822", "Score": "4" } } ]
<p>I have just started to learn programming with Python. I have been going through several online classes for the last month or two. Please bear with me if my questions are noobish.</p> <p>One of the classes I am taking asked us to solve this problem.</p> <pre><code># Define a procedure, check_sudoku, # that takes as input a square list # of lists representing an n x n # sudoku puzzle solution and returns the boolean # True if the input is a valid # sudoku square and returns the boolean False # otherwise. # A valid sudoku square satisfies these # two properties: # 1. Each column of the square contains # each of the whole numbers from 1 to n exactly once. # 2. Each row of the square contains each # of the whole numbers from 1 to n exactly once. # You may assume the the input is square and contains at # least one row and column. </code></pre> <p>After a while of trying to come up with the best code I can, this is what I ended up with.</p> <pre><code>def check_sudoku(sudlist): x = range(1, len(sudlist)+1) # makes a list of each number to be found rows = [[row[i] for row in sudlist] for i in range(len(sudlist))] # assigns all the rows to a flat list z = range(len(sudlist)) for num in x: for pos in z: if num not in sudlist[pos] or num not in rows[pos]: return False return True </code></pre> <p>This code does work and passed all checks the class asked for. I just wonder what problems could the code have or how would you improve it?</p> <p>I am just trying to improve by getting input from others. I appreciate any suggestions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T22:58:29.257", "Id": "35094", "Score": "0", "body": "The problem seems poorly stated. A Sudoku grid has *three* types of constraint: rows, columns, and *blocks*. A grid that only has row and column constraints is known as a [Latin square](http://en.wikipedia.org/wiki/Latin_square)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T21:28:47.017", "Id": "22834", "Score": "5", "Tags": [ "python", "beginner", "sudoku" ], "Title": "Check_sudoku in Python" }
22834
max_votes
[ { "body": "<p>I would use <a href=\"http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset\"><code>set</code></a> to do the checks, and you can build the columns using some <a href=\"http://docs.python.org/2/library/functions.html#zip\"><code>zip</code></a> magic:</p>\n\n<pre><code>def check_sudoku(sudlist) :\n numbers = set(range(1, len(sudlist) + 1))\n if (any(set(row) != numbers for row in sudlist) or\n any(set(col) != numbers for col in zip(*sudlist))) :\n return False\n return True\n</code></pre>\n\n<p>I have tested it with the following samples:</p>\n\n<pre><code>a = [[1, 2, 3, 4, 5],\n [2, 3, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [5, 4, 1, 3, 2]] # latin square\n\nb = [[1, 2, 3, 4, 5],\n [2, 3, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [3, 4, 1, 5, 2]] # 1st and 4th elements of last row interchanged\n\nc = [[1, 2, 3, 4, 5],\n [2, 4, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [5, 3, 1, 3, 2]] #1st and 5th elements of second column intechanged\n\n\n&gt;&gt;&gt; check_sudoku(a)\nTrue\n&gt;&gt;&gt; check_sudoku(b)\nFalse\n&gt;&gt;&gt; check_sudoku(c)\nFalse\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T23:58:31.987", "Id": "22841", "ParentId": "22834", "Score": "8" } } ]
<p>I have just started to learn programming with Python. I have been going through several online classes for the last month or two. Please bear with me if my questions are noobish.</p> <p>One of the classes I am taking asked us to solve this problem.</p> <pre><code># Define a procedure, check_sudoku, # that takes as input a square list # of lists representing an n x n # sudoku puzzle solution and returns the boolean # True if the input is a valid # sudoku square and returns the boolean False # otherwise. # A valid sudoku square satisfies these # two properties: # 1. Each column of the square contains # each of the whole numbers from 1 to n exactly once. # 2. Each row of the square contains each # of the whole numbers from 1 to n exactly once. # You may assume the the input is square and contains at # least one row and column. </code></pre> <p>After a while of trying to come up with the best code I can, this is what I ended up with.</p> <pre><code>def check_sudoku(sudlist): x = range(1, len(sudlist)+1) # makes a list of each number to be found rows = [[row[i] for row in sudlist] for i in range(len(sudlist))] # assigns all the rows to a flat list z = range(len(sudlist)) for num in x: for pos in z: if num not in sudlist[pos] or num not in rows[pos]: return False return True </code></pre> <p>This code does work and passed all checks the class asked for. I just wonder what problems could the code have or how would you improve it?</p> <p>I am just trying to improve by getting input from others. I appreciate any suggestions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T22:58:29.257", "Id": "35094", "Score": "0", "body": "The problem seems poorly stated. A Sudoku grid has *three* types of constraint: rows, columns, and *blocks*. A grid that only has row and column constraints is known as a [Latin square](http://en.wikipedia.org/wiki/Latin_square)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T21:28:47.017", "Id": "22834", "Score": "5", "Tags": [ "python", "beginner", "sudoku" ], "Title": "Check_sudoku in Python" }
22834
max_votes
[ { "body": "<p>I would use <a href=\"http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset\"><code>set</code></a> to do the checks, and you can build the columns using some <a href=\"http://docs.python.org/2/library/functions.html#zip\"><code>zip</code></a> magic:</p>\n\n<pre><code>def check_sudoku(sudlist) :\n numbers = set(range(1, len(sudlist) + 1))\n if (any(set(row) != numbers for row in sudlist) or\n any(set(col) != numbers for col in zip(*sudlist))) :\n return False\n return True\n</code></pre>\n\n<p>I have tested it with the following samples:</p>\n\n<pre><code>a = [[1, 2, 3, 4, 5],\n [2, 3, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [5, 4, 1, 3, 2]] # latin square\n\nb = [[1, 2, 3, 4, 5],\n [2, 3, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [3, 4, 1, 5, 2]] # 1st and 4th elements of last row interchanged\n\nc = [[1, 2, 3, 4, 5],\n [2, 4, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [5, 3, 1, 3, 2]] #1st and 5th elements of second column intechanged\n\n\n&gt;&gt;&gt; check_sudoku(a)\nTrue\n&gt;&gt;&gt; check_sudoku(b)\nFalse\n&gt;&gt;&gt; check_sudoku(c)\nFalse\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T23:58:31.987", "Id": "22841", "ParentId": "22834", "Score": "8" } } ]
<p>Here I have some simple code that worries me, look at the second to last line of code, I have to return spam in order to change spam in the global space. Also is it bad to be writing code in this space and I should create a function or class to call from that space which contains most my code?</p> <p>I found out very recently that I never even understood the differences between Python's identifiers compared to C or C++'s variables. This helps put into perspective why I always have so many errors in Python.</p> <p>I do not want to continue writing code and get into a bad habit and this is why I want your opinion.</p> <p>I also have a tendency to do things like <code>spam = fun()</code> because I do not know how to correctly make Python call a function which changes a variable in the scope of where the function was called. Instead I simply return things from the functions never learning how to correctly write code, I want to change that as soon as possible.</p> <pre><code>import random MAX = 20 def randomize_list(the_list, x=MAX): for i in range(len(the_list)): the_list[i] = random.randint(1, x) def lengthen_list(the_list, desired_length, x=MAX): if len(the_list) &gt;= desired_length: print "erroneous call to lengthen_list(), desired_length is too small" return the_list while(len(the_list) &lt; desired_length): the_list.append(random.randint(1, x)) # organize the_set the_list = set(the_list) the_list = list(the_list) return the_list spam = list(range(10)) randomize_list(spam, MAX) print "the original list:" print spam, '\n' spam = set(spam) spam = list(spam) print "the set spam:" print spam print "the set spam with length 10" spam = lengthen_list(spam, 10, MAX) print spam </code></pre> <p>Please help me adopt a style which correctly fixes, in particular, the second to last line of code so that I do not need the function to do return things in order to work, if this is even possible.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:07:22.220", "Id": "35318", "Score": "0", "body": "Well, I am not a python expert and this is more like my general convention than python convention. You should not reuse variable name. For example, set(spam) and list(spam) should not be assign to the same variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:14:50.947", "Id": "35319", "Score": "0", "body": "@Tg. Yes I know what you mean. The point of the code I think you are talking about changes spam to a set and then back to a list. This is a quick and dirty way of removing repetitious values in the list and organizing them least to greatest in value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:28:26.850", "Id": "35321", "Score": "1", "body": "Well, others already comment on most of your concern. For about your quick and dirty way, here is the better version.\n\nuniqSpam = list(set(spam))\n\nYou should avoid any one-time-use intermediate variable if it does not cluttering much on the right hand side." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-24T14:06:50.190", "Id": "306783", "Score": "0", "body": "Since you wrote this question, our standards have been updated. Could you read [ask] and update your question to match what it is now?" } ]
{ "AcceptedAnswerId": "22952", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T04:57:04.963", "Id": "22951", "Score": "2", "Tags": [ "python" ], "Title": "What parts of my Python code are adopting a poor style and why?" }
22951
accepted_answer
[ { "body": "<blockquote>\n <p>I also have a tendency to do things like spam = fun() because I do not\n know how to correctly make Python call a function which changes a\n variable in the scope of where the function was called.</p>\n</blockquote>\n\n<p>You can't. You cannot replace a variable in an outer scope. So in your case, you cannot replace the list with a new list, although you can modify the list. To make it clear</p>\n\n<pre><code>variable = expression\n</code></pre>\n\n<p>replaces a variable, whereas pretty much anything else:</p>\n\n<pre><code>variable[:] = expression\nvariable.append(expression)\ndel variable[:]\n</code></pre>\n\n<p>Modifies the object. The bottom three will take effect across all references to the object. Whereas the one before replaces the object with another one and won't affect any other references.</p>\n\n<p>Stylistically, it somestimes makes sense to have a function modify a list, and other times it makes sense for a function to return a whole new list. What makes sense depends on the situation. The one rule I'd pretty much always try to follow is to not do both. </p>\n\n<pre><code>def randomize_list(the_list, x=MAX):\n for i in range(len(the_list)):\n the_list[i] = random.randint(1, x)\n</code></pre>\n\n<p>This isn't a good place to use a modified list. The incoming list is ignored except for the length. It'd be more useful as a function that returns a a new list given a size something like:</p>\n\n<pre><code>def random_list(length, maximum = MAX):\n random_list = []\n for _ in range(length):\n random_list.append( random.randint(1, maximum) )\n return random_list\n\ndef lengthen_list(the_list, desired_length, x=MAX):\n if len(the_list) &gt;= desired_length:\n print \"erroneous call to lengthen_list(), desired_length is too small\"\n</code></pre>\n\n<p>Don't report errors by print, raise an exception</p>\n\n<pre><code> raise Exception(\"erroneous call...\")\n\n\n return the_list\n while(len(the_list) &lt; desired_length):\n the_list.append(random.randint(1, x))\n # organize the_set\n the_list = set(the_list)\n the_list = list(the_list)\n</code></pre>\n\n<p>That's not an efficient way to do that. You constantly convert back between a list and set. Instead do something like</p>\n\n<pre><code> new_value = random.randint(1, maximum)\n if new_value not in the_list:\n the_list.append(new_value)\n</code></pre>\n\n<p>That way you avoid the jumping back and forth, and it also modifies the original object rather then creating a new list.</p>\n\n<pre><code> return the_list\n</code></pre>\n\n<p>This particular function could go either way in terms of modifying or returning the list. Its a judgement call which way to go. </p>\n\n<blockquote>\n <p>Also is it bad to be writing code in this space and I should create a\n function or class to call from that space which contains most my code?</p>\n</blockquote>\n\n<p>Yes, you should really put everything in a function and not at the main level for all but the most trivial scripts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:21:29.633", "Id": "35320", "Score": "0", "body": "I have not seen code like yours such as: `for _ in range(length):`, does the underscore just mean that we are not going to use some value from the range, we are instead going to do something `length` times?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T11:03:38.803", "Id": "35331", "Score": "0", "body": "@Leonardo: yes, it's conventional to use `_` for a loop variable that's otherwise unused. See [here](http://stackoverflow.com/q/1739514/68063) or [here](http://stackoverflow.com/q/5893163/68063)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:16:23.067", "Id": "22952", "ParentId": "22951", "Score": "4" } } ]
<p>I needed short, unique, seemingly random URLs for a project I'm working on, so I put together the following after some research. I believe it's working as expected, but I want to know if there's a better or simpler way of doing this. Basically, it takes an integer and returns a string of the specified length using the character list. I'm new to Python, so help is much appreciated.</p> <pre><code>def genkey(value, length=5, chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', prime=694847539): digits = [] base = len(chars) seed = base ** (length - 1) domain = (base ** length) - seed num = ((((value - 1) + seed) * prime) % domain) + seed while num: digits.append(chars[num % base]) num /= base return ''.join(reversed(digits)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T08:18:10.170", "Id": "35328", "Score": "1", "body": "Without knowing your concrete requirements: What do you think about hashing your value and take the first x characters? Maybe you will need some additional checking for duplicates." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T16:33:51.083", "Id": "35366", "Score": "0", "body": "@mnhg I thought about that as well. This sort of became an exercise for its own sake at some point. How would you suggest handling duplicates?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T05:02:15.627", "Id": "35444", "Score": "0", "body": "As this seems not performance critical, I would simple check the existing in the indexed database column that is storing the short url mapping. (Might also be a hashmap.) If I find a conflict I would a attached the current time/spaces/whatever and try it again or just rehash the hash once again." } ]
{ "AcceptedAnswerId": "22957", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:51:44.350", "Id": "22954", "Score": "6", "Tags": [ "python" ], "Title": "Unique short string for URL" }
22954
accepted_answer
[ { "body": "<p>The trouble with using a pseudo-random number generator to produce your shortened URLs is, <em>what do you do if there is a collision?</em> That is, what happens if there are values <code>v</code> and <code>w</code> such that <code>v != w</code> but <code>genkey(v) == genkey(w)</code>? Would this be a problem for your application, or would it be entirely fine?</p>\n\n<p>Anyway, if I didn't need to solve the collision problem, I would use Python's <a href=\"http://docs.python.org/2/library/random.html\" rel=\"nofollow\">built-in pseudo-random number generator</a> for this instead of writing my own. Also, I would add a docstring and some <a href=\"http://docs.python.org/2/library/doctest.html\" rel=\"nofollow\">doctests</a>.</p>\n\n<pre><code>import random\nimport string\n\ndef genkey(value, length = 5, chars = string.ascii_letters + string.digits):\n \"\"\"\n Return a string of `length` characters chosen pseudo-randomly from\n `chars` using `value` as the seed.\n\n &gt;&gt;&gt; ' '.join(genkey(i) for i in range(5))\n '0UAqF i0VpE 76dfZ oHwLM ogyje'\n \"\"\"\n random.seed(value)\n return ''.join(random.choice(chars) for _ in xrange(length))\n</code></pre>\n\n<p><strong>Update:</strong> you clarified in comments that you <em>do</em> need to avoid collisions, and moreover you know that <code>value</code> is a number between 1 and <code>domain</code> inclusive. In that case, you're right that your transformation is an injection, since <code>prime</code> is coprime to <code>domain</code>, so your method is fine, but there are several things that can be done to simplify it:</p>\n\n<ol>\n<li><p>As far as I can see, there's no need to subtract 1 from <code>value</code>.</p></li>\n<li><p>There's no need to use the value <code>seed</code> at all. You're using this to ensure that you have at least <code>length</code> digits in <code>num</code>, but it's easier just to generate exactly <code>length</code> digits. (This gives you a bigger domain in any case.)</p></li>\n<li><p>There's no need to call <code>reversed</code>: the reverse of a pseudo-random string is also a pseudo-random string.</p></li>\n</ol>\n\n<p>Applying all those simplifications yields the following:</p>\n\n<pre><code>def genkey(value, length=5, chars=string.ascii_letters + string.digits, prime=694847539):\n \"\"\"\n Return a string of `length` characters chosen pseudo-randomly from\n `chars` using `value` as the seed and `prime` as the multiplier.\n `value` must be a number between 1 and `len(chars) ** length`\n inclusive.\n\n &gt;&gt;&gt; ' '.join(genkey(i) for i in range(1, 6))\n 'xKFbV UkbdG hVGer Evcgc 15HhX'\n \"\"\"\n base = len(chars)\n domain = base ** length\n assert(1 &lt;= value &lt;= domain)\n n = value * prime % domain\n digits = []\n for _ in xrange(length):\n n, c = divmod(n, base)\n digits.append(chars[c])\n return ''.join(digits)\n</code></pre>\n\n<p>A couple of things you might want to beware of:</p>\n\n<ol>\n<li><p>This pseudo-random scheme is not cryptographically strong: that is, it's fairly easy to go back from the URL to the value that produced it. This can be a problem in some applications.</p></li>\n<li><p>The random strings produced by this scheme may include real words or names in human languages. This could be unfortunate in some applications, if the resulting words were offensive or otherwise inappropriate.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T16:29:09.780", "Id": "35365", "Score": "0", "body": "With the system I have in place now, collisions would be a problem. I'm under the impression that the code I wrote would not produce collisions for values within the `domain` (901,356,496 for length=5 and base=62). Do you know of any ways to test this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T20:44:47.753", "Id": "35399", "Score": "0", "body": "Thanks for the great in-depth answer. How would you go about getting the initial value from the URL?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T20:49:18.643", "Id": "35401", "Score": "0", "body": "[Extended Euclidean algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T11:25:57.170", "Id": "22957", "ParentId": "22954", "Score": "5" } } ]
<p>This code loads the data for <a href="http://projecteuler.net/problem=18" rel="nofollow">Project Euler problem 18</a>, but I feel that there must be a better way of writing it. Maybe with a double list comprehension, but I couldn't figure out how I might do that. It is a lot more difficult since the rows to split up are not uniform in length.</p> <pre><code>def organizeVar(): triangle = "\ 75,\ 95 64,\ 17 47 82,\ 18 35 87 10,\ 20 04 82 47 65,\ 19 01 23 75 03 34,\ 88 02 77 73 07 63 67,\ 99 65 04 28 06 16 70 92,\ 41 41 26 56 83 40 80 70 33,\ 41 48 72 33 47 32 37 16 94 29,\ 53 71 44 65 25 43 91 52 97 51 14,\ 70 11 33 28 77 73 17 78 39 68 17 57,\ 91 71 52 38 17 14 91 43 58 50 27 29 48,\ 63 66 04 68 89 53 67 30 73 16 69 87 40 31,\ 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23" triangle = [row for row in list(triangle.split(","))] adjTriangle = [] for row in range(len(triangle)): adjTriangle.append([int(pos) for pos in triangle[row].split(" ")]) return adjTriangle </code></pre> <p>The code converts this string into a list of lists of <code>int</code>s where the first list contains 75, the second list 95, 64, the third list 17, 47, 82, the fourth list 18, 35, 87, 10 and so on to the bottom row.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T13:28:28.237", "Id": "35340", "Score": "0", "body": "Also there's no need to `list()` the `trianle.split(\",\")`, `split` will *always* return a list." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T12:25:39.773", "Id": "22959", "Score": "2", "Tags": [ "python", "programming-challenge" ], "Title": "Organizing a long string into a list of lists" }
22959
max_votes
[ { "body": "<ol>\n<li><p>Avoid the need to escape the newlines by using Python's <a href=\"http://docs.python.org/2/reference/lexical_analysis.html#string-literals\" rel=\"nofollow\">triple-quoted strings</a> that can extend over multiple lines:</p>\n\n<pre><code>triangle = \"\"\"\n75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 38 17 14 91 43 58 50 27 29 48\n63 66 04 68 89 53 67 30 73 16 69 87 40 31\n04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n\"\"\"\n</code></pre></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.strip\" rel=\"nofollow\"><code>strip</code> method</a> to remove the whitespace at the beginning and end.</p></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.splitlines\" rel=\"nofollow\"><code>splitlines</code> method</a> to split the string into lines.</p></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.split\" rel=\"nofollow\"><code>split</code> method</a> to split each line into words.</p></li>\n<li><p>Use the built-in <a href=\"http://docs.python.org/2/library/functions.html#map\" rel=\"nofollow\"><code>map</code> function</a> to call <code>int</code> on each word.</p></li>\n</ol>\n\n<p>Putting that all together in a list comprehension:</p>\n\n<pre><code>&gt;&gt;&gt; [map(int, line.split()) for line in triangle.strip().splitlines()]\n[[75],\n [95, 64],\n [17, 47, 82],\n [18, 35, 87, 10],\n [20, 4, 82, 47, 65],\n [19, 1, 23, 75, 3, 34],\n [88, 2, 77, 73, 7, 63, 67],\n [99, 65, 4, 28, 6, 16, 70, 92],\n [41, 41, 26, 56, 83, 40, 80, 70, 33],\n [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],\n [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],\n [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],\n [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],\n [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],\n [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]\n</code></pre>\n\n<p>In Python 3 <code>map</code> doesn't return a list, so you have to write</p>\n\n<pre><code>[list(map(int, line.split())) for line in triangle.strip().splitlines()]\n</code></pre>\n\n<p>instead. If you prefer a double list comprehension you can write it like this:</p>\n\n<pre><code>[[int(word) for word in line.split()] for line in triangle.strip().splitlines()]\n</code></pre>\n\n<p>but the version with <code>map</code> is shorter, and, I think, clearer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T12:51:38.207", "Id": "35337", "Score": "0", "body": "Wow, that is awesome. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:46:43.270", "Id": "35409", "Score": "0", "body": "Using Python 3.3 I haven't quite gotten this to work. The closest I get while trying to use the map form is:`[line.strip().split(' ') for line in triangle.strip().splitlines()]`. This returns everything correctly except ints. When I try to use map, as in `map(int, line.strip().split(' ')` or even just `map(int, line.split())` I get a bunch of these: `<map object at 0x0000000002F469E8>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:52:31.480", "Id": "35410", "Score": "0", "body": "See revised answer. (Also, it's usually better to write `.split()` instead of `.split(\" \")` unless you really want `'a  b'` to split into `['a', '', 'b']`.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:03:15.463", "Id": "35412", "Score": "0", "body": "I think also, if you try to put this into a function, you have to strip it twice; once for the two outside lines, and once for the indentation. If you don't, map will try to turn the extra space into ints, but will give an error when that happens... I didn't read your above comment in time. Alternatively I could just do that .split() to make it work. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:07:03.840", "Id": "35414", "Score": "0", "body": "No, that's not necessary: `' a b '.split()` → `['a', 'b']`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T12:48:47.570", "Id": "22960", "ParentId": "22959", "Score": "4" } } ]
<p>I have a grid as </p> <pre><code>&gt;&gt;&gt; data = np.zeros((3, 5)) &gt;&gt;&gt; data array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]] </code></pre> <p>i wrote a function in order to get the ID of each tile.</p> <pre><code>array([[(0,0), (0,1), (0,2), (0,3), (0,4)], [(1,0), (1,1), (1,2), (1,3), (1,4)], [(2,0), (2,1), (2,2), (2,3), (2,4)]] def get_IDgrid(nx,ny): lstx = list() lsty = list() lstgrid = list() for p in xrange(ny): lstx.append([p]*nx) for p in xrange(ny): lsty.append(range(0,nx)) for p in xrange(ny): lstgrid.extend(zip(lstx[p],lsty[p])) return lstgrid </code></pre> <p>where nx is the number of columns and ny the number of rows</p> <pre><code>test = get_IDgrid(5,3) print test [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)] </code></pre> <p>this function will be embed inside a class</p> <pre><code>class Grid(object): __slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell") def __init__(self,xMin,yMax,nx,ny,xDist,yDist): self.xMin = xMin self.yMax = yMax self.nx = nx self.ny = ny self.xDist = xDist self.yDist= yDist self.ncell = nx*ny </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:28:44.323", "Id": "35382", "Score": "2", "body": "Good question. The only thing I'd suggest is actually having `get_IDgrid` in the class rather than saying that it will be embedded." } ]
{ "AcceptedAnswerId": "22973", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T16:33:57.390", "Id": "22968", "Score": "1", "Tags": [ "python", "optimization", "performance" ], "Title": "python Improve a function in a elegant way" }
22968
accepted_answer
[ { "body": "<p>Numpy has built in functions for most simple tasks like this one. In your case, <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html\" rel=\"nofollow\"><code>numpy.ndindex</code></a> should do the trick:</p>\n\n<pre><code>&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; [j for j in np.ndindex(3, 5)]\n[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]\n</code></pre>\n\n<p>You can get the same result in a similarly compact way using <a href=\"http://docs.python.org/2/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a> :</p>\n\n<pre><code>&gt;&gt;&gt; import itertools\n&gt;&gt;&gt; [j for j in itertools.product(xrange(3), xrange(5))]\n[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]\n</code></pre>\n\n<p><strong>EDIT</strong> Note that the (now corrected) order of the parameters is reversed with respect to the OP's <code>get_IDgrid</code>.</p>\n\n<p>Both expressions above require a list comprehension, because what gets returned is a generator. You may want to consider whether you really need the whole list of index pairs, or if you could consume them one by one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:28:55.673", "Id": "35374", "Score": "0", "body": "Thanks @jaime. Do you think insert the def of [j for j in np.ndindex(5, 3)] in the class can be correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:33:07.450", "Id": "35376", "Score": "0", "body": "@Gianni It is kind of hard to tell without knowing what exactly you are trying to accomplish. I can't think of any situation in which I would want to store a list of all possible indices to a numpy array, but if you really do need it, then I guess it is OK." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:34:34.857", "Id": "35379", "Score": "0", "body": "@jamie with [j for j in np.ndindex(5, 3)] return a different result respect my function and the Grid (see the example). Just invert the example :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:47:24.460", "Id": "35381", "Score": "1", "body": "@Gianni I did notice that, it is now corrected. What `np.ndindex` does is what is known as [row major order](http://en.wikipedia.org/wiki/Row-major_order) arrays, which is the standard in C language, and the default in numpy. What your function is doing is column major order, which is the Fortran and Matlab way. If you are using numpy, it will probably make your life easier if you stick to row major." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:27:13.847", "Id": "22973", "ParentId": "22968", "Score": "4" } } ]
<p>I wrote function to generate nearly sorted numbers:</p> <pre><code>def nearly_sorted_numbers(n): if n &gt;= 100: x = (int)(n/10) elif n &gt;= 10: x = 9 else: x = 4 numbers = [] for i in range(1,n): if i%x==0: numbers.append(random.randint(0,n)) else: numbers.append(i) return numbers </code></pre> <p>Have you any idea how improve my code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T19:58:55.010", "Id": "35394", "Score": "0", "body": "What's the purpose of this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T20:26:58.053", "Id": "35398", "Score": "0", "body": "I want to make performance test for sorting algorithms and this function should prepare input data according to x parameter (length of input data)." } ]
{ "AcceptedAnswerId": "22982", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:33:46.550", "Id": "22974", "Score": "2", "Tags": [ "python" ], "Title": "Function to generate nearly sorted numbers" }
22974
accepted_answer
[ { "body": "<pre><code>def nearly_sorted_numbers(n):\n if n &gt;= 100:\n x = (int)(n/10)\n</code></pre>\n\n<p>Use <code>int(n//10)</code>, the <code>//</code> explicitly request integer division and python doesn't have casts</p>\n\n<pre><code> elif n &gt;= 10:\n x = 9\n else:\n x = 4 \n</code></pre>\n\n<p>I wouldn't name the variable <code>x</code>, as it gives no hint as to what it means. I'd also wonder whether it wouldn't be better as a parameter to this function. It seems out of place to be deciding that here.</p>\n\n<pre><code> numbers = [] \n for i in range(1,n):\n if i%x==0: \n numbers.append(random.randint(0,n))\n else:\n numbers.append(i)\nreturn numbers\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T21:20:33.740", "Id": "22982", "ParentId": "22974", "Score": "1" } } ]
<p>first of all sorry for this easy question. I have a class</p> <pre><code>class Grid(object): __slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell","IDtiles") def __init__(self,xMin,yMax,nx,ny,xDist,yDist): self.xMin = xMin self.yMax = yMax self.nx = nx self.ny = ny self.xDist = xDist self.yDist= yDist self.ncell = nx*ny self.IDtiles = [j for j in np.ndindex(ny, nx)] if not isinstance(nx, int) or not isinstance(ny, int): raise TypeError("an integer is required for nx and ny") </code></pre> <p>where</p> <pre><code>xMin = minimum x coordinate (left border) yMax = maximum y coordinate (top border) nx = number of columns ny = number of rows xDist and yDist = resolution (e.g., 1 by 1) </code></pre> <p>nx and ny need to be an integer. I wish to ask where is the most elegant position for the TypeError. Before all self. or in the end?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:40:58.530", "Id": "35384", "Score": "0", "body": "Ideally, you should write your whole Grid class and then show it to us. Then we'd suggest all the ways in which it could be improved rather then asking lots of specific questions." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:17:04.027", "Id": "22977", "Score": "1", "Tags": [ "python", "optimization" ], "Title": "Python right position for a Error message in a class" }
22977
max_votes
[ { "body": "<pre><code>class Grid(object):\n __slots__= (\"xMin\",\"yMax\",\"nx\",\"ny\",\"xDist\",\"yDist\",\"ncell\",\"IDtiles\")\n def __init__(self,xMin,yMax,nx,ny,xDist,yDist):\n</code></pre>\n\n<p>Python convention says that argument should be lowercase_with_underscores</p>\n\n<pre><code> self.xMin = xMin\n self.yMax = yMax\n</code></pre>\n\n<p>The same convention holds for your object attributes</p>\n\n<pre><code> self.nx = nx\n self.ny = ny\n self.xDist = xDist\n self.yDist= yDist\n self.ncell = nx*ny\n self.IDtiles = [j for j in np.ndindex(ny, nx)]\n</code></pre>\n\n<p>This is the same as <code>self.IDtiles = list(np.ndindex(ny,nx))</code></p>\n\n<pre><code> if not isinstance(nx, int) or not isinstance(ny, int):\n raise TypeError(\"an integer is required for nx and ny\")\n</code></pre>\n\n<p>This would be more conventialy put at the top. But in python we prefer duck typing, and don't check types. You shouldn't really be checking the types are correct. Just trust that the user of the class will pass the right type or something close enough.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:45:17.073", "Id": "35385", "Score": "0", "body": "Thanks @Winston Ewert. I didn't get about \"duck typing\". Do you suggest to avoid the \"TypeError\"? and the argument should be lowercase_with_underscores do you intend example self.__xMin = xMin?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:49:02.503", "Id": "35386", "Score": "1", "body": "@Gianni, xMin should be x_min. There should be no capital letters in your names. Basically, only class names are named using capital letters. Re: duck typing. Just don't throw the TypeError. The python convention is to not check the types and just allow exceptions to be thrown when the type is used in an invalid manner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:58:11.073", "Id": "35387", "Score": "0", "body": "Thank Winston really useful post for me. I have just the last question to clarify my doubts. inside a class if i have a function def get_distance_to_origin(xPoint,yPoint):\n#do some stuff (es euclidean distance). Do i need to write x_point and y_point in order to respect the style?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T19:00:47.677", "Id": "35388", "Score": "0", "body": "@Gianni, yes, that is correct" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:40:14.643", "Id": "22978", "ParentId": "22977", "Score": "1" } } ]
<p>I'm starting to learn Python and am trying to optimize this bisection search game.</p> <pre><code>high = 100 low = 0 guess = (high + low)/2 print('Please think of a number between 0 and 100!') guessing = True while guessing: print('Is your secret number ' + str(guess) + '?') pointer = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if pointer == 'h': high = guess guess = (low + guess)/2 elif pointer == 'l': low = guess guess = (high + guess)/2 elif pointer == 'c': guessing = False else: print('Sorry, I did not understand your input.') print('Game over. Your secret number was: ' + str(guess)) </code></pre>
[]
{ "AcceptedAnswerId": "22992", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:01:04.830", "Id": "22984", "Score": "6", "Tags": [ "python", "beginner", "number-guessing-game" ], "Title": "Bisection search game" }
22984
accepted_answer
[ { "body": "<p>Some things I think would improve your code, which is quite correct:</p>\n\n<ul>\n<li>Having variables for <code>high</code> and <code>low</code>, you shouldn't hard code their values in the opening <code>print</code>.</li>\n<li>You should use <code>//</code> to make sure you are getting integer division.</li>\n<li>You can write <code>guess = (low + high) // 2</code> only once, if you place it as the first line inside the <code>while</code> loop.</li>\n<li>When checking for <code>pointer</code>, you may want to first convert it to lower case, to make sure both <code>h</code> and <code>H</code> are understood.</li>\n<li>Make your code conform to <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> on things like maximum line length.</li>\n<li>Using the <code>format</code> method of <code>str</code> can make more clear what you are printing.</li>\n</ul>\n\n<p>Putting it all together:</p>\n\n<pre><code>high, low = 100, 0\n\nprint('Please think of a number between {0} and {1}!'.format(low, high))\n\nguessing = True\nwhile guessing:\n guess = (low + high) // 2\n print('Is your secret number {0}?'.format(guess))\n pointer = raw_input(\"Enter 'h' to indicate the guess is too high. \"\n \"Enter 'l' to indicate the guess is too low. \"\n \"Enter 'c' to indicate I guessed correctly.\").lower()\n if pointer == 'h' :\n high = guess\n elif pointer == 'l' :\n low = guess\n elif pointer == 'c':\n guessing = False\n else:\n print('Sorry, I did not understand your input.')\n\nprint('Game over. Your secret number was {0}.'.format(guess))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T00:44:11.667", "Id": "22992", "ParentId": "22984", "Score": "8" } } ]
<p>I'm trying to become more proficient in Python and have decided to run through the Project Euler problems. </p> <p>In any case, the problem that I'm on (<a href="http://projecteuler.net/problem=17" rel="nofollow">17</a>) wants me to count all the letters in the English words for each natural number up to 1,000. In other words, one + two would have 6 letters, and so on continuing that for all numbers to 1,000.</p> <p>I wrote this code, which produces the correct answer (21,124). However, I'm wondering if there's a more pythonic way to do this.</p> <p>I have a function (<code>num2eng</code>) which translates the given integer into English words but does not include the word "and". </p> <pre><code>for i in range (1, COUNTTO + 1): container = num2eng(i) container = container.replace(' ', '') print container if i &gt; 100: if not i % 100 == 0: length = length + container.__len__() + 3 # account for 'and' in numbers over 100 else: length = length + container.__len__() else: length = length + container.__len__() print length </code></pre> <p>There is some repetition in my code and some nesting, both of which seem un-pythonic.</p> <p>I'm specifically looking for ways to make the script shorter and with simpler loops; I think that's my biggest weakness in general.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:36:38.837", "Id": "35424", "Score": "0", "body": "Your question isn't very specific; it's pretty open ended. We like specific programming questions here with a clear answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:39:51.883", "Id": "35425", "Score": "5", "body": "Don’t call magic methods directly, just use `len(container)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:07:05.217", "Id": "35426", "Score": "0", "body": "I know it doesn't relate to the programming question, but integers should never be written out or spoken with \"and.\" \"And\" is used only for fractions. 1234 is \"one thousand twenty-four\" with no \"and\", but 23.5 is twenty-three and one half." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T00:56:28.790", "Id": "35432", "Score": "0", "body": "@askewchan: that's far from a universal standard, and I definitely don't think it rises to the level of \"should never be\". Even Americans, I believe, tend to include the \"and\" when writing on cheques. Unfortunately continued discussion would be off-topic, but for my part, let a thousand (and one) flowers bloom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T05:23:31.840", "Id": "35446", "Score": "0", "body": "@Hiroto Edited to make more specific, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T08:31:18.670", "Id": "35452", "Score": "0", "body": "If you _have_ to ask, then yes it _can_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T18:21:01.390", "Id": "35515", "Score": "0", "body": "I think my question should have been \"how can\", since I believe virtually any code \"can\" be improved. Changed to reflect that, thanks!" } ]
{ "AcceptedAnswerId": "22996", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:34:46.893", "Id": "22993", "Score": "1", "Tags": [ "python", "programming-challenge" ], "Title": "Number letter counts" }
22993
accepted_answer
[ { "body": "<p>Here are a few things:</p>\n\n<ul>\n<li><code>container.__len__()</code> – You should never call magic methods directly. Just use <code>len(container)</code>.</li>\n<li><p>As you don’t know to what amount you need to increment (i.e. your <code>COUNTTO</code>), it would make more sense to have a while loop that keeps iterating until you reach your final length result:</p>\n\n<pre><code>while length &lt; 1000:\n # do stuff with i\n length += # update length\n i += 1\n</code></pre></li>\n<li><p>You could also make use of <a href=\"http://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"nofollow\"><code>itertools.count</code></a>:</p>\n\n<pre><code>length = 0\nfor i in itertools.count(1):\n length += # update length\n if length &gt; 1000:\n break\n</code></pre></li>\n<li><code>not i % 100 == 0</code> – When you already have a operator (<code>==</code>) then don’t use <code>not</code> to invert the whole condition, but just use the inverted operator: <code>i % 100 != 0</code></li>\n<li><p>Also having additional counting logic outside of your <code>num2eng</code> does not seem to be appropriate. What does that function do exactly? Shouldn’t it rather produce a real number using a complete logic? Ideally, it should be as simple as this:</p>\n\n<pre><code>length = 0\nfor i in itertools.count(1):\n length += len(num2eng(i))\n if length &gt; 1000:\n break\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:10:16.997", "Id": "35430", "Score": "0", "body": "I think the reason to have some logic outside of `num2eng` is to avoid counting the letters in `'hundred'` and `'thousand'` so many times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:13:58.527", "Id": "35431", "Score": "0", "body": "@askewchan Huh? That doesn’t make much sense to me, as you still do that. Also I’d expect a function `num2eng` to return a complete written English representation of the number I pass in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T05:19:16.370", "Id": "35445", "Score": "0", "body": "You're correct. The function num2eng returns the English representation of the numbers provided. For instance, 102 becomes one hundred two. It's doesn't include \"and\" though and the scope of the challenge required \"and\" to be included (e.g., one hundred and two), hence the addition. But it would makes sense to modify num2eng instead of making up for it here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T05:25:41.577", "Id": "35448", "Score": "0", "body": "Thank you so much for this feedback, this is exactly what I was looking for!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:44:02.690", "Id": "22996", "ParentId": "22993", "Score": "2" } } ]
<p>I have a function that needs to return the call to another function that have some parameters. Let's say, for example, the following:</p> <pre><code>def some_func(): iss = do_something() example = do_something_else() return some_long_name('maybe long string', {'this': iss, 'an': example, 'dictionary': 'wich is very long'}) </code></pre> <p>I want to adjust it so it will comply with PEP 8. I tried:</p> <pre><code>def some_func(): iss = do_something() example = do_something_else() return some_long_name('maybe long string', {'this': iss, 'an': example, 'dictionary': 'wich is very long'}) </code></pre> <p>But it still goes way beyond 80 characters. So I did a two step 'line continuation', but don't know if it's how it's done.</p> <pre><code>def some_func(): iss = do_something() example = do_something_else() return some_long_name('maybe long string', { 'this': iss, 'an': example, 'dictionary': 'wich is very long' }) </code></pre> <p>Or should it be something like:</p> <pre><code>def some_func(): iss = do_something() example = do_something_else() return some_long_name('maybe long string', {'this': iss, 'an': example, 'dictionary': 'wich is very long'}) </code></pre> <p>I would appreciate some insight so I can maintain a better code because PEP8 doesn't explain it very well.</p>
[]
{ "AcceptedAnswerId": "23014", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T07:05:59.650", "Id": "23006", "Score": "1", "Tags": [ "python" ], "Title": "Python Line continuation dictionary" }
23006
accepted_answer
[ { "body": "<p>In my opinion, use Explaining Variables or Summary Variables express the dict. I like this coding style as follows.</p>\n\n<pre><code>keyword = {\n 'this': iss,\n 'an': example,\n 'dictionary': 'wich is very long',\n}\nreturn some_long_name('maybe long string', keyword)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T12:52:08.637", "Id": "23014", "ParentId": "23006", "Score": "2" } } ]
<p>This function takes in a number and returns all divisors for that number. <code>list_to_number()</code> is a function used to retrieve a list of prime numbers up to a limit, but I am not concerned over the code of that function right now, only this divisor code. I am planning on reusing it when solving various Project Euler problems.</p> <pre><code>def list_divisors(num): ''' Creates a list of all divisors of num ''' orig_num = num prime_list = list_to_number(int(num / 2) + 1) divisors = [1, num] for i in prime_list: num = orig_num while not num % i: divisors.append(i) num = int(num / i) for i in range(len(divisors) - 2): for j in range(i + 1, len(divisors) - 1): if i and j and j != num and not orig_num % (i * j): divisors.append(i * j) divisors = list(set(divisors)) divisors.sort() return divisors </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T09:38:25.387", "Id": "35455", "Score": "0", "body": "I've changed the bottom for loop to be `for i in range(1, len(divisors) - 2):\n for j in range(i + 1, len(divisors) - 1):\n if not orig_num % (i * j):\n divisors.append(i * j)` but it doesn't read well here." } ]
{ "AcceptedAnswerId": "23015", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T08:55:46.097", "Id": "23008", "Score": "4", "Tags": [ "python", "primes" ], "Title": "Returning a list of divisors for a number" }
23008
accepted_answer
[ { "body": "<ul>\n<li>Don't reset <code>num</code> to <code>orig_num</code> (to fasten division/modulo) </li>\n<li>Think functionnaly :\n<ul>\n<li>From your prime factors, if you generate a <em>new</em> collection with all possible combinations, no need to check your products.</li>\n<li>It makes harder to introduce bugs. Your code is indeed broken and won't output 20 or 25 (...) as divisors of 100.</li>\n<li>You can re-use existing (iter)tools.</li>\n</ul></li>\n<li>Avoid unnecessary convertions (<code>sorted</code> can take any iterable)</li>\n<li>Compute primes as you need them (eg, for 10**6, only 2 and 5 will suffice). Ie, use a generator.</li>\n</ul>\n\n<p>This leads to :</p>\n\n<pre><code>from prime_sieve import gen_primes\nfrom itertools import combinations, chain\nimport operator\n\ndef prod(l):\n return reduce(operator.mul, l, 1)\n\ndef powerset(lst):\n \"powerset([1,2,3]) --&gt; () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n return chain.from_iterable(combinations(lst, r) for r in range(len(lst)+1))\n\ndef list_divisors(num):\n ''' Creates a list of all divisors of num\n '''\n primes = gen_primes()\n prime_divisors = []\n while num&gt;1:\n p = primes.next()\n while not num % p:\n prime_divisors.append(p)\n num = int(num / p)\n\n return sorted(set(prod(fs) for fs in powerset(prime_divisors)))\n</code></pre>\n\n<p>Now, the \"factor &amp; multiplicity\" approach like in suggested link is really more efficient.\nHere is my take on it :</p>\n\n<pre><code>from prime_sieve import gen_primes\nfrom itertools import product\nfrom collections import Counter\nimport operator\n\ndef prime_factors(num):\n \"\"\"Get prime divisors with multiplicity\"\"\"\n\n pf = Counter()\n primes = gen_primes()\n while num&gt;1:\n p = primes.next()\n m = 0\n while m == 0 :\n d,m = divmod(num,p)\n if m == 0 :\n pf[p] += 1\n num = d\n return pf\n\ndef prod(l):\n return reduce(operator.mul, l, 1)\n\ndef powered(factors, powers):\n return prod(f**p for (f,p) in zip(factors, powers))\n\n\ndef divisors(num) :\n\n pf = prime_factors(num)\n primes = pf.keys()\n #For each prime, possible exponents\n exponents = [range(i+1) for i in pf.values()]\n return sorted([powered(primes,es) for es in product(*exponents)])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T13:06:57.343", "Id": "23015", "ParentId": "23008", "Score": "3" } } ]
<p>I'm reading the awesome Head First Design Patterns book. As an exercise I converted first example (or rather a subset of it) to Python. The code I got is rather too simple, i.e. there is no abstract nor interface declarations, it's all just 'classes'. Is that the right way to do it in Python? My code is below, original Java code and problem statement can be found at <a href="http://books.google.com/books?id=LjJcCnNf92kC&amp;pg=PA18">http://books.google.com/books?id=LjJcCnNf92kC&amp;pg=PA18</a></p> <pre><code>class QuackBehavior(): def __init__(self): pass def quack(self): pass class Quack(QuackBehavior): def quack(self): print "Quack!" class QuackNot(QuackBehavior): def quack(self): print "..." class Squeack(QuackBehavior): def quack(self): print "Squeack!" class FlyBehavior(): def fly(self): pass class Fly(): def fly(self): print "I'm flying!" class FlyNot(): def fly(self): print "Can't fly..." class Duck(): def display(self): print this.name def performQuack(self): self.quackBehavior.quack() def performFly(self): self.flyBehavior.fly() class MallardDuck(Duck): def __init__(self): self.quackBehavior = Quack() self.flyBehavior = Fly() if __name__ == "__main__": mallard = MallardDuck() mallard.performQuack() mallard.performFly() mallard.flyBehavior = FlyNot() mallard.performFly() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-24T20:04:40.450", "Id": "35602", "Score": "0", "body": "This looked [very familiar](http://codereview.stackexchange.com/questions/20718/the-strategy-design-pattern-for-python-in-a-more-pythonic-way/20719#20719) - you might want to take a look at my answer to that question." } ]
{ "AcceptedAnswerId": "23044", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T17:46:59.227", "Id": "23033", "Score": "5", "Tags": [ "python", "object-oriented", "design-patterns" ], "Title": "Strategy Design Pattern in Python" }
23033
accepted_answer
[ { "body": "<p>In Python, you can pass functions as argument. This simplifies the \"Strategy\" Design pattern, as you don't need to create classes just for one method or behavior. See this <a href=\"https://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia\">question</a> for more info.</p>\n\n<pre><code>def quack():\n print \"Quack!\"\n\ndef quack_not():\n print \"...\"\n\ndef squeack():\n print \"Squeack!\"\n\ndef fly():\n print \"I'm flying!\"\n\ndef fly_not():\n print \"Can't fly...\"\n\n\nclass Duck:\n def display(self):\n print this.name\n\n def __init__(self, quack_behavior, fly_behavior):\n self.performQuack = quack_behavior\n self.performFly = fly_behavior\n\nclass MallardDuck(Duck):\n def __init__(self):\n Duck.__init__(self, quack, fly)\n\nif __name__ == \"__main__\":\n duck = Duck(quack_not, fly_not)\n duck.performQuack()\n mallard = MallardDuck()\n mallard.performQuack()\n mallard.performFly()\n mallard.performFly = fly_not\n mallard.performFly()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>...\nQuack!\nI'm flying!\nCan't fly...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-23T15:08:54.087", "Id": "35550", "Score": "0", "body": "I picked this answer because it actually shows what @WinstonEwert's only proposed. However, this code lets you create a generic Duck, which was not possible in original Java example (that class is abstract). I assumed not having \\_\\_init__ in Duck() would make it kind-of-abstract in Python... Is that a correct assumption?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-25T23:27:35.507", "Id": "35677", "Score": "0", "body": "Yes, here's some more info on that: http://fw-geekycoder.blogspot.com/2011/02/creating-abstract-class-in-python.html\nThe reason I had the `__init__` was for my own reasons of testing the script." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T23:35:22.530", "Id": "23044", "ParentId": "23033", "Score": "5" } } ]
<p>I am trying to combine two programs that analyze strings into one program. The result should look at a parent string and determine if a sub-string has an exact match or a "close" match within the parent string; if it does it returns the location of this match </p> <p>i.e. parent: abcdefefefef sub cde is exact and returns 2 sub efe is exact and returns 4, 6, 8 sub deg is close and returns 3 sub z has no match and returns None</p> <p>The first program I wrote locates exact matches of a sub-string within a parent string:</p> <pre><code>import string def subStringMatchExact(): print "This program will index the locations a given sequence" print "occurs within a larger sequence" seq = raw_input("Please input a sequence to search within: ") sub = raw_input("Please input a sequence to search for: ") n = 0 for i in range(0,len(seq)): x = string.find(seq, sub, n, len(seq)) if x == -1: break print x n = x + 1 </code></pre> <p>The second analyzes whether or not there is an close match within a parent string and returns True if there is, and false if there isn't. Again a close match is an exact match or one that differs by only one character.</p> <pre><code>import string def similarstrings(): print "This program will determine whether two strings differ" print "by more than one character. It will return True when they" print "are the same or differ by one character; otherwise it will" print "return False" str1 = raw_input("Enter first string:") str2 = raw_input("Enter second string:") x = 0 for i in range(len(str1)): if str1[i] == str2[i]: x = x + 1 else: x = x if x &gt;= len(str1) - 1: print True else: print False </code></pre> <p>Any suggestions on how to combine the two would be much appreciated.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T01:35:09.573", "Id": "23141", "Score": "2", "Tags": [ "python" ], "Title": "Python: Combing two programs that analyze strings" }
23141
max_votes
[ { "body": "<p>Firstly, a quick review of what you've done:</p>\n\n<p><code>import string</code> is unnecessary really. You utilize <code>string.find</code>, but you can simply call the find method on your first argument, that is, <code>seq.find(sub, n, len(seq))</code>. </p>\n\n<p>In your second method, you have:</p>\n\n<pre><code>if str1[i] == str2[i]:\n x = x + 1\nelse:\n x = x\n</code></pre>\n\n<p>The <code>else</code> statement is completely redundant here, you don't need it.</p>\n\n<p>I think we can simplify the logic quite a bit here. I'm going to ignore <code>raw_input</code> and take the strings as arguments instead, but it doesn't change the logic (and is arguably better style anyway). Note that this is not fantastically optimized, it can definitely be made faster:</p>\n\n<pre><code>def similar_strings(s1, s2):\n '''Fuzzy matches s1 with s2, where fuzzy match is defined as\n either all of s2 being contained somewhere within s1, or\n a difference of only one character. Note if len(s2) == 1, then\n the character represented by s2 must be found within s1 for a match\n to occur.\n\n Returns a list with the starting indices of all matches.\n\n '''\n block_size = len(s2)\n match = []\n for j in range(0, len(s1) - block_size):\n diff = [ord(i) - ord(j) for (i, j) in zip(s1[j:+block_size],s2)]\n if diff.count(0) and diff.count(0) &gt;= (block_size - 1):\n match.append(j)\n if not match:\n return None\n return match\n</code></pre>\n\n<p>How does this work? Well, it basically creates a \"window\" of size <code>len(s2)</code> which shifts along the original string (<code>s1</code>). Within this window, we take a slice of our original string (<code>s1[j:j+block_size]</code>) which is of length <code>len(s2)</code>. <code>zip</code> creates a list of tuples, so, for example, <code>zip(['a','b','c'], ['x','y','z'])</code> will give us back <code>[(a, x), (b, y), (c, z)</code>].</p>\n\n<p>Then, we make a difference of all the characters from our <code>s2</code> sized block of <code>s1</code> and our actual <code>s2</code> - <code>ord</code> gives us the (integer) value of a character. So the rather tricky line <code>diff = [ord(i) - ord(j) for (i, j) in zip(s1[j:+block_size],s2)]</code> will give us a list of size <code>len(s2)</code> which has all the differences between characters. As an example, with <code>s1</code> being <code>abcdefefefef</code> and <code>s2</code> being <code>cde</code>, our first run through will give us the slice <code>abc</code> to compare with <code>cde</code> - which gives us <code>[-2, -2, -2]</code> since all characters are a distance of 2 apart.</p>\n\n<p>So, given <code>diff</code>, we want to see how many 0's it has, as two characters will be the same when their <code>ord</code> difference is 0. However, we need to make sure there is at least 1 character the same in our block (if you simply pass in <code>z</code>, or any string length 1, diff will always have length 1, and <code>block_size - 1</code> will be 0. Hence <code>diff.count(0) &gt;= 0</code> will always be <code>True</code>, which is not what we want). Thus <code>diff.count(0)</code> will only be true if it is greater than 0, which protects us from this. When that's true, look at the block size, make sure it is at least <code>len(s2) - 1</code>, and if so, add that index to <code>match</code>.</p>\n\n<p>Hopefully this gives you an idea of how you'd do this, and I hope the explanation is detailed enough to make sense of some python constructs you may not have seen before.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T02:41:03.293", "Id": "23142", "ParentId": "23141", "Score": "1" } } ]
<p>I like the radix function and found a really neat way to compute its inverse in Python with a lambda and <code>reduce()</code> (so I really feel like I'm learning my cool functional programming stuff):</p> <pre><code>def unradix(source,radix): # such beauty return reduce(lambda (x,y),s: (x*radix,y+s*x), source, (1,0)) </code></pre> <p>where:</p> <pre><code>&gt;&gt;&gt; unradix([1,0,1,0,1,0,1],2) (128,85) </code></pre> <p>But its dizygotic twin is unable to use the same pattern without an ugly hack:</p> <pre><code>def radix(source,radix): import math hack = 1+int(math.floor(math.log(source)/math.log(radix))) # ^^^^ ... _nearly_ , such beauty return reduce(lambda (x,y),s: (x/radix,y+[x%radix]), xrange(hack), (source,[])) </code></pre> <p>where:</p> <pre><code>&gt;&gt;&gt; radix(85,2) (0, [1, 0, 1, 0, 1, 0, 1]) </code></pre> <p>How can I remove the hack from this pattern? Or failing that, how can I rewrite this pair of functions and inverse so they use the same pattern, and only differ in "mirror-symmetries" as much as possibly?</p> <p>By mirror symmetry I mean something like the way <em>increment</em> and <em>decrement</em> are mirror images, or like the juxtaposition of <code>x*radix</code> versus <code>x/radix</code> in the same code location as above.</p>
[]
{ "AcceptedAnswerId": "23188", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:25:39.303", "Id": "23180", "Score": "3", "Tags": [ "python", "functional-programming", "lambda" ], "Title": "Removing hackery from pair of radix functions" }
23180
accepted_answer
[ { "body": "<p>The reverse operation to folding is unfolding. To be honest, I'm not very\nfluent in python and I couldn't find if python has an unfolding function.\n(In Haskell we have\n<a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v%3afoldr\" rel=\"nofollow\">foldr</a>\nand its complement \n<a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v%3aunfoldr\" rel=\"nofollow\">unfoldr</a>.)</p>\n\n<p>Nevertheless, we can easily construct one:</p>\n\n<pre><code>\"\"\"\nf accepts a value and returns None or a pair.\nThe first element of the pair is the next seed,\nthe second element is the value to yield.\n\"\"\"\ndef unfold(f, r):\n while True:\n t = f(r);\n if t:\n yield t[1];\n r = t[0];\n else: \n break;\n</code></pre>\n\n<p>It iterates a given function on a seed until it returns <code>None</code>, yielding intermediate results. It's dual to <code>reduce</code>, which takes a function and an iterable and produces a value. On the other hand, <code>unfold</code> takes a value and a generating function, and produces a generator. For example, to create a list of numbers from 0 to 10 we could write:</p>\n\n<pre><code>print list(unfold(lambda n: (n+1, n) if n &lt;= 10 else None, 0));\n</code></pre>\n\n<p>(we call <code>list</code> to convert a generator into a list).</p>\n\n<p>Now we can implement <code>radix</code> quite nicely:</p>\n\n<pre><code>def radix(source, radix):\n return unfold(lambda n: divmod(n, radix) if n != 0 else None, source);\n\nprint list(radix(12, 2));\n</code></pre>\n\n<p>prints <code>[0, 0, 1, 1]</code>.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Folding (<code>reduce</code>) captures the pattern of consuming lists. Any function that sequentially consumes a list can be eventually written using <code>reduce</code>. The first argument to <code>reduce</code> represents the core computation and the third argument, the accumulator, the state of the loop. Similarly, unfolding (my <code>unfold</code>) represents the pattern of producing lists. Again, any function that sequentially produces a list can be eventually rewritten using <code>unfold</code>.</p>\n\n<p>Note that there are functions that can be expressed using either of them, as we can look at them as functions that produce or consume lists. For example, we can implement <code>map</code> (disregarding any efficiency issues) as</p>\n\n<pre><code>def map1(f, xs):\n return reduce(lambda rs, x: rs + [f(x)], xs, [])\n\ndef map2(f, xs):\n return unfold(lambda xs: (xs[1:], f(xs[0])) if xs else None, xs)\n</code></pre>\n\n<hr>\n\n<p>The duality of <code>reduce</code> and <code>unfold</code> is nicely manifested in a technique called <a href=\"https://en.wikipedia.org/wiki/Deforestation_%28computer_science%29\" rel=\"nofollow\">deforestation</a>. If you know that you create a list using <code>unfold</code> only to consume it immediately with <code>reduce</code>, you can combine these two operations into a single, higher-order function that doesn't build the intermediate list:</p>\n\n<pre><code>def deforest(foldf, init, unfoldf, seed):\n while True:\n t = unfoldf(seed);\n if t:\n init = foldf(t[1], init);\n seed = t[0];\n else:\n return init;\n</code></pre>\n\n<p>For example, if we wanted to compute the sum of digits of 127 in base 2, we could call</p>\n\n<pre><code>print deforest(lambda x,y: x + y, 0, # folding part\n lambda n: divmod(n, 2) if n != 0 else None, # unfolding\n 127); # the seed\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T21:47:34.107", "Id": "35769", "Score": "0", "body": "A beautiful and symmetric radix! A *great* explanation as well. Thanks for teach me, and \"us\", something!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T22:33:46.853", "Id": "35772", "Score": "0", "body": "(in spirit) +1 for deforest, that *soo* cool." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T22:47:30.013", "Id": "35773", "Score": "0", "body": "@PetrPudlák so I understand, we are using our function (that would have been in unfold) on init, one time, then we are using our fold function on the yield value of that 'unfold' function, and accumulating that into init. And we are 're'-unfolding with the seed value. So we interleave folding into init, and unfolding out of seed. If we were to capture the sequences of seed and init, they would reproduce the lists being produced and consumed at each step of the deforest while loop. Does that sound right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T08:01:45.600", "Id": "35795", "Score": "0", "body": "@CrisStringfellow Yes, it's just like you say." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T08:02:43.853", "Id": "35796", "Score": "0", "body": "@PetrPudlák good to know, thanks. Now I have learnt something else. :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T21:37:19.217", "Id": "23188", "ParentId": "23180", "Score": "4" } } ]
<p>I'm implementing a checkers engine for a scientific experiment. I found out through profiling that this is one of the functions that takes up a lot of time. I'm not looking for an in-depth analysis, because I don't expect you to dive super deep into my code.</p> <p>Just: <strong>are there any obvious inefficiencies here?</strong> Like, is it slow to do those starting for loops (<code>dx, dy</code>) just for 2 values each?</p> <pre><code>def captures(self, (py, px), piece, board, captured=[], start=None): """ Return a list of possible capture moves for given piece in a checkers game. :param (py, px): location of piece on the board :param piece: piece type (BLACK/WHITE|MAN/KING) :param board: the 2D board matrix :param captured: list of already-captured pieces (can't jump twice) :param start: from where this capture chain started. """ if start is None: start = (py, px) # Look for capture moves for dx in [-1, 1]: for dy in [-1, 1]: dist = 1 while True: jx, jy = px + dist * dx, py + dist * dy # Jumped square # Check if piece at jx, jy: if not (0 &lt;= jx &lt; 8 and 0 &lt;= jy &lt; 8): break if board[jy, jx] != EMPTY: tx, ty = px + (dist + 1) * dx, py + (dist + 1) * dy # Target square # Check if it can be captured: if ((0 &lt;= tx &lt; 8 and 0 &lt;= ty &lt; 8) and ((ty, tx) == start or board[ty, tx] == EMPTY) and (jy, jx) not in captured and ((piece &amp; WHITE) and (board[jy, jx] &amp; BLACK) or (piece &amp; BLACK) and (board[jy, jx] &amp; WHITE)) ): # Normal pieces cannot continue capturing after reaching last row if not piece &amp; KING and (piece &amp; WHITE and ty == 0 or piece &amp; BLACK and ty == 7): yield (NUMBERING[py, px], NUMBERING[ty, tx]) else: for sequence in self.captures((ty, tx), piece, board, captured + [(jy, jx)], start): yield (NUMBERING[py, px],) + sequence break else: if piece &amp; MAN: break dist += 1 yield (NUMBERING[py, px],) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T16:31:35.090", "Id": "23323", "Score": "3", "Tags": [ "python", "recursion", "generator", "checkers-draughts" ], "Title": "Efficiency of Recursive Checkers Legal Move Generator" }
23323
max_votes
[ { "body": "<p>A couple of little things that caught my eye:</p>\n\n<p>You could simplify this</p>\n\n<pre><code>dist = 1 \nwhile True:\n jx, jy = px + dist * dx, py + dist * dy \n dist += 1\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>jx, jy = px, py\nwhile True:\n jx += dx\n jy += dy\n</code></pre>\n\n<hr>\n\n<p>You don't need this range check</p>\n\n<pre><code>if not (0 &lt;= jx &lt; 8 and 0 &lt;= jy &lt; 8):\n break\nif board[jy, jx] != EMPTY:\n</code></pre>\n\n<p>because, assuming <code>board</code> is a dict indexed by tuple, you can just catch <code>KeyError</code> when out of bounds:</p>\n\n<pre><code>try:\n if board[jy, jx] != EMPTY:\n ...\nexcept KeyError:\n break\n</code></pre>\n\n<hr>\n\n<p>Instead of</p>\n\n<pre><code>((piece &amp; WHITE) and (board[jy, jx] &amp; BLACK) or\n (piece &amp; BLACK) and (board[jy, jx] &amp; WHITE))\n</code></pre>\n\n<p>you could use <code>board[jy, jx] &amp; opponent</code> if you determine the opponent's color in the beginning of the function:</p>\n\n<pre><code>opponent = BLACK if piece &amp; WHITE else WHITE\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T17:19:11.613", "Id": "23626", "ParentId": "23323", "Score": "2" } } ]
<p>I made a Python function that takes an XML file as a parameter and returns a JSON. My goal is to convert some XML get from an old API to convert into Restful API.</p> <p>This function works, but it is really ugly. I try to clean everything, without success.</p> <p>Here are my tests:</p> <pre class="lang-python prettyprint-override"><code> def test_one_node_with_more_than_two_children(self): xml = '&lt;a id="0" name="foo"&gt;&lt;b id="00" name="moo" /&gt;&lt;b id="01" name="goo" /&gt;&lt;b id="02" name="too" /&gt;&lt;/a&gt;' expected_output = { "a": { "@id": "0", "@name": "foo", "b": [ { "@id": "00", "@name": "moo" }, { "@id": "01", "@name": "goo" }, { "@id": "02", "@name": "too" } ] } } self.assertEqual(expected_output, self.parser.convertxml2json(xml)) </code></pre> <p>And my function:</p> <pre class="lang-python prettyprint-override"><code>from xml.dom.minidom import parseString, Node class Parser(object): def get_attributes_from_node(self, node): attributes = {} for attrName, attrValue in node.attributes.items(): attributes["@" + attrName] = attrValue return attributes def convertxml2json(self, xml): parsedXml = parseString(xml) return self.recursing_xml_to_json(parsedXml) def recursing_xml_to_json(self, parsedXml): output_json = {} for node in parsedXml.childNodes: attributes = "" if node.nodeType == Node.ELEMENT_NODE: if node.hasAttributes(): attributes = self.get_attributes_from_node(node) if node.hasChildNodes(): attributes[node.firstChild.nodeName] = self.recursing_xml_to_json(node)[node.firstChild.nodeName] if node.nodeName in output_json: if type(output_json[node.nodeName]) == dict: output_json[node.nodeName] = [output_json[node.nodeName]] + [attributes] else: output_json[node.nodeName] = [x for x in output_json[node.nodeName]] + [attributes] else: output_json[node.nodeName] = attributes return output_json </code></pre> <p>Can someone give me some tips to improve this code?<br> <code>def recursing_xml_to_json(self, parsedXml)</code> is really bad.<br> I am ashamed to produce it :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T19:07:29.333", "Id": "36326", "Score": "0", "body": "Could you explain the intent, and add some comments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:33:47.853", "Id": "36596", "Score": "0", "body": "i updated my question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:22:17.250", "Id": "62799", "Score": "0", "body": "What about [XMLtoDict](https://github.com/martinblech/xmltodict) ?\nIt seems similar to what you created, no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T11:15:27.707", "Id": "62800", "Score": "0", "body": "After studying the source code of this application, I thought there was an easier way to do. It allowed me to improve myself." } ]
{ "AcceptedAnswerId": "23551", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T16:36:00.630", "Id": "23324", "Score": "5", "Tags": [ "python", "unit-testing", "xml", "json", "recursion" ], "Title": "Recursive XML2JSON parser" }
23324
accepted_answer
[ { "body": "<p>There is a structural issue with your code: the recursive function works at two levels. 1) It constructs a dict representing a node, and 2) it does some work in constructing the representation for the children. This makes it unnecessarily complicated. Instead, the function should focus on handling one node, and delegate the creation of child nodes to itself via recursion.</p>\n\n<p>You seem to have requirements such as:</p>\n\n<ol>\n<li>A node that has no children nor attributes converts to an empty string. My implementation: <code>return output_dict or \"\"</code></li>\n<li>Multiple children with same nodeName convert to a list of dicts, while a single one converts to just a dict. My implementation makes this explicit by constructing lists first, then applying this conversion: <code>v if len(v) &gt; 1 else v[0]</code></li>\n<li>A node with children but no attributes raises a TypeError. I suspect this is an oversight and did not reproduce the behavior.</li>\n</ol>\n\n<p>Note that (2) means that a consumer of your JSON that expects a variable number of nodes must handle one node as a special case. I don't think that is good design.</p>\n\n<pre><code>def get_attributes_from_node(self, node):\n attributes = {}\n if node.attributes:\n for attrName, attrValue in node.attributes.items():\n attributes[\"@\" + attrName] = attrValue\n return attributes\n\ndef recursing_xml_to_json(self, node):\n d = collections.defaultdict(list)\n for child in node.childNodes:\n if child.nodeType == Node.ELEMENT_NODE:\n d[child.nodeName].append(self.recursing_xml_to_json(child))\n\n output_dict = self.get_attributes_from_node(node)\n output_dict.update((k, v if len(v) &gt; 1 else v[0])\n for k, v in d.iteritems())\n\n return output_dict or \"\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:33:26.653", "Id": "36595", "Score": "0", "body": "This answer is really amazing" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T20:44:52.960", "Id": "23551", "ParentId": "23324", "Score": "2" } } ]
<p>I believe this is essentially the same method as the <code>itertools.combinations</code> function, but is there any way to make this code more more perfect in terms of speed, code size and readability :</p> <pre><code>def all_subsets(source,size): index = len(source) index_sets = [()] for sz in xrange(size): next_list = [] for s in index_sets: si = s[len(s)-1] if len(s) &gt; 0 else -1 next_list += [s+(i,) for i in xrange(si+1,index)] index_sets = next_list subsets = [] for index_set in index_sets: rev = [source[i] for i in index_set] subsets.append(rev) return subsets </code></pre> <p>Yields:</p> <pre><code>&gt;&gt;&gt; Apriori.all_subsets(['c','r','i','s'],2) [['c', 'r'], ['c', 'i'], ['c', 's'], ['r', 'i'], ['r', 's'], ['i', 's']] </code></pre> <p>There is probably a way to use generators or functional concepts, hopefully someone can suggest improvements.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-02T23:53:25.477", "Id": "36021", "Score": "0", "body": "Why aren't you using itertools.combinations? It's reasonable to do this for learning purposes, but if you are actually doing a bigger project you'll want to use the itertools version." } ]
{ "AcceptedAnswerId": "23371", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-02T19:38:14.427", "Id": "23363", "Score": "1", "Tags": [ "python", "functional-programming", "combinatorics" ], "Title": "Any way to optimize or improve this python combinations/subsets functions?" }
23363
accepted_answer
[ { "body": "<p>This type of problems lend themselves very well to <a href=\"http://en.wikipedia.org/wiki/Recursion\" rel=\"nofollow\">recursion</a>. A possible implementation, either in list or generator form could be:</p>\n\n<pre><code>def all_subsets(di, i) :\n ret = []\n for j, item in enumerate(di) :\n if i == 1 :\n ret = [(j,) for j in di]\n elif len(di) - j &gt;= i :\n for subset in all_subsets(di[j + 1:], i - 1) :\n ret.append((item,) + subset)\n return ret\n\ndef all_subsets_gen(di, i) :\n for j, item in enumerate(di) :\n if i == 1 :\n yield (j,)\n elif len(di) - j &gt;= i :\n for subset in all_subsets(di[j + 1:], i - 1) :\n yield (item,) + subset\n\n&gt;&gt;&gt; all_subsets(range(4), 3)\n[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]\n&gt;&gt;&gt; list(all_subsets_gen(range(4), 3))\n[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]\n</code></pre>\n\n<p>If you are going to run this on large sets, you may want to <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow\">memoize</a> intermediate results to speed things up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:14:46.120", "Id": "36045", "Score": "0", "body": "RE the memorization, do you mean if the function is going to be run more than once? Otherwise I don't see how memorization would help here, since isn't there only *one path* down through the recursion, with each size of subsets being created just once?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:47:23.860", "Id": "36047", "Score": "0", "body": "@CrisStringfellow In my example above, the `(0, 2, 3)` and the `(1, 2, 3)` are both calling `all_subsets([2, 3], 2)` and it gets worse for larger sets, especially with a small `i`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:50:22.550", "Id": "36049", "Score": "0", "body": "Got it. I was wrong. But couldn't that be subtly changed by making the call to 2,3 and then prepending the first element/s? Is this what you mean by memorization?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-02T23:54:14.707", "Id": "23371", "ParentId": "23363", "Score": "2" } } ]
<p>I got a ton of helpful tips last time I posted some code, so I thought I would come back to the well.</p> <p>My function is deciding whether or not the <code>secretWord</code> has been guessed in my hangman game. I am trying to accomplish this by taking a list, <code>lettersGuessed</code>, and comparing it to the char in each index of the string <code>secretWord</code>. My code works, but I feel as though it is not optimal nor formatted well.</p> <pre><code>def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' chars = len(secretWord) place = 0 while place &lt; chars: if secretWord[0] in lettersGuessed: place += 1 return isWordGuessed(secretWord[1:], lettersGuessed) else: return False return True </code></pre> <p>I tried to use a for loop (<code>for i in secretWord:</code>) originally, but I could not get my code to return both True and False. It would only do one or the other, which is how I ended up with the while loop. It seems that <code>while</code> loops are discouraged/looked at as not very useful. Is this correct?</p> <p>Also, I am wondering if the recursive call is a good way of accomplishing the task.</p>
[]
{ "AcceptedAnswerId": "23378", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T05:01:59.713", "Id": "23375", "Score": "5", "Tags": [ "python", "hangman" ], "Title": "In my Hangman game, one of my functions is correct but messy" }
23375
accepted_answer
[ { "body": "<p>Because we always return from the inside of the while, we'll never perform the loop more than once. Thus, your while actually acts like an <code>if</code>. Thus the value of <code>place</code> is not really used and you can get rid of it : <code>if place &lt; chars</code> becomes <code>if 0 &lt; chars</code> which is <code>if chars</code> which is <code>if len(secretWord)</code> which is really <code>if secretWord</code> because of the way Python considers the empty string as a false value.\nThus, you code could be :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n if secretWord:\n if secretWord[0] in lettersGuessed:\n return isWordGuessed(secretWord[1:], lettersGuessed)\n else:\n return False\n return True\n</code></pre>\n\n<p>Which can be re-written as :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n if secretWord:\n return secretWord[0] in lettersGuessed and isWordGuessed(secretWord[1:], lettersGuessed)\n return True\n</code></pre>\n\n<p>which is then nothing but :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n return not secretWord or secretWord[0] in lettersGuessed and isWordGuessed(secretWord[1:], lettersGuessed)\n</code></pre>\n\n<p>Now, if I was to write the same function, because it is so easy to iterate on strings in Python, I'd probably avoid the recursion and so something like :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n for letter in secretWord:\n if letter not in lettersGuessed:\n return False\n return True\n</code></pre>\n\n<p>Then, there might be a way to make this a one-liner but I find this to be pretty easy to understand and pretty efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-18T00:15:37.170", "Id": "401411", "Score": "0", "body": "If you wanted a one-liner for your final code, you could do `return all(letter in lettersGuessed for letter in secretWord)`; the Python default built-ins [`all()`](https://docs.python.org/3/library/functions.html#all) and [`any()`](https://docs.python.org/3/library/functions.html#any) are good tricks to have up your sleave for crafting concise Python code. I actually think it's equally clear too, so (IMO) it's even better than your current final version." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T06:51:44.373", "Id": "23378", "ParentId": "23375", "Score": "7" } } ]
<p>This is my python solution to the first problem on Project Euler:</p> <pre><code>n = 1 rn = 0 while n &lt; 1000: if n%3 == 0 or n%5 == 0: rn += n n = n + 1 print(rn) </code></pre> <p>I would like to find a way to keep everything in this python code to as little number of lines as possible (maybe even a one liner??), and possibly improve the speed (it's currently around 12 ms). By the way, this is the problem: <blockquote>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> <p>Find the sum of all the multiples of 3 or 5 below 1000.</blockquote>Suggestions?<br />Thanks.<br /></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-29T21:28:10.807", "Id": "63715", "Score": "1", "body": "`sum(n for n in range(1000) if not n%3 or not n%5)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-04T08:50:05.540", "Id": "232506", "Score": "0", "body": "I like your solution to the problem. It is much more efficiently coded than another Project Euler #1 code question I just read." } ]
{ "AcceptedAnswerId": "23380", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T11:41:15.993", "Id": "23379", "Score": "5", "Tags": [ "python", "project-euler" ], "Title": "Project Euler Problem 1" }
23379
accepted_answer
[ { "body": "<p><strong>Python hint number 1:</strong></p>\n\n<p>The pythonic way to do :</p>\n\n<pre><code>n = 1\nwhile n &lt; 1000:\n # something using n\n n = n + 1\n</code></pre>\n\n<p>is :</p>\n\n<pre><code>for n in range(1,1000):\n # something using n\n</code></pre>\n\n<p><strong>Python hint number 2:</strong></p>\n\n<p>You could make your code a one-liner by using list comprehension/generators :</p>\n\n<pre><code>print sum(n for n in range(1,1000) if (n%3==0 or n%5==0))\n</code></pre>\n\n<p>Your code works fine but if instead of 1000, it was a much bigger number, the computation would take much longer. A bit of math would make this more more efficient.</p>\n\n<p><strong>Math hint number 1 :</strong></p>\n\n<p>The sum of all the multiples of 3 or 5 below 1000 is really the sum of (the sum of all the multiples of 3 below 1000) plus (the sum of all the multiples of 5 below 1000) minus the numbers you've counted twice.</p>\n\n<p><strong>Math hint number 2 :</strong></p>\n\n<p>The number you've counted twice are the multiple of 15.</p>\n\n<p><strong>Math hint number 3 :</strong></p>\n\n<p>The sum of the multiple of 3 (or 5 or 15) below 1000 is the <a href=\"http://en.wikipedia.org/wiki/Arithmetic_progression#Sum\">sum of an arithmetic progression.</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T13:02:15.763", "Id": "36037", "Score": "0", "body": "Oh, sorry, my mistake, I inputted `100` instead of `1000` @Josay" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T17:04:20.053", "Id": "36050", "Score": "2", "body": "Math hint #4: every number that is divideable by an odd number is an odd number itself (so you can skip half of the loop iterations). @Lewis" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T12:37:59.057", "Id": "23380", "ParentId": "23379", "Score": "8" } } ]
<p>You might have read my question on shortening my code to a one-liner for Problem 1. So, I was wondering, is there any more tricks of the trade to shorten my <a href="http://projecteuler.net/problem=2" rel="nofollow">Problem 2</a> solution:</p> <pre><code>fib = [0, 1] final = 1 ra = 0 while final &lt; 4000000: fib.append(fib[-1] + fib[-2]) final = fib[-1] fib.pop() for a in fib: if a%2 == 0: ra += a print(ra) </code></pre> <p>Down to one line??<br /> This is the official Problem 2 question:<blockquote>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</blockquote> Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T15:59:51.477", "Id": "36044", "Score": "5", "body": "Writing everything in a single line is rarely a good idea. Why not strive for the most expressive, readable version, regardless of the number of lines?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T08:52:43.310", "Id": "36084", "Score": "0", "body": "please note that the sharing projecteuler solutions outside the scope of the website is not appreciated. See http://projecteuler.net/about (after loggin in)" } ]
{ "AcceptedAnswerId": "23387", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T13:44:49.857", "Id": "23383", "Score": "2", "Tags": [ "python", "project-euler", "fibonacci-sequence" ], "Title": "Project Euler - Shortening Problem 2" }
23383
accepted_answer
[ { "body": "<p>The first few are probably OK, but you really shouldn't be publishing solutions to Project Euler problems online: don't spoil the fun for others!</p>\n\n<p>This said, there are several things you could consider to improve your code. As you will find if you keep doing Project Euler problems, eventually efficiency becomes paramount. So to get the hang of it, you may want to try and write your program as if being asked for a much, much larger threshold. So some of the pointers I will give you would generally be disregarded as micro optimizations, and rightfully so, but that's the name of the game in Project Euler!</p>\n\n<p>Keeping the general structure of your program, here are a few pointers:</p>\n\n<ul>\n<li>Why start with <code>[0, 1]</code> when they tell you to go with <code>[1, 2]</code>? The performance difference is negligible, but it is also very unnecessary.</li>\n<li>You don't really need several of your intermediate variables.</li>\n<li>You don't need to <code>pop</code> the last value, just ignore it when summing.</li>\n<li>An important thing is that in the Fibonacci sequence even numbers are every third element of the sequence, so you can avoid the divisibility check.</li>\n</ul>\n\n<p>Putting it all together:</p>\n\n<pre><code>import operator\n\ndef p2bis(n) :\n fib = [1, 2]\n while fib[-1] &lt; n :\n fib.append(fib[-1] + fib[-2])\n return reduce(operator.add, fib[1:-1:3])\n</code></pre>\n\n<p>This is some 30% faster than your code, not too much, but the idea of not checking divisibility, but stepping in longer strides over a sequence, is one you want to hold to:</p>\n\n<pre><code>In [4]: %timeit p2(4000000)\n10000 loops, best of 3: 64 us per loop\n\nIn [5]: %timeit p2bis(4000000)\n10000 loops, best of 3: 48.1 us per loop\n</code></pre>\n\n<p>If you wanted to really streamline things, you could get rid of the list altogether and keep a running sum while building the sequence:</p>\n\n<pre><code>def p2tris(n) :\n a, b, c = 1, 1, 2\n ret = 2\n while c &lt; n :\n a = b + c\n b = c + a\n c = a + b\n ret += c\n return ret - c\n</code></pre>\n\n<p>This gives a 7x performance boost, not to mention the memory requirements:</p>\n\n<pre><code>In [9]: %timeit p2tris(4000000)\n100000 loops, best of 3: 9.21 us per loop\n</code></pre>\n\n<p>So now you can compute things that were totally unthinkable before:</p>\n\n<pre><code>In [19]: %timeit p2tris(4 * 10**20000)\n1 loops, best of 3: 3.49 s per loop\n</code></pre>\n\n<p>This type of optimization eventually becomes key in solving more advanced problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T20:09:36.963", "Id": "36065", "Score": "0", "body": "`p2tris` seems to be computing something slightly different than `p2bis`: it's off by 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T05:20:07.447", "Id": "36081", "Score": "0", "body": "@DSM Thanks for checking my code! It is solved now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:31:49.990", "Id": "23387", "ParentId": "23383", "Score": "2" } } ]
<p>I'd like to know any ways of shortening this UI window for Maya, at the moment, because I couldn't find very detailed documentation and not very skilled with python, I have just built this UI with the knowledge that I have already, I know it's not the best way of doing it (using empty text elements to fill gaps etc)</p> <p>Can someone provide me with an example on how to shorten this code or structure it properly?</p> <pre><code>import maya.cmds as cmds class randomScatter(): def __init__(self): if cmds.window("randSelection", exists=1): cmds.deleteUI("randSelection") cmds.window("randSelection", t="Scatter Objects - Shannon Hochkins", w=405, sizeable=0) cmds.rowColumnLayout(nc=3,cal=[(1,"right")], cw=[(1,100),(2,200),(3,105)]) cmds.text(l="Prefix ") cmds.textField("prefix") cmds.text(l="") cmds.text(l="Instanced object(s) ") cmds.textField("sourceObj", editable=0) cmds.button("sourceButton", l="Select") cmds.text(l="Target ") cmds.textField("targetObj", editable=0) cmds.button("targetButton", l="Select") cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.text(l='Copy Options ') cmds.radioButtonGrp('copyOptions', labelArray2=['Duplicate', 'Instance'], numberOfRadioButtons=2, sl=2) cmds.text(l="") cmds.text(l="Rotation Options ") cmds.radioButtonGrp('orientation', labelArray2=['Follow Normals', 'Keep original'], numberOfRadioButtons=2, sl=1) cmds.text(l="") cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.text(l="") cmds.checkBox('copyCheck', l='Stick copies to target mesh.') cmds.text(l="") cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.text('maxNumber', l="Copies ") cmds.intFieldGrp("totalCopies", nf=1, v1=10, cw1=100) cmds.text(l="") cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.text(l='') cmds.text(l=" From To", align='left') cmds.text(l='') cmds.text(l="Random Rotation") cmds.floatFieldGrp("rotValues", nf=2, v1=0, v2=0, cw2=[100,100]) cmds.text(l="") cmds.text(l="Random Scale") cmds.floatFieldGrp("scaleValues", nf=2, v1=0, v2=0, cw2=[100,100]) cmds.text(l="") cmds.setParent("..") cmds.rowColumnLayout(w=405) cmds.separator( height=20, style='in') cmds.text("Progress", height=20) cmds.progressBar('buildGridProgBar', maxValue=100, width=250) cmds.separator( height=20, style='in') cmds.button("excute", l="Scatter Objects", w=403, al="right") cmds.showWindow("randSelection") randomScatter() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T13:59:48.320", "Id": "51163", "Score": "0", "body": "You have alot of cmds.separator lines in a group of 3. Put them in for loops. Allmost everytime when the code looks repetetive, there can be used a loop to shorten it." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T06:02:07.410", "Id": "23413", "Score": "2", "Tags": [ "python" ], "Title": "Shorten Python/Maya Window UI code" }
23413
max_votes
[ { "body": "<p>(1) You define <code>random_scatter</code> as a class but then call it like a function, which works but is confusing. With your programme as it currently stands, there is no reason for it to be a class, so better simply to define <code>random_scatter</code> as a function (use <code>def random_scatter():</code> at the top). </p>\n\n<p>(2) You can remove repetition and make the code more readable using functions and loops, e.g. write a function</p>\n\n<pre><code>def insert_seperators(number):\n for _ in range(number):\n cmds.separator(height=20, style='in')\n</code></pre>\n\n<p>then you can replace </p>\n\n<pre><code> cmds.separator( height=20, style='in')\n cmds.separator( height=20, style='in')\n cmds.separator( height=20, style='in')\n</code></pre>\n\n<p>with</p>\n\n<pre><code> insert_separators(3)\n</code></pre>\n\n<p>(3) If you have other functions doing similar things with <code>cmds</code> then try to see what they have in common and put that in a single function, which accepts parameters according to what changes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T13:09:51.487", "Id": "30559", "ParentId": "23413", "Score": "1" } } ]
<p>This script extracts all urls from a specific HTML div block (with BeautifulSoup 4) : </p> <pre><code>raw_data = dl("http://somewhere") links = [] soup = BeautifulSoup(raw_data) data = str(soup.find_all('div', attrs={'class' : "results"})) for link in BeautifulSoup(data, parse_only = SoupStrainer('a')): links.append(urllib.parse.unquote_plus(link['href'])) return links </code></pre> <p>Is there a more efficient and clean way to do it ?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T09:40:40.713", "Id": "23416", "Score": "1", "Tags": [ "python" ], "Title": "URLs extraction from specific block" }
23416
max_votes
[ { "body": "<p>AFAIK, you can use <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">List comprehension</a> to make it more efficient </p>\n\n<pre><code>raw_data = dl(\"http://somewhere\")\nsoup = BeautifulSoup(raw_data)\ndata = str(soup.find_all('div', attrs={'class' : \"results\"}))\nreturn [ urllib.parse.unquote_plus(link['href']) for link in BeautifulSoup(data, parse_only = SoupStrainer('a'))]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T12:45:56.947", "Id": "23426", "ParentId": "23416", "Score": "1" } } ]
<p>So I am essentially a complete newbie to programming, and have been attempting to learn Python by completing the Project Euler problems. I haven't gotten very far, and this is my code for <a href="http://projecteuler.net/problem=3" rel="nofollow">problem #3</a> :</p> <blockquote> <p>The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <p>Although my solution works, I'd like to know how I can improve.</p> <pre><code>primes = [2] factors = [] def isPrime(x): a = 1 if x == 1: return False while a &lt; x: a += 1 if x % a == 0 and a != x and a != 1: return False break return True def generatePrime(): a = primes[-1]+1 while isPrime(a) == False: a += 1 primes.append(a) def primeFactor(x): a = primes[-1] while a &lt;= x: if x % a == 0: factors.append(a) x /= a generatePrime() a = primes[-1] primeFactor(input("Enter the number: ")) print("The prime factors are: " + str(factors) + "\nThe largest prime factor is: " + str(sorted(factors)[-1])) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T14:06:48.310", "Id": "36112", "Score": "0", "body": "You should replace `while a < x:` with `while a < math.sqrt(x):` You can also check whether x is even and > 2, in that case it is not a prime, also google for 'prime sieve'." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T13:17:46.433", "Id": "23429", "Score": "8", "Tags": [ "python", "project-euler", "primes" ], "Title": "Project Euler #3 - how inefficient is my code?" }
23429
max_votes
[ { "body": "<p>You can save quite a bit time on your prime generation. What you should keep in mind is that a prime is a number which is no multiple of a prime itself; all other numbers are.</p>\n\n<p>So in your <code>isPrime</code> function you can just go through your primes list and check if each prime is a divisor of the number. If not, then it is a prime itself. Of course you would need to make sure that you fill your primes list enough first.</p>\n\n<p>As the most basic idea, you only need to check until <code>sqrt(n)</code>, so you only generate numbers this far. And you can also just skip every even number directly. You could also make similar assumptions for numbers dividable by 3 etc., but the even/uneven is the simplest one and enough to get fast results for not too big numbers.</p>\n\n<p>So a prime generation algorithm, for possible prime divisors up to <code>n</code>, could look like this:</p>\n\n<pre><code>primes = [2]\nfor i in range(3, int(math.sqrt(n)), 2):\n isPrime = not any(i % p == 0 for p in primes)\n if isPrime:\n primes.append(i)\n</code></pre>\n\n<p>Then to get the prime factors of <code>n</code>, you just need to check those computed primes:</p>\n\n<pre><code>primeFactors = []\nm = n\nfor p in primes:\n while m % p == 0:\n m = m / p\n primeFactors.append(p)\n if m == 0:\n break\n\nprint('The prime factorization of `{0}` is: {1}'.format(n, '×'.join(map(str,primeFactors))))\n</code></pre>\n\n<p>For the euler problem 3 with <code>n = 317584931803</code>, this would produce the following output:</p>\n\n<blockquote>\n <p>The prime factorization of <code>317584931803</code> is: 67×829×1459×3919</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T18:42:02.080", "Id": "36164", "Score": "0", "body": "If you are not going to sieve to calculate your primes, you should at least bring together your prime calculation and factor testing together, so that as soon as you find the `67` factor, your largest prime to calculate is reduced from `563546` to `68848`, and by the time you know `829` is a prime to `2391`, and once `1459` is known as a prime you don't calculate any more primes to test as factors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T19:19:03.887", "Id": "36167", "Score": "0", "body": "@Jaime Sure, you can again save a lot when combining those two. My original solution for problem 3 (which btw. doesn’t even require factorization) is a lot more concise too. But given OP’s original code structure I thought it would make more sense to show separated and reusable pieces. With my example I could once generate the primes and then just run the factorization against multiple numbers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T16:58:58.283", "Id": "23447", "ParentId": "23429", "Score": "5" } } ]
<p>I've never had a serious attempt at writing an encryption algorithm before, and haven't read much on the subject. I have tried to write an encryption algorithm (of sorts), I would just like to see if anyone thinks it's any good. (Obviously, it's not going to be comparable to those actually used, given that it's a first attempt)</p> <p>Without further adieu:</p> <pre><code>def encode(string, giveUserKey = False, doubleEncode = True): encoded = [] #Numbers representing encoded characters keys = [] #Key numbers to unlonk code fakes = [] #Which items in "encoded" are fake #All of these are stored in a file if giveUserKey: userkey = random.randrange(2 ** 10, 2 ** 16) # Key given to the user, entered during decryption for confirmation # Could change range for greater security else: userkey = 1 for char in string: ordChar = ord(char) key = random.randrange(sys.maxsize) encoded.append(hex((ordChar + key) * userkey)) keys.append(hex(key)) if random.randrange(fakeRate) == 0: fake = hex(random.randrange(sys.maxsize) * userkey) encoded.append(fake) fakes.append(fake) if doubleEncode: encoded = [string.encode() for string in encoded] keys = [string.encode() for string in keys] fakes = [string.encode() for string in fakes] hashValue = hex(hash("".join([str(obj) for obj in encoded + keys + fakes]))).encode() return encoded, keys, hashValue, fakes, userkey def decode(encoded, keys, hashValue, fakes, userkey = 1): if hash("".join([str(obj) for obj in encoded + keys + fakes])) != eval(hashValue): #File has been tampered with, possibly attempted reverse-engineering return "ERROR" for fake in fakes: encoded.remove(fake) decoded = "" for i in range(len(keys)): j = eval(encoded[i]) / userkey decoded += chr(int(j - eval(keys[i]))) return decoded </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T16:49:41.997", "Id": "36238", "Score": "0", "body": "usually an encryption algo takes input `data` and a `key`(private/symmetric) then outputs `cipher`. What's with `fakes` and `keys` in your case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T16:53:09.137", "Id": "36239", "Score": "0", "body": "\"fakes\" are fake bits of data inserted in to the code. \"keys\" are the keys from the file used to determine what the characters should actually be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T16:55:52.487", "Id": "36240", "Score": "0", "body": "If two parties say `A` & `B`, then isn't it necessary to exchange these `fakes`, `keys` along with actual `cipher` and `Key`(public/symmetric)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T17:01:12.870", "Id": "36241", "Score": "0", "body": "I don't quite know what you mean. fakes and keys are exchanged in that they are written in to the file which is exchanged. (There is then \"userkey\" which is not written in to the file. It can be specified by the encryptor whether this is needed. It is then told to them and needs to be entered for decryption)." } ]
{ "AcceptedAnswerId": "23506", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T16:42:35.983", "Id": "23492", "Score": "4", "Tags": [ "python", "algorithm" ], "Title": "Is this a good encryption algorithm?" }
23492
accepted_answer
[ { "body": "<p>Firstly, your encryption is useless. Just run this one line of python code:</p>\n\n<pre><code>print reduce(fractions.gcd, map(eval, encoded))\n</code></pre>\n\n<p>And it will tell you what your user key is (with a pretty high probability). </p>\n\n<p>Your algorithm is really obfuscation, not encrytion. Encryption is designed so that even if you know the algorithm, but not the key, you can't decryt the message. But your algorithm is basically designed to make it less obvious what the parts mean, not make it hard to decrypt without the key. As demonstrated, retrieving the key is trivial anyways. </p>\n\n<pre><code>def encode(string, giveUserKey = False, doubleEncode = True):\n</code></pre>\n\n<p>Python convention is lowercase_with_underscores for local names</p>\n\n<pre><code> encoded = [] #Numbers representing encoded characters\n keys = [] #Key numbers to unlonk code\n fakes = [] #Which items in \"encoded\" are fake\n #All of these are stored in a file\n\n if giveUserKey:\n userkey = random.randrange(2 ** 10, 2 ** 16)\n # Key given to the user, entered during decryption for confirmation\n # Could change range for greater security\n</code></pre>\n\n<p>Why isn't the key a parameter?</p>\n\n<pre><code> else:\n userkey = 1\n\n for char in string:\n ordChar = ord(char)\n key = random.randrange(sys.maxsize)\n encoded.append(hex((ordChar + key) * userkey))\n keys.append(hex(key))\n</code></pre>\n\n<p>These just aren't keys. Don't call them that.</p>\n\n<pre><code> if random.randrange(fakeRate) == 0:\n fake = hex(random.randrange(sys.maxsize) * userkey)\n encoded.append(fake)\n fakes.append(fake)\n\n if doubleEncode:\n encoded = [string.encode() for string in encoded]\n keys = [string.encode() for string in keys]\n fakes = [string.encode() for string in fakes]\n</code></pre>\n\n<p>Since these are all hex strings, why in the world are you encoding them?</p>\n\n<pre><code> hashValue = hex(hash(\"\".join([str(obj) for obj in encoded + keys + fakes]))).encode()\n\n return encoded, keys, hashValue, fakes, userkey\n\ndef decode(encoded, keys, hashValue, fakes, userkey = 1):\n if hash(\"\".join([str(obj) for obj in encoded + keys + fakes])) != eval(hashValue):\n #File has been tampered with, possibly attempted reverse-engineering\n return \"ERROR\"\n</code></pre>\n\n<p>Do not report errors by return value, use exceptions.</p>\n\n<pre><code> for fake in fakes:\n encoded.remove(fake)\n</code></pre>\n\n<p>What if coincidentally one of the fakes looks just like one of the data segments?</p>\n\n<pre><code> decoded = \"\"\n\n for i in range(len(keys)):\n</code></pre>\n\n<p>Use <code>zip</code> to iterate over lists in parallel</p>\n\n<pre><code> j = eval(encoded[i]) / userkey\n</code></pre>\n\n<p>Using <code>eval</code> is considered a bad idea. It'll execute any python code passed to it and that could be dangerous.</p>\n\n<pre><code> decoded += chr(int(j - eval(keys[i])))\n</code></pre>\n\n<p>It's better to append strings into a list and join them.</p>\n\n<pre><code> return decoded\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T21:20:47.527", "Id": "23506", "ParentId": "23492", "Score": "5" } } ]
<p>My context is a very simple filter-like program that streams lines from an input file into an output file, filtering out lines the user (well, me) doesn't want. The filter is rather easy, simply requiring a particular value for some 'column' in the input file. Options are easily expressed with <code>argparse</code>:</p> <pre><code>parser.add_argument('-e', '--example', type=int, metavar='EXAMPLE', help='require a value of %(metavar)s for column "example"') </code></pre> <p>There's a few of these, all typed. As the actual filter gets a line at some point, the question whether to include such a line is simple: split the line and check all the required filters:</p> <pre><code>c1, c2, c3, *_ = line.split('\t') c1, c2, c3 = int(c1), int(c2), int(c3) # ← this line bugs me if args.c1 and args.c1 != c1: return False </code></pre> <p>The second line of which bugs me a bit: as the values are initially strings and I need them to be something else, the types need to be changed. Although short, I'm not entirely convinced this is the best solution. Some other options:</p> <ul> <li>create a separate function to hide the thing that bugs me;</li> <li>remove the <code>type=</code> declarations from the options (also removes automatic user input validation);</li> <li>coerce the arguments back to <code>str</code>s and do the comparison with <code>str</code>s (would lead to about the same as what I've got).</li> </ul> <p>Which of the options available would be the 'best', 'most pythonic', 'prettiest'? Or am I just overthinking this...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T13:59:23.147", "Id": "36310", "Score": "0", "body": "`int()` skips leading and trailing whitespace and leading zeros. So, a string comparison is not quite the same. Which do you need?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T14:34:26.357", "Id": "36313", "Score": "0", "body": "I need the numeric value. My data doesn't contain extraneous whitespace or zeroes, thought that doesn't much matter for the issue at hand." } ]
{ "AcceptedAnswerId": "23560", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T12:24:18.877", "Id": "23531", "Score": "3", "Tags": [ "python", "type-safety" ], "Title": "Pythonic type coercion from input" }
23531
accepted_answer
[ { "body": "<h3>1. Possible bugs</h3>\n\n<p>I can't be certain that these are bugs, but they look dodgy to me:</p>\n\n<ol>\n<li><p>You can't filter on the number 0, because if <code>args.c1</code> is 0, then it will test false and so you'll never compare it to <code>c1</code>. Is this a problem? If it is, you ought to compare <code>args.c1</code> explicitly against <code>None</code>.</p></li>\n<li><p>If the string <code>c1</code> cannot be converted to an integer, then <code>int(c1)</code> will raise <code>ValueError</code>. Is this what you want? Would it be better to treat this case as \"not matching the filter\"?</p></li>\n<li><p>If <code>line</code> has fewer than three fields, the assignment to <code>c1, c2, c3, *_</code> will raise <code>ValueError</code>. Is this what you want? Would it be better to treat this case as \"not matching the filter\"?</p></li>\n</ol>\n\n<h3>2. Suggested improvement</h3>\n\n<p>Fixing the possible bugs listed above:</p>\n\n<pre><code>def filter_field(filter, field):\n \"\"\"\n Return True if the string `field` passes `filter`, which is\n either None (meaning no filter), or an int (meaning that \n `int(field)` must equal `filter`).\n \"\"\"\n try:\n return filter is None or filter == int(field)\n except ValueError:\n return False\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>filters = [args.c1, args.c2, args.c3]\nfields = line.split('\\t')\nif len(fields) &lt; len(filters):\n return False\nif not all(filter_field(a, b) for a, b in zip(filters, fields)):\n return False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T11:21:07.007", "Id": "36341", "Score": "0", "body": "1: figured that as well, though my current context will never 'require' a falsy value. 2: valid point, crashing isn't good, even though I'd expect only integers. 3: also a valid point, though my lines contain far more than 3 values in reality.\nFurthermore, I like your idea of using `all` and `zip`; does feel prettier to me :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T09:51:20.527", "Id": "23560", "ParentId": "23531", "Score": "1" } } ]
<p>My context is a very simple filter-like program that streams lines from an input file into an output file, filtering out lines the user (well, me) doesn't want. The filter is rather easy, simply requiring a particular value for some 'column' in the input file. Options are easily expressed with <code>argparse</code>:</p> <pre><code>parser.add_argument('-e', '--example', type=int, metavar='EXAMPLE', help='require a value of %(metavar)s for column "example"') </code></pre> <p>There's a few of these, all typed. As the actual filter gets a line at some point, the question whether to include such a line is simple: split the line and check all the required filters:</p> <pre><code>c1, c2, c3, *_ = line.split('\t') c1, c2, c3 = int(c1), int(c2), int(c3) # ← this line bugs me if args.c1 and args.c1 != c1: return False </code></pre> <p>The second line of which bugs me a bit: as the values are initially strings and I need them to be something else, the types need to be changed. Although short, I'm not entirely convinced this is the best solution. Some other options:</p> <ul> <li>create a separate function to hide the thing that bugs me;</li> <li>remove the <code>type=</code> declarations from the options (also removes automatic user input validation);</li> <li>coerce the arguments back to <code>str</code>s and do the comparison with <code>str</code>s (would lead to about the same as what I've got).</li> </ul> <p>Which of the options available would be the 'best', 'most pythonic', 'prettiest'? Or am I just overthinking this...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T13:59:23.147", "Id": "36310", "Score": "0", "body": "`int()` skips leading and trailing whitespace and leading zeros. So, a string comparison is not quite the same. Which do you need?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T14:34:26.357", "Id": "36313", "Score": "0", "body": "I need the numeric value. My data doesn't contain extraneous whitespace or zeroes, thought that doesn't much matter for the issue at hand." } ]
{ "AcceptedAnswerId": "23560", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T12:24:18.877", "Id": "23531", "Score": "3", "Tags": [ "python", "type-safety" ], "Title": "Pythonic type coercion from input" }
23531
accepted_answer
[ { "body": "<h3>1. Possible bugs</h3>\n\n<p>I can't be certain that these are bugs, but they look dodgy to me:</p>\n\n<ol>\n<li><p>You can't filter on the number 0, because if <code>args.c1</code> is 0, then it will test false and so you'll never compare it to <code>c1</code>. Is this a problem? If it is, you ought to compare <code>args.c1</code> explicitly against <code>None</code>.</p></li>\n<li><p>If the string <code>c1</code> cannot be converted to an integer, then <code>int(c1)</code> will raise <code>ValueError</code>. Is this what you want? Would it be better to treat this case as \"not matching the filter\"?</p></li>\n<li><p>If <code>line</code> has fewer than three fields, the assignment to <code>c1, c2, c3, *_</code> will raise <code>ValueError</code>. Is this what you want? Would it be better to treat this case as \"not matching the filter\"?</p></li>\n</ol>\n\n<h3>2. Suggested improvement</h3>\n\n<p>Fixing the possible bugs listed above:</p>\n\n<pre><code>def filter_field(filter, field):\n \"\"\"\n Return True if the string `field` passes `filter`, which is\n either None (meaning no filter), or an int (meaning that \n `int(field)` must equal `filter`).\n \"\"\"\n try:\n return filter is None or filter == int(field)\n except ValueError:\n return False\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>filters = [args.c1, args.c2, args.c3]\nfields = line.split('\\t')\nif len(fields) &lt; len(filters):\n return False\nif not all(filter_field(a, b) for a, b in zip(filters, fields)):\n return False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T11:21:07.007", "Id": "36341", "Score": "0", "body": "1: figured that as well, though my current context will never 'require' a falsy value. 2: valid point, crashing isn't good, even though I'd expect only integers. 3: also a valid point, though my lines contain far more than 3 values in reality.\nFurthermore, I like your idea of using `all` and `zip`; does feel prettier to me :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T09:51:20.527", "Id": "23560", "ParentId": "23531", "Score": "1" } } ]
<pre><code>#!/usr/bin/env python import os, sys variable = sys.argv def enVar(variable): """ This function returns all the environment variable set on the machine or in active project. if environment variable name is passed to the enVar function it returns its values. """ nVar = len(sys.argv)-1 if len(variable) == 1: # if user entered no environment variable name for index, each in enumerate(sorted(os.environ.iteritems())): print index, each else: # if user entered one or more than one environment variable name for x in range(nVar): x+=1 if os.environ.get(variable[x].upper()): # convertes to upper if user mistakenly enters lowecase print "%s : %s" % (variable[x].upper(), os.environ.get(variable[x].upper())) else: print 'Make sure the Environment variable "%s" exists or spelled correctly.' % variable[x] enVar(variable) </code></pre> <p>i run the above file as <code>show.py</code> is their a better way to do it ?</p>
[]
{ "AcceptedAnswerId": "23628", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T15:29:46.960", "Id": "23623", "Score": "6", "Tags": [ "python" ], "Title": "this code returns environment varibles or passed enverionment variable with values" }
23623
accepted_answer
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li>Indent with 4 spaces (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>)</li>\n<li>Use <code>underscore_names</code> for function and variables.</li>\n<li>Use meaningful names for functions (specially) and variables.</li>\n<li>Be concise in docstrings.</li>\n<li>Don't write <code>for index in range(iterable):</code> but <code>for element in iterable:</code>.</li>\n<li>Don't write <code>variable = sys.argv</code> in the middle of the code, use it directly as an argument.</li>\n<li>Use an import for each module.</li>\n</ul>\n\n<p>I'd write (Python 3.0):</p>\n\n<pre><code>import sys\nimport os\n\ndef print_environment_variables(variables):\n \"\"\"Print environment variables (all if variables list is empty).\"\"\"\n if not variables:\n for index, (variable, value) in enumerate(sorted(os.environ.items())):\n print(\"{0}: {1}\".format(variable, value))\n else: \n for variable in variables:\n value = os.environ.get(variable)\n if value:\n print(\"{0}: {1}\".format(variable, value))\n else:\n print(\"Variable does not exist: {0}\".format(variable))\n\nprint_environment_variables(sys.argv[1:])\n</code></pre>\n\n<p>But if you asked me, I would simplify the function without second thoughts, functions are more useful when they are homogeneous (that's it, they return similar outputs for the different scenarios):</p>\n\n<pre><code>def print_environment_variables(variables):\n \"\"\"Print environment variables (all if variables list is empty).\"\"\"\n variables_to_show = variables or sorted(os.environ.keys())\n for index, variable in enumerate(variables_to_show):\n value = os.environ.get(variable) or \"[variable does not exist]\"\n print(\"{0}: {1}={2}\".format(index, variable, value))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T18:46:50.090", "Id": "23628", "ParentId": "23623", "Score": "3" } } ]
<p>I am writing a specialized version of the cross correlation function as used in neuroscience. The function below is supposed to take a time series <code>data</code> and ask how many of its values fall in specified bins. My function <code>xcorr</code> works but is horrifically slow even. A test data set with 1000 points (and so 0.5*(1000*999) intervals) distributed over 400 bins takes almost ten minutes.</p> <p><strong>Bottleneck</strong></p> <p>The bottleneck is in the line <code>counts = array([sum ...</code>. I assume it is there because each iteration of the <code>foreach</code> loop searches through the entire vector <code>diffs</code>, which is of length <code>len(first)**2</code>.</p> <pre><code>def xcorr(first,second,dt=0.001,window=0.2,savename=None): length = min(len(first),len(second)) diffs = array([first[i]-second[j] for i in xrange(length) for j in xrange(length)]) bins = arange(-(int(window/dt)),int(window/dt)) counts = array[sum((diffs&gt;((i-.5)*dt)) &amp; (diffs&lt;((i+.5)*dt))) for i in bins] counts -= len(first)**2*dt/float(max(first[-1],second[-1])) #Normalization if savename: cPickle.dump((bins*dt,counts),open(savename,'wb')) return (bins,counts) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T14:43:36.820", "Id": "23656", "Score": "3", "Tags": [ "python", "performance", "numpy", "statistics" ], "Title": "Specialized version of the cross correlation function" }
23656
max_votes
[ { "body": "<p>Here's a crack at my own question that uses built-in functions from <code>NumPy</code> </p>\n\n<p><strong>Update</strong></p>\n\n<p>The function chain <code>bincount(digitize(data,bins))</code> is equivalent to <code>histogram</code>, which allows for a more succinct expression.</p>\n\n<pre><code> def xcorr(first,second,dt=0.001,window=0.2,savename=None):\n length = min(len(first),len(second))\n diffs = array([first[i]-second[j] for i in xrange(length) for j in xrange(length)])\n counts,edges = histogram(diffs,bins=arange(-window,window,dt))\n counts -= length**2*dt/float(first[length])\n if savename:\n cPickle.dump((counts,edges[:-1]),open(savename,'wb'))\n return (counts,edges[:-1])\n</code></pre>\n\n<p>The indexing in the <code>return</code> statement comes because I want to ignore the edge bins. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:05:23.163", "Id": "23663", "ParentId": "23656", "Score": "1" } } ]
<p><strong>Premise:</strong> Write a program that counts the frequencies of each word in a text, and output each word with its count and line numbers where it appears. We define a word as a contiguous sequence of non-white-space characters. Different capitalizations of the same character sequence should be considered same word (e.g. Python and python). The output is formatted as follows: each line begins with a number indicating the frequency of the word, a white space, then the word itself, and a list of line numbers containing this word. You should output from the most frequent word to the least frequent. In case two words have the same frequency, the lexicographically smaller one comes first. All words are in lower case in the output.</p> <p><strong>Solution:</strong></p> <pre><code># Amazing Python libraries that prevent re-invention of wheels. import re import collections import string from operator import itemgetter # Simulate work for terminal print 'Scanning input for word frequency...' # Text files input = open('input.txt', 'r') output = open('output.txt', 'w') # Reads every word in input as lowercase while ignoring punctuation and # returns a list containing 2-tuples of (word, frequency). list = collections.Counter(input.read().lower() .translate(None, string.punctuation).split()).most_common() # Sorts the list by frequency in descending order. list = sorted(list, key=itemgetter(0)) # Sorts the list by lexicogrpahical order in descending order while maintaining # previous sorting. list = sorted(list, key=itemgetter(1), reverse=True) # Gets the lines where each word in list appears in the input. for word in list: lineList = [] # Reads the input line by line. Stores each text line in 'line' and keeps a # counter in 'lineNum' that starts at 1. for lineNum, line in enumerate(open('input.txt'),1): # If the word is in the current line then add it to the list of lines # in which the current word appears in. The word frequency list is not # mutated. This is stored in a separate list. if re.search(r'(^|\s)'+word[0]+'\s', line.lower().translate(None, string.punctuation), flags=re.IGNORECASE): lineList.append(lineNum) # Write output with proper format. output.write(str(word[1]) + ' ' + word[0] + ' ' + str(lineList)+'\n') # End work simulation for terminal print 'Done! Output in: output.txt' </code></pre> <p>How can I get the line numbers without re-reading the text? I want to achieve sub-O(n^2) time complexity. I am new to Python so feedback on other aspects is greatly appreciated as well.</p>
[]
{ "AcceptedAnswerId": "23681", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:00:50.760", "Id": "23662", "Score": "4", "Tags": [ "python", "optimization" ], "Title": "Improve efficiency for finding word frequency in text" }
23662
accepted_answer
[ { "body": "<p>You're right, the basic point to make this program faster is to store the line numbers in the first pass.</p>\n\n<p>The <code>for word in list</code> loop will run many times. The count depends on how many words you have. Every time it runs, it reopens and rereads the whole input file. This is awfully slow.</p>\n\n<p>If you start using a more generic data structure than your <code>Counter()</code>, then you'll be able to store the line numbers. For example you could use a dictionary. The key of the dict is the word, the value is a list of line numbers. The hit count is stored indirectly as the length of the list of line numbers.</p>\n\n<p>In one pass over the input you can populate this data structure. In a second step, you can properly sort this data structure and iterate over the elements.</p>\n\n<p>An example implementation:</p>\n\n<pre><code>from collections import defaultdict\nimport sys \n\nif __name__ == \"__main__\":\n hit = defaultdict(list)\n for lineno, line in enumerate(sys.stdin, start=1):\n for word in line.split():\n hit[word.lower()].append(lineno)\n for word, places in sorted(hit.iteritems(), key=lambda (w, p): (-len(p), w)):\n print len(places), word, \",\".join(map(str, sorted(set(places))))\n</code></pre>\n\n<p>A few more notes:</p>\n\n<ol>\n<li><p>If you <code>open()</code> a file, <code>close()</code> it too. As soon as you're done with using it. (Or use <a href=\"http://docs.python.org/2/reference/compound_stmts.html#the-with-statement\" rel=\"nofollow\">the <code>with</code> statement</a> to ensure that it gets closed.)</p></li>\n<li><p>Don't hardcode input/output file names. Read from standard input (<code>sys.stdin</code>), write to standard output (<code>sys.stdout</code> or simply <code>print</code>), and let the user use his shell's redirections: <code>program &lt;input.txt &gt;output.txt</code></p></li>\n<li><p>Don't litter standard output with progress messages. If you absolutely need them use <code>sys.stderr.write</code> or get acquainted with the <code>logging</code> module.</p></li>\n<li><p>Don't use regular expressions, unless it's necessary. Prefer string methods for their simplicity and speed.</p></li>\n<li><p>Name your variables in <code>lower_case_with_underscores</code> as <a href=\"https://www.google.co.uk/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CDIQFjAA&amp;url=http://www.python.org/dev/peps/pep-0008/&amp;ei=8Pc9UfzGLKaM7AaSloB4&amp;usg=AFQjCNERHdnSYA5JWg_ZfKT_cVYU4MWGyw&amp;bvm=bv.43287494,d.ZGU\" rel=\"nofollow\">PEP8</a> recommends.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T05:38:24.860", "Id": "36524", "Score": "0", "body": "Great review. Are there any performance reasons for note 2? Also, when you say \"let the user use his shell's redirections: `program <input.txt >output.txt`\" does that mean that when I run my program from the terminal I can pass the filenames as arguments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T09:21:06.210", "Id": "36528", "Score": "1", "body": "There are cases when (2) can help in better performance. In a pipeline like `prg1 <input.txt | prg2 >output.txt` prg1 and prg2 are started in parallel (at least in unix-like OSes). prg2 does not have to wait for prg1 to finish, but can start to work when prg1 produced any output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T09:28:59.343", "Id": "36529", "Score": "1", "body": "__Can I pass the filenames as arguments?__ Yes, you can specify the filenames in the terminal. To be precise, these are not arguments, they are not processed by your program. They are called `shell redirections` and are processed by your command shell. They are extra useful, google them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:18:21.743", "Id": "36621", "Score": "0", "body": "@Gareth Rees: I'm not sure whether you have noticed, but with your edit you introduced a little semantic change. The edited code counts a word at most once per line. Previously (as in the OP) it counted multiple occurences in the same line, but later printed the line number only once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:29:44.803", "Id": "36625", "Score": "0", "body": "@rubasov: You're quite right. That was my mistake." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T22:39:58.410", "Id": "23681", "ParentId": "23662", "Score": "3" } } ]
<p>I created this version of Hangman in Python 3. Does anyone have any tips for optimization or improvement?</p> <pre><code>import random HANGMAN = ( ''' -------+''', ''' + | | | | | -------+''', ''' -----+ | | | | | -------+''', ''' -----+ | | | | | | -------+''', ''' -----+ | | O | | | | -------+''', ''' -----+ | | O | | | | | -------+''', ''' -----+ | | O | /| | | | -------+''', ''' -----+ | | O | /|\ | | | -------+''', ''' -----+ | | O | /|\ | / | | -------+''', ''' -----+ | | O | /|\ | / \ | | -------+''') MAX = len(HANGMAN) - 1 WORDS = ('jazz', 'buzz', 'hajj', 'fuzz', 'jinx', 'jazzy', 'fuzzy', 'faffs', 'fizzy', 'jiffs', 'jazzed', 'buzzed', 'jazzes', 'faffed', 'fizzed', 'jazzing', 'buzzing', 'jazzier', 'faffing', 'fuzzing') sizeHangman = 0 word = random.choice(WORDS) hiddenWord = list('-' * len(word)) lettersGuessed = [] print('\tHANGMAN GAME\n\t\tBy Lewis Cornwall\n') while sizeHangman &lt; MAX: print('This is your hangman:' + HANGMAN[sizeHangman] + '\nThis is the word:\n' + ''.join(hiddenWord) + '\nThese are the letters you\'ve already guessed:\n' + str(lettersGuessed)) guess = input('Guess a letter: ').lower() while guess in lettersGuessed: print('You\'ve already guessed that letter!') guess = input('Guess a letter: ').lower() if guess in word: print('Well done, "' + guess + '" is in my word!') for i in range(len(word)): if guess == word[i]: hiddenWord[i] = guess if hiddenWord.count('-') == 0: print('Congratulations! My word was ' + word + '!') input('Press &lt;enter&gt; to close.') quit() else: print('Unfortunately, "' + guess + '" is not in my word.') sizeHangman += 1 lettersGuessed.append(guess) print('This is your hangman: ' + HANGMAN[sizeHangman] + 'You\'ve been hanged! My word was actually ' + word + '.') input('Press &lt;enter&gt; to close.') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T13:22:45.947", "Id": "36588", "Score": "2", "body": "Not an optimization, but you could load your words from a - possibly encrypted - text file instead of having them in your raw code :)" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T21:43:33.187", "Id": "23678", "Score": "6", "Tags": [ "python", "optimization", "game", "python-3.x", "hangman" ], "Title": "Hangman in Python" }
23678
max_votes
[ { "body": "<p>You can avoid repeating <code>guess = input('Guess a letter: ').lower()</code> by changing the inner while loop to:</p>\n\n<pre><code>while True:\n guess = input('Guess a letter: ').lower()\n if guess in lettersGuessed:\n print('You\\'ve already guessed that letter!')\n else:\n break\n</code></pre>\n\n<p>Instead of <code>for i in range(len(word))</code> use:</p>\n\n<pre><code>for i, letter in enumerate(word):\n</code></pre>\n\n<p>You could also avoid indexing by <code>i</code> altogether by using a list comprehension. I'm not sure if this is as clear in this case, though.</p>\n\n<pre><code>hiddenWord = [guess if guess == letter else hidden for letter, hidden in zip(word, hiddenWord)]\n</code></pre>\n\n<p>Instead of <code>hiddenWord.count('-') == 0</code> use:</p>\n\n<pre><code>'-' not in hiddenWord\n</code></pre>\n\n<p><a href=\"http://docs.python.org/3/library/constants.html#constants-added-by-the-site-module\">The docs</a> say <code>quit()</code> should not be used in programs. Your <code>count('-') == 0</code> check is unnecessarily inside the <code>for i</code> loop. If you move it after the loop, you could use <code>break</code> to exit the main loop. You could add an <code>else</code> clause to the main <code>with</code> statement for dealing with the \"You've been hanged\" case. The main loop becomes:</p>\n\n<pre><code>while sizeHangman &lt; MAX:\n print('This is your hangman:' + HANGMAN[sizeHangman] + '\\nThis is the word:\\n' + ''.join(hiddenWord) + '\\nThese are the letters you\\'ve already guessed:\\n' + str(lettersGuessed))\n while True:\n guess = input('Guess a letter: ').lower()\n if guess in lettersGuessed:\n print('You\\'ve already guessed that letter!')\n else:\n break\n if guess in word:\n print('Well done, \"' + guess + '\" is in my word!')\n for i, letter in enumerate(word):\n if guess == letter:\n hiddenWord[i] = guess\n if '-' not in hiddenWord:\n print('Congratulations! My word was ' + word + '!')\n break\n else:\n print('Unfortunately, \"' + guess + '\" is not in my word.')\n sizeHangman += 1\n lettersGuessed.append(guess)\nelse:\n print('This is your hangman: ' + HANGMAN[sizeHangman] + 'You\\'ve been hanged! My word was actually ' + word + '.')\ninput('Press &lt;enter&gt; to close.')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T13:36:26.593", "Id": "23733", "ParentId": "23678", "Score": "6" } } ]
<p>The required output is stated just before the <code>main()</code> function. Is there a better way to achieve it? I feel like I am repeating code unnecessarily but am unable to find a better way to get the result. Not squeezing the code too much, like one liners, but reasonably using better logic.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- #Time to play a guessing game. #Enter a number between 1 and 100: 62 #Too high. Try again: 32 #Too low. Try again: 51 #Too low. Try again: 56 #Congratulations! You got it in 4 guesses. import random def main(): return 0 if __name__ == '__main__': main() print("Time to play a guessing game.") val = random.randint(1, 100) guess = 0 count = 1 guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) print("") print("randint is", val) print("") if (guess == val): print("\nCongratulations! You got it in", count, "guesses.") while(guess != val): if guess &gt; val: print("Too high. Try again:", guess) guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) count = count + 1 if guess == val: print("\nCongratulations! You got it in", count, "guesses.") break elif guess &lt; val: print("Too low. Try again:", guess) guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) count = count + 1 if guess == val: print("\nCongratulations! You got it in", count, "guesses.") break else: pass print("") </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T14:43:48.083", "Id": "23694", "Score": "12", "Tags": [ "python", "game" ], "Title": "Guessing Game: computer generated number between 1 and 100 guessed by user" }
23694
max_votes
[ { "body": "<ol>\n<li>The pythonic way to do <code>count = count + 1</code> is <code>count += 1</code></li>\n<li><p>You don't need to repeat the 'guess again' part of the game twice:</p>\n\n<pre><code>if guess &gt; val:\n print(\"Too high. Try again:\", guess) \nelif guess &lt; val:\n print(\"Too low. Try again:\", guess)\nguess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\ncount += 1\nif guess == val:\n print(\"\\nCongratulations! You got it in\", count, \"guesses.\")\n break\n</code></pre></li>\n<li><p>You don't need to add the extra <code>if</code> statement because if <code>guess != val</code>, then the loop with break anyway:</p>\n\n<pre><code>while guess != val:\n if guess &gt; val:\n print(\"Too high. Try again:\", guess) \n elif guess &lt; val:\n print(\"Too low. Try again:\", guess)\n guess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\n count += 1\nprint(\"Congratulations! You got it in\", count, \"guesses.\")\n</code></pre></li>\n<li><p>I think <code>print(\"randint is\", val)</code> was probably for testing purposes, but it's still in your code!</p></li>\n<li><p>If you execute your program outside the command module (I'm not quite sure what it's called), the program will close immediately after it's finished; it's always best to give the user the choice of when to quit, so insert this at the end of your code:</p>\n\n<pre><code>input(\"Press enter to quit\")\n</code></pre></li>\n<li><p>The first section is unneeded:</p>\n\n<pre><code>def main():`, `if __name__ == \"__main__\":\n</code></pre></li>\n<li><p>The first <code>if</code> statement is also unneeded:</p>\n\n<pre><code>if guess == val:\n</code></pre></li>\n<li><p>You don't need to define <code>guess = 0</code> the first time.</p></li>\n</ol>\n\n<p>So, all in all, my improvement of your code is:</p>\n\n<pre><code>import random\nprint(\"Time to play a guessing game.\")\nval = random.randint(1, 100)\ncount = 1 \nguess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\nwhile(guess != val): \n if guess &gt; val:\n print(\"Too high. Try again:\", guess) \n elif guess &lt; val:\n print(\"Too low. Try again:\", guess)\n guess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\n count += 1\nprint(\"\\nCongratulations! You got it in \", count, \" guesses.\")\ninput(\"Press enter to quit.\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:01:52.480", "Id": "36567", "Score": "0", "body": "I'd use instead of `while guess != val:` is `elif guess == val` then break" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-27T06:14:20.910", "Id": "261599", "Score": "0", "body": "One minor thing: `while(guess != val):` can be changed to `while guess != val:`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T15:09:37.870", "Id": "23696", "ParentId": "23694", "Score": "10" } } ]
<p>The required output is stated just before the <code>main()</code> function. Is there a better way to achieve it? I feel like I am repeating code unnecessarily but am unable to find a better way to get the result. Not squeezing the code too much, like one liners, but reasonably using better logic.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- #Time to play a guessing game. #Enter a number between 1 and 100: 62 #Too high. Try again: 32 #Too low. Try again: 51 #Too low. Try again: 56 #Congratulations! You got it in 4 guesses. import random def main(): return 0 if __name__ == '__main__': main() print("Time to play a guessing game.") val = random.randint(1, 100) guess = 0 count = 1 guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) print("") print("randint is", val) print("") if (guess == val): print("\nCongratulations! You got it in", count, "guesses.") while(guess != val): if guess &gt; val: print("Too high. Try again:", guess) guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) count = count + 1 if guess == val: print("\nCongratulations! You got it in", count, "guesses.") break elif guess &lt; val: print("Too low. Try again:", guess) guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) count = count + 1 if guess == val: print("\nCongratulations! You got it in", count, "guesses.") break else: pass print("") </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T14:43:48.083", "Id": "23694", "Score": "12", "Tags": [ "python", "game" ], "Title": "Guessing Game: computer generated number between 1 and 100 guessed by user" }
23694
max_votes
[ { "body": "<ol>\n<li>The pythonic way to do <code>count = count + 1</code> is <code>count += 1</code></li>\n<li><p>You don't need to repeat the 'guess again' part of the game twice:</p>\n\n<pre><code>if guess &gt; val:\n print(\"Too high. Try again:\", guess) \nelif guess &lt; val:\n print(\"Too low. Try again:\", guess)\nguess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\ncount += 1\nif guess == val:\n print(\"\\nCongratulations! You got it in\", count, \"guesses.\")\n break\n</code></pre></li>\n<li><p>You don't need to add the extra <code>if</code> statement because if <code>guess != val</code>, then the loop with break anyway:</p>\n\n<pre><code>while guess != val:\n if guess &gt; val:\n print(\"Too high. Try again:\", guess) \n elif guess &lt; val:\n print(\"Too low. Try again:\", guess)\n guess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\n count += 1\nprint(\"Congratulations! You got it in\", count, \"guesses.\")\n</code></pre></li>\n<li><p>I think <code>print(\"randint is\", val)</code> was probably for testing purposes, but it's still in your code!</p></li>\n<li><p>If you execute your program outside the command module (I'm not quite sure what it's called), the program will close immediately after it's finished; it's always best to give the user the choice of when to quit, so insert this at the end of your code:</p>\n\n<pre><code>input(\"Press enter to quit\")\n</code></pre></li>\n<li><p>The first section is unneeded:</p>\n\n<pre><code>def main():`, `if __name__ == \"__main__\":\n</code></pre></li>\n<li><p>The first <code>if</code> statement is also unneeded:</p>\n\n<pre><code>if guess == val:\n</code></pre></li>\n<li><p>You don't need to define <code>guess = 0</code> the first time.</p></li>\n</ol>\n\n<p>So, all in all, my improvement of your code is:</p>\n\n<pre><code>import random\nprint(\"Time to play a guessing game.\")\nval = random.randint(1, 100)\ncount = 1 \nguess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\nwhile(guess != val): \n if guess &gt; val:\n print(\"Too high. Try again:\", guess) \n elif guess &lt; val:\n print(\"Too low. Try again:\", guess)\n guess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\n count += 1\nprint(\"\\nCongratulations! You got it in \", count, \" guesses.\")\ninput(\"Press enter to quit.\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:01:52.480", "Id": "36567", "Score": "0", "body": "I'd use instead of `while guess != val:` is `elif guess == val` then break" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-27T06:14:20.910", "Id": "261599", "Score": "0", "body": "One minor thing: `while(guess != val):` can be changed to `while guess != val:`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T15:09:37.870", "Id": "23696", "ParentId": "23694", "Score": "10" } } ]
<p>I am trying to write a Python script that download an image from a webpage. On the webpage (I am using NASA's picture of the day page), a new picture is posted everyday, with different file names. After download, set the image as desktop. </p> <p>My solutions was to parse the HTML using <code>HTMLParser</code>, looking for "jpg", and write the path and file name of the image to an attribute (named as "output", see code below) of the HTML parser object.</p> <p>The code works, but I am just looking for comments and advice. I am new to Python and OOP (this is my first real python script ever), so I am not sure if this is how it is generally done.</p> <pre><code>import urllib2 import ctypes from HTMLParser import HTMLParser # Grab image url response = urllib2.urlopen('http://apod.nasa.gov/apod/astropix.html') html = response.read() class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, print it. if name == "href": if value[len(value)-3:len(value)]=="jpg": #print value self.output=value parser = MyHTMLParser() parser.feed(html) imgurl='http://apod.nasa.gov/apod/'+parser.output print imgurl # Save the file img = urllib2.urlopen(imgurl) localFile = open('desktop.jpg', 'wb') localFile.write(img.read()) localFile.close() # set to desktop(windows method) SPI_SETDESKWALLPAPER = 20 ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "desktop.jpg" , 0) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T00:08:39.580", "Id": "23759", "Score": "4", "Tags": [ "python", "beginner", "parsing", "windows", "web-scraping" ], "Title": "Download an image from a webpage" }
23759
max_votes
[ { "body": "<pre><code># Save the file\nimg = urllib2.urlopen(imgurl)\nlocalFile = open('desktop.jpg', 'wb')\nlocalFile.write(img.read())\nlocalFile.close()\n</code></pre>\n\n<p>For opening file it's recommend to do:</p>\n\n<pre><code>with open('desktop.jpg','wb') as localFile:\n localFile.write(img.read())\n</code></pre>\n\n<p>Which will make sure the file closes regardless.</p>\n\n<p>Also, urllib.urlretrieve does this for you. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T01:27:02.603", "Id": "23761", "ParentId": "23759", "Score": "2" } } ]
<p>I wrote a two player Noughts and Crosses game in Python 3, and came here to ask how I can improve this code.</p> <pre><code>import random cell = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] def owin(cell): return cell[0] == cell[1] == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell[1] == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8] == 'O' or cell[0] == cell[4] == cell[8] == 'O' or cell[2] == cell[4] == cell[6] == 'O' def xwin(cell): return cell[0] == cell[1] == cell[2] == 'X' or cell[3] == cell[4] == cell[5] == 'X' or cell[6] == cell[7] == cell[8] == 'X' or cell[0] == cell[3] == cell[6] == 'X' or cell[1] == cell[4] == cell[7] == 'X' or cell[2] == cell[5] == cell[8] == 'X' or cell[0] == cell[4] == cell[8] == 'X' or cell[2] == cell[4] == cell[6] == 'X' def tie(cell): return cell[0] in ('O', 'X') and cell[1] in ('O', 'X') and cell[2] in ('O', 'X') and cell[3] in ('O', 'X') and cell[4] in ('O', 'X') and cell[5] in ('O', 'X') and cell[6] in ('O', 'X') and cell[7] in ('O', 'X') and cell[8] in ('O', 'X') print('\tNOUGHTS AND CROSSES\n\t\tBy Lewis Cornwall') instructions = input('Would you like to read the instructions? (y/n)') if instructions == 'y': print('\nEach player takes turns to place a peice on the following grid:\n\n\t 1 | 2 | 3\n\t-----------\n\t 4 | 5 | 6\n\t-----------\n\t 7 | 8 | 9\n\nBy inputing a vaule when prompted. The first to 3 peices in a row wins.') player1 = input('Enter player 1\'s name: ') player2 = input('Enter player 2\'s name: ') print(player1 + ', you are O and ' + player2 + ', you are X.') nextPlayer = player1 while not(owin(cell) or xwin(cell)) and not tie(cell): print('This is the board:\n' + board) if nextPlayer == player1: move = input('\n' + player1 + ', select a number (1 - 9) to place your peice: ') cell[int(move) - 1] = 'O' board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] nextPlayer = player2 else: move = input('\n' + player2 + ', select a number (1 - 9) to place your peice: ') cell[int(move) - 1] = 'X' board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] nextPlayer = player1 if owin(cell): print('Well done, ' + player1 + ', you won!') elif xwin(cell): print('Well done, ' + player2 + ', you won!') else: print('Unfortunately, neither of you were able to win today.') input('Press &lt;enter&gt; to quit.') </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T11:42:53.097", "Id": "23784", "Score": "9", "Tags": [ "python", "game" ], "Title": "Noughts and Crosses game in Python" }
23784
max_votes
[ { "body": "<p>Some notes:</p>\n\n<blockquote>\n <p>cell = ['1', '2', '3', '4', '5', '6', '7', '8', '9']</p>\n</blockquote>\n\n<p>Try to be less verbose: <code>cell = \"123456789\".split()</code> or <code>cell = [str(n) for n in range(1, 10)]</code>. Anyway, conceptually it's very dubious you initialize the board with its number instead of its state. Also, <code>cell</code> is not a good name, it's a collection, so <code>cells</code>.</p>\n\n<pre><code>board = '\\n\\t ' + cell[0] + ...\n</code></pre>\n\n<p>Don't write such a long lines, split them to fit a sound max width (80/100/...). Anyway, here the problem is that you shouldn't do that manually, do it programmatically (<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">grouped</a> from itertools):</p>\n\n<pre><code>board = \"\\n\\t-----------\\n\\t\".join(\" | \".join(xs) for xs in grouped(cell, 3)) \n</code></pre>\n\n<blockquote>\n <p>return cell[0] == cell<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">1</a> == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">1</a> == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8]== 'O</p>\n</blockquote>\n\n<p>Ditto, use code: </p>\n\n<pre><code>groups = grouped(cell, 3)\nany(all(x == 'O' for x in xs) for xs in [groups, zip(*groups)])\n</code></pre>\n\n<p>Note that you are not checking if a cell has already a piece.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T12:23:06.963", "Id": "23787", "ParentId": "23784", "Score": "4" } } ]
<p>Here is a solution to the <a href="http://pl.spoj.com/problems/JPESEL/" rel="nofollow">SPOJ's JPESEL problem</a>. Basically the problem was to calculate cross product of 2 vectors modulo 10. If there is a positive remainder, it's not a valid <a href="http://en.wikipedia.org/wiki/PESEL" rel="nofollow">PESEL number</a>; (return <code>D</code>) if the remainder equals <code>0</code>, it's a valid number (return <code>N</code>).</p> <pre><code>import re, sys n = input() t = [1,3,7,9,1,3,7,9,1,3,1] while(n): p = map(int, re.findall('.',sys.stdin.readline())) # Another approach I've tried in orer to save some memory - didn't help: # print 'D' if sum([int(p[0]) * 1,int(p[1]) * 3,int(p[2]) * 7,int(p[3]) * 9,int(p[4]) * 1,int(p[5]) * 3,int(p[6]) * 7,int(p[7]) * 9,int(p[8]) * 1,int(p[9]) * 3,int(p[10]) * 1]) % 10 == 0 else 'N' print 'D' if ( sum(p*q for p,q in zip(t,p)) % 10 ) == 0 else 'N' n-=1 </code></pre> <p>The solution above got the following results at SPOJ:</p> <p>Time: 0.03s<br> Memory: 4.1M</p> <p>where the best solutions (submitted in Python 2.7) got:</p> <p>Time: 0.01s<br> Memory: 3.7M</p> <p>How can I optimize this code in terms of time and memory used?</p> <p>Note that I'm using different function to read the input, as <code>sys.stdin.readline()</code> is the fastest one when reading strings and <code>input()</code> when reading integers.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T17:58:26.517", "Id": "36992", "Score": "0", "body": "Why do you need to read from STDIN? I guess it will be faster with a file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:02:45.890", "Id": "36993", "Score": "0", "body": "You mean to read the whole input at once? I need STDIN because that's how the program sumbitted to SPOJ should work." } ]
{ "AcceptedAnswerId": "23993", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T09:30:44.913", "Id": "23981", "Score": "1", "Tags": [ "python", "optimization", "programming-challenge", "python-2.x" ], "Title": "SPOJ \"Pesel\" challemge" }
23981
accepted_answer
[ { "body": "<p>You can try to replace <code>re</code> module with just a <code>sys.stdin.readline()</code> and replace <code>zip</code> interator with <code>map</code> and <code>mul</code> function from <a href=\"http://docs.python.org/2.7/library/operator.html\" rel=\"nofollow\">operator</a> module like this:</p>\n\n<pre><code>from sys import stdin\nfrom operator import mul\n\nreadline = stdin.readline\nn = int(readline())\nt = [1,3,7,9,1,3,7,9,1,3,1]\n\nwhile n:\n p = map(int, readline().rstrip())\n print 'D' if (sum(map(mul, t, p)) % 10) == 0 else 'N'\n n -= 1\n</code></pre>\n\n<h2>Update</h2>\n\n<p>It seems getting item from a small dictionary is faster than <code>int</code> so there is a version without <code>int</code>:</p>\n\n<pre><code>from sys import stdin\n\nreadline = stdin.readline\nval = {\"0\": 0, \"1\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6,\n \"7\": 7, \"8\": 8, \"9\": 9}\nval3 = {\"0\": 0, \"1\": 3, \"2\": 6, \"3\": 9, \"4\": 12, \"5\": 15, \"6\": 18,\n \"7\": 21, \"8\": 24, \"9\": 27}\nval7 = {\"0\": 0, \"1\": 7, \"2\": 14, \"3\": 21, \"4\": 28, \"5\": 35, \"6\": 42,\n \"7\": 49, \"8\": 56, \"9\": 63}\nval9 = {\"0\": 0, \"1\": 9, \"2\": 18, \"3\": 27, \"4\": 36, \"5\": 45, \"6\": 54,\n \"7\": 63, \"8\": 72, \"9\": 81}\n\nn = int(readline())\nwhile n:\n # Expects only one NL character at the end of the line\n p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, _ = readline()\n print 'D' if ((val[p1] + val3[p2] + val7[p3] + val9[p4]\n + val[p5] + val3[p6] + val7[p7] + val9[p8]\n + val[p9] + val3[p10] + val[p11]) % 10 == 0) else 'N'\n n -= 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T19:12:36.463", "Id": "36999", "Score": "0", "body": "Much better time: `0.02` (is it because of using `readline()` instead of `input()`?), slightly better memory: `4.0M`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T16:10:47.063", "Id": "37040", "Score": "0", "body": "(after your update) It's still slower than the best implementations on SPOJ but I've learned a few things - thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:49:19.997", "Id": "23993", "ParentId": "23981", "Score": "1" } } ]
<p>Looking for optimizations and cleaner, more pythonic ways of implementing the following code.</p> <pre><code>#Given an array find any three numbers which sum to zero. import unittest def sum_to_zero(a): a.sort(reverse=True) len_a = len(a) if len_a &lt; 3: return [] for i in xrange(0, len_a): j = i + 1 for k in xrange(j + 1, len_a): if a[j] + a[k] == -1 * a[i]: return [a[i], a[j], a[k]] return [] class SumToZeroTest(unittest.TestCase): def test_sum_to_zero_basic(self): a = [1, 2, 3, -1, -2, -3, -5, 1, 10, 100, -200] res = sum_to_zero(a) self.assertEqual([3, 2, -5], res, str(res)) def test_sum_to_zero_no_res(self): a = [1, 1, 1, 1] res = sum_to_zero(a) self.assertEqual(res, [], str(res)) def test_small_array(self): a = [1, 2, -3] res = sum_to_zero(a) self.assertEqual(res, [2, 1, -3], str(res)) def test_invalid_array(self): a = [1, 2] res = sum_to_zero(a) self.assertEqual(res, [], str(res)) #nosetests sum_to_zero.py </code></pre>
[]
{ "AcceptedAnswerId": "23998", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T22:10:11.573", "Id": "23996", "Score": "9", "Tags": [ "python", "algorithm" ], "Title": "Given an array find any three numbers which sum to zero" }
23996
accepted_answer
[ { "body": "<p>Your code fails this test case:</p>\n\n<pre><code>def test_winston1(self):\n res = sum_to_zero([125, 124, -100, -25])\n self.assertEqual(res, [125,-100,-25])\n</code></pre>\n\n<p>As for the code</p>\n\n<pre><code>def sum_to_zero(a):\n a.sort(reverse=True)\n</code></pre>\n\n<p>Why sort?</p>\n\n<pre><code> len_a = len(a)\n if len_a &lt; 3:\n return []\n for i in xrange(0, len_a):\n</code></pre>\n\n<p>You can just do <code>xrange(len_a)</code>. I recommend doing <code>for i, a_i in enumerate(a)</code> to avoid having the index the array later.</p>\n\n<pre><code> j = i + 1\n</code></pre>\n\n<p>Thar be your bug, you can't assumed that j will be i + 1.</p>\n\n<pre><code> for k in xrange(j + 1, len_a):\n if a[j] + a[k] == -1 * a[i]:\n</code></pre>\n\n<p>Why this instead of <code>a[j] + a[k] + a[i] == 0</code>?</p>\n\n<pre><code> return [a[i], a[j], a[k]]\n return []\n</code></pre>\n\n<p>Not a good a choice of return value. I'd return None. An empty list isn't a natural continuation of the other outputs. </p>\n\n<p>Here is my implementation of it:</p>\n\n<pre><code>def sum_to_zero(a):\n a.sort(reverse = True)\n for triplet in itertools.combinations(a, 3):\n if sum(triplet) == 0:\n return list(triplet)\n return []\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T23:31:59.803", "Id": "37007", "Score": "1", "body": "Thanks for the feedback. I like the use of itertools.combinations... good to know." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T23:19:00.037", "Id": "23998", "ParentId": "23996", "Score": "15" } } ]
<p>i wish to improve my Progressbar in Python</p> <pre><code>from __future__ import division import sys import time class Progress(object): def __init__(self, maxval): self._seen = 0.0 self._pct = 0 self.maxval = maxval def update(self, value): self._seen = value pct = int((self._seen / self.maxval) * 100.0) if self._pct != pct: sys.stderr.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() self._pct = pct def start(self): pct = int((0.0 / self.maxval) * 100.0) sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() def finish(self): pct = int((self.maxval / self.maxval) * 100.0) sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() toolbar_width = 300 pbar = Progress(toolbar_width) pbar.start() for i in xrange(toolbar_width): time.sleep(0.1) # do real work here pbar.update(i) pbar.finish() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:05:07.600", "Id": "37061", "Score": "1", "body": "CodeReview is to get review on code which is working, not to get some help to add a feature." } ]
{ "AcceptedAnswerId": "24024", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T23:05:03.840", "Id": "24023", "Score": "0", "Tags": [ "python", "optimization" ], "Title": "Progressbar in Python" }
24023
accepted_answer
[ { "body": "<p>As per my comments, I've not sure SE.CodeReview is the right place to get the help you are looking for.</p>\n\n<p>However, as I didn't read your question properly at first, I had a look at your code and changed a few things (please note that it's not exactly the same behavior as it used to be):</p>\n\n<ul>\n<li>extract the display logic in a method on its own</li>\n<li>reuse update in start and finish (little changes here : this method now updates the object instead of just doing some display)</li>\n<li>removed self._seen because it didn't seem useful</li>\n</ul>\n\n<p>Here the code :</p>\n\n<pre><code>class Progress(object):\n def __init__(self, maxval):\n self._pct = 0\n self.maxval = maxval\n\n def update(self, value):\n pct = int((value / self.maxval) * 100.0)\n if self._pct != pct:\n self._pct = pct\n self.display()\n\n def start(self):\n self.update(0)\n\n def finish(self):\n self.update(self.maxval)\n\n def display(self):\n sys.stdout.write(\"|%-100s| %d%%\" % (u\"\\u2588\"*self._pct, self._pct) + '\\n')\n sys.stdout.flush()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:19:30.073", "Id": "37062", "Score": "0", "body": "Thank Josay for the review. What i wish to do is print the percentage (1%, 2%, 3%, ..., 100%) in the middle of the progress bar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:22:48.020", "Id": "37067", "Score": "0", "body": "@Gianni unfortunately, that's off-topic for Code Review. You should edit your question to be a valid code review request as defined in the [faq], otherwise it will be closed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:58:08.810", "Id": "37086", "Score": "0", "body": "@codesparkle it's a fuzzy definition about SO (= stackoverflow) or CR (code review). Normally people use this approach: code works CR, code doesn't work SO, no code Programmer. In my case the code works and i want to improve the quality. With a with a working code (no error) i think (maybe i wrong) this question is more appropriate in CD" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:11:02.147", "Id": "24024", "ParentId": "24023", "Score": "2" } } ]
<p>A large .csv file I was given has a large table of flight data. A function I wrote to help parse it iterates over the column of Flight IDs, and then returns a dictionary containing the index and value of every unique Flight ID in order of first appearance.</p> <pre><code>Dictionary = { Index: FID, ... } </code></pre> <p>This comes as a quick adjustment to an older function that didn't require having to worry about <code>FID</code> repeats in the column (a few hundred thousand rows later...).</p> <p>Example:</p> <pre><code>20110117559515, ... 20110117559515, ... 20110117559515, ... 20110117559572, ... 20110117559572, ... 20110117559572, ... 20110117559574, ... 20110117559587, ... 20110117559588, ... </code></pre> <p>and so on for 5.3 million some rows.</p> <p>Right now, I have it iterating over and comparing each value in order. If a unique value appears, it only stores the first occurrence in the dictionary. I changed it to now also check if that value has already occurred before, and if so, to skip it.</p> <pre><code>def DiscoverEarliestIndex(self, number): result = {} columnvalues = self.column(number) column_enum = {} for a, b in enumerate(columnvalues): column_enum[a] = b i = 0 while i &lt; (len(columnvalues) - 1): next = column_enum[i+1] if columnvalues[i] == next: i += 1 else: if next in result.values(): i += 1 continue else: result[i+1]= next i += 1 else: return result </code></pre> <p>It's very inefficient, and slows down as the dictionary grows. The column has 5.2 million rows, so it's obviously not a good idea to handle this much with Python, but I'm stuck with it for now.</p> <p>Is there a more efficient way to write this function?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T09:20:04.877", "Id": "37238", "Score": "0", "body": "You are not always retrieving the first occurrence because \"If a value is equal to the value after it, it skips it.\"" } ]
{ "AcceptedAnswerId": "24170", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T20:40:52.533", "Id": "24126", "Score": "3", "Tags": [ "python", "performance", "parsing", "csv", "iteration" ], "Title": "Retrieving the first occurrence of every unique value from a CSV column" }
24126
accepted_answer
[ { "body": "<p>So here is what I came up with, now that I had access to a computer:</p>\n\n<p>raw_data.csv:</p>\n\n<pre><code>20110117559515,1,10,faa\n20110117559515,2,20,bar\n20110117559515,3,30,baz\n20110117559572,4,40,fii\n20110117559572,5,50,bir\n20110117559572,6,60,biz\n20110117559574,7,70,foo\n20110117559587,8,80,bor\n20110117559588,9,90,boz\n</code></pre>\n\n<p>code:</p>\n\n<pre><code>import csv\nfrom collections import defaultdict\nfrom pprint import pprint\nimport timeit\n\n\ndef method1():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n unik = set(cols[0])\n\n indexed = defaultdict(list)\n\n for x in unik:\n i = cols[0].index(x)\n indexed[i] = rows[i]\n\n return indexed\n\ndef method2():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n unik = set(cols[0])\n\n indexed = defaultdict(list)\n\n for x in unik:\n i = next(index for index,fid in enumerate(cols[0]) if fid == x)\n indexed[i] = rows[i]\n\n return indexed\n\ndef method3():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n indexes = [cols[0].index(x) for x in set(cols[0])]\n\n for index in indexes:\n yield (index,rows[index])\n\n\nif __name__ == '__main__':\n\n results = method1() \n print 'indexed:'\n pprint(dict(results))\n\n print '-' * 80\n\n results = method2() \n print 'indexed:'\n pprint(dict(results))\n\n print '-' * 80\n\n results = dict(method3())\n print 'indexed:'\n pprint(results)\n\n #--- Timeit ---\n\n print 'method1:', timeit.timeit('dict(method1())', setup=\"from __main__ import method1\", number=10000)\n print 'method2:', timeit.timeit('dict(method2())', setup=\"from __main__ import method2\", number=10000)\n print 'method3:', timeit.timeit('dict(method3())', setup=\"from __main__ import method3\", number=10000)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>indexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n--------------------------------------------------------------------------------\nindexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n--------------------------------------------------------------------------------\nindexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n\nmethod1: 0.283623933792\nmethod2: 0.37960600853\nmethod3: 0.293814182281\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:59:54.303", "Id": "37351", "Score": "0", "body": "An issue with this script, it's sucking up a TON of memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T21:26:45.067", "Id": "37373", "Score": "0", "body": "Tried with 2 other methods, but it looks like the initial one is still the fastest.\nPlease compare which is the best in terms of memory consumption on runtime, using your big data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T14:29:04.500", "Id": "37401", "Score": "0", "body": "FYI I tried to implement an 100% python way of solving your question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T20:15:10.837", "Id": "24170", "ParentId": "24126", "Score": "1" } } ]
<p>I am just learning how to do some multiprocessing with Python, and I would like to create a non-blocking chat application that can add/retrieve messages to/from a database. This is my somewhat primitive attempt (note: It is simplified for the purposes of this post); however, I would like to know how close/far off off the mark I am. Any comments, revisions, suggestions, etc. are greatly appreciated. </p> <p>Thank you!</p> <pre><code>import multiprocessing import Queue import time # Get all past messages def batch_messages(): # The messages list here will be attained via a db query messages = ["&gt;&gt; This is a message.", "&gt;&gt; Hello, how are you doing today?", "&gt;&gt; Really good!"] for m in messages: print m # Add messages to the DB def add_messages(q): # Retrieve from the queue message_to_add = q.get() # For testing purposes only; perfrom another DB query to add the message to the DB print "(Add to DB)" # Recieve new, inputted messages. def receive_new_message(q, new_message): # Add the new message to the queue: q.put(new_message) # Print the message to the screen print "&gt;&gt;", new_message if __name__ == "__main__": # Set up the queue q = multiprocessing.Queue() # Print the past messages batch_messages() while True: # Enter a new message input_message = raw_input("Type a message: ") # Set up the processes p_add = multiprocessing.Process(target=add_messages, args=(q,)) p_rec = multiprocessing.Process(target=receive_new_message, args=(q, input_message,)) # Start the processes p_rec.start() p_add.start() # Let the processes catch up before printing "Type a message: " again. (Shell purposes only) time.sleep(1) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:43:34.277", "Id": "37333", "Score": "0", "body": "That's quite odd that it works fine when I run it...I will look further into this. But, thank you for the feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:48:26.577", "Id": "37335", "Score": "0", "body": "I can explicitly pass it to the functions that require it, and then I assume it will work for as well, correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:48:57.300", "Id": "37336", "Score": "0", "body": "Yes, you should pass `q` as a parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:58:10.620", "Id": "37338", "Score": "0", "body": "`q` is now passed to the functions. Thanks." } ]
{ "AcceptedAnswerId": "24213", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T06:56:02.460", "Id": "24187", "Score": "4", "Tags": [ "python" ], "Title": "Python multiprocessing messaging code" }
24187
accepted_answer
[ { "body": "<ul>\n<li>Don't create a new process for every task. Put a loop in <code>add_messages</code>; <code>q.get</code> will wait for the next task in the queue.</li>\n<li><code>receive_new_message</code> is not doing anything useful in your example. Place <code>q.put(new_message)</code> right after <code>raw_input</code> instead.</li>\n</ul>\n\n<p>:</p>\n\n<pre><code>def add_messages(q): \n while True:\n # Retrieve from the queue\n message_to_add = q.get()\n print \"(Add to DB)\"\n\nif __name__ == \"__main__\":\n q = multiprocessing.Queue()\n p_add = multiprocessing.Process(target=add_messages, args=(q,))\n p_add.start()\n\n while True: \n input_message = raw_input(\"Type a message: \")\n\n # Add the new message to the queue:\n q.put(input_message)\n\n # Let the processes catch up before printing \"Type a message: \" again. (Shell purposes only)\n time.sleep(1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T17:38:24.597", "Id": "37415", "Score": "0", "body": "Thank you for the revision! I appreciate your help. On a side note, I included the `receive_new_message` process with the thought that I would need to output messages from the queue to users' screens, and that this process should be separate from the `add_messages` (to the db) process. Is this \"concern\" a necessary one? Or can the outputting to the screen be coupled with the database querying?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T09:11:20.743", "Id": "37441", "Score": "0", "body": "@JohnZ If you need the two subprocesses, you would use two queues. For example, `receive_new_message` might read from `q1`, do some processing and forward the results to `add_messages` via `q2`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T15:33:52.110", "Id": "37443", "Score": "0", "body": "Ahhh okay. That makes sense. Thank you for the feedback!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T20:29:27.990", "Id": "24213", "ParentId": "24187", "Score": "1" } } ]