body
stringlengths
144
5.53k
comments
list
meta_data
dict
question_id
stringlengths
1
6
yield
stringclasses
2 values
answers
list
<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" } ]
{ "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
max_votes
[ { "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" } } ]
<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" } ]
{ "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
max_votes
[ { "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" } } ]
<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." } ]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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..." } ]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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." } ]
{ "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
accepted_answer
[ { "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" } } ]
<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" } ]
{ "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
max_votes
[ { "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" } } ]
<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." } ]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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 : )" } ]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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." } ]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
max_votes
[ { "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" } } ]
<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)" } ]
{ "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
max_votes
[ { "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" } } ]
<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." } ]
{ "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
max_votes
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<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>
[]
{ "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
accepted_answer
[ { "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" } } ]
<p>I just wrote this small inch &lt;-> cm conversion program. It works just fine, although I know that I've done some things in a rather stupid manner and that it could be improved.</p> <pre><code>def conversion(): try: amount = int(raw_input("Please enter the value: ")) except ValueError: print "Please specify a valid amount." return conversion() answer = raw_input("Please choose between converting FROM kilograms/pounds: ") if answer == "kilograms": return amount * 2.2 elif answer == "pounds": return amount / 1.45 else: print "Please choose between kilograms and pounds." restart = raw_input("Try again? ") if restart == "yes": return conversion() elif restart == "y": return conversion() else: print "Okay, bye." return print conversion() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-24T16:49:42.230", "Id": "110541", "Score": "1", "body": "where are cm and inch?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-18T14:57:51.360", "Id": "1952", "Score": "5", "Tags": [ "python", "converting" ], "Title": "Inch <-> cm conversion program" }
1952
max_votes
[ { "body": "<p>Don't use recursion in this case. Python doesn't optimize tail recursion and after long session script can show your <code>RuntimeError: maximum recursion depth exceeded</code>.</p>\n\n<p>Don't use <a href=\"http://docs.python.org/tutorial/floatingpoint.html\" rel=\"nofollow\">floating point arithmetic</a> in this case. Use <a href=\"http://speleotrove.com/decimal/\" rel=\"nofollow\">decimal arithmetic</a> with <a href=\"http://docs.python.org/library/decimal.html#module-decimal\" rel=\"nofollow\">decimal</a> module. For example:</p>\n\n<pre><code>&gt;&gt;&gt; 100 * 2.2\n220.00000000000003\n&gt;&gt;&gt; from decimal import Decimal\n&gt;&gt;&gt; Decimal(\"100\") * Decimal(\"2.2\")\nDecimal('220.0')\n</code></pre>\n\n<p>Split logic and presentation. For now there is no way to use this converter with Web UI or as a library for a bigger program. For example you can start with low level functions like this:</p>\n\n<pre><code>def kilograms_to_pounds(amount):\n return amount * Decimal(\"2.2\")\n\ndef pounds_to_kilograms(amount):\n return amount / Decimal(\"1.45\")\n</code></pre>\n\n<p>Then you can create front-end function like this:</p>\n\n<pre><code>converters = {\n (\"kilograms\", \"pounds\"): kilograms_to_pounds,\n (\"pounds\", \"kilograms\"): pounds_to_kilograms,\n}\n\ndef convert(amount, from_, to):\n c = converters.get((from_, to))\n if c is None:\n raise ValueError(\"converter not found\")\n return c(amount)\n\n&gt;&gt;&gt; convert(Decimal(\"100\"), \"pounds\", \"kilograms\")\nDecimal('68.96551724137931034482758621')\n</code></pre>\n\n<p>Later you can add aliases like this (or as function decorator):</p>\n\n<pre><code>aliases = {\n \"kg\": \"kilograms\",\n \"lb\": \"pounds\",\n ...\n}\n\ndef convert(amount, from_, to):\n from_ = aliases.get(from_, from_)\n to = aliases.get(to, to)\n c = converters.get((from_, to))\n if c is None:\n raise ValueError(\"converter not found\")\nreturn c(amount)\n\n&gt;&gt;&gt; convert(Decimal(\"100\"), \"lb\", \"kg\")\nDecimal('68.96551724137931034482758621')\n</code></pre>\n\n<p>With this architecture you can later add other converters to your library and you need to call only <code>convert()</code> function from your UI loop.</p>\n\n<p>Also I don't like your UI. For example if I need to convert 10 values from kilograms to pounds I need to enter value then I need to enter \"kilograms\". By adding modes to your converter you can save me 10 lines. For example user first enter \"kilograms to pounds\" and this conversion mode stored and displayed in the prompt. Then user can enter values which will be converted from kilograms to pounds. Later user can change conversion mode by entering \"pounds to kilograms\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-18T19:14:31.077", "Id": "1956", "ParentId": "1952", "Score": "4" } } ]
<p>I just wrote this small inch &lt;-> cm conversion program. It works just fine, although I know that I've done some things in a rather stupid manner and that it could be improved.</p> <pre><code>def conversion(): try: amount = int(raw_input("Please enter the value: ")) except ValueError: print "Please specify a valid amount." return conversion() answer = raw_input("Please choose between converting FROM kilograms/pounds: ") if answer == "kilograms": return amount * 2.2 elif answer == "pounds": return amount / 1.45 else: print "Please choose between kilograms and pounds." restart = raw_input("Try again? ") if restart == "yes": return conversion() elif restart == "y": return conversion() else: print "Okay, bye." return print conversion() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-24T16:49:42.230", "Id": "110541", "Score": "1", "body": "where are cm and inch?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-18T14:57:51.360", "Id": "1952", "Score": "5", "Tags": [ "python", "converting" ], "Title": "Inch <-> cm conversion program" }
1952
max_votes
[ { "body": "<p>Don't use recursion in this case. Python doesn't optimize tail recursion and after long session script can show your <code>RuntimeError: maximum recursion depth exceeded</code>.</p>\n\n<p>Don't use <a href=\"http://docs.python.org/tutorial/floatingpoint.html\" rel=\"nofollow\">floating point arithmetic</a> in this case. Use <a href=\"http://speleotrove.com/decimal/\" rel=\"nofollow\">decimal arithmetic</a> with <a href=\"http://docs.python.org/library/decimal.html#module-decimal\" rel=\"nofollow\">decimal</a> module. For example:</p>\n\n<pre><code>&gt;&gt;&gt; 100 * 2.2\n220.00000000000003\n&gt;&gt;&gt; from decimal import Decimal\n&gt;&gt;&gt; Decimal(\"100\") * Decimal(\"2.2\")\nDecimal('220.0')\n</code></pre>\n\n<p>Split logic and presentation. For now there is no way to use this converter with Web UI or as a library for a bigger program. For example you can start with low level functions like this:</p>\n\n<pre><code>def kilograms_to_pounds(amount):\n return amount * Decimal(\"2.2\")\n\ndef pounds_to_kilograms(amount):\n return amount / Decimal(\"1.45\")\n</code></pre>\n\n<p>Then you can create front-end function like this:</p>\n\n<pre><code>converters = {\n (\"kilograms\", \"pounds\"): kilograms_to_pounds,\n (\"pounds\", \"kilograms\"): pounds_to_kilograms,\n}\n\ndef convert(amount, from_, to):\n c = converters.get((from_, to))\n if c is None:\n raise ValueError(\"converter not found\")\n return c(amount)\n\n&gt;&gt;&gt; convert(Decimal(\"100\"), \"pounds\", \"kilograms\")\nDecimal('68.96551724137931034482758621')\n</code></pre>\n\n<p>Later you can add aliases like this (or as function decorator):</p>\n\n<pre><code>aliases = {\n \"kg\": \"kilograms\",\n \"lb\": \"pounds\",\n ...\n}\n\ndef convert(amount, from_, to):\n from_ = aliases.get(from_, from_)\n to = aliases.get(to, to)\n c = converters.get((from_, to))\n if c is None:\n raise ValueError(\"converter not found\")\nreturn c(amount)\n\n&gt;&gt;&gt; convert(Decimal(\"100\"), \"lb\", \"kg\")\nDecimal('68.96551724137931034482758621')\n</code></pre>\n\n<p>With this architecture you can later add other converters to your library and you need to call only <code>convert()</code> function from your UI loop.</p>\n\n<p>Also I don't like your UI. For example if I need to convert 10 values from kilograms to pounds I need to enter value then I need to enter \"kilograms\". By adding modes to your converter you can save me 10 lines. For example user first enter \"kilograms to pounds\" and this conversion mode stored and displayed in the prompt. Then user can enter values which will be converted from kilograms to pounds. Later user can change conversion mode by entering \"pounds to kilograms\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-18T19:14:31.077", "Id": "1956", "ParentId": "1952", "Score": "4" } } ]
<p>The objective was the following to be solved in Python:</p> <blockquote> <p>Given a string, def a function that returns another string with the vowels (upper or lowercase) replaced by 0,1,2,3,4 respectively.</p> <hr> <p>Example input:</p> <pre><code>"bB nN aei ou AEIOU" </code></pre> <p>Desired Output:</p> <pre><code>"bB nN 012 34 01234" </code></pre> <hr> </blockquote> <p>This is in fact quite trivial and can be solved in several ways, one way may be this:</p> <pre><code>def crypt(s): vow = ["a","e","i","o","u"] stringL = [] for x in s: if x in vow or x.lower() in vow: stringL.append(str(vow.index(x.lower()))) else: stringL.append(x) return "".join(stringL) </code></pre> <p>I was told this was over-complicated for such a simple task, that code like this would be difficult to debug etc.</p> <p>Would you consider this approach a "bad" one, which way would you have gone instead, is it unclear?</p>
[]
{ "AcceptedAnswerId": "2168", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-30T00:24:30.360", "Id": "2164", "Score": "11", "Tags": [ "python", "strings" ], "Title": "Change upper or lowercase vowels to [0,1,2,3,4] respectively and leave the rest the same" }
2164
accepted_answer
[ { "body": "<p>Use <a href=\"https://docs.python.org/2/library/string.html#string.maketrans\" rel=\"nofollow noreferrer\"><code>string.maketrans()</code></a>.</p>\n\n<pre><code>from string import maketrans \n\ninput = \"aeiouAEIOU\"\noutput = '0123401234'\ntrans = maketrans(input,output)\nstr = 'This is a Q&amp;A site, not a discussiOn forUm, so please make sure you answer the question.'\nprint str.translate(trans)\n</code></pre>\n\n<p>Output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Th2s 2s 0 Q&amp;0 s2t1, n3t 0 d2sc4ss23n f3r4m, s3 pl10s1 m0k1 s4r1 y34 0nsw1r th1 q41st23n.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-30T01:14:56.297", "Id": "2168", "ParentId": "2164", "Score": "14" } } ]
<p>In order to avoid the user having to explicitly prefix a script with <code>sudo</code> or <code>su --command</code>, I wrote the following:</p> <pre><code>import sys import os if os.getuid(): root = "/usr/bin/sudo" if not os.path.exists("/usr/bin/sudo"): root = "/bin/su --command" command = "{} {}".format(root, sys.argv[0]) command = command.split() retcode = subprocess.call(command) if retcode: print("something wrong happened") else: action_that_needs_admin_rights() </code></pre> <p>It feels like a hack to me, so am looking forward to better approaches.</p>
[]
{ "AcceptedAnswerId": "2205", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-03T01:18:16.187", "Id": "2203", "Score": "7", "Tags": [ "python" ], "Title": "Becoming root from Python" }
2203
accepted_answer
[ { "body": "<p>The last time I checked (which admittedly has been a while) all major Linux distributions except Ubuntu have a default setup in which sudo is installed, but not configured to be able to start arbitrary applications. So on those your script will fail.</p>\n\n<p>Apart from that I think it's a bad idea to use split like this. This will break if the python file (or the path to it if it was invoked with a path) contains spaces. I'd do it like this instead:</p>\n\n<pre><code>if sudo:\n root = [\"/usr/bin/sudo\"]\nelse:\n root = [\"/bin/su\", \"--command\"]\ncommand = root + [ sys.argv[0] ]\n</code></pre>\n\n<p>A further problem is that you're requiring the script to be marked as executable. I think it'd be a better idea to use <code>sys.executable</code> to get the python interpreter and invoke that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-03T02:21:19.230", "Id": "3558", "Score": "0", "body": "What's wrong with requiring the script executable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-03T02:32:43.767", "Id": "3559", "Score": "0", "body": "@Tshepang: It's not wrong as such, it just means that it won't work in cases in which it otherwise would (i.e. in the case where the user invokes the script with `python script.py` rather than making it executable)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-03T08:30:55.540", "Id": "3561", "Score": "0", "body": "Even in that case it should work, because `sys.argv[0]` is always the script filename." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-03T08:40:00.323", "Id": "3562", "Score": "3", "body": "@Tshepang: Yes, that's the point. `sudo filename.py` does not work, if the file is not executable. You need to do `sudo python filename.py`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-03T02:06:21.273", "Id": "2205", "ParentId": "2203", "Score": "5" } } ]
<p>As a Python newbie, I have coded this binary tree as best as I could to follow Python idioms. However, I know it is still very verbose and not up to standard. I would like Python experts to tear this apart and identify its weaknesses. </p> <pre><code>class TreeNode(object): """ applicable to all tree nodes including root node """ def __init__(self, value, left=None, right=None,root=False): self.value = value TreeNode.check(left) TreeNode.check(right) self.left = left self.right = right self.root = root def inorder(self): s = list() if not self.left: s.append('') else: s.append(self.left.inorder()) s.append(str(self.value)) if not self.right: s.append('') else: s.append(self.right.inorder()) return ' '.join(s).strip() # returns True if success, False otherwise def insert( self, new_value ): # TODO ?? what happens if we are inserting strings if not new_value and new_value != 0: return False if new_value == self.value: return False # need to find the right location in terms of binary tree ordering if new_value &lt; self.value: if not self.left: self.left = TreeNode(new_value) return True else: return self.left.insert( new_value ) elif new_value &gt; self.value: if not self.right: self.right = TreeNode(new_value) return True return self.right.insert( new_value ) return False @staticmethod def check(node): if not node: return if not isinstance(node, TreeNode): raise TypeError('only instances of TreeNode are allowed') def __repr__(self): return '(' + repr(self.left) + ',' + \ str(self.value) + ',' + repr(self.right) + ')' </code></pre>
[]
{ "AcceptedAnswerId": "2282", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T10:06:26.743", "Id": "2280", "Score": "9", "Tags": [ "python", "beginner", "tree" ], "Title": "Binary tree in Python" }
2280
accepted_answer
[ { "body": "<p>Firstly, the official python style guide recommends 4-space indentation, and you are using 2. (No big deal but following the style guide is helpful)</p>\n\n<pre><code>class TreeNode(object):\n \"\"\" applicable to all tree nodes including root node \"\"\"\n def __init__(self, value, left=None, right=None,root=False):\n</code></pre>\n\n<p>Your code never passes a left/right parameter. There are also doesn't seem to be a good reason why you would pass left/right parameters in the construction of the tree. I assume you would use this class by constructing an empty tree and inserting values into it, not by composing trees. As a result, I suggest eliminating left/right.</p>\n\n<p>Also, you have a root parameter which is never used. It looks like something that you should eliminate. </p>\n\n<p>Additionally, you cannot create an empty tree with this method.</p>\n\n<pre><code> self.value = value \n TreeNode.check(left)\n TreeNode.check(right)\n self.left = left\n self.right = right\n self.root = root\n\n def inorder(self):\n s = list()\n</code></pre>\n\n<p>Use s = [], also don't use single letter variable names. </p>\n\n<pre><code> if not self.left:\n</code></pre>\n\n<p>When checking for None, recommened practice is to do it like: if self.left is None:</p>\n\n<pre><code> s.append('') \n else:\n s.append(self.left.inorder())\n\n s.append(str(self.value))\n\n if not self.right:\n s.append('')\n else:\n s.append(self.right.inorder())\n\n return ' '.join(s).strip()\n</code></pre>\n\n<p>The fact that you are trying to construct a string is kinda wierd. I'd expect this method to produce either an iterator or a list containing all the elements. </p>\n\n<pre><code> # returns True if success, False otherwise \n def insert( self, new_value ):\n # TODO ?? what happens if we are inserting strings\n if not new_value and new_value != 0:\n return False\n</code></pre>\n\n<p>This is why you should \"is None\"</p>\n\n<pre><code> if new_value == self.value:\n return False\n\n # need to find the right location in terms of binary tree ordering\n if new_value &lt; self.value:\n if not self.left:\n self.left = TreeNode(new_value) \n return True\n else:\n return self.left.insert( new_value )\n elif new_value &gt; self.value:\n</code></pre>\n\n<p>You've already established that this expression must be true, just use else</p>\n\n<pre><code> if not self.right:\n self.right = TreeNode(new_value)\n return True\n return self.right.insert( new_value )\n</code></pre>\n\n<p>The previous branch had this inside an else. You should at least be consistent between branches</p>\n\n<pre><code> return False\n\n @staticmethod \n def check(node):\n if not node:\n return\n if not isinstance(node, TreeNode):\n raise TypeError('only instances of TreeNode are allowed')\n</code></pre>\n\n<p>Explicitly checking types is frowned upon. All you manage is converting an AttributeError into a TypeError. However, a check method could usefully verify the invariants of a data structure. (Just only do it while debugging). </p>\n\n<pre><code> def __repr__(self):\n return '(' + repr(self.left) + ',' + \\\n str(self.value) + ',' + repr(self.right) + ')'\n</code></pre>\n\n<p>TreeNode seems to be a collection class, one that holds elements. The internal structure shouldn't matter to the world. However, repr spills the internal structure for the world to see. I'd suggest calling inorder to produce all of the elements inside the string and show that. Also repr's value should make it clear what class is being repr, by including \"TreeMap\" somewhere in its output.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T20:58:27.117", "Id": "3676", "Score": "0", "body": "Whats wrong with single letter variable names? Especially for something so used as the `s` in this case. Do you dislike `i` as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T21:31:47.397", "Id": "3677", "Score": "0", "body": "Single letter variable names are acceptable if the abbreviation is common. Otherwise it just makes the code harder to read. s doesn't strike me as a common abbreviation for what you are doing. Of course, that's subjective, so if you find it common enough, that's ok." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T21:33:34.243", "Id": "3678", "Score": "0", "body": "My own policy is to almost entirely avoid single letter variable names. Python features properly used eliminate many of the variables which would typically be candidates for such short names. I always use longer names to make sure I don't slip into being lazy and stop looking for a better way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T06:28:06.763", "Id": "3681", "Score": "0", "body": "There are tons of code written by supposedly expert pythonista which uses `isinstance`. When is it kosher to use it ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T13:56:34.920", "Id": "3683", "Score": "0", "body": "@Jacques, that question is much too large to answer here. You should probably open another question on that. Short answer: everything always depends." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T12:35:48.017", "Id": "2282", "ParentId": "2280", "Score": "6" } } ]
<p>I've just written this Twisted resource base class for serving files. It's part of a larger application, this is just for serving its images, JavaScript files, etc.</p> <p>Is it okay? I wonder if checking for <code>..</code> in the path is enough -- all the files that exist in <code>self.directory</code> are intended to be served, to anyone, so this should be all that's needed, I think. Should these it be a Unicode string? Should they all be Unicode strings?</p> <p>Will <code>return open(file).read()</code> be enough? I would think the resource would be closed when the function goes out of scope, but I'm not completely sure.</p> <pre><code>""" Base class for resources serving files to the browser. This doesn't use the `Page` class because it doesn't need to set up templates or anything, just serve the file. """ from twisted.web.resource import Resource import os.path class File(Resource): """ Serves a certain type of file from the server. It could be images, javascript, etc. It serves files from a single directory which have a single extension. members: content_type -- the HTTP content type of the files to be served directory -- the local directory the files are stored in extension -- the extension which the files are saved with. """ content_type = None directory = None extension = None def render_GET(self, request): """ Serve the requested file. Makes sure the file exists and the request doesn't contain '..' to escape the file directory. """ file = request.path.strip("/") file = file.split("/", 1)[1] file = "{directory}/{filepath}.{extension}".format( directory=self.directory, filepath=file, extension=self.extension) request.responseHeaders.setRawHeaders("content-type", [self.content_type]) if ".." in file: request.setResponseCode(400) return "" if not os.path.isfile(file): request.setResponseCode(404) return "" return open(file).read() </code></pre>
[]
{ "AcceptedAnswerId": "2317", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T20:58:38.770", "Id": "2315", "Score": "4", "Tags": [ "python", "twisted" ], "Title": "File-serving Twisted resource" }
2315
accepted_answer
[ { "body": "<p>Firstly, don't try to think of everything that could go wrong. Instead, check for what you know to be valid.</p>\n\n<pre><code>import re\ndirectory, filename = re.match('/([A-Za-z0-9]+)/([A-Za-z0-9]+)/?', alpha).groups()\n</code></pre>\n\n<p>By using this method to extract the directory and filename, we can be sure that directory and filename contain nothing except letters and numbers which are perfectly safe.</p>\n\n<p>Its also best to use <code>os.path.join</code> to produce folder paths rather then string formatting to put them together. </p>\n\n<pre><code> return open(file).read()\n</code></pre>\n\n<p>This works, but not if you try and run on IronPython/Jython/PyPy. CPython depends on reference counting which will cause the file to be closed as soon as it returns. A better version is probably:</p>\n\n<pre><code>with open(file) as source:\n return source.read()\n</code></pre>\n\n<p>This is guaranteed to close the file even without reference counting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-18T17:51:26.207", "Id": "333769", "Score": "0", "body": "The regex for directory and filename isn't very good. Many, many valid directory and filenames would be treated as invalid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-18T23:31:05.330", "Id": "333830", "Score": "0", "body": "@jwg, yes, but that's my point. Its better to reject good filenames than to fail to reject bad ones. If all you need are alphanumeric names, then you don't need to go the extra mile to handle other characters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-19T07:57:55.857", "Id": "333871", "Score": "0", "body": "Rejecting anything with a `.` or `_` is clearly broken." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T22:19:48.987", "Id": "2317", "ParentId": "2315", "Score": "2" } } ]
<p>Suppose you have a list of the diameters of some circular holes, and a list of the diameters of some cylindrical pegs. Now the problem is finding all the ways you can fit the pegs in the holes, where the order in which you put them in doesn't matter, and it's OK to put a peg in a hole that's too large.</p> <p>I've written the code below to solve the problem, and it <em>works</em> as intended. The innermost tuples of the answer matches a peg to a hole, i.e. (4, 7) means put d4 peg in d7 hole, and these tuples make up a set that represents one way of putting all the pegs in.</p> <p>I'm not completely happy with the solution. It's not... snappy enough, and it feels overly complicated. Is there a smarter way to go about it?</p> <pre><code>def fit(pegs, holes): for h in holes: for p in pegs: if p &lt;= h: pegs_left = [x for x in pegs if x != p] if pegs_left: free_holes = [x for x in holes if x != h] for rest in fit(pegs_left, free_holes): yield frozenset(((p, h),)) | rest else: yield frozenset(((p, h),)) def fitted(pegs, holes): return sorted(sorted(x) for x in set(fit(pegs, holes))) pegs = [2, 4, 7] holes = [1, 3, 4, 6, 9] print fitted(pegs, holes) # [[(2, 3), (4, 4), (7, 9)], # [(2, 3), (4, 6), (7, 9)], # [(2, 4), (4, 6), (7, 9)], # [(2, 6), (4, 4), (7, 9)]] </code></pre>
[]
{ "AcceptedAnswerId": "2408", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T15:47:54.207", "Id": "2407", "Score": "5", "Tags": [ "python", "optimization", "algorithm" ], "Title": "all the ways to fit some pegs into given holes" }
2407
accepted_answer
[ { "body": "<ol>\n<li>I recommend against using single letter variable names, in particular your use of p and h. \nI think the code is clearer if you use peg and hole. </li>\n<li>Your code is going to break if you have multiple holes or pegs of the same size.</li>\n<li>You'd be better off using tuples instead of frozensets. You don't appear to be using the set features.</li>\n</ol>\n\n<p>In order to have better code/algorithm you need to look at the problem differently. Right now you are trying to find peg/hole combinations. Instead, you should try to figure out where each peg fits. </p>\n\n<p>You have the pegs: 2, 4, 7</p>\n\n<p>Your goal is to select three of the holes: 1, 3, 4, 6, 9 which fit the pegs.</p>\n\n<pre><code>itertools.permutations(holes, 3)\n</code></pre>\n\n<p>will produce an iterator over all possible choices of 3 holes from the list. Something like:</p>\n\n<pre><code>1 3 4\n1 3 6\n1 3 9\n1 4 3\n...\n</code></pre>\n\n<p>We interpret each value as an assignment of holes to pegs. So 1,3,4 means (2, 1), (4, 3), (7,4). Of course not all such assignments are valid. So we filter out the invalid ones (i.e. where the pegs don't fit). </p>\n\n<p>As an added bonus, itertools.permutations generates its values in sorted order. Because we only filter the results, the resulting function will also produce its values in sorted order. This removes the neccesity of doing the sorting yourself.</p>\n\n<p>Here is my implementation:</p>\n\n<pre><code>import itertools\n\ndef check_fits(pegs, holes):\n for peg, hole in zip(pegs, holes):\n if peg &gt; hole:\n return False\n return True\n\ndef fit(pegs, holes):\n assert len(pegs) &lt;= len(holes)\n for selected_holes in itertools.permutations(holes, len(pegs)):\n if check_fits(pegs, selected_holes):\n yield zip(pegs, selected_holes)\n\npegs = [2, 4, 7]\nholes = [1, 3, 4, 6, 9]\n\nfor item in fit(pegs, holes):\n print item\n</code></pre>\n\n<p>itertools.permutations will generate many invalid assignment of pegs to holes. For example, in the example above, it will generate a significant number of assignment which attempt to fit a peg of size 2 into a hole of size 1. A simple recursive function could avoid spending time on so many bad assignments. However, itertools.permutation is written in C, and so probably still has a speed advantage over such a recursive algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T17:47:47.317", "Id": "3807", "Score": "0", "body": "Thank you for a very nice answer! Timeit shows that your solution, in addition to being more readable and nicer overall, also is over an order of magnitude faster; 13.3 usec vs. 650 usec. A couple of comments: 1) Frozenset is there so the order in which the pegs are inserted won't matter, so it had a purpose! 2) In your solution, `assert (...)` should probably be replaced by `if (...); raise ValueError()`, since `assert` statements are ignored when python runs in optimized mode." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T17:53:59.587", "Id": "3808", "Score": "0", "body": "Oh, and I suppose you meant \"1,3,4 means (2, 1), (4, 3), (7, 4)\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T18:47:46.293", "Id": "3809", "Score": "0", "body": "@lazyr, re: frozenset, I understand now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T18:47:59.307", "Id": "3810", "Score": "0", "body": "@lazyr, re: numbers, you are correct. I've edited" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T18:51:19.227", "Id": "3811", "Score": "0", "body": "@lazy, re: assert. it seems to me that depends on the context. Any sort of reusable function should raise a ValueError. However, if its strictly for internal use within one module then I'd probably use an assert. (In this case I was just trying to clarify that the code made that assumption. I didn't think too hard about it)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T10:16:58.770", "Id": "3839", "Score": "0", "body": "Another optimization I thought of: eliminate the holes that are smaller than the smallest peg before beginning. I.e. `min_peg = min(pegs)`, `holes = [hole for hole in holes if hole >= min_peg]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T14:10:38.550", "Id": "3844", "Score": "0", "body": "@lazyr, I doubt that will help a whole lot, but it might." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T17:16:07.020", "Id": "2408", "ParentId": "2407", "Score": "6" } } ]
<p>I'm fetching a string that is JSONP, and looking to convert it to JSON. </p> <p>I'm using the following regular expression for matching (for removal) the padding on the JSON. </p> <pre><code>([a-zA-Z_0-9\.]*\()|(\);?$) </code></pre> <p>In python, here's the line I'm using for converting the JSONP to JSON:</p> <pre><code>apijson = re.sub(r'([a-zA-Z_0-9\.]*\()|(\);?$)','',jsonp) </code></pre> <p>Is there anything I should worry about using this regular expression? Any chance I could end up mangling the JSON?</p>
[]
{ "AcceptedAnswerId": "2562", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T00:30:33.330", "Id": "2561", "Score": "6", "Tags": [ "python", "json", "regex" ], "Title": "Converting JSONP to JSON: Is this Regex correct?" }
2561
accepted_answer
[ { "body": "<p>The problem with the code is that it doesn't really express what you are trying to do:</p>\n\n<pre><code>apijson = re.sub(r'([a-zA-Z_0-9\\.]*\\()|(\\);?$)','',jsonp)\n</code></pre>\n\n<p>The code would seem to indicate that you are trying to find and replace many instances of some regular expressions inside the string. However, you are really trying to strip parts off of the beginning and end. I'm also not a huge fan of regular expressions because they are usually pretty dense and hard to read. Sometimes they are awesome, but this is not one of those times.</p>\n\n<p>Additionally, you aren't anchoring the regular expression to the beginning of the string which is what you'd need to strip off. The only case I could see that being a problem is perhaps if there were strings inside the json which matched the regular expression. Its best to be sure.</p>\n\n<p>Also, I think JSON-P allows functions like alpha[\"beta\"] which will doesn't fit your regular expression. Also what about additional whitespace or comments? </p>\n\n<p>I would suggest doing something like:</p>\n\n<pre><code> apijson = jsonp[ jsonp.index(\"(\") + 1 : jsonp.rindex(\")\") ]\n</code></pre>\n\n<p>That way you are more clearly stripping everything outside of the first and last parenthesis. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T01:19:10.333", "Id": "2562", "ParentId": "2561", "Score": "8" } } ]
<p>I wrote a little Python script to replace some files in <code>usr/bin</code> with symlinks to files in a different location.</p> <p>I wouldn't mind anyone telling me where I could do better.</p> <pre><code>#!/usr/bin/env python -tt """Xcode4 installs and expects to find a git installation at /usr/bin. This is a pain if you want to control your own installation of git that might be installed elsewhere. This script replaces the git files in /usr/bin with symlinks to the preferred installation. Update the 'src_directory' to the location of your preferred git installation. """ import sys import os #- Configuration ----------------------------------------------------------------- src_directory = '/usr/local/git/bin/' # preferred installation #---------------------------------------------------------------------------------- dest_directory = '/usr/bin/' files = ('git','git-cvsserver','git-receive-pack','git-shell','git-upload-archive','git-upload-pack','gitk') def main(): if os.getuid(): print "This script needs to be run as 'sudo python update_git.py'" sys.exit(1) for a_file in files: src_file = os.path.join(src_directory, a_file) dest_file = os.path.join(dest_directory, a_file) if os.path.exists(dest_file): os.remove(dest_file) os.symlink(src_file, dest_file) if __name__ == '__main__': main() </code></pre>
[]
{ "AcceptedAnswerId": "2683", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-28T09:31:08.380", "Id": "2678", "Score": "7", "Tags": [ "python", "file-system" ], "Title": "Replacing files with symlinks to other files" }
2678
accepted_answer
[ { "body": "<pre><code>#!/usr/bin/env python -tt\n\n\"\"\"Xcode4 installs and expects to find a git installation at /usr/bin.\nThis is a pain if you want to control your own installation of git that\nmight be installed elsewhere. This script replaces the git files in\n/usr/bin with symlinks to the preferred installation.\n\nUpdate the 'src_directory' to the location of your preferred git installation.\n\"\"\"\nimport sys\nimport os\n\n#- Configuration -----------------------------------------------------------------\nsrc_directory = '/usr/local/git/bin/' # preferred installation\n#----------------------------------------------------------------------------------\n\ndest_directory = '/usr/bin/'\nfiles = ('git','git-cvsserver','git-receive-pack','git-shell','git-upload-archive','git-upload-pack','gitk')\n</code></pre>\n\n<p>The official python style guide recommends using ALL_CAPS to name global constants. Additionally, some of these constants might be better as command line arguments to the script. That way you don't need to modify the script to install to a different location.</p>\n\n<pre><code>def main():\n if os.getuid():\n</code></pre>\n\n<p>I suggest using <code>if os.getuid() != 0</code> because I think its better to be explicit. The code will run the same, but this way I think its clearer that you are checking for zero rather then an actual boolean value.</p>\n\n<pre><code> print \"This script needs to be run as 'sudo python update_git.py'\"\n sys.exit(1)\n\n for a_file in files:\n</code></pre>\n\n<p>a_file is kinda ugly. I'm guessing you are using it to avoid replace the builtin file. I suggest filename.</p>\n\n<pre><code> src_file = os.path.join(src_directory, a_file)\n dest_file = os.path.join(dest_directory, a_file)\n\n if os.path.exists(dest_file):\n os.remove(dest_file)\n</code></pre>\n\n<p>What if someone deletes the file between your script checking if it exists and deleting it? Also checking if the file exists duplicates effort that remove will have to do. You could rewrite the code to try remove, and then catching the doesn't exist exception. I wouldn't bother here though.</p>\n\n<pre><code> os.symlink(src_file, dest_file)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>You don't catch any exceptions. In a script this simple that might be okay. But it might be a good idea to try/catch IOError/OSError and print them out for the user hopefully with enough detail that the user can tell whats going wrong. If you don't the exception will be dumped, but the user will also see a stack trace which might be scary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-28T16:11:59.237", "Id": "4187", "Score": "0", "body": "Wow! That's a lot of good points. Thanks very much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-28T15:41:31.457", "Id": "2683", "ParentId": "2678", "Score": "5" } } ]
<p>This code comes straight out from the example code in a Django book. I find it quite bad, mainly because the use of flags (<code>if ajax</code> then again <code>if ajax</code>) and unnecessarily bigger variable scope (set <code>title=''</code>, <code>tags=''</code> and then use these variables in different flows). The function body also seems way too long.<br> I guess I'll subtract the book title (for the record I find the book in general good). </p> <p>How would you rate this code, say out of 10 (10=very good, 3 and below being unacceptable)? (I'd rate it a 3) </p> <p>The reason I ask is, I had rejected similar code in the past during code review and now I'm wondering whether I've been too strict or didn't understand python culture (I'm new to python).</p> <pre><code>@login_required def bookmark_save_page(request): ajax = 'ajax' in request.GET if request.method == 'POST': form = BookmarkSaveForm(request.POST) if form.is_valid(): bookmark = _bookmark_save(request, form) if ajax: variables = RequestContext(request, { 'bookmarks': [bookmark], 'show_edit': True, 'show_tags': True }) return render_to_response( 'bookmark_list.html', variables ) else: return HttpResponseRedirect( '/user/%s/' % request.user.username ) else: if ajax: return HttpResponse(u'failure') elif 'url' in request.GET: url = request.GET['url'] title = '' tags = '' try: link = Link.objects.get(url=url) bookmark = Bookmark.objects.get( link=link, user=request.user ) title = bookmark.title tags = ' '.join( tag.name for tag in bookmark.tag_set.all() ) except (Link.DoesNotExist, Bookmark.DoesNotExist): pass form = BookmarkSaveForm({ 'url': url, 'title': title, 'tags': tags }) else: form = BookmarkSaveForm() variables = RequestContext(request, { 'form': form }) if ajax: return render_to_response( 'bookmark_save_form.html', variables ) else: return render_to_response( 'bookmark_save.html', variables ) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-31T15:24:19.487", "Id": "4250", "Score": "0", "body": "Seems okay-ish to me, but I would absolutely split it up into into functions/methods instead of the slightly silly \"if ajax\" check. There are also too many hardcoded values. I'd give it a \"4\"." } ]
{ "AcceptedAnswerId": "2737", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-31T01:23:22.153", "Id": "2721", "Score": "5", "Tags": [ "python", "django", "ajax" ], "Title": "How would you rate this python code? (Django AJAX)" }
2721
accepted_answer
[ { "body": "<p>In my opinion it's little bit hard to read. You have to split it up into POST/GET methods.\nThen you have to clean up code in POST/GET methods.\nSomething like this, for example.</p>\n\n<pre><code>@login_required\ndef bookmark_save(request):\n form = BookmarkSaveForm()\n if request.method == 'POST':\n form = bookmark_POST(request):\n if isinstance(form, HttpResponse):\n return form\n elif 'url' in request.GET:\n form = bookmark_GET(request)\n\n variables = RequestContext(request, {'form': form})\n\n if 'ajax' in request.GET:\n template_name = 'bookmark_save_form.html'\n else:\n temaplte_name = 'bookmark_save.html'\n return render_to_response(temaplte_name, variables)\n</code></pre>\n\n<p>And functions for POST/GET actions</p>\n\n<pre><code>def bookmark_POST(request):\n form = BookmarkSaveForm(request.POST)\n if form.is_valid():\n bookmark = _bookmark_save(request, form)\n if 'ajax' in request.GET:\n variables = RequestContext(request, {\n 'bookmarks': [bookmark],\n 'show_edit': True,\n 'show_tags': True\n })\n return render_to_response(\n 'bookmark_list.html', variables\n )\n else:\n return HttpResponseRedirect(\n '/user/%s/' % request.user.username\n )\n else:\n if 'ajax' in request.GET:\n return HttpResponse(u'failure')\n return form\n\ndef bookmark_GET(request):\n url = request.GET['url']\n try:\n link = Link.objects.get(url=url)\n bookmark = Bookmark.objects.get(\n link=link,\n user=request.user\n )\n title = bookmark.title\n tags = ' '.join(\n bookmark.tag_set.all().\\\n values_list('name', flat=True)\n )\n except (Link.DoesNotExist, Bookmark.DoesNotExist):\n title = ''\n tags = ''\n form = BookmarkSaveForm({\n 'url': url,\n 'title': title,\n 'tags': tags\n })\n return form\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-31T16:18:09.227", "Id": "2737", "ParentId": "2721", "Score": "6" } } ]
<p>I've never done anything like this before so I'd like someone else to look at this before I get too carried away :)</p> <p>Am I making this more complicated than it needs to be? I'm trying to make it EASY for other modules/scripts on this system to store and retrieve their settings. Hence why I trap the <code>ConfigParser.NoOptionError</code> error and return <code>None</code> and create the section if it doesn't exist in the <code>set()</code> method.</p> <p>Suggestions?</p> <pre><code>import ConfigParser import os from ast import literal_eval as Eval class _ConfParse(ConfigParser.ConfigParser): def __init__(self, confpath, conffile): ConfigParser.ConfigParser.__init__(self) self.conf_file = os.path.join(confpath, conffile) try: self.readfp(open(self.conf_file), 'r') except IOError as Err: if Err.errno == 2: pass else: raise Err def set(self, section, option, value): if self.has_section(section): ConfigParser.ConfigParser.set(self, section, option, str(value)) else: self.add_section(section) ConfigParser.ConfigParser.set(self, section, option, str(value)) def get(self, section, option): try: return Eval(ConfigParser.ConfigParser.get(self, section, option)) except ConfigParser.NoOptionError: return None def save(self): self.write(open(self.conf_file, 'w')) def __del__(self): self.save() class LocalConfig(_ConfParse): def __init__(self, conffile, confpath = '/etc/local/cnf'): _ConfParse.__init__(self, confpath, conffile) class SysConfig(_ConfParse): def __init__(self, conffile, confpath = '/etc/sys/cnf'): _ConfParse.__init__(self, confpath, conffile) </code></pre>
[]
{ "AcceptedAnswerId": "2804", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-02T02:20:10.937", "Id": "2775", "Score": "3", "Tags": [ "python" ], "Title": "Python subclassing ConfigParser" }
2775
accepted_answer
[ { "body": "<p>One problem I see is that returning None from your modified get() method conflicts with the normal case of a valueless option (from the bottom of the module docs for ConfigParser):</p>\n\n<pre><code>&gt;&gt;&gt; import ConfigParser\n&gt;&gt;&gt; import io\n\n&gt;&gt;&gt; sample_config = \"\"\"\n... [mysqld]\n... user = mysql\n... pid-file = /var/run/mysqld/mysqld.pid\n... skip-external-locking\n... old_passwords = 1\n... skip-bdb\n... skip-innodb\n... \"\"\"\n&gt;&gt;&gt; config = ConfigParser.RawConfigParser(allow_no_value=True)\n&gt;&gt;&gt; config.readfp(io.BytesIO(sample_config))\n\n&gt;&gt;&gt; # Settings with values are treated as before:\n&gt;&gt;&gt; config.get(\"mysqld\", \"user\")\n'mysql'\n\n&gt;&gt;&gt; # Settings without values provide None:\n&gt;&gt;&gt; config.get(\"mysqld\", \"skip-bdb\")\n\n&gt;&gt;&gt; # Settings which aren't specified still raise an error:\n&gt;&gt;&gt; config.get(\"mysqld\", \"does-not-exist\")\nTraceback (most recent call last):\n ...\nConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'\n</code></pre>\n\n<p>Note the second-to-last example commented as \"Settings without values provide None:\" Of course this isn't an issue if you intend to exclude this sort of option. Other than that, I like the auto-section feature.</p>\n\n<p>Though, I'd lean towards adding to the interface rather than masking and changing the behavior, so instead of replacing get/set, add safe_ versions:</p>\n\n<pre><code>def safe_set(self, section, option, value):\n if self.has_section(section):\n self.set(section, option, str(value))\n else:\n self.add_section(section)\n self.set(section, option, str(value))\n\ndef safe_get(self, section, option):\n if self.has_option(section, option):\n return self.get(section, option)\n else:\n return None\n</code></pre>\n\n<p>This would make it more flexible as code would still have access to ConfigParser's normal interface and the option of using the \"safe\" calls which don't throw exceptions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-03T20:51:53.883", "Id": "4345", "Score": "0", "body": "I thought about creating a different 'safe' method, but since I'm not doing anything to mess with the format of the file; you could still use the standard `ConfigParser` on the same file. Is retaining the inherited class methods un-modified a 'best' or 'standard' practice? I just don't know what the conventions are for something like this- if there are any! Thanks for looking at this!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-03T20:38:17.297", "Id": "2804", "ParentId": "2775", "Score": "1" } } ]
<p>I have over 300 questions that I plan to include in the program. The flow is pretty much like this:</p> <ul> <li>Create a window with the question</li> <li>Store answer in variable</li> <li>Create NEW window with question</li> <li>Store NEW answer</li> </ul> <p>(This continues on for over 300 questions.)</p> <p>I have 2 questions:</p> <ol> <li>Will this eventually lead to a crash since I'm creating so many windows?</li> <li>Everything works with this code if you select 'Yes' to the second question (A2) but it does not work if you select 'No'. Can you please see if you can find what's wrong with it?</li> </ol> <pre><code>import wx a1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon', "Don't remember", 'None of the above'] a2 = ['No', 'Yes'] a4 = ['No', 'Yes'] class Fruit(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200)) #create panel and button panel = wx.Panel(self) # B1 - create multiple choice list box = wx.MultiChoiceDialog(None, """ A1. What kind of fruit did you buy at the store?""", 'Fruit', a1) if box.ShowModal() == wx.ID_OK: a_1 = box.GetSelections() print (a_1, '\n') # A2 - create single choice list box = wx.SingleChoiceDialog(None, """ A2. Do you like eating fruit? """, 'Fruit', a2) if box.ShowModal() == wx.ID_OK: a_2 = box.GetStringSelection() print (a_2, '\n') if a_2 == 'Yes': box = wx.TextEntryDialog(None, "A3. What kind of fruit is your favorite? ", "Fruit", "") if box.ShowModal() == wx.ID_OK: a_3 = box.GetValue() print (a_3, '\n') box = wx.SingleChoiceDialog(None, """ A4. Did you eat the fruit that you bought? """, 'Fruit', a4) if box.ShowModal() == wx.ID_OK: a_4 = box.GetStringSelection() print (a_4, '\n') </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-06T22:36:17.373", "Id": "2837", "Score": "2", "Tags": [ "python", "wxpython" ], "Title": "Questionnaire program using many wxPython windows" }
2837
max_votes
[ { "body": "<pre><code>import wx\n\na1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon',\n \"Don't remember\", 'None of the above']\n\na2 = ['No', 'Yes']\n\na4 = ['No', 'Yes']\n</code></pre>\n\n<p>The Python style guide recommend ALL_CAPS for global constants.</p>\n\n<pre><code>class Fruit(wx.Frame):\n\n def __init__(self, parent, id):\n wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200))\n\n #create panel and button\n panel = wx.Panel(self)\n\n # B1 - create multiple choice list\n box = wx.MultiChoiceDialog(None, \"\"\"\n\nA1. What kind of fruit did you buy at the store?\"\"\", 'Fruit', a1)\n</code></pre>\n\n<p>When strings get long enough that they force breaking across multiple lines, its usually best to move them to global constants</p>\n\n<pre><code> if box.ShowModal() == wx.ID_OK:\n a_1 = box.GetSelections()\n\n\n print (a_1, '\\n')\n</code></pre>\n\n<p>I don't think this does what you think it does. For python 2.x (which unless wxPython has been ported to python 3.x recently, must be what you are using), you shouldn't put parenthesis around your print statements. </p>\n\n<pre><code> # A2 - create single choice list\n box = wx.SingleChoiceDialog(None, \"\"\"\nA2. Do you like eating fruit?\n\"\"\", 'Fruit', a2)\n if box.ShowModal() == wx.ID_OK:\n a_2 = box.GetStringSelection()\n\n print (a_2, '\\n')\n\n if a_2 == 'Yes':\n box = wx.TextEntryDialog(None, \"A3. What kind of fruit is your favorite? \", \"Fruit\", \"\")\n if box.ShowModal() == wx.ID_OK:\n</code></pre>\n\n<p>If the answer to the previous question was \"Yes\", then box is now the result of asking question A3. However, otherwise its the still the previous question. As a result, it'll ask the same question again. You probably want to indent this if block so that it only happens if a_2 was Yes.</p>\n\n<pre><code> a_3 = box.GetValue()\n\n\n print (a_3, '\\n')\n\n\n box = wx.SingleChoiceDialog(None, \"\"\"\nA4. Did you eat the fruit that you bought?\n\"\"\", 'Fruit', a4)\n if box.ShowModal() == wx.ID_OK:\n a_4 = box.GetStringSelection()\n\n print (a_4, '\\n')\n</code></pre>\n\n<p>As for your questions:</p>\n\n<ol>\n<li>You can probably get away with creating that many windows. However, you can make sure that a dialog gets destroyed by calling its Destroy() method. </li>\n<li>I explained above what was wrong with your logic.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-06T23:25:49.843", "Id": "4372", "Score": "0", "body": "Thank you. So basically I need to change a1 to A1, and maybe create another module with all of the questions and answers and just import it to keep my code clean? Anyways, thanks for taking the time to give me a detailed answer. For some reason I keep having trouble with the indented blocks so I will try to check that next time when something goes wrong. Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-06T23:45:36.750", "Id": "4373", "Score": "0", "body": "@Jerry, if you elaborate on what you plan on doing with the answers I can suggest the best way to structure that part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-06T23:48:52.667", "Id": "4374", "Score": "0", "body": "Hey Winston, after the answers are all entered, I will be attempting to use pyodbc to write them to an MS Access Database. Hopefully it won't be too hard, but I am already finding your approach much easier than mine :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T01:12:45.893", "Id": "4376", "Score": "0", "body": "@Jerry, basically, what I think should happen is to make a list of all questions that you can then just process in a for loop. There is some trickiness in doing that, but its probably the best way." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-06T23:17:00.447", "Id": "2838", "ParentId": "2837", "Score": "3" } } ]
<p>How does this recursive selection sort look to everyone here? Am I missing anything 'pythonic' about the way I have done it?</p> <pre><code>def selection_sort(li, out=None): if out is None: out = [] li = li[:] if len(li) == 0: return out small = min(li) li.remove(small) out.append(small) return selection_sort(li, out) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T18:34:22.767", "Id": "2855", "Score": "4", "Tags": [ "python", "algorithm", "recursion" ], "Title": "Selection sort using recursion" }
2855
max_votes
[ { "body": "<pre><code>def selection_sort(li, out=None):\n</code></pre>\n\n<p>I dislike the name \"li,\" I think abbreviations are bad.</p>\n\n<pre><code> if out is None:\n out = [] \n li = li[:]\n</code></pre>\n\n<p>Rather then using the out parameter to do this, I suggest creating a seperate internal function which is called. Otherwise, it looks like the caller to the function might reasonable pass out = something, when its only meant to be used internally.</p>\n\n<pre><code> if len(li) == 0:\n return out\n</code></pre>\n\n<p>Better to use <code>if not li:</code></p>\n\n<pre><code> small = min(li)\n li.remove(small)\n out.append(small)\n return selection_sort(li, out)\n</code></pre>\n\n<p>Its a little hard to gauge this code because you are doing two things you shouldn't, using recursion when its not necessary and implementing your own sort routine. But if you are doing so for learning purposes that's fine.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Iterative solution:</p>\n\n<pre><code>def selection_sort(li):\n li = li[:]\n out = []\n\n while li:\n smallest = min(li)\n li.remove(smallest)\n out.append(smallest)\n\n return out\n</code></pre>\n\n<p>But why is this better than the recursive solution:</p>\n\n<ol>\n<li>There is a limit to your stack space. If you try to sort a large list using this function you'll get a RuntimeError</li>\n<li>Calling a function has extra overhead that iterating in a loop does not, the iterative version will be faster</li>\n<li>A loop is usually easier to read then recursion. The while loop makes it easy to see whats doing on, whereas the recursive version requires some thought about the code to see the logic.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T19:06:54.487", "Id": "4399", "Score": "0", "body": "Aye learning, and why not recursion for this situation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T19:18:50.980", "Id": "4400", "Score": "0", "body": "@Jakob, see edit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T01:09:09.093", "Id": "4554", "Score": "0", "body": "+1: amplifying \"don't have output parameters\". Given Python's ability to return arbitrary tuples, there is never a reason to use an output parameter. For example: `return (a_list, a_dict_of_dicts, status)` is valid and idiomatic. Also pay attention to the difference between list.sort() and list.sorted() in the standard library (hint: one returns a value, the other doesn't, why?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T23:14:03.037", "Id": "4559", "Score": "0", "body": "@msw, I wouldn't quite say \"never.\" For example, numpy has reasonable use of out parameters for efficiency reasons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-18T10:04:35.483", "Id": "4564", "Score": "0", "body": "Fair 'nuff. How about \"unless you know whyfor\"?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T19:06:23.740", "Id": "2856", "ParentId": "2855", "Score": "3" } } ]
<p>Looking for a code review, and hopefully to learn something if someone has a nicer solution. Here's what I wrote:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import division, print_function from future_builtins import * import numpy as np def _walk(num_dims, samples_per_dim, max_): if num_dims == 0: yield np.array([(max_ - 1) / (samples_per_dim - 1)]) else: for i in range(max_): for rest in _walk(num_dims - 1, samples_per_dim, max_ - i): yield np.concatenate((np.array([i]) / (samples_per_dim - 1), rest)) def walk(num_dims, samples_per_dim): """ A generator that returns lattice points on an n-simplex. """ return _walk(num_dims, samples_per_dim, samples_per_dim) </code></pre> <p>So, <code>list(walk(2, 3))</code> yields:</p> <pre><code>[array([ 0., 0., 1.]), array([ 0. , 0.5, 0.5]), array([ 0., 1., 0.]), array([ 0.5, 0. , 0.5]), array([ 0.5, 0.5, 0. ]), array([ 1., 0., 0.])] </code></pre>
[]
{ "AcceptedAnswerId": "2868", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T22:41:43.537", "Id": "2860", "Score": "2", "Tags": [ "python", "generator" ], "Title": "Python generator to produce lattice points on an n-simplex." }
2860
accepted_answer
[ { "body": "<p>Using Winston Ewert's suggestions of using itertools, and using lists instead of numpy arrays internally, here's an alternate solution:</p>\n\n<pre><code>def walk(num_dims, samples_per_dim):\n \"\"\"\n A generator that returns lattice points on an n-simplex.\n \"\"\"\n max_ = samples_per_dim + num_dims - 1\n for c in combinations(range(max_), num_dims):\n c = list(c)\n yield [(y - x - 1) / (samples_per_dim - 1)\n for x, y in izip([-1] + c, c + [max_])]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T07:19:43.093", "Id": "2868", "ParentId": "2860", "Score": "1" } } ]
<p>Is this code Pythonic?</p> <pre><code>def emit_decorator(method, signal_name): def decorated(self, *args, **kwargs): retval = method(self, *args, **kwargs) getattr(self, signal_name).emit() return retval return decorated class Model(base.Transformer, Node): """ Transformer subclass that implements the Model of the Model-View-Controller paradigm. """ def __init__(self, *args, **kwargs): super(Model, self).__init__(*args, **kwargs) modelChanged = pyqtSignal() def create_view(self, parent=None): return View(self, parent) for x in ('importance_changed', 'evidence_changed', ): setattr(Model, x, emit_decorator(getattr(Model, x), 'modelChanged')) </code></pre> <hr> <p>Final decorator code:</p> <pre><code>from functools import update_wrapper def method_emit_decorator(signal_name): def method_decorator(method): def decorated(self, *args, **kwargs): retval = method(self, *args, **kwargs) getattr(self, signal_name).emit() return retval return update_wrapper(decorated, method) return method_decorator def class_emit_decorator(signal_name_to_method_names_dict): def class_decorator(cls): retval = cls for signal_name, method_names in ( signal_name_to_method_names_dict.items()): for method_name in method_names: method = method_emit_decorator(signal_name)( getattr(cls, method_name)) setattr(retval, method_name, method) return retval return class_decorator </code></pre>
[]
{ "AcceptedAnswerId": "2893", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T20:23:27.413", "Id": "2890", "Score": "5", "Tags": [ "python" ], "Title": "Python subclass method decoration" }
2890
accepted_answer
[ { "body": "<p>Modifying the class after defining it smells. That is, its not necessarily a bad idea but one should explore options before resorting to it.</p>\n\n<p>When \"decorating\" a function you should use the functools.wraps decorator. It will make the decorated function look more like the original.</p>\n\n<p>The code you are replacing looks like:</p>\n\n<pre><code>def importance_changed(self):\n return_value = super(Model, self).importance_changed()\n self.modelChanged.emit()\n return return_value\n</code></pre>\n\n<p>Your code is harder to read and longer then just writing those two functions. Its not really worth implementing what you've done just for two functions. However, if you have a lot of functions then the situation changes.</p>\n\n<p>Your emit_decorator function isn't a decorator. Dectorators have to take exactly one argument, (the function they are wrapping) to be used with the @syntax.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T22:07:10.720", "Id": "4440", "Score": "0", "body": "Thanks for the great tips! I already have four such functions, so I thought this would be an easy way to save on boilerplate. I don't know of any way of doing this without modifying the class after defining it. Do you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T22:22:14.860", "Id": "4441", "Score": "0", "body": "@Neil G, I do, but they are uglier then what you are doing. I might think about defining a class dectorator that connects all _changed() function to a modelChanged() signal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T23:47:14.273", "Id": "4445", "Score": "0", "body": "I was just thinking along the same lines. Thanks a lot for your input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T06:46:55.663", "Id": "4515", "Score": "0", "body": "I have taken all of your suggestions into account and produced two decorators." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T22:02:28.413", "Id": "2893", "ParentId": "2890", "Score": "3" } } ]
<p>I'm an experienced programmer, but just a beginner in Python, and would like some input on a small function that's working but which I'm not very happy with.</p> <p>It's used to produce XML tags (strings). The content argument can be a string, a number etc., but if it's a datetime I have to format it properly. Also, if there is no content, the tag should not be rendered (return empty string).</p> <pre><code>def tag(tagName, content): if isinstance(content, datetime): content = content.strftime('%Y%m%d%H%M') else: content = str(content) if content: return "&lt;" + tagName + "&gt;" + content + "&lt;/" + tagName + "&gt;" return "" </code></pre> <p>Please enlighten me!</p>
[]
{ "AcceptedAnswerId": "3313", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T12:05:07.070", "Id": "2941", "Score": "2", "Tags": [ "python", "strings", "xml" ], "Title": "XML-tag function" }
2941
accepted_answer
[ { "body": "<p>Try this:</p>\n\n<pre><code>return \"&lt;%s&gt;%s&lt;/%s&gt;\" % (tagName, content, tagName)\n</code></pre>\n\n<p>e.g:</p>\n\n<pre><code>def tag(tagName, content):\n if isinstance(content, datetime):\n content = content.strftime('%Y%m%d%H%M')\n else:\n content = str(content)\n\n if content:\n return \"&lt;%s&gt;%s&lt;/%s&gt;\" % (tagName, content, tagName)\n\n return \"\"\n</code></pre>\n\n<p>Slightly more attractive if that's what you want?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T13:36:20.203", "Id": "5000", "Score": "0", "body": "Since there have been no other concrete suggestions actually answering the question I guess 1) there is nothing really wrong or non-idiomatic with my code, and 2) you deserve to get your answer accepted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T21:54:47.633", "Id": "5015", "Score": "0", "body": "To be honest I think text based UI's are an ancient paradigm, but are mostly the best we have in terms of practicality for the moment. There are a whole array of approaches, node based UIs, wiki based UIs, social coding environments, batteries massively included libraries brimming with start convenience functions that might make logic / code elegance more obvious. Maybe it's offtopic or meandering but if you feel dissatisfied in general with the elegance - the problem isn't the language as such, it's the medium. It's steadily evolving." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T23:38:33.910", "Id": "5018", "Score": "0", "body": "Code Bubbles is one such thing I was thinking of: http://www.youtube.com/watch?v=PsPX0nElJ0k" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T18:29:13.587", "Id": "3313", "ParentId": "2941", "Score": "2" } } ]
<p>I've been playing around with Python off and on for about the past year and recently came up with the following 68 (was 62) lines. I think I'll try making a calculator out of it. I'd really like to know what readers here think of its attributes such as coding style, readability, and feasible purposefulness.</p> <pre><code># notes: separate addresses from data lest the loop of doom cometh class Interpreter: def __init__(self): self.memory = { } self.dictionary = {"mov" : self.mov, "put" : self.put, "add" : self.add, "sub" : self.sub, "clr" : self.clr, "cpy" : self.cpy, "ref" : self.ref } self.hooks = {self.val("0") : self.out } def interpret(self, line): x = line.split(" ") vals = tuple(self.val(y) for y in x[1:]) dereferenced = [] keys_only = tuple(key for key in self.memory) for val in vals: while val in self.memory: val = self.memory[val] dereferenced.append(val) vals = tuple(y for y in dereferenced) self.dictionary[x[0]](vals) def val(self, x): return tuple(int(y) for y in str(x).split(".")) def mov(self, value): self.ptr = value[0] def put(self, value): self.memory[self.ptr] = value[0] def clr(self, value): if self.ptr in self.hooks and self.ptr in self.memory: x = self.hooks[self.ptr] y = self.memory[self.ptr] for z in y: x(z) del self.memory[self.ptr] def add(self, values): self.put(self.mat(values, lambda x, y: x + y)) def sub(self, values): self.put(self.mat(values, lambda x, y: x - y)) def mat(self, values, op): a, b = self.memory[values[0]], self.memory[values[1]] if len(a) &gt; len(b): a, b = b, a c = [op(a[x], b[x]) for x in xrange(len(b))] + [x for x in a[len(a):]] return [tuple(x for x in c)] def cpy(self, value): self.put(value) def out(self, x): print chr(x), def ref(self, x): self.put(x) interp = Interpreter() for x in file(__file__.split('/')[-1].split(".")[-2] + ".why"): interp.interpret(x.strip()) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T14:37:04.900", "Id": "4557", "Score": "2", "body": "It would be nice to see some sample input too." } ]
{ "AcceptedAnswerId": "2994", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T05:41:16.843", "Id": "2988", "Score": "6", "Tags": [ "python", "interpreter" ], "Title": "Simple Language Interpreter" }
2988
accepted_answer
[ { "body": "<p>To allow your module to be loadable by other files, it's customary to write the end of it with a <code>if __name__ == '__main__':</code> conditional like so:</p>\n\n<pre><code>if __name__ == '__main__':\n interp = Interpreter()\n for x in file(__file__.split('/')[-1].split(\".\")[-2] + \".why\"):\n interp.interpret(x.strip())\n</code></pre>\n\n<p>Maybe I'm being picky (but you did ask for style input), read <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> and try to follow it as best you can (stand). One thing that jumped out at me right away was your 2 space indentation vs. the PEP8 recommendation of 4. One letter variables are usually only recommended for looping vars. You could probably increase the readability of your code by renaming some of those x's, y's, a's, etc.</p>\n\n<p>Another maxim of Python programming is to use the tools provided, I was pondering what you were doing with:</p>\n\n<pre><code>__file__.split('/')[-1].split(\".\")[-2] + \".why\"\n</code></pre>\n\n<p>an alternative that uses existing Python modules (and is more portable across platforms) is:</p>\n\n<pre><code>os.path.splitext(os.path.basename(__file__))[0] + \".why\"\n</code></pre>\n\n<p>It's about the same length, and is a good deal more clear as to what you're doing as the function names spell it out.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T14:35:30.923", "Id": "2994", "ParentId": "2988", "Score": "3" } } ]

Dataset Card for "2048_has_code_filtered_base_code_review_python_based_on_property"

More Information needed

Downloads last month
0
Edit dataset card