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" } } ]
<p>I have a file containing one long line:</p> <pre><code>"name surname" &lt;name.surname@example.com&gt;, 'name surname' &lt;name.surname@example.com&gt;, name surname &lt;name.surname@example.com&gt;, "'name surname'" &lt;name.surname@example.com&gt;, surname, &lt;name.surname@example.com&gt;, name &lt;name.surname@example.com&gt; </code></pre> <p>Note that that's 6 different forms.</p> <p>I am splitting each email address into its own line, and saving the results into another file:</p> <pre><code>import sys ifile = sys.argv[1] ofile = sys.argv[2] with open(ifile) as ifile, open(ofile, "w") as ofile: addresses = ifile.readline().split("&gt;,") for n, address in enumerate(addresses): address = address.replace("'", "") address = address.replace('"', "") name, address = address.split("&lt;") address = "&lt;" + address if len(name) &gt; 1: name = name.strip() name = '"{}" '.format(name) address = "".join(name + address) if n &lt; len(addresses) - 1: ofile.write(address.strip() + "&gt;\n") else: ofile.write(address.strip() + "\n") </code></pre> <p>Feels to me like hackery so am looking for a better solution.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T09:35:49.410", "Id": "3016", "Score": "1", "Tags": [ "python" ], "Title": "Splitting one line into multiple ones given a separator" }
3016
max_votes
[ { "body": "<p>Why are you first removing the quotes and then putting them back?</p>\n\n<p>And why are you removing the brackets and them putting them back?</p>\n\n<p>This does the same thing, except change ' to \". It also doesn't handle commas in names,\nso if you have that it won't work. In that case I'd probably use a regexp.</p>\n\n<pre><code>import sys\n\nifile = sys.argv[1]\nofile = sys.argv[2]\n\nwith open(ifile) as ifile, open(ofile, \"w\") as ofile:\n for address in ifile.readline().split(\",\"):\n ofile.write(address.strip() + '\\n')\n</code></pre>\n\n<p>Update:</p>\n\n<p><code>\"surname, name &lt;name.surname@example.com&gt;\"</code> sucks, and that means your format is inconsistent and not parseable without horrid hacks. In that case your code seems OK, although I'd probably do it differently. I would most likely use a regexp to find all cases of commas that are NOT preceded by > and followed by a space to something else, say chr(128) or something like that. I'd then parse the code with my code above, extract the email from withing the brackets, strip all quotes and brackets from the remander, and replace back chr(128) with commas.</p>\n\n<p>And the lastly write that to the outfile.</p>\n\n<p>The difference there is that I don't try to handle a horrid format, I first try to fix the problems. It makes for cleaner code, IMO.</p>\n\n<p><strong>Update 2:</strong></p>\n\n<p>I instead replaced the commas that <em>should</em> be split on, making it simpler, like so:</p>\n\n<pre><code>import sys\n\nifile = sys.argv[1]\nofile = sys.argv[2]\n\nwith open(ifile) as ifile, open(ofile, \"w\") as ofile:\n data = ifile.read()\n data = data.replace('&gt;,', '&gt;\\xF0')\n for line in data.split('\\xF0'):\n name, email = line.split('&lt;')\n email = email.replace('&gt;', '').strip()\n name = name.replace('\"', '').replace(\"'\", \"\").strip()\n ofile.write('\"%s\" &lt;%s&gt;\\n' % (name, email))\n</code></pre>\n\n<p>and then I realized I could simplify it even more:</p>\n\n<pre><code>import sys\n\nifile = sys.argv[1]\nofile = sys.argv[2]\n\nwith open(ifile) as ifile, open(ofile, \"w\") as ofile:\n data = ifile.read()\n for line in data.split('&gt;,'):\n name, email = line.split('&lt;')\n email = email.strip()\n name = name.replace('\"', '').replace(\"'\", \"\").strip()\n ofile.write('\"%s\" &lt;%s&gt;\\n' % (name, email))\n</code></pre>\n\n<p>And as this point I'm basically doing what you are doing, but much simplified.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T10:58:56.097", "Id": "4571", "Score": "0", "body": "I'm sorry for forgetting to include the other things that the code must handle. See my updated question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T11:28:41.977", "Id": "4572", "Score": "0", "body": "I put back the single opening bracket because str.split() removes it from the list elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T11:34:22.127", "Id": "4573", "Score": "0", "body": "@Tshepang: Updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T17:23:41.093", "Id": "4577", "Score": "0", "body": "I'm not see where he indicates that he needs to parse that terrible version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T17:28:41.277", "Id": "4578", "Score": "0", "body": "There's 2 cases that your code doesn't handle. Run my code and yours and compare the results. Use the given input line to test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T17:29:46.707", "Id": "4579", "Score": "0", "body": "I prefer that you split the `replace()` functionality into separate lines, for the sake of clarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T18:54:32.963", "Id": "4588", "Score": "0", "body": "@Tshepang: I'm not here to write code for you. I charge $100 and hour for that. You can split that into separate lines yourself. The only difference in output between yours and mine is that you skip the name if it's empty, which I leave as a trivial example for you to handle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:08:53.587", "Id": "4590", "Score": "0", "body": "@LennartRegebro: There is another difference: your code leaves an extra `>` in the output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:11:50.387", "Id": "4592", "Score": "0", "body": "@LennartRegebro: Regarding the $100 thing, it's only fair that you make your code to at least do what mine does, since you are trying to improve it. It makes it easier to compare my code and yours to clearly see the improvements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:12:47.563", "Id": "4593", "Score": "0", "body": "It's interesting that you didn't implement your solution in regexp. May I ask why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:14:19.903", "Id": "4594", "Score": "0", "body": "Can you comment on my `replace` suggestion. Does it make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:21:43.730", "Id": "4595", "Score": "0", "body": "This was simpler. I have no comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T19:39:08.860", "Id": "4596", "Score": "0", "body": "It seems I pissed you off. The assumption came due to your mention of money. I didn't mean to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T21:33:39.830", "Id": "4598", "Score": "0", "body": "@Tshepang: No, I just find your follow-up questions weird, including asking me to split the line. You can split the line. There is no requirement that you take my code character by character. And there is nothing to say about that suggestion. If you want to split the line, split the line. I don't understand why you are asking for comments on that. It's like asking for permission to go to the toilet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T22:12:41.293", "Id": "4602", "Score": "0", "body": "@LennartRegebro: Since this is Code Review (my code is already working), we are looking for best practices, and that includes code clarity. That's why I thought it's worth mentioning that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T05:11:44.897", "Id": "4604", "Score": "0", "body": "@Tshepang: That doesn't really explain your questions. Sorry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T17:45:24.960", "Id": "4677", "Score": "1", "body": "Instead of doing: `name.replace('\"', '').replace(\"'\", \"\").strip()` you should be able to do `name.strip(\"'\\\" \")` for the same effect, see: http://docs.python.org/library/string.html?highlight=strip#string.strip." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T18:09:05.303", "Id": "4679", "Score": "0", "body": "@Kit: Yeah, good point, didn't think of that." } ], "meta_data": { "CommentCount": "18", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-20T10:53:10.070", "Id": "3017", "ParentId": "3016", "Score": "2" } } ]
<p>I've knocked together a few lines of python to read in stats for a service (haproxy), and store them in an array (to do some analysis on later). It basically takes a multiline output, and splits it into multiple subarrays. This is how I've done it - can anyone offer improvements for me?</p> <pre><code>def build_array(): services=[] for line in data.split('\n'): # split out each line of raw input holding=[] # start a temp array for var in line.split(','): # for each value append it to the temp array holding.append(var) services.append(holding) # append the temp array to the services array return services </code></pre> <p>The raw data is in the format:</p> <pre><code>data="""web,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,0,0,0,,,,0,0,0,0,0,0,,0,0,0,,, mysql,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,3,0,,,,0,0,0,0,,,,,,,,,,,0,0,0,,, web-https,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,4,0,,,,0,0,0,0,,,,,,,,,,,0,0,0,,, web,web2-NEW,0,0,0,0,,0,0,0,,0,,0,0,0,0,UP,1,0,1,0,0,19,0,,1,5,1,,0,,2,0,,0,L4OK,,0,0,0,0,0,0,0,0,,,,0,0, web,web1-OLD,0,0,0,0,,0,0,0,,0,,0,0,0,0,UP,1,1,0,0,0,19,0,,1,5,2,,0,,2,0,,0,L4OK,,0,0,0,0,0,0,0,0,,,,0,0, web,BACKEND,0,0,0,0,0,0,0,0,0,0,,0,0,0,0,UP,1,1,1,,0,19,0,,1,5,0,,0,,1,0,,0,,,,0,0,0,0,0,0,,,,,0,0,""" </code></pre>
[]
{ "AcceptedAnswerId": "3046", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T11:29:23.630", "Id": "3040", "Score": "1", "Tags": [ "python", "array" ], "Title": "Multiline Input into Python Arrays" }
3040
accepted_answer
[ { "body": "<p>This looks like CSV. You are probably better off using the python csv module.</p>\n\n<pre><code> holding=[] # start a temp array\n for var in line.split(','): # for each value append it to the temp array\n holding.append(var)\n services.append(holding) # append the temp array to the services arra\n</code></pre>\n\n<p>Can be written as</p>\n\n<pre><code>services.append( line.split(',') )\n</code></pre>\n\n<p>line.split() returns a list already, there is no need to copy the elements into another list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T11:00:59.250", "Id": "4633", "Score": "0", "body": "I was trying something like that originally, but it kept failing on me. Works now! Cheers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T16:52:16.220", "Id": "3046", "ParentId": "3040", "Score": "4" } } ]
<p>I've knocked together a few lines of python to read in stats for a service (haproxy), and store them in an array (to do some analysis on later). It basically takes a multiline output, and splits it into multiple subarrays. This is how I've done it - can anyone offer improvements for me?</p> <pre><code>def build_array(): services=[] for line in data.split('\n'): # split out each line of raw input holding=[] # start a temp array for var in line.split(','): # for each value append it to the temp array holding.append(var) services.append(holding) # append the temp array to the services array return services </code></pre> <p>The raw data is in the format:</p> <pre><code>data="""web,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,2,0,,,,0,0,0,0,,,,0,0,0,0,0,0,,0,0,0,,, mysql,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,3,0,,,,0,0,0,0,,,,,,,,,,,0,0,0,,, web-https,FRONTEND,,,0,0,4096,0,0,0,0,0,0,,,,,OPEN,,,,,,,,,1,4,0,,,,0,0,0,0,,,,,,,,,,,0,0,0,,, web,web2-NEW,0,0,0,0,,0,0,0,,0,,0,0,0,0,UP,1,0,1,0,0,19,0,,1,5,1,,0,,2,0,,0,L4OK,,0,0,0,0,0,0,0,0,,,,0,0, web,web1-OLD,0,0,0,0,,0,0,0,,0,,0,0,0,0,UP,1,1,0,0,0,19,0,,1,5,2,,0,,2,0,,0,L4OK,,0,0,0,0,0,0,0,0,,,,0,0, web,BACKEND,0,0,0,0,0,0,0,0,0,0,,0,0,0,0,UP,1,1,1,,0,19,0,,1,5,0,,0,,1,0,,0,,,,0,0,0,0,0,0,,,,,0,0,""" </code></pre>
[]
{ "AcceptedAnswerId": "3046", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T11:29:23.630", "Id": "3040", "Score": "1", "Tags": [ "python", "array" ], "Title": "Multiline Input into Python Arrays" }
3040
accepted_answer
[ { "body": "<p>This looks like CSV. You are probably better off using the python csv module.</p>\n\n<pre><code> holding=[] # start a temp array\n for var in line.split(','): # for each value append it to the temp array\n holding.append(var)\n services.append(holding) # append the temp array to the services arra\n</code></pre>\n\n<p>Can be written as</p>\n\n<pre><code>services.append( line.split(',') )\n</code></pre>\n\n<p>line.split() returns a list already, there is no need to copy the elements into another list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-22T11:00:59.250", "Id": "4633", "Score": "0", "body": "I was trying something like that originally, but it kept failing on me. Works now! Cheers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-21T16:52:16.220", "Id": "3046", "ParentId": "3040", "Score": "4" } } ]
<p>I wrote this program to do a simple Caesar shift by a user inputted key, and then deshift. I'm really enjoying it, but I've run out of ideas on improvements! Can you think of anything?</p> <pre><code>def decrypt(): a=raw_input("Give me the word to decrypt:") number=input("What was it shifted by?") b=list(a) str(b) c=[ord(x)for x in(b)] d=[] for i in c: d.append(i-number) e=[chr(i) for i in (d)] e="".join(e) print "Decryption Successful, your word is",e,"!" def encrypt(): a=raw_input("Give me a word:") number=input("Give me a number:") b=list(a) str(b) c=[ord(x)for x in(b)] d=[] for i in c: d.append(i+number) e=[chr(i) for i in (d)] e="".join(e) print "Your Caesar shifted result (ascii code) is:",e,"!" print "Your key is", number, ",remember that!" def menu(): print "\n\n\nWelcome to the Caesar Shifter." print "What would you like to do?" print "Option 1:Encrypt Word" print "Option 2:Decrypt Word" print "If you would like to quit, press 0." choice=input("Pick your selection:") if choice==1: run=encrypt() run menu() elif choice==2: derun=decrypt() derun menu() elif choice==0: quit else: print"That is not a correct selection, please pick either 1, or 2." menu() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:23:02.880", "Id": "4810", "Score": "0", "body": "Agree with previous comment. One \"easy way\" to often improve code is to use more (smaller) functions that do less but do whatever they do really well -- it makes the program more modular, testable, and the function names (if chosen correctly) add self-documentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:30:15.833", "Id": "4811", "Score": "0", "body": "So I should break up my functions more? So when say \"encrypt\" is run it calls 2 sub functions as opposed to just running that chunk of code?" } ]
{ "AcceptedAnswerId": "3203", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:14:34.163", "Id": "3201", "Score": "14", "Tags": [ "python", "caesar-cipher" ], "Title": "Simple Caesar shift and deshift" }
3201
accepted_answer
[ { "body": "<p>This might not be quite what you've got in mind, but one big improvement you could make would be to use meaningful variable names and insert whitespace.</p>\n\n<pre><code>def decrypt():\n cyphertext = raw_input('Give me the word to decrypt:')\n shift = input('What was it shifted by?')\n\n cypher_chars = list(cyphertext)\n str(b) # this does nothing; you should remove it\n cypher_ords = [ord(x) for x in cypher_list]\n plaintext_ords = []\n for i in cypher_ords:\n plaintext_ords.append(i - shift)\n\n plaintext_chars = [chr(i) for i in plaintext_ords]\n plaintext = ''.join(plaintext_chars)\n print 'Decryption Successful, your word is', plaintext, '!'\n</code></pre>\n\n<p>Of course you could actually compress much of this into a one-liner. But for a new programmer, I'd suggest sticking with readable variable names that make it clear what's going on.</p>\n\n<p>Still, you could do that while compressing the code a bit:</p>\n\n<pre><code>def decrypt():\n cyphertext = raw_input('Give me the word to decrypt:')\n shift = input('What was it shifted by?')\n\n cypher_ords = [ord(x) for x in cyphertext]\n plaintext_ords = [o - shift for o in cypher_ords]\n plaintext_chars = [chr(i) for i in plaintext_ords]\n plaintext = ''.join(plaintext_chars)\n print 'Decryption Successful, your word is', plaintext, '!'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:31:27.707", "Id": "4817", "Score": "0", "body": "Ok thanks, is it more a style system change so it's more interpretable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:40:44.073", "Id": "4818", "Score": "0", "body": "@SecNewbie, yes, exactly. Using variable names like `a`, `b`, etc is ok if you're planning to throw those variables away immediately or on the next line. But it's much easier for others to read your code if you give descriptive names to variables that are used throughout the function. For that matter, it's much easier for _you_ to read your code, after setting it aside and returning to it after six months!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:28:21.117", "Id": "3203", "ParentId": "3201", "Score": "8" } } ]
<p>I wrote this program to do a simple Caesar shift by a user inputted key, and then deshift. I'm really enjoying it, but I've run out of ideas on improvements! Can you think of anything?</p> <pre><code>def decrypt(): a=raw_input("Give me the word to decrypt:") number=input("What was it shifted by?") b=list(a) str(b) c=[ord(x)for x in(b)] d=[] for i in c: d.append(i-number) e=[chr(i) for i in (d)] e="".join(e) print "Decryption Successful, your word is",e,"!" def encrypt(): a=raw_input("Give me a word:") number=input("Give me a number:") b=list(a) str(b) c=[ord(x)for x in(b)] d=[] for i in c: d.append(i+number) e=[chr(i) for i in (d)] e="".join(e) print "Your Caesar shifted result (ascii code) is:",e,"!" print "Your key is", number, ",remember that!" def menu(): print "\n\n\nWelcome to the Caesar Shifter." print "What would you like to do?" print "Option 1:Encrypt Word" print "Option 2:Decrypt Word" print "If you would like to quit, press 0." choice=input("Pick your selection:") if choice==1: run=encrypt() run menu() elif choice==2: derun=decrypt() derun menu() elif choice==0: quit else: print"That is not a correct selection, please pick either 1, or 2." menu() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:23:02.880", "Id": "4810", "Score": "0", "body": "Agree with previous comment. One \"easy way\" to often improve code is to use more (smaller) functions that do less but do whatever they do really well -- it makes the program more modular, testable, and the function names (if chosen correctly) add self-documentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:30:15.833", "Id": "4811", "Score": "0", "body": "So I should break up my functions more? So when say \"encrypt\" is run it calls 2 sub functions as opposed to just running that chunk of code?" } ]
{ "AcceptedAnswerId": "3203", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:14:34.163", "Id": "3201", "Score": "14", "Tags": [ "python", "caesar-cipher" ], "Title": "Simple Caesar shift and deshift" }
3201
accepted_answer
[ { "body": "<p>This might not be quite what you've got in mind, but one big improvement you could make would be to use meaningful variable names and insert whitespace.</p>\n\n<pre><code>def decrypt():\n cyphertext = raw_input('Give me the word to decrypt:')\n shift = input('What was it shifted by?')\n\n cypher_chars = list(cyphertext)\n str(b) # this does nothing; you should remove it\n cypher_ords = [ord(x) for x in cypher_list]\n plaintext_ords = []\n for i in cypher_ords:\n plaintext_ords.append(i - shift)\n\n plaintext_chars = [chr(i) for i in plaintext_ords]\n plaintext = ''.join(plaintext_chars)\n print 'Decryption Successful, your word is', plaintext, '!'\n</code></pre>\n\n<p>Of course you could actually compress much of this into a one-liner. But for a new programmer, I'd suggest sticking with readable variable names that make it clear what's going on.</p>\n\n<p>Still, you could do that while compressing the code a bit:</p>\n\n<pre><code>def decrypt():\n cyphertext = raw_input('Give me the word to decrypt:')\n shift = input('What was it shifted by?')\n\n cypher_ords = [ord(x) for x in cyphertext]\n plaintext_ords = [o - shift for o in cypher_ords]\n plaintext_chars = [chr(i) for i in plaintext_ords]\n plaintext = ''.join(plaintext_chars)\n print 'Decryption Successful, your word is', plaintext, '!'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:31:27.707", "Id": "4817", "Score": "0", "body": "Ok thanks, is it more a style system change so it's more interpretable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:40:44.073", "Id": "4818", "Score": "0", "body": "@SecNewbie, yes, exactly. Using variable names like `a`, `b`, etc is ok if you're planning to throw those variables away immediately or on the next line. But it's much easier for others to read your code if you give descriptive names to variables that are used throughout the function. For that matter, it's much easier for _you_ to read your code, after setting it aside and returning to it after six months!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:28:21.117", "Id": "3203", "ParentId": "3201", "Score": "8" } } ]
<p>I just watched a Khan Academy <a href="http://www.khanacademy.org/video/insertion-sort-algorithm?playlist=Computer%20Science" rel="nofollow">video</a> on Insertion Sort and I've tried to write an implementation in Python. Please suggest corrections or improvements on this program:</p> <pre><code>unsorted_list=[45,99,1,-22,7,3,294,10,36] def insertion_sort(unsorted): for i in range(1,len(unsorted)): for j in range(i): if unsorted[i]&lt;unsorted[j]: temp = unsorted[j] unsorted[j]=unsorted[i] unsorted[i]=temp return unsorted print insertion_sort(unsorted_list) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T12:15:18.220", "Id": "4893", "Score": "1", "body": "This acts more like [bubble sort](http://en.wikipedia.org/wiki/Bubble_sort) in that it swaps more elements than necessary. The inner loop should not put the sorted sublist out of order. You need to run the inner loop in reverse and move the *ith* element toward the front of the sorted list--swapping each time with the next element closer to the front--until it finds its spot." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T07:57:02.547", "Id": "3264", "Score": "6", "Tags": [ "python", "sorting", "insertion-sort" ], "Title": "Khan inspired Insertion Sort" }
3264
max_votes
[ { "body": "<p>I wouldn't call your implementation insertion sort as it's sorting in place using swaps, which as David pointed out makes it look more like a bubble sort. An insertion sort sorts by building up a new list and inserting items into the proper place. A very crude first pass at an insertion sort might look like:</p>\n\n<pre><code>def insertion_sort(unsorted_list):\n result = []\n for n in unsorted_list:\n inserted = False\n for i in range(len(result)):\n if n &lt; result[i]:\n result.insert(i, n)\n inserted = True\n break\n if not inserted:\n result.append(n)\n return result\n</code></pre>\n\n<p>This could be greatly improved for larger data sets by making the inner search take advantage of the fact that <code>s</code> is sorted and doing a binary search for the insertion point. Of course, this being Python, the whole mess could be optimized to <code>sorted(unsorted_list)</code>. ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T21:44:33.260", "Id": "3300", "ParentId": "3264", "Score": "6" } } ]
<p>I've written a python module that randomly generates a list of ideas that can be used as the premises for furthur research. For instance, it would be useful in situations where a new thesis topic is required, either for a masters or a doctorate program. Or if someone is just simply bored with their lives and wants some brainstorming ideas about the kind of project that they would like to be involved in, this python module can be used.</p> <p>The output is a list of random ideas or technologies. It is up to the user as to how they interpret the output. Each idea in the list can be assessed individually, or the ideas can be combined in ways never thought off before to create something new.</p> <p>I would like some input on how else I can improve the project or what other features I may add. The project is hosted on github. The name of the project is <a href="https://github.com/kissandra79/Ranto" rel="nofollow">ranto</a> for lack of a better name.</p> <p>For the impatient, here is the code from the sole python file in the project...</p> <pre><code>import random import sys def topics(f): f = open(f, 'r') wordlist = [] for i in f: wordlist.append(i.strip()) return wordlist def mainp(): wordlist = topics('../data/' + sys.argv[1]) while True: print random.sample(wordlist, int(sys.argv[2])) if raw_input() == '': continue else: break mainp() </code></pre> <p>If you want to test it out, you need to download one of the data files from the github repo linked earlier.</p> <p>Any feedback would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T16:21:17.783", "Id": "4971", "Score": "1", "body": "Even for such simple program there's a thing you could do: replace each <tab> with four spaces (it isn't obvious here, but it is on the GitHub); this is a PEP recommendation. On a slightly unrelated note (since this is Code Review, not Feature Review), it would be cool if Ranto could get data for topics from other sources—for example, Wikipedia." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T13:57:34.133", "Id": "3295", "Score": "5", "Tags": [ "python", "python-2.x", "random", "generator" ], "Title": "Random Topic Generator" }
3295
max_votes
[ { "body": "<p>I can't tell from your question whether you are wanting ideas to improve this python code or the project itself. Your code above works and is readable, so take the following re-spelling of it as minor nitpicks.</p>\n\n<pre><code>def topics(f):\n for i in open(f): # inline the call to open(), and drop the implicit 'r'.\n yield i.strip() # \"yield\" turns this into a generator function that will only\n # read as many lines of the file as are requested.\n\ndef mainp(): # consider renaming to something more descriptive (generate_topics?)\n wordlist = topics('../data/' + sys.argv[1])\n response = True # Or any \"truthy\" value that drops us into the while loop one time.\n while response:\n print random.sample(wordlist, int(sys.argv[2]))\n response = raw_input()\n\nif __name__ == \"__main__\": # Putting in this if guard allows you to import your \n mainp() # functions above from anywhere else you might want them.\n</code></pre>\n\n<p>You may want to peruse the <a href=\"http://docs.python.org/howto/functional.html#generators\" rel=\"nofollow\">HOWTO for generator functions</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T14:51:40.767", "Id": "5091", "Score": "0", "body": "-1: \"and drop the implicit 'r'.\" Never works out well in the long run. Only really smart people remember that 'r' is the default. The rest of us have to look it up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T15:40:03.200", "Id": "5092", "Score": "0", "body": "@S.Lott: Weird. I thought this was generally known, and am not so smart." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T15:42:38.053", "Id": "5093", "Score": "0", "body": "@Tshepang: \"generally known\" is really hard to determine. However, I do (1) Explicit is better than implicit and (2) I have to look up the defaults and (3) I've had other programmers unable to remember this kind of default. So, for those reasons, I suggest avoiding defaults for this kind of thing. It may be \"generally known\", but it still doesn't work out well in the long run." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T20:54:56.860", "Id": "5133", "Score": "0", "body": "I agree with Lott on this one. If not for all the reasons but one.......'Explicit' is better than 'Implicit'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T12:36:50.023", "Id": "5292", "Score": "0", "body": "@S.Lott: I don't see how anyone can misread `for i in open(f)` as opening the file for writing. Do you similarly specify the slice step as 1 when slicing a sequence (e.g. `chunk = seq[10:20:1]`)? That's certainly more explicit, but readability suffers from the extra noise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:05:05.190", "Id": "5295", "Score": "0", "body": "@Don Spaulding: \"I don't see how anyone can misread `open(f)` as opening the file for writing.\" Sadly, however, some folks are not as cognizant of the defaults as others. I'm not making a blanket statement about all defaults for all language constructs. I'm making one point about one default for one specific function that has caused confusion in the past." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T18:18:22.783", "Id": "3332", "ParentId": "3295", "Score": "2" } } ]
<p>I'm looking for a single-pass algorithm for finding the topX percent of floats in a stream where I do not know the total number ahead of time ... but its on the order of 5-30 million floats. It needs to be single-pass since the data is generated on the fly and recreate the exact stream a second time.</p> <p>The algorithm I have so far is to keep a sorted list of the topX items that I've seen so far. As the stream continues I enlarge the list as needed. Then I use <code>bisect_left</code> to find the insertion point if needed.</p> <p>Below is the algorithm I have so far:</p> <pre><code>from bisect import bisect_left from random import uniform from itertools import islice def data_gen(num): for _ in xrange(num): yield uniform(0,1) def get_top_X_percent(iterable, percent = 0.01, min_guess = 1000): top_nums = sorted(list(islice(iterable, int(percent*min_guess)))) #get an initial guess for ind, val in enumerate(iterable, len(top_nums)): if int(percent*ind) &gt; len(top_nums): top_nums.insert(0,None) newind = bisect_left(top_nums, val) if newind &gt; 0: top_nums.insert(newind, val) top_nums.pop(0) return top_nums if __name__ == '__main__': num = 1000000 all_data = sorted(data_gen(num)) result = get_top_X_percent(all_data) assert result[0] == all_data[-int(num*0.01)], 'Too far off, lowest num:%f' % result[0] print result[0] </code></pre> <p>In the real case the data does not come from any standard distribution (otherwise I could use some statistics knowledge).</p> <p>Any suggestions would be appreciated.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T00:26:44.347", "Id": "3429", "Score": "4", "Tags": [ "python", "algorithm" ], "Title": "Single pass algorithm for finding the topX percent of items" }
3429
max_votes
[ { "body": "<pre><code>top_nums = sorted(list(islice(iterable, int(percent*min_guess)))) #get an initial guess\n</code></pre>\n\n<p>There is no reason to make a list out of it before you sort it.</p>\n\n<pre><code>for ind, val in enumerate(iterable, len(top_nums))\n</code></pre>\n\n<p>I dislike abbreviations. I think it makes it harder to figure out what ind and val are doing. </p>\n\n<pre><code> all_data = sorted(data_gen(num))\n</code></pre>\n\n<p>Why are you sorting your test data? </p>\n\n<p>As I understand your problem, your code is wrong. It only works in your test case because you sort the incoming data. </p>\n\n<p>Your algorithm regularly increases the size of the list of values. But when it does so, there have been previous numbers which have been thrown away which may greater then the value you insert at that point. As a result, you cannot be sure you've actually ended up with with the top 1%.</p>\n\n<p>How should you fix it? If you can upper bound the size of your input, then you can start with a list of sufficient size and then scale back at the end. Otherwise I don't think you can do it. The problem being that you cannot throw away any values because there is no way to be sure you won't need them later.</p>\n\n<p>You might consider using a heap. Python has a heapq module including a function heapq.nlargest which does pretty much what you are doing, (but uses a count rather then a percentage) A heap is pretty much a semi-sorted list and lets you do things like find/remove/replace the lowest value without the overhead of actually sorting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T23:05:54.813", "Id": "5280", "Score": "2", "body": "Actually. Only a heap can possibly work. Consider the case where all the incoming data is in strictly descending order. No value can be discarded because the top *X* percent is always the first arrived items in descending order. Until the entire stream has been seen, no value can be discarded as the number of slots comprising *X* percent grows." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T06:59:29.220", "Id": "5287", "Score": "0", "body": "@S. Lott, I'm not seeing the connection between \"only a heap can possibly work\" and the rest of your comment. At the very least, I'd think a sorted list can do the same things a heap can, (with more computational cost)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T09:47:51.870", "Id": "5290", "Score": "0", "body": "True. A sorted list and lots of other expensive and bad ideas for keeping the data will \"work\". Since they'll be more costly, they aren't very good ideas are they? The heap, however, is a very good idea. I think it belongs up higher in your answer, because it's a very good ideas. The theoretical possibility of other less good ideas didn't seem very relevant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:03:33.710", "Id": "5294", "Score": "0", "body": "@S.Lott, you said that only a heap could possibly work. If we are considering what could possibly work the efficiency doesn't matter. A heap is better, although I'm not sure how much. If I recall correctly, I have O(log n) insertion for both a sorted list and a heap. The heap is at the end because I thought it more important to point out that the code doesn't work then how to optimize it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:10:50.917", "Id": "5296", "Score": "0", "body": "Your distinction between bad algorithms which may work eventually and a good algorithm is getting too subtle for me. I'm sure it's an important hair, but I can't understand splitting it. The algorithm as presented is fundamentally flawed -- as you noted. Further, the whole thing can be simplified to just a heap and nothing more. There's little more to say than you pointed out both flaws. Feel, free, however, to continue to split whatever hair you need to in your already complete answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:08:45.773", "Id": "5318", "Score": "0", "body": "@S. Lott, the fundamental flaw in his algoritm isn't solved by using a heap. Just using a heap leaves his algorithm fundamentally flawed. Whether using a heap or sorted list the algorithm will give the wrong answers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:16:24.380", "Id": "5319", "Score": "0", "body": "If the algorithm given is discarded, and a heap is used, then the top *X* percent is available in the heap. That sounds like what you said. That's what made sense to me. Discard the broken algorithm. Use a heap. Right? Isn't that what you said? That's what my comment meant. Use a heap. Just use a heap. Ignore the broken algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:24:30.210", "Id": "5321", "Score": "0", "body": "@S. Lott, we don't know how big to make the heap. We won't know how big to make the heap until we've seen all the data, but at that point its too late. We need to know from the beginning of the algorithm how many values to keep in the heap, but since we only have a percentage we have a problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:27:42.177", "Id": "5322", "Score": "0", "body": "@S. Lott, if we solve the problem of how many items to keep, then yes use a heap. But, we've moved from the area of accuracy (What's really really important) to effeciency (which is less important)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T02:37:03.853", "Id": "5325", "Score": "0", "body": "\"We won't know how big to make the heap until we've seen all the data\". Precisely. The only solution is a heap. \"if we solve the problem of how many items to keep\"? What kind of random hypothetical is that? We can't know that in advance under any circumstances. Hence the heap as the only sensible solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T09:45:16.413", "Id": "5331", "Score": "0", "body": "@S. Lott, wait, are you suggesting putting the entire contents of the incoming data in a heap?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T09:51:48.077", "Id": "5333", "Score": "0", "body": "I can't see how any other approach would work. Until you've seen `len(stream)` items you don't know how large `X*len(stream)` is, so you don't know how many to \"keep\". If the data arrives in strictly descending order, you can't discard anything until you've reached `(1-X)*len(stream)`. Anyway, that's what appears to be the case to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:41:26.103", "Id": "5339", "Score": "0", "body": "@S. Lott, ok I misunderstood what you were suggesting. I agree that unless you can determine an upper bound on input size, you are stuck with keeping all values in memory until the end. The confusion resulted because when I suggested a heap, I didn't intend as an entire algorithm merely to replace the sorted list the OP was using for part of his \"broken\" algorithm. Hence when you started talking about the heap as \"the\" solution, I was rather confused." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:44:13.607", "Id": "5340", "Score": "0", "body": "I also confused because of the emphasis you placed on the heap, which as the data structure seems to be a fairly minor component of the solution. I wasn't really attempting to provide a complete solution because what the OP seems to want (not keeping everything in memory and returning the top 1% doesn't seem to possible.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:51:43.657", "Id": "5341", "Score": "0", "body": "\"what the OP seems to want\" appears unworkable. The heap appears workable. That was my comment. Only a heap will work. Other structures that keep all the data may work, but will be inefficient and therefore unworkable. I'm trying to keep this simple. The heap is the only thing that's workable. That was my comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T11:16:23.483", "Id": "5343", "Score": "0", "body": "@S. Lott, I must submit that I could also put everything into a list and then use a variant of quickselect to find the top 1%. Its also not clear to me that the solution is workable because the OP may simply have too much data. I'm just not willing to agree that the heap is the only data structure which is workable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T11:35:03.433", "Id": "5344", "Score": "0", "body": "\"not willing to agree\". Doesn't mean anything. Rather than fail to agree, you really must propose an alternative." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T13:24:02.797", "Id": "5345", "Score": "0", "body": "@S.Lott, I have proposed an alternative: modified quickselect. A heap-based algorithm is not the only workable solution to this problem. (It is, I think, the best one). But my point is that you are making an absolute statement: no algorithm besides a heap-based one is workable. To be able to make that claim, you need to demonstrate good reason to believe that no other workable algorithm exists. (Also workable is a little bit vauge)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T13:46:12.297", "Id": "5346", "Score": "0", "body": "Algorithms must be finite, definite and effective. Effective usually means minimal. Any O(n log n) algorithm would be effective. If the quickselect is as fast as the heap insertion, then it seems like it's isomorphic to it. Perhaps I'm missing something in the quickselect, but the way that it builds partitions sure sounds a lot like way a heap is built." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T22:29:13.163", "Id": "5365", "Score": "0", "body": "@S. Lott, I would take effective to mean that is runs in a reasonable amount of time for the problem under consideration. i.e a program which takes several years is not effective. However, a program which takes two minutes rather the one is still effective, but not as efficient as the other one. But that would be a matter of definition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T22:32:13.053", "Id": "5366", "Score": "0", "body": "O(n log n) isn't minimal for this problem. O(n log n) is enough time to sort and slice the data which is another technique. Quickselect will solve the problem in O(n). A heap could also solve it in O(n) although the niave heap-based solution will use O(n log n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T22:38:19.137", "Id": "5367", "Score": "0", "body": "I'm not seeing enough similarity between heap-building and partitioning that they look isomorphic to me. Perhaps I'm missing something. But more to the point, does it matter? From the programmer's perspective the implementation looks fairly different and so you still have choose between one and the other?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T11:15:00.000", "Id": "5377", "Score": "0", "body": "\"A heap could also solve it in O(n)\". Correct. I was wrong because this is partitioning not a full sort. \"But more to the point, does it matter?\" I have no idea. I suggested that a heap was the only solution because they appear isomorphic to me. However, you have split (and resplit) that hair now many, many times. You tell me. \"does it matter?\" Evidence indicates that it does matter, since you appear to be convinced that it requires extensive discussion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:02:09.757", "Id": "5381", "Score": "0", "body": "@S. Lott, re: does it matter. That was specifically about your claim of isomorphism between quickselect and heap. Since the end programmer has to choose between heaps and quickselect, claiming that they are isomorphic doesn't help the programmer. He still has to make the choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:06:19.117", "Id": "5383", "Score": "0", "body": "But let's put this in a practical context: what is the implication of claiming that \"heap is the only solution\"? As I read it, the implication is that no other algorithm should ever be implemented to solve this problem. But I don't think that statement is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:16:54.570", "Id": "5384", "Score": "0", "body": "I also mystified by your claim that I'm splitting hairs. I have no idea what hair you think I'm splitting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:42:36.610", "Id": "5386", "Score": "0", "body": "But let's put this in a practical context: \"heap is the only solution\". The way I wrote it, all solutions that are O(n) are isomorphic to a heap, which is minimal. You **already** suggested this, and I liked your suggestion and wanted to emphasize that your suggestion was very very good. For some reason, you don't seem to like the idea that your suggestion was very, very good. What's the point of downgrading your own suggestion by splitting a hair on the *exact* meaning of \"only\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T21:05:13.270", "Id": "5403", "Score": "0", "body": "@S. Lott, I see where you are coming from now. The problem is that your definition of \"only\" is very different from mine. As a result, your original claim came across as bizarre. There isn't really any point in discussing the meaning of the word, so I'll leave it at that. I wasn't trying to split hairs, but I thought you were trying to claim something that you aren't." } ], "meta_data": { "CommentCount": "28", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T04:17:09.797", "Id": "3431", "ParentId": "3429", "Score": "5" } } ]
<p>I wrote a simple function that calculates and returns the maximum drawdown of a set of returns. I am trying to squeeze as much efficiency for speed out of the code as possible. I've got it down to about as fast as I can go. Does anyone have suggestions on how to write this function more efficiently, perhaps through list comprehensions etc.?</p> <pre><code>import numpy as np def max_drawdown(returns): draw_series = np.array(np.ones(np.size(returns))) max_return = 0; max_draw = 1; draw = 1 returns = returns + 1 for r in range(returns.count()-1, 0, -1): if returns[r] &gt; max_return: max_return = returns[r] else: draw = returns[r] / max_return if draw &lt; max_draw: max_draw = draw draw_series[r-1] = -(1 - max_draw) return draw_series </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:54:19.583", "Id": "5238", "Score": "0", "body": "What type of object is `returns`? `returns = returns + 1` suggests it might be an integer, or a numpy array, but neither of those has a `count` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:57:53.390", "Id": "5239", "Score": "0", "body": "It is actually a Pandas TimeSeries object which acts like a numpy array. returns.count() is the same as len(returns)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T22:11:50.263", "Id": "5240", "Score": "0", "body": "This is minor and more aesthetic than performance-related, but note that `numpy.ones` returns an array, so passing it to `numpy.array` is redundant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T22:19:50.413", "Id": "5241", "Score": "0", "body": "Thanks @senderle. I found some optimization stuff on loops here, http://www.python.org/doc/essays/list2str.html." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:48:58.460", "Id": "3503", "Score": "6", "Tags": [ "python", "performance", "numpy" ], "Title": "Calculating the maximum drawdown of a set of returns" }
3503
max_votes
[ { "body": "<p>Untested, and probably not quite correct. I think it may actually apply operations backwards, but you should be easily able to flip that.</p>\n\n<pre><code>import numpy as np\n\ndef max_drawdown(returns):\n returns += 1\n max_returns = np.maximum.accumulate(returns)\n draw = returns / max_returns\n max_draw = np.minimum.accumulate(draw)\n draw_series = -(1 - max_draw)\n\n return draw_series\n</code></pre>\n\n<p>Comments on your code:</p>\n\n<pre><code>import numpy as np\n\ndef max_drawdown(returns):\n\n draw_series = np.array(np.ones(np.size(returns)))\n</code></pre>\n\n<p>np.ones, returns an array. There is no reason to pass it to np.array afterwards. If you aren't going to use the ones you store in the array use numpy.empty which skips the initialization step.</p>\n\n<pre><code> max_return = 0; max_draw = 1; draw = 1\n</code></pre>\n\n<p>You declare draw far away from where it used. Just assign to it in the scope its used in. Multiple assignments on one lined is also frowned upon in python. </p>\n\n<pre><code> returns = returns + 1\n</code></pre>\n\n<p>Use a compound assignment</p>\n\n<pre><code> for r in range(returns.count()-1, 0, -1):\n</code></pre>\n\n<p>I have to recommend against r, as its not a common abbreviation and I think it makes the code hard to read.</p>\n\n<pre><code> if returns[r] &gt; max_return:\n max_return = returns[r]\n\n else:\n draw = returns[r] / max_return\n if draw &lt; max_draw:\n max_draw = draw\n</code></pre>\n\n<p>Your math seems inscrutable, but perhaps it makes sense in context. Consider some comments to explain the reasoning</p>\n\n<pre><code> draw_series[r-1] = -(1 - max_draw)\n\n return draw_series\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T05:08:22.697", "Id": "5250", "Score": "0", "body": "+1 I was writing up the exact same thing eariler, but got busy and never posted it. This is definitely the way to go! (It's also ~3 orders of magnitude faster for large-ish arrays.) For the OP, note that you can create a reversed view of the array by returning `return draw_series[::-1]`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T03:19:25.400", "Id": "3519", "ParentId": "3503", "Score": "2" } } ]
<p>Context: I wrote a simple as an <a href="https://unix.stackexchange.com/questions/16849/importing-csv-contacts-into-evolution-3-0-2/16858#16858">answer</a> to a problem in <a href="http://unix.stackexchange.com">Unix.SE</a> and it was suggested to me to post it here for review.</p> <p>A comma separated file is generated by an application. On the first column it contains a last name, on the second a first name and on the tenth column a telephone number. For each row of this csv an vcard entry should be generated.</p> <p>This was my solution:</p> <pre><code>#!/usr/bin/python import csv import sys def convert(file): reader = csv.reader(open(file, 'rb')) for row in reader: print 'BEGIN:VCARD' print 'VERSION:2.1' print 'N:' + row[0] + ';' + row[1] print 'FN:' + row[1] + ' ' + row[0] print 'TEL;HOME;VOICE:' + row[9] print 'END:VCARD' def main(args): if len(args) != 2: print "Usage:" print args[0] + " filename" return convert(args[1]) if __name__ == '__main__': main(sys.argv) </code></pre> <p>Outputting the generated vcard on stdout was fine for me, I just redirected it into an appropriate file.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T01:47:28.223", "Id": "3517", "Score": "6", "Tags": [ "python", "converting", "csv" ], "Title": "Converting a csv to vcards in Python" }
3517
max_votes
[ { "body": "<p>Read about the <code>with</code> statement and ALWAYS use it with file operations</p>\n\n<pre><code>with open( somefilename, 'rb' ) as source:\n reader = csv.reader( source )\n for row in reader:\n etc.\n</code></pre>\n\n<p>That guarantees that the file is closed and all OS resources released.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T21:14:39.473", "Id": "3528", "ParentId": "3517", "Score": "5" } } ]
<p>Context: I wrote a simple as an <a href="https://unix.stackexchange.com/questions/16849/importing-csv-contacts-into-evolution-3-0-2/16858#16858">answer</a> to a problem in <a href="http://unix.stackexchange.com">Unix.SE</a> and it was suggested to me to post it here for review.</p> <p>A comma separated file is generated by an application. On the first column it contains a last name, on the second a first name and on the tenth column a telephone number. For each row of this csv an vcard entry should be generated.</p> <p>This was my solution:</p> <pre><code>#!/usr/bin/python import csv import sys def convert(file): reader = csv.reader(open(file, 'rb')) for row in reader: print 'BEGIN:VCARD' print 'VERSION:2.1' print 'N:' + row[0] + ';' + row[1] print 'FN:' + row[1] + ' ' + row[0] print 'TEL;HOME;VOICE:' + row[9] print 'END:VCARD' def main(args): if len(args) != 2: print "Usage:" print args[0] + " filename" return convert(args[1]) if __name__ == '__main__': main(sys.argv) </code></pre> <p>Outputting the generated vcard on stdout was fine for me, I just redirected it into an appropriate file.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T01:47:28.223", "Id": "3517", "Score": "6", "Tags": [ "python", "converting", "csv" ], "Title": "Converting a csv to vcards in Python" }
3517
max_votes
[ { "body": "<p>Read about the <code>with</code> statement and ALWAYS use it with file operations</p>\n\n<pre><code>with open( somefilename, 'rb' ) as source:\n reader = csv.reader( source )\n for row in reader:\n etc.\n</code></pre>\n\n<p>That guarantees that the file is closed and all OS resources released.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T21:14:39.473", "Id": "3528", "ParentId": "3517", "Score": "5" } } ]
<p>For some time now, I've been using a pattern which I think could be done more elegantly. I have a lot of XML files that need to be represented in a Django views. My current approach is like this:</p> <p>I get a XML response from an API which gives me several documents.</p> <p>First I define a mock class like this:</p> <pre><code>class MockDocument: pass </code></pre> <p>Then I write an XPath expression that gives me a list of the document nodes:</p> <pre><code>from lxml import etree with open("xmlapiresponse.xml", "r") as doc: xml_response = doc.read() tree = etree.fromstring(xml_response) document_nodes = tree.xpath("//documents/item") </code></pre> <p>Now I iterate over the different documents and their fields using nested <code>for</code>-loops:</p> <pre><code># list for storing the objects document_objects = [] for document in document_nodes: # create a MockDocument for each item returned by the API document_object = MockDocument() for field in document: # store the corresponding fields as object attributes if field.tag == "something": document.something = field.text document_objects.append(document) </code></pre> <p>Now I can pass the list of mock objects to a Django view and represent them in the template in whichever way I want. Could this be done in a simpler fashion, though?</p>
[]
{ "AcceptedAnswerId": "3596", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T10:48:16.397", "Id": "3593", "Score": "2", "Tags": [ "python", "xml", "django", "xpath" ], "Title": "Parsing and data presentation in Django" }
3593
accepted_answer
[ { "body": "<p>Using a generator function gives you some flexibility. You don't have to create a list.</p>\n\n<pre><code>def generate_documents( document_nodes ):\n\n for document in document_nodes:\n # create a MockDocument for each item returned by the API\n document_object = MockDocument() \n for field in document:\n # store the corresponding fields as object attributes\n if field.tag == \"something\":\n document.something = field.text\n yield document_object \n</code></pre>\n\n<p>You can do this of the list object is somehow important.</p>\n\n<pre><code>document_objects = list( generate_documents( document_nodes ) )\n</code></pre>\n\n<p>Or, more usefully, this</p>\n\n<pre><code>for d in generate_documents( document_nodes ):\n ... process the document ...\n</code></pre>\n\n<p>Which never actually creates a list object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T15:24:44.153", "Id": "3596", "ParentId": "3593", "Score": "4" } } ]
<p>I was wondering if this code can be coded better in terms of semantics or design. Should I return the LOS as numbers? should I have the constants be read from the db in case the user or I want to change them in the future?</p> <pre><code>def get_LOS(headway = None, frequency = None, veh_per_hr = None): if frequency != None and headway = veh_per_hr == None: headway = 1 / frequency if headway!= None or veh_per_hr != None: if headway 10 &lt; or veh_per_hr &gt; 6: return 'A' elif 10 &lt;= headway &lt; 15 or 5 &lt; veh_per_hr &lt;= 6: return 'B' elif 15 &lt;= headway &lt; 20 or 3 &lt; veh_per_hr &lt;= 5: return 'C' elif 20 &lt;= headway &lt; 31 or 2 &lt; veh_per_hr &lt;= 3: return 'D' elif 31 &lt;= headway &lt; 60 or 1 &lt;= veh_per_hr &lt; 2: return 'E' elif headway &gt;= 60 or veh_per_hr &lt; 1: return 'F' else: return 'Error' </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T21:20:47.117", "Id": "5515", "Score": "1", "body": "Edit so that the code is readable and correct. Also you might want to explain a little more about what get_LOS is actually trying to accomplish and what the values 'A' - 'F' mean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T21:20:59.290", "Id": "5530", "Score": "2", "body": "This code can't run in this form. `headway = veh_per_hr == None` is illegal as is `headway 10 <`. Please be sure that code you want reviewed has a small chance of actually running. And if it doesn't run, please use StackOverflow to find and fix the problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-04T09:29:19.120", "Id": "376989", "Score": "0", "body": "The current question title is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
{ "AcceptedAnswerId": "3654", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T19:46:56.183", "Id": "3650", "Score": "3", "Tags": [ "python" ], "Title": "Simple Function in python" }
3650
accepted_answer
[ { "body": "<pre><code>def get_LOS(headway = None, frequency = None, veh_per_hr = None):\n</code></pre>\n\n<p>You have no docstring. That would helpful in explaining what the parameters are doing.</p>\n\n<pre><code> if frequency != None and headway = veh_per_hr == None:\n</code></pre>\n\n<p>When checking wheter something is none it is best to use <code>is None</code> or <code>is not None</code></p>\n\n<pre><code> headway = 1 / frequency\n</code></pre>\n\n<p>The problem is that if someone passes frequency along with one of the other parameters, this function will go merrily onwards and probably not even produce an error. I recommend having a get_LOS_from_frequency function which takes the frequency and then calls this function.</p>\n\n<pre><code> if headway!= None or veh_per_hr != None:\n if headway 10 &lt; or veh_per_hr &gt; 6:\n</code></pre>\n\n<p>I'm pretty sure that won't compile</p>\n\n<pre><code> return 'A'\n elif 10 &lt;= headway &lt; 15 or 5 &lt; veh_per_hr &lt;= 6:\n return 'B'\n elif 15 &lt;= headway &lt; 20 or 3 &lt; veh_per_hr &lt;= 5:\n return 'C'\n elif 20 &lt;= headway &lt; 31 or 2 &lt; veh_per_hr &lt;= 3:\n return 'D'\n elif 31 &lt;= headway &lt; 60 or 1 &lt;= veh_per_hr &lt; 2:\n return 'E'\n elif headway &gt;= 60 or veh_per_hr &lt; 1:\n return 'F'\n</code></pre>\n\n<p>I'd store these values in a list which makes it easy to pull them from configuration at a later date if neccesary.</p>\n\n<pre><code> else:\n return 'Error'\n</code></pre>\n\n<p>Don't report error by returning strings. Throw an exception, or at least assert False.</p>\n\n<p>How I'd do this:</p>\n\n<pre><code>import bisect\ndef get_los_from_frequency(frequency):\n return get_los(1 / frequency)\n\nHEADWAY_LIMITS = [10, 15, 20, 31, 60]\nVEH_PER_HR_LIMITS = [1,2,3,5,6]\nGRADES = \"ABCDEF\"\n\ndef get_los(headway = None, veh_per_hr = None):\n if headway is None:\n headway_score = len(GRADES)\n else:\n headway_score = bisect.bisect_left(HEADWAY_LIMITS, headway)\n\n if veh_pr_hr is None:\n veh_pr_hr_score = len(GRADES)\n else:\n veh_pr_hr_score = len(GRADES) - bisect.bisect_left(VEH_PR_HR_LIMITS, veh_pr_hr)\n\n return GRADES[min(headway_score, veh_pr_hr_score)]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T11:31:03.267", "Id": "5519", "Score": "0", "body": "This was very helpful especially with the bisect and lists :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T04:02:37.330", "Id": "3654", "ParentId": "3650", "Score": "8" } } ]
<p>I was wondering if this code can be coded better in terms of semantics or design. Should I return the LOS as numbers? should I have the constants be read from the db in case the user or I want to change them in the future?</p> <pre><code>def get_LOS(headway = None, frequency = None, veh_per_hr = None): if frequency != None and headway = veh_per_hr == None: headway = 1 / frequency if headway!= None or veh_per_hr != None: if headway 10 &lt; or veh_per_hr &gt; 6: return 'A' elif 10 &lt;= headway &lt; 15 or 5 &lt; veh_per_hr &lt;= 6: return 'B' elif 15 &lt;= headway &lt; 20 or 3 &lt; veh_per_hr &lt;= 5: return 'C' elif 20 &lt;= headway &lt; 31 or 2 &lt; veh_per_hr &lt;= 3: return 'D' elif 31 &lt;= headway &lt; 60 or 1 &lt;= veh_per_hr &lt; 2: return 'E' elif headway &gt;= 60 or veh_per_hr &lt; 1: return 'F' else: return 'Error' </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T21:20:47.117", "Id": "5515", "Score": "1", "body": "Edit so that the code is readable and correct. Also you might want to explain a little more about what get_LOS is actually trying to accomplish and what the values 'A' - 'F' mean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T21:20:59.290", "Id": "5530", "Score": "2", "body": "This code can't run in this form. `headway = veh_per_hr == None` is illegal as is `headway 10 <`. Please be sure that code you want reviewed has a small chance of actually running. And if it doesn't run, please use StackOverflow to find and fix the problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-04T09:29:19.120", "Id": "376989", "Score": "0", "body": "The current question title is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
{ "AcceptedAnswerId": "3654", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T19:46:56.183", "Id": "3650", "Score": "3", "Tags": [ "python" ], "Title": "Simple Function in python" }
3650
accepted_answer
[ { "body": "<pre><code>def get_LOS(headway = None, frequency = None, veh_per_hr = None):\n</code></pre>\n\n<p>You have no docstring. That would helpful in explaining what the parameters are doing.</p>\n\n<pre><code> if frequency != None and headway = veh_per_hr == None:\n</code></pre>\n\n<p>When checking wheter something is none it is best to use <code>is None</code> or <code>is not None</code></p>\n\n<pre><code> headway = 1 / frequency\n</code></pre>\n\n<p>The problem is that if someone passes frequency along with one of the other parameters, this function will go merrily onwards and probably not even produce an error. I recommend having a get_LOS_from_frequency function which takes the frequency and then calls this function.</p>\n\n<pre><code> if headway!= None or veh_per_hr != None:\n if headway 10 &lt; or veh_per_hr &gt; 6:\n</code></pre>\n\n<p>I'm pretty sure that won't compile</p>\n\n<pre><code> return 'A'\n elif 10 &lt;= headway &lt; 15 or 5 &lt; veh_per_hr &lt;= 6:\n return 'B'\n elif 15 &lt;= headway &lt; 20 or 3 &lt; veh_per_hr &lt;= 5:\n return 'C'\n elif 20 &lt;= headway &lt; 31 or 2 &lt; veh_per_hr &lt;= 3:\n return 'D'\n elif 31 &lt;= headway &lt; 60 or 1 &lt;= veh_per_hr &lt; 2:\n return 'E'\n elif headway &gt;= 60 or veh_per_hr &lt; 1:\n return 'F'\n</code></pre>\n\n<p>I'd store these values in a list which makes it easy to pull them from configuration at a later date if neccesary.</p>\n\n<pre><code> else:\n return 'Error'\n</code></pre>\n\n<p>Don't report error by returning strings. Throw an exception, or at least assert False.</p>\n\n<p>How I'd do this:</p>\n\n<pre><code>import bisect\ndef get_los_from_frequency(frequency):\n return get_los(1 / frequency)\n\nHEADWAY_LIMITS = [10, 15, 20, 31, 60]\nVEH_PER_HR_LIMITS = [1,2,3,5,6]\nGRADES = \"ABCDEF\"\n\ndef get_los(headway = None, veh_per_hr = None):\n if headway is None:\n headway_score = len(GRADES)\n else:\n headway_score = bisect.bisect_left(HEADWAY_LIMITS, headway)\n\n if veh_pr_hr is None:\n veh_pr_hr_score = len(GRADES)\n else:\n veh_pr_hr_score = len(GRADES) - bisect.bisect_left(VEH_PR_HR_LIMITS, veh_pr_hr)\n\n return GRADES[min(headway_score, veh_pr_hr_score)]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T11:31:03.267", "Id": "5519", "Score": "0", "body": "This was very helpful especially with the bisect and lists :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T04:02:37.330", "Id": "3654", "ParentId": "3650", "Score": "8" } } ]
<p>I have a NumPy array of about 2500 data points. This function is called on a rolling basis where 363 data points is passed at a time.</p> <pre><code>def fcn(data): a = [data[i]/np.mean(data[i-2:i+1])-1 for i in range(len(data)-1, len(data)-362, -1)] return a </code></pre> <p>This takes about 5 seconds to run. I think the bottleneck is the list slicing. Any thoughts on how to speed this up?</p>
[]
{ "AcceptedAnswerId": "3827", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T18:29:16.250", "Id": "3808", "Score": "2", "Tags": [ "python", "array", "numpy" ], "Title": "Rolling loop with an array of data points" }
3808
accepted_answer
[ { "body": "<p><code>range</code> returns a list. You could use <code>xrange</code> instead.</p>\n\n<blockquote>\n<pre><code>range([start,] stop[, step]) -&gt; list of integers\n</code></pre>\n \n <p>Return a list containing an arithmetic progression of integers.</p>\n</blockquote>\n\n<p>vs</p>\n\n<blockquote>\n<pre><code>xrange([start,] stop[, step]) -&gt; xrange object\n</code></pre>\n \n <p>Like <code>range()</code>, but instead of returning a list, returns an object that\n generates the numbers in the range on demand. For looping, this is \n slightly faster than <code>range()</code> and more memory efficient.</p>\n</blockquote>\n\n<p>The other thing that strikes me is the slice in the argument to <code>np.mean</code>. The slice is always of length 3. Assuming this is an arithmetic mean, you could turn the division into</p>\n\n<pre><code>(3.0 * data[i] / (data[i - 2] + data[i - 1] + data[i]))\n</code></pre>\n\n<p>So putting it together</p>\n\n<pre><code>def fcn(data):\n return [(3.0 * data[i] / (data[i - 2] + data[i - 1] + data[i])) - 1\n for i in xrange(len(data) - 1, len(data) - 362, -1)]\n</code></pre>\n\n<p>and you could further optimize the sum of last three values by recognizing that if</p>\n\n<pre><code>x = a[n] + a[n+1] + a[n+2]\n</code></pre>\n\n<p>and you have already computed</p>\n\n<pre><code>y = a[n - 1] + a[n] + a[n + 1]\n</code></pre>\n\n<p>then</p>\n\n<pre><code>x = y + (a[n - 1] - a[n + 2])\n</code></pre>\n\n<p>which helps whenever a local variable access and assignment is faster than accessing an element in a series.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T00:46:58.697", "Id": "5770", "Score": "0", "body": "This is great feedback. Your version of fcn runs in half the time as using np.mean!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T23:46:51.160", "Id": "3827", "ParentId": "3808", "Score": "4" } } ]
<p>I've been seeking to optimize this algorithm, perhaps by eliminating one of the loops, or with a better test to check for prime numbers.</p> <p>I'm trying to calculate and display 100000 prime numbers has the script pausing for about 6 seconds as it populates the list with primes before the primes list is returned to the console as output.</p> <p>I've been experimenting with using</p> <pre><code>print odd, </code></pre> <p>to simply print every found prime number, which is faster for smaller inputs like n = 1000, but for n = 1000000 the list itself prints much faster (both in the Python shell and in the console).</p> <p>Perhaps the entire code/algorithm should be revamped, but the script should remain essentially the same: The user types in the number of prime numbers to be printed (n) and the script returns all prime numbers up to the nth prime number.</p> <pre><code>from time import time odd = 1 primes = [2] n = input("Number of prime numbers to print: ") clock = time() def isPrime(number): global primes for i in primes: if i*i &gt; number: return True if number%i is 0: return False while len(primes) &lt; n: odd += 2 if isPrime(odd): primes += [odd] print primes clock -= time() print "\n", -clock raw_input() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T18:10:55.187", "Id": "5787", "Score": "3", "body": "Take a look at http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes for ideas." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T03:48:57.560", "Id": "3833", "Score": "4", "Tags": [ "python", "optimization", "algorithm", "beginner", "primes" ], "Title": "Optimizing this 'print up to the nth prime number' script" }
3833
max_votes
[ { "body": "<p>Welcome to programming and code review!</p>\n\n<p>Your code is pretty good especially for a beginner, but I'm going to be picky:</p>\n\n<pre><code>from time import time\n</code></pre>\n\n<p>I recommend putting at least one blank line between the imports and the code proper</p>\n\n<pre><code>odd = 1\n</code></pre>\n\n<p>You don't use this until much later. Don't declare variables until you actually need them. It will make the code easier to read.</p>\n\n<pre><code>primes = [2]\nn = input(\"Number of prime numbers to print: \")\n</code></pre>\n\n<p>Rather than using input, I recommend using int(raw_input(. Input actually interprets the text entered as a python expression which means it can do anything. If you really just wanted a number, using int(raw_input is better. Also, input has been modified in python 3 to be like raw_input.</p>\n\n<pre><code>clock = time()\ndef isPrime(number):\n</code></pre>\n\n<p>Typically functions are defined before the actual code not in the middle of it.</p>\n\n<pre><code> global primes\n</code></pre>\n\n<p>global is only necessary if you want to modify the primes. Since you don't modify it, you don't need it. </p>\n\n<pre><code> for i in primes:\n if i*i &gt; number:\n</code></pre>\n\n<p>It's not immediately obvious why you can stop here. A comment would be helpful.</p>\n\n<pre><code> return True\n if number%i is 0:\n</code></pre>\n\n<p>Put spaces around your operators: %</p>\n\n<pre><code> return False\nwhile len(primes) &lt; n:\n odd += 2\n if isPrime(odd):\n primes += [odd]\n</code></pre>\n\n<p>When adding a single element to a list use primes.append(odd)</p>\n\n<pre><code>print primes\nclock -= time()\n</code></pre>\n\n<p>That's kinda confusing. I'd suggest doing start_time = .., end_time = ..., time_spent = end_time - start_time. That ways it clear what you are doing, whereas what you've done with the clock is unusual and not immeadiately obvious.</p>\n\n<pre><code>print \"\\n\", -clock\nraw_input()\n</code></pre>\n\n<p>Also, don't put logic in the top level scope of your program. Put all logic especially loops inside a function. It'll run faster in the function, and will keep the program neater.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T06:25:49.057", "Id": "3835", "ParentId": "3833", "Score": "7" } } ]
<p>I have designed this model which is very flexible. For example, you can create asset types, assets and combinations of them infinitely. It is the front end to a Python Pyramid website, so all the validation and business logic is handled by the web app.</p> <p>However, not being a db guy, I have this sneaking suspicion that the schema totally sucks. There may be performance issues etc that I haven't foreseen etc.</p> <pre><code>class Asset(Entity): has_field('TimeStamp', Unicode, nullable=False) has_field('Modified', Unicode) belongs_to('AssetType', of_kind='AssetType', inverse='Assets') has_many('Values', of_kind='Value', inverse='Asset') Assets = ManyToMany('Asset') @property def Label(self): if self.AssetType: for f in self.AssetType.Fields: if f.Label: if self.Values: for v in self.Values: if v.Field.Name == f.Name: return v.Value def __repr__(self): return '&lt;Asset | %s&gt;' % self.id class AssetType(Entity): has_field('Name', Unicode, primary_key=True) has_field('Plural', Unicode) has_many('Assets', of_kind='Asset', inverse='AssetType') has_many('Fields', of_kind='Field', inverse='AssetType') class Value(Entity): has_field('Value', Unicode) belongs_to('Asset', of_kind='Asset', inverse='Values') belongs_to('Field', of_kind='Field', inverse='Values') class Field(Entity): has_field('Name', Unicode) has_field('Unique', Unicode, default=False) has_field('Label', Boolean, default=False) has_field('Searchable', Boolean, default=False) has_field('Required', Boolean, default=False) has_many('Values', of_kind='Value', inverse='Field') belongs_to('FieldType', of_kind='FieldType', inverse='Fields') belongs_to('AssetType', of_kind='AssetType', inverse='Fields') class FieldType(Entity): has_field('Name', Unicode, primary_key=True) has_field('Label', Unicode, unique=True) has_many('Fields', of_kind='Field', inverse='FieldType') </code></pre>
[]
{ "AcceptedAnswerId": "3890", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-05T01:04:52.997", "Id": "3888", "Score": "3", "Tags": [ "python", "pyramid" ], "Title": "Elixir db model" }
3888
accepted_answer
[ { "body": "<p>You've reinvented a database inside a database. Basically, the Asset/AssetType is a simulation of a database inside a database which will as a result be slow. Also, you are going to spend a lot of effort reimplementing database features.</p>\n\n<p>You could do this by using a NoSQL database which is designed to handle less structured data might be a good idea. Or you could create a table for each asset type which will perform better. </p>\n\n<pre><code>@property \ndef Label(self):\n if self.AssetType:\n for f in self.AssetType.Fields:\n if f.Label:\n if self.Values:\n for v in self.Values:\n if v.Field.Name == f.Name:\n return v.Value\n</code></pre>\n\n<p>That's really nested which is bad sign. I suggest something like:</p>\n\n<pre><code>@property\ndef Label(self):\n if self.AssetType:\n label = self.AssetType.Label\n field = self.find_field(label)\n if field:\n return field.Value\n</code></pre>\n\n<p>Or if you use the Null Object pattern:</p>\n\n<pre><code>@property\ndef Label(self):\n return self.find_field(self.AssetType.label).Value\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-05T04:37:00.070", "Id": "5829", "Score": "0", "body": "Thanks @Winston, you're right about the db in the db idea. I'm a bit scared of locking the schema because the business rules here are changing rapidly. I had a look at CouchDB which is very flexible, but I can't get my head around map/reduce. I'll take a look at NoSQL. Failing that, I think I'll take your advice and just structure it. Thanks for the rewrites above too, I learned a lot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-07T22:26:57.017", "Id": "5916", "Score": "0", "body": "ok CouchDB IS NoSQL... and it's documentation has come a long way since I first looked into it. CouchDB is exactly what I need for a db in this case, and as it turns out, it will probably suffice as a web server too. Woot!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-10T12:52:12.193", "Id": "5997", "Score": "0", "body": "@MFB, The fact that your business rules are changing shouldn't drive you to NoSQL. In that case, I'm just going to constantly update the schema." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-11T13:22:14.247", "Id": "6036", "Score": "0", "body": "you're right. It's not my only reason for looking at Couch. The more I look at Couch though, the more sense it makes to me, for this application at least. Almost everything in my business model can be described as an asset (or Document). The flexibility to continually add and subtract keys is just a huge bonus." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-05T03:24:49.977", "Id": "3890", "ParentId": "3888", "Score": "3" } } ]
<p>I need to get this program reviewed. It is counting the lines of code in all files in the given directory. </p> <p>I'm new to python and need some advice on pretty much everything.</p> <pre><code>#!/usr/bin/python import os import sys def CountFile(f): counter = 0 f = open(f, "r") for line in f.read().split('\n'): counter = counter + 1 f.close() return counter def CountDir(dirname): counter = 0 for f in os.listdir(dirname): fa = os.path.join(dirname, f) if os.path.isdir(fa): dcount = CountDir(fa) counter = counter + dcount else: fcount = CountFile(fa) counter = counter + fcount return counter print CountDir(sys.argv[1]) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T21:15:54.457", "Id": "68626", "Score": "2", "body": "What was wrong with `wc -l *`?" } ]
{ "AcceptedAnswerId": "4289", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T17:53:12.863", "Id": "4286", "Score": "4", "Tags": [ "python" ], "Title": "Program to count the number of lines of code" }
4286
accepted_answer
[ { "body": "<p>First a small nitpick: in python the prevailing naming convention for function names is all lowercase, with words separated by underscores. So <code>CountFile</code> should be <code>count_file</code>, or even better would be something like <code>count_lines</code>, since <code>count_file</code> doesn't really explain what the function does.</p>\n\n<p>Now in <code>CountFile</code>, you read the file using <code>f.read()</code> then <code>split</code> on newlines. This isn't really necessary -- for one thing because file objects have a method called <code>readlines</code> which returns a list of the lines, but more importantly because file objects are iterable, and iterating over them is equivalent to iterating over the lines. So <code>for line in f.read().split('\\n'):</code> is equivalent to <code>for line in f:</code>, but the latter is better because when you call <code>read()</code> you actually read the entire contents of the file into memory, whereas <code>for line in f:</code> reads the lines one at a time. It's also the idiomatic way to go about reading a file line by line.</p>\n\n<p>If you're not concerned about memory, however, then because <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">flat is better than nested</a> you can do away with the explicit for loop and just call <code>len</code> on your list of lines. The entire function could be <code>return len(open(f, 'r').readlines())</code> (but this isn't really advisable in the general case because of the memory thing). You could also use a <a href=\"http://docs.python.org/reference/expressions.html#generator-expressions\" rel=\"nofollow\">generator expression</a> and write <code>return sum(1 for line in f)</code>.</p>\n\n<p>Now notice that in <code>CountFile</code>, you write <code>f = open(f, \"r\")</code> to open a file, then later you write <code>f.close()</code> -- this kind of pattern is what <a href=\"http://docs.python.org/whatsnew/2.5.html#pep-343\" rel=\"nofollow\">context managers and the <code>with</code> statement</a> were introduced for. The context manager protocol is already conveniently implemented for file objects, so you could write:</p>\n\n<pre><code>counter = 0\nwith open(f, 'r') as f:\n for line in f:\n counter += 1\n</code></pre>\n\n<p>And you wouldn't need to explicitly close the file. This may not seem like such a big deal in this case, and it isn't really, but <code>with</code> statements are a convenient way to ensure you that you only use resources (like files, or database connections, or anything like that) just as long as you need to. (Also, allocating and later freeing a resource might be a lot more involved than just calling <code>open</code> and <code>close</code> on it, and you might have to worry about what happens if something goes wrong while you're using the resource (using <code>try... finally</code>)... Hiding that behind a <code>with</code> statement makes for much more readable code because you can focus on what you're trying to accomplish instead of details like that.)</p>\n\n<p>Your <code>CountDir</code> function looks mostly okay. You might look into using <a href=\"http://docs.python.org/library/os.html#os.walk\" rel=\"nofollow\"><code>os.walk</code></a> instead of <code>os.listdir</code> so you won't need to check for directories -- it would look something like</p>\n\n<pre><code>for root, _, files in os.walk(dirname):\n for f in files:\n count += CountFile(os.path.join(root, f))\n</code></pre>\n\n<p>(The <code>_</code> doesn't have any special meaning, it just by convention means that we won't be using that variable.) Another advantage of <code>os.walk</code> is that by default it doesn't follow symlinks, whereas <code>listdir</code> doesn't care, so if you don't explicitly check for symlinks you might end up counting things twice.</p>\n\n<p>If you stick with <code>os.listdir</code>, you could still make your code a bit cleaner by using a <a href=\"http://docs.python.org/whatsnew/2.5.html#pep-308-conditional-expressions\" rel=\"nofollow\">conditional expression</a>, which would look like:</p>\n\n<pre><code>counter += CountDir(fa) if os.path.isdir(fa) else CountFile(fa)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T19:04:45.220", "Id": "4289", "ParentId": "4286", "Score": "4" } } ]
<p>I have written this implementation of Huffman coding. Please suggest ways to make this code better, i.e. more Pythonic.</p> <pre><code>from collections import Counter ##################################################################### class Node(object): def __init__(self, pairs, frequency): self.pairs = pairs self.frequency = frequency def __repr__(self): return repr(self.pairs) + ", " + repr(self.frequency) def merge(self, other): total_frequency = self.frequency + other.frequency for p in self.pairs: p[1] = "1" + p[1] for p in other.pairs: p[1] = "0" + p[1] new_pairs = self.pairs + other.pairs return Node(new_pairs, total_frequency) ##################################################################### def huffman_codes(s): frequency_table = Counter(s) initial_table = [] for k, v in frequency_table.items(): initial_table.append([k, v]) initial_table = sorted(initial_table, key = lambda p : p[1]) # print(initial_table) table = [] for entry in initial_table: ch = entry[0] freq = entry[1] table.append(Node([[ch, ""]], freq)) # print(table) while len(table) &gt; 1: first_node = table.pop(0) second_node = table.pop(0) new_node = first_node.merge(second_node) table.append(new_node) table = sorted(table, key = lambda n : n.frequency) # print(table) return dict(map(lambda p: (p[0], p[1]), table[0].pairs)) ##################################################################### print(huffman_codes('yashaswita')) </code></pre> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T14:44:01.500", "Id": "6418", "Score": "2", "body": "Also, if you want to compare methods, there is an early version of a Huffman coding module I wrote as an exercise [on pastebin](http://pastebin.com/QEK3WdbE). The core is the same as what I ended up with, but it ended up getting significantly refactored and simplified." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-22T01:42:24.023", "Id": "6424", "Score": "1", "body": "\"pythonic\" rocks" } ]
{ "AcceptedAnswerId": "4293", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T12:58:13.197", "Id": "4290", "Score": "8", "Tags": [ "python", "algorithm" ], "Title": "Is there a better way to implement this Huffman Algorithm in Python?" }
4290
accepted_answer
[ { "body": "<p>I agree with <code>agf</code> except for point 4.\nThis is my try on your code:</p>\n\n<pre><code>from collections import Counter\nimport heapq\n\nclass Node(object):\n def __init__(self, pairs, frequency):\n self.pairs = pairs\n self.frequency = frequency\n\n def __repr__(self):\n return repr(self.pairs) + \", \" + repr(self.frequency)\n\n def merge(self, other):\n total_frequency = self.frequency + other.frequency\n for p in self.pairs:\n p[1] = \"1\" + p[1]\n for p in other.pairs:\n p[1] = \"0\" + p[1]\n new_pairs = self.pairs + other.pairs\n return Node(new_pairs, total_frequency)\n\n def __lt__(self, other):\n return self.frequency &lt; other.frequency\n\ndef huffman_codes(s):\n table = [Node([[ch, '']], freq) for ch, freq in Counter(s).items()]\n heapq.heapify(table)\n while len(table) &gt; 1:\n first_node = heapq.heappop(table)\n second_node = heapq.heappop(table)\n new_node = first_node.merge(second_node)\n heapq.heappush(table, new_node)\n return dict(table[0].pairs)\n\nprint(huffman_codes('yashaswita'))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T14:18:26.280", "Id": "6422", "Score": "2", "body": "Nice, (I'm out of votes), but you actually did exactly what I did in #4 except for not needing to sort because you added the `heapq`, and better variable naming." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T14:10:23.720", "Id": "4293", "ParentId": "4290", "Score": "7" } } ]
<p>I have written this implementation of Huffman coding. Please suggest ways to make this code better, i.e. more Pythonic.</p> <pre><code>from collections import Counter ##################################################################### class Node(object): def __init__(self, pairs, frequency): self.pairs = pairs self.frequency = frequency def __repr__(self): return repr(self.pairs) + ", " + repr(self.frequency) def merge(self, other): total_frequency = self.frequency + other.frequency for p in self.pairs: p[1] = "1" + p[1] for p in other.pairs: p[1] = "0" + p[1] new_pairs = self.pairs + other.pairs return Node(new_pairs, total_frequency) ##################################################################### def huffman_codes(s): frequency_table = Counter(s) initial_table = [] for k, v in frequency_table.items(): initial_table.append([k, v]) initial_table = sorted(initial_table, key = lambda p : p[1]) # print(initial_table) table = [] for entry in initial_table: ch = entry[0] freq = entry[1] table.append(Node([[ch, ""]], freq)) # print(table) while len(table) &gt; 1: first_node = table.pop(0) second_node = table.pop(0) new_node = first_node.merge(second_node) table.append(new_node) table = sorted(table, key = lambda n : n.frequency) # print(table) return dict(map(lambda p: (p[0], p[1]), table[0].pairs)) ##################################################################### print(huffman_codes('yashaswita')) </code></pre> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T14:44:01.500", "Id": "6418", "Score": "2", "body": "Also, if you want to compare methods, there is an early version of a Huffman coding module I wrote as an exercise [on pastebin](http://pastebin.com/QEK3WdbE). The core is the same as what I ended up with, but it ended up getting significantly refactored and simplified." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-22T01:42:24.023", "Id": "6424", "Score": "1", "body": "\"pythonic\" rocks" } ]
{ "AcceptedAnswerId": "4293", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T12:58:13.197", "Id": "4290", "Score": "8", "Tags": [ "python", "algorithm" ], "Title": "Is there a better way to implement this Huffman Algorithm in Python?" }
4290
accepted_answer
[ { "body": "<p>I agree with <code>agf</code> except for point 4.\nThis is my try on your code:</p>\n\n<pre><code>from collections import Counter\nimport heapq\n\nclass Node(object):\n def __init__(self, pairs, frequency):\n self.pairs = pairs\n self.frequency = frequency\n\n def __repr__(self):\n return repr(self.pairs) + \", \" + repr(self.frequency)\n\n def merge(self, other):\n total_frequency = self.frequency + other.frequency\n for p in self.pairs:\n p[1] = \"1\" + p[1]\n for p in other.pairs:\n p[1] = \"0\" + p[1]\n new_pairs = self.pairs + other.pairs\n return Node(new_pairs, total_frequency)\n\n def __lt__(self, other):\n return self.frequency &lt; other.frequency\n\ndef huffman_codes(s):\n table = [Node([[ch, '']], freq) for ch, freq in Counter(s).items()]\n heapq.heapify(table)\n while len(table) &gt; 1:\n first_node = heapq.heappop(table)\n second_node = heapq.heappop(table)\n new_node = first_node.merge(second_node)\n heapq.heappush(table, new_node)\n return dict(table[0].pairs)\n\nprint(huffman_codes('yashaswita'))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T14:18:26.280", "Id": "6422", "Score": "2", "body": "Nice, (I'm out of votes), but you actually did exactly what I did in #4 except for not needing to sort because you added the `heapq`, and better variable naming." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-21T14:10:23.720", "Id": "4293", "ParentId": "4290", "Score": "7" } } ]
<p>I wrote this program which finds the definite integral of a function. Where in the program could I optimize this code:</p> <pre><code>def trapezium(f,n,a,b): h=(b-a)/float(n) area = (0.5)*h sum_y = (f(0)+f(b)) i=a while i&lt;b: print i sum_y += 2*f(i) i += h area *= sum_y return area def f(x): return x ** 2 print trapezium(f, 10000, 0, 5) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-27T07:46:22.863", "Id": "4426", "Score": "2", "Tags": [ "python" ], "Title": "finding definite integrals in Python using Trapezium rule" }
4426
max_votes
[ { "body": "<p>First, there is an error where you have:</p>\n\n<pre><code>sum_y = (f(0)+f(b))\n</code></pre>\n\n<p>f(0) should be f(a). It doesn't matter on your example, because you start with 0, but would otherwise.</p>\n\n<p>Another error is that you add f(a) 3x instead of just once. i=a+h should be the line before while.</p>\n\n<p>Your while loop makes O(n) multiplications and twice as many additions. Instead you should have something like:</p>\n\n<pre><code>i = a+h\npart_sum = 0\nwhile i&lt;b:\n part_sum += f(i)\n i += h\nsum_y += 2*part_sum\n</code></pre>\n\n<p>Still same number of additions, but only one multiplication.</p>\n\n<p>Using list comprehensions might be a bit faster, but you'd spend too much memory at scale where it matters.</p>\n\n<p>print significantly slows your function. If you actually need to print this, then store intermediate results in array and then print them before final result with print \"\\n\".join(intermediates).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-27T09:37:05.813", "Id": "4430", "ParentId": "4426", "Score": "6" } } ]
<p>In our hg workflow we use <code>default</code> as testing branch and <code>stable</code> as the one that contains stable code. All changes are made in feature-branches that are started from latest <code>stable</code>. This hook checks if there is a "direct" commit to <code>default</code> or <code>stable</code> (they are denied, only merges may change contents of <code>default</code> and <code>stable</code>) or that new feature branch has been started from <code>default</code> (which is denied by conventions too).</p> <p>Any proposal to make it more "pythonic" (or just better)?</p> <pre><code>from mercurial import context def check(ui, repo, hooktype, node=None, source=None, **kwargs): for rev in xrange(repo[node].rev(), len(repo)): ctx = context.changectx(repo, rev) parents = ctx.parents() if len(parents) == 1: if ctx.branch() in ['default', 'stable']: ui.warn('!!! You cannot commit directly to %s at %s !!!' % (ctx.branch(), ctx.hex())) return True if parents[0].branch() == 'default': ui.warn('!!! You cannot start your private branch from default at %s !!!' % (ctx.hex())) return True return False </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-30T12:06:23.923", "Id": "6715", "Score": "0", "body": "The correct word is pythonic not pythonish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-30T12:08:13.743", "Id": "6716", "Score": "0", "body": "@Winston Ewert: fixed ;-)" } ]
{ "AcceptedAnswerId": "4498", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-30T06:57:18.353", "Id": "4494", "Score": "5", "Tags": [ "python" ], "Title": "My python hook for mercurial" }
4494
accepted_answer
[ { "body": "<pre><code> for rev in xrange(repo[node].rev(), len(repo)):\n ctx = context.changectx(repo, rev)\n</code></pre>\n\n<p>In Python, I generally try to avoid iterating using xrange. I prefer to iterate over what I'm interested in.</p>\n\n<pre><code>def revisions(repo, start, end):\n for revision_number in xrange(start, end):\n yield context.changectx(repo, revision_number)\n\nfor rev in revisions(repo, repo[node].rev(), len(repo)):\n ...\n</code></pre>\n\n<p>Although I'm not sure its worthwhile in this case. </p>\n\n<p>The only other issue is your use of abbreviations like repo and rev. They aren't that bad because its pretty clear from the context what they stand for. But I'd write them fully out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-31T01:15:21.757", "Id": "6723", "Score": "1", "body": "I think you mean `for revision_number in xrange(start, end):` in that second snippet." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-30T12:16:05.483", "Id": "4498", "ParentId": "4494", "Score": "5" } } ]
<p>The following code is a quick implementation since I only needed 3 random images sorted by category (a random eyes image, a random nose image and a random mouth image and then combine them):</p> <pre><code> fileinfos = FileInfo.all().filter("category =", "eyes") fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)] url = images.get_serving_url(str(fileinfo.blob.key()), size=420) fileinfos = FileInfo.all().filter("category =", "nose") fileinfo2 = fileinfos[random.randint(0, fileinfos.count()-1)] url2 = images.get_serving_url(str(fileinfo2.blob.key()), size=420) fileinfos = FileInfo.all().filter("category =", "mouth") fileinfo3 = fileinfos[random.randint(0, fileinfos.count()-1)] url3 = images.get_serving_url(str(fileinfo3.blob.key()), size=420) </code></pre> <p>This case is somewhat specific since the number of selection are fixed to 3. Surely iteration or a function to do this is preferred and <code>memcache</code> would also increase response time since there are not many files and the same file gets chosen sometimes then I'd like to use <code>memcache</code> and it seems <code>memcache</code> can cache the results from <code>get_serving_url</code> so I could cache the <code>fileinfos</code> or the results from <code>get_serving_url</code>. I know <code>memcache</code> is limited in memory.</p> <pre><code> def get_memcached_serving_url(fileinfo): from google.appengine.api import memcache memcache_key = "blob_%d" % fileinfo.blob.key() data = memcache.get(memcache_key) if data is not None: return data </code></pre> <p>And I think I can't cache the blob itself and only the result from <code>get_serving_url</code> while it is the trip to the datastore that supposedly takes time.</p> <p>Please tell me any thoughts or opinions about this quick prototyping how to get random elements while hoping to cache elements since the number of elements is still not very large (&lt;100 elements and if the same is chosen twice then I'd like a fast and preferably cached response)</p> <p>If you want you can have a look at the actual application here.</p>
[]
{ "AcceptedAnswerId": "4540", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-01T23:09:04.013", "Id": "4538", "Score": "0", "Tags": [ "python", "image", "cache", "google-app-engine" ], "Title": "Iteration and memcache for selected categorized random elements" }
4538
accepted_answer
[ { "body": "<p>Regarding image caching, <a href=\"https://stackoverflow.com/questions/1380431/caching-images-in-memcached\">this seems relevant</a>.</p>\n\n<p>Secondly, <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> this code up, it'll make your code more maintainable: </p>\n\n<pre><code>fileinfos = FileInfo.all().filter(\"category =\", \"eyes\")\nfileinfo = fileinfos[random.randint(0, fileinfos.count()-1)] \nurl = images.get_serving_url(str(fileinfo.blob.key()), size=420)\n</code></pre>\n\n<p>Should have it's own function (forgive my py):</p>\n\n<pre><code>def get_random_image_url(category)\n fileinfos = FileInfo.all().filter(\"category =\", category)\n fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)] \n return images.get_serving_url(str(fileinfo.blob.key()), size=420)\n\neyes_url = get_random_image_url(\"eyes\")\nnose_url = get_random_image_url(\"nose\")\nmouth_url = get_random_image_url(\"mouth\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-02T23:24:17.500", "Id": "6807", "Score": "1", "body": "Thank you for the important help with structuring it to a function. Thank you also for the link with the important insight when not to use memcache." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-02T01:31:58.200", "Id": "4540", "ParentId": "4538", "Score": "2" } } ]
<p>I've written this small class in Python that wraps bound methods but does not prevent the deletion of self.</p> <ol> <li>Do you have any thoughts on my code?</li> <li>Do you think I handle errors appropriately?</li> <li>Is it missing anything?</li> <li>What should be done to make it more robust?</li> <li>Is the documentation clear enough?</li> </ol> <p></p> <pre><code>import weakref class WeakBoundMethod: """ Wrapper around a method bound to a class instance. As opposed to bare bound methods, it holds only a weak reference to the `self` object, allowing it to be deleted. This can be useful when implementing certain kinds of systems that manage callback functions, such as an event manager. """ def __init__(self, meth): """ Initializes the class instance. It should be ensured that methods passed through the `meth` parameter are always bound methods. Static methods and free functions will produce an `AssertionError`. """ assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\ 'Object is not a bound method.' self._self = weakref.ref(meth.__self__) self._func = meth.__func__ def __call__(self, *args, **kw): """ Calls the bound method and returns whatever object the method returns. Any arguments passed to this will also be forwarded to the method. In case an exception is raised by the bound method, it will be caught and thrown again to the caller of this `WeakBoundMethod` object. Calling this on objects that have been collected will result in an `AssertionError` being raised. """ assert self.alive(), 'Bound method called on deleted object.' try: return self._func(self._self(), *args, **kw) except Exception, e: raise e def alive(self): """ Checks whether the `self` object the method is bound to has been collected. """ return self._self() is not None </code></pre>
[]
{ "AcceptedAnswerId": "4579", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-04T06:32:31.290", "Id": "4574", "Score": "4", "Tags": [ "python", "classes", "weak-references" ], "Title": "Wrapping bound methods" }
4574
accepted_answer
[ { "body": "<pre><code>class WeakBoundMethod:\n</code></pre>\n\n<p>I suggest making it a new-style class by inheriting from object.</p>\n\n<pre><code> assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\\\n 'Object is not a bound method.'\n</code></pre>\n\n<p>Don't do this. Just let the invalid parameter types raise attribute errors when you try to fetch the <code>__func__</code> and <code>__self__</code>. You don't gain anything by checking them beforehand.</p>\n\n<pre><code>assert self.alive(), 'Bound method called on deleted object.'\n</code></pre>\n\n<p>Raising an Assertion here is a bad choice. Assertions are for thing that should never happen, but having the underlying self object cleaned up doesn't really count. Raise an exception like weakref.ReferenceError. That way a caller can reasonably catch the error.</p>\n\n<p>The documentation is very clear, well done.</p>\n\n<p><strong>EDIT</strong></p>\n\n<pre><code> try:\n return self._func(self._self(), *args, **kw)\n except Exception as e:\n raise e\n</code></pre>\n\n<p>Why are you catching an exception only to rethrow it? That's really pointless.</p>\n\n<p>I'd write the whole function as:</p>\n\n<pre><code>def __call__(self, *args, **kw):\n _self = self._self()\n if _self is None:\n raise weakref.ReferenceError()\n\n return self._func(_self, *args, **kw)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-04T13:16:17.097", "Id": "4579", "ParentId": "4574", "Score": "3" } } ]
<p>I've written this small class in Python that wraps bound methods but does not prevent the deletion of self.</p> <ol> <li>Do you have any thoughts on my code?</li> <li>Do you think I handle errors appropriately?</li> <li>Is it missing anything?</li> <li>What should be done to make it more robust?</li> <li>Is the documentation clear enough?</li> </ol> <p></p> <pre><code>import weakref class WeakBoundMethod: """ Wrapper around a method bound to a class instance. As opposed to bare bound methods, it holds only a weak reference to the `self` object, allowing it to be deleted. This can be useful when implementing certain kinds of systems that manage callback functions, such as an event manager. """ def __init__(self, meth): """ Initializes the class instance. It should be ensured that methods passed through the `meth` parameter are always bound methods. Static methods and free functions will produce an `AssertionError`. """ assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\ 'Object is not a bound method.' self._self = weakref.ref(meth.__self__) self._func = meth.__func__ def __call__(self, *args, **kw): """ Calls the bound method and returns whatever object the method returns. Any arguments passed to this will also be forwarded to the method. In case an exception is raised by the bound method, it will be caught and thrown again to the caller of this `WeakBoundMethod` object. Calling this on objects that have been collected will result in an `AssertionError` being raised. """ assert self.alive(), 'Bound method called on deleted object.' try: return self._func(self._self(), *args, **kw) except Exception, e: raise e def alive(self): """ Checks whether the `self` object the method is bound to has been collected. """ return self._self() is not None </code></pre>
[]
{ "AcceptedAnswerId": "4579", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-04T06:32:31.290", "Id": "4574", "Score": "4", "Tags": [ "python", "classes", "weak-references" ], "Title": "Wrapping bound methods" }
4574
accepted_answer
[ { "body": "<pre><code>class WeakBoundMethod:\n</code></pre>\n\n<p>I suggest making it a new-style class by inheriting from object.</p>\n\n<pre><code> assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\\\n 'Object is not a bound method.'\n</code></pre>\n\n<p>Don't do this. Just let the invalid parameter types raise attribute errors when you try to fetch the <code>__func__</code> and <code>__self__</code>. You don't gain anything by checking them beforehand.</p>\n\n<pre><code>assert self.alive(), 'Bound method called on deleted object.'\n</code></pre>\n\n<p>Raising an Assertion here is a bad choice. Assertions are for thing that should never happen, but having the underlying self object cleaned up doesn't really count. Raise an exception like weakref.ReferenceError. That way a caller can reasonably catch the error.</p>\n\n<p>The documentation is very clear, well done.</p>\n\n<p><strong>EDIT</strong></p>\n\n<pre><code> try:\n return self._func(self._self(), *args, **kw)\n except Exception as e:\n raise e\n</code></pre>\n\n<p>Why are you catching an exception only to rethrow it? That's really pointless.</p>\n\n<p>I'd write the whole function as:</p>\n\n<pre><code>def __call__(self, *args, **kw):\n _self = self._self()\n if _self is None:\n raise weakref.ReferenceError()\n\n return self._func(_self, *args, **kw)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-04T13:16:17.097", "Id": "4579", "ParentId": "4574", "Score": "3" } } ]
<p>I have the following function:</p> <pre><code>from collections import Counter import itertools def combinationsWithMaximumCombinedIntervals(data, windowWidth, maximumCombinedIntervals): for indices in itertools.combinations(range(len(data)),windowWidth): previous = indices[0] combinedIntervals = 0 for i in indices[1:]: combinedIntervals = combinedIntervals + i-previous-1 if combinedIntervals &gt; maximumCombinedIntervals: break previous = i else: yield(tuple(data[i] for i in indices)) test = ["a","b","c","d","e","f","g","h","i","j","k","l"] combinations = combinationsWithMaximumCombinedIntervals(test, 5, 2) for i in combinations: pass </code></pre> <p>The function is associated with a set of combinations for the data supplied to it. Each element in the list represents a combination with the length of each of these combinations equal to windowLength. </p> <p>If we take the flowing combination ("a","b","c","d","f"), then the combined interval is 1 since "d" to "f" is a hop of 1. If we take the flowing combination ("a","b","c","e","g"), then the combined interval is 2 since "c" to "e" and "e" to "g" are hops of 1 each. Finally, combination ("a","b","c","d","g") has a combined interval of 2 since "d" to "g" is a hop of 2. The maximumCombinedIntervals argument limits the number of combinations based on the combined interval. In other words, this combination is not available when maximumCombinedIntervals is 2: ("a","c","e","f","h") since the combination of hops is now greater than 2.</p> <p>I wish to run this function on data with a length of many thousands, a windowWidth in the order of 10 and a maximumCombinedIntervals under 10. However this takes forever to execute.</p> <p>Can anyone suggest how I might refactor this function so that it will run much more quickly in Python. itertools.combinations is implemented in C.</p> <p>Here is a similar function which I'm also interested in using:</p> <pre><code>def combinationsWithMaximumIntervalSize(data, windowWidth, maximumIntervalSize): maximumIntervalSizePlusOne = maximumIntervalSize+1 for indices in itertools.combinations(range(len(data)),windowWidth): previous = indices[0] for i in indices[1:]: if i-previous&gt;maximumIntervalSizePlusOne: break previous = i else: yield(tuple(data[i] for i in indices)) </code></pre> <p>I'm working in python 3. </p> <hr> <p>Edit: Here's my latest attempt. Any comments?</p> <pre><code>def combinationsWithMaximumCombinedIntervals2(data, combinationWidth, maximumCombinedIntervals): windowWidth = combinationWidth + maximumCombinedIntervals combinations = [] for startingIndex in range(len(data)-windowWidth+1): for indices in itertools.combinations(range(startingIndex, startingIndex+windowWidth), combinationWidth): if not indices in combinations: yield(tuple(data[j] for j in indices)) combinations.append(indices) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-17T12:29:23.873", "Id": "348187", "Score": "0", "body": "Just wondering what on earth `for i in combinations: pass` is actually adding to the code as it seems to be doing nothing." } ]
{ "AcceptedAnswerId": "4687", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T16:57:40.790", "Id": "4682", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "Very slow Python Combination Generator" }
4682
accepted_answer
[ { "body": "<p>As for your actual algorithm, you need to change it. Filtering down python's generating makes things relatively simple. However, in this case you are going throw away way more items then you keep. As a result, this isn't going to be an efficient method.</p>\n\n<p>What I'd try is iterating over all possible starting positions. For each starting position I'd take the next windowWidth+maximumIntervalSize items. Then I'd use itertools.combinations to grab each possible set of maximumIntervalSize items to remove from the list. </p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Review of new code:</p>\n\n<pre><code>def combinationsWithMaximumCombinedIntervals2(data, combinationWidth, maximumCombinedIntervals):\n</code></pre>\n\n<p>The python style guide recommends lowercase_with_underscores for function and parameter names. The name are also just a bit on the longish side. (Which is way better then being too short or cryptic)</p>\n\n<pre><code> windowWidth = combinationWidth + maximumCombinedIntervals\n\n combinations = []\n\n for startingIndex in range(len(data)-windowWidth+1):\n for indices in itertools.combinations(range(startingIndex, startingIndex+windowWidth), combinationWidth):\n</code></pre>\n\n<p>If possible, try to avoid looping over indexes. Code is cleaner if it loops over the data elements.</p>\n\n<pre><code> if not indices in combinations: \n</code></pre>\n\n<p>You use <code>if indices not in combinations</code> for a slightly cleaner expression</p>\n\n<pre><code> yield(tuple(data[j] for j in indices))\n</code></pre>\n\n<p>You don't need the parenthesis for yield, it is a statement not a function.</p>\n\n<pre><code> combinations.append(indices)\n</code></pre>\n\n<p>Combinations would be faster to check if it were a set rather then a list.</p>\n\n<p>But the real question here is how to avoid the duplicates being generated in the first place. We simple restrict the combinations generated to include the startingIndex. This prevents duplicates because no later window can produce the same combinations. (They don't have the startingIndex in them). But it still produces all values because all combinations without the startingIndex will still be contained in the next window. (The next window is the current window except without startingIndex and with an additional value) The only tricky part is the end, when there are no more windows. This is most easily handled by continuing to generate just with a smaller window size for as long as possible.</p>\n\n<p>My solution (tested to make sure it produces the same results as yours, so I don't make any more silly mistakes):</p>\n\n<pre><code>def combinationsWithMaximumCombinedIntervals3(data, combinationWidth, maximumCombinedIntervals):\n windowWidth = combinationWidth + maximumCombinedIntervals\n\n for startingIndex in range(len(data)-combinationWidth+1):\n window = data[startingIndex + 1: startingIndex + windowWidth]\n for indices in itertools.combinations(window, combinationWidth - 1):\n yield (data[startingIndex],) + indices\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T20:35:31.877", "Id": "7273", "Score": "0", "body": "Thanks for your suggestion, I will investigate it. I will get duplicates with your approach - what would be a good way to deal with these? yield(tuple(data[i] for i in indices)) is not equal yield tuple(data). Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T22:38:49.173", "Id": "7282", "Score": "0", "body": "@Baz, sorry about the tuple code, I misread that" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T21:25:38.273", "Id": "4687", "ParentId": "4682", "Score": "4" } } ]
<p>How can I rework the code up that <code>ema(x, 5)</code> returns the data now in <code>emaout</code>? I'm trying to enclose everything in one def.</p> <p>Right now its in a for loop and a def.</p> <pre><code>x = [32.47, 32.70, 32.77, 33.11, 33.25, 33.23, 33.23, 33.0, 33.04, 33.21] def ema(series, period, prevma): smoothing = 2.0 / (period + 1.0) return prevma + smoothing * (series[bar] - prevma) prevema = x[0] emaout =[] for bar, close in enumerate(x): curema = ema(x, 5, prevema) prevema = curema emaout.append(curema) print print emaout </code></pre> <p><code>x</code> could be a NumPy array.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T02:24:57.203", "Id": "4692", "Score": "0", "Tags": [ "python", "numpy" ], "Title": "Moving average of a data series" }
4692
max_votes
[ { "body": "<ol>\n<li>ema uses series in one place, where it references <code>series[bar]</code>. But bar is a global variable which is frowned upon. Let's pass series[bar] instead of series to ema.</li>\n<li>That would be series[bar] in the for loop, but series[bar] is the same thing as close, so let's pass that instead.</li>\n<li>ema's period is only used to calculate smoothing. Let's calculate smoothing outside and pass it in.</li>\n<li>But now ema's a single line, so let's inline it</li>\n<li>Let's put all of that logic inside a function</li>\n<li>We use enumerate in the for loop, but we don't use bar</li>\n</ol>\n\n<p>Result:</p>\n\n<pre><code>x = [32.47, 32.70, 32.77, 33.11, 33.25, 33.23, 33.23, 33.0, 33.04, 33.21]\n\ndef function(x, period):\n prevema = x[0] \n emaout =[]\n\n smoothing = 2.0 / (period + 1.0) \n for close in x:\n curema = prevma + smoothing * (close - prevma) \n prevema = curema\n emaout.append(curema)\n\n return prevema\nprint \nprint function(x, 5)\n</code></pre>\n\n<p>We can better by using numpy. </p>\n\n<pre><code>def function(x, period):\n smoothing = 2.0 / (period + 1.0) \n current = numpy.array(x) # take the current value as a numpy array\n\n previous = numpy.roll(x,1) # create a new array with all the values shifted forward\n previous[0] = x[0] # start with this exact value\n # roll will have moved the end into the beginning not what we want\n\n return previous + smoothing * (current - previous)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:42:32.517", "Id": "7082", "Score": "0", "body": "@ winston the answers dont match." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T17:38:56.520", "Id": "7085", "Score": "0", "body": "@Merlin, I didn't test what I wrote. But hopefully it gives you some idea of how to improve your existing code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T18:15:58.800", "Id": "7090", "Score": "0", "body": "@merlin, `numpy.roll([1,2,3,4], 1) == numpy.array(4,1,2,3)` It shifts all of the elements in the array by one. That way when I subtract the original and rolled arrays I get the difference from one to the next." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T18:16:55.913", "Id": "7091", "Score": "0", "body": "@merlin, you are supposed to @ username of person you are talking to, not @ yourself. You don't need to when commenting on my questions because I am automatically alerted about those" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T18:28:50.050", "Id": "7092", "Score": "0", "body": "@winston...the on numpy.roll, how can you 'roll' only one column in array? tIA" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T18:47:35.533", "Id": "7093", "Score": "0", "body": "@Merlin, I've never needed to. Perhaps you should ask another question with the complete context of what you are now trying to accomplish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T01:17:00.560", "Id": "10407", "Score": "0", "body": "The numpy version here doesn't implement the same algorithm and I don't think it's possible with the constructs shown. The problem is an EMA at index T is calculated based on the EMA at index T-1 (except for T=0 where the EMA must be hard-wired somehow). This explains the usage of the `prevema` value in the non-numpy example. Rolling the input values by 1 doesn't achieve this desired effect. Essentially EMA is a low-pass filter which I'm guessing can be implemented concisely using numpy/scipy, but I haven't found a good example yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T01:35:58.630", "Id": "10408", "Score": "0", "body": "@JoeHolloway, you are right. Apparently I was suffering from brain fog when I wrote this." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T03:29:39.380", "Id": "4694", "ParentId": "4692", "Score": "2" } } ]
<p>The idea is to apply some function on each element in each list, then compare two lists by the value returned by the function.</p> <p>My current solution works but is not fast enough. running "python -m cProfile" gives sth. like:</p> <pre><code> ncalls tottime percall cumtime percall filename:lineno(function) 2412505 13.335 0.000 23.633 0.000 common.py:38(&lt;genexpr&gt;) 285000 5.434 0.000 29.067 0.000 common.py:37(to_dict) 142500 3.392 0.000 35.948 0.000 common.py:3(compare_lists) </code></pre> <p>Here is my code, I would like to know how to optimize it to run faster.</p> <pre><code>import itertools def compare_lists(li1, li2, value_func1=None, value_func2=None): """ Compare *li1* and *li2*, return the results as a list in the following form: [[data seen in both lists], [data only seen in li1], [data only seen in li2]] and [data seen in both lists] contains 2 tuple: [(actual items in li1), (actual items in li2)] * *value_func1* callback function to li1, applied to each item in the list, returning the **logical** value for comparison * *value_func2* callback function to li2, similarly If not supplied, lists will be compared as it is. Usage:: &gt;&gt;&gt; compare_lists([1, 2, 3], [1, 3, 5]) &gt;&gt;&gt; ([(1, 3), (1, 3)], [2], [5]) Or with callback functions specified:: &gt;&gt;&gt; f = lambda x: x['v'] &gt;&gt;&gt; &gt;&gt;&gt; li1 = [{'v': 1}, {'v': 2}, {'v': 3}] &gt;&gt;&gt; li2 = [1, 3, 5] &gt;&gt;&gt; &gt;&gt;&gt; compare_lists(li1, li2, value_func1=f) &gt;&gt;&gt; ([({'v': 1}, {'v': 3}), (1, 3)], [{'v': 2}], [5]) """ if not value_func1: value_func1 = (lambda x:x) if not value_func2: value_func2 = (lambda x:x) def to_dict(li, vfunc): return dict((k, list(g)) for k, g in itertools.groupby(li, vfunc)) def flatten(li): return reduce(list.__add__, li) if li else [] d1 = to_dict(li1, value_func1) d2 = to_dict(li2, value_func2) if d1 == d2: return (li1, li2), [], [] k1 = set(d1.keys()) k2 = set(d2.keys()) elems_left = flatten([d1[k] for k in k1 - k2]) elems_right = flatten([d2[k] for k in k2 - k1]) common_keys = k1 &amp; k2 elems_both = flatten([d1[k] for k in common_keys]), flatten([d2[k] for k in common_keys]) return elems_both, elems_left, elems_right </code></pre> <p>Edit:</p> <p>zeekay suggests using set, which is also what I was doing, except that I make a dict for each list first, then compare the keys using set, finally return the original elements using the dict. I realized that the speed actually depends on which one will take more time -- the callback function, or the groupby. In my case, the possible callback functions are mostly dot access on objects, and the length of lists can be large causing groupby on lists takes more time.</p> <p>In the improved version each callback function is executed more than once on every single element, which I considered is a waste and has been trying to avoid in the first place, but it's still much faster than my original approach, and much simpler.</p> <pre><code>def compare_lists(li1, li2, vf1=None, vf2=None): l1 = map(vf1, li1) if vf1 else li1 l2 = map(vf2, li2) if vf2 else li2 s1, s2 = set(l1), set(l2) both, left, right = s1 &amp; s2, s1 - s2, s2 - s1 orig_both = list((x for x in li1 if vf1(x) in both) if vf1 else both), list((x for x in li2 if vf2(x) in both) if vf2 else both) orig_left = list((x for x in li1 if vf1(x) in left) if vf1 else left) orig_right = list((x for x in li2 if vf2(x) in right) if vf2 else right) return orig_both, orig_left, orig_right </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T08:58:51.990", "Id": "7109", "Score": "0", "body": "there are smarter ways to flatten a list, using `sum`, for other comparison approaches see http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:26:54.090", "Id": "7110", "Score": "0", "body": "@Fredrik Thanks. sum does not work for list of lists though... sum([1, 2], [3]) raises TypeError." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:39:35.390", "Id": "7111", "Score": "1", "body": "@Shaung it does if you use it like `sum([[],[1],[2,3]], [])`, note the 2nd argument `[]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:39:40.940", "Id": "7112", "Score": "0", "body": "he would be referring to `sum([[1, 2], [3]], [])`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:40:08.317", "Id": "7113", "Score": "0", "body": "@Dan D... snap!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:45:49.183", "Id": "7114", "Score": "0", "body": "Oh I see now. Cool! Wish I knew that earlier" } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T08:46:15.343", "Id": "4757", "Score": "6", "Tags": [ "python", "performance", "optimization" ], "Title": "Python list comparison: Can this code run faster?" }
4757
max_votes
[ { "body": "<p>So it seems you primarily want to use your callback functions to pull the value to compare out of an object, if you don't mind simplifying how compared items are returned, a faster and simpler approach would be:</p>\n\n<pre><code>def simple_compare(li1, li2, value_func1=None, value_func2=None):\n s1, s2 = set(map(value_func1, li1)), set(map(value_func2, li2))\n common = s1.intersection(s2)\n s1_diff, s2_diff = s1.difference(s2), s2.difference(s1)\n return common, s1_diff, s2_diff\n\n&gt;&gt;&gt; simple_compare(li1, li2, value_func1=f)\n&lt;&lt;&lt; (set([1, 3]), set([2]), set([5]))\n\n&gt;&gt;&gt; compare_lists(li1, li2, value_func1=f)\n&lt;&lt;&lt; (([{'v': 1}, {'v': 3}], [1, 3]), [{'v': 2}], [5])\n</code></pre>\n\n<p>Which depending on actual use case, might be something you could live with. It's definitely a lot faster:</p>\n\n<pre><code>&gt;&gt;&gt; timeit x = simple_compare(xrange(10000), xrange(10000))\n100 loops, best of 3: 2.3 ms per loop\n\n&gt;&gt;&gt; timeit x = compare_lists(xrange(10000), xrange(10000))\n10 loops, best of 3: 53.1 ms per loop\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:28:15.807", "Id": "7115", "Score": "0", "body": "You did not read my question, dude :) What I am trying to do is compare lists by the value after applied to some function, and return the original elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:42:08.650", "Id": "7116", "Score": "1", "body": "You can of course use my answer to modify your original function and support applying functions to values. As is, it merely demonstrates how much faster using the `set` methods would be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:45:02.483", "Id": "7117", "Score": "1", "body": "yes, quite simply by for example using `s1, s2 = set(map(func1, l1)), set(map(func2, l2))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:18:42.907", "Id": "7118", "Score": "0", "body": "Yeah I suppose I'll update with an alternate approach using `map`, actually. Format of return is a bit different, but I think this makes more sense honestly. Might not work for you, but if you can make it work it'd be a lot simpler and faster." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:06:59.140", "Id": "4758", "ParentId": "4757", "Score": "3" } } ]
<p>As part of my implementation of cross-validation, I find myself needing to split a list into chunks of roughly equal size.</p> <pre><code>import random def chunk(xs, n): ys = list(xs) random.shuffle(ys) ylen = len(ys) size = int(ylen / n) chunks = [ys[0+size*i : size*(i+1)] for i in xrange(n)] leftover = ylen - size*n edge = size*n for i in xrange(leftover): chunks[i%n].append(ys[edge+i]) return chunks </code></pre> <p>This works as intended</p> <pre><code>&gt;&gt;&gt; chunk(range(10), 3) [[4, 1, 2, 7], [5, 3, 6], [9, 8, 0]] </code></pre> <p>But it seems rather long and boring. Is there a library function that could perform this operation? Are there pythonic improvements that can be made to my code?</p>
[]
{ "AcceptedAnswerId": "4880", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T19:46:13.750", "Id": "4872", "Score": "6", "Tags": [ "python" ], "Title": "Pythonic split list into n random chunks of roughly equal size" }
4872
accepted_answer
[ { "body": "<pre><code>import random\n\ndef chunk(xs, n):\n ys = list(xs)\n</code></pre>\n\n<p>Copies of lists are usually taken using <code>xs[:]</code></p>\n\n<pre><code> random.shuffle(ys)\n ylen = len(ys)\n</code></pre>\n\n<p>I don't think storing the length in a variable actually helps your code much</p>\n\n<pre><code> size = int(ylen / n)\n</code></pre>\n\n<p>Use <code>size = ylen // n</code> // is the integer division operator</p>\n\n<pre><code> chunks = [ys[0+size*i : size*(i+1)] for i in xrange(n)]\n</code></pre>\n\n<p>Why the <code>0+</code>? </p>\n\n<pre><code> leftover = ylen - size*n\n</code></pre>\n\n<p>Actually, you can find size and leftover using <code>size, leftover = divmod(ylen, n)</code></p>\n\n<pre><code> edge = size*n\n for i in xrange(leftover):\n chunks[i%n].append(ys[edge+i])\n</code></pre>\n\n<p>You can't have <code>len(leftovers) &gt;= n</code>. So you can do:</p>\n\n<pre><code> for chunk, value in zip(chunks, leftover):\n chunk.append(value)\n\n\n return chunks\n</code></pre>\n\n<p>Some more improvement could be had if you used numpy. If this is part of a number crunching code you should look into it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T22:27:21.407", "Id": "4880", "ParentId": "4872", "Score": "5" } } ]
<p>I'm using some slow-ish emit() methods in Python (2.7) logging (email, http POST, etc.) and having them done synchronously in the calling thread is delaying web requests. I put together this function to take an existing handler and make it asynchronous, but I'm new to python and want to make sure my assumptions about object scope are correct. Here's the code:</p> <pre><code>def patchAsyncEmit(handler): base_emit = handler.emit queue = Queue.Queue() def loop(): while True: record = queue.get(True) # blocks try : base_emit(record) except: # not much you can do when your logger is broken print sys.exc_info() thread = threading.Thread(target=loop) thread.daemon = True thread.start() def asyncEmit(record): queue.put(record) handler.emit = asyncEmit return handler </code></pre> <p>That let's me create an asynchronous LogHandler using code like:</p> <pre><code>handler = patchAsyncEmit(logging.handlers.HttpHandler(...)) </code></pre> <p>I've confirmed the messages are sent, and not in the calling thread, but I want to make sure I'm getting only one queue and only one thread per Handler, and that I'm not at risk of those somehow going out of scope.</p> <p>Am I off base or did I get that okay?</p>
[]
{ "AcceptedAnswerId": "4958", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T15:11:58.413", "Id": "4954", "Score": "2", "Tags": [ "python", "multithreading", "thread-safety", "asynchronous", "python-2.x" ], "Title": "Is this a safe/correct way to make a python LogHandler asynchronous?" }
4954
accepted_answer
[ { "body": "<p>It would seem to me that writing a class would be better:</p>\n\n<pre><code>class AsyncHandler(threading.Thread):\n def __init__(self, handler):\n self._handler = handler\n self._queue = Queue.Queue()\n\n self.daemon = True\n self.start()\n\n def run(self):\n while True:\n record = self._queue.get(True)\n self._handler.emit(record)\n\n def emit(self, record):\n self._queue.put(record)\n</code></pre>\n\n<p>Patching objects can be useful, but its usually clearer to create another object like this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T16:09:12.830", "Id": "7422", "Score": "0", "body": "A decorator like that (the pattern not the @pythonthing) is the route I wanted to go, but the LogHandler creation, at least when using the dictionary schema http://docs.python.org/library/logging.config.html#configuration-dictionary-schema ), doesn't allow for passing a handler into a handler's constructor -- only literals. So I couldn't think of a way to make that work using dict config (which I recognize I didn't mention in the question), but if there is a way I'd welcome it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T16:36:39.773", "Id": "7423", "Score": "0", "body": "@Ry4an, ah. Actually, I believe you can pass objects using the cfg:// syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T16:49:45.510", "Id": "7424", "Score": "0", "body": "oh, wow, I hadn't previously seen that at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T04:53:47.487", "Id": "7488", "Score": "0", "body": "A LogHandler has a few other important methods (configuration, etc.) would all of those have to be written into the AsyncHander to delegate correctly to the `_handler`? Is there an easy way to pull in all of `_handler`'s method except the one we want to override?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T12:47:58.423", "Id": "7496", "Score": "0", "body": "@Ry4an, in that case I'd probably want to subclass the handler of interest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T16:05:15.467", "Id": "7502", "Score": "0", "body": "But if I want an asynchronous wrapper for the python standard HTTPLogHandler, SocketHandler, and SMTPHandler do I need to put the async code in a subclass of each of them? I did end up subclassing them but then had the __init__ method of each subclass call my original `patchAsychEmit` with `self` as an argument. I see python provides BufferingHandler and MemoryHandler which are decorators w/ a target of the sort you did, so that's probably the right way even if it does mean wrapping some extra methods. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T16:18:02.437", "Id": "7503", "Score": "0", "body": "@Ry4an, with a little multiple inheritance you should be able to avoid putting the async code in multiple classes or doing the patching. Whether thats better then the extra method wrapping is hard to say. You could also overload __getattr__, but that quickly gets messy so I can't recommend it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T17:54:27.117", "Id": "7506", "Score": "0", "body": "Yeah, I tried pulling all the attributes of the \"target\" into the client automatically and that quickly went past the depth of my meager python knowledge. I'll stick with the patch for now, but it makes sense that a class is the way to go and multiple inheritance is the way to do it. In Scala I'd be using a trait, which is multiple inheritance without the horror. Thanks a ton." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T15:57:03.223", "Id": "4958", "ParentId": "4954", "Score": "2" } } ]
<p>Can you suggest how I might make the following code more efficient:</p> <pre><code>from collections import Counter a = [1,1,3,3,1,3,2,1,4,1,6,6] c = Counter(a) length = len(set(c.values())) normalisedValueCount = {} previousCount = 0 i = 0 for key in sorted(c, reverse=True): count = c[key] if not previousCount == count: i = i+1 previousCount = count normalisedValueCount[key] = i/length print(normalisedValueCount) </code></pre> <p>It basically gives a dictionary similar to counter, but instead of counting the number of occurrences, it contains a weighting based on the number of occurrences.</p> <ul> <li>The number 1 is associated with 1.0 (<code>4/length</code>) because it occurs the most often.</li> <li>2 and 4 occur the least often and are associated with the value <code>1/length</code>.</li> <li>6 is the second least occurring value and is associated with <code>2/length</code>.</li> <li>3 is the third least occurring value and is associated with <code>3/length</code>. </li> </ul> <p>Some more examples: </p> <ul> <li>The list <code>a[1,2,3]</code> results in a <code>normalisedValueCount</code> of 1:1.0, 2:1.0, 3:1.0.</li> <li>The list <code>a[2,1,2]</code> results in a <code>normalisedValueCount</code> of 2:1.0, 1:0.5.</li> <li>The list <code>a[2,1,2,3]</code> results in a <code>normalisedValueCount</code> of 2:1.0, 1:0.5, 3:0.5.</li> <li>The list <code>a[2,2,2,2,2,2,2,2,2,2,1,2,3,3]</code> results in a <code>normalisedValueCount</code> of 2:1.0, 3:0.66666, 1:0.33333.</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T19:28:27.850", "Id": "7472", "Score": "0", "body": "Your most recent edit changed the contents of the last list but didn't update the `normaizedValueCount`s. Are those the results you would be expecting?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:13:25.657", "Id": "4963", "Score": "3", "Tags": [ "python", "optimization", "python-3.x", "collections" ], "Title": "Collections.Counter in Python3" }
4963
max_votes
[ { "body": "<p>I have no idea what you code is doing, it doesn't look like any normalization I've seen. I'd offer a more specific suggestion on restructuring if I understood what you are doing.</p>\n\n<p>You:</p>\n\n<ol>\n<li>Put a in a counter</li>\n<li>Put that counter's values into a set</li>\n<li>sort the keys of the counter</li>\n</ol>\n\n<p>I'd look for another approach that doesn't involve so much moving around.</p>\n\n<pre><code>if not previousCount == count:\n</code></pre>\n\n<p>better as</p>\n\n<pre><code>if previousCount != count:\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<ol>\n<li>Counter.most_common returns what you are fetching using sorted(c, reverse=True)</li>\n<li>itertools.groupby allows you group together common elements nicely (such as the same count)</li>\n<li>enumerate can be used to count over the elements in a list rather then keeping track of the counter</li>\n</ol>\n\n<p>My code: </p>\n\n<pre><code>c = Counter(a)\nlength = len(set(c.values()))\ncounter_groups = itertools.groupby(c.most_common(), key = lambda x: x[1]))\nnormalisedValueCount = {}\nfor i, (group_key, items) in enumerate(counter_groups)\n for key, count in items:\n normalisedValueCount[key] = (i+1)/length\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T19:55:16.200", "Id": "7510", "Score": "0", "body": "Shouldn't it be?- counter_groups = itertools.groupby(reversed(combinationsCount.most_common()), key = lambda x: x[1])" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T21:41:07.760", "Id": "7512", "Score": "0", "body": "@Baz, I may be wrong, but I don't think so. `most_common` returns the elements from the most common to the least common. Of course your the best judge of whether that is what you wanted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T18:50:30.747", "Id": "7528", "Score": "0", "body": "Yes, but if the items are sorted from most to least common then the __for loop__ section will start with the most common number when i = 0. This will result in the most common values being associated with the smaller __normalisedValueCounts__ ((i+1)/length), which is the opposite of what we want. Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T19:59:21.350", "Id": "7532", "Score": "0", "body": "@Baz, okay, I guess I misread the original code. Your welcome." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T22:12:45.327", "Id": "4975", "ParentId": "4963", "Score": "1" } } ]
<pre><code>def int_to_roman (integer): returnstring='' table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]] for pair in table: while integer-pair[1]&gt;=0: integer-=pair[1] returnstring+=pair[0] return returnstring def rom_to_int(string): table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]] returnint=0 for pair in table: continueyes=True while continueyes: if len(string)&gt;=len(pair[0]): if string[0:len(pair[0])]==pair[0]: returnint+=pair[1] string=string[len(pair[0]):] else: continueyes=False else: continueyes=False return returnint </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T00:18:48.033", "Id": "5091", "Score": "14", "Tags": [ "python", "converting", "integer", "roman-numerals" ], "Title": "Converting Roman numerals to integers and vice versa" }
5091
max_votes
[ { "body": "<pre><code>def int_to_roman (integer):\n\n returnstring=''\n table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]\n</code></pre>\n\n<p>The element in your list should really be tuples not lists. It should also be a global constant so that you can reuse across both functions.</p>\n\n<pre><code> for pair in table:\n</code></pre>\n\n<p>Use <code>for letter, value in table:</code> rather then indexing the tuples.</p>\n\n<pre><code> while integer-pair[1]&gt;=0:\n</code></pre>\n\n<p>I think the code looks better with spacing around binary operators. Also why this instead of: <code>while integer &gt;= pair[1]:</code>?</p>\n\n<pre><code> integer-=pair[1]\n returnstring+=pair[0]\n</code></pre>\n\n<p>It'll probably be better to create and append to list and then join the list elements together at the end.</p>\n\n<pre><code> return returnstring\n\ndef rom_to_int(string):\n\n table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]\n returnint=0\n for pair in table:\n\n\n continueyes=True\n</code></pre>\n\n<p>Whenever I use a logical flag like this, I think: it should be removed. I figure that flags like this only serve to confuse the logic of what you are doing. i think a break is clearer then setting a flag.</p>\n\n<pre><code> while continueyes:\n if len(string)&gt;=len(pair[0]):\n\n if string[0:len(pair[0])]==pair[0]:\n</code></pre>\n\n<p>strings have a funciton: startswith that does this. You should use it here. There is also need to check the length. If you take a slice past the end of a string in python, you just get a shorter string. </p>\n\n<pre><code> returnint+=pair[1]\n string=string[len(pair[0]):]\n\n else: continueyes=False\n else: continueyes=False\n\n return returnint\n</code></pre>\n\n<p>My version of your code:</p>\n\n<pre><code>def int_to_roman (integer):\n parts = []\n for letter, value in TABLE:\n while value &lt;= integer:\n integer -= value\n parts.append(letter)\n return ''.join(parts)\n\ndef rom_to_int(string):\n result = 0\n for letter, value in table:\n while string.startswith(letter):\n result += value\n string = string[len(pairs[0]):]\n return result\n</code></pre>\n\n<p>One last thought. Your rom_to_int doesn't handle the case where an invalid string is passed. You might want to consider having it throw an exception or something in that case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T23:09:42.467", "Id": "7716", "Score": "1", "body": "thank you! This is incredibly helpful. This all makes a lot of sense. I learned python (my first prog. language since turbo pascal in 1980s) very quickly and with specific tasks in mind, really don't yet know how to utilize its features..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T03:41:10.637", "Id": "5095", "ParentId": "5091", "Score": "8" } } ]
<p>The following is a function that I wrote to display page numbers as they appear in books.</p> <p>If you enter the list <code>[1,2,3,6,7,10]</code>, for example, it would return:</p> <pre><code>1-3,6-7,10 </code></pre> <p>This seemed like a nice example of how the dictionary data type can be used in Python.</p> <p>Is there is an even more code-efficient way to do this?</p> <pre><code>def formatpagelist (numberlist): tempdic={} returnstring='' for number in numberlist: if number-1 in tempdic.keys(): tempdic[number-1]=number elif number-1 in tempdic.values(): for key in tempdic.keys(): if number-1==tempdic[key]: foundkey=key tempdic[foundkey]=number else: tempdic[number]=0 keylist=list(tempdic.keys()) keylist.sort() for key in keylist: if tempdic[key]&gt;0: returnstring+=(str(key)+'-'+str(tempdic[key])+',') else: returnstring+=str(key)+',' return returnstring </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T16:05:07.040", "Id": "5196", "Score": "13", "Tags": [ "python", "clustering", "interval" ], "Title": "Grouping consecutive numbers into ranges in Python 3.2" }
5196
max_votes
[ { "body": "<p>You could use this one-liner to generate groups of consecutive integers in a list:</p>\n\n<pre><code>from itertools import groupby, count\n\ngroupby(numberlist, lambda n, c=count(): n-next(c))\n</code></pre>\n\n<p>Then to finish it off, generate the string from the groups.</p>\n\n<pre><code>def as_range(iterable): # not sure how to do this part elegantly\n l = list(iterable)\n if len(l) &gt; 1:\n return '{0}-{1}'.format(l[0], l[-1])\n else:\n return '{0}'.format(l[0])\n\n','.join(as_range(g) for _, g in groupby(numberlist, key=lambda n, c=count(): n-next(c)))\n# '1-3,6-7,10'\n</code></pre>\n\n<p>This assumes they are in sorted order and there are no duplicates. If not sorted, add a <code>sorted()</code> call on <code>numberlist</code> beforehand. If there's duplicates, make it a <code>set</code> beforehand.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T00:11:35.367", "Id": "7839", "Score": "0", "body": "You'll never hit that IndexError. If `len(l) == 1` then `l[0] == l[-1]` and you'll never get IndexError" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T01:05:27.883", "Id": "7840", "Score": "0", "body": "Ah, thanks for pointing that out. That was a last minute change and I mixed up one idea for another." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T00:38:12.277", "Id": "11105", "Score": "0", "body": "+1 for the enumerate + groupby pattern to group consecutive elements (I think to recall it's somewhere in the docs)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T15:59:44.623", "Id": "32746", "Score": "1", "body": "FWIW, the output feature of [intspan](http://pypi.python.org/pypi/intspan) uses this technique." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-28T21:53:25.343", "Id": "365958", "Score": "1", "body": "this is a really neat solution :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T10:21:44.590", "Id": "434700", "Score": "0", "body": "This is great! what way of thinking made you think of implementing it this way?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T19:29:23.797", "Id": "5202", "ParentId": "5196", "Score": "18" } } ]
<p>I'm trying to implement my own A* pathfinder, but the voices in my head scream of better ways to do this. Probably because I'm exceeding Python's default maximum recursion depth of 1000.</p> <pre><code>class PathFinder(): ## grid is a list of 8 sub-lists, each containing 8 nodes. ## start and goal are tuples representing the grid indexes of my start and goal. def __init__(self, start, goal, grid): ## I don't do anything with these yet, ## just thought they would be good to have. self.goal = goal self.start = start self.grid = grid def find_path(self, start, goal, path=[]): ## My seemingly hackish method of looping through ## the 8 cells surrounding the one I'm on. for row in (-1,0,1): for col in (-1,0,1): if row == 0 and col == 0: continue cell = [start[0]+row,start[1]+col] ## Catching the inevitable exception when I try to examine ## the surroundings of cells that are already on the edge. try: ## Skip if the cell is blocked ("X"). if self.grid[cell[0]][cell[1]] == "X": continue except IndexError: continue path.append(cell) if cell == goal: return path self.find_path(cell, goal, path) def main(): import Gridder2 grid = Gridder2.board() start = (0,0) goal = (0,3) pt = PathFinder(start, goal, grid) print(pt.find_path(start, goal)) return 0 if __name__ == '__main__': main() </code></pre> <p>My <code>find_path</code> function particularly seems like it needs work. Seems like I <em>should</em> be able to calculate a path through an 8x8 grid with a recursion depth of less than 1000.</p> <p>How can I improve this? </p>
[]
{ "AcceptedAnswerId": "5221", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T03:27:40.240", "Id": "5219", "Score": "5", "Tags": [ "python" ], "Title": "How can I improve my A* algorithm in Python?" }
5219
accepted_answer
[ { "body": "<pre><code>class PathFinder():\n</code></pre>\n\n<p>Either but object in the () or drop them. Having them there empty makes me feel hollow inside.</p>\n\n<pre><code> ## grid is a list of 8 sub-lists, each containing 8 nodes.\n ## start and goal are tuples representing the grid indexes of my start and goal.\n\n def __init__(self, start, goal, grid):\n ## I don't do anything with these yet, \n ## just thought they would be good to have.\n self.goal = goal\n self.start = start\n self.grid = grid\n\n def find_path(self, start, goal, path=[]):\n</code></pre>\n\n<p>Don't put mutable values like list as your default parameters. Python will not create a new list everytime this function is called, rather it will keep reusing the same list which is probably not what you want</p>\n\n<pre><code> ## My seemingly hackish method of looping through \n ## the 8 cells surrounding the one I'm on.\n for row in (-1,0,1):\n for col in (-1,0,1):\n if row == 0 and col == 0:\n continue\n</code></pre>\n\n<p>I suggest creating a global constant with the 8 directions and doing: <code>for row, col in DIRECTIONS:</code></p>\n\n<pre><code> cell = [start[0]+row,start[1]+col]\n</code></pre>\n\n<p>Don't use lists unless they are actually lists. This should be a tuple. </p>\n\n<pre><code> ## Catching the inevitable exception when I try to examine\n ## the surroundings of cells that are already on the edge.\n try:\n ## Skip if the cell is blocked (\"X\").\n if self.grid[cell[0]][cell[1]] == \"X\":\n continue\n except IndexError:\n continue\n</code></pre>\n\n<p>I suggest a function <code>get_blocked</code> that you pass cell to which check for 'X' and also returns True if the cell is off the side of the map. Also catching IndexError may not be quite what you want because negative numbers are valid indexes, but probably not want you want. I suggest checking in the get_blocked function for inboundedness.</p>\n\n<pre><code> path.append(cell)\n if cell == goal:\n return path\n self.find_path(cell, goal, path)\n\ndef main():\n import Gridder2\n</code></pre>\n\n<p>Usually not a good idea to import anywhere but at the start of a file</p>\n\n<pre><code> grid = Gridder2.board()\n start = (0,0)\n goal = (0,3)\n pt = PathFinder(start, goal, grid)\n</code></pre>\n\n<p>pt?</p>\n\n<pre><code> print(pt.find_path(start, goal))\n</code></pre>\n\n<p>Decide whether the start/goal get passed to the constructor or the find method. Don't do both.</p>\n\n<pre><code> return 0\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>If you are going to return a value from your main function, you should pass it to sys.exit() so that it actually functions as a return code.</p>\n\n<p>And everything Thomas said. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:29:03.483", "Id": "7871", "Score": "0", "body": "All good points, but especially important catch on the negative indices not raising an IndexError, just wrapping around. I won't so confidently assert what the code is doing without executing it next time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T05:01:48.330", "Id": "7872", "Score": "0", "body": "@Thomas, yah, I've hit that enough times to be wary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T18:40:35.827", "Id": "7910", "Score": "0", "body": "It works so much better now and it's more readable too! Thank you very much!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:22:29.440", "Id": "5221", "ParentId": "5219", "Score": "6" } } ]
<pre><code>def range_find(pageset,upperlimit=1000): pagerangelist=[] for page in range(0,upperlimit): if page in pageset and previouspage in pageset:pagerangelist[-1].append(page) elif page in pageset and not (previouspage in pageset):pagerangelist.append([page]) else: pass previouspage=page pagerangestringlist=[] for pagerange in pagerangelist: pagerangestringlist.append(str(pagerange[0])+('-'+str(pagerange[-1]))*((len(pagerange)-1)&gt;0)) return(','.join(pagerangestringlist)) print(range_find({1,2,5,7,8,11,19,25,29,30,31,39,40,41,42,43,44,56,57,59,60,70,71,72,100,101,103,104,105})) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T15:22:11.620", "Id": "7898", "Score": "0", "body": "(a) Your indentation is wrtong. (b) You didn't reference the previous version of this question. (c) You didn't include the output from your test. (d) You didn't test the `[1, 2, 4, 5, 3]` case which requires merging two partitions. If you require the input to be sorted, please state that clearly or add `sorted` to assure it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:06:48.037", "Id": "7899", "Score": "0", "body": "@S.Lott, where is the indentation wrong? He's passing in a set so order doesn't matter. Your other points are good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:17:21.857", "Id": "7900", "Score": "0", "body": "Since the indentation is *now* fixed, it's no longer wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T17:13:55.540", "Id": "7909", "Score": "0", "body": "@S.Lott, okay, so it was just that he failed to format the code correctly in his post, not that the indentation in the original code was incorrect." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T15:07:41.950", "Id": "5229", "Score": "1", "Tags": [ "python" ], "Title": "Grouping consecutive numbers into ranges in Python 3.2 : New version for set" }
5229
max_votes
[ { "body": "<pre><code>def range_find(pageset,upperlimit=1000):\n\n pagerangelist=[]\n\n for page in range(0,upperlimit):\n</code></pre>\n\n<p>There is no reason to include the 0. Why don't you calculate the upperlimit by max(pageset)?</p>\n\n<pre><code> if page in pageset and previouspage in pageset:pagerangelist[-1].append(page)\n elif page in pageset and not (previouspage in pageset):pagerangelist.append([page])\n else: pass\n</code></pre>\n\n<p>Don't squish all that stuff onto one line. It makes it harder to read. Having an else: pass case is useless</p>\n\n<pre><code> previouspage=page\n</code></pre>\n\n<p>Since you are counting, just use page - 1 instead of previouspage</p>\n\n<pre><code> pagerangestringlist=[]\n\n for pagerange in pagerangelist:\n\n pagerangestringlist.append(str(pagerange[0])+('-'+str(pagerange[-1]))*((len(pagerange)-1)&gt;0))\n</code></pre>\n\n<p>Too clever. Just use an if. This technique makes it harder to see what is going on. Also pointless extra parens.</p>\n\n<pre><code> return(','.join(pagerangestringlist))\n</code></pre>\n\n<p>Don't put parens around your return statement expressions. </p>\n\n<p>Algorithmwise this may be problematic because it will slower for books with many pages even if you don't use many pages from them. For example</p>\n\n<pre><code>range_find({1, 2, 1000000},100000000)\n</code></pre>\n\n<p>Will spend a long time churning through pages that aren't really of interest.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:08:56.097", "Id": "5230", "ParentId": "5229", "Score": "2" } } ]
<pre><code>def range_find(pageset): pagerangelist=[] for page in list(pageset): if page in pageset and page-1 in pageset:pagerangelist[-1].append(page) elif page in pageset and not (page-1 in pageset):pagerangelist.append([page]) pagerangestringlist=[] for pagerange in pagerangelist: if len(pagerange)==1:pagerangestringlist.append(str(pagerange[0])) else: pagerangestringlist.append(str(pagerange[0])+'-'+str(pagerange[-1])) return ','.join(pagerangestringlist) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T00:20:51.897", "Id": "7918", "Score": "0", "body": "why so many versions? and why haven't you learned to format your posts correctly yet?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T01:10:26.143", "Id": "7919", "Score": "0", "body": "1)I do not understand the point about formatting...I simply cut and paste into the text field. What am I supposed to do? Or is it a question of the title. 2) I created different versions in response to feedback. If I edit the original post, then it would make it hard to understand the original comments. Or am I missing something about the way this web site works?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T02:00:53.790", "Id": "7920", "Score": "1", "body": "The textfield isn't a code box, its a general formatting box. You need to specifically tell it that you have put code in your post by using the toolbar button it gives you. Most people who post here edit their posts if they have new versions." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T23:01:16.693", "Id": "5247", "Score": "1", "Tags": [ "python" ], "Title": "Grouping consecutive numbers into ranges in Python 3.2; third version (accepts page numbers as an unsorted set)" }
5247
max_votes
[ { "body": "<pre><code>def range_find(pageset):\n\n pagerangelist=[]\n\n for page in list(pageset):\n</code></pre>\n\n<p>There is no point in listifying the set just to iterate over it. I think you meant <code>for page in sorted(pageset)</code> to get access to the page in sorted order.</p>\n\n<pre><code> if page in pageset and page-1 in pageset:pagerangelist[-1].append(page)\n elif page in pageset and not (page-1 in pageset):pagerangelist.append([page])\n</code></pre>\n\n<p>You still make it hard to read by putting those on the same line. </p>\n\n<pre><code> pagerangestringlist=[]\n</code></pre>\n\n<p>If you've got multiple words I suggest under scores. I also suggest dropping types like list/set from your names. I'd call this <code>page_range_strings</code>.</p>\n\n<pre><code> for pagerange in pagerangelist:\n\n if len(pagerange)==1:pagerangestringlist.append(str(pagerange[0]))\n else: pagerangestringlist.append(str(pagerange[0])+'-'+str(pagerange[-1])) \n</code></pre>\n\n<p>I'm going to recommend using string formating. It'll be easier to read then concatenating strings.</p>\n\n<pre><code> return ','.join(pagerangestringlist)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T00:25:14.977", "Id": "5249", "ParentId": "5247", "Score": "1" } } ]
<p>I wrote a Python method to convert an object and a subset of its attributes into a JSON string with a given field as the key.</p> <p>There's a lot of string concatenation, and I'm not too sure what the best way to do that in Python is.</p> <p>I'm also wondering if <code>attr.replace('"','\"')</code> is sufficient to sanitize input.</p> <pre><code>def to_json_with_key(nodes, key, fields, insertIndex=False): i=0 s="{" for node in nodes: s += '"%s":{' % getattr(node,key) attrs=[] for field in fields: attr = getattr(node,field) if not isinstance(attr,int) and not isinstance(attr,float) and not isinstance(attr,long): attrs.insert(0, '"%s":"%s"' % (field, attr.replace('"','\"') )) else: attrs.insert(0, '"%s":%s' % (field, attr )) if (insertIndex): s+='index:%d,' % i i=i+1 s+=','.join(attrs) + "}," s = s.rstrip(",") + "}" return s </code></pre> <p>Sample input:</p> <blockquote> <pre><code>to_json_with_key(myObj, "title", fields=["length","time_offset"], insertIndex=True) </code></pre> </blockquote> <p>Sample output:</p> <blockquote> <pre><code>{"Introduction_to_Lists":{index:0,"length":128,"time_offset":0, "Pass_by_Reference":{index:1,"length":84,"time_offset":128}} </code></pre> </blockquote>
[]
{ "AcceptedAnswerId": "5267", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T17:01:44.690", "Id": "5266", "Score": "2", "Tags": [ "python", "converting", "json" ], "Title": "Converting an object into a JSON string" }
5266
accepted_answer
[ { "body": "<p>Firstly, python includes a json module. Use that rather then writing your own.</p>\n\n<p>However, just to give some comments on your style:</p>\n\n<pre><code>def to_json_with_key(nodes, key, fields, insertIndex=False):\n</code></pre>\n\n<p>python recommend words_with_underscores for parameter names</p>\n\n<pre><code> i=0\n</code></pre>\n\n<p>Rather then manually keeping a count use enumerate</p>\n\n<pre><code> s=\"{\"\n for node in nodes:\n s += '\"%s\":{' % getattr(node,key)\n</code></pre>\n\n<p>You don't check the value to make sure it is json-safe. Building strings by concatenation is not usually a good idea. Either build a list and join it or use StringIO</p>\n\n<pre><code> attrs=[]\n for field in fields:\n attr = getattr(node,field)\n if not isinstance(attr,int) and not isinstance(attr,float) and not isinstance(attr,long):\n</code></pre>\n\n<p>You can pass several types in a tuple to isinstance to check several types at once.</p>\n\n<pre><code> attrs.insert(0, '\"%s\":\"%s\"' % (field, attr.replace('\"','\\\"') ))\n</code></pre>\n\n<p>This won't be sufficient. For example, you could have a \\ at the end of a string. You also need to handle newlines, tabs, and other escaped characters.</p>\n\n<pre><code> else:\n attrs.insert(0, '\"%s\":%s' % (field, attr ))\n</code></pre>\n\n<p>Why insert rather then append?</p>\n\n<pre><code> if (insertIndex):\n</code></pre>\n\n<p>No need for parens</p>\n\n<pre><code> s+='index:%d,' % i\n i=i+1\n\n s+=','.join(attrs) + \"},\"\n s = s.rstrip(\",\") + \"}\"\n</code></pre>\n\n<p>It would be cleaner to join a list of items rather then stripping off stray commas. </p>\n\n<pre><code> return s\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T17:33:41.533", "Id": "5267", "ParentId": "5266", "Score": "7" } } ]
<p>I want to limit the load so I rewrite the most expensive method and add caching, both memcache and cache-control:</p> <pre><code>class GeoRSS(webapp.RequestHandler): def get(self): start = datetime.datetime.now() - timedelta(days=60) count = (int(self.request.get('count' )) if not self.request.get('count') == '' else 1000) memcache_key = 'ads' data = memcache.get(memcache_key) if data is None: a = Ad.all().filter('modified &gt;', start).filter('published =', True).order('-modified').fetch(count) memcache.set('ads', a) else: a = data template_values = {'a': a, 'request': self.request, 'host': os.environ.get('HTTP_HOST', os.environ['SERVER_NAME'])} dispatch = 'templates/georss.html' path = os.path.join(os.path.dirname(__file__), dispatch) output = template.render(path, template_values) self.response.headers["Cache-Control"] = "public,max-age=%s" % 86400 self.response.headers['Content-Type'] = 'application/rss+xml' self.response.out.write(output) </code></pre> <p>Will this limit the load on my app? Did I prioritize correctly when I see the load on the app:</p> <p><img src="https://i.stack.imgur.com/zlcNl.png" alt="enter image description here"></p>
[]
{ "AcceptedAnswerId": "5429", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T06:04:26.670", "Id": "5317", "Score": "1", "Tags": [ "python", "cache" ], "Title": "Does this function cache correctly?" }
5317
accepted_answer
[ { "body": "<p>You can simplify (and sometimes speed up) things like this</p>\n\n<pre><code>try:\n a = memcache.get('ads')\nexcept KeyError:\n a = Ad.all().filter('modified &gt;',\n start).filter('published =',\n True).order('-modified').fetch(count)\n memcache.set('ads', a)\n</code></pre>\n\n<p>It's (often) slightly faster in Python to avoid the <code>if</code> statement.</p>\n\n<p>After measuring that with <code>timeit</code>, you should rename the variable <code>a</code>. That's a poor name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T18:37:07.097", "Id": "5429", "ParentId": "5317", "Score": "3" } } ]
<p>I want to limit the load so I rewrite the most expensive method and add caching, both memcache and cache-control:</p> <pre><code>class GeoRSS(webapp.RequestHandler): def get(self): start = datetime.datetime.now() - timedelta(days=60) count = (int(self.request.get('count' )) if not self.request.get('count') == '' else 1000) memcache_key = 'ads' data = memcache.get(memcache_key) if data is None: a = Ad.all().filter('modified &gt;', start).filter('published =', True).order('-modified').fetch(count) memcache.set('ads', a) else: a = data template_values = {'a': a, 'request': self.request, 'host': os.environ.get('HTTP_HOST', os.environ['SERVER_NAME'])} dispatch = 'templates/georss.html' path = os.path.join(os.path.dirname(__file__), dispatch) output = template.render(path, template_values) self.response.headers["Cache-Control"] = "public,max-age=%s" % 86400 self.response.headers['Content-Type'] = 'application/rss+xml' self.response.out.write(output) </code></pre> <p>Will this limit the load on my app? Did I prioritize correctly when I see the load on the app:</p> <p><img src="https://i.stack.imgur.com/zlcNl.png" alt="enter image description here"></p>
[]
{ "AcceptedAnswerId": "5429", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T06:04:26.670", "Id": "5317", "Score": "1", "Tags": [ "python", "cache" ], "Title": "Does this function cache correctly?" }
5317
accepted_answer
[ { "body": "<p>You can simplify (and sometimes speed up) things like this</p>\n\n<pre><code>try:\n a = memcache.get('ads')\nexcept KeyError:\n a = Ad.all().filter('modified &gt;',\n start).filter('published =',\n True).order('-modified').fetch(count)\n memcache.set('ads', a)\n</code></pre>\n\n<p>It's (often) slightly faster in Python to avoid the <code>if</code> statement.</p>\n\n<p>After measuring that with <code>timeit</code>, you should rename the variable <code>a</code>. That's a poor name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T18:37:07.097", "Id": "5429", "ParentId": "5317", "Score": "3" } } ]
<p>Please review this simple code. When I review it I decide to rewrite so that it doesn't write to a template, but instead directly to output since the whole HTML is fetched from the data layer. I used the tool <code>appengine_admin</code> to get editable HTML for simple html capabilities to an appspot project:</p> <pre><code> class Page(db.Model): html = db.TextProperty(required=True) class AdminPage(appengine_admin.ModelAdmin): model = Page listFields = ( 'html', ) editFields = ( 'html', ) application = webapp.WSGIApplication([ ('/page/([0-9]+)', PageHandler), ]) class PageHandler(BaseHandler): def get(self, file_id): page = Page.get_by_id(long(file_id)) if not page: self.error(404) return self.render_template(file_id+'.html', { 'body': page.body, }) </code></pre> <p>My 2 to-dos:</p> <ol> <li>change variable <code>file_id</code> to <code>page_id</code></li> <li>change writing to direct output instead of template</li> </ol>
[]
{ "AcceptedAnswerId": "5578", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T02:26:09.710", "Id": "5577", "Score": "2", "Tags": [ "python", "google-app-engine" ], "Title": "HTML editor for Google App Engine" }
5577
accepted_answer
[ { "body": "<pre><code> application = webapp.WSGIApplication([ ('/page/([0-9]+)', PageHandler), ])\n</code></pre>\n\n<p>I'd put the list of urls as a global constant, I think that would make it easier to read.</p>\n\n<pre><code> class PageHandler(BaseHandler):\n def get(self, file_id):\n page = Page.get_by_id(long(file_id))\n if not page:\n</code></pre>\n\n<p>If you are checking against None here, I'd use <code>if page is None:</code></p>\n\n<pre><code> self.error(404)\n return\n</code></pre>\n\n<p>I'd use else instead of returning here</p>\n\n<pre><code>self.render_template(file_id+'.html', {\n 'body': page.body,\n})\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T04:05:09.857", "Id": "5578", "ParentId": "5577", "Score": "3" } } ]
<p>I have the following code (for <code>Country</code> and <code>City</code> classes <code>key_name</code> is numeric id with addition of 'i' at the beginning):</p> <pre><code>def add_country(country, country_name): if country and country_namef and country_name != '': return Country.get_or_insert('i'+str(country), country_name=country_name) else: return None def add_city(city, city_name, country): if country and city and city_name and city_name != '': return City.get_or_insert('i'+str(city), city_name=city_name, parent=country) else: return None </code></pre> <p>Is it correct code or can it be optimized somehow?</p>
[]
{ "AcceptedAnswerId": "5601", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T19:33:35.027", "Id": "5599", "Score": "0", "Tags": [ "python" ], "Title": "How to optimize the code to save data at GAE datastore?" }
5599
accepted_answer
[ { "body": "<pre><code>def add_country(country, country_name):\n if country and country_namef and country_name != '':\n</code></pre>\n\n<p>I assume that country_namef is a typo. If so, there is no point in checking <code>country_name != ''</code> because empty strings are already considered False</p>\n\n<pre><code> return Country.get_or_insert('i'+str(country), country_name=country_name)\n else:\n return None \n\ndef add_city(city, city_name, country):\n if country and city and city_name and city_name != '':\n</code></pre>\n\n<p>As before, empty strings are false, so you are checking that twice</p>\n\n<pre><code> return City.get_or_insert('i'+str(city), city_name=city_name, parent=country)\n else:\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T17:56:50.780", "Id": "8512", "Score": "0", "body": "So, in case when `country_name` is equal to `None` and when `country_name` is equal to `''`, in both cases `if country_name` returns `False`, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T17:58:09.233", "Id": "8513", "Score": "0", "body": "@LA_, yes that is correct." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-26T20:25:39.233", "Id": "5601", "ParentId": "5599", "Score": "2" } } ]
<p>I have a function that is being called in a tight loop. I've profiled my code and this is where my largest bottleneck is. The function is fairly simple: it checks if a point in (x,y) form is above a line in (slope, intercept) form. </p> <p>The problem is, it also has to deal with the case where the slope is positive infinity, and the intercept gives the x-intercept. In this case, the function should return <code>True</code> if the point is to the right of the line.</p> <p>Here's the function written out how it was when I noticed the bottleneck:</p> <pre><code>def point_over(point, line): """Return true if the point is above the line. """ slope, intercept = line if slope != float("inf"): return point[0] * slope + intercept &lt; point[1] else: return point[0] &gt; intercept </code></pre> <p>On my machine, this is how fast it runs:</p> <pre><code>&gt;&gt;&gt; timeit("point_over((2.412412,3.123213), (-1.1234,9.1234))", "from __main__ import point_over", number = 1000000) 1.116534522825532 </code></pre> <p>Since this function is being called a lot, I've inlined it to avoid the function call overhead. The inlined version is fairly simple:</p> <pre><code>point[0] * line[0] + line[1] &lt; point[1] if line[0] != float('inf') else point[0] &gt; line[1] </code></pre> <p>And performs similarly in <code>timeit</code>:</p> <pre><code>&gt;&gt;&gt; timeit("point[0] * line[0] + line[1] &lt; point[1] if line[0] != float('inf') else point[0] &gt; line[1]", "point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000) 0.9410096389594945 </code></pre> <p>However, this one line of code is still hogging the largest proportion of execution time in my code, even after being inlined.</p> <p>Why does the comparison to <code>float('inf')</code> take longer than a number of calculations as well as a comparison? Is there any way to make this faster?</p> <p>As an example of what I'm claiming, here are the speeds of two parts of my ternary statement separated and timed:</p> <pre><code>&gt;&gt;&gt; timeit("line[0] != float('inf')", "point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000) 0.528602410095175 &gt;&gt;&gt; timeit("point[0] * line[0] + line[1] &lt; point[1]", "point, line = ((2.412412,3.123213), (-1.1234,9.1234))", number = 1000000) 0.48756339706397966 </code></pre> <p>My primary question is why it takes so long to do the comparison to infinity. Secondary is any tips on how to speed these up. Ideally there exists some magical (even if incredibly hacky) way to half the execution time of this line, without dropping down to C. Otherwise, tell me I need to drop down to C.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T22:36:30.263", "Id": "9312", "Score": "0", "body": "If you really want speedups, you should look at using numpy." } ]
{ "AcceptedAnswerId": "6041", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T21:41:21.713", "Id": "6040", "Score": "14", "Tags": [ "python", "performance", "coordinate-system" ], "Title": "Comparison to infinity when checking if a point is above a line" }
6040
accepted_answer
[ { "body": "<p>It would be faster to use the <em><a href=\"http://docs.python.org/library/math.html#math.isinf\">math.isinf()</a></em> function:</p>\n\n<pre><code>&gt;&gt;&gt; from math import e, pi, isinf\n&gt;&gt;&gt; s = [0, float('inf'), e, pi]\n&gt;&gt;&gt; map(isinf, s)\n[False, True, False, False]\n</code></pre>\n\n<p>The reason your current check is taking so long is due to how much work it has to do:</p>\n\n<pre><code>&gt;&gt;&gt; from dis import dis\n\n&gt;&gt;&gt; def my_isinf(f):\n return f == float('Inf')\n\n&gt;&gt;&gt; dis(my_isinf)\n 2 0 LOAD_FAST 0 (f)\n 3 LOAD_GLOBAL 0 (float)\n 6 LOAD_CONST 1 ('Inf')\n 9 CALL_FUNCTION 1\n 12 COMPARE_OP 2 (==)\n 15 RETURN_VALUE \n</code></pre>\n\n<p>There is a global load which involves a dictionary lookup. There is a two-arguments function call. The Float constructor has to parse the string and then allocate (and refcount) a new float object in memory. Then the comparison step dispatches its work to float.__eq__ which returns a boolean value which is then the fed to the if-statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T21:43:43.317", "Id": "6041", "ParentId": "6040", "Score": "17" } } ]
<p>I am writing this Monte Carlo simulation and I am facing this issue when running the code at 10,000,000 iterations. here is the code:</p> <pre><code>import random as rnd from time import time #get user input on number of iterations numOfIterations = raw_input('Enter the number of iterations: ') numOfIterations = int(numOfIterations) start = time() #initialize bag (44 green, 20 blue, 15 yellow, 11 red, 2 white, 1 black #a counter #and question counter bag = 44*'g'+ 20*'b' + 15*'y' + 11*'r' + 2*'w' + 'k' counter = {'g':0, 'b':0,'y':0 ,'r':0,'w':0,'k':0} question = {'one':0,'two':0,'three':0,'four':0,'five':0} for i in range(0,numOfIterations): for j in xrange(0,5): draw = rnd.sample(bag,5) for x in draw: counter[x]+=1 if counter['w'] &gt;0 and counter['k'] &gt;0: question['one']+=1 if counter['b'] &gt; counter['r']: question['two']+=1 if counter['b'] &gt; counter['y']: question['three']+=1 if counter['y'] &gt; counter['r']: question['four']+=1 if counter['g'] &lt; (counter['b']+counter['y']+counter['r']+counter['w']+counter['k']): question['five']+=1 for k in counter: counter[k] = 0 p1 = float(question['one'])/float(numOfIterations) p2 = float(question['two'])/float(numOfIterations) p3 = float(question['three'])/float(numOfIterations) p4 = float(question['four'])/float(numOfIterations) p5 = float(question['five'])/float(numOfIterations) print 'Q1 \t Q2 \t Q3 \t Q4 \t Q5' print str(p1)+'\t'+str(p2)+'\t'+str(p3)+'\t'+str(p4)+'\t'+str(p5) end = time() print 'it took ' +str(end-start)+ ' seconds' </code></pre> <p>any suggestions/criticism would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-28T16:26:05.633", "Id": "9870", "Score": "1", "body": "Maybe switching to a compiled language might help. Not sure how well Python can JIT." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T08:18:43.970", "Id": "30519", "Score": "0", "body": "you might want to try an run it in pypy. http://pypy.org/" } ]
{ "AcceptedAnswerId": "6313", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-26T12:01:57.800", "Id": "6311", "Score": "5", "Tags": [ "python", "optimization" ], "Title": "How can I optimize this Monte Carlo simulation running at 10,000,000 iterations?" }
6311
accepted_answer
[ { "body": "<pre><code>import random as rnd\n</code></pre>\n\n<p>I dislike abbreviation like this, they make the code harder to read</p>\n\n<pre><code>from time import time\n\n#get user input on number of iterations\nnumOfIterations = raw_input('Enter the number of iterations: ')\nnumOfIterations = int(numOfIterations)\n</code></pre>\n\n<p>Any reason you didn't combine these two lines?</p>\n\n<pre><code>start = time()\n\n#initialize bag (44 green, 20 blue, 15 yellow, 11 red, 2 white, 1 black\n#a counter\n#and question counter\nbag = 44*'g'+ 20*'b' + 15*'y' + 11*'r' + 2*'w' + 'k'\ncounter = {'g':0, 'b':0,'y':0 ,'r':0,'w':0,'k':0}\nquestion = {'one':0,'two':0,'three':0,'four':0,'five':0}\n</code></pre>\n\n<p>Looking up your data by strings all the time is going to be somewhat slower. Instead, I'd suggest you keep lists and store the data that way. </p>\n\n<pre><code>for i in range(0,numOfIterations):\n</code></pre>\n\n<p>Given that numOfIterations will be very large, its probably a good idea to use xrange here. </p>\n\n<pre><code> for j in xrange(0,5):\n</code></pre>\n\n<p>You should generally put logic inside a function. That is especially true for any sort of loop as it will run faster in a function.</p>\n\n<pre><code> draw = rnd.sample(bag,5)\n for x in draw: counter[x]+=1\n</code></pre>\n\n<p>I dislike putting the contents of the loop on the same line. I think it makes it harder to read.</p>\n\n<pre><code> if counter['w'] &gt;0 and counter['k'] &gt;0: question['one']+=1\n if counter['b'] &gt; counter['r']: question['two']+=1\n if counter['b'] &gt; counter['y']: question['three']+=1\n if counter['y'] &gt; counter['r']: question['four']+=1\n if counter['g'] &lt; (counter['b']+counter['y']+counter['r']+counter['w']+counter['k']): question['five']+=1\n for k in counter: counter[k] = 0\n\np1 = float(question['one'])/float(numOfIterations)\np2 = float(question['two'])/float(numOfIterations)\np3 = float(question['three'])/float(numOfIterations)\np4 = float(question['four'])/float(numOfIterations)\np5 = float(question['five'])/float(numOfIterations)\n</code></pre>\n\n<p>Don't create five separate variables, create a list. Also, if you add the line <code>from __future__ import division</code> at the beginning of the file then dividing two ints will produce a float. Then you don't need to convert them to floats here.</p>\n\n<pre><code>print 'Q1 \\t Q2 \\t Q3 \\t Q4 \\t Q5'\nprint str(p1)+'\\t'+str(p2)+'\\t'+str(p3)+'\\t'+str(p4)+'\\t'+str(p5)\n</code></pre>\n\n<p>See if you had p1 a list, this would be much easier</p>\n\n<pre><code>end = time()\n\nprint 'it took ' +str(end-start)+ ' seconds'\n</code></pre>\n\n<p>For speed improvements you want to look at using numpy. It allows implementing efficient operations over arrays. </p>\n\n<p>In this precise case I'd use a multinomial distribution and solve the problem analytically rather then using monte carlo. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-26T15:50:49.213", "Id": "6313", "ParentId": "6311", "Score": "8" } } ]
<p>I took a challenge on <a href="http://www.codeeval.com/open_challenges/37/" rel="nofollow">CodeEval</a>. Although the code seems to work for the examples taken from the site, I feel it is not really pretty and must be more complicated than it should be.</p> <blockquote> <p><strong>Description:</strong></p> <p>The sentence 'A quick brown fox jumps over the lazy dog' contains every single letter in the alphabet. Such sentences are called pangrams. You are to write a program, which takes a sentence, and returns all the letters it is missing (which prevent it from being a pangram). You should ignore the case of the letters in sentence, and your return should be all lower case letters, in alphabetical order. You should also ignore all non US-ASCII characters.In case the input sentence is already a pangram, print out the string NULL.</p> </blockquote> <pre><code>import sys filepath = sys.argv[1] f = open(filepath) wholealphabet = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r', 's','t','u','v','w','x','y','z') for line in f: sortedletters = list(set(line.lower())) i = 0 while i != len(sortedletters): if wholealphabet.count(sortedletters[i]) != 0: i = i + 1 else: sortedletters.pop(i) missingletters = "" for letter in wholealphabet: if sortedletters.count(letter) == 0: missingletters +=letter if len(missingletters) == 0: print("NULL") else: print(missingletters) </code></pre>
[]
{ "AcceptedAnswerId": "6324", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-11-27T02:58:15.993", "Id": "6323", "Score": "9", "Tags": [ "python", "beginner", "programming-challenge" ], "Title": "Pangrams CodeEval challenge" }
6323
accepted_answer
[ { "body": "<p>One of Python's greatest strengths is its built-in capability to use sets directly. I don't feel you've used sets to their fullest extent here. I'd also like to point out the <code>with</code> statement, which you should probably use to handle file handles.</p>\n\n<pre><code>from __future__ import with_statement\nimport sys\nfrom string import ascii_lowercase\nfilepath = sys.argv[1]\nwholealphabet = frozenset(ascii_lowercase)\n\n# Use with to handle file … handles\nwith open(filepath) as f:\n for line in f: # assume a line is a sentence, not exactly per spec?\n # sortedletters = list(set(line.lower())) # guaranteed to be *unsorted*\n missingletters = wholealphabet.difference(line.lower())\n if missingletters:\n print ''.join(sorted(missingletters))\n else:\n print 'NULL'\n</code></pre>\n\n<p>That's really all you need. Unless you want to reconsider the definition of a sentence. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-27T04:50:33.927", "Id": "9821", "Score": "0", "body": "wow it really is much simpler that way, didn't know about the with. It seems to work like the using statement in c#. I will do a research on each of the method used as I do not know them. I indeed forgot about actually doing the sort, I made some attempt with the interpreter at first and then pretty much copy pasted in a .py file. What did you mean about reconsidering the definition of a sentence? Wish I could upvote but I do not have the required rank yet. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-27T05:06:41.227", "Id": "9823", "Score": "0", "body": "Nevermind about the sentence definition I rereaded the answer and understood :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-28T23:33:54.210", "Id": "9884", "Score": "0", "body": "FYI I moved the `from future…` to the top of the code, because (as I'm sure you've discovered) the code won't work otherwise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T02:33:40.977", "Id": "9889", "Score": "1", "body": "Indeed I had to change it, I also discover that string has a ascii_lowercase method which I used instead of letters.lower()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T02:59:36.040", "Id": "9890", "Score": "0", "body": "Great catch. So edited!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-27T04:12:20.383", "Id": "6324", "ParentId": "6323", "Score": "12" } } ]
<p>I made a small command line tool to help my Italian studies. Any thoughts on how it could be improved? I can't think of much but would like to be proved wrong.</p> <pre><code>import random class RegularVerb(object): def __init__(self, name): self._name = name def name(self): return self._name def _make(self, verb_end): return self.name()[:-3] + verb_end def _build_condizionale_semplice(self, verb_forms, prefix): def verb_base(prefix): return (prefix + condizionale_semplice_base for condizionale_semplice_base in ['rei', 'resti', 'rebbe', 'remmo', 'reste', 'rebbero'] ) return dict(zip(verb_forms, verb_base(prefix))) class EreVerb(RegularVerb): def __init__(self, name, verb_forms): super(EreVerb, self).__init__(name) self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'e') def condizionale_semplice(self, verb_form): return self._make(self._condizionale_semplice[verb_form]) class IreVerb(RegularVerb): def __init__(self, name, verb_forms): super(IreVerb, self).__init__(name) self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'i') def condizionale_semplice(self, verb_form): return self._make(self._condizionale_semplice[verb_form]) class AreVerb(RegularVerb): def __init__(self, name, verb_forms): super(AreVerb, self).__init__(name) self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'e') def condizionale_semplice(self, verb_form): return self._make(self._condizionale_semplice[verb_form]) class Questioner(): def __init__(self, verb_forms, verbs): self._verb_forms = verb_forms self._verbs = verbs def _handle_answer(self, user_answer, correct_answer): if user_answer == correct_answer: print "bravo!" else: print "no, correct form is:", correct_answer def ask_random_condizionale_semplice(self): def ask(verb_form, verb): print "condizionale semplice for {0} in {1}?".format(verb.name(), verb_form), self._handle_answer(raw_input(), verb.condizionale_semplice(verb_form)) ask(random.choice(self._verb_forms), random.choice(self._verbs)) def build_regular_verbs(verbs, verb_forms): def make(verb): if verb[-3:] == 'are': return AreVerb(verb, verb_forms) elif verb[-3:] == 'ire': return IreVerb(verb, verb_forms) elif verb[-3:] == 'ere': return EreVerb(verb, verb_forms) else: raise Exception("not a regular verb") return [make(v) for v in verbs] def build_questioner(verb_forms, regular_verbs): return Questioner(verb_forms, build_regular_verbs( regular_verbs, verb_forms ) ) if __name__ == "__main__": questioner = build_questioner( ['I sg', 'II sg', 'III sg', 'I pl', 'II pl', 'III pl'], ['passare', 'mettere', 'sentire'], ) while True: questioner.ask_random_condizionale_semplice() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T16:04:28.020", "Id": "9909", "Score": "1", "body": "hmm now after posting.. I see that the class RegularCondizionaleSemplice is actually useless and could easily be refactored into each type of verb." } ]
{ "AcceptedAnswerId": "6388", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T15:59:44.127", "Id": "6385", "Score": "7", "Tags": [ "python" ], "Title": "Command line tool for Italian language studies" }
6385
accepted_answer
[ { "body": "<p>Maybe this could provide of a more neat way of relating verbs with veb_forms:</p>\n\n<pre><code>verb_binder = dict(are=AreVerb, ire=IreVerb, ere=EreVerb)\n\ndef build_regular_verbs(verbs, verb_forms):\n def make(verb):\n try:\n return verb_binder[verb[-3:]](verb, verb_forms)\n except KeyError:\n raise Exception(\"not a regular verb\")\n\n return [make(v) for v in verbs]\n</code></pre>\n\n<p>not sure if verb_binder dictionary should be a module global or local to the function or maybe it should be located elsewhere, but this is the idea.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T20:21:36.783", "Id": "6388", "ParentId": "6385", "Score": "3" } } ]
<p>I'm learning Python 3 at the moment, so to test the skills I've learned, I am trying the puzzles at <a href="http://www.pythonchallenge.com/" rel="nofollow">Python Challenge</a>.</p> <p>I've created some code to solve the 2nd puzzle <a href="http://www.pythonchallenge.com/pc/def/map.html" rel="nofollow">here</a>. it works, but I think that the way I've done it is very convoluted. Any suggestions on how to solve the puzzle in a simpler way? </p> <p>(The code basically needs to substitute each letter in a message to the letter 2 spaces to the right of it, such as E->G.)</p> <pre><code>import string alphabet = string.ascii_lowercase letter=0 replaceLetter = 2 times=1 message = input() newMessage='' while times &lt; 26: newMessage = message.replace(alphabet[letter], str(replaceLetter)+',') message = newMessage letter = letter + 1 replaceLetter = replaceLetter + 1 time = times + 1 if letter == 26: times = 0 break newMessage = message.replace('26'+',', 'a') message = newMessage newMessage = message.replace('27'+',', 'b') message = newMessage number = 25 message = newMessage while times &lt; 26: newMessage = message.replace(str(number)+',', str(alphabet[number])) message = newMessage letter = letter + 1 number = number - 1 time = times + 1 if number == -1: times = 0 break print(newMessage) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T03:54:03.800", "Id": "64519", "Score": "0", "body": "Take a look at the python dictionary. Consider replacing characters?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T06:46:48.197", "Id": "114769", "Score": "1", "body": "There is a hint in the title of the challenge \"What about making trans?\". See [maketrans](http://docs.python.org/py3k/library/stdtypes.html?highlight=maketrans#str.maketrans).\nIt can be only a couple of lines of code." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T03:49:51.177", "Id": "6493", "Score": "3", "Tags": [ "python", "python-3.x", "caesar-cipher" ], "Title": "Simplifying working Caesar cipher" }
6493
max_votes
[ { "body": "<p>I would define a shift function that shifted the letters like so:</p>\n\n<pre><code>from string import whitespace, punctuation\n\ndef shift(c, shift_by = 2):\n if c in whitespace + punctuation: return c\n\n upper_ord, lower_ord, c_ord = ord('A'), ord('a'), ord(c)\n c_rel = (c_ord - lower_ord) if c_ord &gt;= lower_ord else (c_ord - upper_ord)\n offset = lower_ord if c_ord &gt;= lower_ord else upper_ord\n return chr(offset + (c_rel + shift_by) % 26)\n</code></pre>\n\n<p>Then, to translate a message:</p>\n\n<pre><code>msg = 'a quick brown fox jumped over the lazy dog'\nencoded_msg = ''.join(shift(l) for l in msg)\n</code></pre>\n\n<p>Alternatively, combine Mark Tolonen's maketrans suggestion with g.d.d's deque suggestion to get:</p>\n\n<pre><code>import string\nfrom collections import deque\n\nalphabet = string.ascii_lowercase\nalphabet_deque = deque(alphabet)\nalphabet_deque.rotate(-2)\nrotated_alphabet = ''.join(alphabet_deque)\ntbl = string.maketrans(alphabet, rotated_alphabet)\n</code></pre>\n\n<p>Then, later in the code:</p>\n\n<pre><code>msg = 'a quick brown fox jumped over the lazy dog'\nencoded_msg = string.translate(msg, tbl)\n</code></pre>\n\n<p>This second method only works for lowercase letters, but you can always create two separate translation tables -- one for uppercase letters and another for lowercase letters -- to account for case.</p>\n\n<p>Offtopic note: sometimes I wish Python had Smalltalk-like cascaded message sends. Ah well, one can dream.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T15:42:27.013", "Id": "6600", "ParentId": "6493", "Score": "3" } } ]
<p>I'm trying to get a better grasp on generators in Python because I don't use them enough (I think generators are cool). To do so I wrote a generator for prime numbers:</p> <pre><code>def primes(): x = 2 while True: for y in xrange(2, x/2 + 1): if x % y == 0: break else: yield x x = x + 1 </code></pre> <p>This works as expected but if I use list comprehension to create a list of primes using this generator it's really slow when compared to sieve function that generates the same list:</p> <pre><code>[prime.next() for i in xrange(1000)] # exectues in 0.212 sec, sieve in 0.001 sec </code></pre> <p>I'm assuming that this is not the intended purpose of a generator, but I thought I would see if anyone can think of a way to make this faster.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T20:05:39.030", "Id": "10450", "Score": "1", "body": "I can't come up with a proper answer at the moment but you should look into using memoization and a different algorithm here." } ]
{ "AcceptedAnswerId": "6698", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T19:35:08.033", "Id": "6696", "Score": "3", "Tags": [ "python", "performance", "primes", "generator" ], "Title": "Python prime number generator" }
6696
accepted_answer
[ { "body": "<p>Stylistically, using <code>itertools.count()</code> rather than implementing your own counter would be a bit cleaner.</p>\n\n<p>I also prefer using the <code>any()</code> over a generator rather than an explicit for loop with a break and else. I think it's easier to follow.</p>\n\n<p>Algorithmically, the sieve has a big advantage because it uses the previously calculated primes to make checking the next prime faster. You don't need to check every number for divisions, just the primes. You could do something like:</p>\n\n<pre><code>past_primes = []\nfor x in itertools.count(2):\n if not any(x % prime == 0 for prime in past_primes):\n past_primes.append(x)\n yield x\n</code></pre>\n\n<p>Performing the division will still be more expensive than what the sieve has to do. You could implement the entire sieve algorithm in a generator. But I'm not sure what purpose that would serve.</p>\n\n<p>Generally, generators work nicely when you don't have to maintain a lot of state for each value generated. But that's not the case for primes. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T17:37:58.137", "Id": "10846", "Score": "1", "body": "It's not really necessary to test divisibility by all past primes, only by ones up to `sqrt(x)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T20:10:21.187", "Id": "6698", "ParentId": "6696", "Score": "7" } } ]
<p>I'm trying to implement simple data streamer in Python with sockets. Consider one server and one or more clients. I just want to read data from server, process it and send it to the client. Here's how I do it now:</p> <pre><code> outputsocket = socket.socket() outputsocket.bind((self.outputaddress, self.outputport)) outputsocket.listen(2) inputsocket = socket.socket() rsocks, wsocks = [], [] rsocks.append(outputsocket) rsocks.append(inputsocket) recv_data = [] try: inputsocket.connect((self.inputaddress, self.inputport)) while True: try: reads, writes, errs = select.select(rsocks, [], []) except: return for sock in reads: if sock == outputsocket: client, address = sock.accept() wsocks.append(client) elif sock == inputsocket: data_from_socket = sock.recv(8192) if data_from_socket: outdata = process_data(data_from_socket) if wsocks: reads, writes, errs = select.select([], wsocks, [], 0) for sock in writes: sock.send(outdata) except KeyboardInterrupt: inputsocket.close() outputsocket.close() # etc </code></pre> <p>Obviously, it's stripped down example, but I think you got the idea. Does anyone have better ideas?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:34:46.507", "Id": "11045", "Score": "1", "body": "You might want to put `inputsocket.close()` and `outputsocket.close()` in a `finally:` block, instead of in the exception block, as a general clean up measure." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T18:30:45.863", "Id": "6722", "Score": "4", "Tags": [ "python" ], "Title": "implementing simple stream processor with sockets" }
6722
max_votes
[ { "body": "<p>For the benefit of others (because this answer is two years late):</p>\n\n<p>I had to implement a socket solution rapidly to accommodate testing a feature that required them. Ended up using <a href=\"http://docs.python.org/3.3/library/socketserver.html\" rel=\"nofollow\">socketserver</a> to simplify the implementation, i.e., only about a dozen lines were needed.</p>\n\n<p>Example below is pretty much straight out of the socket server docs:</p>\n\n<pre><code>\"\"\" creates, activates a socket server \"\"\"\nimport socketserver\n\nHOST, PORT = \"localhost\", 9999\n\n\nclass MyTCPHandler(socketserver.BaseRequestHandler):\n def handle(self):\n # self.request is the TCP socket connected to the client\n self.data = self.request.recv(1024).strip()\n print(\"{} wrote:\".format(self.client_address[0]))\n print(self.data)\n # just send back the same data, but upper-cased\n self.request.sendall(self.data.upper())\n\n\nprint(\"Creating the server, binding to localhost on port\", PORT)\nserver = socketserver.TCPServer((HOST, PORT), MyTCPHandler)\n\n\ndef activate_server():\n server.serve_forever()\n\n\ndef stop_server():\n print(\"Shutting the server on port\", PORT)\n server.shutdown()\n\n\nif __name__ == \"__main__\":\n activate_server()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T15:28:18.650", "Id": "37596", "ParentId": "6722", "Score": "2" } } ]
<p>Here is a small script I wrote to get the HNews ask section and display them without using a web browser. I'm just looking for feedback on how to improve my style/coding logic/overall code.</p> <pre><code>#!/usr/bin/python '''This script gets the headlines from hacker news ask section''' import urllib2 import HTMLParser import re class HNParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.data=[] self.recording=0 def handle_starttag(self, tag, attribute): if tag!='a': return elif self.recording: self.recording +=1 return for name, value in attribute: if name=='href' and value[0]=='i': break else: return self.recording=1 def handle_endtag(self, tag): if tag=='a' and self.recording: self.recording-=1 def handle_data(self, data): if self.recording: self.data.append(data) HOST='http://news.ycombinator.com/ask' parser=HNParser() f=urllib2.urlopen(HOST) rawHTML=f.read() parser.feed(rawHTML) i=0 for items in parser.data: try: print parser.data[2*i] i+=1 except IndexError: break parser.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T00:53:22.533", "Id": "10673", "Score": "0", "body": "You'll almost definitely get someone who points out that your indenting is incorrect ... wait that was me! Just check the preview before you submit it so that the code section looks the same as your file." } ]
{ "AcceptedAnswerId": "7085", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T23:41:06.660", "Id": "6813", "Score": "2", "Tags": [ "python", "web-scraping" ], "Title": "HNews \"ask section\" page scraping Python script" }
6813
accepted_answer
[ { "body": "<p>This is how I would modify your script. Comments are inline. This version is PEP8-PyLint-PyFlakes approved. ;-)</p>\n\n<pre><code>#!/usr/bin/python\n\n'''This script gets the headlines from hacker news ask section'''\n\nimport urllib2\nimport HTMLParser\n# remove unused imports\n\n\nclass HNParser(HTMLParser.HTMLParser):\n\n # use class-level attribute instead of \"magic\" strings.\n tag_name = 'a'\n\n def __init__(self):\n HTMLParser.HTMLParser.__init__(self)\n self.data = []\n self.recording = 0\n\n def handle_starttag(self, tag, attribute):\n\n if tag != self.tag_name:\n return\n\n # clearer implicit loop, with no \"break\"\n if not any(name == 'href' and value.startswith('item')\n for name, value in attribute):\n return\n\n # no need to check if self.recording == 0, because in that case setting\n # self.recording = 1 is equivalent to incrementing self.recording!\n self.recording += 1\n\n def handle_endtag(self, tag):\n if tag == self.tag_name and self.recording:\n self.recording -= 1\n\n def handle_data(self, data):\n if self.recording:\n self.data.append(data)\n\n\ndef main():\n HOST = 'http://news.ycombinator.com/ask'\n parser = HNParser()\n f = urllib2.urlopen(HOST)\n rawHTML = f.read()\n parser.feed(rawHTML)\n try:\n # use fancy list indexing and omit last \"Feature Request\" link\n for item in parser.data[:-1:2]:\n print item\n finally:\n # close the parser even if exception is raised\n parser.close()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-14T20:22:46.440", "Id": "22115", "Score": "0", "body": "I’m not convinced that the generic `tag_name` is more readable than `'a'`, on the contrary. I’m all for using an attribute here, but give it a proper name. The context suggets that it should be called `starttag` – or maybe `linktag`. Also, the `try … finally: parser.close()` should be replaced with a `with` block." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T15:31:04.650", "Id": "7085", "ParentId": "6813", "Score": "1" } } ]
<p><strong>Magnus Lie Hetland</strong> in his <strong>Beginning python</strong> wrote a code to replicate the range() built-in.</p> <pre><code>def interval(start, stop=None, step=1): if stop is None: start, stop = 0, start result = [] i = start while i &lt; stop: result.append(i) i += step return result </code></pre> <p>I re-wrote it like this.</p> <pre><code>def interval(*args): if len(args)&lt;1: raise TypeError('range expected at least 1 arguments, got 0') elif len(args)&gt;3 : raise TypeError('range expected at most 3 arguments, got %d' % len(args)) else: if len(args)==1: start = 0 stop = args[0] step = 1 elif len(args)==2: start=args[0] stop=args[1] step=1 elif len(args)==3: start=args[0] stop=args[1] step=args[2] result = [] while start &lt; stop: result.append(start) start+=step return result </code></pre> <p>I know my code is lengthier but don't you people think its easier to grasp/understand than Hetland's code? Different peoples' minds work differently. In my mind the code felt easier to understand cos I come from a <strong>C</strong> background. My emphasis is on code comprehension.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T08:55:33.557", "Id": "10740", "Score": "0", "body": "You got **Magnus Lie Hetland**'s version slightly wrong. The line that reads `i = start` is indented one level too far." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T05:59:50.693", "Id": "6858", "Score": "3", "Tags": [ "python", "c" ], "Title": "Thinking in python" }
6858
max_votes
[ { "body": "<p>This is bad</p>\n\n<pre><code> while start &lt; stop:\n result.append(start)\n start+=step\n</code></pre>\n\n<p>Don't reuse <code>start</code> to be the index of the loop. It's confusing. It violates the <em>meaning</em> of start. </p>\n\n<p>The lengthy parameter parsing is good, but can be made more clear. Don't waste time on checking for <code>&lt;1</code> or <code>&gt;3</code>. Just use the <code>if</code> statement.</p>\n\n<pre><code>if len(args)==1:...\nelif len(args)==2:...\nelif len(args)==3:...\nelse:\n raise TypeError( \"Wrong number of arguments\" )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T04:04:45.407", "Id": "11409", "Score": "0", "body": "Well,the range() built-in shows the argument No in exception message like **range expected at least 1 arguments, got 0**.I wanted to emulate it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T13:29:22.843", "Id": "11437", "Score": "0", "body": "@Jibin: \"built-in shows the argument number\". That doesn't mean it's **good** design. It should also be part of the `else` clause if it's so important to provide that kind of message." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T04:32:19.820", "Id": "11584", "Score": "0", "body": ":got that.I think there is a psychological reason to 'why error/exception should be in else case'.Suppose a programmer is reading the code, for first few moments his mind is fresh so main logic should come first,error/exceptions can come last.What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T23:06:05.583", "Id": "11669", "Score": "0", "body": "\"logic should come first,error/exceptions can come last.\" I'm unclear on how it can be otherwise. What's the alternative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T06:57:35.190", "Id": "12048", "Score": "0", "body": "As in my code - the exception comes first in the `if` clause and actual the calculation of `range` comes last in the `else` clause." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T13:07:34.513", "Id": "12067", "Score": "0", "body": "@Jibin: I'm confused. First you say \"logic should come first,error/exceptions can come last\". I agree with you. Then you say \"the exception comes first in the if clause\". I thought you agreed that the exception should come first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-16T11:43:25.263", "Id": "12447", "Score": "0", "body": "Never mind.Thank you for putting up with me this far" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T12:01:12.643", "Id": "6916", "ParentId": "6858", "Score": "3" } } ]