body
stringlengths
144
5.58k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'd like suggestions for optimizing this brute force solution to <a href="http://projecteuler.net/index.php?section=problems&amp;id=1">problem 1</a>. The algorithm currently checks every integer between 3 and 1000. I'd like to cut as many unnecessary calls to <code>isMultiple</code> as possible:</p> <pre><code>''' 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. Find the sum of all the multiples of 3 or 5 below 1000. ''' end = 1000 def Solution01(): ''' Solved by brute force #OPTIMIZE ''' sum = 0 for i in range(3, end): if isMultiple(i): sum += i print(sum) def isMultiple(i): return (i % 3 == 0) or (i % 5 == 0) </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:06:48.893", "Id": "3", "Score": "1", "body": "Are you trying to optimize the algorithm or the code itself?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:07:15.663", "Id": "5", "Score": "0", "body": "@JoePhillips: Why not both? ;)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:08:43.633", "Id": "6", "Score": "0", "body": "@JoePhillips: the algorithm. it currently checks every single integer between 3 and 1000." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:09:03.493", "Id": "7", "Score": "0", "body": "@Zolomon: good point, either type of answer would be helpful." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:12:10.890", "Id": "2889", "Score": "0", "body": "Just a note. The detailed explanation for [Richard's Answer](http://codereview.stackexchange.com/questions/2/project-euler-problem-1-in-python/280#280) on Wikipedia may be helpful if you didn't already understand the Math. See [here](http://en.wikipedia.org/wiki/Arithmetic_series#Sum)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-12T16:57:29.667", "Id": "12182", "Score": "0", "body": "[Relevant blog post](http://cowbelljs.blogspot.com/2011/12/projecteuler-001.html)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-13T02:30:06.993", "Id": "12221", "Score": "0", "body": "@TryPyPy, you may want to weigh in here: http://meta.codereview.stackexchange.com/questions/429/online-contest-questions" } ]
[ { "body": "<p>I think the best way to cut out possible checks is something like this:</p>\n\n<pre><code>valid = set([])\n\nfor i in range(3, end, 3):\n valid.add(i)\n\nfor i in range(5, end, 5):\n valid.add(i)\n\ntotal = sum(valid)\n</code></pre>\n\n<p>There's still a bit of redundancy (numbers which are multiples of both 3 and 5 are checked twice) but it's minimal.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:25:31.500", "Id": "25", "Score": "0", "body": "@gddc: nice, I didn't even know you could specify an increment in a range like that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:26:07.760", "Id": "26", "Score": "0", "body": "That's also what I would do now." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:26:24.727", "Id": "27", "Score": "0", "body": "@calavera - range() is a great function ... the optional step as a 3rd parameter can save tons of iterations." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:03:12.310", "Id": "50", "Score": "0", "body": "http://docs.python.org/library/functions.html#range just for good measure" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:36:59.043", "Id": "496", "Score": "0", "body": "You could save some memory (if using 2.x) by using the xrange function instead of range, it uses the iterator protocol instead of a full blown list." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:38:54.627", "Id": "497", "Score": "2", "body": "Also by using the set.update method you could shed the loop and write someting like: valid.update(xrange(3, end, 3))" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:23:04.670", "Id": "11", "ParentId": "2", "Score": "28" } }, { "body": "<p>g.d.d.c's solution is slightly redundant in that it checks numbers that are multiples of 3 and 5 twice. I was wondering about optimizations to this, so this is slightly longer than a comment, but not really an answer in itself, as it totally relies on g.d.d.c's awesome answer as inspiration.</p>\n\n<p>If you add multiples to the valid list for the multiple \"3\" and then do another pass over the whole list (1-1000) for the multiple \"5\" then you do experience some redundancy.</p>\n\n<p>The order in which you add them:</p>\n\n<pre><code> add 3-multiples first\n add 5 multiples second\n</code></pre>\n\n<p>will matter (albeit slightly) if you want to check if the number exists in the list or not.</p>\n\n<p>That is, if your algorithm is something like</p>\n\n<pre><code>add 3-multiples to the list\n\nadd 5-multiples to the list if they don't collide\n</code></pre>\n\n<p>it will perform slightly worse than</p>\n\n<pre><code>add 5-multiples to the list\n\nadd 3-multiples to the list if they don't collide\n</code></pre>\n\n<p>namely, because there are more 3-multiples than 5-multiples, and so you are doing more \"if they don't collide\" checks.</p>\n\n<p>So, here are some thoughts to keep in mind, in terms of optimization:</p>\n\n<ul>\n<li>It would be best if we could iterate through the list once</li>\n<li>It would be best if we didn't check numbers that weren't multiples of 3 nor 5.</li>\n</ul>\n\n<p>One possible way is to notice the frequency of the multiples. That is, notice that the LCM (least-common multiple) of 3 and 5 is 15: </p>\n\n<pre><code>3 6 9 12 15 18 21 24 27 30\n || ||\n 5 10 15 20 25 30\n</code></pre>\n\n<p>Thus, you should want to, in the optimal case, want to use the frequency representation of multiples of 3 and 5 in the range (1,15) over and over until you reach 1000. (really 1005 which is divided by 15 evenly 67 times).</p>\n\n<p>So, you want, for each iteration of this frequency representation:</p>\n\n<p>the numbers at: 3 5 6 9 10 12 15</p>\n\n<p>Your frequencies occur (I'm sorta making up the vocab for this, so please correct me if there are better math-y words) at starting indexes from <strong>0k + 1 to 67k</strong> (1 to 1005) [technically 66k]</p>\n\n<p>And you want the numbers at positions <em>3, 5, 6, 9, 10, 12, and 15</em> enumerating from the index.</p>\n\n<p>Thus,</p>\n\n<pre><code>for (freq_index = 0; freq_index &lt; 66; ++freq_index) {\n valid.add(15*freq_index + 3);\n valid.add(15*freq_index + 5);\n valid.add(15*freq_index + 6);\n valid.add(15*freq_index + 9);\n valid.add(15*freq_index + 10);\n valid.add(15*freq_index + 12);\n valid.add(15*freq_index + 15); //also the first term of the next indexed range\n}\n</code></pre>\n\n<p>and we have eliminated redundancy</p>\n\n<p>=)</p>\n\n<p><hr>\n<em>Exercise for the astute / determined programmer:</em><br>\nWrite a function that takes three integers as arguments, <em>x y z</em> and, without redundancy, finds all the multiples of <em>x</em> and of <em>y</em> in the range from 1 to <em>z</em>.<br>\n(basically a generalization of what I did above).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:44:11.497", "Id": "54", "Score": "0", "body": "I'll have to check the documentation to be sure, but I believe the `set.add()` method uses a binary lookup to determine whether or not the new element exists already. If that's correct then the order you check the multiples of 3's or 5's won't matter - you have an identical number of binary lookups. If you can implement a solution that rules out double-checks for multiples of both you may net an improvement." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T01:14:51.330", "Id": "72", "Score": "1", "body": "@g.d.d.c: Ah, good point. I was thinking more language-agnostically, since the most primitive implementation wouldn't do it efficiently. An interesting aside about the python <code>.add()</code> function from a google: http://indefinitestudies.org/2009/03/11/dont-use-setadd-in-python/" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T16:46:42.527", "Id": "146", "Score": "0", "body": "@sova - Thanks for the link on the union operator. I hadn't ever encountered that and usually my sets are small enough they wouldn't suffer from the performance penalty, but knowing alternatives is always great." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T22:45:48.320", "Id": "169", "Score": "0", "body": "@g.d.d.c also, the solution above does indeed rule out double-checks for multiples of both, it figures out the minimal frequency at which you can repeat the pattern for digits (up to the LCM of the two digits). Each valid multiple of 3, 5, or both, is \"checked\" (actually, not really checked, just added) only once." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T17:57:44.573", "Id": "1741", "Score": "0", "body": "@g.d.d.c python's set is based on a hash table. It is not going to use a binary lookup. Instead it will do a hash table lookup." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T18:29:45.833", "Id": "1744", "Score": "0", "body": "@sova, the conclusion in that blog post is wrong. Its actually measuring the overhead of profiling. Profile .add is more expensive then profiling |=, but .add is actually faster." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:23:56.613", "Id": "24", "ParentId": "2", "Score": "8" } }, { "body": "<p>I would do it like this:</p>\n\n<pre><code>total = 0\n\nfor i in range(3, end, 3):\n total += i\n\nfor i in range(5, end, 5):\n if i % 3 != 0: # Only add the number if it hasn't already\n total += i # been added as a multiple of 3\n</code></pre>\n\n<p>The basic approach is the same as g.d.d.c's: iterate all the multiples of 3, then 5. However instead of using a set to remove duplicates, we simply check that the multiples of 5 aren't also multiples of 3. This has the following upsides:</p>\n\n<ol>\n<li>Checking divisibility is less expensive than adding to a set.</li>\n<li>We build the total up incrementally, so we don't need a separate call to sum at the end.</li>\n<li>We got rid of the set, so we only need constant space again.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T15:24:15.257", "Id": "3594", "Score": "0", "body": "do you think it would be faster or slow to allow the repetitive 5's to be added and then substract the 15's? we would lose `end/5` divisibility checks and it costs only `add/15` subtractions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T04:38:14.877", "Id": "67", "ParentId": "2", "Score": "12" } }, { "body": "<p>I would get rid of the <code>for</code> loops and use <code>sum</code> on generator expressions.</p>\n\n<pre><code>def solution_01(n):\n partialsum = sum(xrange(3, n, 3)) \n return partialsum + sum(x for x in xrange(5, n, 5) if x % 3)\n</code></pre>\n\n<p>Note that we're using <code>xrange</code> instead of <code>range</code> for python 2. I have never seen a case where this isn't faster for a <code>for</code> loop or generator expression. Also consuming a generator expression with <code>sum</code> <em>should</em> be faster than adding them up manually in a <code>for</code> loop.</p>\n\n<p>If you wanted to do it with sets, then there's still no need for <code>for</code> loops</p>\n\n<pre><code>def solution_01(n):\n values = set(range(3, n, 3)) | set(range(5, n, 5))\n return sum(values)\n</code></pre>\n\n<p>Here, we're just passing the multiples to the set constructor, taking the union of the two sets and returning their sum. Here, I'm using <code>range</code> instead of <code>xrange</code>. For some reason, I've seen that it's faster when passing to <code>list</code>. I guess it would be faster for <code>set</code> as well. You would probably want to benchmark though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T06:23:09.830", "Id": "71", "ParentId": "2", "Score": "17" } }, { "body": "<p>Using a generator is also possible :</p>\n\n<pre><code>print sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)\n</code></pre>\n\n<p>Note that intent is not really clear here. For shared code, I would prefer something like</p>\n\n<pre><code>def euler001(limit):\n return sum(n for n in range(limit) if n % 3 == 0 or n % 5 == 0)\n\nprint euler001(1000)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:37:09.013", "Id": "275", "ParentId": "2", "Score": "8" } }, { "body": "<p>The sum 3+6+9+12+...+999 = 3(1+2+3+...+333) = 3 (n(n+1))/2 for n = 333. And 333 = 1000/3, where \"/\" is integral arithmetic.</p>\n\n<p>Also, note that multiples of 15 are counted twice.</p>\n\n<p>So</p>\n\n<pre><code>def sum_factors_of_n_below_k(k, n):\n m = (k-1) // n\n return n * m * (m+1) // 2\n\ndef solution_01():\n return (sum_factors_of_n_below_k(1000, 3) + \n sum_factors_of_n_below_k(1000, 5) - \n sum_factors_of_n_below_k(1000, 15))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T15:19:22.627", "Id": "3593", "Score": "9", "body": "this is obviously most efficient. i was about to post this as a one liner but i prefer the way you factored it. still, would `sum_multiples_of_n_below_k` be the appropriate name? they are not n's factors, they are its multiples" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T15:27:51.710", "Id": "280", "ParentId": "2", "Score": "43" } }, { "body": "<p>Well, this <em>is</em> an answer to a Project Euler question after all, so perhaps the best solution is basically a pencil-paper one.</p>\n\n<pre><code>sum(i for i in range(n + 1)) # sums all numbers from zero to n\n</code></pre>\n\n<p>is a triangular number, the same as</p>\n\n<pre><code>n * (n + 1) / 2\n</code></pre>\n\n<p>This is the triangular function we all know and love. Rather, more formally, </p>\n\n<pre><code>triangle(n) = n * (n + 1) / 2\n</code></pre>\n\n<p>With that in mind, we next note that the sum of the series</p>\n\n<pre><code>3, 6, 9, 12, 15, 18, 21, 24, ...\n</code></pre>\n\n<p>is 3 * the above triangle function. And the sums of</p>\n\n<pre><code>5, 10, 15, 20, 25, 30, 35, ...\n</code></pre>\n\n<p>are 5 * the triangle function. We however have one problem with these current sums, since a number like 15 or 30 would be counted in each triangle number. Not to worry, the inclusion-exclusion principle comes to the rescue! The sum of</p>\n\n<pre><code>15, 30, 45 ,60, 75, 90, 105, ...\n</code></pre>\n\n<p>is 15 * the triangle function. Well, if this so far makes little sense don't worry. Finding the sum of the series from 1 up to n, incrementing by k, is but</p>\n\n<pre><code>triangle_with_increments(n, k = 1) = k * (n/k) * (n/k + 1) / 2\n</code></pre>\n\n<p>with this, and the inclusion-exclusion principle, the final answer is but</p>\n\n<pre><code>triangle_with_increments(100, 5) + triangle_with_increments(100, 3) - triangle_with_increments(100, 15)\n</code></pre>\n\n<p>Wow. Who'da thunk? an n complexity problem suddenly became a constant time one. That's what I call optimization IMHO :P. But in all seriousness, Project Euler asks you to answer problems in really the lowest computational complexity possible. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-12T01:39:34.380", "Id": "5978", "ParentId": "2", "Score": "15" } }, { "body": "<p>The list comprehension one is an awesome solution, but making use of set is a lot faster:</p>\n\n<pre><code>from __future__ import print_function\n\ndef euler_001(limit):\n s1, s2 = set(range(0, limit, 3)), set(range(0, limit, 5))\n\n return sum(s1.union(s2))\n\nprint(euler_001(1000))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T16:42:50.027", "Id": "75000", "ParentId": "2", "Score": "6" } }, { "body": "<p>I used a slightly simpler method, but essentially did the same thing:</p>\n\n<pre><code>total = 0\n\nfor n in range(3,1000):\n if n % 3 == 0:\n total += n\n elif n % 5 == 0:\n total += n\n\n\nprint total\n</code></pre>\n\n<p>The <code>elif</code> makes sure that you only count any factor/divisor once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-04T00:38:58.953", "Id": "262984", "Score": "1", "body": "(`did the same thing`: The order in which answers are shown is bound to change, and you might be referring to the question: please disambiguate with a quote or a hyperlink (e.g., from the `share`-link at the end of each post).)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-03T19:15:05.807", "Id": "140425", "ParentId": "2", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:04:27.573", "Id": "2", "Score": "56", "Tags": [ "python", "optimization", "algorithm", "programming-challenge" ], "Title": "Project Euler problem 1 in Python - Multiples of 3 and 5" }
2
<p>I started programming with Java and C++, so I'm used to having a 'main' function that calls other functions that do the actual work. At university I was always told that doing actual computation in the main function is bad practice. I'm currently playing around with Python, and I have trouble figuring out how to write a nice 'main' function, especially since I'm doing small stuff that doesn't need separate classes.</p> <p>What do you think about the following code? Is the main function necessary, or would you just write everything without functions? Is there a general consent on this in the Python world?</p> <pre><code># Finds sum of all multiples of 3 and 5 from 0 to 999 def find_multiples(): global numbers for i in range(0,1000): if i%3==0 or i%5==0: numbers.append(i); numbers = [] if __name__ == '__main__': find_multiples() print sum(numbers) </code></pre>
[]
[ { "body": "<p>Here's some superficial review. More for testing the site and some comment formatting than anything, but: do create main functions (helps us benchmarkers a lot) and do think that your module can be imported, so docstrings and local variables help. </p>\n\n<pre><code># Finds...\n###-^ Put this in a docstring\n\ndef find_multiples():\n \"\"\"Finds sum of all multiples of 3 and 5 from 0 to 999 \"\"\"\n###-^ This allows you to \"from x import find_multiples, help(find_multiples)\"\n numbers = []\n###-^ Avoid globals\n for i in xrange(1000):\n###-^ Use xrange if Python 2.x, no need to start at 0 (it's the default)\n if not (i % 3) or not (i % 5):\n###-^ Add spaces around operators, simplify\n###-^ the boolean/numeric checks\n numbers.append(i)\n###-^ Remove trailing ;\n return numbers\n\n###-^ Removed global\n\ndef main():\n###-^ Allows calling main many times, e.g. for benchmarking\n numbers = find_multiples()\n print sum(numbers)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T21:57:35.937", "Id": "166", "Score": "1", "body": "`xrange(1000)` would suffice. Which version is more readable is arguable. Otherwise, excellent code review! Chapeau bas!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T17:51:51.517", "Id": "19954", "Score": "0", "body": "I would be tempted (although perhaps not for such a small program) to move the print statement out of main, and to keep the main() function strictly for catching exceptions, printing error messages to stderr, and returning error/success codes to the shell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-28T14:53:40.477", "Id": "117208", "Score": "0", "body": "Another reason for using a 'main function' is that otherwise all variables you declare are global." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:43:12.493", "Id": "32", "ParentId": "7", "Score": "53" } }, { "body": "<p>Here's how I would do it:</p>\n\n<pre><code>def find_multiples(min=0, max=1000):\n \"\"\"Finds multiples of 3 or 5 between min and max.\"\"\"\n\n for i in xrange(min, max):\n if i%3 and i%5:\n continue\n\n yield i\n\nif __name__ == '__main__':\n print sum(find_multiples())\n</code></pre>\n\n<p>This makes find_multiples a generator for the multiples it finds. The multiples no longer need to be stored explicitly, and especially not in a global. </p>\n\n<p>It's also now takes parameters (with default values) so that the caller can specify the range of numbers to search. </p>\n\n<p>And of course, the global \"if\" block now only has to sum on the numbers generated by the function instead of hoping the global variable exists and has remained untouched by anything else that might come up.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:29:00.797", "Id": "231", "ParentId": "7", "Score": "15" } }, { "body": "<p>The UNIX Man's recommendation of using a generator rather than a list is good one. However I would recommend using a generator expressions over <code>yield</code>:</p>\n\n<pre><code>def find_multiples(min=0, max=1000):\n \"\"\"Finds multiples of 3 or 5 between min and max.\"\"\"\n return (i for i in xrange(min, max) if i%3==0 or i%5==0)\n</code></pre>\n\n<p>This has the same benefits as using <code>yield</code> and the added benefit of being more concise. In contrast to UNIX Man's solution it also uses \"positive\" control flow, i.e. it selects the elements to select, not the ones to skip, and the lack of the <code>continue</code> statement simplifies the control flow¹.</p>\n\n<p>On a more general note, I'd recommend renaming the function <code>find_multiples_of_3_and_5</code> because otherwise the name suggests that you might use it to find multiples of any number. Or even better: you could generalize your function, so that it can find the multiples of any numbers. For this the code could look like this:</p>\n\n<pre><code>def find_multiples(factors=[3,5], min=0, max=1000):\n \"\"\"Finds all numbers between min and max which are multiples of any number\n in factors\"\"\"\n return (i for i in xrange(min, max) if any(i%x==0 for x in factors))\n</code></pre>\n\n<p>However now the generator expression is getting a bit crowded, so we should factor the logic for finding whether a given number is a multiple of any of the factors into its own function:</p>\n\n<pre><code>def find_multiples(factors=[3,5], min=0, max=1000):\n \"\"\"Finds all numbers between min and max which are multiples of any number\n in factors\"\"\"\n def is_multiple(i):\n return any(i%x==0 for x in factors)\n\n return (i for i in xrange(min, max) if is_multiple(i))\n</code></pre>\n\n<hr>\n\n<p>¹ Of course the solution using <code>yield</code> could also be written positively and without <code>continue</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-28T14:55:39.270", "Id": "117210", "Score": "0", "body": "I like your second version. Perhaps you could make it even more general and succinct by removing the `min`, `max` argument, and just letting it take an iterator argument. That way the remaindin program would be `sum(find_multiples(xrange(1000)))`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:55:19.263", "Id": "238", "ParentId": "7", "Score": "25" } }, { "body": "<p>Regarding the use of a <code>main()</code> function.</p>\n\n<p>One important reason for using a construct like this:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Is to keep the module importable and in turn much more reusable. I can't really reuse modules that runs all sorts of code when I import them. By having a main() function, as above, I can import the module and reuse relevant parts of it. Perhaps even by running the <code>main()</code> function at my convenience.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T10:22:13.827", "Id": "267", "ParentId": "7", "Score": "6" } }, { "body": "<p>Just in case you're not familiar with the generator technique being used above, here's the same function done in 3 ways, starting with something close to your original, then using a <a href=\"http://docs.python.org/tutorial/datastructures.html#list-comprehensions\" rel=\"noreferrer\">list comprehension</a>, and then using a <a href=\"http://docs.python.org/tutorial/classes.html#generator-expressions\" rel=\"noreferrer\">generator expression</a>:</p>\n\n<pre><code># Finds sum of all multiples of 3 and 5 from 0 to 999 in various ways\n\ndef find_multiples():\n numbers = []\n for i in range(0,1000):\n if i%3 == 0 or i%5 == 0: numbers.append(i)\n return numbers\n\ndef find_multiples_with_list_comprehension():\n return [i for i in range(0,1000) if i%3 == 0 or i%5 == 0]\n\ndef find_multiples_with_generator():\n return (i for i in range(0,1000) if i%3 == 0 or i%5 == 0)\n\nif __name__ == '__main__':\n numbers1 = find_multiples()\n numbers2 = find_multiples_with_list_comprehension()\n numbers3 = list(find_multiples_with_generator())\n print numbers1 == numbers2 == numbers3\n print sum(numbers1)\n</code></pre>\n\n<p><code>find_multiples()</code> is pretty close to what you were doing, but slightly more Pythonic. It avoids the <code>global</code> (icky!) and returns a list.</p>\n\n<p>Generator expressions (contained in parentheses, like a tuple) are more efficient than list comprehensions (contained in square brackets, like a list), but don't actually return a list of values -- they return an object that can be iterated through. </p>\n\n<p>So that's why I called <code>list()</code> on <code>find_multiples_with_generator()</code>, which is actually sort of pointless, since you could also simply do <code>sum(find_multiples_with_generator()</code>, which is your ultimate goal here. I'm just trying to show you that generator expressions and list comprehensions look similar but behave differently. (Something that tripped me up early on.)</p>\n\n<p>The other answers here really solve the problem, I just thought it might be worth seeing these three approaches compared.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:38:27.180", "Id": "299", "ParentId": "7", "Score": "6" } }, { "body": "<p>Here is one solution using ifilter. Basically it will do the same as using a generator but since you try to filter out numbers that don't satisfy a function which returns true if the number is divisible by all the factors, maybe it captures better your logic. It may be a bit difficult to understand for someone not accustomed to functional logic.</p>\n\n<pre><code>from itertools import ifilter\n\ndef is_multiple_builder(*factors):\n \"\"\"returns function that check if the number passed in argument is divisible by all factors\"\"\"\n def is_multiple(x):\n return all(x % factor == 0 for factor in factors)\n return is_multiple\n\ndef find_multiples(factors, iterable):\n return ifilter(is_multiple_builder(*factors), iterable)\n</code></pre>\n\n<p>The <code>all(iterable)</code> function returns <code>true</code>, if all elements in the <code>iterable</code> passed as an argument are <code>true</code>.</p>\n\n<pre><code>(x % factor == 0 for factor in factors)\n</code></pre>\n\n<p>will return a generator with true/false for all factor in factors depending if the number is divisible by this factor. I could omit the parentheses around this expression because it is the only argument of <code>all</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T05:59:23.090", "Id": "10314", "ParentId": "7", "Score": "1" } }, { "body": "<p>I would keep it simple. In this particular case I would do:</p>\n\n<pre><code>def my_sum(start, end, *divisors):\n return sum(i for i in xrange(start, end + 1) if any(i % d == 0 for d in divisors))\n\nif __name__ == '__main__':\n print(my_sum(0, 999, 3, 5))\n</code></pre>\n\n<p>Because it is readable enough. Should you need to implement more, then add more functions.</p>\n\n<p>There is also an O(1) version(if the number of divisors is assumed constant), of course.</p>\n\n<p><strong>Note:</strong> In Python 3 there is no <code>xrnage</code> as <code>range</code> is lazy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-28T15:00:00.030", "Id": "117212", "Score": "1", "body": "Nice and clear. Perhaps don't make an `end` argument which is included in the range. It's easier if we just always make ranges exclusive like in `range`. If we do that, we never have to think about what values to pass again :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T19:21:07.970", "Id": "10325", "ParentId": "7", "Score": "3" } }, { "body": "<p>Adding more to @pat answer, a function like the one below has no meaning because you can NOT re-use for similar tasks. (Copied stripping comments and docstring.)</p>\n\n<pre><code>def find_multiples():\n numbers = []\n for i in xrange(1000):\n if not (i % 3) or not (i % 5):\n numbers.append(i)\n return numbers\n</code></pre>\n\n<p>Instead put parametres at the start of your function in order to be able to reuse it. </p>\n\n<pre><code>def find_multiples(a,b,MAX):\n numbers = []\n for i in xrange(MAX):\n if not (i % a) or not (i % b):\n numbers.append(i)\n return numbers\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-25T13:12:33.337", "Id": "70802", "ParentId": "7", "Score": "2" } } ]
{ "AcceptedAnswerId": "8", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:16:08.443", "Id": "7", "Score": "60", "Tags": [ "python", "programming-challenge" ], "Title": "Using separate functions for Project Euler 1" }
7
<p>This is part from an <a href="https://stackoverflow.com/questions/4706151/python-3-1-memory-error-during-sampling-of-a-large-list/4706317#4706317">answer to a Stack Overflow question</a>. The OP needed a way to perform calculations on samples from a population, but was hitting memory errors due to keeping samples in memory. </p> <p>The function is based on part of <a href="http://svn.python.org/view/python/trunk/Lib/random.py?view=markup#sample" rel="nofollow noreferrer">random.sample</a>, but only the code branch using a set is present.</p> <p>If we can tidy and comment this well enough, it might be worth publishing as a recipe at the <a href="http://code.activestate.com/recipes/" rel="nofollow noreferrer">Python Cookbook</a>.</p> <pre><code>import random def sampling_mean(population, k, times): # Part of this is lifted straight from random.py _int = int _random = random.random n = len(population) kf = float(k) result = [] if not 0 &lt;= k &lt;= n: raise ValueError, "sample larger than population" for t in xrange(times): selected = set() sum_ = 0 selected_add = selected.add for i in xrange(k): j = _int(_random() * n) while j in selected: j = _int(_random() * n) selected_add(j) sum_ += population[j] # Partial result we're interested in mean = sum_/kf result.append(mean) return result sampling_mean(x, 1000000, 100) </code></pre> <p>Maybe it'd be interesting to generalize it so you can pass a function that calculates the value you're interested in from the sample?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T15:04:51.737", "Id": "800", "Score": "1", "body": "But you keep the samples in memory too, so this isn't an improvement, over the solution you gave him, namely not keeping the samples around but calculating each mean directly." } ]
[ { "body": "<p>Making a generator version of <code>random.sample()</code> seems to be a much better idea:</p>\n\n<pre><code>from __future__ import division\nfrom random import random\nfrom math import ceil as _ceil, log as _log\n\ndef xsample(population, k):\n \"\"\"A generator version of random.sample\"\"\"\n n = len(population)\n if not 0 &lt;= k &lt;= n:\n raise ValueError, \"sample larger than population\"\n _int = int\n setsize = 21 # size of a small set minus size of an empty list\n if k &gt; 5:\n setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets\n if n &lt;= setsize or hasattr(population, \"keys\"):\n # An n-length list is smaller than a k-length set, or this is a\n # mapping type so the other algorithm wouldn't work.\n pool = list(population)\n for i in xrange(k): # invariant: non-selected at [0,n-i)\n j = _int(random() * (n-i))\n yield pool[j]\n pool[j] = pool[n-i-1] # move non-selected item into vacancy\n else:\n try:\n selected = set()\n selected_add = selected.add\n for i in xrange(k):\n j = _int(random() * n)\n while j in selected:\n j = _int(random() * n)\n selected_add(j)\n yield population[j]\n except (TypeError, KeyError): # handle (at least) sets\n if isinstance(population, list):\n raise\n for x in sample(tuple(population), k):\n yield x\n</code></pre>\n\n<p>Taking a sampling mean then becomes trivial: </p>\n\n<pre><code>def sampling_mean(population, k, times):\n for t in xrange(times):\n yield sum(xsample(population, k))/k\n</code></pre>\n\n<p>That said, as a code review, not much can be said about your code as it is more or less taking directly from the Python source, which can be said to be authoritative. ;) It does have a lot of silly speed-ups that make the code harder to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-01-31T15:01:59.697", "Id": "485", "ParentId": "217", "Score": "2" } } ]
{ "AcceptedAnswerId": "485", "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T23:27:25.303", "Id": "217", "Score": "8", "Tags": [ "python", "random" ], "Title": "Randomly sampling a population and keeping means: tidy up, generalize, document?" }
217
<p>The requirements for this one were (<a href="https://stackoverflow.com/q/4630723/555569">original SO question</a>):</p> <ul> <li>Generate a random-ish sequence of items.</li> <li>Sequence should have each item N times.</li> <li>Sequence shouldn't have serial runs longer than a given number (longest below).</li> </ul> <p>The solution was actually drafted by another user, this is <a href="https://stackoverflow.com/questions/4630723/using-python-for-quasi-randomization/4630784#4630784">my implementation</a> (influenced by <a href="http://svn.python.org/view/python/trunk/Lib/random.py?view=markup#shuffle" rel="nofollow noreferrer">random.shuffle</a>).</p> <pre><code>from random import random from itertools import groupby # For testing the result try: xrange except: xrange = range def generate_quasirandom(values, n, longest=3, debug=False): # Sanity check if len(values) &lt; 2 or longest &lt; 1: raise ValueError # Create a list with n * [val] source = [] sourcelen = len(values) * n for val in values: source += [val] * n # For breaking runs serial = 0 latest = None for i in xrange(sourcelen): # Pick something from source[:i] j = int(random() * (sourcelen - i)) + i if source[j] == latest: serial += 1 if serial &gt;= longest: serial = 0 guard = 0 # We got a serial run, break it while source[j] == latest: j = int(random() * (sourcelen - i)) + i guard += 1 # We just hit an infinit loop: there is no way to avoid a serial run if guard &gt; 10: print("Unable to avoid serial run, disabling asserts.") debug = False break else: serial = 0 latest = source[j] # Move the picked value to source[i:] source[i], source[j] = source[j], source[i] # More sanity checks check_quasirandom(source, values, n, longest, debug) return source def check_quasirandom(shuffled, values, n, longest, debug): counts = [] # We skip the last entries because breaking runs in them get too hairy for val, count in groupby(shuffled): counts.append(len(list(count))) highest = max(counts) print('Longest run: %d\nMax run lenght:%d' % (highest, longest)) # Invariants assert len(shuffled) == len(values) * n for val in values: assert shuffled.count(val) == n if debug: # Only checked if we were able to avoid a sequential run &gt;= longest assert highest &lt;= longest for x in xrange(10, 1000): generate_quasirandom((0, 1, 2, 3), 1000, x//10, debug=True) </code></pre> <p>I'd like to receive any input you have on improving this code, from style to comments to tests and anything else you can think of. </p>
[]
[ { "body": "<p>A couple of possible code improvements that I noticed:</p>\n\n<pre><code>sourcelen = len(values) * n\n</code></pre>\n\n<p>This seems unnecessarily complicated to me. I mean, after a second of thinking the reader of this line will realize that <code>len(values) * n</code> is indeed the length of <code>source</code>, but that's still one step of thinking more than would be required if you just did <code>sourcelen = len(source)</code> (after populating <code>source</code> of course).</p>\n\n<p>That being said, I don't see why you need to store the length of <code>source</code> in a variable at all. Doing <code>for i in xrange(len(source)):</code> isn't really less readable or less efficient than doing <code>for i in xrange(sourcelen):</code>, so I'd just get rid of the variable altogether.</p>\n\n<hr>\n\n<pre><code>source = []\nfor val in values:\n source += [val] * n\n</code></pre>\n\n<p>This can be written as a list comprehension like this:</p>\n\n<pre><code>source = [x for val in values for x in [val]*n]\n</code></pre>\n\n<p>Using list comprehensions is usually considered more idiomatic python than building up a list iteratively. It is also often more efficient.</p>\n\n<p>As Fred Nurk points out, the list comprehension can also be written as</p>\n\n<pre><code>source = [val for val in values for _ in xrange(n)]\n</code></pre>\n\n<p>which avoids the creation of a temporary list and is maybe a bit more readable.</p>\n\n<hr>\n\n<pre><code>j = int(random() * (sourcelen - i)) + i\n</code></pre>\n\n<p>To get a random integer between <code>x</code> (inclusive) and <code>y</code> (exclusive), you can use <code>random.randrange(x,y)</code>, so the above can be written as:</p>\n\n<pre><code>j = randrange(i, len(source) - i)\n</code></pre>\n\n<p>(You'll also need to import <code>randrange</code> instead of <code>random</code> from the random module). This makes it more immediately obviously that <code>j</code> is a random number between <code>i</code> and <code>len(source) - i</code> and introduces less room for mistakes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T09:20:50.903", "Id": "419", "Score": "0", "body": "Alternatively: `source = [val for val in values for _ in xrange(n)]` which, for me, makes it more clear you're repeating values compared to creating a temporary list, multiplying it, and then iterating it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:33:23.913", "Id": "243", "ParentId": "219", "Score": "4" } } ]
{ "AcceptedAnswerId": "243", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T23:41:23.607", "Id": "219", "Score": "14", "Tags": [ "python", "random" ], "Title": "Quasi-random sequences: how to improve style and tests?" }
219
<p>It's clever, but makes me vomit a little:</p> <pre><code>file = '0123456789abcdef123' path = os.sep.join([ file[ x:(x+2) ] for x in range(0,5,2) ]) </code></pre>
[]
[ { "body": "<p>Is there are reason you're not just doing:</p>\n\n<pre><code>path = os.sep.join([file[0:2], file[2:4], file[4:6]])\n</code></pre>\n\n<p>I think that my version is a little easier to parse (as a human), but if you need to extend the number of groups, your code is more extensible.</p>\n\n<p>Edit: and if we're looking for things that are easy to read but not necessarily the best way to do it...</p>\n\n<pre><code>slash = os.sep\npath = file[0:2] + slash + file[2:4] + slash + file[4:6]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:00:30.617", "Id": "347", "ParentId": "346", "Score": "10" } }, { "body": "<p>I have no idea what you're trying to do here, but it looks like you're splitting a string into groups of two a specified number of times? Despite the magic constants, etc. there's really no better way to <strong>do</strong> it, but I think there's certainly a better way to format it (I'm assuming these are directories since you're using os.sep):</p>\n\n<p>The below is I think a more clear way to write it:</p>\n\n<pre><code>file = '0123456789abcdef123'\ndir_len = 2\npath_len = 3\n\npath = os.sep.join(file[ x:(x+2) ] for x in range(0, dir_len * path_len-1, dir_len))\n</code></pre>\n\n<p>Note that the [] around the list comprehension is gone - it's now a <a href=\"http://linuxgazette.net/100/pramode.html\" rel=\"nofollow\">generator</a>. For this example it really doesn't matter which one you use, but since this is Code Review generators are another Python concept you should look at.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:20:27.817", "Id": "349", "ParentId": "346", "Score": "2" } } ]
{ "AcceptedAnswerId": "349", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T01:28:04.327", "Id": "346", "Score": "0", "Tags": [ "python" ], "Title": "Generating filesystem paths from a fixed string" }
346
<p>Here is the skeleton of my (first!) Django app:</p> <pre><code># models.py class Task(models.Model): description = models.CharField(max_length = 200) ... # forms.py class AddTaskForm(forms.ModelForm): class Meta: model = Task </code></pre> <p>I then created two views using <code>AddTaskForm</code>: one to create a new instance, the other to edit an existing one. I was able to refactor those two views (and the function they call) into one, but I'm not sure I got the best possible result...</p> <pre><code># urls.py: (r'^yata/add_task/$', 'yata.views.edit'), (r'^yata/(?P&lt;task_id&gt;\d+)/edit/$', 'yata.views.edit'), # views.py def edit(request, task_id = None): t = get_object_or_404(Task, pk=task_id) if task_id else None if request.method == 'POST': form = AddTaskForm(request.POST, instance=t) if form.is_valid(): form.save() return HttpResponseRedirect('/yata/') else: form = AddTaskForm(instance = t) # Either the form was not valid, or we've just created it d = {'form': form} if task_id: # The template needs the id to decide if the form's action # is .../add_task or .../{{id}}/edit d['id'] = t.id return render_to_response('yata/edit.html', d, context_instance=RequestContext(request)) </code></pre> <p>And here is the corresponding part of the template:</p> <pre><code># edit.html {% if id %} &lt;form action="/yata/{{ id }}/edit/" method="post"&gt; {% else %} &lt;form action="/yata/add_task/" method="post"&gt; {% endif %} {{ form.as_p }} &lt;input type="submit" value="Save!" /&gt; &lt;/form&gt; </code></pre> <p>Is there a better Django idiom to handle this 'add or create' issue? Or can this be considered a correct way?</p>
[]
[ { "body": "<p>I have looked at your code and I think that it actually looks pretty clean and straight forward. However, I would suggest that you make it more DRY by using <a href=\"http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse\" rel=\"nofollow\">reverse()</a> to figure out what action to assign to the form.</p>\n\n<p>views.py:</p>\n\n<pre><code>if task_id:\n action = reverse(edit, args=[task_id])\nelse:\n action = reverse(edit)\nd['action'] = action\n</code></pre>\n\n<p>edit.html:</p>\n\n<pre><code>&lt;form action=\"{{ action }}\" method=\"post\"&gt;\n {{ form.as_p }}\n &lt;input type=\"submit\" value=\"Save!\" /&gt;\n&lt;/form&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T07:52:06.830", "Id": "653", "Score": "0", "body": "And, additionally, it helps separating concerns: the view is not supposed to contain the application's logic... Great! Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T22:49:48.980", "Id": "392", "ParentId": "374", "Score": "2" } }, { "body": "<p>You don't need set \"action\" for form directly.</p>\n\n<pre><code># views.py\ndef edit(request, task_id = None):\n t = get_object_or_404(Task, pk=task_id) if task_id else None\n\n form = AddTaskForm(request.POST or None, instance=t)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/yata/')\n\n return render_to_response('yata/edit.html', {'form': form}, \n context_instance=RequestContext(request))\n\n# edit.html\n&lt;form action=\"\" method=\"post\"&gt;\n {{ form.as_p }}\n &lt;input type=\"submit\" value=\"Save!\" /&gt;\n&lt;/form&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T20:31:40.057", "Id": "1831", "ParentId": "374", "Score": "2" } } ]
{ "AcceptedAnswerId": "392", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T14:08:51.607", "Id": "374", "Score": "11", "Tags": [ "python", "django" ], "Title": "An idiom to use the same view function to create or edit an object?" }
374
<p>Can I make my template syntax simpler? I'm hoping to eliminate the <code>if</code> and maybe also the <code>for</code> block. </p> <p>This worked in the shell but I can't figure out the template syntax.</p> <pre><code>recipes[0].recipephotos_set.get(type=3).url </code></pre> <p>model.py</p> <pre><code>class Recipe(models.Model): .... class RecipePhotos(models.Model): PHOTO_TYPES = ( ('3', 'Sub Featured Photo: 278x209'), ('2', 'Featured Photo: 605x317'), ('1', 'Recipe Photo 500x358'), ) recipe = models.ForeignKey(Recipe) url = models.URLField(max_length=128,verify_exists=True) type = models.CharField("Type", max_length=1, choices=PHOTO_TYPES) </code></pre> <p>view.py</p> <pre><code>recipes = Recipe.objects.filter(recipephotos__type=3) </code></pre> <p>template.html</p> <pre><code>{% for recipe in recipes %} {% for i in recipe.recipephotos_set.all %} {% if i.type == '3' %} {{ i.url }} {% endif %} {% endfor %} &lt;a href="/recipe/{{ recipe.recipe_slug }}/"&gt;{{ recipe.recipe_name }}&lt;/a&gt;&lt;/li&gt; {% empty %} </code></pre>
[]
[ { "body": "<p>I'll refer you to a <a href=\"https://stackoverflow.com/questions/223990/how-do-i-perform-query-filtering-in-django-templates\">Stack Overflow post</a> that pretty much nails the answer.</p>\n\n<p>I assume that you want to display all recipes that have \"Sub Featured Photos\".</p>\n\n<p>The call <code>recipes = Recipe.objects.filter(recipephotos__type=3)</code> will give you a queryset of recipes that have at least one photos with type 3. So far so good. Note, that this code is in the views.py file and not in the template. Like the StackOverflow post mentioned, you should put the filtering code in your view or model.</p>\n\n<p>Personally I'd prefer writing a function for your model class:</p>\n\n<pre><code>class Recipe(models.Model):\n (...)\n def get_subfeature_photos(self):\n return self.recipephotos_set.filter(type=\"3\")\n</code></pre>\n\n<p>And access it in the template like this:</p>\n\n<pre><code>{% for recipe in recipes %}\n {% for photo in recipe.get_subfeature_photos %}\n {{ photo.url }}\n {% endfor %}\n (...)\n{% endfor %}\n</code></pre>\n\n<p>Please note that the function is using <code>filter()</code> for multiple items instead of <code>get()</code>, which only ever returns one item and throws a <code>MultipleObjectsReturned</code> exception if there are more.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T08:06:38.763", "Id": "451", "ParentId": "445", "Score": "9" } } ]
{ "AcceptedAnswerId": "451", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T01:57:55.443", "Id": "445", "Score": "6", "Tags": [ "python", "django", "django-template-language" ], "Title": "Django query_set filtering in the template" }
445
<p>Please review this:</p> <pre><code>from os import path, remove try: video = Video.objects.get(id=original_video_id) except ObjectDoesNotExist: return False convert_command = ['ffmpeg', '-i', input_file, '-acodec', 'libmp3lame', '-y', '-ac', '2', '-ar', '44100', '-aq', '5', '-qscale', '10', '%s.flv' % output_file] convert_system_call = subprocess.Popen( convert_command, stderr=subprocess.STDOUT, stdout=subprocess.PIPE ) logger.debug(convert_system_call.stdout.read()) try: f = open('%s.flv' % output_file, 'r') filecontent = ContentFile(f.read()) video.converted_video.save('%s.flv' % output_file, filecontent, save=True) f.close() remove('%s.flv' % output_file) video.save() return True except: return False </code></pre>
[]
[ { "body": "<p>Clean, easy to understand code. However:</p>\n\n<p>Never hide errors with a bare except. Change </p>\n\n<pre><code>try:\n ...\nexcept:\n return False\n</code></pre>\n\n<p>into </p>\n\n<pre><code>try:\n ...\nexcept (IOError, AnyOther, ExceptionThat, YouExpect):\n logging.exception(\"File conversion failed\")\n</code></pre>\n\n<p>Also, unless you need to support Python 2.4 or earlier, you want to use the files context manager support:</p>\n\n<pre><code>with open('%s.flv' % output_file, 'r') as f:\n filecontent = ContentFile(f.read())\n video.converted_video.save('%s.flv' % output_file, \n filecontent, \n save=True)\nremove('%s.flv' % output_file)\n</code></pre>\n\n<p>That way the file will be closed immediately after exiting the <code>with</code>-block, even if there is an error. For Python 2.5 you would have to <code>from __future__ import with_statement</code> as well.</p>\n\n<p>You might also want to look at using a temporary file from <code>tempfile</code> for the output file. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T15:15:26.917", "Id": "866", "Score": "0", "body": "Thanks a lot for the review! I have updated the snippet to be http://pastebin.com/9fAepHaL But I am confused as to how to use tempfile. The file is already created by the \"convert_system_call\" before I use it's name in the try/catch block. Hmm,, maybe I use tempfile.NamedTemporaryFile()?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T15:43:30.093", "Id": "870", "Score": "0", "body": "@Chantz: Yeah, exactly. If not you may end up with loads of temporary files in a current directory, where users won't find them and they ever get deleted." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T16:43:47.623", "Id": "951", "Score": "1", "body": "Lennart following your & sepp2k's suggestion I modified my code to be like http://pastebin.com/6NpsbQhz Thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T06:29:50.330", "Id": "510", "ParentId": "507", "Score": "5" } } ]
{ "AcceptedAnswerId": "510", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-01T04:39:28.163", "Id": "507", "Score": "5", "Tags": [ "python", "converting", "django" ], "Title": "Converting an already-uploaded file and saving it to a model's FileField" }
507
<p>Is there a better (more pythonic?) way to filter a list on attributes or methods of objects than relying on lamda functions?</p> <pre><code>contexts_to_display = ... tasks = Task.objects.all() tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks) tasks = filter(lambda t: not t.is_future(), tasks) tasks = sorted(tasks, Task.compare_by_due_date) </code></pre> <p>Here, <code>matches_contexts</code> and <code>is_future</code> are methods of <code>Task</code>. Should I make those free-functions to be able to use <code>filter(is_future, tasks)</code>?</p> <p>Any other comment?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T22:49:25.317", "Id": "889", "Score": "3", "body": "I think this is too specific a question to qualify as a code review." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-10T16:47:05.750", "Id": "1319", "Score": "0", "body": "Are you coding Django? Looks like it from the `Task.objects.all()` line." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-10T17:03:39.870", "Id": "1320", "Score": "0", "body": "That's part of the Django app I'm writing to learn both Python and Django, yes..." } ]
[ { "body": "<p>The first lambda (calling <code>matches_contexts</code>) can't be avoided because it has to capture the <code>contexts_to_display</code>, but the <code>not is_future()</code> can be moved into a new <code>Task</code> method <code>can_start_now</code>: it's clearer (hiding the negative conditions), reusable, and this condition will most probably be more complicated in the future. Yes, <a href=\"http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it\" rel=\"nofollow\">YAGNI</a>, I know... ;)</p>\n\n<p>And because I did not need the sorting phase to return a copy of <code>tasks</code>, I used in-place sort. By the way, the arguments are reversed between <code>filter(f,iterable)</code> and <code>sorted(iterable,f)</code>, using one just after the other seemed akward...</p>\n\n<p>So the code is now:</p>\n\n<pre><code>class Task:\n ...\n def can_start_now(self):\n return not self.is_future()\n\n\ncontexts_to_display = ...\ntasks = Task.objects.all()\ntasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)\ntasks = filter(Task.can_start_now, tasks)\ntasks.sort(Task.compare_by_due_date)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T08:53:18.163", "Id": "545", "ParentId": "533", "Score": "0" } }, { "body": "<p>I would use a list comprehension:</p>\n\n<pre><code>contexts_to_display = ...\ntasks = [t for t in Task.objects.all()\n if t.matches_contexts(contexts_to_display)\n if not t.is_future()]\ntasks.sort(cmp=Task.compare_by_due_date)\n</code></pre>\n\n<p>Since you already have a list, I see no reason not to sort it directly, and that simplifies the code a bit.</p>\n\n<p>The cmp keyword parameter is more of a reminder that this is 2.x code and will need to be changed to use a key in 3.x (but you can start using a key now, too):</p>\n\n<pre><code>import operator\ntasks.sort(key=operator.attrgetter(\"due_date\"))\n# or\ntasks.sort(key=lambda t: t.due_date)\n</code></pre>\n\n<p>You can combine the comprehension and sort, but this is probably less readable:</p>\n\n<pre><code>tasks = sorted((t for t in Task.objects.all()\n if t.matches_contexts(contexts_to_display)\n if not t.is_future()),\n cmp=Task.compare_by_due_date)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T18:20:22.993", "Id": "966", "Score": "0", "body": "Thanks for the tip about list comprehension! As `compare_by_due_date` specifically handles null values for the due date, I'm not sure I can use a key. But I'll find out!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T18:24:03.433", "Id": "969", "Score": "0", "body": "@XavierNodet: Anything which can be compared by a cmp parameter can be converted (even if tediously) to a key by simply wrapping it. With my use of the \"due_date\" attribute, I'm making some assumptions on how compare_by_due_date works, but if you give the code for compare_by_due_date (possibly in a SO question?), I'll try my hand at writing a key replacement for it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T20:00:57.003", "Id": "977", "Score": "0", "body": "Thanks! SO question is here: http://stackoverflow.com/q/4879228/4177" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T11:44:09.317", "Id": "547", "ParentId": "533", "Score": "7" } }, { "body": "<p>Since you are writing Django code, you don't need lambdas at all (explanation below). In other Python code, you might want to use list comprehensions, as other commenters have mentioned. <code>lambda</code>s are a powerful concept, but they are extremely crippled in Python, so you are better off with loops and comprehensions.</p>\n\n<p>Now to the Django corrections.</p>\n\n<pre><code>tasks = Task.objects.all()\n</code></pre>\n\n<p><code>tasks</code> is a <code>QuerySet</code>. <code>QuerySet</code>s are lazy-evaluated, i.e. the actual SQL to the database is deferred to the latest possible time. Since you are using lambdas, you actually force Django to do an expensive <code>SELECT * FROM ...</code> and filter everything manually and in-memory, instead of letting the database do its work.</p>\n\n<pre><code>contexts_to_display = ...\n</code></pre>\n\n<p>If those contexts are Django model instances, then you can be more efficient with the queries and fields instead of separate methods:</p>\n\n<pre><code># tasks = Task.objects.all()\n# tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks) \n# tasks = filter(lambda t: not t.is_future(), tasks)\n# tasks = sorted(tasks, Task.compare_by_due_date)\nqs = Task.objects.filter(contexts__in=contexts_to_display, date__gt=datetime.date.today()).order_by(due_date)\ntasks = list(qs)\n</code></pre>\n\n<p>The last line will cause Django to actually evaluate the <code>QuerySet</code> and thus send the SQL to the database. Therefore you might as well want to return <code>qs</code> instead of <code>tasks</code> and iterate over it in your template.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-11T14:25:55.053", "Id": "1360", "Score": "0", "body": "`Context` is indeed a model class, but tasks may have no context, and I want to be able to retrieve the set of all tasks that 'have a given context or no context'. But `context__in=[c,None]` does not work... Maybe 'no context' should actually be an instance of Context..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-11T14:26:45.067", "Id": "1361", "Score": "0", "body": "Similarly, the date may be null, so I can't simply filter or order on the date..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-11T10:40:35.640", "Id": "743", "ParentId": "533", "Score": "3" } } ]
{ "AcceptedAnswerId": "547", "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T22:44:01.423", "Id": "533", "Score": "1", "Tags": [ "python" ], "Title": "Is there a better way than lambda to filter on attributes/methods of objects?" }
533
<p>I haven't had anyone help me out with code review, etc, so I thought I'd post a Python class I put together for interfacing with Telnet to get information from a memcached server.</p> <pre><code>import re, telnetlib class MemcachedStats: _client = None def __init__(self, host='localhost', port='11211'): self._host = host self._port = port @property def client(self): if self._client is None: self._client = telnetlib.Telnet(self._host, self._port) return self._client def key_details(self, sort=True): ' Return a list of tuples containing keys and details ' keys = [] slab_ids = self.slab_ids() for id in slab_ids: self.client.write("stats cachedump %s 100\n" % id) response = self.client.read_until('END') keys.extend(re.findall('ITEM (.*) \[(.*); (.*)\]', response)) if sort: return sorted(keys) return keys def keys(self, sort=True): ' Return a list of keys in use ' return [key[0] for key in self.key_details(sort=sort)] def slab_ids(self): ' Return a list of slab ids in use ' self.client.write("stats items\n") response = self.client.read_until('END') return re.findall('STAT items:(.*):number', response) def stats(self): ' Return a dict containing memcached stats ' self.client.write("stats\n") response = self.client.read_until('END') return dict(re.findall("STAT (.*) (.*)\r", response)) </code></pre> <p>This is also up on <a href="https://github.com/dlrust/python-memcached-stats/blob/master/src/memcached_stats.py" rel="nofollow">GitHub</a>. </p> <p>I would love some feedback on:</p> <ul> <li>Organization</li> <li>Better ways of accomplishing the same result</li> </ul>
[]
[ { "body": "<p>The pattern</p>\n\n<pre><code>self.client.write(\"some command\\n\")\nresponse = self.client.read_until('END')\n</code></pre>\n\n<p>appears three times in your code. I think this is often enough to warrant refactoring it into its own method like this:</p>\n\n<pre><code>def command(self, cmd):\n self.client.write(\"%s\\n\" % cmd)\n return self.client.read_until('END')\n</code></pre>\n\n<hr>\n\n<p>In <code>key_details</code> you're using <code>extend</code> to build up a list. However it's more pythonic to use list comprehensions than building up a list imperatively. Thus I'd recommend using the following list comprehension:</p>\n\n<pre><code>regex = 'ITEM (.*) \\[(.*); (.*)\\]'\ncmd = \"stats cachedump %s 100\"\nkeys = [key for id in slab_ids for key in re.findall(regex, command(cmd % id))]\n</code></pre>\n\n<hr>\n\n<p>Afterwards you do this:</p>\n\n<pre><code>if sort:\n return sorted(keys)\nreturn keys\n</code></pre>\n\n<p>Now this might be a matter of opinion, but I'd rather write this using an <code>else</code>:</p>\n\n<pre><code>if sort:\n return sorted(keys)\nelse:\n return keys\n</code></pre>\n\n<p>I think this is optically more pleasing as both <code>return</code>s are indented at the same level. It also makes it immediately obviously that the second <code>return</code> is what happens if the <code>if</code> condition is false.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-07T05:24:21.443", "Id": "1189", "Score": "0", "body": "thanks! I've incorporated some of these into the code on github. I also added precompiled versions of the regex into the class" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-07T05:26:09.680", "Id": "1190", "Score": "0", "body": "Also, as far as the list comprehension goes. Since `re.findall(regex, command(cmd % id))` can return multiple items, I am using extend. Is there a way to build a list that extends itself vs item by item building?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-07T05:31:04.700", "Id": "1191", "Score": "0", "body": "@dlrust: Yes, of course, you need to add another `for` in the list comprehension to get a flat list. I actually meant to do that, but forgot somehow." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-07T19:39:37.137", "Id": "1207", "Score": "0", "body": "Thanks. Not sure if this is the best way to do this, but it works `keys = [j for i in [self._key_regex.findall(self.command(cmd % id)) for id in self.slab_ids()] for j in i]`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-07T19:43:32.983", "Id": "1208", "Score": "0", "body": "@lrust: By using an inner list like that, you need one more `for` than you would otherwise. Does `[key for id in slab_ids for key in self._key_regex.findall(self.command(cmd % id))]` not work for you?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-06T05:08:06.750", "Id": "638", "ParentId": "636", "Score": "7" } } ]
{ "AcceptedAnswerId": "638", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-06T01:42:42.690", "Id": "636", "Score": "10", "Tags": [ "python", "networking" ], "Title": "Python class w/ Telnet interface to memcached" }
636
<p>Below are two solutions to the FizzBuzz problem in Python. Which one of these is more "Pythonic" and why is it more "Pythonic" than the other?</p> <p>Solution One:</p> <pre><code>fizzbuzz = '' start = int(input("Start Value:")) end = int(input("End Value:")) for i in range(start,end+1): if i%3 == 0: fizzbuzz += "fizz" if i%5 == 0: fizzbuzz += "buzz" if i%3 != 0 and i%5 != 0: fizzbuzz += str(i) fizzbuzz += ' ' print(fizzbuzz) </code></pre> <p>Solution Two:</p> <pre><code>fizzbuzz = [] start = int(input("Start Value:")) end = int(input("End Value:")) for i in range(start,end+1): entry = '' if i%3 == 0: entry += "fizz" if i%5 == 0: entry += "buzz" if i%3 != 0 and i%5 != 0: entry = i fizzbuzz.append(entry) for i in fizzbuzz: print(i) </code></pre>
[]
[ { "body": "<p>As has already been pointed out, creating a list is preferable as it avoids the concatenation of large strings. However neither of your solutions is the most pythonic solution possible:</p>\n\n<p>Whenever you find yourself appending to a list inside a for-loop, it's a good idea to consider whether you could use a list comprehension instead. List comprehensions aren't only more pythonic, they're also usually faster.</p>\n\n<p>In this case the body of the loop is a bit big to fit into a list comprehension, but that's easily fixed by refactoring it into its own function, which is almost always a good idea software design-wise. So your code becomes:</p>\n\n<pre><code>def int_to_fizzbuzz(i):\n entry = ''\n if i%3 == 0:\n entry += \"fizz\"\n if i%5 == 0:\n entry += \"buzz\"\n if i%3 != 0 and i%5 != 0:\n entry = i\n return entry\n\nfizzbuzz = [int_to_fizzbuzz(i) for i in range(start, end+1)]\n</code></pre>\n\n<p>However, while we're at it we could just put the whole fizzbuzz logic into a function as well. The function can take <code>start</code> and <code>end</code> as its argument and return the list. This way the IO-logic, living outside the function, is completely separated from the fizzbuzz logic - also almost always a good idea design-wise.</p>\n\n<p>And once we did that, we can put the IO code into a <code>if __name__ == \"__main__\":</code> block. This way your code can be run either as a script on the command line, which will execute the IO code, or loaded as a library from another python file without executing the IO code. So if you should ever feel the need to write a GUI or web interface for fizzbuzz, you can just load your fizzbuzz function from the file without changing a thing. Reusability for the win!</p>\n\n<pre><code>def fizzbuzz(start, end):\n def int_to_fizzbuzz(i):\n entry = ''\n if i%3 == 0:\n entry += \"fizz\"\n if i%5 == 0:\n entry += \"buzz\"\n if i%3 != 0 and i%5 != 0:\n entry = i\n return entry\n\n return [int_to_fizzbuzz(i) for i in range(start, end+1)]\n\nif __name__ == \"__main__\":\n start = int(input(\"Start Value:\"))\n end = int(input(\"End Value:\"))\n for i in fizzbuzz(start, end):\n print(i)\n</code></pre>\n\n<p>(Note that I've made <code>int_to_fizzbuzz</code> an inner function here, as there's no reason you'd want to call it outside of the <code>fizzbuzz</code> function.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T00:10:32.443", "Id": "1469", "Score": "0", "body": "You could also take start end as command line arguments (as opposed to user input) so any future GUI can call the command line version in its present state without having to refactor any code. You'll probably need to add a --help argument so users have a way to look up what arguments are available." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-28T02:22:53.313", "Id": "18110", "Score": "0", "body": "I think those last two lines could better be `print '\\n'.join(fizzbuzz(start, end))`. Also, refactored like this, the third `if` can be written `if not entry:`. Also, writing a bunch of Java may have made me hypersensitive, but `entry = str(i)` would make the list be of consistent type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-04T09:05:41.910", "Id": "130912", "Score": "0", "body": "The list comprehension could be replaced with a generator." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-14T02:11:32.663", "Id": "768", "ParentId": "763", "Score": "20" } }, { "body": "<p>I have read a good solution with decorator, and I think it is a pythonic way to achieve a FizzBuzz solution:</p>\n\n<pre><code>@fizzbuzzness( (3, \"fizz\"), (5, \"buzz\") )\ndef f(n): return n\n</code></pre>\n\n<p>Generators are also a good pythonic way to get a list of numbers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-07T14:09:08.937", "Id": "332165", "Score": "0", "body": "If you read python guide for beginners, you probably read about pep20. it says that \"Explicit is better than implicit.\" also YAGNI principle defines not to do anything if you need it only once. so there is no point to write decorator." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-14T11:24:12.343", "Id": "770", "ParentId": "763", "Score": "4" } }, { "body": "<p>I am not sure either solution has any 'Pythonic' elements. What I mean is, you have not used any features that are characteristic of Python. I think that for a beginner litmus test, you should demonstrate your ability to create functions and make some use of lambda, map, reduce, filter, or list comprehensions. Since output formatting is also an important fundamental skill, I would throw in some gratuitous use of it. Using comments before code blocks and using docstrings inside functions is always a good idea. Using the 'else' of iterators would also be more python-like, but this problem does not lend itself to such a solution.</p>\n\n<p>I would leave out the type casting on the user input. If you are using Python 2.X then it is redundant to cast the value since the print statement evaluates the input. If you are using 3.X then the point of type casting would be to force the value from a char to an int. The problem is, if the input included alphabetic characters then Python would throw an error. Also, since you do no bounds checking, casting to an int would not protect you from a negative integer screwing up you range.</p>\n\n<p>Here is what I would do in Python 2.x:</p>\n\n<pre><code># gather start and end value from user\nstart = input(\"Start value: \")\nend = input(\"End value: \")\n\ndef fizzbuzz(x):\n \"\"\" The FizzBuzz algorithm applied to any value x \"\"\"\n if x % 3 == 0 and x % 5 == 0:\n return \"FizzBuzz\"\n elif x % 3 == 0:\n return \"Fizz\"\n elif x % 5 == 0:\n return \"Buzz\"\n else:\n return str(x)\n\n# apply fizzbuzz function to all values in the range\nfor x in map(fizzbuzz, range(start,end+1)):\n print \"{0:&gt;8s}\".format(x)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T06:37:01.823", "Id": "78609", "ParentId": "763", "Score": "3" } }, { "body": "<p>Not a decorator nor a function it's a right solution. Do some benchmarks and you will see. Call a function in Python is quite expensive, so try to avoid them.</p>\n\n<pre><code>for n in xrange(1, 101):\n s = \"\"\n if n % 3 == 0:\n s += \"Fizz\"\n if n % 5 == 0:\n s += \"Buzz\"\n print s or n\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<pre><code>for n in xrange(1, 101):\n print(\"Fizz\"*(n % 3 == 0) + \"Buzz\"*(n % 5 == 0) or n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-28T16:52:27.117", "Id": "148975", "Score": "0", "body": "_Call a function in Python is quite expensive, so try to avoid them._ You do not pay money to call a function. You just wait a tiny bit of time. If a function is going to be called 100 or 10000 times, then you need not to worry. When writing in a high level language we should optimize for readability and maintainability, if you want rough speed use C, do not write highly obfuscated Python code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-01T17:56:12.810", "Id": "149084", "Score": "0", "body": "I dont see any obfuscated code here, it's just a more pytonic way of writing.\nI am really worried that you don't understand what a function call is in Python." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-27T23:14:14.493", "Id": "82785", "ParentId": "763", "Score": "1" } }, { "body": "<p>Answering my own question: \"why noone uses <code>yield</code>?\"</p>\n\n<pre><code># the fizbuz logic, returns an iterator object that\n# calculates one value at a time, not all ot them at once\ndef fiz(numbers):\n for i in numbers:\n if i % 15 == 0:\n yield 'fizbuz'\n elif i % 5 == 0:\n yield 'buz'\n elif i % 3 == 0:\n yield 'fiz'\n else:\n yield str(i)\n\n# xrange evaluates lazily, good for big numbers\n# matches well with the lazy-eval generator function\nnumbers = xrange(1,2**20)\n\n# this gets one number, turns that one number into fuz, repeat\nprint ' '.join(fiz(numbers))\n\n# returns: 1 2 fiz 4 buz fiz [...] fiz 1048573 1048574 fizbuz\n</code></pre>\n\n<ul>\n<li>clearly separates fizbuz logic from concatenation</li>\n<li>is as plain and readeable as possible</li>\n<li><a href=\"https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/\" rel=\"nofollow\">generator iterator</a> does not keep all the array in memory</li>\n<li>so that you can do it on arbitrary numbers (see <a href=\"https://projecteuler.net/problem=10\" rel=\"nofollow\">Euler problem #10</a>)</li>\n</ul>\n\n<p>What I do not like in this solution is the three <code>if</code>s, whereas the problem can be solved with two.</p>\n\n<p><strong>Answer:</strong> because yield is efficient when you do not want to keep big arrays in memory just to iterate through them. But this question is not about big arrays.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-09T14:51:11.840", "Id": "245332", "Score": "2", "body": "I was tempted to post a answer solely to explain that 3 and 5 are primes, and that you can check for 15 rather than 3 and 5 individually." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-25T10:01:55.103", "Id": "248449", "Score": "0", "body": "And why is yield a better solution? Please explain so that the OP can learn from your thought process, instead of just saying \"Here's how I would do\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-07T14:13:36.030", "Id": "332168", "Score": "0", "body": "Actually, you can do yeild only once, also you dont need to get remainder by 15. look \n\n\ndef fizzbuzz(count, step):\n for num in range(1, count, step):\n output = \"\"\n if not num % 3:\n output += \"fizz\"\n if not num % 5:\n output += \"buzz\"\n yield (output if output else str(num))\n\n\nprint(', '.join(fizzbuzz(count=100, step=2)))" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-09T12:45:13.367", "Id": "131528", "ParentId": "763", "Score": "1" } } ]
{ "AcceptedAnswerId": "768", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-13T22:06:54.343", "Id": "763", "Score": "14", "Tags": [ "python", "comparative-review", "fizzbuzz" ], "Title": "Two FizzBuzz solutions" }
763
<p>I had a question about using the modulus operator in Python and whether I have used it in a understandable way. </p> <p>This is how I've written the script:</p> <pre><code>#sum numbers 1 to 200 except mults of 4 or 7 def main(): sum = 0 for x in range(200+1): if (x % 4 and x % 7): #is this bad??? sum = sum + x print sum if __name__ == '__main__': main() </code></pre> <p>So my questions are:</p> <ul> <li>Should I spell out the modulo more clearly? ie <code>if x % 4 != 0 and x % 7 != 0</code></li> <li>Should I be approaching this in a very different way? </li> </ul>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T02:45:46.707", "Id": "1471", "Score": "2", "body": "Omitting the `!= 0` is fine, even preferable. Most everyone understands that non-zero numbers are `True` in most high-level languages, so you're not exploiting some tough-to-remember quirk that will trip you up later." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T06:07:25.803", "Id": "1476", "Score": "2", "body": "@David: \"In most high-level languages\"? I'd assume that the number of high-level languages in which this is not true is greater than the number of low-level languages in which it is not true." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T06:11:40.040", "Id": "1477", "Score": "0", "body": "@sepp2k I'm not sure I understand your comment. Could you explain further?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T06:16:10.570", "Id": "1479", "Score": "1", "body": "@Kyle: You make it sound as if `0` being false (and the other numbers being true) was a concept introduced by high-level languages (otherwise why say \"most high-level languages\" instead of \"most languages\"). This is not true - 0 being false was a concept introduced by machine language. And as a matter of fact I believe there are more high-level languages in which 0 is not usable in place of `false` than there are low-level languages in which 0 can not be used as false." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T06:21:39.017", "Id": "1480", "Score": "0", "body": "@ sepp2k, I got it now. I had originally submitted this code for a quick online test to qualify for an interview. And after I clicked submit I thought, \"geez, that's probably a crappy way to make code someone else could read.\" I really wanted a feel for how more experienced programmers would look at it. Especially using the modulo in the way I did, that a remainder = `True`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T06:38:02.827", "Id": "1481", "Score": "0", "body": "@sepp2k - I wasn't denying the case for low-level languages, only speaking about most high-level languages that I know. As for machine language, in 65c02 (the one I know) you have BEQ and BNE which test for equality and inequality to zero, thus zero was neither `true` nor `false` by definition." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T07:46:08.110", "Id": "1483", "Score": "0", "body": "I find `sum += x` more compact and elegant than `sum = sum + x`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T15:40:33.873", "Id": "1497", "Score": "0", "body": "@ Ori, I got confused there, forgetting that python has the `+=` operator, but not the `++` increment operator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T15:42:31.257", "Id": "49790", "Score": "0", "body": "I just want to add that I also think the `!= 0` should be explicitly written out." } ]
[ { "body": "<p>I think your use of <code>%</code> is fine, but that could be simplified to:</p>\n\n<pre><code>def main():\n print sum([i for i in range(201) if i % 4 and i % 7])\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p><em>Edit:</em> Since I had a bug in there, that's a pretty clear indication that the <code>%</code> is a tripwire. Instead, I'd probably do:</p>\n\n<pre><code>def divisible(numerator, denominator):\n return numerator % denominator == 0\n\ndef main():\n print sum(i for i in range(201) if not(divisible(i, 4) or divisible(i, 7)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-15T23:39:19.340", "Id": "1465", "Score": "0", "body": "Ahhh... seeing it in a generator expression makes me feel like I should make the comparison explicit, as a relative n00b, it confuses me what the comparison is doing exactly. I think that's bad since it's my code." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T00:00:21.360", "Id": "1467", "Score": "0", "body": "What elegant looking code." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T02:50:28.603", "Id": "1472", "Score": "0", "body": "@munificent - The `or` should be `and` to skip numbers that are multiples of 4 and/or 7. I thought Kyle had it wrong at first, but after careful consideration I'm 93.84% sure it should be `and`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T03:40:22.323", "Id": "1473", "Score": "0", "body": "Thanks Munificent! I think you answer helped me a lot in understanding generator expressions too." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T04:44:47.903", "Id": "1474", "Score": "0", "body": "@David - You're right. This is actually one of the things I don't like about how this uses `%`. `i % 4` means \"*not* divisible by four\" which is backwards from what you expect (but also what we want, which makes it hard to read." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T04:59:14.983", "Id": "1475", "Score": "0", "body": "@munificent, this was really the essence of the question. I was really trying to figure out if my usage of the modulo operator was abusive, and I think it was. Because it looks like it should do one thing, but instead it does the other. Thanks for editing to the correct code." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T06:11:56.843", "Id": "1478", "Score": "0", "body": "@Kyle: This is not a generator expression, it's a list comprehension. You can tell because it's surrounded by square brackets. However it *should* be a generator expression as there is no benefit to generating a list here. So you should remove the brackets." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T06:56:28.757", "Id": "1482", "Score": "0", "body": "Updated to be clearer, I think." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-15T23:09:40.267", "Id": "795", "ParentId": "794", "Score": "9" } }, { "body": "<p>My program is the shortest possible:</p>\n\n<pre><code>print 12942\n</code></pre>\n\n<p>Use the formula of inclusion/exclusion.</p>\n\n<p>There should be <code>200-(200/4)-(200/7)+(200/28) (Using integer division) = 200-50-28+7 = 129</code> terms in the sum.</p>\n\n<p>The sum must be <code>s(200) - 4*s(200/4) - 7*s(200/7) + 28*s(200/28) where s(n) = sum from 1 till n = n*(n+1)/2</code>.</p>\n\n<p>This evaluates to <code>0.5* (200*201 - 4*50*51 - 7*28*29 + 28*7*8) = 0.5*(40200 - 10200 - 5684 + 1568) = **12942**</code>.</p>\n\n<p>Why write a program if you can use math?</p>\n\n<p>(I'll admit I used a calculator to multiply and add the numbers)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-17T05:54:22.990", "Id": "1522", "Score": "2", "body": "Because just doing the maths doesn't teach you anything about the programming language you're using." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-17T11:51:05.470", "Id": "1527", "Score": "0", "body": "@dreamlax I think that \"your piece of code is more complex than required. Use a bit of math to simplify it\" is a valid comment during code review. This is not learning-a-language.stackexchange.com." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-17T12:02:51.860", "Id": "1528", "Score": "2", "body": "It's also not codegolf.stackexchange.com. We're reviewing the algorithm, not the result." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-17T19:15:02.570", "Id": "1537", "Score": "1", "body": "I don't find this solution very helpful, but in code as an algorithm it would be." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-19T03:30:49.230", "Id": "1578", "Score": "0", "body": "@KyleWpppd I don't know enough Python to turn this into correct Python code, that's why my answer has just one print statement. If anyone writes some Python code for the s() function, the integer divisions, and calling the s function, feel free to edit my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T16:26:04.627", "Id": "49792", "Score": "0", "body": "I think `print(12942)` would be better, since it would run on both Python 2 and Python 3. :-P" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-17T05:07:10.877", "Id": "821", "ParentId": "794", "Score": "3" } }, { "body": "<p>This is a more generalised version of the answers already given:</p>\n\n<pre><code>def sum_excluding_multiples(top, factors):\n return sum(i for i in range(top + 1) if all(i % factor for factor in factors))\n\nprint sum_excluding_multiples(200, (4, 7))\nprint sum_excluding_multiples(200, (3, 5, 10, 9))\n</code></pre>\n\n<p>This is @Sjoerd's answer as Python code:</p>\n\n<pre><code>def sum_excluding_multiples2(top, factor1, factor2):\n def sum_of_multiples(m=1):\n return m * int(top / m) * (int(top / m) + 1) / 2\n return (sum_of_multiples() - sum_of_multiples(factor1) \n - sum_of_multiples(factor2) + sum_of_multiples(factor1 * factor2))\n\nprint sum_excluding_multiples2(200, 4, 7)\n</code></pre>\n\n<p>This is more complicated and harder to read, and I'm not sure how to generalise it to exclude multiples of more than two numbers. But it would be faster if very large numbers were involved, since it solves the problem mathematically instead of by iterating through a range.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T10:01:39.443", "Id": "31274", "ParentId": "794", "Score": "4" } }, { "body": "<p>I think <code>x % 4 != 0</code> is clearer than <code>x % 4</code>, because:</p>\n\n<ul>\n<li>The standard way to check if a number <strong>is</strong> divisible is <code>x % 4 == 0</code>. Of course that could also be written as <code>not x % 4</code>, but usually, it's not. <code>x % 4 != 0</code> is more in line with the standard way of writing tests for divisibility.</li>\n<li><code>x % 4</code> is probably more error-prone. <a href=\"https://codereview.stackexchange.com/questions/794/print-sum-of-numbers-1-to-200-except-mults-of-4-or-7-in-python#comment1474_795\">Quoting munificient</a>:\n\n<blockquote>\n <p>'i % 4 means \"not divisible by four\" which is backwards from what you expect (but also what we want, which makes it hard to read.</p>\n</blockquote></li>\n</ul>\n\n<p>It's not really a big deal though.</p>\n\n<hr>\n\n<p>A few more comments on your code:</p>\n\n<p>Don't shadow the built-in function <code>sum()</code> with your variable <code>sum</code>. Instead, use <code>total</code> or something similar.</p>\n\n<p>You don't need the parentheses in <code>if (x % 4 and x % 7):</code>.</p>\n\n<p>As has been mentioned in the comments, write <code>sum = sum + x</code> more concisely as <code>sum += x</code>.</p>\n\n<p>I would make <code>main()</code> return the number and then write <code>print main()</code> in the last line. This way, you could reuse the function in a different context.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T15:29:03.437", "Id": "31277", "ParentId": "794", "Score": "2" } } ]
{ "AcceptedAnswerId": "795", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-15T22:37:23.323", "Id": "794", "Score": "10", "Tags": [ "python" ], "Title": "Print sum of numbers 1 to 200 except mults of 4 or 7 in Python" }
794
<p>I am primarily a Python programmer and have finally ditched the IDE in favour of vim and I will admit, I am loving it !</p> <p>My <code>vimrc</code> file looks like this:</p> <pre><code>autocmd BufRead,BufNewFile *.py syntax on autocmd BufRead,BufNewFile *.py set ai autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,with,try,except,finally,def,class set tabstop=4 set expandtab set shiftwidth=4 filetype indent on </code></pre> <p>Any changes I should make to make my Python vim experience more pleasant? </p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T19:53:30.063", "Id": "1646", "Score": "0", "body": "Hi Henry, welcome to the site. This really isn't a question for Code Review though, as this site is for reviewing working code. It is most likely better on Stack Overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:20:14.807", "Id": "472003", "Score": "0", "body": "why would this be offtopic? this is working code" } ]
[ { "body": "<p>I like to add the following:</p>\n\n<pre><code>\" Allow easy use of hidden buffers.\n\" This allows you to move away from a buffer without saving\nset hidden\n\n\" Turn search highlighting on\nset hlsearch\n\n\" Turn on spelling\n\" This auto spell checks comments not code (so very cool)\nset spell\n\n\" tabstop: Width of tab character\n\" expandtab: When on uses space instead of tabs\n\" softtabstop: Fine tunes the amount of white space to be added\n\" shiftwidth Determines the amount of whitespace to add in normal mode\nset tabstop =4\nset softtabstop =4\nset shiftwidth =4\nset expandtab\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T19:34:31.727", "Id": "1509", "Score": "0", "body": "Wonderful! Any suggestions for must-have vim plugins for enhanced Python support?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T16:58:54.873", "Id": "1639", "Score": "0", "body": "@Henry You don't want to miss pyflakes (on-the fly syntax error reporting) and using pep8 as a compiler to see if you comply with the python style guide (PEP8). See my vim cfg files at (https://github.com/lupino3/config), it is fully commented and there also are some useful vim plugins." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T19:21:28.523", "Id": "816", "ParentId": "810", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T17:48:55.890", "Id": "810", "Score": "11", "Tags": [ "python" ], "Title": "Review the vimrc for a Python programmer" }
810
<p>I have a function that takes a column title, and a response.body from a urllib GET (I already know the body contains text/csv), and iterates through the data to build a list of values to be returned. My question to the gurus here: have I written this in the cleanest, most efficient way possible? Can you suggest any improvements?</p> <pre><code>def _get_values_from_csv(self, column_title, response_body): """retrieves specified values found in the csv body returned from GET @requires: csv @param column_title: the name of the column for which we'll build a list of return values. @param response_body: the raw GET output, which should contain the csv data @return: list of elements from the column specified. @note: the return values have duplicates removed. This could pose a problem, if you are looking for duplicates. I'm not sure how to deal with that issue.""" dicts = [row for row in csv.DictReader(response_body.split("\r\n"))] results = {} for dic in dicts: for k, v in dic.iteritems(): try: results[k] = results[k] + [v] #adds elements as list+list except: #first time through the iteritems loop. results[k] = [v] #one potential problem with this technique: handling duplicate rows #not sure what to do about it. return_list = list(set(results[column_title])) return_list.sort() return return_list </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T19:13:14.887", "Id": "1508", "Score": "1", "body": "Tip: Don't use a blanket `except`, you will catch ALL exceptions rather than the one you want." } ]
[ { "body": "<p>My suggestions:</p>\n\n<pre><code>def _get_values_from_csv(self, column_title, response_body):\n # collect results in a set to eliminate duplicates\n results = set()\n\n # iterate the DictReader directly\n for dic in csv.DictReader(response_body.split(\"\\r\\n\")):\n # only add the single column we are interested in\n results.add(dic[column_title])\n\n # turn the set into a list and sort it\n return_list = list(results)\n return_list.sort()\n return return_list</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T19:19:04.433", "Id": "814", "ParentId": "812", "Score": "0" } }, { "body": "<p>Here's a shorter function that does the same thing. It doesn't create lists for the columns you're not interested in.</p>\n\n<pre><code>def _get_values_from_csv(self, column_title, response_body):\n dicts = csv.DictReader(response_body.split(\"\\r\\n\"))\n return sorted(set(d[column_title] for d in dicts))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T19:39:06.497", "Id": "1510", "Score": "0", "body": "Thanks! This is brilliant! I'm still trying to wrap my head around how to use dictionaries in a comprehension context like this. So this is exactly what I was looking for. :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T20:54:42.550", "Id": "1511", "Score": "0", "body": "sorted() will return a list, so the list() bit isn't needed." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-17T08:12:37.030", "Id": "1526", "Score": "0", "body": "Good point, Lennart -- Edited out." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T19:24:29.407", "Id": "817", "ParentId": "812", "Score": "7" } } ]
{ "AcceptedAnswerId": "817", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-16T19:08:41.697", "Id": "812", "Score": "9", "Tags": [ "python", "csv" ], "Title": "Getting lists of values from a CSV" }
812
<p>I'm trying to apply <code>string.strip()</code> to all the leafs that are strings in a multidimensional collection, but my Python is a bit rusty (to say the least). The following is the best I've come up with, but I suspect there's a much better way to do it.</p> <pre><code>def strip_spaces( item ): if hasattr( item, "__iter__" ): if isinstance( item, list ): return [strip_spaces( value ) for value in item] elif isinstance( item, dict ): return dict([(value,strip_spaces(value)) for value in item]) elif isinstance( item, tuple ): return tuple([ strip_spaces( value ) for value in item ]) elif isinstance( item, str ) or isinstance( item, unicode ): item = item.strip() return item </code></pre>
[]
[ { "body": "<pre><code>elif isinstance( item, dict ):\n return dict([(value,strip_spaces(value)) for value in item])\n</code></pre>\n\n<p>This will transform <code>{ ' a ': ' b ' }</code> into <code>{' a ': 'a' }</code>, which I suspect is not what you want. How about:</p>\n\n<pre><code> return dict([(key, strip_spaces(value)) for key, value in item.items()])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T19:44:12.957", "Id": "843", "ParentId": "834", "Score": "5" } }, { "body": "<p>I don't understand why you are checking for an <code>__iter__</code> attribute, as you don't seem to use it. However I would recommend a couple of changes:</p>\n\n<ul>\n<li>Use Abstract Base Classes in the <code>collections</code> module to test duck types, such as \"Iterable\"</li>\n<li>Use <code>types.StringTypes</code> to detect string types</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>import collections\nimport types\n\ndef strip_spaces( item ):\n if isinstance( item, types.StringTypes ):\n return item.strip()\n\n if isinstance( item, collections.Iterable ):\n if isinstance( item, list ):\n return [ strip_spaces( value ) for value in item ]\n\n elif isinstance( item, dict ):\n return dict([ ((strip_spaces(key), strip_spaces(value)) \\\n for key, value in item.iteritems() ])\n\n elif isinstance( item, tuple ):\n return tuple( [ strip_spaces( value ) for value in item ] )\n\n return item\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T21:49:51.253", "Id": "844", "ParentId": "834", "Score": "6" } } ]
{ "AcceptedAnswerId": "844", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-18T02:52:08.510", "Id": "834", "Score": "12", "Tags": [ "python", "strings" ], "Title": "Traversing a multidimensional structure and applying strip() to all strings" }
834
<p>I need to parse an invalid JSON string in which I find many repetitions of the same key, like the following snippet:</p> <pre><code>[...] "term" : {"Entry" : "value1", [.. other data ..]}, "term" : {"Entry" : "value2", [.. other data ..]}, [...] </code></pre> <p>I thought of appending a suffix to each key, and I do it using the following code:</p> <pre><code>word = "term" offending_string = '"term" : {"Entry"' replacing_string_template = '"%s_d" : {"Entry"' counter = 0 index = 0 while index != -1: # result is the string containing the JSON data index = result.find(offending_string, index) result = result.replace(offending_string, replacing_string_template % (word, counter), 1) counter += 1 </code></pre> <p>It works, but I'd like to know if it is a good approach and if you would do this in a different way.</p>
[]
[ { "body": "<pre><code>import json\n\ndef fixup(pairs):\n return pairs\n\ndecoded = json.loads(bad_json, object_pairs_hook = fixup)\n</code></pre>\n\n<p>object_pairs_hook is a more recent addition. If you have an older version of python you may not have it. The resulting python object will contain lists of pairs (including duplicates) rather then dictionaries. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T17:32:37.650", "Id": "1739", "Score": "0", "body": "+1 great! But I doubt it will work, because this code is deployed under Google App Engine, that uses an old version of python that doesn't even contain the json module. I have to `import simplejson as json` from django." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T17:36:53.890", "Id": "1740", "Score": "0", "body": "@Andrea, the current version of simplejson does support the object_pairs_hook. Even if Google App Engine doesn't have the latest version, you can probably download and install your own copy of simplejson for your project." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T17:19:37.210", "Id": "974", "ParentId": "968", "Score": "4" } } ]
{ "AcceptedAnswerId": "974", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T13:03:07.473", "Id": "968", "Score": "5", "Tags": [ "python", "parsing", "strings", "json" ], "Title": "Substitution of different occurrences of a string with changing patterns" }
968
<p>I'm trying to port this little F# snippet while staying pythonic:</p> <pre><code>["something"; "something else"; "blah"; "a string"] |&gt; List.map (fun p -&gt; p, p.Length) |&gt; List.sortBy snd </code></pre> <p>In case you don't speak F#, it gets the length of each string, then sorts by length.</p> <p>Output:</p> <blockquote> <pre><code>[("blah", 4); ("a string", 8); ("something", 9); ("something else", 14)] </code></pre> </blockquote> <p>In Python, this is the best I could do so far:</p> <pre><code>sorted([(p, len(p)) for p in ["something", "something else", "blah", "a string"]], key=lambda a:a[1]) </code></pre> <p>While correct, this doesn't look very elegant to me, or maybe it's just my non-pythonic eye.</p> <p>Is this pythonic code? How would you write it? Maybe an imperative style is more appropriate?</p>
[]
[ { "body": "<pre><code>data = [\"something\", \"something else\", \"blah\", \"a string\"]\nresult = [(x, len(x)) for x in sorted(data, key = len)]\n</code></pre>\n\n<p>Basically, its more straightforward to sort first then decorate. Although, I'm not sure why you would need the length of the list in your tuple. If you don't really need it sorting by length can be much shorter.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>If all I wanted was to output the data, I'd do it like this:</p>\n\n<pre><code>for string in sorted(data, key = len):\n print string, len(string)\n</code></pre>\n\n<p>If you really wanted to eliminate the two references to len you could do:</p>\n\n<pre><code>mykey = len\nfor string in sorted(data, key = mykey):\n print string, mykey(string)\n</code></pre>\n\n<p>But unless you are reusing the code with different mykey's that doesn't seem worthwhile.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T16:24:15.013", "Id": "1816", "Score": "0", "body": "@Mauricio Scheffer, what are you doing with it afterwards?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T16:34:35.360", "Id": "1817", "Score": "0", "body": "@Winston Ewert: just printing it to screen." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T16:37:50.097", "Id": "1818", "Score": "0", "body": "@Mauricio Scheffer, so you are just printing this list out? Why do you need the string lengths in there?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T16:39:13.493", "Id": "1819", "Score": "0", "body": "@Winston Ewert: just need to display that information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T21:17:13.283", "Id": "12906", "Score": "0", "body": "If you do not need to reuse `len` (eg. you need it only for sorting), you can use simply: `sorted(data, key=len)`. If you need it later, you can do it in two steps, to improve readability: 1) `data_sorted = sorted(data, key=len)`, 2) `result = zip(data_sorted, map(len, data_sorted))`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T19:36:36.287", "Id": "51091", "Score": "1", "body": "Nitpicking: the space between the `=` when using keyword arguments is not PEP8 compliant." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T00:48:39.577", "Id": "1004", "ParentId": "1001", "Score": "29" } }, { "body": "<p>I don't think that your solution looks bad. I would probably use a temporary variable to make the line length a bit more readable. You could consider <code>itemgetter</code> from the <code>operator</code> module.</p>\n\n<p>E.g.</p>\n\n<pre><code>from operator import itemgetter\n\norig_list = [\"something\", \"something else\", \"blah\", \"a string\"]\nmylist = [(p, len(p)) for p in orig_list]\nmylist.sort(itemgetter(1))\n</code></pre>\n\n<p>Personally I think that this is just as readable.</p>\n\n<pre><code>mylist = sorted([(p, len(p)) for p in orig_list], key=itemgetter(1))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T00:48:54.177", "Id": "1005", "ParentId": "1001", "Score": "6" } }, { "body": "<p>Here's another option. For the key function, it specifies a lambda that takes a two-item sequence, and unpacks the two items into \"s\" and \"l\", and returns \"l\". This avoids poking around each (string, length) pair by magic number, and also enforces a bit of a type constraint on the items to sort. Also, it breaks lines in convenient places, which is perfectly legal in Python:</p>\n\n<pre><code>sorted([(p, len(p)) for p \n in (\"something\", \n \"something else\", \n \"blah\", \n \"a string\")], \n key=lambda (s, l): l)\n</code></pre>\n\n<p>And here is a version that uses a generator comprehension instead of a list comprehension. Generator expressions are evaluated as items are pulled from them, rather than all at once. In this example there's no advantage, but when using expressions where items are expensive to create, or where iteration could terminate early (like database queries), generators are a big win:</p>\n\n<pre><code>sorted(((p, len(p)) for p \n in (\"something\", \n \"something else\", \n \"blah\", \n \"a string\")), \n key=lambda (s, l): l)\n</code></pre>\n\n<p>And this version deterministically handles cases where there is some ambiguity on sorting only by length:</p>\n\n<pre><code>sorted(((p, len(p)) for p \n in (\"something\", \n \"something else\", \n \"four things\", \n \"five things\", \n \"a string\")), \n key=lambda (s, l): (l, s))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T18:45:19.620", "Id": "1063", "ParentId": "1001", "Score": "1" } }, { "body": "<p>If you don't want to call <code>len</code> twice for each item (if, for example, you need to call some expensive function instead of <code>len</code>), you can sort by the second item without lambdas by using <code>itemgetter</code>.</p>\n\n<pre><code>from operator import itemgetter \n\ndata = [\"something\", \"something else\", \"blah\", \"a string\"]\nl = [(s, len(s)) for s in data]\nl.sort(key = itemgetter(1))\n</code></pre>\n\n<p>However, if the order of members is not important, it would be better to place the length first in the tuple, because the default behaviour for sorting tuples is to compare the elements in order.</p>\n\n<pre><code>data = [\"something\", \"something else\", \"blah\", \"a string\"]\nl = sorted((len(s), s) for s in data)\n</code></pre>\n\n<p>You can then switch them around during output if you want:</p>\n\n<pre><code>for length, item in l:\n print item, length\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T07:07:35.007", "Id": "1152", "ParentId": "1001", "Score": "5" } }, { "body": "<p>If the order of the items in the tuple isn't important (depends on what you're going to do with it), then it's easier to put the length first and the string second. The standard tuple sorting sorts on the first element, or if they're equal on the second, and so on.</p>\n\n<pre><code>sorted(\n (len(p), p) for p in\n (\"something\", \"something else\", \"four things\", \"five things\", \"a string\"))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T09:58:23.377", "Id": "36950", "ParentId": "1001", "Score": "1" } } ]
{ "AcceptedAnswerId": "1004", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T23:44:49.373", "Id": "1001", "Score": "37", "Tags": [ "python", "beginner", "strings", "sorting", "functional-programming" ], "Title": "Sorting strings by length - functional Python" }
1001
<pre><code>class Pool(type): pool = dict() def __new__(clas, *a, **k): def __del__(self): Pool.pool[self.__class__] = Pool.pool.get(self.__class__, []) + [self] a[-1]['__del__'] = __del__ return type.__new__(clas, *a, **k) def __call__(clas, *a, **k): if Pool.pool.get(clas): print('Pool.pool is not empty: return an already allocated instance') r = Pool.pool[clas][0] Pool.pool[clas] = Pool.pool[clas][1:] return r else: print('Pool.pool is empty, allocate new instance') return type.__call__(clas, *a, **k) class Foo(metaclass=Pool): def __init__(self): print('Foo &gt; .', self) def foo(self): print('Foo &gt; foo:', self) f1 = Foo() f1.foo() print('## now deleting f1') del f1 print('## now create f2') f2 = Foo() f2.foo() print('## now create f3') f3 = Foo() f3.foo() </code></pre> <p>what do you think about this piece of code?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:54:13.780", "Id": "1976", "Score": "0", "body": "Well, calling class variables \"clas\" annoys the heck out of me. klass or class_ is better IMO. But that's a matter of taste." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T22:35:14.517", "Id": "1998", "Score": "0", "body": "i don't like k in place of c, but i'm agree with bad sound of 'clas' too : )" } ]
[ { "body": "<pre><code>class Pool(type):\n</code></pre>\n\n<p>The defaultdict class will automatically create my list when I access it</p>\n\n<pre><code> pool = collection.defaultdict(list)\n</code></pre>\n\n<p>The python style guide suggests using the form class_ rather then clas\nIt is also not clear why you are capturing the incoming arguments as variable.\nThis being a metaclass it is going to have consistent parameters</p>\n\n<pre><code> def __new__(class_, name, bases, classdict):\n def __del__(self):\n</code></pre>\n\n<p>Since pool now automatically creates the list, we can just append to it\n Pool.pool[self.<strong>class</strong>].append(self)</p>\n\n<p>Getting rid of the variable arguments also makes this much clearer. </p>\n\n<pre><code> classdict['__del__'] = __del__\n return type.__new__(class_, name, bases, classdict)\n</code></pre>\n\n<p>args and kwargs are often used as the names for variable parameters. I recommend using them to make code clearer</p>\n\n<pre><code> def __call__(class_, *args, **kwargs):\n</code></pre>\n\n<p>Thanks to the use of defaultdict above we can make this code quite a bit cleaner. Also, this code doesn't pretend its using a functional programming language. Your code created lists by adding them together, slicing, etc. That is not a really efficient or clear way to use python.</p>\n\n<pre><code> instances = Pool.pool[class_]\n if instances:\n</code></pre>\n\n<p>There is a subtle and dangerous problem here. When you create a new instance, you pass along your parameters.\nHowever, if an instance is already created, you return that ignoring what the parameters were doing.\nThis means that you might get an object back which was created using different parameters then you just passed.\nI haven't done anything to fix that here</p>\n\n<pre><code> print('Pool.pool is not empty: return an already allocated instance')\n return instances.pop()\n else:\n print('Pool.pool is empty, allocate new instance')\n return type.__call__(class_, *args, **kwargs)\n</code></pre>\n\n<p>Your technique is to install a <code>__del__</code> method on the objects so that you can detect when they are no longer being used and keep them in your list for the next person who asks for them. the <code>__del__</code> method is invoked when the object is about to be deleted. You prevent the deletion by storing a reference to the object in your list. This is allowed but the python documentation indicates that it is not recommended.</p>\n\n<p><code>__del__</code> has a number of gotchas. If an exception is caused while running the <code>__del__</code> method it will be ignored. Additionally, it will tend to cause objects in references cycles to not be collectable. If your code is ever run on Jython/IronPython then you can't be sure that <code>__del__</code> will be called in a timely manner. For these reasons I generally avoid use of <code>__del__</code>. </p>\n\n<p>You are using a metaclass so the fact that the given object is pooled is hidden from the user. I don't really think this is a good idea. I think it is far better to be explict about something like pooling. You also lose flexibility doing it this way. You cannot create multiple pools, etc.</p>\n\n<p>The interface that I would design for this would be:</p>\n\n<pre><code>pool = Pool(Foo, 1, 2, alpha = 5) # the pool gets the arguments that will be used to construct Foo\nwith pool.get() as f1:\n # as long as I'm in the with block, I have f1, it'll be returned when I exit the block\n f1.foo()\nwith pool.get() as f2:\n f2.foo()\n with pool.get() as f3:\n f3.foo()\n\nf4 = pool.get()\nf4.foo()\npool.repool(f4)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:07:13.240", "Id": "2033", "Score": "0", "body": "yeah i would pooling to be transparent to the user because i thought it was a good thing. thanks to point me in right way. but i don't understand thw with usage" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:09:20.750", "Id": "2034", "Score": "0", "body": "\"This means that you might get an object back which was created using different parameters then you just passed\" recalling __init__ method could be help or it make pooling useless?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:12:11.873", "Id": "2035", "Score": "0", "body": "\"Also, this code doesn't pretend its using a functional programming language. Your code created lists by adding them together, slicing, etc. That is not a really efficient or clear way to use python.\" i thought functional python was more pythonic. thanks to point this" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:15:28.250", "Id": "2036", "Score": "0", "body": "@nkint, for with see: http://docs.python.org/reference/datamodel.html#context-managers basically, it allows you to provide code which is run before and after the with. That way you can write code that returns the Foo back to the pool as soon as the with block exits." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:17:21.563", "Id": "2037", "Score": "0", "body": "@nkint, if you recall __init__, you are probably not saving any noticeable amount of time by pooling. Why do we want to pool objects anyways? Typically, you pool objects because they are expensive to create." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:18:41.053", "Id": "2038", "Score": "0", "body": "@nkint, python has some influence from functional languages. In some cases functional techniques are pythonic. Basically, you should use the method that provides the most straightforward implementation. Sometimes that is functional, in this case its not." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T15:33:11.150", "Id": "1161", "ParentId": "1119", "Score": "3" } } ]
{ "AcceptedAnswerId": "1161", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T14:23:53.130", "Id": "1119", "Score": "6", "Tags": [ "python", "design-patterns" ], "Title": "python object pool with metaclasses" }
1119
<p>This takes an array of numbers then splits it into all possible combinations of the number array of size 4 then in another array puts the leftovers. As I want to take the difference in averages of the first column and the second.</p> <pre><code>import itertools #defines the array of numbers and the two columns number = [53, 64, 68, 71, 77, 82, 85] col_one = [] col_two = [] #creates an array that holds the first four results = itertools.combinations(number,4) for x in results: col_one.append(list(x)) #attempts to go through and remove those numbers in the first array #and then add that array to col_two for i in range(len(col_one)): holder = list(number) for j in range(4): holder.remove(col_one[i][j]) col_two.append(holder) col_one_average = [] col_two_average = [] for k in col_one: col_one_average.append(sum(k)/len(k)) for l in col_two: col_two_average.append(sum(l)/len(l)) dif = [] for i in range(len(col_one_average)): dif.append(col_one_average[i] - col_two_average[i]) print dif </code></pre> <p>So for example, if I have</p> <pre><code>a = [1,2,3] </code></pre> <p>and I want to split it into an array of size 2 and 1, I get</p> <pre><code>col_one[0] = [1,2] </code></pre> <p>and</p> <pre><code>col_two[0] = [3] </code></pre> <p>then</p> <pre><code>col_one[1] = [1,3] </code></pre> <p>and</p> <pre><code>col_two[1] = [2] </code></pre> <p>After I get all those I find the average of <code>col_one[0]</code> - average of <code>col_two[0]</code>.</p> <p>I hope that makes sense. I'm trying to do this for a statistics class, so if there is a 'numpy-y' solution, I'd love to hear it.</p>
[]
[ { "body": "<p>Not using numpy or scipy, but there are several things that can be improved about your code:</p>\n\n<ul>\n<li>This is minor, but in your comments you call your lists arrays, but it in python they're called lists</li>\n<li>Variable names like <code>col_one</code> and <code>col_two</code> aren't very meaningful. Maybe you should call them <code>combinations</code> and <code>rests</code> or something like that.</li>\n<li>You should definitely refactor your code into functions</li>\n<li>You often use index-based loops where it is not necessary. Where possible you should iterate by element, not by index.</li>\n<li>You're also often setting lists to the empty list and then appending to them in a loop. It is generally more pythonic and often faster to use list comprehensions for this.</li>\n</ul>\n\n<p>If I were to write the code, I'd write something like this:</p>\n\n<pre><code>import itertools\n\ndef average(lst):\n \"\"\"Returns the average of a list or other iterable\"\"\"\n\n return sum(lst)/len(lst)\n\ndef list_difference(lst1, lst2):\n \"\"\"Returns the difference between two iterables, i.e. a list containing all\n elements of lst1 that are not in lst2\"\"\"\n\n result = list(lst1)\n for x in lst2:\n result.remove(x)\n return result\n\ndef differences(numbers, n):\n \"\"\"Returns a list containing the difference between a combination and the remaining\n elements of the list for all combinations of size n of the given list\"\"\"\n\n # Build lists containing the combinations of size n and the rests\n combinations = list(itertools.combinations(numbers, n))\n rests = [list_difference(numbers, row) for row in col_one]\n\n # Create a lists of averages of the combinations and the rests\n combination_averages = [average(k) for k in combinations]\n rest_averages = [average(k) for k in rests]\n\n # Create a list containing the differences between the averages\n # using zip to iterate both lists in parallel\n diffs = [avg1 - avg2 for avg1, avg2 in zip(combination_averages, rest_averages)]\n return diffs\n\nprint differences([53, 64, 68, 71, 77, 82, 85], 4)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T17:05:32.897", "Id": "1128", "ParentId": "1121", "Score": "5" } }, { "body": "<pre><code>import itertools\nimport numpy\n\nnumber = [53, 64, 68, 71, 77, 82, 85]\n\n\nresults = itertools.combinations(number,4)\n# convert the combination iterator into a numpy array\ncol_one = numpy.array(list(results))\n\n# calculate average of col_one\ncol_one_average = numpy.mean(col_one, axis = 1).astype(int)\n\n# I don't actually create col_two, as I never figured out a good way to do it\n# But since I only need the sum, I figure that out by subtraction\ncol_two_average = (numpy.sum(number) - numpy.sum(col_one, axis = 1)) / 3\n\ndif = col_one_average - col_two_average\n\nprint dif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T17:05:13.897", "Id": "38806", "Score": "2", "body": "Using `np.fromiter(combinations(` is far faster than `np.array(list(combinations(`, (0.1 seconds vs 2 seconds, for instance) but it's also more complicated: http://numpy-discussion.10968.n7.nabble.com/itertools-combinations-to-numpy-td16635.html" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T21:28:33.287", "Id": "1140", "ParentId": "1121", "Score": "8" } } ]
{ "AcceptedAnswerId": "1140", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-03T16:05:48.193", "Id": "1121", "Score": "7", "Tags": [ "python", "array", "combinatorics" ], "Title": "Splitting an array of numbers into all possible combinations" }
1121
<p>I have the following code:</p> <pre><code>print o # {'actor_name': [u'Keanu Reeves', u'Laurence Fishburne', u'Carrie-Anne Moss', u'Hugo Weaving', u'Glor # ia Foster', u'Joe Pantoliano', u'Marcus Chong', u'Julian Arahanga', u'Belinda McClory', u'Matt Doran # '], 'played': [u'Neo (Thomas Anderson)', u'Morfeusz', u'Trinity', u'Agent Smith', u'Wyrocznia', u'Cy # pher', u'Tank', u'Apoc', u'Switch', u'Mouse']} li = list(o.itervalues()) for index, value in enumerate(li[0]): print [value, li[1][index]] # [u'Keanu Reeves', u'Neo (Thomas Anderson)'] # [u'Laurence Fishburne', u'Morfeusz'] # [u'Carrie-Anne Moss', u'Trinity'] # [u'Hugo Weaving', u'Agent Smith'] # [u'Gloria Foster', u'Wyrocznia'] # [u'Joe Pantoliano', u'Cypher'] # [u'Marcus Chong', u'Tank'] # [u'Julian Arahanga', u'Apoc'] # [u'Belinda McClory', u'Switch'] # [u'Matt Doran', u'Mouse'] </code></pre> <p>I'm curious how I could write this thing in a more Pythonic way without losing its readability.</p>
[]
[ { "body": "<p>You're looking for <a href=\"http://docs.python.org/library/functions.html#zip\"><code>zip()</code></a>.</p>\n\n<pre><code>print zip(o['actor_name'], o['played'])\n</code></pre>\n\n<p>or to make it look like your output</p>\n\n<pre><code>for entry in zip(o['actor_name'], o['played']):\n print entry\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-12T10:58:57.773", "Id": "1261", "ParentId": "1260", "Score": "10" } } ]
{ "AcceptedAnswerId": "1261", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-12T09:47:08.833", "Id": "1260", "Score": "4", "Tags": [ "python" ], "Title": "Merging two lists from dictionary. How to do this in a better way?" }
1260
<p>I just realized that I could turn:</p> <pre><code>import MySQLdb def main(): db = MySQLdb.connect( .. ) try: while True: do_thingy() finally: db.close() </code></pre> <p>into:</p> <pre><code>import MySQLdb, atexit def main(): db = MySQLdb.connect( .. ) atexit.register( db.close ) while True: do_thingy() </code></pre> <p>Which lets me keep the code for closing the database next to the opening, and saves me a line of code and an indentation level, which I like. Is there a reason why I shouldn't do this?</p>
[]
[ { "body": "<p>Firstly, an alternative:</p>\n\n<pre><code>import MySQLdb, contextlib\n\ndef main():\n db = MySQLdb.connect( .. )\n with contextlib.closing(db):\n do_thingy()\n</code></pre>\n\n<p>The database connection will be closed after the with block even in the case of exceptions.</p>\n\n<p>The primary problem created by atexit is in any attempt to reuse that code in question. It will only release the database connection when the entire program exits. That's fine in the case where this function is your entire program. But at some later point that my cease to be the case. </p>\n\n<p>If you really want the database connection to be closed at the end of the function, its clearest if you write code that does that rather then assuming that this is the only function called in the program.</p>\n\n<p>There really is not much of saving to use the atexit route. I think the clarity in the \"with\" method is worth the extra level of indentation. Additionally, you can use this same technique anywhere in code not just in a main function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-13T02:22:19.770", "Id": "2216", "Score": "0", "body": "Oh yes, you are right, I failed to think outside of my own application. :) I didn't know about contextlib, thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-13T01:24:03.400", "Id": "1277", "ParentId": "1274", "Score": "14" } } ]
{ "AcceptedAnswerId": "1277", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-03-12T22:10:10.403", "Id": "1274", "Score": "4", "Tags": [ "python", "comparative-review" ], "Title": "Should I use atexit to close db connection?" }
1274
<p>I'm learning Python and have found <a href="http://code.google.com/codejam/contest/dashboard?c=635101#s=p0" rel="nofollow noreferrer">this problem</a> from Google Code Jam:</p> <blockquote> <p>How many <code>mkdir</code> commands does it take to construct a given directory tree:</p> <h3>Input</h3> <p>The first line of the input gives the number of test cases, <strong>T</strong>. <strong>T</strong> test cases follow. Each case begins with a line containing two integers <strong>N</strong> and <strong>M</strong>, separated by a space.</p> <p>The next <strong>N</strong> lines each give the path of one directory that already exists on your computer. This list will include every directory already on your computer other than the root directory. (The root directory is on every computer, so there is no need to list it explicitly.)</p> <p>The next <strong>M</strong> lines each give the path of one directory that you want to create.</p> <p>Each of the paths in the input is formatted as in the problem statement above. Specifically, a path consists of one or more lower-case alpha-numeric strings (i.e., strings containing only the symbols 'a'-'z' and '0'-'9'), each preceded by a single forward slash. These alpha-numeric strings are never empty.</p> <h3>Output</h3> <p>For each test case, output one line containing &quot;Case #x: y&quot;, where x is the case number (starting from 1) and y is the number of <code>mkdir</code> you need.</p> </blockquote> <p>I've solved it by writing code shown below, and it works correctly, but how can I make it faster?</p> <pre><code>import sys def split_path(path_file,line_count_to_be_read): for i in range(line_count_to_be_read): # Get the Path line line = path_file.readline() # Skip the first slash line = line[1:] line = line.strip() splited = line.split('/') # make each subpaths from the source path for j in range(1,len(splited)+1): joined = &quot;/&quot;.join(splited[:j]) yield joined def main(): file_name = &quot;&quot; try: file_name = sys.argv[1] except IndexError: file_name = &quot;A-small-practice.in&quot; with open(file_name) as path_file: # skip the first line line = path_file.readline() total_testcases = int(line) # Number of Test Cases - Unused case_no = 0 while True: line = path_file.readline() if not line: break # Get Existing path and New path count existing_count,new_count = line.split() existing_count = int(existing_count) new_count = int(new_count) # Split Every Path and Make all Subpaths existing_paths = list(split_path(path_file,existing_count)) # Existing Subpaths new_paths = list(split_path(path_file,new_count)) # New Subpaths # Remove all paths that is in Existing list from the New list new_mkdir_set = set(new_paths) - set(existing_paths) case_no += 1 # length of new_set contains number of needed mkdir(s) print &quot;Case #{0}: {1}&quot;.format(case_no,len(new_mkdir_set)) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-14T10:46:28.507", "Id": "2236", "Score": "3", "body": "You should really comment your code. Now we will have to basically solve the problem for you before we even understand what your code does. That is a lot of work..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-15T02:53:55.303", "Id": "2252", "Score": "0", "body": "@Lennart Sorry, I should done it first. I hope these comments will help more." } ]
[ { "body": "<p>You can create a tree that you'd update on each iteration (while you calculate also the creation cost). You can do that with a simple nested dictionary. For example:</p>\n\n<pre><code>start with empty filesystem -&gt; fs = {}, cost 0\n\"/1/2/3\" -&gt; fs = {1: {2: 3: {}}}, cost 3\n\"/1/2/4\" -&gt; fs = {1: {2: 3: {}, 4: {}}}, cost 1\n\"/5\" -&gt; fs = {1: {2: 3: {}, 4: {}}, 5: {}}, cost 1\n\n= cost 5\n</code></pre>\n\n<p>You can use an algorithm with recursion (functional) or loops with inplace modifications (imperative). If you are learning I'd go for the first so you can apply some functional programming concepts (basically, one rule: don't update variables!).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-16T03:43:04.330", "Id": "2280", "Score": "0", "body": "Thanks. Is doing functional way increase speed ?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-16T09:38:21.643", "Id": "2283", "Score": "0", "body": "@gkr: probably not, but it will increase your programming skills :-p Seriously, functional programming is a whole new world (and you don't need to use Haskell to apply its principles), it's not about speed (or not only) but about writing clear, modular code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-15T20:26:34.507", "Id": "1297", "ParentId": "1283", "Score": "3" } } ]
{ "AcceptedAnswerId": "1284", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-14T05:43:46.670", "Id": "1283", "Score": "6", "Tags": [ "python", "performance", "programming-challenge", "tree", "file-system" ], "Title": "\"File Fix-it\" challenge" }
1283
<p>I have a section of code I use to extract an event log out of a large text file. It works well, it's just my use of <code>list(itertools.takewhile(...))</code> that feels a little sketchy to me.</p> <p>Is there a nicer way of doing this? </p> <pre><code>import itertools testdata = ''' Lots of other lines... Really quite a few. ************* * Event Log * ************* Col1 Col2 Col3 ----- ----- ----- 1 A B 2 A C 3 B D Other non-relevant stuff... ''' def extractEventLog(fh): fhlines = (x.strip() for x in fh) list(itertools.takewhile(lambda x: 'Event Log' not in x, fhlines)) list(itertools.takewhile(lambda x: '-----' not in x, fhlines)) lines = itertools.takewhile(len, fhlines) # Event log terminated by blank line for line in lines: yield line # In the real code, it's parseEventLogLine(line) </code></pre> <p>Expected output:</p> <pre><code>&gt;&gt;&gt; list(extractEventLog(testdata.splitlines())) ['1 A B', '2 A C', '3 B D'] </code></pre>
[]
[ { "body": "<p>Yes, it is indeed a bit sketchy/confusing to use <code>takewhile</code> when you really don't want to take the lines, but discard them. I think it's better to use <code>dropwhile</code> and then use its return value instead of discarding it. I believe that that captures the intent much more clearly:</p>\n\n<pre><code>def extractEventLog(fh):\n fhlines = (x.strip() for x in fh)\n lines = itertools.dropwhile(lambda x: 'Event Log' not in x, fhlines)\n lines = itertools.dropwhile(lambda x: '-----' not in x, lines)\n lines.next() # Drop the line with the dashes\n lines = itertools.takewhile(len, lines) # Event log terminated by blank line\n for line in lines:\n yield line # In the real code, it's parseEventLogLine(line)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-19T23:03:23.557", "Id": "2366", "Score": "0", "body": "Much nicer! My eyes must have glossed over `dropwhile`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-18T20:42:10.343", "Id": "1345", "ParentId": "1344", "Score": "6" } } ]
{ "AcceptedAnswerId": "1345", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-18T20:15:13.427", "Id": "1344", "Score": "3", "Tags": [ "python" ], "Title": "Extracting lines from a file, the smelly way" }
1344
<p>In Python, <code>itertools.combinations</code> yields combinations of elements in a sequence sorted by lexicographical order. In the course of solving certain math problems, I found it useful to write a function, <code>combinations_by_subset</code>, that yields these combinations sorted by subset order (for lack of a better name).</p> <p>For example, to list all 3-length combinations of the string 'abcde':</p> <pre><code>&gt;&gt;&gt; [''.join(c) for c in itertools.combinations('abcde', 3)] ['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde'] &gt;&gt;&gt; [''.join(c) for c in combinations_by_subset('abcde', 3)] ['abc', 'abd', 'acd', 'bcd', 'abe', 'ace', 'bce', 'ade', 'bde', 'cde'] </code></pre> <p>Formally, for a sequence of length \$n\$, we have \$\binom{n}{r}\$ combinations of length \$r\$, where \$\binom{n}{r} = \frac{n!}{r! (n - r)!}\$</p> <p>The function <code>combinations_by_subset</code> yields combinations in such an order that the first \$\binom{k}{r}\$ of them are the r-length combinations of the first k elements of the sequence.</p> <p>In our example above, the first \$\binom{3}{3} = 1\$ combination is the 3-length combination of 'abc' (which is just 'abc'); the first \$\binom{4}{3} = 4\$ combinations are the 3-length combinations of 'abcd' (which are 'abc', 'abd', 'acd', 'bcd'); etc.</p> <p>My first implementation is a simple generator function:</p> <pre><code>def combinations_by_subset(seq, r): if r: for i in xrange(r - 1, len(seq)): for cl in (list(c) for c in combinations_by_subset(seq[:i], r - 1)): cl.append(seq[i]) yield tuple(cl) else: yield tuple() </code></pre> <p>For fun, I decided to write a second implementation as a generator expression and came up with the following:</p> <pre><code>def combinations_by_subset(seq, r): return (tuple(itertools.chain(c, (seq[i], ))) for i in xrange(r - 1, len(seq)) for c in combinations_by_subset(seq[:i], r - 1)) if r else (() for i in xrange(1)) </code></pre> <p>My questions are:</p> <ol> <li>Which function definition is preferable? (I prefer the generator function over the generator expression because of legibility.)</li> <li>Are there any improvements one could make to the above algorithm/implementation?</li> <li>Can you suggest a better name for this function?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-10T22:24:12.120", "Id": "239403", "Score": "0", "body": "I think this ordering can be very useful and should be added to standard `itertools` library as an option." } ]
[ { "body": "<p>I should preface with the fact that I don't know python. It's likely that I've made a very clear error in my following edit. Generally though, I prefer your second function to your first. If python allows, I would break it up a bit for readability. Why do I like it? It doesn't need the <code>yield</code> keyword and it's less nested.</p>\n\n<pre><code># I like using verbs for functions, perhaps combine_by_subset()\n# or generate_subset_list() ?\ndef combinations_by_subset(seq, r):\n return (\n\n # I don't know what chain does - I'm making a wild guess that\n # the extra parentheses and comma are unnecessary\n # Could this be reduced to just itertools.chain(c, seq[i]) ?\n\n tuple(itertools.chain(c, (seq[i], )))\n for i in xrange(r - 1, len(seq))\n for c in combinations_by_subset(seq[:i], r - 1)\n\n ) if r\n\n else ( () for i in xrange(1) )\n</code></pre>\n\n<p>I'm just waiting for this answer to get flagged as not being helpful. Serves me right for putting my two cents in when I don't even know the language. ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-15T14:32:03.777", "Id": "133937", "Score": "0", "body": "I would say the yield method is preferable because without yield you probably need to build an array (or some other data structure) in memory containing the entire data set, which may take up a lot of memory, or require a considerable amount of CPU power/time to generate." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-24T10:14:33.340", "Id": "1425", "ParentId": "1419", "Score": "0" } }, { "body": "<p>Rather converting from tuple to list and back again, construct a new tuple by adding to it.</p>\n\n<pre><code>def combinations_by_subset(seq, r):\n if r:\n for i in xrange(r - 1, len(seq)):\n for cl in combinations_by_subset(seq[:i], r - 1):\n yield cl + (seq[i],)\n else:\n yield tuple()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-24T14:34:07.493", "Id": "1429", "ParentId": "1419", "Score": "7" } } ]
{ "AcceptedAnswerId": "1429", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-24T04:08:29.953", "Id": "1419", "Score": "5", "Tags": [ "python", "algorithm", "generator", "combinatorics" ], "Title": "Python generator function that yields combinations of elements in a sequence sorted by subset order" }
1419
<p>I'm cleaning build directories produced by GNOME build tool, <a href="http://live.gnome.org/Jhbuild" rel="nofollow">JHBuild</a>. This tool either downloads tarballs or clones git repositories, depending on set-up. After that, it proceeds to compilation (and then installation). Once in a while, something gets screwed up, and I need to clean the build directories so that I can start from scratch (because I don't know how to fix some of these problems).</p> <p>Here's how I did it, and I'd like you to tell me if it can be improved:</p> <pre><code>import os import subprocess top_level = os.path.expanduser("~/src/gnome") for filename in os.listdir(top_level): full_path = "{}/{}".format(top_level, filename) if os.path.isdir(full_path): cmd = "cd ~/src/gnome/{} &amp;&amp; git clean -dfx".format(filename) if subprocess.call(cmd, shell=True) != 0: cmd = "cd ~/src/gnome/{} &amp;&amp; make distclean".format(filename) if subprocess.call(cmd, shell=True) != 0: cmd = "cd ~/src/gnome/{} &amp;&amp; make clean".format(filename) subprocess.call(cmd, shell=True) </code></pre>
[]
[ { "body": "<pre><code>full_path = \"{}/{}\".format(top_level, filename)\n</code></pre>\n\n<p>You can use <code>os.path.join(top_level, filename)</code> for that. That way it will also work on any system which does not use <code>/</code> as a directory separator (that's not really a realistic concern in this case, but using <code>os.path.join</code> doesn't cost you anything and is a good practice to get used to).</p>\n\n<pre><code>cmd = \"cd ~/src/gnome/{} &amp;&amp; git clean -dfx\".format(filename)\n</code></pre>\n\n<p>First of all spelling out <code>~/src/gnome</code> again is bad practice. This way if you want to change it to a different directory you have to change it in all 4 places. You already have it in the <code>top_level</code> variable, so you should use that variable everywhere.</p>\n\n<p>On second thought you should actually not use <code>top_level</code> here, because what you're doing here is you're joining <code>top_level</code> and <code>filename</code>. However you already did that with <code>full_path</code>. So you should just use <code>full_path</code> here.</p>\n\n<p>You should also consider using <code>os.chdir</code> instead of <code>cd</code> in the shell. This way you only have to change the directory once per iteration instead of on every call. I.e. you can just do:</p>\n\n<pre><code>if os.path.isdir(full_path):\n os.chdir(full_path)\n if subprocess.call(\"git clean -dfx\", shell=True) != 0: \n if subprocess.call(\"make distclean\", shell=True) != 0:\n subprocess.call(\"make clean\", shell=True)\n</code></pre>\n\n<p>(Note that since <code>full_path</code> is an absolute path, it doesn't matter that you don't <code>chdir</code> back at the end of each iteration.)</p>\n\n<p>Another good habit to get into is to not use <code>shell=True</code>, but instead pass in a list with command and the arguments, e.g. <code>subprocess.call([\"make\", \"clean\"])</code>. It doesn't make a difference in this case, but in cases where your parameters may contain spaces, it saves you the trouble of escaping them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-26T18:03:46.160", "Id": "2555", "Score": "0", "body": "Regarding your very last comment, I'm tempted to change the subprocess to something like `subprocess.call(\"git clean -dfx\".split())`. Is that kool?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-26T18:09:31.317", "Id": "2556", "Score": "0", "body": "@Tshepang: The point of passing in an array instead of `shell=True` is that it will handle arguments with spaces or shell-metacharacters automatically correctly without you having to worry about. Using `split` circumvents this again (as far as spaces are concerned anyway), so there's little point in that. Since in this case you know that your arguments don't contain any funny characters, you can just keep using `shell=True` if you don't want to pass in a spelled-out array." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-26T18:16:40.643", "Id": "2557", "Score": "0", "body": "In such cases, won't [shlex.split()](http:///doc.python.org/library/shlex.html#shlex.split) be useful?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-26T18:31:29.073", "Id": "2558", "Score": "1", "body": "@Tshepang: I don't see how. If you already know the arguments, `subprocess.call(shlex.split('some_command \"some filename\"'))` buys you nothing over `subprocess.call([\"some_command\", \"some filename\"]` and IMHO has a higher chance that you might forget the quotes. However if the filename is inside a variable, `subprocess.call([\"some_comand\", filename])` still works no matter which special characters `filename` contains, while using `shlex.split` would require you to somehow escape the contents of `filename` first, in which case you could have just used `shell=True` in the first place." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-26T16:56:14.767", "Id": "1477", "ParentId": "1476", "Score": "3" } } ]
{ "AcceptedAnswerId": "1477", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-26T16:33:28.870", "Id": "1476", "Score": "3", "Tags": [ "python", "git", "make" ], "Title": "Cleaning multiple build directories" }
1476
<p>I have the following code for reading <a href="http://htk.eng.cam.ac.uk/" rel="nofollow">HTK</a> feature files. The code below is working completely correct (verified it with unit tests and the output of the original HTK toolkit).</p> <pre><code>from HTK_model import FLOAT_TYPE from numpy import array from struct import unpack def feature_reader(file_name): with open(file_name, 'rb') as in_f: #There are four standard headers. Sample period is not used num_samples = unpack('&gt;i', in_f.read(4))[0] sample_period = unpack('&gt;i', in_f.read(4))[0] sample_size = unpack('&gt;h', in_f.read(2))[0] param_kind = unpack('&gt;h', in_f.read(2))[0] compressed = bool(param_kind &amp; 02000) #If compression is used, two matrices are defined. In that case the values are shorts, and the real values are: # (x+B)/A A = B = 0 if compressed: A = array([unpack('&gt;f',in_f.read(4))[0] for _ in xrange(sample_size/2)], dtype=FLOAT_TYPE) B = array([unpack('&gt;f',in_f.read(4))[0] for _ in xrange(sample_size/2)], dtype=FLOAT_TYPE) #The first 4 samples were the matrices num_samples -= 4 for _ in xrange(0,num_samples): if compressed: yield ((array( unpack('&gt;' + ('h' * (sample_size//2)),in_f.read(sample_size)) ,dtype=FLOAT_TYPE) + B) / A) else: yield (array( unpack('&gt;' + ('f' * (sample_size//4)),in_f.read(sample_size)), dtype=FLOAT_TYPE)) </code></pre> <p>How can I speed up this code, are there things I should improve in the code?</p>
[]
[ { "body": "<pre><code> data = in_f.read(12)\n num_samples, sample_period, sample_size, param_kind = unpack('&gt;iihh', data)\n A = B = 0\n if compressed:\n A = array('f')\n A.fromfile(in_f, sample_size/2)\n B = array('f')\n B.fromfile(in_f, sample_size/2)\n #The first 4 samples were the matrices\n num_samples -= 4\n</code></pre>\n\n<p>And so on</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-28T12:27:11.493", "Id": "1500", "ParentId": "1496", "Score": "3" } } ]
{ "AcceptedAnswerId": "1500", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-28T07:57:03.323", "Id": "1496", "Score": "5", "Tags": [ "python", "performance", "file", "numpy", "serialization" ], "Title": "Reading a binary file containing periodic samples" }
1496
<p>I want to use Tweets sent out by a twitter account as a command to shut down Ubuntu. For this, I've written a Python script using <a href="https://github.com/joshthecoder/tweepy" rel="nofollow">tweepy</a>, a Python library for Twitter. I scheduled the script to run half past the hour every hour (for eg at 5:30, 6:30, and so on) using <code>crontab</code>. </p> <p>Here's the script:</p> <pre><code>import tweepy import os from datetime import datetime p=None api= tweepy.API() for status in api.user_timeline('tweetneag4'): while p==None: #so that it checks only the first tweet if status.text.count(str((datetime.now().hour)+1))&lt; 2 and str((datetime.time.now().hour)+1)==10: p=1 pass elif str((datetime.now().hour)+1) in status.text: print "System shut down in 20 mins." os.system('shutdown -h +20') p=1 </code></pre> <p>Here is a sample tweet:</p> <pre><code>#loadshedding schedule in 10mins: 15:00-21:00 #group4 #nea </code></pre> <p>The twitter account (<a href="http://twitter.com/#!/search/tweetneag4" rel="nofollow">@tweetneag4</a>) tweets an alert 30 mins and 10 mins before the power outage begins (here, the account tweets if and only if there's a power outage next hour). What I've tried to do is check at 5:30 whether it posts a tweet regarding 6 o'clock. I've done this by seeing if the tweet contains the string "6"(when checking at 5). When checking for ten o'clock, an additional complication arises because it may contain "10" in two scenarios- first as in 10 o'clock and second as in 10mins later. (I'm sure there's a better way of doing this)</p> <p>If you see the twitter feed, things should be clearer. How could I improve so that the code become more elegant?</p>
[]
[ { "body": "<pre><code>import tweepy\nimport os\nfrom datetime import datetime\np=None\n</code></pre>\n\n<p>Use of single letter variable names is confusing, I have no idea what p is for.</p>\n\n<pre><code>api= tweepy.API()\n</code></pre>\n\n<p>Put spaces around your =</p>\n\n<pre><code>for status in api.user_timeline('tweetneag4'): \n while p==None: #so that it checks only the first tweet\n</code></pre>\n\n<p>What are you thinking here? If p doesn't get set to a true value, you'll loop over the next block repeatedly in an infinite loop. If you only want the first tweet pass count = 1 to user_timeline</p>\n\n<pre><code> if status.text.count(str((datetime.now().hour)+1))&lt; 2 and str((datetime.time.now().hour)+1)==10:\n\n p=1\n</code></pre>\n\n<p>Setting flags is ugly. If you must set boolean flags use True and False not None and 1.</p>\n\n<pre><code> pass\n elif str((datetime.now().hour)+1) in status.text:\n print \"System shut down in 20 mins.\"\n os.system('shutdown -h +20') \n p=1 \n</code></pre>\n\n<p>It seems to me that a much more straightforward way of doing this is to look at the time at which the status was posted. It seems to be available as status.created_at. Based on that you know that outage is either 30 or 10 minutes after that. So if it has been more then 30 minutes since that message, it must have already happened and we aren't concerned.</p>\n\n<p>Something like this:</p>\n\n<pre><code>import tweepy\nimport os\nfrom datetime import datetime, timedelta\n\napi= tweepy.API()\n\nstatus = api.user_timeline('tweetneag4', count=1)[0]\nage = datetime.now() - status.created_at\nif age &lt; timedelta(minutes = 45):\n print \"System shut down in 20 mins.\"\n os.system('shutdown -h +20') \n</code></pre>\n\n<p>NOTE: I get negative ages when I run this, I'm assuming that's time zones. Its also possible my logic is screwy.</p>\n\n<p>If you really do need to get the actual time from the text, your current strategy of searching for numbers in the text is fragile. Instead you could do something like this:</p>\n\n<pre><code># split the message up by whitespace, this makes it easy to grab the outage time\noutage_time = status.split()[4]\n# find everything up to the colon\nhour_text, junk = outage_time.split(':')\n# parse the actual hour\nhour = int(hour_text)\n</code></pre>\n\n<p>Finally, for more complex examples using regular expressions to parse the text would be a good idea. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T04:11:27.950", "Id": "2675", "Score": "0", "body": "@Winston- Thanks for the critique. I'll try to improve some of my programming habits!! I was really searching for something like `status.created_at` and I'll definitely try out your solution- the logic is much neater." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-29T22:51:04.233", "Id": "1531", "ParentId": "1525", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-29T17:24:54.500", "Id": "1525", "Score": "5", "Tags": [ "python", "datetime", "linux", "twitter" ], "Title": "Using tweet as command to shut down Ubuntu" }
1525
<p>The following code generates all \$k\$-subsets of a given array. A \$k\$-subset of set \$X\$ is a partition of all the elements in \$X\$ into \$k\$ non-empty subsets.</p> <p>Thus, for <code>{1,2,3,4}</code> a 3-subset is <code>{{1,2},{3},{4}}</code>.</p> <p>I'm looking for improvements to the algorithm or code. Specifically, is there a better way than using <code>copy.deepcopy</code>? Is there some <code>itertools</code> magic that does this already?</p> <pre><code>import copy arr = [1,2,3,4] def t(k,accum,index): print accum,k if index == len(arr): if(k==0): return accum; else: return []; element = arr[index]; result = [] for set_i in range(len(accum)): if k&gt;0: clone_new = copy.deepcopy(accum); clone_new[set_i].append([element]); result.extend( t(k-1,clone_new,index+1) ); for elem_i in range(len(accum[set_i])): clone_new = copy.deepcopy(accum); clone_new[set_i][elem_i].append(element) result.extend( t(k,clone_new,index+1) ); return result print t(3,[[]],0); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-02T11:48:53.323", "Id": "154375", "Score": "0", "body": "See also: [Iterator over all partitions into k groups?](http://stackoverflow.com/q/18353280/562769)" } ]
[ { "body": "<p>Here's the obligatory recursive version:</p>\n\n<pre><code>def k_subset(s, k):\n if k == len(s):\n return (tuple([(x,) for x in s]),)\n k_subs = []\n for i in range(len(s)):\n partials = k_subset(s[:i] + s[i + 1:], k)\n for partial in partials:\n for p in range(len(partial)):\n k_subs.append(partial[:p] + (partial[p] + (s[i],),) + partial[p + 1:])\n return k_subs\n</code></pre>\n\n<p>This returns a bunch of duplicates which can be removed using</p>\n\n<pre><code>def uniq_subsets(s):\n u = set()\n for x in s:\n t = []\n for y in x:\n y = list(y)\n y.sort()\n t.append(tuple(y))\n t.sort()\n u.add(tuple(t))\n return u\n</code></pre>\n\n<p>So the final product can be had with</p>\n\n<pre><code>print uniq_subsets(k_subset([1, 2, 3, 4], 3))\n\nset([\n ((1,), (2,), (3, 4)), \n ((1,), (2, 4), (3,)), \n ((1, 3), (2,), (4,)), \n ((1, 4), (2,), (3,)), \n ((1,), (2, 3), (4,)), \n ((1, 2), (3,), (4,))\n])\n</code></pre>\n\n<p>Wow, that's pretty bad and quite unpythonic. :(</p>\n\n<p>Edit: Yes, I realize that reimplementing the problem doesn't help with reviewing the original solution. I was hoping to gain some insight on your solution by doing so. If it's utterly unhelpful, downvote and I'll remove the answer.</p>\n\n<p>Edit 2: I removed the unnecessary second recursive call. It's shorter but still not very elegant.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T07:26:50.793", "Id": "1542", "ParentId": "1526", "Score": "4" } }, { "body": "<p>Couldn't find any super quick wins in itertools.</p>\n\n<p>(Maybe I didn't look hard enough.)\nI did however come up with this,\nit runs pretty slow, but is fairly concise:</p>\n\n<pre><code>from itertools import chain, combinations\n\ndef subsets(arr):\n \"\"\" Note this only returns non empty subsets of arr\"\"\"\n return chain(*[combinations(arr,i + 1) for i,a in enumerate(arr)])\n\ndef k_subset(arr, k):\n s_arr = sorted(arr)\n return set([frozenset(i) for i in combinations(subsets(arr),k) \n if sorted(chain(*i)) == s_arr])\n\n\nprint k_subset([1,2,3,4],3)\n</code></pre>\n\n<p>Some minor wins for speed but less concise, would be to only do the set//frozenset buisness at the end if there are non unique elements in the array, or use a custom flatten function or sum(a_list, []) rather than chain(*a_list).</p>\n\n<p>If you are desperate for speed you might want have a think about another language or maybe:\nwww.cython.org is pretty neat.\nObviously the above algorithms are much better speed-wise for starters.</p>\n\n<p>Also what might be worht a look into is www.sagemath.org...\nIt's an mathematical environment built atop of python, and for example functions like, subsets() , flatten etc and lots of combinatorial things live there.</p>\n\n<p>Cheers,</p>\n\n<p>Matt</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T18:23:01.797", "Id": "1865", "ParentId": "1526", "Score": "3" } }, { "body": "<p>Based on an answer in an all partitions question (<a href=\"https://stackoverflow.com/questions/19368375/set-partitions-in-python/61141601\">https://stackoverflow.com/questions/19368375/set-partitions-in-python/61141601</a>): This can be done with simple recursion, no need for itertools, no need for a complicated algorithm. I am surprised this was not suggested. It should be just as efficient as Knuth's algorithm as well as it goes through every combination only once.</p>\n\n<pre><code>def subsets_k(collection, k): yield from partition_k(collection, k, k)\ndef partition_k(collection, min, k):\n if len(collection) == 1:\n yield [ collection ]\n return\n\n first = collection[0]\n for smaller in partition_k(collection[1:], min - 1, k):\n if len(smaller) &gt; k: continue\n # insert `first` in each of the subpartition's subsets\n if len(smaller) &gt;= min:\n for n, subset in enumerate(smaller):\n yield smaller[:n] + [[ first ] + subset] + smaller[n+1:]\n # put `first` in its own subset \n if len(smaller) &lt; k: yield [ [ first ] ] + smaller\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>something = list(range(1,5))\nfor n, p in enumerate(subsets_k(something, 1), 1):\n print(n, sorted(p))\nfor n, p in enumerate(subsets_k(something, 2), 1):\n print(n, sorted(p))\nfor n, p in enumerate(subsets_k(something, 3), 1):\n print(n, sorted(p)) \nfor n, p in enumerate(subsets_k(something, 4), 1):\n print(n, sorted(p))\n</code></pre>\n\n<p>Yields correctly:</p>\n\n<pre><code>1 [[1, 2, 3, 4]]\n\n1 [[1], [2, 3, 4]]\n2 [[1, 2], [3, 4]]\n3 [[1, 3, 4], [2]]\n4 [[1, 2, 3], [4]]\n5 [[1, 4], [2, 3]]\n6 [[1, 3], [2, 4]]\n7 [[1, 2, 4], [3]]\n\n1 [[1], [2], [3, 4]]\n2 [[1], [2, 3], [4]]\n3 [[1], [2, 4], [3]]\n4 [[1, 2], [3], [4]]\n5 [[1, 3], [2], [4]]\n6 [[1, 4], [2], [3]]\n\n1 [[1], [2], [3], [4]]\n</code></pre>\n\n<p>Compared to the Knuth implementation above (modified for Python3 - <code>xrange</code> changed to <code>range</code>):</p>\n\n<pre><code>if __name__ == '__main__':\n import timeit\n print(timeit.timeit(\"for _ in subsets_k([1, 2, 3, 4, 5], 3): pass\", globals=globals()))\n print(timeit.timeit(\"for _ in algorithm_u([1, 2, 3, 4, 5], 3): pass\", globals=globals()))\n</code></pre>\n\n<p>Results in more than twice as fast code:</p>\n\n<pre><code>20.724652599994442\n41.03094519999286\n</code></pre>\n\n<p>Sometimes a simple approach is the best one. It would be interesting to know if optimizations can be applied to Knuth variation to fix this, or if this simple algorithm is the best one.</p>\n\n<p>Update: the Knuth timing information above is both wrong and misleading!!!</p>\n\n<p>The <code>t</code> implementation compiles a whole list and does not return a generator. Whereas the Knuth version has a generator. To make a fair test comparison, one must enumerate all the elements otherwise the Knuth implementation is just running to the first <code>yield</code> returning the generator and timing this... <code>for _ in generator: pass</code> would have been sufficient to have a real test comparison.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:48:48.547", "Id": "240277", "ParentId": "1526", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-29T17:44:53.210", "Id": "1526", "Score": "20", "Tags": [ "python", "algorithm", "combinatorics" ], "Title": "Finding all k-subset partitions" }
1526
<p>I had a job to remove all kinds of comments from the Lua file. I tried to find a usable Python script to this on the net, but Google did not help. </p> <p>Therefore, I made one. This script recognizes all types of comments such as single and multi-Line comments.</p> <p>I would welcome your opinion.</p> <pre><code># written in Python 3.2 import codecs import re inputFilePath = 'testfile.lua' inputLuaFile = codecs.open( inputFilePath, 'r', encoding = 'utf-8-sig' ) inputLuaFileDataList = inputLuaFile.read().split( "\r\n" ) inputLuaFile.close() outputFilePath = 'testfile_out.lua' outputLuaFile = codecs.open( outputFilePath, 'w', encoding = 'utf-8' ) outputLuaFile.write( codecs.BOM_UTF8.decode( "utf-8" ) ) def create_compile( patterns ): compStr = '|'.join( '(?P&lt;%s&gt;%s)' % pair for pair in patterns ) regexp = re.compile( compStr ) return regexp comRegexpPatt = [( "oneLineS", r"--[^\[\]]*?$" ), ( "oneLine", r"--(?!(-|\[|\]))[^\[\]]*?$" ), ( "oneLineBlock", r"(?&lt;!-)(--\[\[.*?\]\])" ), ( "blockS", r"(?&lt;!-)--(?=(\[\[)).*?$" ), ( "blockE", r".*?\]\]" ), ( "offBlockS", r"---+\[\[.*?$" ), ( "offBlockE", r".*?--\]\]" ), ] comRegexp = create_compile( comRegexpPatt ) comBlockState = False for i in inputLuaFileDataList: res = comRegexp.search( i ) if res: typ = res.lastgroup if comBlockState: if typ == "blockE": comBlockState = False i = res.re.sub( "", i ) else: i = "" else: if typ == "blockS": comBlockState = True i = res.re.sub( "", i ) else: comBlockState = False i = res.re.sub( "", i ) elif comBlockState: i = "" if not i == "": outputLuaFile.write( "{}\n".format( i ) ) </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:46:27.847", "Id": "2861", "Score": "0", "body": "Link to a site with comment examples is missing." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:46:58.877", "Id": "2862", "Score": "1", "body": "Any reason why you have to do this in Python? There are several Lua parsers in Lua." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:48:56.643", "Id": "2863", "Score": "1", "body": "Closing Lua comment symbol does not have to have `--` attached. `--[[ ]]` is perfectly valid" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:51:14.907", "Id": "2864", "Score": "0", "body": "Maybe I missed it, but I think that you do not support for `--[=[ ]=]` \"long bracket\" comments, which may contain any number of `=` as long as they are balanced. See manual: http://www.lua.org/manual/5.1/manual.html#2.1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-01T11:47:55.020", "Id": "4285", "Score": "0", "body": "I agree with Winston, using regexes for parsing a non-trivial programming language is prone to fail, unless using it on a very strict set of files of regular syntax (proprietary code)... At the very least, context is missing, nested comments aren't handled, you don't seem to match comments like -- [huhu] and so on." } ]
[ { "body": "<p>Firstly, I think you have some subtle bugs. </p>\n\n<ul>\n<li>What if -- appears inside a string?\nIn that case it should not be a\ncomment.</li>\n<li>What if someone ends a block and starts another one on the same line: --]] --[[</li>\n<li>You split on '\\r\\n', if you run this on a linux system you won't have those line seperators</li>\n</ul>\n\n<p>Secondly, some your variable names could use help. </p>\n\n<ul>\n<li>The python style guide recommonds\nunderscore_style not camelCase for\nlocal variable names.</li>\n<li>You use some abbreviations in your names, I don't think that's a good idea. e.g. res or comRegexPatt</li>\n<li>You have an i, the name of which gives very little hint what it is doing</li>\n</ul>\n\n<p>Your regular expressions look convoluted. I think this a symptom of the fact that the problem is not best solved by a regular expression. This will be even more so if you fix the string problem. </p>\n\n<p>The way I'd solve this problem: I'd write a class CodeText which holds the actual code in question and then write code like this:</p>\n\n<pre><code>def handle_code(code_text):\n while code_text.text_remaining:\n if code_text.matches('--'):\n handle_comment(code_text)\n elif code_text.matches('\"'):\n handle_string(code_text)\n else:\n code_text.accept()\n\ndef handle_string(code_text):\n while not code_text.matches('\"'):\n code_text.accept()\n\ndef handle_comment(code_text):\n if code_text.matches('[['):\n handle_block_comment(code_text)\n else:\n while not code_text.matches('\\n'):\n code_text.reject()\n\n def handle_comment_block(code_text):\n while not code_text.match(\"--]]\"):\n code_text.reject() \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T14:02:43.780", "Id": "1606", "ParentId": "1601", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T09:43:43.037", "Id": "1601", "Score": "4", "Tags": [ "python" ], "Title": "Lua comment remover" }
1601
<p>I'm changing code that writes data to a DB, so I have a dump (a text file) of an earlier run to compare against, to ensure that my changes don't screw things up. Here goes:</p> <pre><code>def dbcheck(cursor): dbresult = list() cursor.execute("SELECT COLUMN FROM TABLE") for item in cursor.fetchall(): line = item[0] + "\n" dbresult.append(line) with open(dbdump) as f: for n, line in enumerate(f): if line != dbresult[n]: print("DB content does not match original data!") </code></pre> <p>This code runs fine, but I'm worried that <code>dbresult</code> can grow really large, so am looking for a less risky way of doing this. I'm also curious of what else can be improved.</p> <p>[<strong>sidenote</strong>] I left out exception handling for the sake of simplicity/clarity.</p>
[]
[ { "body": "<p>Use zip to iterate over both iterators at the same time. It'll only use the memory needed to hold a single entry from each at a time.</p>\n\n<pre><code>def dbcheck(cursor):\n cursor.execute(\"SELECT COLUMN FROM TABLE\")\n with open(dbdump) as f:\n for item, line in zip(cursor, f):\n if line != item[0] + '\\n':\n print(\"DB content does not match original data!\")\n</code></pre>\n\n<p>If using python 2.x use <code>itertools.izip</code> instead of <code>zip</code>. zip puts everything in a huge list which won't be very efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T23:34:58.390", "Id": "2921", "Score": "0", "body": "Looks more elegant, however wasn't there talk about stuff like zip and lambda not being very Pythonic?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T23:36:51.667", "Id": "2922", "Score": "0", "body": "Aren't you missing `cursor.fetchall()`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T00:31:21.957", "Id": "2923", "Score": "0", "body": "@Tshepange, fetchall() returns the entire result of the query as a list. But you can also iterate over the cursor directly to get the results. Since you want to iterate over all the rows in the table, this is what you want." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T00:37:57.923", "Id": "2924", "Score": "0", "body": "I've never heard zip accused of not being pythonic, lambda and reduce, yes. But zip belongs with enumerate, itertools and all that perfectly pythonic stuff." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T00:42:53.830", "Id": "2925", "Score": "1", "body": "And to be clear, it is not as though certain features of python are unpythonic and should be avoided. The goal of pythonicity is readable code. Some features tend to produce unreadable code and thus get a bad rap." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T07:21:13.493", "Id": "2926", "Score": "0", "body": "\"It'll only use the memory needed to hold a single entry from each at a time.\" - Under Python 3, yes, under Python 2 it will return one megalist." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T12:16:06.350", "Id": "2931", "Score": "0", "body": "@Lennart, yes I'll add that to the answer" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T22:39:42.003", "Id": "1671", "ParentId": "1669", "Score": "4" } }, { "body": "<p>This should do it:</p>\n\n<pre><code>def dbcheck(cursor):\n cursor.execute(\"SELECT COLUMN FROM TABLE\")\n with open(dbdump) as f:\n for item in cursor:\n if f.readline() != item + '\\n'\n print(\"DB content does not match original data!\")\n</code></pre>\n\n<p>No need to read either the whole column nor the whole file before iterating.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T07:15:26.573", "Id": "1674", "ParentId": "1669", "Score": "5" } }, { "body": "<p>You can use itertools.izip to avoid reading all of both sets of data before iterating. Also, this version breaks immediately on finding a problem:</p>\n\n<pre><code>import itertools as it\ndef dbcheck(cursor):\n with open(dbdump) as f:\n cursor.execute(\"SELECT COLUMN FROM TABLE\")\n for fline, dbrec in it.izip(f, cursor):\n if fline.strip() != dbrec[0]:\n print(\"DB content does not match original data!\")\n break\n</code></pre>\n\n<p>Here is a version that reports the line number of the file, along with the mismatched data, and continues for all lines in the file. Also note that it's not calling print as a function, but rather using parenthesis to group the expression creating the string to print (in Python 3.x it is calling print as a function):</p>\n\n<pre><code>import itertools as it\ndef dbcheck(cursor):\n with open(dbdump) as f:\n cursor.execute(\"SELECT COLUMN FROM TABLE\")\n for lineno, fline, dbrec in it.izip(it.count(), f, cursor):\n if fline.strip() != dbrec[0]:\n print(\"Line %d: File: %s, DB: %s\" % \n (lineno, \n fline.strip(), \n dbrec[0].strip()))\n</code></pre>\n\n<p>Also, in Python 3, the \"zip\" function is the same as itertools.zip, I think.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:01:25.893", "Id": "2947", "Score": "1", "body": "2 issues: the very last line, why strip `brec`, and why call it `brec` :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:06:10.757", "Id": "2948", "Score": "1", "body": "Why introduce a variable, `res`? Can't we just play with `cursor`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:42:32.553", "Id": "2949", "Score": "0", "body": "@Tshepang, thanks for the catch. brec in the second example should have been dbrec. I've edited the example to use the correct name." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:44:09.073", "Id": "2950", "Score": "1", "body": "@Tshepang, I'm stripping both the line entry and the database value assuming: 1. whitespace on the ends isn't important, and 2. there will be additional whitespace on both the file line and the database record. The file line will have the end-of-line characters, and the database record may have padding, since some drivers pad the values to the full column width." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:45:46.073", "Id": "2951", "Score": "0", "body": "@Tshepang, I use \"res\" as the resultset from the cursor only because it's more difficult to format the \"for\" construct with the execute() inline. It could be done, of course, but at some point naming a subexpression is as clear as anonymous composition." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T09:57:56.573", "Id": "2965", "Score": "1", "body": "@TheUNIXMan: I don't understand what you say, but can't you do `it.izip(it.count(), f, cursor)` instead of introducing res?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T18:14:20.247", "Id": "3138", "Score": "0", "body": "It depends on what \"cursor\" is, I guess. If it's a result from a query, you can do that. If it's a database connection, you'll have to execute the query on it, giving you a result that you can then iterate over." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T20:42:34.760", "Id": "3148", "Score": "1", "body": "Which DB driver allows you to run execute using a Connection object?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T20:53:18.770", "Id": "3149", "Score": "1", "body": "Well, now that's an interesting question... Apparently I'm not sure. I suppose you do need a cursor if I'm reading the DB API (http://www.python.org/dev/peps/pep-0249/) right. I've been using SQL Alchemy (http://www.sqlalchemy.org/) more lately which has different semantics. So iterating over a cursor is perfectly fine with the DB API. I'll update the example there." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-06T21:54:55.243", "Id": "1689", "ParentId": "1669", "Score": "1" } } ]
{ "AcceptedAnswerId": "1674", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T22:02:19.110", "Id": "1669", "Score": "5", "Tags": [ "python" ], "Title": "Reducing memory usage when comparing two iterables" }
1669
<p>Because I don't like using <code>\</code> to break long lines (to comply with PEP8), I tend to do something like this:</p> <pre><code>message = "There are {} seconds in {} hours." message = message.format(nhours*3600, nhours) print(message) </code></pre> <p>It also makes code cleaner. Is this an okay way of doing things?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:33:42.040", "Id": "2989", "Score": "1", "body": "Not really a Code Review, I feel this is more appropriate at [Programmers.SE](http://programmers.stackexchange.com/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T02:35:35.867", "Id": "3000", "Score": "4", "body": "I think this is perfectly *on-topic* here." } ]
[ { "body": "<p>Nothing necessarily wrong with doing that - I use that for situations that the message would be used more than once. However, for one-shot, multiline messages I'd do:</p>\n\n<pre><code>message = \"There are %d seconds \" % nhours*3600\nmessage += \"in %d hours.\" % nhours\nprint message\n</code></pre>\n\n<p>Honestly, the only difference is stylistic. I prefer this method because it places the variables directly within the string, which I feel is more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T17:33:41.293", "Id": "2985", "Score": "0", "body": "What does `it places the variables directly within the string` mean?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T17:40:35.867", "Id": "2986", "Score": "0", "body": "Maybe a bad wording there. I mean that since the variable is assigned in the same line as the string, it's a bit clearer what goes where. In fact, I'd prefer `msg = \"There are \" + nhours*3600 + \" seconds in \" + nhours + \" hours.\"` but I'm not certain whether you can do that in Python." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T17:43:34.833", "Id": "2987", "Score": "0", "body": "That's a lot uglier I think, but yeah you can do that. You just need to convert your integers to string: `msg = \"There are \" + str(nhours*3600) + \" seconds in \" + str(nhours) + \" hours.\"`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:01:43.387", "Id": "2988", "Score": "0", "body": "Like I said, matter of personal style :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:40:35.857", "Id": "2990", "Score": "0", "body": "You do lose reuseability which is important to note (without putting this code in a function). Ofcourse this isn't relevant if you only format once." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:52:14.340", "Id": "2993", "Score": "0", "body": "@StevenJeuris: What reusability do you lose?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:55:55.517", "Id": "2994", "Score": "0", "body": "@Tshepang: Both of our formats only allow for one use: Yours because the format overwrites the template, and mine because the message is constructed in situ." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T19:04:45.223", "Id": "2995", "Score": "0", "body": "@Michael: I'm referring to the possible reuse if you wouldn't overwrite. :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T16:50:36.230", "Id": "1717", "ParentId": "1716", "Score": "-2" } } ]
{ "AcceptedAnswerId": "1719", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T16:20:41.737", "Id": "1716", "Score": "6", "Tags": [ "python" ], "Title": "Is it okay to 'abuse' re-assignment?" }
1716
<p>UPDATE: I didn't write the library pasted below I just make use of it. I'm unable to paste the <a href="https://github.com/ocanbascil/Performance-AppEngine/blob/master/PerformanceEngine/__init__.py" rel="nofollow">part I wrote</a> here because the message exceeds 30k characters when I try to do so. </p> <p>I have been working on my <a href="http://tweethit.com" rel="nofollow">webapp</a> and this a simple came into life as I needed to scratch my own itch. It basically enables you to store models and query results into datastore, memcache or local instance storage using a basic API. </p> <p>I haven't published any open source work before, but as this thing helped me keep the lines of code and CPU usage low, I thought it would help others too. </p> <p>How can I make it any better? I'm planning to write unit tests, but I'm not experienced with it, so any suggestions on which libraries to use etc. is welcome.</p> <pre><code>""" Author: Juan Pablo Guereca Module which implements a per GAE instance data cache, similar to what you can achieve with APC in PHP instances. Each GAE instance caches the global scope, keeping the state of every variable on the global scope. You can go farther and cache other things, creating a caching layer for each GAE instance, and it's really fast because there is no network transfer like in memcache. Moreover GAE doesn't charge for using it and it can save you many memcache and db requests. Not everything are upsides. You can not use it on every case because: - There's no way to know if you have set or deleted a key in all the GAE instances that your app is using. Everything you do with Cachepy happens in the instance of the current request and you have N instances, be aware of that. - The only way to be sure you have flushed all the GAE instances caches is doing a code upload, no code change required. - The memory available depends on each GAE instance and your app. I've been able to set a 60 millions characters string which is like 57 MB at least. You can cache somethings but not everything. """ import time import logging import os CACHE = {} STATS_HITS = 0 STATS_MISSES = 0 STATS_KEYS_COUNT = 0 """ Flag to deactivate it on local environment. """ ACTIVE = True#False if os.environ.get('SERVER_SOFTWARE').startswith('Devel') else True """ None means forever. Value in seconds. """ DEFAULT_CACHING_TIME = None URL_KEY = 'URL_%s' """ Curious thing: A dictionary in the global scope can be referenced and changed inside a function without using the global statement, but it can not be redefined. """ def get( key ): """ Gets the data associated to the key or a None """ if ACTIVE is False: return None global CACHE, STATS_MISSES, STATS_HITS """ Return a key stored in the python instance cache or a None if it has expired or it doesn't exist """ if key not in CACHE: STATS_MISSES += 1 return None value, expiry = CACHE[key] current_timestamp = time.time() if expiry == None or current_timestamp &lt; expiry: STATS_HITS += 1 return value else: STATS_MISSES += 1 delete( key ) return None def set( key, value, expiry = DEFAULT_CACHING_TIME ): """ Sets a key in the current instance key, value, expiry seconds till it expires """ if ACTIVE is False: return None global CACHE, STATS_KEYS_COUNT if key not in CACHE: STATS_KEYS_COUNT += 1 if expiry != None: expiry = time.time() + int( expiry ) try: CACHE[key] = ( value, expiry ) except MemoryError: """ It doesn't seems to catch the exception, something in the GAE's python runtime probably """ logging.info( "%s memory error setting key '%s'" % ( __name__, key ) ) def delete( key ): """ Deletes the key stored in the cache of the current instance, not all the instances. There's no reason to use it except for debugging when developing, use expiry when setting a value instead. """ global CACHE, STATS_KEYS_COUNT if key in CACHE: STATS_KEYS_COUNT -= 1 del CACHE[key] def dump(): """ Returns the cache dictionary with all the data of the current instance, not all the instances. There's no reason to use it except for debugging when developing. """ global CACHE return CACHE def flush(): """ Resets the cache of the current instance, not all the instances. There's no reason to use it except for debugging when developing. """ global CACHE, STATS_KEYS_COUNT CACHE = {} STATS_KEYS_COUNT = 0 def stats(): """ Return the hits and misses stats, the number of keys and the cache memory address of the current instance, not all the instances.""" global CACHE, STATS_MISSES, STATS_HITS, STATS_KEYS_COUNT memory_address = "0x" + str("%X" % id( CACHE )).zfill(16) return {'cache_memory_address': memory_address, 'hits': STATS_HITS, 'misses': STATS_MISSES , 'keys_count': STATS_KEYS_COUNT, } def cacheit( keyformat, expiry=DEFAULT_CACHING_TIME ): """ Decorator to memoize functions in the current instance cache, not all the instances. """ def decorator( fxn ): def wrapper( *args, **kwargs ): key = keyformat % args[:keyformat.count('%')] data = get( key ) if data is None: data = fxn( *args, **kwargs ) set( key, data, expiry ) return data return wrapper return decorator </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T21:57:20.317", "Id": "3118", "Score": "5", "body": "Welcome to code review! If you read the FAQ you'll learn that any code that you want reviewed should really be pasted into your question. Its also geared towards smaller pieces of code (classes/functions) rather then even a small library like yours. You'll probably have better success if you show specific pieces of code you want feedback on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T13:10:57.533", "Id": "3130", "Score": "0", "body": "On a side note, I like the app --- I got distracted from looking at its technical merits by my interest in the content!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T12:35:34.007", "Id": "3157", "Score": "0", "body": "Thanks for your interest, I'm not the author of cachepy but I guess I may have to rewrite it based on your suggestions. Also I refrained from pasting the whole library code here as it is about 1000 loc (400 loc comments), to keep the question less intimidating." } ]
[ { "body": "<pre><code>\"\"\"\nCurious thing: A dictionary in the global scope can be referenced and changed inside a function without using the global statement, but it can not be redefined.\n\"\"\"\n</code></pre>\n\n<p>It's default behavior for global variable. When you try to redefine global variable inside some function without <code>global</code> keyword then python interpreter creates local variable with the same name. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T16:35:28.420", "Id": "1815", "ParentId": "1791", "Score": "0" } } ]
{ "AcceptedAnswerId": "1835", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T21:48:59.503", "Id": "1791", "Score": "4", "Tags": [ "python" ], "Title": "Review request: My App Engine library (python)" }
1791
<p>I've written a backup script to make a backup of the latest modified files in 12 hours. Basically, it searches two directories for modified files (statically coded) then the <code>find</code> command is used to find the related files. A log file is then created to keep a list of the files. Later on, they are used to form a list of files and these files are used for the backup by tar.</p> <p>Let me know which parts could be developed so that I can improve on and learn new things.</p> <pre><code>#!/usr/bin/env python ''' backup script to make a backup of the files that are newer than 12 hours in the home directory see " man find " " man tar " for more information on the dates and the specific options on how to set different specifications for the selections ''' import sys import os import time if (len(sys.argv) != 2): # if argument count is different # than 2, then there is an error print "Error on usage -&gt; binary &lt;hours_count_back&gt;" quit() else: # convert to integer value hours_back = int(sys.argv[1]) message_start = "Operation is starting".center(50, '-') message_end = "Operation terminated with success".center(50,'-') # print message_start # source directories to check for backup source = [ '/home/utab/thesis', '/home/utab/Documents' ] # find files newer than 24 hours # change to the target directories newer_files = [] # log_file = "log.dat" # cmd to find newer files # than 24 hours cmd_find = "find . -type f -a -mmin " + str(-hours_back*60) + " &gt; " + log_file for directory in source: # iterate over the directories # change to the directory first os.chdir(directory) # apply the command os.system(cmd_find); # files are found with respect to the current directory # change the "." to directory for correct backups c = 0 # process log file files = [] lines = [] log_in = open(log_file,'r') # read lines without \n character while 1: l = log_in.readline() if not l: break # do not include the newline # -1 is for that lines.append(l[:-1]) # for l in lines: l_dummy = l.replace( '.', directory, 1 ) files.append(l_dummy) # extend the list with newer files newer_files.extend(files) #print newer_files print newer_files # date today = time.strftime('%Y%m%d') # current time of the date # possible to do different backups in different times of the day now = time.strftime('%H%M%S') # target_directory = "/home/utab/" target = target_directory + today + "_" + now + \ '.tgz' # do the actual back up backup_cmd = "tar -C ~ -zcvf %s %s" % ( target , ' '.join(newer_files) ) status = os.system(backup_cmd) if status == 0: print message_end else: print "Back-up failed" </code></pre>
[]
[ { "body": "<p>A general suggestion which might yield a performance boost: if you can somehow determine that the directories in the <code>source</code> lists are on different harddisks, you could execute the main loop (which spends most of the time in the <code>find</code> invocation, I guess) in parallel.</p>\n\n<p>That being said, you could replace </p>\n\n<pre><code>for l in lines:\n l_dummy = l.replace( '.', directory, 1 )\n files.append(l_dummy)\n# extend the list with newer files\nnewer_files.extend(files)\n</code></pre>\n\n<p>with a list comprehension:</p>\n\n<pre><code>newer_files.extend([l.replace( '.', directory, 1 ) for l in lines])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T07:32:26.430", "Id": "1876", "ParentId": "1866", "Score": "3" } }, { "body": "<p>The script is vulnerable to an injection attack. If anyone can write files under any of the directories to be backed up then the script can be made to execute code of their choosing. (I realize that this is your home directory and \"this could never happen\" but bear with me for a moment). The problem is that a non-validated string is passed to <code>os.system()</code>:</p>\n\n<pre><code>backup_cmd = \"tar -C ~ -zcvf %s %s\" % ( target , ' '.join(newer_files) )\nstatus = os.system(backup_cmd)\n</code></pre>\n\n<p>Attacker just needs to:</p>\n\n<pre><code>cd some/where/writable\ntouch '; rm -rf ~'\n</code></pre>\n\n<p>But it doesn't even need to be a malicious attack. If any of the files have characters in their names that are interesting to the shell then the script may fail. A tamer example: if any filename contains a hash character (<code>#</code>) then all subsequent filenames in the <code>newer_files</code> list will be ignored and will not be backed up by <code>tar(1)</code>.</p>\n\n<p>Instead please consider using <a href=\"http://docs.python.org/library/os.html#os.execv\" rel=\"noreferrer\"><code>os.exec*()</code></a> or better still the <a href=\"http://docs.python.org/library/subprocess.html\" rel=\"noreferrer\"><code>subprocess</code> module</a>. These take a vector of arguments rather than a string and so do not suffer from the same problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T12:46:15.550", "Id": "1881", "ParentId": "1866", "Score": "6" } } ]
{ "AcceptedAnswerId": "1881", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T18:30:45.843", "Id": "1866", "Score": "8", "Tags": [ "python", "linux" ], "Title": "Linux backup script in Python" }
1866

Dataset Card for "2048_has_code_filtered_base_code_review_python"

More Information needed

Downloads last month
0
Edit dataset card