body
stringlengths
144
5.53k
comments
list
meta_data
dict
question_id
stringlengths
1
6
yield
stringclasses
2 values
answers
list
<p>I took the Python class at Google code today, and this is what I made for the problem about building a word counter.</p> <p>Please take a look and suggest any improvements that can be done. Please do point out the bad practices if I have used any.</p> <pre><code>import sys def make_dict(filename): """returns a word/count dictionary for the given input file""" myFile=open(filename,'rU') text=myFile.read() words=text.lower().split() wordcount_dict={} #map each word to its count for word in words: wordcount_dict[word]=0 for word in words: wordcount_dict[word]=wordcount_dict[word]+1 myFile.close() return wordcount_dict def print_words(filename): """prints each word in the file followed by its count""" wordcount_dict=make_dict(filename) for word in wordcount_dict.keys(): print word, " " , wordcount_dict[word] def print_top(filename): """prints the words with the top 20 counts""" wordcount_dict=make_dict(filename) keys = wordcount_dict.keys() values = sorted(wordcount_dict.values()) for x in xrange (1,21): #for the top 20 values for word in keys : if wordcount_dict[word]==values[-x]: print word, " ",wordcount_dict[word] def main(): if len(sys.argv) != 3: print 'usage: ./wordcount.py {--count | --topcount} file' sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_words(filename) elif option == '--topcount': print_top(filename) else: print 'unknown option: ' + option sys.exit(1) if __name__ == '__main__': main() </code></pre>
[]
{ "AcceptedAnswerId": "6865", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T12:41:18.810", "Id": "6863", "Score": "6", "Tags": [ "python", "optimization", "programming-challenge" ], "Title": "Optimizing word counter" }
6863
accepted_answer
[ { "body": "<p>I like the way you've broken down the code into functions, I think it makes sense and avoids repetition or duplication of code and functionality.</p>\n\n<p>One slight improvement to consider here is to have <code>print_words</code> and <code>print_top</code> take the dictionary returned from <code>make_dict</code> rather than calling it as their first step. In addition to avoiding a tiny amount of duplicated code, this sort of \"function composition\" when used effectively can be a very powerful design pattern, allowing very expressive and readable code for more complicated problems than this one.</p>\n\n<p>A few other specific thoughts:</p>\n\n<p>In <code>make_dict</code>, you're reading the entire file contents into memory, and then processing each word twice. This works well enough for small files, but imagine that you had a 500 gigabyte text file? In this case, reading the file into memory (\"buffering\" it) will lead to a program crash, or at the very least, very bad performance.</p>\n\n<p>Instead, you can actually iterate the file in a <code>for</code> loop, which will only read small portions of the file into memory at once. This requires a slight change to your logic in <code>make_dict</code>:</p>\n\n<pre><code>myFile=open(filename,'rU')\nwordcount_dict={} #map each word to its count\nfor line in myFile:\n # .strip() removes the newline character from the\n # end of the line, as well as any leading or trailing\n # white-space characters (spaces, tabs, etc)\n words = line.strip().lower().split()\n for word in words:\n if word not in wordcount_dict:\n wordcount_dict[word] = 0\n wordcount_dict[word] += 1\n</code></pre>\n\n<p>In <code>print_words</code>, you're using <code>.keys()</code> to get the words from the <code>wordcount_dict</code>, then accessing those keys from the dictionary. This works fine, but Python dictionaries allow you to get <em>items</em> (that is, key-value pairs) directly when iterating a dictionary, using <code>.items()</code> instead of <code>.keys()</code>:</p>\n\n<pre><code>for word, count in wordcount_dict.items():\n print word, \" \" , count\n</code></pre>\n\n<p><code>items()</code> returns a list of length-2 tuples, and the <code>for word, count in ...</code> syntax \"unpacks\" those tuples into the variables <code>word</code> and <code>count</code>.</p>\n\n<p>Building on this technique, we can simplify <code>print_top</code> as well. Once we have in hand a list of each (word, count) pair (the length-2 tuples), we can sort that list, and then print only the top 20 words (ranked by their count):</p>\n\n<pre><code>wordcount_dict=make_dict(filename)\nword_count_pairs = wordcount_dict.items()\nword_count_pairs.sort(\n # use a \"key\" function to return the sort key\n # for each item in the list we are sorting; here\n # we return index 1 -- that is, the count -- to\n # sort by that\n key=lambda pair: pair[1],\n\n # reverse the sort so that the words with the\n # highest counts come first in the sorted list\n reverse=True\n)\n\n# make a copy of the first 20 elements of the\n# list, using slice notation\ntop_word_count_pairs = word_count_pairs[:20]\n\nfor word, count in top_word_count_pairs:\n print word, \" \",wordcount_dict[word]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T13:15:47.277", "Id": "6865", "ParentId": "6863", "Score": "2" } } ]
<p>Which version of this code is better?</p> <p>Ver 1.</p> <pre><code>a = 0 for i in xrange( 1000 ): if i % 3 == 0 or i % 5 == 0: a += i print a </code></pre> <p>Ver 2.</p> <pre><code>from operator import add print reduce( add, ( i for i in xrange( 1000 ) if i % 3 == 0 or i % 5 == 0 ) ) </code></pre> <p>Things I like about version one is that it is more readable, but it creates requires a variable. If you had to choose, which one would you argue is better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:26:40.117", "Id": "10824", "Score": "1", "body": "Version 3: Use the `sum()` function with the generator used in version 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T01:11:49.140", "Id": "10856", "Score": "1", "body": "is `list descriptor` a correct name for that ? Should not be `for-loops` vs `generator comprehensions` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T01:30:30.953", "Id": "10857", "Score": "0", "body": "@joaquin Yes, it should (and is now). Descriptors are [something entirely different](http://users.rcn.com/python/download/Descriptor.htm)." } ]
{ "AcceptedAnswerId": "6928", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:19:33.193", "Id": "6927", "Score": "7", "Tags": [ "python" ], "Title": "What is better? For-loops or generator expressions (in cases like this)" }
6927
accepted_answer
[ { "body": "<p>The second version can (and should) be written using <code>sum</code> instead of <code>reduce(add,...)</code>, which is somewhat more readable:</p>\n\n<pre><code>sum(i for i in xrange( 1000 ) if i % 3 == 0 or i % 5 == 0)\n</code></pre>\n\n<p>That is the version that I'd prefer as far as implementations of this particular algorithm go because it's more declarative than a loop and just reads nicer in my opinion. (It's also faster though that's less of a concern).</p>\n\n<p>However it should be noted that for summing all numbers up to n that divisible by 3 or 5, <a href=\"https://codereview.stackexchange.com/a/280/128\">there's actually a better algorithm than going over all those numbers and summing them</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-01T01:01:55.780", "Id": "360280", "Score": "0", "body": "On testing, the generator version is not faster than a simple `for` loop. Do you have a reference / benchmarking to support your claim?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:30:11.403", "Id": "6928", "ParentId": "6927", "Score": "8" } } ]
<p>I have a data structure that looks like this:</p> <pre><code>a = { 'red': ['yellow', 'green', 'purple'], 'orange': ['fuschia'] } </code></pre> <p>This is the code I write to add new elements:</p> <pre><code>if a.has_key(color): a[color].append(path) else: a[color] = [path] </code></pre> <p>Is there a shorter way to write this?</p>
[]
{ "AcceptedAnswerId": "7029", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T19:15:31.217", "Id": "7028", "Score": "1", "Tags": [ "python" ], "Title": "Shorter way to write list-as-dict-value in Python?" }
7028
accepted_answer
[ { "body": "<p>You can use <a href=\"http://docs.python.org/library/collections.html\">collections.defaultdict</a>:</p>\n\n<pre><code>from collections import defaultdict\n\nmydict = defaultdict(list)\n</code></pre>\n\n<p>Now you just need:</p>\n\n<pre><code>mydict[color].append(path)\n</code></pre>\n\n<p><code>defaultdict</code> is a subclass of <code>dict</code> that can be initialized to a list, integer... </p>\n\n<hr>\n\n<p>btw, the use of <code>has_key</code> is discouraged, and in fact <code>has_key</code> has been removed from python 3.2.<br>\nWhen needed, use this by far more pythonic idiom instead:</p>\n\n<pre><code>if color in a:\n ........\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T08:58:16.137", "Id": "10965", "Score": "0", "body": "even better is\ntry:\n a[color].append(path)\nexcept KeyError:\n a[color] = [path]\n\n... and this comment formatting is broken :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T21:24:35.880", "Id": "11131", "Score": "1", "body": "@blaze try/except is better? I'd say not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T13:11:16.023", "Id": "11160", "Score": "0", "body": "if try is usually successful and exception isn't raised - it's effective. one less \"if\" to check." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T15:39:10.923", "Id": "11169", "Score": "0", "body": "lots of stuff happening around checking whether operation goes right and whether exception is thrown. besides the semantics of \"exception\" should be that something, well, exceptional is taking place. I'd avoid using exceptions for regular code flow if a convenient alternative exists" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T19:22:25.153", "Id": "7029", "ParentId": "7028", "Score": "7" } } ]
<p>I'm working through an introduction to computer science book, this is not homework for me but me trying to learn in my spare time, I'm not asking for homework help!</p> <p>The output is below, and this is all ok, but I'm just certain there is a more efficient way of doing this. I have been trying for many hours now and this is still the best solution I can come up with, if anyone can improve upon this and possibly explain how, I would highly appreciate it.</p> <p>The code:</p> <pre><code>naught = 0 one = 0 two = 0 three = 0 four = 0 five = 0 six = 0 seven = 0 eight = 0 nine = 0 for i in range (0, 10): print("") for i in range (0,1): print(naught, end = " ") for i in range (0,1): print(one, end = " ") one += 1 for i in range (0,1): print(two, end = " ") two += 2 for i in range (0,1): print(three, end = " ") three += 3 for i in range (0,1): print(four, end = " ") four += 4 for i in range (0,1): print(five, end = " ") five += 5 for i in range (0,1): print(six, end = " ") six += 6 for i in range (0,1): print(seven, end = " ") seven += 7 for i in range (0,1): print(eight, end = " ") eight += 8 for i in range (0,1): print(nine, end = " ") nine += 9 </code></pre> <p>The output is below and that is all correct, that's no problem.</p> <pre><code>0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 10 12 14 16 18 0 3 6 9 12 15 18 21 24 27 0 4 8 12 16 20 24 28 32 36 0 5 10 15 20 25 30 35 40 45 0 6 12 18 24 30 36 42 48 54 0 7 14 21 28 35 42 49 56 63 0 8 16 24 32 40 48 56 64 72 0 9 18 27 36 45 54 63 72 81 </code></pre> <p>As I said I'm getting the right answer, just I'm not satisfied that it's in the best way. Many thanks, Matt.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:35:51.073", "Id": "11018", "Score": "1", "body": "Is this literally a multiplication table generator?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T20:54:06.717", "Id": "11019", "Score": "2", "body": "`range(0,1)` = `range(1)` = `[0]` = one iteration? I don't get the point of doing a single iteration for-loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T21:02:13.293", "Id": "11020", "Score": "2", "body": "@julio.alegria this has got to be the first time I have seen anyone do that deliberately and not as a joke." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:32:28.160", "Id": "7068", "Score": "4", "Tags": [ "python" ], "Title": "Improving many for loops, any more efficient alternative?" }
7068
max_votes
[ { "body": "<pre><code>for i in range(10):\n for j in range(10):\n print i*j,\n print \"\"</code></pre>\n\n<p>Something like this, perhaps?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:37:25.313", "Id": "7069", "ParentId": "7068", "Score": "10" } } ]
<p>I'm working through an introduction to computer science book, this is not homework for me but me trying to learn in my spare time, I'm not asking for homework help!</p> <p>The output is below, and this is all ok, but I'm just certain there is a more efficient way of doing this. I have been trying for many hours now and this is still the best solution I can come up with, if anyone can improve upon this and possibly explain how, I would highly appreciate it.</p> <p>The code:</p> <pre><code>naught = 0 one = 0 two = 0 three = 0 four = 0 five = 0 six = 0 seven = 0 eight = 0 nine = 0 for i in range (0, 10): print("") for i in range (0,1): print(naught, end = " ") for i in range (0,1): print(one, end = " ") one += 1 for i in range (0,1): print(two, end = " ") two += 2 for i in range (0,1): print(three, end = " ") three += 3 for i in range (0,1): print(four, end = " ") four += 4 for i in range (0,1): print(five, end = " ") five += 5 for i in range (0,1): print(six, end = " ") six += 6 for i in range (0,1): print(seven, end = " ") seven += 7 for i in range (0,1): print(eight, end = " ") eight += 8 for i in range (0,1): print(nine, end = " ") nine += 9 </code></pre> <p>The output is below and that is all correct, that's no problem.</p> <pre><code>0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 10 12 14 16 18 0 3 6 9 12 15 18 21 24 27 0 4 8 12 16 20 24 28 32 36 0 5 10 15 20 25 30 35 40 45 0 6 12 18 24 30 36 42 48 54 0 7 14 21 28 35 42 49 56 63 0 8 16 24 32 40 48 56 64 72 0 9 18 27 36 45 54 63 72 81 </code></pre> <p>As I said I'm getting the right answer, just I'm not satisfied that it's in the best way. Many thanks, Matt.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:35:51.073", "Id": "11018", "Score": "1", "body": "Is this literally a multiplication table generator?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T20:54:06.717", "Id": "11019", "Score": "2", "body": "`range(0,1)` = `range(1)` = `[0]` = one iteration? I don't get the point of doing a single iteration for-loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T21:02:13.293", "Id": "11020", "Score": "2", "body": "@julio.alegria this has got to be the first time I have seen anyone do that deliberately and not as a joke." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:32:28.160", "Id": "7068", "Score": "4", "Tags": [ "python" ], "Title": "Improving many for loops, any more efficient alternative?" }
7068
max_votes
[ { "body": "<pre><code>for i in range(10):\n for j in range(10):\n print i*j,\n print \"\"</code></pre>\n\n<p>Something like this, perhaps?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:37:25.313", "Id": "7069", "ParentId": "7068", "Score": "10" } } ]
<p>The goal is displaying the date and time of an article in a humanized and localized way:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Yesterday 13:21 </code></pre> </blockquote> <p>or if the Swedish language parameter is set it will display:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Igår 13:21 </code></pre> </blockquote> <p>And if the date wasn't yesterday or today, it will print the date and 24-hour time. I think I succeeded with everything except handling the timezone:</p> <pre class="lang-py prettyprint-override"><code>def datetimeformat_jinja(value, format='%H:%M / %d-%m-%Y', locale='en'): now= datetime.now() info = None if datetime.date(value) == datetime.date(now): info= _('Today') elif (now - value).days &lt; 2: info= _('Yesterday') else: month = value.month if month == 1: info = str(value.day)+' '+_('Jan') elif month == 2: info = str(value.day)+' '+_('Feb') elif month == 3: info = str(value.day)+' '+_('Mar') elif month == 4: info = str(value.day)+' '+_('April') elif month == 5: info = str(value.day)+' '+_('May') elif month == 6: info = str(value.day)+' '+_('June') elif month == 7: info = str(value.day)+' '+_('July') elif month == 8: info = str(value.day)+' '+_('Aug') elif month == 9: info = str(value.day)+' '+_('Sep') elif month == 10: info = str(value.day)+' '+_('Oct') elif month == 11: info = str(value.day)+' '+_('Nov') else: info = str(value.day)+' '+_('Dec') return info+'&lt;br&gt;'+format_time(value, 'H:mm', locale=locale) </code></pre> <p>The above code localizes and humanizes the output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Today 3:29 </code></pre> </blockquote> <p>I can also switch languages to, for example, Portuguese:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Hoje 3:29 </code></pre> </blockquote> <p>Where "Hoje" means "today," so the filter appears to work. </p> <p>Could you please review it or give me a hint on how I can admit my code to also allow time zones? I use babel for localization and Jinja2 for rendering. </p>
[]
{ "AcceptedAnswerId": "7150", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T03:41:20.930", "Id": "7147", "Score": "4", "Tags": [ "python", "datetime", "i18n" ], "Title": "Date and time of an article in a humanized and localized way" }
7147
accepted_answer
[ { "body": "<h2>Adding time zone support</h2>\n\n<p>Add a new argument to your function: <code>now</code>. This should be the localized datetime of the client. Compare <code>now</code> to the current server datetime and adjust the formatted time by the difference between them. Boom, timezone support added.</p>\n\n<p>That said <strong><em>you cannot get the client timezone server-side</em></strong>. Look into client-side solutions with JavaScript (either full client-side date formatting, or phoning home). <a href=\"https://stackoverflow.com/q/2542206/998283\">This should start you off on the right track.</a></p>\n\n<p>On with the code review.</p>\n\n<h2>Tidying up the code</h2>\n\n<h3>Variable and function naming</h3>\n\n<ul>\n<li><code>info</code> and <code>value</code> are excessively vague. </li>\n<li><code>datetimeformat_jinja()</code> is a bit eccentric as a function name, as its not in imperative form (eg <code>format_datetime</code>).</li>\n</ul>\n\n<h3>String formatting</h3>\n\n<p>Concatenating strings with addition is considered bad practice is Python. You should format individual elements of your message together, rather than starting with <code>info=''</code> and adding new parts as you go along. Use <a href=\"http://docs.python.org/library/string.html#string-formatting\" rel=\"nofollow noreferrer\"><code>str.format()</code></a> (or <code>%s</code>-formatting with Python 2.5 and below) to achieve this.</p>\n\n<h3>The <code>If</code>-<code>elif</code>-<code>else</code> chain</h3>\n\n<p>In lines 9 through 33 you copy-pasted the same logic twelve times over; that's a sure-fire sign you need to express things more generically.</p>\n\n<h3>Style</h3>\n\n<p>Take this suggestion for the petty nothing it is, but—please, please, please—unless you're following the style guidelines of your team or employer, read and obey <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.</p>\n\n<h2>Result</h2>\n\n<pre><code>MONTHS = ('Jan', 'Feb', 'Mar', 'April', 'May', 'June',\n 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')\nFORMAT = '%H:%M / %d-%m-%Y'\n\ndef format_datetime(to_format, format=FORMAT, locale='en'):\n now = datetime.now()\n if datetime.date(to_format) == datetime.date(now):\n date_str = _('Today')\n elif (now - to_format).days &lt; 2:\n date_str = _('Yesterday')\n else:\n month = MONTHS[to_format.month - 1]\n date_str = '{0} {1}'.format(to_format.day, _(month))\n time_str = format_time(to_format, 'H:mm', locale=locale)\n return \"{0}&lt;br&gt;{1}\".format(date_str, time_str)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T07:33:11.817", "Id": "7150", "ParentId": "7147", "Score": "4" } } ]
<p>The goal is displaying the date and time of an article in a humanized and localized way:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Yesterday 13:21 </code></pre> </blockquote> <p>or if the Swedish language parameter is set it will display:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Igår 13:21 </code></pre> </blockquote> <p>And if the date wasn't yesterday or today, it will print the date and 24-hour time. I think I succeeded with everything except handling the timezone:</p> <pre class="lang-py prettyprint-override"><code>def datetimeformat_jinja(value, format='%H:%M / %d-%m-%Y', locale='en'): now= datetime.now() info = None if datetime.date(value) == datetime.date(now): info= _('Today') elif (now - value).days &lt; 2: info= _('Yesterday') else: month = value.month if month == 1: info = str(value.day)+' '+_('Jan') elif month == 2: info = str(value.day)+' '+_('Feb') elif month == 3: info = str(value.day)+' '+_('Mar') elif month == 4: info = str(value.day)+' '+_('April') elif month == 5: info = str(value.day)+' '+_('May') elif month == 6: info = str(value.day)+' '+_('June') elif month == 7: info = str(value.day)+' '+_('July') elif month == 8: info = str(value.day)+' '+_('Aug') elif month == 9: info = str(value.day)+' '+_('Sep') elif month == 10: info = str(value.day)+' '+_('Oct') elif month == 11: info = str(value.day)+' '+_('Nov') else: info = str(value.day)+' '+_('Dec') return info+'&lt;br&gt;'+format_time(value, 'H:mm', locale=locale) </code></pre> <p>The above code localizes and humanizes the output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Today 3:29 </code></pre> </blockquote> <p>I can also switch languages to, for example, Portuguese:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Hoje 3:29 </code></pre> </blockquote> <p>Where "Hoje" means "today," so the filter appears to work. </p> <p>Could you please review it or give me a hint on how I can admit my code to also allow time zones? I use babel for localization and Jinja2 for rendering. </p>
[]
{ "AcceptedAnswerId": "7150", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T03:41:20.930", "Id": "7147", "Score": "4", "Tags": [ "python", "datetime", "i18n" ], "Title": "Date and time of an article in a humanized and localized way" }
7147
accepted_answer
[ { "body": "<h2>Adding time zone support</h2>\n\n<p>Add a new argument to your function: <code>now</code>. This should be the localized datetime of the client. Compare <code>now</code> to the current server datetime and adjust the formatted time by the difference between them. Boom, timezone support added.</p>\n\n<p>That said <strong><em>you cannot get the client timezone server-side</em></strong>. Look into client-side solutions with JavaScript (either full client-side date formatting, or phoning home). <a href=\"https://stackoverflow.com/q/2542206/998283\">This should start you off on the right track.</a></p>\n\n<p>On with the code review.</p>\n\n<h2>Tidying up the code</h2>\n\n<h3>Variable and function naming</h3>\n\n<ul>\n<li><code>info</code> and <code>value</code> are excessively vague. </li>\n<li><code>datetimeformat_jinja()</code> is a bit eccentric as a function name, as its not in imperative form (eg <code>format_datetime</code>).</li>\n</ul>\n\n<h3>String formatting</h3>\n\n<p>Concatenating strings with addition is considered bad practice is Python. You should format individual elements of your message together, rather than starting with <code>info=''</code> and adding new parts as you go along. Use <a href=\"http://docs.python.org/library/string.html#string-formatting\" rel=\"nofollow noreferrer\"><code>str.format()</code></a> (or <code>%s</code>-formatting with Python 2.5 and below) to achieve this.</p>\n\n<h3>The <code>If</code>-<code>elif</code>-<code>else</code> chain</h3>\n\n<p>In lines 9 through 33 you copy-pasted the same logic twelve times over; that's a sure-fire sign you need to express things more generically.</p>\n\n<h3>Style</h3>\n\n<p>Take this suggestion for the petty nothing it is, but—please, please, please—unless you're following the style guidelines of your team or employer, read and obey <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.</p>\n\n<h2>Result</h2>\n\n<pre><code>MONTHS = ('Jan', 'Feb', 'Mar', 'April', 'May', 'June',\n 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')\nFORMAT = '%H:%M / %d-%m-%Y'\n\ndef format_datetime(to_format, format=FORMAT, locale='en'):\n now = datetime.now()\n if datetime.date(to_format) == datetime.date(now):\n date_str = _('Today')\n elif (now - to_format).days &lt; 2:\n date_str = _('Yesterday')\n else:\n month = MONTHS[to_format.month - 1]\n date_str = '{0} {1}'.format(to_format.day, _(month))\n time_str = format_time(to_format, 'H:mm', locale=locale)\n return \"{0}&lt;br&gt;{1}\".format(date_str, time_str)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T07:33:11.817", "Id": "7150", "ParentId": "7147", "Score": "4" } } ]
<p>I have an MD5 hash string:</p> <pre><code>_hash = '743a0e0c5c657d3295d347a1f0a66109' </code></pre> <p>I want to write function that splits passed string to path in nginx cache format:</p> <pre><code>print hash2path(_hash, [1, 2, 3]) # outputs '7/43/a0e/743a0e0c5c657d3295d347a1f0a66109' </code></pre> <p>This is my variant:</p> <pre><code>def hash2path(_hash, levels): hash_copy = _hash parts = [] for level in levels: parts.append(_hash[:level]) _hash = _hash[level:] parts.append(hash_copy) return '/'.join(parts) </code></pre> <p>How could this be improved?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T05:58:48.010", "Id": "7298", "Score": "1", "Tags": [ "python", "cryptography" ], "Title": "Nginx cache path function" }
7298
max_votes
[ { "body": "<p>Why you can't just hardcode cache path calculation?</p>\n\n<pre><code>&gt;&gt;&gt; _hash = '743a0e0c5c657d3295d347a1f0a66109'\n&gt;&gt;&gt; def hash2path(_hash):\n... return \"%s/%s/%s/%s\" % (_hash[0], _hash[1:3], _hash[3:6], _hash)\n... \n&gt;&gt;&gt; hash2path(_hash)\n'7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'\n</code></pre>\n\n<p>UPDATE: If you really need to pass level array there is a little bit faster version:</p>\n\n<pre><code>def hash2path(_hash, levels):\n prev = 0\n parts = []\n for level in levels:\n parts.append(_hash[prev:prev + level])\n prev += level\n parts.append(_hash)\n return \"/\".join(parts)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T07:49:34.160", "Id": "11419", "Score": "0", "body": "The point is to pass level array to function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T18:30:46.267", "Id": "11447", "Score": "0", "body": "Thank you, Dmitry. But it doesn't work correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T18:38:16.480", "Id": "11448", "Score": "0", "body": "Works if `prev += level` is in 6th line" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T22:21:41.810", "Id": "11466", "Score": "0", "body": "Ah, you're right. I didn't test it thoroughly." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T07:34:33.657", "Id": "7299", "ParentId": "7298", "Score": "3" } } ]
<p>I have an MD5 hash string:</p> <pre><code>_hash = '743a0e0c5c657d3295d347a1f0a66109' </code></pre> <p>I want to write function that splits passed string to path in nginx cache format:</p> <pre><code>print hash2path(_hash, [1, 2, 3]) # outputs '7/43/a0e/743a0e0c5c657d3295d347a1f0a66109' </code></pre> <p>This is my variant:</p> <pre><code>def hash2path(_hash, levels): hash_copy = _hash parts = [] for level in levels: parts.append(_hash[:level]) _hash = _hash[level:] parts.append(hash_copy) return '/'.join(parts) </code></pre> <p>How could this be improved?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T05:58:48.010", "Id": "7298", "Score": "1", "Tags": [ "python", "cryptography" ], "Title": "Nginx cache path function" }
7298
max_votes
[ { "body": "<p>Why you can't just hardcode cache path calculation?</p>\n\n<pre><code>&gt;&gt;&gt; _hash = '743a0e0c5c657d3295d347a1f0a66109'\n&gt;&gt;&gt; def hash2path(_hash):\n... return \"%s/%s/%s/%s\" % (_hash[0], _hash[1:3], _hash[3:6], _hash)\n... \n&gt;&gt;&gt; hash2path(_hash)\n'7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'\n</code></pre>\n\n<p>UPDATE: If you really need to pass level array there is a little bit faster version:</p>\n\n<pre><code>def hash2path(_hash, levels):\n prev = 0\n parts = []\n for level in levels:\n parts.append(_hash[prev:prev + level])\n prev += level\n parts.append(_hash)\n return \"/\".join(parts)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T07:49:34.160", "Id": "11419", "Score": "0", "body": "The point is to pass level array to function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T18:30:46.267", "Id": "11447", "Score": "0", "body": "Thank you, Dmitry. But it doesn't work correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T18:38:16.480", "Id": "11448", "Score": "0", "body": "Works if `prev += level` is in 6th line" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T22:21:41.810", "Id": "11466", "Score": "0", "body": "Ah, you're right. I didn't test it thoroughly." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T07:34:33.657", "Id": "7299", "ParentId": "7298", "Score": "3" } } ]
<p>I have an MD5 hash string:</p> <pre><code>_hash = '743a0e0c5c657d3295d347a1f0a66109' </code></pre> <p>I want to write function that splits passed string to path in nginx cache format:</p> <pre><code>print hash2path(_hash, [1, 2, 3]) # outputs '7/43/a0e/743a0e0c5c657d3295d347a1f0a66109' </code></pre> <p>This is my variant:</p> <pre><code>def hash2path(_hash, levels): hash_copy = _hash parts = [] for level in levels: parts.append(_hash[:level]) _hash = _hash[level:] parts.append(hash_copy) return '/'.join(parts) </code></pre> <p>How could this be improved?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T05:58:48.010", "Id": "7298", "Score": "1", "Tags": [ "python", "cryptography" ], "Title": "Nginx cache path function" }
7298
max_votes
[ { "body": "<p>Why you can't just hardcode cache path calculation?</p>\n\n<pre><code>&gt;&gt;&gt; _hash = '743a0e0c5c657d3295d347a1f0a66109'\n&gt;&gt;&gt; def hash2path(_hash):\n... return \"%s/%s/%s/%s\" % (_hash[0], _hash[1:3], _hash[3:6], _hash)\n... \n&gt;&gt;&gt; hash2path(_hash)\n'7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'\n</code></pre>\n\n<p>UPDATE: If you really need to pass level array there is a little bit faster version:</p>\n\n<pre><code>def hash2path(_hash, levels):\n prev = 0\n parts = []\n for level in levels:\n parts.append(_hash[prev:prev + level])\n prev += level\n parts.append(_hash)\n return \"/\".join(parts)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T07:49:34.160", "Id": "11419", "Score": "0", "body": "The point is to pass level array to function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T18:30:46.267", "Id": "11447", "Score": "0", "body": "Thank you, Dmitry. But it doesn't work correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T18:38:16.480", "Id": "11448", "Score": "0", "body": "Works if `prev += level` is in 6th line" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T22:21:41.810", "Id": "11466", "Score": "0", "body": "Ah, you're right. I didn't test it thoroughly." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T07:34:33.657", "Id": "7299", "ParentId": "7298", "Score": "3" } } ]
<p>Is there a better way to express the dispatch (switch) code without using a lambda? I think I need the lambda to act as an intermediary because the functions have varying numbers of parameters.</p> <pre><code>def printf(arg): print arg def printf2(arg1, arg2): print arg1 print arg2 def printn(arg): print arg action = 'op2' functions = { 'op1': lambda: printf('op1 called'), 'op2': lambda: printf2('op2 called', 'param 2'), } functions.get(action, lambda: printn('default op'))() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T01:58:23.687", "Id": "7433", "Score": "4", "Tags": [ "python" ], "Title": "Dictionary-based dispatch in Python with multiple parameters" }
7433
max_votes
[ { "body": "<p>You could change it to just store the functions <em>and</em> the arguments. Then use the argument unpacking to fill in the correct arguments to the function call.</p>\n\n<pre><code>action = 'op2'\nfunctions = {\n 'op1': (printf, ('op1 called',)),\n 'op2': (printf2, ('op2 called', 'param 2')),\n}\n\nfn, args = functions.get(action, (printn, ('default op',)))\nfn(*args) # call the function unpacking the provided arguments\n</code></pre>\n\n<hr>\n\n<p>A better solution in this particular case IMHO, rather than defining multiple functions with varying number of arguments, you could just define one function accepting variable arguments to achieve the same thing.</p>\n\n<pre><code>def printf(*args):\n if args:\n for arg in args:\n print arg\n else:\n print 'default op'\n</code></pre>\n\n<p>Then it's just a matter of storing only the arguments to the call rather than the functions themselves:</p>\n\n<pre><code>action = 'op2'\narguments = {\n 'op1': ('op1 called',),\n 'op2': ('op2 called', 'param 2'),\n}\n\nprintf(*arguments.get(action, ()))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T02:26:17.980", "Id": "7435", "ParentId": "7433", "Score": "2" } } ]
<p>Is there a better way to express the dispatch (switch) code without using a lambda? I think I need the lambda to act as an intermediary because the functions have varying numbers of parameters.</p> <pre><code>def printf(arg): print arg def printf2(arg1, arg2): print arg1 print arg2 def printn(arg): print arg action = 'op2' functions = { 'op1': lambda: printf('op1 called'), 'op2': lambda: printf2('op2 called', 'param 2'), } functions.get(action, lambda: printn('default op'))() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T01:58:23.687", "Id": "7433", "Score": "4", "Tags": [ "python" ], "Title": "Dictionary-based dispatch in Python with multiple parameters" }
7433
max_votes
[ { "body": "<p>You could change it to just store the functions <em>and</em> the arguments. Then use the argument unpacking to fill in the correct arguments to the function call.</p>\n\n<pre><code>action = 'op2'\nfunctions = {\n 'op1': (printf, ('op1 called',)),\n 'op2': (printf2, ('op2 called', 'param 2')),\n}\n\nfn, args = functions.get(action, (printn, ('default op',)))\nfn(*args) # call the function unpacking the provided arguments\n</code></pre>\n\n<hr>\n\n<p>A better solution in this particular case IMHO, rather than defining multiple functions with varying number of arguments, you could just define one function accepting variable arguments to achieve the same thing.</p>\n\n<pre><code>def printf(*args):\n if args:\n for arg in args:\n print arg\n else:\n print 'default op'\n</code></pre>\n\n<p>Then it's just a matter of storing only the arguments to the call rather than the functions themselves:</p>\n\n<pre><code>action = 'op2'\narguments = {\n 'op1': ('op1 called',),\n 'op2': ('op2 called', 'param 2'),\n}\n\nprintf(*arguments.get(action, ()))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T02:26:17.980", "Id": "7435", "ParentId": "7433", "Score": "2" } } ]
<p>I have this module which computes checksums from a list of files in a given directory. The problem is that my is_changed_file is long and ugly, but my attempts in refactoring failed, so I would like some other point of views...</p> <pre><code>import hashlib import logging # if available use the faster cPickle module try: import cPickle as pickle except ImportError: import pickle from os import path class DirectoryChecksum(object): """Manage the checksums of the given files in a directory """ def __init__(self, directory, to_hash): self.directory = directory self.to_hash = to_hash self.checksum_file = path.join(self.directory, '.checksums') self.checks = self._compute() self.logger = logging.getLogger("checksum(%s): " % self.directory) def _abs_path(self, filename): return path.join(self.directory, filename) def _get_checksum(self, filename): content = open(self._abs_path(filename)).read() return hashlib.md5(content).hexdigest() def _compute(self): """Compute all the checksums for the files to hash """ dic = {} for f in self.to_hash: if self._file_exists(f): dic[f] = self._get_checksum(f) return dic def _file_exists(self, filename): return path.isfile(self._abs_path(filename)) def is_changed(self): """True if any of the files to hash has been changed """ return any(self.is_file_changed(x) for x in self.to_hash) #FIXME: refactor this mess, there is also a bug which impacts on #the airbus. eggs, so probably something to do with the path def is_file_changed(self, filename): """Return true if the given file was changed """ if not self._has_checksum(): self.logger.debug("no checksum is available yet, creating it") self.write_checksums() return True stored_checks = self.load_checksums() if not self._file_exists(filename): if filename in stored_checks: self.logger.debug("file %s has been removed" % filename) # what if it existed before and now it doesn't?? return True else: return False checksum = self._get_checksum(filename) if filename in stored_checks: # if the file is already there but the values are changed # then we also need to rewrite the stored checksums if stored_checks[filename] != checksum: self.write_checksums() return True else: return False else: # this means that there is a new file to hash, just do it again self.write_checksums() return True def _has_checksum(self): return path.isfile(self.checksum_file) def load_checksums(self): """Load the checksum file, returning the dictionary stored """ return pickle.load(open(self.checksum_file)) def write_checksums(self): """Write to output (potentially overwriting) the computed checksum dictionary """ self.logger.debug("writing the checksums to %s" % self.checksum_file) return pickle.dump(self.checks, open(self.checksum_file, 'w')) </code></pre>
[]
{ "AcceptedAnswerId": "7595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-06T13:50:15.787", "Id": "7529", "Score": "2", "Tags": [ "python" ], "Title": "Python and computing checksums" }
7529
accepted_answer
[ { "body": "<p>Probably there is no need to refactor the method as it represents quite clear decision tree. Breaking it down into smaller methods will cause readability problems.</p>\n\n<p>Just make sure you have unit tests covering each outcome and that there are no cases, which the code doesn't handle.</p>\n\n<p>If you definitely want to refactor, I propose to add a method like this:</p>\n\n<pre><code>def _check_log_writesums(cond, logmessage, rewrite=True):\n if cond:\n if logmessage:\n self.logger.debug(logmessage)\n if rewrite:\n self.write_checksums()\n return True\n return False\n</code></pre>\n\n<p>Then you can call it like this:</p>\n\n<pre><code> if filename in stored_checks:\n return self._check_log_writesums(stored_checks[filename] != checksum,\n \"\",\n rewrite=True)\n</code></pre>\n\n<p>Maybe the name can be better (_update_checksums or _do_write_checksums).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T11:57:02.570", "Id": "11989", "Score": "0", "body": "Yes well I don't definitively want to refactor, but I found it very strange that I could not easily refactor it...\nWhat is your \"if logmessage\" for?\nI normally just use levels or more specialized loggers that can be filtered more easily..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T20:05:36.893", "Id": "12105", "Score": "0", "body": "I just wanted to make it optional for \"if stored_checks[filename] != checksum\", because logging is missing in the original code. There is no sense to log empty message" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-08T18:39:06.533", "Id": "7595", "ParentId": "7529", "Score": "1" } } ]
<p>I have this module which computes checksums from a list of files in a given directory. The problem is that my is_changed_file is long and ugly, but my attempts in refactoring failed, so I would like some other point of views...</p> <pre><code>import hashlib import logging # if available use the faster cPickle module try: import cPickle as pickle except ImportError: import pickle from os import path class DirectoryChecksum(object): """Manage the checksums of the given files in a directory """ def __init__(self, directory, to_hash): self.directory = directory self.to_hash = to_hash self.checksum_file = path.join(self.directory, '.checksums') self.checks = self._compute() self.logger = logging.getLogger("checksum(%s): " % self.directory) def _abs_path(self, filename): return path.join(self.directory, filename) def _get_checksum(self, filename): content = open(self._abs_path(filename)).read() return hashlib.md5(content).hexdigest() def _compute(self): """Compute all the checksums for the files to hash """ dic = {} for f in self.to_hash: if self._file_exists(f): dic[f] = self._get_checksum(f) return dic def _file_exists(self, filename): return path.isfile(self._abs_path(filename)) def is_changed(self): """True if any of the files to hash has been changed """ return any(self.is_file_changed(x) for x in self.to_hash) #FIXME: refactor this mess, there is also a bug which impacts on #the airbus. eggs, so probably something to do with the path def is_file_changed(self, filename): """Return true if the given file was changed """ if not self._has_checksum(): self.logger.debug("no checksum is available yet, creating it") self.write_checksums() return True stored_checks = self.load_checksums() if not self._file_exists(filename): if filename in stored_checks: self.logger.debug("file %s has been removed" % filename) # what if it existed before and now it doesn't?? return True else: return False checksum = self._get_checksum(filename) if filename in stored_checks: # if the file is already there but the values are changed # then we also need to rewrite the stored checksums if stored_checks[filename] != checksum: self.write_checksums() return True else: return False else: # this means that there is a new file to hash, just do it again self.write_checksums() return True def _has_checksum(self): return path.isfile(self.checksum_file) def load_checksums(self): """Load the checksum file, returning the dictionary stored """ return pickle.load(open(self.checksum_file)) def write_checksums(self): """Write to output (potentially overwriting) the computed checksum dictionary """ self.logger.debug("writing the checksums to %s" % self.checksum_file) return pickle.dump(self.checks, open(self.checksum_file, 'w')) </code></pre>
[]
{ "AcceptedAnswerId": "7595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-06T13:50:15.787", "Id": "7529", "Score": "2", "Tags": [ "python" ], "Title": "Python and computing checksums" }
7529
accepted_answer
[ { "body": "<p>Probably there is no need to refactor the method as it represents quite clear decision tree. Breaking it down into smaller methods will cause readability problems.</p>\n\n<p>Just make sure you have unit tests covering each outcome and that there are no cases, which the code doesn't handle.</p>\n\n<p>If you definitely want to refactor, I propose to add a method like this:</p>\n\n<pre><code>def _check_log_writesums(cond, logmessage, rewrite=True):\n if cond:\n if logmessage:\n self.logger.debug(logmessage)\n if rewrite:\n self.write_checksums()\n return True\n return False\n</code></pre>\n\n<p>Then you can call it like this:</p>\n\n<pre><code> if filename in stored_checks:\n return self._check_log_writesums(stored_checks[filename] != checksum,\n \"\",\n rewrite=True)\n</code></pre>\n\n<p>Maybe the name can be better (_update_checksums or _do_write_checksums).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T11:57:02.570", "Id": "11989", "Score": "0", "body": "Yes well I don't definitively want to refactor, but I found it very strange that I could not easily refactor it...\nWhat is your \"if logmessage\" for?\nI normally just use levels or more specialized loggers that can be filtered more easily..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T20:05:36.893", "Id": "12105", "Score": "0", "body": "I just wanted to make it optional for \"if stored_checks[filename] != checksum\", because logging is missing in the original code. There is no sense to log empty message" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-08T18:39:06.533", "Id": "7595", "ParentId": "7529", "Score": "1" } } ]
<p>I've got my answer working (up until a <a href="http://www.nairaland.com/nigeria/topic-791297.0.html#msg9490894" rel="nofollow">7-digit answer</a> is requested, anyway), and would like some help </p> <ol> <li>returning the correct answer</li> <li>speeding up the results</li> </ol> <p>I was thinking of storing the values of the possible palindromes before beginning my calculations, but I know it wouldn't speed things up anyhow. I've also read around that <a href="http://mathsuniverse.blogspot.com/2009/04/all-about-palindrome-numbers.html" rel="nofollow">the <em>'divide by 11'</em></a> trick isn't always reliable (see comment #2...<code>900009 / 11 = 81819</code>).</p> <p>My code skims the top 10% of both the inner and outer loop before it decrements the outer loop by one, and repeats until the <em>first result</em> is found. This works fine, until the answer for 7-digit numbers is requested.</p> <pre><code>"""http://projecteuler.net/problem=4 Problem 4 16 November 2001 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def main(n): """return the largest palindrome of products of `n` digit numbers""" strstart = "9" * n multic = int(strstart) multip = multic -1 top = multic while multic &gt; top * .9: while multip &gt; multic * .9: multip -= 1 if isPalin(multic * multip): return multic, multip, multic*multip multip = multic multic -= 1 def isPalin(n): n = str(n) leng = len(n) half = n[:leng/2] if n[leng/2:] == half[::-1]: return True return False if __name__ == '__main__': main(3) </code></pre> <p>How's my approach here?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-09T00:59:54.577", "Id": "11926", "Score": "0", "body": "what makes you think your code is broken for 7 digit numbers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-09T02:13:13.557", "Id": "11933", "Score": "2", "body": "The point of the Euler Project is that you should figure out the solution *yourself*, not get it from a forum..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-09T20:36:36.730", "Id": "11969", "Score": "0", "body": "@Guffa: He did, he's just asking how to make it better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-09T22:16:37.143", "Id": "11972", "Score": "0", "body": "@sepp2k: Most questions are designes so that you easily can get the correct result for small values, the tricky part is to make it work for large numbers, and using something other than brute force so that it doesn't take ages. So, he did the easy part..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T00:51:36.410", "Id": "11975", "Score": "0", "body": "@Guffa is there a pattern for palindromes? I tried looking them up, but all I got was a rule that said most of the time, a palindrome / 11 will make another palindrome, and another that said summing the reverse of two numbers will eventually produce one...is there something you could share with me?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T04:45:05.687", "Id": "11980", "Score": "0", "body": "@Guffa, you may be interested in voicing your opinions here: http://meta.codereview.stackexchange.com/questions/429/online-contest-questions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-12T13:52:48.507", "Id": "12168", "Score": "0", "body": "The assumption that checking the top 10% of the 'current range' will yield the top result is false. For 7 digits numbers, that yields the number 94677111177649 (composed from 9999979 and 9467731), while using a 1% spectrum yields the larger number 99500822800599 (composed from 9999539 and 9950541). Though I've no good idea on how to define the proper spectrum, or good ideas for another halting condition." } ]
{ "AcceptedAnswerId": "7617", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-09T00:31:08.417", "Id": "7615", "Score": "3", "Tags": [ "python", "optimization", "project-euler", "palindrome" ], "Title": "Project Euler, #4: Incorrect Results on 7-digit numbers" }
7615
accepted_answer
[ { "body": "<pre><code>def main(n):\n \"\"\"return the largest palindrome of products of `n` digit numbers\"\"\"\n strstart = \"9\" * n\n multic = int(strstart)\n</code></pre>\n\n<p>Firstly, for two such short lines you'd do better to combine them. <code>multic = int(\"9\" * n)</code>. However, even better would be to avoid generating strings and then converting to ints. Instead, use math. <code>multic = 10**n - 1</code></p>\n\n<pre><code> multip = multic -1\n</code></pre>\n\n<p>Guessing what multip and multic mean is kinda hard. I suggest better names.</p>\n\n<pre><code> top = multic\n\n while multic &gt; top * .9:\n</code></pre>\n\n<p>You should almost always use for loops for counting purposes. It'll make you code easier to follow.</p>\n\n<pre><code> while multip &gt; multic * .9:\n multip -= 1\n if isPalin(multic * multip):\n return multic, multip, multic*multip\n multip = multic\n multic -= 1\n\ndef isPalin(n):\n</code></pre>\n\n<p>Use underscores to seperate words (the python style guide says so) and avoid abbreviations.</p>\n\n<pre><code> n = str(n)\n leng = len(n)\n</code></pre>\n\n<p>This assignment doesn't really help anything. It doesn't make it clearer or shorter, so just skip it</p>\n\n<pre><code> half = n[:leng/2]\n if n[leng/2:] == half[::-1]:\n return True\n return False \n</code></pre>\n\n<p>Why split the slicing of the second half in two? Just do it all in the if. Also use <code>return n[...] == half[..]</code> no need for the if.</p>\n\n<pre><code>if __name__ == '__main__':\n main(3) \n</code></pre>\n\n<p>Here is my quick rehash of your code:</p>\n\n<pre><code>def main(n):\n \"\"\"return the largest palindrome of products of `n` digit numbers\"\"\"\n largest = 10 ** n - 1\n for a in xrange(largest, int(.9 * largest), -1):\n for b in xrange(a, int(.9 * a), -1):\n if is_palindrome(a * b):\n return a, b, a * b\n\ndef is_palindrome(number):\n number = str(number)\n halfway = len(number) // 2\n return number[:halfway] == number[:-halfway - 1:-1]\n\nif __name__ == '__main__':\n print main(3) \n</code></pre>\n\n<p>Your link on 7-digit numbers is to a post discussing integer overflow in Java. Integer overflow does not exist in Python. You simply don't need to worry about that.</p>\n\n<p>The challenge asks the answer for a 3 digit problem, so I'm not sure why you are talking about 7 digits. Your code is also very quick for the 3 digits so I'm not sure why you want it faster. But if we assume for some reason that you are trying to solve the problem for 7 digits and that's why you want more speed:</p>\n\n<p>My version is already a bit faster then yours. But to do better we need a more clever strategy. But I'm not aware of any here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T00:53:29.760", "Id": "11976", "Score": "0", "body": "`multic` = `multicand`; `multip` = `multiplier`. Would it be better if I changed the names to `mc` and `mp`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T01:20:52.900", "Id": "11977", "Score": "0", "body": "Thanks for the `10**n` bit, and pointing out the string at the top of the method. Those were leftovers form an earlier approach. Do you know of a pattern to [generate palindromes *mathematically*](http://math.stackexchange.com/questions/97752/generating-numeric-palindromes)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T02:13:12.703", "Id": "11979", "Score": "1", "body": "@Droogans, no `mc` and `mp` don't help. Use `multiplier` and `multicand` you aren't paying per letter you use in your variable name. Use full words and avoid abbreviations" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-09T01:17:21.040", "Id": "7617", "ParentId": "7615", "Score": "4" } } ]
<pre><code>mysql&gt; select count(username) from users where no_tweets &gt; 50; +-----------------+ | count(username) | +-----------------+ | 282366 | +-----------------+ 1 row in set (5.41 sec) mysql&gt; select sum(no_tweets) from users where no_tweets &gt; 50; +----------------+ | sum(no_tweets) | +----------------+ | 38569853 | +----------------+ 1 row in set (1.75 sec) </code></pre> <p>I have that many users, who have collectively tweeted that many tweets. My aim is to store them in a file and then find out what a user generally tweets about (for starters, my aim is to run vanilla LDA and see if it works well on short documents), but the problem is that I ran the python code like an hour back and it has still not finished even 2% of users. I have posted the python code below.</p> <pre><code>''' The plan is : Find out all users from the users database who have more than 50 tweets Create a file for them in the directory passed as an argument with the same name as the username and write all the tweets in them ''' def fifty(cursor): ''' Find all users and return , all of them having more than 50 tweets''' cursor.execute("select username from users where no_tweets&gt;50") return cursor.fetchall() def connect(): ''' Cursor for mySQLdb''' conn = MySQLdb.connect(host="localhost",user="rohit",passwd="passwd",db="Twitter") return conn.cursor() def tweets(cursor,name): ''' All tweets by a given user''' cursor.execute("select tweets from tweets where username='"+name+"'") return cursor.fetchall() import sys,os,MySQLdb directory = sys.argv[1] #Directory to write the user files cursor = connect() rows = fifty(cursor) #Find all users who have more than 50 tweets for i in rows:#For all users data = open(os.path.join(directory,i[0]),'w') #Open a file same as their name allTweets = tweets(cursor,i[0]) #Find all tweets by them for j in allTweets: data.write(j[0]+"\n") #Write them data.close() </code></pre> <p>The problem is that the code is running too slow and at this rate, it will take more than a day for it to finish writing all files. So some way that would make it faster would be great. So yeah, that is the question.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:32:13.970", "Id": "12004", "Score": "1", "body": "And your question is...?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:34:56.443", "Id": "12005", "Score": "0", "body": "Did not realize that I had not put the question in there . Apologies. Made the necessary changes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:36:03.217", "Id": "12006", "Score": "0", "body": "This really isn't a \"just go and fix my code for me\" place. If you just want someone to go do the work for you you should hire a dev." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:38:18.673", "Id": "12007", "Score": "2", "body": "If I had written no code at all and asked for help from someone to literally write the code , that would have made sense. I thought SO is a place where mistakes by people who are learning , like me, are corrected by those who can correct them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:38:18.877", "Id": "12008", "Score": "0", "body": "My gut feeling is that performance is slow due to I/O. That can't be avoided, but perhaps you could look into the [subprocess](http://docs.python.org/library/subprocess.html) module." } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:26:53.443", "Id": "7645", "Score": "5", "Tags": [ "python", "mysql", "performance" ], "Title": "40 million tweets from 200k users" }
7645
max_votes
[ { "body": "<p>Yikes, you're running almost 3,000,000 individual queries. If you could do 4 a second (and you probably cannot) that is <em>still</em> a day!</p>\n\n<p>How about just</p>\n\n<pre><code>select username, tweets from tweets order by username\n</code></pre>\n\n<p>Then of course you have to do some fancy footwork to switch from one file to the next when the user changes.</p>\n\n<p>It should only take a few hours to run.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:41:56.040", "Id": "12015", "Score": "0", "body": "I guess I will have to make necessary change so that I select only those users who have more than 50 tweets in the other table ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:47:06.207", "Id": "12016", "Score": "0", "body": "`select t.username, tweets from tweets t, (select username from tweets group by username having count(*) > 50) e where e.username = t.username order by t.username` -- but if you think *most* people have more than 50 (seems likely, since the average is 500), you might be better off just creating the files for everybody and deleting the small ones later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:55:41.203", "Id": "12018", "Score": "0", "body": "I thought of the creating all files earlier. But , only 3% of users have more than 50 tweets ~ ( 282366 / 6161529 ). So had to chuck that. Thanks ! Thanks again !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T20:05:46.693", "Id": "12022", "Score": "0", "body": "And I actually have two tables. One is (username,tweets) and other is (username,no_tweets) . I stored them separately as username would be a primary key in the 2nd table. Plus would help for future reference" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T20:15:15.463", "Id": "12025", "Score": "0", "body": "mysql> select t.tweets tweets,u.username username from tweets t,users u where t.username=u.username and u.no_tweets > 50 order by t.username;\nIs this one correct ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T01:58:42.910", "Id": "12032", "Score": "0", "body": "Looks good to me. Try it out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T05:39:34.517", "Id": "12039", "Score": "0", "body": "When I ran it from cursor.execute , it gave an error :( Incorrect key for the table it seems :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T05:41:26.293", "Id": "12040", "Score": "0", "body": "And this happened after 4 hours of running, so I suspect something else went wrong altogether" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T09:32:26.177", "Id": "12064", "Score": "0", "body": "Well, what was the error?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T09:59:22.673", "Id": "12065", "Score": "0", "body": "The error was InternalError: (126, \"Incorrect key file for table '/var/tmp/mysql.ms5v75/#sql_6cd_1.MYI'; try to repair it\") <-- I think my root ran outta memory . I have asked MySQL to store everything on my /home directory , but , this query, I ran using IPython. So I think it was writing everything into that . Could that be the prob ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T16:14:31.167", "Id": "12078", "Score": "0", "body": "[Out of file space](http://stackoverflow.com/questions/2090073/mysql-incorrect-key-file-for-tmp-table-when-making-multiple-joins). You can't be shocked about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T22:22:44.203", "Id": "12137", "Score": "0", "body": "The weird part is that I have given /home/crazyabtliv/mysql as my defacto path. Then why did MySQLdb try and store things somewhere else :(" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-10T19:35:44.163", "Id": "7647", "ParentId": "7645", "Score": "8" } } ]
<p>I am writing a few python functions to parse through an xml schema for reuse later to check and create xml docs in this same pattern. Below are two functions I wrote to parse out data from simpleContent and simpleType objects. After writing this, it looked pretty messy to me and I'm sure there is a much better (more pythonic) way to write these functions and am looking for any assistance. I am use lxml for assess to the etree library.</p> <pre><code>def get_simple_type(element): simple_type = {} ename = element.get("name") simple_type[ename] = {} simple_type[ename]["restriction"] = element.getchildren()[0].attrib elements = element.getchildren()[0].getchildren() simple_type[ename]["elements"] = [] for elem in elements: simple_type[ename]["elements"].append(elem.get("value")) return simple_type def get_simple_content(element): simple_content = {} simple_content["simpleContent"] = {} simple_content["simpleContent"]["extension"] = element.getchildren()[0].attrib simple_content["attributes"] = [] attributes = element.getchildren()[0].getchildren() for attribute in attributes: simple_content["attributes"].append(attribute.attrib) return simple_content </code></pre> <p>Examples in the schema of simpleContent and simpleTypes (they will be consistently formatted so no need to make the code more extensible for the variety of ways these elements could be represented in a schema):</p> <pre><code>&lt;xs:simpleContent&gt; &lt;xs:extension base="xs:integer"&gt; &lt;xs:attribute name="sort_order" type="xs:integer" /&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;xs:simpleType name="yesNoOption"&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:enumeration value="yes"/&gt; &lt;xs:enumeration value="no"/&gt; &lt;xs:enumeration value="Yes"/&gt; &lt;xs:enumeration value="No"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; </code></pre> <p>The code currently creates dictionaries like those show below, and I would like to keep that consistent:</p> <pre><code>{'attributes': [{'type': 'xs:integer', 'name': 'sort_order'}], 'simpleContent': {'extension': {'base': 'xs:integer'}}} {'yesNoOption': {'restriction': {'base': 'xs:string'}, 'elements': ['yes', 'no', 'Yes', 'No']}} </code></pre>
[]
{ "AcceptedAnswerId": "10493", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-12T21:06:39.923", "Id": "7725", "Score": "0", "Tags": [ "python", "parsing", "xml" ], "Title": "Python xml schema parsing for simpleContent and simpleTypes" }
7725
accepted_answer
[ { "body": "<p>Do more with literals:</p>\n\n<pre><code>def get_simple_type(element):\n return {\n element.get(\"name\"): {\n \"restriction\": element.getchildren()[0].attrib,\n \"elements\": [ e.get(\"value\") for e in element.getchildren()[0].getchildren() ]\n }\n }\n\ndef get_simple_content(element):\n return { \n \"simpleContent\": {\n \"extension\": element.getchildren()[0].attrib,\n \"attributes\": [ a.attrib for a in element.getchildren()[0].getchildren() ]\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T14:17:29.627", "Id": "10493", "ParentId": "7725", "Score": "3" } } ]
<p>I just started Python a few days ago, and I haven't programmed much before. I know my code is terrible; however, I would like someone to look it over. What I'm trying to do is create a photo "loop" that changes my Windows 7 login screen. I had a batch file doing it, but even though my code is crappy it does the job way better.</p> <p>I'm using two separate scripts, and if possible I would like to combine them. Renamer.py only runs when new photos are added. It sets up the file names for LoginChanger.py. <code>LoginChanger</code> is picky in the filenames, but <code>Renamer</code> doesn't change the photos in a loop. So I have to use <code>Renamer</code>, then <code>LoginChanger</code> to loop the photos.</p> <p><strong>Renamer.py</strong></p> <pre><code>#------------------------------------------------------------------------------- # Name: Renamer # Purpose: Renames all .jpg's in a dir from 0 - n (where "n" is the number of .jpg's.) # This is to be used in conjunction with loginchanger.py # Author: Nathan Snow # # Created: 13/01/2012 # Copyright: (c) Nathan Snow 2012 # Licence: &lt;your licence&gt; #------------------------------------------------------------------------------- #!/usr/bin/env python import os count = 0 count2 = 0 list1 = [] list2 = [] for filename2 in os.listdir('.'): if filename2.endswith('.jpg'): list1.append(filename2) while count &lt; len(list1): os.rename(filename2, str(count)+"old.jpg") count += 1 for filename3 in os.listdir('.'): if filename3.endswith('.jpg'): list2.append(filename3) while count2 &lt; len(list2): os.rename(filename3, str(count2)+".jpg") count2 += 1 </code></pre> <p><strong>LoginChanger.py</strong></p> <pre><code>#------------------------------------------------------------------------------- # Name: LoginChanger # Purpose: This is to be used after renamer.py. This loops the properly named # .jpg's in a "circle" first to last, 2-1, 3-2, ..., and changes # 0 to BackgroundDefault.jpg. # Author: Nathan Snow # # Created: 13/01/2012 # Copyright: (c) Nathan Snow 2012 # Licence: &lt;your licence&gt; #------------------------------------------------------------------------------- #!/usr/bin/env python import os count = 0 list1 = [] list2 = [] list3 = [] for filename in os.listdir('.'): if filename.endswith('.jpg'): list3.append(filename) list3len = len(list3) list3len = list3len - 1 if filename.startswith('BackgroundDefault'): os.rename('BackgroundDefault.jpg', str(list3len)+'.jpg') for filename2 in os.listdir('.'): if filename2.endswith('.jpg'): list1.append(filename2) while count &lt; len(list1): jpg = str(count)+'.jpg' oldjpg = str(count)+'old.jpg' os.rename(str(jpg), str(oldjpg)) count += 1 for filename4 in os.listdir('.'): if filename4.startswith('0'): os.rename('0old.jpg', 'BackgroundDefault.jpg') count = 1 count2 = 0 for filename3 in os.listdir('.'): if filename3.endswith('.jpg'): list2.append(filename3) while count &lt; len(list2): newjpg = str(count2)+'.jpg' oldjpg = str(count)+'old.jpg' os.rename(str(oldjpg), str(newjpg)) count2 += 1 count += 1 print ('Created new login background') </code></pre>
[]
{ "AcceptedAnswerId": "7823", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-14T19:29:00.193", "Id": "7809", "Score": "5", "Tags": [ "python", "image" ], "Title": "Photo changer loop" }
7809
accepted_answer
[ { "body": "<p>You could avoid continuously renaming all files by overwriting just <code>BackgroundDefault.jpg</code> file instead e.g., <code>change-background.py</code>:</p>\n\n<pre><code>#!/usr/bin/env python\nimport bisect\nimport codecs\nimport os\nimport shutil\n\nBG_FILE = u'BackgroundDefault.jpg'\ndb_file = 'change-background.db'\ndb_encoding = 'utf-8'\n\n# read image filenames; sort to use bisect later\nfiles = sorted(f for f in os.listdir(u'.')\n if f.lower().endswith(('.jpg', '.jpeg')) and os.path.isfile(f)) \ntry: files.remove(BG_FILE)\nexcept ValueError: pass # the first run\n\n# read filename to use as a background from db_file\ntry:\n # support Unicode names, use human-readable format\n with codecs.open(db_file, encoding=db_encoding) as f:\n bg_file = f.read().strip()\nexcept IOError: # the first run\n bg_file = files[0] # at least one image file must be present\n\n# change background image: copy bg_file to BG_FILE\ntmp_file = BG_FILE+'.tmp'\nshutil.copy2(bg_file, tmp_file)\n# make (non-atomic) rename() work even if destination exists on Windows\ntry: os.remove(BG_FILE)\nexcept OSError: # in use or doesn't exist yet (the first run)\n if os.path.exists(BG_FILE):\n os.remove(tmp_file)\n raise\nos.rename(tmp_file, BG_FILE)\n\n# write the next filename to use as a background\nnext_file = files[bisect.bisect(files, bg_file) % len(files)]\nwith codecs.open(db_file, 'w', encoding=db_encoding) as f:\n f.write(next_file)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-15T03:08:21.940", "Id": "12367", "Score": "0", "body": "I copied this and it worked the first time. Then it said it couldn't change the background image because the file was already there. I had to remove a \")\" from \"files = sorted(glob.glob(u'*.jpg')))\" to get it to work as well. I really appreciate the help though, Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-15T04:18:05.540", "Id": "12391", "Score": "0", "body": "@Jedimaster0: I've fixed the code. I don't use Windows so it is untested." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-15T00:37:19.897", "Id": "7823", "ParentId": "7809", "Score": "3" } } ]
<p>I am doing my homework and i have done this? Is there any other better way to do this? <br> <br></p> <pre><code>def write_log(name, total): # change user input with shape names name = name.replace('1', 'triangle') name = name.replace('2', 'square') name = name.replace('3', 'rectangle') name = name.replace('4', 'pentagon') name = name.replace('5', 'hexagon') name = name.replace('6', 'octagon') name = name.replace('7', 'circle') total = int(total) logfile = open("text.txt", "a") if (total == 1): towrite = ('%i %s \n' % (total, name)) elif (total &gt;= 2 and total &lt;= 5): name += 's' # add s to name to make it plural towrite = ('%i %s \n' % (total, name)) else: towrite = '' try: logfile.write(towrite) finally: logfile.close() return </code></pre>
[]
{ "AcceptedAnswerId": "7859", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-15T17:26:21.557", "Id": "7857", "Score": "4", "Tags": [ "python", "homework" ], "Title": "is there a better way than replace to write this function?" }
7857
accepted_answer
[ { "body": "<p>I'd find it a bit more elegant to use a list of tuples:</p>\n\n<pre><code>replacements = [('1', 'triangle'),\n ('2', 'square'),\n # etc.\n ]\n\nfor old, new in replacements:\n name = name.replace(old, new)\n</code></pre>\n\n<p>This way, you can more easily change the code later on; e.g., when you decide you want to use <code>re.sub</code> instead of <code>.replace</code>.</p>\n\n<p>Also, I'd use the <a href=\"http://effbot.org/zone/python-with-statement.htm\"><code>with</code> statement</a> for the logfile:</p>\n\n<pre><code>with open(\"text.txt\", \"a\") as logfile:\n # write stuff\n</code></pre>\n\n<p>This saves you the trouble of closing the file explicitly, so you can remove the exception-handling logic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-16T21:45:51.617", "Id": "12463", "Score": "0", "body": "Use [enumerate](http://docs.python.org/library/functions.html#enumerate) to build the dictionary as I show in [my answer](http://codereview.stackexchange.com/a/7873/9370). Then just access the dictionary using the number as the key. +1 for using `with`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-15T17:33:29.327", "Id": "7859", "ParentId": "7857", "Score": "7" } } ]
<p>I'm starting to look at Python and its facilities. I've just tried to make one simple program using some base libraries. </p> <p>I would like to hear some comments about anything you've noticed - style, readability, safety, etc.</p> <pre><code>#!/usr/bin/python2.6 -u import urllib2 import simplejson import zlib from optparse import OptionParser class StackOverflowFetcher: """Simple SO fetcher""" def getUserInfo( self, userId ): response = urllib2.urlopen( 'http://api.stackoverflow.com/1.1/users/' + str(userId) ) response = response.read() jsonData = zlib.decompress( response, 16+zlib.MAX_WBITS ) return simplejson.loads( jsonData ) def getUserDisplayName( self, userId ): return self.getUserInfo( userId )['users'][0]['display_name'] def getUserViewCount( self, userId ): return self.getUserInfo( userId )['users'][0]['view_count'] def getUserReputation( self, userId ): return self.getUserInfo( userId )['users'][0]['reputation'] if __name__ == '__main__': parser = OptionParser() parser.add_option("-u", "--userId", dest="userId", help="Set userId (default is 1)", default=1 ) parser.add_option("-n", "--display-name", action="store_true", dest="show_display_name", default=False, help="Show user's display name") parser.add_option("-v", "--view_count", action="store_true", dest="show_view_count", default=False, help="Show user's profile page view count") parser.add_option("-r", "--reputation", action="store_true", dest="show_reputation", default=False, help="Show user's reputation") (options, args) = parser.parse_args() userId = options.userId show_display_name = options.show_display_name show_view_count = options.show_view_count show_reputation = options.show_reputation if ( (not show_display_name) and (not show_view_count) and (not show_reputation) ): show_display_name = show_view_count = show_reputation = True fetcher = StackOverflowFetcher() if ( show_display_name ) : print fetcher.getUserDisplayName( userId ) if ( show_view_count) : print fetcher.getUserViewCount( userId ) if ( show_reputation ) : print fetcher.getUserReputation( userId ) </code></pre> <p>Python version 2.6</p>
[]
{ "AcceptedAnswerId": "7970", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-01-18T15:43:16.380", "Id": "7930", "Score": "10", "Tags": [ "python", "json", "stackexchange", "python-2.x" ], "Title": "Stack Overflow user info fetcher" }
7930
accepted_answer
[ { "body": "<pre><code>#!/usr/bin/python2.6 -u\n\nimport urllib2\nimport simplejson\nimport zlib\nfrom optparse import OptionParser\n\nclass StackOverflowFetcher:\n \"\"\"Simple SO fetcher\"\"\"\n def getUserInfo( self, userId ):\n</code></pre>\n\n<p>The python style guide recommends words_with_underscores for function names and parameter names.</p>\n\n<pre><code> response = urllib2.urlopen( 'http://api.stackoverflow.com/1.1/users/' + str(userId) )\n</code></pre>\n\n<p>I'd consider moving the API into a global constant</p>\n\n<pre><code> response = response.read()\n jsonData = zlib.decompress( response, 16+zlib.MAX_WBITS )\n</code></pre>\n\n<p>I'd combine the previous two lines</p>\n\n<pre><code> return simplejson.loads( jsonData )\n\n def getUserDisplayName( self, userId ):\n return self.getUserInfo( userId )['users'][0]['display_name']\n\n def getUserViewCount( self, userId ):\n return self.getUserInfo( userId )['users'][0]['view_count']\n\n def getUserReputation( self, userId ):\n return self.getUserInfo( userId )['users'][0]['reputation']\n</code></pre>\n\n<p>There three functions share most of their code. Why don't you modify getUserInfo to do the ['users'][0] itself instead?</p>\n\n<pre><code>if __name__ == '__main__':\n parser = OptionParser()\n parser.add_option(\"-u\", \"--userId\", dest=\"userId\", help=\"Set userId (default is 1)\", default=1 )\n parser.add_option(\"-n\", \"--display-name\", action=\"store_true\", dest=\"show_display_name\", default=False, help=\"Show user's display name\")\n parser.add_option(\"-v\", \"--view_count\", action=\"store_true\", dest=\"show_view_count\", default=False, help=\"Show user's profile page view count\")\n parser.add_option(\"-r\", \"--reputation\", action=\"store_true\", dest=\"show_reputation\", default=False, help=\"Show user's reputation\")\n (options, args) = parser.parse_args()\n\n userId = options.userId\n show_display_name = options.show_display_name\n show_view_count = options.show_view_count\n show_reputation = options.show_reputation\n\n if ( (not show_display_name) and (not show_view_count) and (not show_reputation) ):\n</code></pre>\n\n<p>None of those parentheses are necessary. I'd probably go with <code>if not (show_display_name or show_view_count or show_reputation):</code> as I think that mostly clear states what you are doing.\n show_display_name = show_view_count = show_reputation = True</p>\n\n<pre><code> fetcher = StackOverflowFetcher()\n if ( show_display_name ) : print fetcher.getUserDisplayName( userId )\n if ( show_view_count) : print fetcher.getUserViewCount( userId )\n if ( show_reputation ) : print fetcher.getUserReputation( userId )\n</code></pre>\n\n<p>Firstly, the ifs don't need the parens. Secondly, the way your code is written each call goes back to the server. So you'll three calls to the stackoverflow server which you could have gotten with one. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T16:04:00.387", "Id": "7970", "ParentId": "7930", "Score": "7" } } ]
<p>Given:</p> <pre><code>k = {'MASTER_HOST': '10.178.226.196', 'MASTER_PORT': 9999} </code></pre> <p>I want to flatten into the string:</p> <pre><code>"MASTER_HOST='10.178.226.196', MASTER_PORT=9999" </code></pre> <p>This is the ugly way that I'm achieving this right now:</p> <pre><code>result = [] for i,j in k.iteritems(): if isinstance(j, int): result.append('%s=%d' % (i,j)) else: result.append("%s='%s'" % (i,j)) ', '.join(result) </code></pre> <p>I'm sure my developer colleagues are going to chastize me for this code. Surely there is a better way.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T09:00:09.547", "Id": "12600", "Score": "0", "body": "I don't think it's that bad, unless perhaps you also have Boolean values in your dict, because `isinstance(False, int)` returns `True`, so instead of `flag='False'`, you'd get `flag=0` (both of which are not optimal)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T08:47:59.230", "Id": "7953", "Score": "20", "Tags": [ "python", "strings" ], "Title": "Flattening a dictionary into a string" }
7953
max_votes
[ { "body": "<p>For python 3.0+ (as @Serdalis suggested)</p>\n\n<pre><code>', '.join(\"{!s}={!r}\".format(key,val) for (key,val) in k.items())\n</code></pre>\n\n<p>Older versions:</p>\n\n<pre><code>', '.join(\"%s=%r\" % (key,val) for (key,val) in k.iteritems())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T08:53:40.223", "Id": "12601", "Score": "1", "body": "Close but no cigar. I don't want quotes around 9999 for `MASTER_PORT` in the final result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T08:57:21.373", "Id": "12602", "Score": "1", "body": "@BonAmi You're right. I replaced the second `%s` with `%r` to achieve that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T09:31:08.100", "Id": "12607", "Score": "0", "body": "Instead of the `(key,val)` you could simply write `item`. iteritems returns tuples, and if you have multiple replacements in a string, you replace those using a tuple. You drop a second temporary variable and imo, you gain some readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T09:34:00.343", "Id": "12608", "Score": "0", "body": "@Elmer That's interesting you say that, because I think novice pythoners might get more readability by using `(key,val)`, since it explains better what happens. But I guess that's a matter of taste. I do agree your way is more efficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-18T06:35:11.730", "Id": "192174", "Score": "0", "body": "I know it's a dictionary and .iteritems returns `(key, val)`, so unless you have better variable names that warrant creating temporary variables, like `(food_name, price)`, you can save yourself the characters. It's all about increasing your signal to noise, and `(k,v)` or `(key, value)` is mostly noise." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T08:50:03.863", "Id": "7954", "ParentId": "7953", "Score": "33" } } ]
<p>I'm attempting to create a linked list of length n using Python. I have the simple list implemented, a working concatenation function, and a working create_list function; however, I just want to know if there is a more efficient method at making the linked list than using my concatenate function (made for testing).</p> <p>Simple List Class:</p> <pre><code>class Cell: def __init__( self, data, next = None ): self.data = data self.next = next </code></pre> <p>Concatenate Function:</p> <pre><code>def list_concat(A, B): current = A while current.next != None: current = current.next current.next = B return A </code></pre> <p>List create (that takes forever!):</p> <pre><code>def create_list(n): a = cell.Cell(0) for i in (range(1,n)): b = cell.Cell(i) new_list = cell.list_concat(a, b) return new_list </code></pre> <p>This is an assignment, but efficiency is not part of it. I am just wondering if there is a more efficient way to create a large list using this implementation of the structure.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T01:06:36.780", "Id": "12864", "Score": "1", "body": "do you really need a linked list?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:50:25.270", "Id": "12985", "Score": "0", "body": "Comparisons with None are best done based on identity (since None is a singleton), so `while current.next is not None` will suffice. Given that `Cell` has no defined boolean truthness, it is as object \"always True\" and you could reduce the while loop to `while current.next`." } ]
{ "AcceptedAnswerId": "8327", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T01:02:06.747", "Id": "8237", "Score": "6", "Tags": [ "python", "algorithm" ], "Title": "Faster way to create linked list of length n in Python" }
8237
accepted_answer
[ { "body": "<p>The current algorithm has a failure in using the <code>list_concat</code> during list creation. The <code>list_concat</code> function walks to the end of the list for each node you want to add. So adding a node becomes O(n). This means creating a list of 10,000 items takes 1+2+3...+10,000 steps. That's O(n*n) performance.</p>\n\n<p>As hinted, you should add the next node in the creation loop. You then get code that looks like this (I left out the <code>list_concat</code> function as it's not used):</p>\n\n<pre><code>class Cell(object):\n def __init__(self, data, next=None):\n self.data = data\n self.next = next\n\ndef create_list(length=1):\n linked_list = Cell(0)\n head = linked_list\n for prefill_value in xrange(1, length):\n head.next = Cell(prefill_value)\n head = head.next\n return linked_list\n</code></pre>\n\n<p>You could also create the list in reverse order, allowing you to immediately fill the <code>next</code> attribute of the Cell. Your create_list function then looks like this (the <code>reversed</code> function should not be used for really huge lengths (several million) because it's created in-memory):</p>\n\n<pre><code>def create_list(length=1):\n tail = Cell(length - 1)\n for prefill_value in xrange(length - 2, -1, -1):\n tail = Cell(prefill_value, tail)\n return tail\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:55:13.033", "Id": "12986", "Score": "0", "body": "Of course, if you don't need the values of the `Cells` to be increasing the `xrange` statement could be drastically simplified. This would make the second, reverse, `create_list` function a lot easier on the eyes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T14:38:04.483", "Id": "8327", "ParentId": "8237", "Score": "4" } } ]
<p>I looked at the <a href="http://pypi.python.org/pypi?:action=list_classifiers" rel="nofollow">pypi classifiers</a> and <a href="http://wiki.python.org/moin/PyPiXmlRpc" rel="nofollow">some guide</a> to help me write the following script, and here's me wondering if it can be improved:</p> <pre><code>import xmlrpc.client # pypi language version classifiers PY3 = ["Programming Language :: Python :: 3"] PY2 = ["Programming Language :: Python :: 2"] PY27 = ["Programming Language :: Python :: 2.7"] PY26 = ["Programming Language :: Python :: 2.6"] PY25 = ["Programming Language :: Python :: 2.5"] PY24 = ["Programming Language :: Python :: 2.4"] PY23 = ["Programming Language :: Python :: 2.3"] def main(): client = xmlrpc.client.ServerProxy('http://pypi.python.org/pypi') # get module metadata py3names = [name[0] for name in client.browse(PY3)] py2names = [name[0] for name in client.browse(PY2)] py27names = [name[0] for name in client.browse(PY27)] py26names = [name[0] for name in client.browse(PY26)] py25names = [name[0] for name in client.browse(PY25)] py24names = [name[0] for name in client.browse(PY24)] py23names = [name[0] for name in client.browse(PY23)] cnt = 0 for py3name in py3names: if py3name not in py27names \ and py3name not in py26names \ and py3name not in py25names \ and py3name not in py24names \ and py3name not in py23names \ and py3name not in py2names: cnt += 1 print("Python3-only packages: {}".format(cnt)) main() </code></pre> <p><strong>Sidenote</strong>:</p> <pre><code>$ time python3 py3k-only.py Python3-only packages: 259 real 0m17.312s user 0m0.324s sys 0m0.012s </code></pre> <p>In addition, can you spot any functionality bugs in there? Will it give accurate results, assuming that pypi has correct info?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T08:03:35.633", "Id": "12968", "Score": "0", "body": "[**a more complete script**](http://stackoverflow.com/a/9012768)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T18:57:08.127", "Id": "116565", "Score": "0", "body": "@jamal you killed the evolution of the Question, and now the Answer looks odd" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T18:57:46.420", "Id": "116566", "Score": "0", "body": "The answer was never edited, though. It had to correspond to just the original code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T18:59:22.690", "Id": "116567", "Score": "0", "body": "Yeah, but look at *Why do you have a single string in a list?* for example. You got rid of that part of the original Question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T19:00:39.853", "Id": "116570", "Score": "0", "body": "I still see that in this code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T19:04:45.030", "Id": "116573", "Score": "0", "body": "Oh, I see my mistake. I still unlove your Edit, because my Question showed the progress as I made the code better, as a result of feedback. You simply made that disappear. Your deed makes me sad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T19:16:09.840", "Id": "116575", "Score": "0", "body": "Only thing I like is title change." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T20:24:59.977", "Id": "116592", "Score": "0", "body": "I'm sorry, but it's to help make the post easier to follow. You can still post a follow-up if you'd like further review, or a self-answer if you want to show your improvements (but they'll have to explain the changes). The Help Center now explains this in depth." } ]
{ "AcceptedAnswerId": "8260", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T19:07:49.007", "Id": "8259", "Score": "5", "Tags": [ "python" ], "Title": "Checking which pypi packages are Py3k-only" }
8259
accepted_answer
[ { "body": "<pre><code>import xmlrpc.client\n\n# pypi language version classifiers\nPY3 = [\"Programming Language :: Python :: 3\"]\n</code></pre>\n\n<p>Why do you have a single string in a list?</p>\n\n<pre><code>PY2 = [\"Programming Language :: Python :: 2\"]\nPY27 = [\"Programming Language :: Python :: 2.7\"]\nPY26 = [\"Programming Language :: Python :: 2.6\"]\nPY25 = [\"Programming Language :: Python :: 2.5\"]\nPY24 = [\"Programming Language :: Python :: 2.4\"]\nPY23 = [\"Programming Language :: Python :: 2.3\"]\n</code></pre>\n\n<p>You should put all these strings in one list.</p>\n\n<pre><code>def main():\n client = xmlrpc.client.ServerProxy('http://pypi.python.org/pypi')\n\n # get module metadata\n py3names = [name[0] for name in client.browse(PY3)]\n py2names = [name[0] for name in client.browse(PY2)]\n py27names = [name[0] for name in client.browse(PY27)]\n py26names = [name[0] for name in client.browse(PY26)]\n py25names = [name[0] for name in client.browse(PY25)]\n py24names = [name[0] for name in client.browse(PY24)]\n py23names = [name[0] for name in client.browse(PY23)]\n</code></pre>\n\n<p>If you put the python 2.x versions in a one list, you should be able to fetch all this data\ninto one big list rather then all of these lists.</p>\n\n<pre><code> cnt = 0\n</code></pre>\n\n<p>Don't uselessly abbreviate, spell out <code>counter</code></p>\n\n<pre><code> for py3name in py3names:\n if py3name not in py27names \\\n and py3name not in py26names \\\n and py3name not in py25names \\\n and py3name not in py24names \\\n and py3name not in py23names \\\n and py3name not in py2names:\n cnt += 1\n</code></pre>\n\n<p>I'd do something like: <code>python3_only = [name for name in py3name if py3name not in py2names]</code>. Then I'd get the number of packages as a len of that.</p>\n\n<pre><code> print(\"Python3-only packages: {}\".format(cnt))\n\nmain()\n</code></pre>\n\n<p>Usually practice is to the call to main inside <code>if __name__ == '__main__':</code> so that it only gets run if this script is the main script.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T11:17:50.083", "Id": "12930", "Score": "0", "body": "I think you meant `py3only = [name for name in py3names if name not in py2names]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T11:20:03.870", "Id": "12931", "Score": "0", "body": "BTW, with your suggested change to put all Python 2 classifiers in one list, the only modules that get excluded are those which match all the Python 2 classifiers. That is, my output includes a lot of packages that also have Python 2 versions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T14:59:22.510", "Id": "12933", "Score": "1", "body": "@Tshepang, yes on the first comment, not if you do it properly on the second comment. I didn't expressly state how to do it, but you can go through the list, pass each element to the client.browse() one at a time, and then combine the lists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T22:07:09.930", "Id": "12952", "Score": "0", "body": "@Tshepang, yes that's the idea. But you'd be better off to use a list literal instead of the append lines to build `PY2` you might also consider using a nested list comprehension in the fetch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T00:16:36.647", "Id": "12959", "Score": "1", "body": "@Tshepang, ` py2names = [name[0] for classifier in PY2 \n for name in client.browse([classifier])]`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T19:49:30.193", "Id": "8260", "ParentId": "8259", "Score": "3" } } ]
<p>I ran into an issue where I was doing this:</p> <pre><code>dictionary1 = {} dictionary2 = {} foo = dictionary1.get('foo', dictionary1.get('bar', dictionary2.get('baz'))) </code></pre> <p>I.e. if the value isn't supplied in one dict, it would fall back on the next and then on the next. In this case <code>dictionary1</code> has a key that is deprecated that I'm getting in case the new style on isn't there, dictionary2 is completely different. It looks pretty ugly though, the alternative seem to be to break it up across multiple lines like:</p> <pre><code>foo = dictionary2.get('baz') foo = dictionary1.get('bar', foo) foo = dictionary1.get('foo', foo) </code></pre> <p>Which might be better, though it seems like it could be confusing to read the code in the reverse order. I wonder if there's an alternative more straight forward and prettier solution?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T05:43:42.427", "Id": "8272", "Score": "2", "Tags": [ "python" ], "Title": "How can I make handling multiple {}.get('value', {}.get('foo')) pretty?" }
8272
max_votes
[ { "body": "<p>Your code attempts to fetch the values of <em>all</em> keys when it probably only really needs one. You do not want to be doing this.</p>\n\n<p>I think it would be better to create a list representing the priorities of what values you wish to retrieve and attempt to retrieve them.</p>\n\n<pre><code>def get_value(priorities):\n for key, dictionary in priorities:\n try:\n return dictionary[key]\n except KeyError:\n pass\n return None\n\npriorities = [\n ('foo', dictionary1),\n ('bar', dictionary1),\n ('baz', dictionary2),\n]\nfoo = get_value(priorities)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T07:04:04.767", "Id": "8275", "ParentId": "8272", "Score": "3" } } ]
<p>I am running through a file and inserting elements one by one. The counties all contain specific county codes which are duplicated many times throughout the file. I am looking for a way to assign these codes to a specific county while ignoring duplicate county codes.</p> <p>I have two versions I wrote below with runtimes:</p> <p><strong><code>getCodes()</code></strong></p> <pre><code>def get_codes(data): code_info = {} for row in data: county = row["county"] code = int(float(row["code"])) if code &gt; 100000: code = code/100 if county not in code_info: code_info[county] = [] code_info[county].append(code) for county in code_info: code_info[county] = list(set(code_info[county])) return code_info </code></pre> <p><strong><code>get_codes2()</code></strong></p> <pre><code>def get_codes2(data): code_info = {} for row in data: county = row["county"] code = int(float(row["code"])) if code &gt; 100000: code = code/100 if county in code_info: if not code in code_info[county]: code_info[county].append(code) else: code_info[county] = [] code_info[county].append(code) return code_info </code></pre> <p></p> <pre><code>county_data = csv.DictReader(open("county_file.txt")) start = time.time() county_codes = get_codes(county_data) end = time.time() print "run time: " + str(end-start) county_data = csv.DictReader(open("county_file.txt")) start = time.time() county_codes = get_codes2(county_data) end = time.time() print "run time: " + str(end-start) </code></pre> <p>Also, it's probably obvious from this, but county codes that are greater than 100000 can have trailing zeroes accidentally added, so I'm removing them by dividing by 100. As another note, the <code>int(float())</code> conversion is intentional. Sometimes the county codes are values such as "27.7" and need to be converted to "27", other times they are just basic <code>int</code>s.</p> <p>The runtimes on my system:</p> <ul> <li><code>get_codes</code>: 9 seconds</li> <li><code>get_codes2</code>: 14 seconds</li> </ul> <p>How can I improve this further for better performance?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T05:52:30.913", "Id": "13321", "Score": "0", "body": "Python 2.5 supports a [`defaultdict`](http://blog.ludovf.net/python-collections-defaultdict/), which might save some time with the \"if county in code_info\" checks." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T17:48:51.273", "Id": "8284", "Score": "2", "Tags": [ "python", "optimization", "parsing", "csv" ], "Title": "Parsing files with county codes" }
8284
max_votes
[ { "body": "<p>I think you're pretty close to optimal here. I made a few tweaks, to avoid some conditionals by using sets instead. I don't actually know if it'll run faster; you'll need to benchmark it, and it likely depends on the breakdown of how many dupes per county there are.</p>\n\n<pre><code>def get_codes3(data):\n from collections import defaultdict\n codeinfo = defaultdict(set)\n for row in data:\n county = row[\"county\"]\n # remove float() if you can get away with it - are there\n # actually values like '1.5' in the data?\n code = int(float(row[\"code\"]))\n if code &gt; 100000:\n code = code/100\n\n codeinfo[county].add(code)\n # if you can get away with sets instead of lists in your return\n # value, you're good\n return code_info\n # otherwise:\n # return dict([(county, list(info)) for county, info in code_info.iteritems()])\n</code></pre>\n\n<ul>\n<li>You don't need <code>float()</code> unless the data is actually like <code>\"123.45\"</code> - it's not clear if that's the case</li>\n<li><code>set</code>s can work in most places that lists work, so you might not need to convert to a list</li>\n<li>It might be worth it to write a script that does just the <code>x = x/100 if x &gt; 100000</code> part and writes that out to a new file</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:07:33.953", "Id": "12945", "Score": "0", "body": "I ran a few bench marks, the time difference was negligible (usually within a few hundredth of a second).\n\nTo respond to a few of your questions:\n1. Yes, I need int(float()) there. There are some values like \"123.45\" that need to be converted to \"123\", but most are already integers. You are definitely right though, I should have mentioned this in my original post\n2. Yeah, I" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:14:06.703", "Id": "12947", "Score": "0", "body": "2. You may be correct on the set issue, but I need to access the data structure by index later on, so I'd prefer to convert it to a list. 3. That would be ideal solution, but the data in the file may change but the format issue won't. You solution looks a lot more elegant than mine though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T19:31:45.810", "Id": "12949", "Score": "1", "body": "@MikeJ, if you ran AdamKG's exact code for your benchmark, you should try it again with the import moved outside of the function. As I understand imports are actually pretty expensive. Also, try dropping the square brackets for the alternate return. There's not much reason to generate a list first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T15:02:03.273", "Id": "12987", "Score": "0", "body": "Additionally, you could write `code = code / 100` as `code /= 100` if you're going for brevity. It doesn't do much for performance, but it's quicker to read." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-25T18:49:47.600", "Id": "8287", "ParentId": "8284", "Score": "1" } } ]
<p>I'm fairly new to Python and currently building a small application to record loans of access cards to people in a company. I'm using wxPython for the GUI and SQLAlchemy for the CRUD. I'm loosely following <a href="http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/" rel="nofollow">Mike Driscoll's tutorial for a similar application</a> but I want to add some extra things that he hasn't implemented (he has most controls in the same window, but I'm passing things a lot between dialogues and windows and it's starting to look messy).</p> <p>Particularly concerned about the following method in <code>dialogs.py</code>:</p> <pre><code>def OnCardReturn(self, event): """ Call the controller and get back a list of objects. If only one object return then set that loan as returned. If none returned then error, no loans currently on that card. If more than one returned something has gone wrong somewhere, but present a list of the loans against that card for the user to pick the correct one to return. """ value = self.txtInputGenericNum.GetValue() loans = controller.getQueriedRecords(self.session, "card", value) #returns a list of objects numLoans = len(loans) if numLoans == 1: controller.returnLoan(self.session, value) #returns nothing successMsg = "Card " + str(value) + " has been marked as returned" showMessageDlg(successMsg, "Success!") elif numLoans == 0: failureMsg = "Card " + str(value) + " is not currently on loan" showMessageDlg(failureMsg, "Failed", flag="error") elif numLoans &gt; 1: failureMsg = """ More than one loan for " + str(value) + " exists. Please select the correct loan to return from the next screen. """ showMessageDlg(failureMsg, "Failed", flag="error") selectReturnLoan = DisplayList(parent=self, loanResults=loans, returnCard=True) selectReturnLoan.ShowModal() selectReturnLoan.Destroy() </code></pre> <p>The controller is still under construction, so no complete code yet, but I've commented in what is returned by the calls to it so it's still possible to see what the functionality is.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-17T20:59:32.670", "Id": "134446", "Score": "2", "body": "Hi, I removed the external links are broken as of today. If you still have those scripts somewhere online, please re-add the working links. Btw, any code you want reviewed should be included in the post itself (and now you see the reason for that)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T13:33:22.380", "Id": "8358", "Score": "6", "Tags": [ "python", "beginner", "mvc" ], "Title": "Recording loans of access cards to people in a company" }
8358
max_votes
[ { "body": "<p>Inline comments should only be used sparingly, and definitely not on already long lines. Your <code>#returns a list of objects</code> is pretty unnecessary both because it's overly long, but also because it's inferrable and doesn't seem to matter. You only pass the <code>loans</code> on unchanged so the user doesn't care that they're a list of objects. You can infer that it's a collection of something because of the name <code>loans</code> and the <code>len</code> usage. And that's all you need to know in this function, so forget that comment.</p>\n\n<p>You should also format your docstring so it contains just one line summarising the function, a blank line and then the further details. You just have one long block but it's hard to read from it what the function should do. Instead you detail the possible results.</p>\n\n<p>Instead of using <code>str</code> and concatenation, just use <code>str.format</code>. It's a convenient way of formatting strings and coverting their type at the same time:</p>\n\n<pre><code> successMsg = \"Card {} has been marked as returned\".format(value)\n</code></pre>\n\n<p>Also note that you haven't correctly inserted this value in the <code>failureMsg</code> of <code>numLoans &gt; 1</code>. You just have the string literal <code>\" + str(value) + \"</code>. You'd need the extra quotation marks to do it your way:</p>\n\n<pre><code> failureMsg = \"\"\"\n More than one loan for \"\"\" + str(value) + \"\"\" exists. Please select\n the correct loan to return from the next screen.\n \"\"\"\n</code></pre>\n\n<p>But instead I'd suggest using <code>str.format</code> again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T09:52:13.120", "Id": "108984", "ParentId": "8358", "Score": "2" } } ]
<p>I have written a simple python program which takes a number from the user and checks whether that number is divisible by 2:</p> <pre><code># Asks the user for a number that is divisible by 2 # Keep asking until the user provides a number that is divisible by 2. print 'Question 4. \n' num = float(raw_input('Enter a number that is divisible by 2: ')) while (num%2) != 0: num = float(raw_input('Please try again: ')) print 'Congratulations!' </code></pre> <p>I would appreciate any feedback on this code, areas for improvement and/or things that I could have done differently.</p>
[]
{ "AcceptedAnswerId": "8404", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T22:25:57.030", "Id": "8403", "Score": "5", "Tags": [ "python" ], "Title": "Python 'check if number is divisible by 2' program" }
8403
accepted_answer
[ { "body": "<p>Well, first of all, you should put code in an <code>if __name__ == '__main__':</code> block to make sure it doesn't run whenever the file is imported. Thus, just copy pasting:</p>\n\n<pre><code>if __name__ == '__main__':\n print 'Question 4. \\n'\n\n num = float(raw_input('Enter a number that is divisible by 2: '))\n while (num%2) != 0:\n num = float(raw_input('Please try again: '))\n\n print 'Congratulations!'\n</code></pre>\n\n<p>The next thing to notice is that a number being even is actually a fairly common check to make. Such things should be turned into functions. Mostly copy-pasting again:</p>\n\n<pre><code>def is_even(num):\n \"\"\"Return whether the number num is even.\"\"\"\n return num % 2 == 0\n\nif __name__ == '__main__':\n print 'Question 4. \\n'\n\n num = float(raw_input('Enter a number that is divisible by 2: '))\n while not is_even(num):\n num = float(raw_input('Please try again: '))\n\n print 'Congratulations!'\n</code></pre>\n\n<p>Notice the docstring: it's important to document your code, and while the purpose of <code>is_even</code> is obvious, getting into the habit of adding documentation is good. You could also put the following docstring at the top of the file:</p>\n\n<pre><code>\"\"\"Provide the is_even function.\n\nWhen imported, print prompts for numbers to standard output and read numbers\nfrom standard input separated by newlines until an even number is entered. Not\nentering an even number raises EOFError.\n\n\"\"\"\n</code></pre>\n\n<p>In my opinion, you should get into the habit of programs working on files, not on user input; you'll find that programs are much easier to chain that way.</p>\n\n<p>Possible further improvements are handling the <code>EOFError</code> (catching it and printing something like \"No even numbers entered.\"), splitting the repeating functionality into a <code>main</code> function (questionable use), and maybe adding a <code>read_float</code> function that would be something along the lines of</p>\n\n<pre><code>def read_float(prompt):\n \"\"\"Read a line from the standard input and return it as a float.\n\n Display the given prompt prior to reading the line. No error checking is done.\n\n \"\"\"\n return float(raw_input(prompt))\n</code></pre>\n\n<p>Here too, there is plenty of room for error checking.</p>\n\n<p>I removed the parentheses around <code>(num%2)</code> as I went along; <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> discourages these, if I remember correctly. Either way, it is a very valuable read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T10:50:28.050", "Id": "13171", "Score": "0", "body": "Thanks for the great feedback, I found it very helpful. You suggested that I put `if __name__ == '__main__':` into my code. Any I correct in thinking that the code will then only be run when the file is called directly? If so, how would you call the code indirectly through another file?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T11:16:04.523", "Id": "13173", "Score": "0", "body": "@TomKadwill - That is correct; if you feel the need to call it from another file, put it into a function (which is often called `main`), as far as I've seen." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T23:32:12.237", "Id": "8404", "ParentId": "8403", "Score": "3" } } ]
<p>I had to replace all instances of scientific notation with fixed point, and wrote a Python script to help out. Here it is:</p> <pre><code>#!/usr/bin/python2 # Originally written by Anton Golov on 29 Jan 2012. # Feedback can be sent to &lt;email&gt; . """Provide functions for converting scientific notation to fixed point. When imported, reads lines from stdin and prints them back to stdout with scientific notation removed. WARNING: The resulting fixed point values may be of a different precision than the original values. This will usually be higher, but may be lower for large numbers. Please don't rely on the precision of the values generated by this script for error analysis. """ from re import compile exp_regex = compile(r"(\d+(\.\d+)?)[Ee](\+|-)(\d+)") def to_fixed_point(match): """Return the fixed point form of the matched number. Parameters: match is a MatchObject that matches exp_regex or similar. If you wish to make match using your own regex, keep the following in mind: group 1 should be the coefficient group 3 should be the sign group 4 should be the exponent """ sign = -1 if match.group(3) == "-" else 1 coefficient = float(match.group(1)) exponent = sign * float(match.group(4)) return "%.16f" % (coefficient * 10**exponent) def main(): """Read lines from stdin and print them with scientific notation removed. """ try: while True: line = raw_input('') print exp_regex.sub(to_fixed_point, line) except EOFError: pass if __name__ == "__main__": main() </code></pre> <p>I am primarily interested about the way the regex is used (can it match something it can't replace?), but comments on code clarity and features that may be simple to add are also welcome, as well as any further nitpicking .</p>
[]
{ "AcceptedAnswerId": "8429", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T18:24:19.200", "Id": "8428", "Score": "2", "Tags": [ "python", "regex" ], "Title": "Python program for converting scientific notation to fixed point" }
8428
accepted_answer
[ { "body": "<pre><code>from re import compile\n\n\nexp_regex = compile(r\"(\\d+(\\.\\d+)?)[Ee](\\+|-)(\\d+)\")\n</code></pre>\n\n<p>Python style guide recommends that global constants be in ALL_CAPS. And what about numbers like \"1e99\"? They won't match this regex.</p>\n\n<pre><code>def to_fixed_point(match):\n \"\"\"Return the fixed point form of the matched number.\n\n Parameters:\n match is a MatchObject that matches exp_regex or similar.\n\n If you wish to make match using your own regex, keep the following in mind:\n group 1 should be the coefficient\n group 3 should be the sign\n group 4 should be the exponent\n\n \"\"\"\n</code></pre>\n\n<p>I'd suggest breaking the groups out of the match into local variables</p>\n\n<pre><code>coefficient, decimals, sign, exponent = match.groups()\n</code></pre>\n\n<p>And then use those names instead of match.group(1). That way your code will be easier to follow.</p>\n\n<pre><code> sign = -1 if match.group(3) == \"-\" else 1\n coefficient = float(match.group(1))\n exponent = sign * float(match.group(4))\n return \"%.16f\" % (coefficient * 10**exponent)\n</code></pre>\n\n<p>Here's the thing. Python already support scientific notation, so you should just ask python to do conversion for you:</p>\n\n<pre><code> value = float(match.group(0))\n</code></pre>\n\n<p>Less bugs, more efficient, better all around.</p>\n\n<pre><code>def main():\n \"\"\"Read lines from stdin and print them with scientific notation removed.\n\n \"\"\"\n try:\n while True:\n line = raw_input('')\n print exp_regex.sub(to_fixed_point, line)\n except EOFError:\n pass\n</code></pre>\n\n<p>I'd suggest using <code>for line in sys.stdin:</code>. It'll automatically get you the lines, stop when the file ends. That'll make this piece of code simpler.</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-29T19:11:23.603", "Id": "8429", "ParentId": "8428", "Score": "2" } } ]
<p>I have existing code that handles a tarball and would like to use that to process a directory, so I thought it would be reasonable to pack the directory up in a temporary file. I ended up writing:</p> <pre><code>class temp_tarball( object ): def __init__( self, path ): self.tmp = tempfile.NamedTemporaryFile() self.tarfile = tarfile.open( None, 'w:', self.tmp ) self.tarfile.add( path, '.' ) self.tarfile.close() self.tmp.flush() self.tarfile = tarfile.open( self.tmp.name, 'r:' ) def __del__( self ): self.tarfile.close() self.tmp.close() </code></pre> <p>I am looking for a cleaner way to reopen the tarfile with mode 'r'.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:47:55.030", "Id": "13363", "Score": "0", "body": "What's your concern with it now?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T16:21:28.297", "Id": "13367", "Score": "0", "body": "@winston I don't like using the NamedTemporaryFile, and would prefer to use tempfile.TemporaryFile. I don't really have a specific complaint; it just smells a bit funny as it is." } ]
{ "AcceptedAnswerId": "10491", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T15:32:27.797", "Id": "8557", "Score": "3", "Tags": [ "python" ], "Title": "Using temporary file as backing object for a tarfile" }
8557
accepted_answer
[ { "body": "<p>You could try:</p>\n\n<pre><code>def __init__(self, path):\n self.tmp = tempfile.TemporaryFile()\n self.tarfile = tarfile.open( fileobj=self.tmp, mode='w:' )\n self.tarfile.add( path, '.' )\n self.tarfile.close()\n self.tmp.flush()\n self.tmp.seek(0)\n self.tarfile = tarfile.open( fileobj=self.tmp, mode='r:' )\n</code></pre>\n\n<p>tarfile() will take a fileobj in the constructor instead of a name, so as long as you don't close it, and instead just seek() to 0 when you want to re-read it, you should be good.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T13:49:08.297", "Id": "10491", "ParentId": "8557", "Score": "2" } } ]
<p>I often need to parse tab-separated text (usually from a huge file) into records. I wrote a generator to do that for me; is there anything that could be improved in it, in terms of performance, extensibility or generality? </p> <pre><code>def table_parser(in_stream, types = None, sep = '\t', endl = '\n', comment = None): header = next(in_stream).rstrip(endl).split(sep) for lineno, line in enumerate(in_stream): if line == endl: continue # ignore blank lines if line[0] == comment: continue # ignore comments fields = line.rstrip(endl).split(sep) try: # could have done this outside the loop instead: # if types is None: types = {c : (lambda x : x) for c in headers} # but it nearly doubles the run-time if types actually is None if types is None: record = {col : fields[no] for no, col in enumerate(header)} else: record = {col : types[col](fields[no]) for no, col in enumerate(header)} except IndexError: print('Insufficient columns in line #{}:\n{}'.format(lineno, line)) raise yield record </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:56:42.030", "Id": "13425", "Score": "0", "body": "@RikPoggi: I asked moderator to move it there. Thank you" } ]
{ "AcceptedAnswerId": "8590", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:40:15.453", "Id": "8589", "Score": "3", "Tags": [ "python", "performance", "parsing", "generator" ], "Title": "Text parser implemented as a generator" }
8589
accepted_answer
[ { "body": "<p>One thing you could try to reduce the amount of code in the loop is to make a function expression for these.</p>\n\n<pre><code> if types is None:\n record = {col : fields[no] for no, col in enumerate(header)}\n else:\n record = {col : types[col](fields[no]) for no, col in enumerate(header)}\n</code></pre>\n\n<p>something like this: <em>not tested but you should get the idea</em></p>\n\n<pre><code>def table_parser(in_stream, types = None, sep = '\\t', endl = '\\n', comment = None):\n header = next(in_stream).rstrip(endl).split(sep)\n enumheader=enumerate(header) #### No need to do this every time\n if types is None:\n def recorder(col,fields): \n return {col : fields[no] for no, col in enumheader}\n else:\n def recorder(col,fields): \n return {col : types[col](fields[no]) for no, col in enumheader}\n\n for lineno, line in enumerate(in_stream):\n if line == endl:\n continue # ignore blank lines\n if line[0] == comment:\n continue # ignore comments\n fields = line.rstrip(endl).split(sep)\n try:\n record = recorder(col,fields)\n except IndexError:\n print('Insufficient columns in line #{}:\\n{}'.format(lineno, line))\n raise\n yield record\n</code></pre>\n\n<p>EDIT: from my first version (read comments)</p>\n\n<pre><code>Tiny thing:\n\n if types is None:\n\nI suggest\n\n if not types:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:48:43.397", "Id": "13426", "Score": "0", "body": "In many cases I think `if types is None` would be preferable. I think I see why you disagree in this case, but I'm curious... could you say more?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:57:12.773", "Id": "13427", "Score": "0", "body": "Generally do not test types if it's not clear that it's required. (duck type). In this case I can't come up with a specific benefit, some other type evaluated to false in a boolean context?\nAlso `is` is testing the identity and would be false even if the other None type was identical to None. Completely academic, yes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T10:03:06.797", "Id": "13428", "Score": "2", "body": "Well, [PEP 8](http://www.python.org/dev/peps/pep-0008/) says \"Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.\" In this particular case, using `is` makes it possible to distinguish between cases where `[]` was passed and cases where no variable was passed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T10:08:51.010", "Id": "13429", "Score": "0", "body": "All right that makes sense. From your link: A Foolish Consistency is the Hobgoblin of Little Minds" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:44:19.277", "Id": "8590", "ParentId": "8589", "Score": "1" } } ]
<p>I often need to parse tab-separated text (usually from a huge file) into records. I wrote a generator to do that for me; is there anything that could be improved in it, in terms of performance, extensibility or generality? </p> <pre><code>def table_parser(in_stream, types = None, sep = '\t', endl = '\n', comment = None): header = next(in_stream).rstrip(endl).split(sep) for lineno, line in enumerate(in_stream): if line == endl: continue # ignore blank lines if line[0] == comment: continue # ignore comments fields = line.rstrip(endl).split(sep) try: # could have done this outside the loop instead: # if types is None: types = {c : (lambda x : x) for c in headers} # but it nearly doubles the run-time if types actually is None if types is None: record = {col : fields[no] for no, col in enumerate(header)} else: record = {col : types[col](fields[no]) for no, col in enumerate(header)} except IndexError: print('Insufficient columns in line #{}:\n{}'.format(lineno, line)) raise yield record </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:56:42.030", "Id": "13425", "Score": "0", "body": "@RikPoggi: I asked moderator to move it there. Thank you" } ]
{ "AcceptedAnswerId": "8590", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:40:15.453", "Id": "8589", "Score": "3", "Tags": [ "python", "performance", "parsing", "generator" ], "Title": "Text parser implemented as a generator" }
8589
accepted_answer
[ { "body": "<p>One thing you could try to reduce the amount of code in the loop is to make a function expression for these.</p>\n\n<pre><code> if types is None:\n record = {col : fields[no] for no, col in enumerate(header)}\n else:\n record = {col : types[col](fields[no]) for no, col in enumerate(header)}\n</code></pre>\n\n<p>something like this: <em>not tested but you should get the idea</em></p>\n\n<pre><code>def table_parser(in_stream, types = None, sep = '\\t', endl = '\\n', comment = None):\n header = next(in_stream).rstrip(endl).split(sep)\n enumheader=enumerate(header) #### No need to do this every time\n if types is None:\n def recorder(col,fields): \n return {col : fields[no] for no, col in enumheader}\n else:\n def recorder(col,fields): \n return {col : types[col](fields[no]) for no, col in enumheader}\n\n for lineno, line in enumerate(in_stream):\n if line == endl:\n continue # ignore blank lines\n if line[0] == comment:\n continue # ignore comments\n fields = line.rstrip(endl).split(sep)\n try:\n record = recorder(col,fields)\n except IndexError:\n print('Insufficient columns in line #{}:\\n{}'.format(lineno, line))\n raise\n yield record\n</code></pre>\n\n<p>EDIT: from my first version (read comments)</p>\n\n<pre><code>Tiny thing:\n\n if types is None:\n\nI suggest\n\n if not types:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:48:43.397", "Id": "13426", "Score": "0", "body": "In many cases I think `if types is None` would be preferable. I think I see why you disagree in this case, but I'm curious... could you say more?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:57:12.773", "Id": "13427", "Score": "0", "body": "Generally do not test types if it's not clear that it's required. (duck type). In this case I can't come up with a specific benefit, some other type evaluated to false in a boolean context?\nAlso `is` is testing the identity and would be false even if the other None type was identical to None. Completely academic, yes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T10:03:06.797", "Id": "13428", "Score": "2", "body": "Well, [PEP 8](http://www.python.org/dev/peps/pep-0008/) says \"Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.\" In this particular case, using `is` makes it possible to distinguish between cases where `[]` was passed and cases where no variable was passed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T10:08:51.010", "Id": "13429", "Score": "0", "body": "All right that makes sense. From your link: A Foolish Consistency is the Hobgoblin of Little Minds" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T09:44:19.277", "Id": "8590", "ParentId": "8589", "Score": "1" } } ]
<p>I create python dictionary based on the parsed data:</p> <pre><code>user_details['city'] = None if api_result.get('response')[1] and api_result.get('response')[1][0]: api_result_response = api_result.get('response')[1][0] # city details if api_result_response: user_details['city'] = int(api_result_response.get('cid')) city_name = api_result_response.get('name') if user_details['city'] and city_name: # do something </code></pre> <p>So, I do a lot of verifications if passed data exists, if <code>user_details['city']</code> assigned etc. Is there any way to simplify that?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T13:27:42.437", "Id": "8652", "Score": "4", "Tags": [ "python" ], "Title": "Python dictionary usage" }
8652
max_votes
[ { "body": "<p>Another key feature to dictionaries is the <code>dict.get(key, default)</code> function which allows you to get a default value if the key doesn't exist. This allows you to make the code less cluttered with <code>if</code> statements and also <code>try/except</code>.</p>\n\n<p>The solution is often a balance between <code>if</code> and <code>try</code> statements and default values. If you are checking correctness of values, keep the <code>try/catch</code> statements as small as possible.</p>\n\n<pre><code> response = api_result.get('response', None)\n if response:\n city_name = response.get('name', '')\n try:\n user_details['city'] = int( reponse.get('cid', 0) )\n except ValueError, e:\n pass # report that the 'cid' value was bogus\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T17:40:31.077", "Id": "13527", "Score": "0", "body": "I think your answer would be better to include the numerical indexes as well as the string ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T15:42:16.033", "Id": "13579", "Score": "0", "body": "FWIW, PEP8 asks you to use `if response is not None:`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T04:22:25.820", "Id": "13844", "Score": "0", "body": "@WielandH., this way you will get an `AttributeError` on the next line, if response will happen to be `0`/`[]`/`False`/`()`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T16:51:21.280", "Id": "8660", "ParentId": "8652", "Score": "4" } } ]
<p>I create python dictionary based on the parsed data:</p> <pre><code>user_details['city'] = None if api_result.get('response')[1] and api_result.get('response')[1][0]: api_result_response = api_result.get('response')[1][0] # city details if api_result_response: user_details['city'] = int(api_result_response.get('cid')) city_name = api_result_response.get('name') if user_details['city'] and city_name: # do something </code></pre> <p>So, I do a lot of verifications if passed data exists, if <code>user_details['city']</code> assigned etc. Is there any way to simplify that?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T13:27:42.437", "Id": "8652", "Score": "4", "Tags": [ "python" ], "Title": "Python dictionary usage" }
8652
max_votes
[ { "body": "<p>Another key feature to dictionaries is the <code>dict.get(key, default)</code> function which allows you to get a default value if the key doesn't exist. This allows you to make the code less cluttered with <code>if</code> statements and also <code>try/except</code>.</p>\n\n<p>The solution is often a balance between <code>if</code> and <code>try</code> statements and default values. If you are checking correctness of values, keep the <code>try/catch</code> statements as small as possible.</p>\n\n<pre><code> response = api_result.get('response', None)\n if response:\n city_name = response.get('name', '')\n try:\n user_details['city'] = int( reponse.get('cid', 0) )\n except ValueError, e:\n pass # report that the 'cid' value was bogus\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T17:40:31.077", "Id": "13527", "Score": "0", "body": "I think your answer would be better to include the numerical indexes as well as the string ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T15:42:16.033", "Id": "13579", "Score": "0", "body": "FWIW, PEP8 asks you to use `if response is not None:`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T04:22:25.820", "Id": "13844", "Score": "0", "body": "@WielandH., this way you will get an `AttributeError` on the next line, if response will happen to be `0`/`[]`/`False`/`()`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T16:51:21.280", "Id": "8660", "ParentId": "8652", "Score": "4" } } ]
<p>For <a href="http://www.cs.rhul.ac.uk/home/joseph/teapot.html" rel="nofollow">this project</a>, I'm using a small piece of Python code to return an error 418 to any request. I'm interested in knowing if there is a much smaller piece of code that does the same thing.</p> <pre><code>#Modfied from code provided by Copyright Jon Berg , turtlemeat.com import string,cgi,time from os import curdir, sep from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer #import pri class MyHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_error(418,'I am a Teapot') def main(): try: server = HTTPServer(('', 80), MyHandler) print 'started httpserver...' server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close() if __name__ == '__main__': main() </code></pre> <p>PS - I considered putting this on Code Golf SE, but I wasn't sure if single-language-only requests are on-topic.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T17:26:06.027", "Id": "13874", "Score": "0", "body": "Why do you want a shorter version?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-11T09:42:22.263", "Id": "13905", "Score": "0", "body": "Oh, well, mainly out of interest and to perhaps illustrate to me that there are much more compact ways that this can be done..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T12:06:09.983", "Id": "54428", "Score": "1", "body": "Code Golf questions should be asked exclusively on [codegolf.se] and are off-topic here." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-09T08:52:33.457", "Id": "8799", "Score": "0", "Tags": [ "python" ], "Title": "Python server that only returns error 418" }
8799
max_votes
[ { "body": "<p>Not really <em>smaller</em> but it will respond to any request, not just GET:</p>\n\n<pre><code>class MyHandler(BaseHTTPRequestHandler):\n def handle_one_request(self):\n self.send_error(418, 'I am a Teapot')\n</code></pre>\n\n<p>Usually, <code>handle_one_request</code> delegates to the appropriate <code>do_METHOD</code> method, but since we want to treat all of them equal, we may as well not let that delegation take place.</p>\n\n<p>In the interest of making things shorter, you generally don't need the <code>server.socket.close()</code>, unless you plan on restarting a server on that same port right after shutting down this server.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T18:40:11.477", "Id": "9567", "ParentId": "8799", "Score": "2" } } ]
<p>This is from an answer to my own <a href="https://stackoverflow.com/q/9242733/12048">StackOverflow question</a> on how to efficiently find a <a href="http://en.wikipedia.org/wiki/Regular_number" rel="nofollow noreferrer">regular number</a> that is greater than or equal to a given value.</p> <p>I originally implemented this in C# but translated it to Python because I guessed (correctly) that it would be shorter and would eliminate a third-party library dependency.</p> <p>I am a Python newbie though - This is the longest Python program I have ever written. So I would like to know:</p> <ul> <li>Is there a convention for indicating what version of the language you are targeting (like <code>require&nbsp;&lt;version&gt;</code> in perl?) This program only works in 2.6. <li>Instead of the priority queue, is there a better way to generate the odd regular numbers? I know it is possible to implement lazy lists in Python but they are not in 2.6 are they? <li>Any other idioms/naming conventions I am missing? </ul> <pre><code>from itertools import ifilter, takewhile from Queue import PriorityQueue def nextPowerOf2(n): p = max(1, n) while p != (p &amp; -p): p += p &amp; -p return p # Generate multiples of powers of 3, 5 def oddRegulars(): q = PriorityQueue() q.put(1) prev = None while not q.empty(): n = q.get() if n != prev: prev = n yield n if n % 3 == 0: q.put(n // 3 * 5) q.put(n * 3) # Generate regular numbers with the same number of bits as n def regularsCloseTo(n): p = nextPowerOf2(n) numBits = len(bin(n)) for i in takewhile(lambda x: x &lt;= p, oddRegulars()): yield i &lt;&lt; max(0, numBits - len(bin(i))) def nextRegular(n): bigEnough = ifilter(lambda x: x &gt;= n, regularsCloseTo(n)) return min(bigEnough) </code></pre>
[]
{ "AcceptedAnswerId": "8931", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T23:29:25.053", "Id": "8928", "Score": "5", "Tags": [ "python" ], "Title": "Find the smallest regular number that is not less than N (Python)" }
8928
accepted_answer
[ { "body": "<pre><code>from itertools import ifilter, takewhile\nfrom Queue import PriorityQueue\n\ndef nextPowerOf2(n):\n</code></pre>\n\n<p>Python convention says that function should be named with_underscores</p>\n\n<pre><code> p = max(1, n)\n while p != (p &amp; -p):\n</code></pre>\n\n<p>Parens not needed.</p>\n\n<pre><code> p += p &amp; -p\n return p\n</code></pre>\n\n<p>I suspect that isn't the most efficient way to implement this function. See here for some profiling done on various implementations. <a href=\"http://www.willmcgugan.com/blog/tech/2007/7/1/profiling-bit-twiddling-in-python/\" rel=\"nofollow\">http://www.willmcgugan.com/blog/tech/2007/7/1/profiling-bit-twiddling-in-python/</a></p>\n\n<pre><code># Generate multiples of powers of 3, 5\ndef oddRegulars():\n q = PriorityQueue()\n</code></pre>\n\n<p>So this is a synchronized class, intended to be used for threading purposes. Since you aren't using it that way, you are paying for locking you aren't using.</p>\n\n<pre><code> q.put(1)\n prev = None\n while not q.empty():\n</code></pre>\n\n<p>Given that the queue will never be empty in this algorithm, why are you checking for it?</p>\n\n<pre><code> n = q.get()\n if n != prev:\n prev = n\n</code></pre>\n\n<p>The prev stuff bothers me. Its ugly code that seems to distract from your algorithm. It also means that you are generating duplicates of the same number. I.e. it would be better to avoid generating the duplicates at all.</p>\n\n<pre><code> yield n\n if n % 3 == 0:\n q.put(n // 3 * 5)\n q.put(n * 3)\n</code></pre>\n\n<p>So why don't you just push <code>n * 3</code> and <code>n * 5</code> onto your queue?</p>\n\n<pre><code># Generate regular numbers with the same number of bits as n\ndef regularsCloseTo(n):\n p = nextPowerOf2(n)\n numBits = len(bin(n))\n</code></pre>\n\n<p>These two things are basically the same thing. <code>p = 2**(numBits+1)</code>. You should be able to calculate one from the other rather then going through the work over again.</p>\n\n<pre><code> for i in takewhile(lambda x: x &lt;= p, oddRegulars()):\n yield i &lt;&lt; max(0, numBits - len(bin(i)))\n</code></pre>\n\n<p>I'd have a comment here because its tricky to figure out what you are doing. </p>\n\n<pre><code>def nextRegular(n):\n bigEnough = ifilter(lambda x: x &gt;= n, regularsCloseTo(n))\n return min(bigEnough)\n</code></pre>\n\n<p>I'd combine those two lines.</p>\n\n<blockquote>\n <p>Is there a convention for indicating what version of the language you are targeting (like > require in perl?) This program only works in 2.6.</p>\n</blockquote>\n\n<p>Honestly, much programs just fail when trying to use something not supported in the current version of python. </p>\n\n<blockquote>\n <p>I know it is possible to implement lazy lists in Python but they are not in 2.6 are they?</p>\n</blockquote>\n\n<p>Lazy lists? You might be referring to generators. But they are supported in 2.6, and you used one in your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T16:57:08.783", "Id": "14009", "Score": "0", "body": "The point of the bit twiddling was to calculate exactly the right power of 2 to multiply by to get the regular number in the right range. This could be applied to your version, if you turn those nested loops inside-out, the inner loop could be replaced by a bit count + shift. \nAnd no I was referring to lazy lists: http://svn.python.org/projects/python/tags/r267/Lib/test/test_generators.py" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T17:00:59.270", "Id": "14010", "Score": "0", "body": "@finnw, oh I figured out what you were doing with the bit twiddles. It just took me a while, hence my suggestion for a comment. Certainly you can further improve my version, I've left that as an exercise for the reader." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T17:03:14.480", "Id": "14011", "Score": "1", "body": "@finnw, I don't think that any version of python includes lazy lists. You can implement lazy lists, which is what is done in what you linked. But as far as I know they've never been added to the standard library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-02T23:51:52.010", "Id": "51372", "Score": "0", "body": "Note that this doesn't fulfill the original requirements of \"greater than or equal to\". The original question wants p(18) = 18, but this returns 24" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T02:02:45.247", "Id": "51605", "Score": "0", "body": "This doesn't produce the right numbers. `next_regular(670)` should produce 675 but produces 720, `next_regular(49)` should produce 50 but produces 54, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-06T02:06:41.250", "Id": "51606", "Score": "1", "body": "@endolith, removed apparently bad algorithm." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-13T04:53:31.293", "Id": "8931", "ParentId": "8928", "Score": "2" } } ]
<p>This is a script I wrote to find the <em>n</em> biggest files in a given directory (recursively):</p> <pre><code>import heapq import os, os.path import sys import operator def file_sizes(directory): for path, _, filenames in os.walk(directory): for name in filenames: full_path = os.path.join(path, name) yield full_path, os.path.getsize(full_path) num_files, directory = sys.argv[1:] num_files = int(num_files) big_files = heapq.nlargest( num_files, file_sizes(directory), key=operator.itemgetter(1)) print(*("{}\t{:&gt;}".format(*b) for b in big_files)) </code></pre> <p>It can be run as, eg: <code>bigfiles.py 5 ~</code>. </p> <p>Ignoring the complete lack of error handling, is there any obvious way to make this clearer, or at least more succinct? I am thinking about, eg, using <code>namedtuple</code>s in <code>file_sizes</code>, but is there also any way to implement <code>file_sizes</code> in terms of a generator expression? (I'm thinking probably not without having two calls to <code>os.path</code>, but I'd love to be proven wrong :-)</p>
[]
{ "AcceptedAnswerId": "8973", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T05:54:29.153", "Id": "8958", "Score": "6", "Tags": [ "python" ], "Title": "n largest files in a directory" }
8958
accepted_answer
[ { "body": "<p>You could replace your function with:</p>\n\n<pre><code>file_names = (os.path.join(path, name) for path, _, filenames in os.walk(directory)\n for name in filenames)\n\nfile_sizes = ((name, os.path.getsize(name)) for name in file_names)\n</code></pre>\n\n<p>However, I'm not sure that really helps the clarity.</p>\n\n<p>I found doing this:</p>\n\n<pre><code>big_files = heapq.nlargest(\n num_files, file_names, key=os.path.getsize)\nprint(*(\"{}\\t{:&gt;}\".format(b, os.path.getsize(b)) for b in big_files))\n</code></pre>\n\n<p>Actually runs slightly quicker then your version. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T02:47:46.840", "Id": "14088", "Score": "0", "body": "That's an interesting result. How did you time it? You wouldn't think that twice as many syscalls would speed it up!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T03:59:33.457", "Id": "14089", "Score": "0", "body": "@lvc, I used `time python script.py`. Its not making twice as many sys calls because I'm only making the second call for the top 5 or so files." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-15T05:06:16.653", "Id": "14092", "Score": "0", "body": "Ah, indeed, it will only be `num_files` extra syscalls. Presumably, what's happening is that constructing multiple tuples is more expensive - if that's the case, we could expect the difference to shrink and eventually go away as `num_files` approaches the number of files searched. But, when I look at it, I think I do prefer `key=os.path.getsize` over my many tuples for clarity, anyway." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-14T19:49:58.823", "Id": "8973", "ParentId": "8958", "Score": "4" } } ]
<p>I wrote code in python that works slow. Because I am new to python, I am not sure that I am doing everything right. My question is what I can do optimally? About the problem: I have 25 *.json files, each is about 80 MB. Each file just contain json strings. I need make some histogram based on data.</p> <p>In this part I want create list of all dictionaries ( one dictionary represent json object):</p> <pre><code>d = [] # filename is list of name of files for x in filename: d.extend(map(json.loads, open(x))) </code></pre> <p>then I want to create list <code>u</code> :</p> <pre><code>u = [] for x in d: s = x['key_1'] # s is sting which I use to get useful value t1 = 60*int(s[11:13]) + int(s[14:16])# t1 is useful value u.append(t1) </code></pre> <p>Now I am creating histogram:</p> <pre><code>plt.hist(u, bins = (max(u) - min(u))) plt.show() </code></pre> <p>Any thought and suggestions are appreciated. Thank you!</p>
[]
{ "AcceptedAnswerId": "8966", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T03:51:37.250", "Id": "8963", "Score": "6", "Tags": [ "python", "json" ], "Title": "python: is my program optimal" }
8963
accepted_answer
[ { "body": "<p>You might be able to save some run time by using a couple of <a href=\"http://docs.python.org/reference/expressions.html#generator-expressions\" rel=\"nofollow\">generator expressions</a> and a <a href=\"http://docs.python.org/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehension</a>. For example:</p>\n\n<pre><code>def read_json_file(name):\n with open(name, \"r\") as f:\n return json.load(f)\n\ndef compute(s):\n return 60 * int(s[11:13]) + int(s[14:16])\n\nd = (read_json_file(n) for n in filename)\nu = list(compute(x['key_1']) for x in d)\n\nplt.hist(u, bins = (max(u) - min(u)))\nplt.show()\n</code></pre>\n\n<p>This should save on memory, since anything that isn't needed is discarded.</p>\n\n<p><strong>Edit:</strong> it's difficult to discern from the information available, but I think the OP's json files contain multiple json objects, so calling <code>json.load(f)</code> won't work. If that is the case, then this code should fix the problem</p>\n\n<pre><code>def read_json_file(name):\n \"Return an iterable of objects loaded from the json file 'name'\"\n with open(name, \"r\") as f:\n for s in f:\n yield json.loads(s)\n\ndef compute(s):\n return 60 * int(s[11:13]) + int(s[14:16])\n\n# d is a generator yielding an iterable at each iteration\nd = (read_json_file(n) for n in filename)\n\n# j is the flattened version of d\nj = (obj for iterable in d for obj in iterable)\n\nu = list(compute(x['key_1']) for x in j)\n\nplt.hist(u, bins = (max(u) - min(u)))\nplt.show()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:05:43.503", "Id": "14046", "Score": "0", "body": "your code gives error : ValueError: Extra data: line 2 column 1 - line 131944 column 1 (char 907 - 96281070)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:16:39.913", "Id": "14047", "Score": "0", "body": "I created a couple of test json files and ran this code in Python 2.7 and it worked fine for me. The error appears to be in reading the json file, but without seeing your actual code and the content of your json files, its very difficult for me to diagnose the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:24:55.803", "Id": "14048", "Score": "0", "body": "2srgerg it returns error from read_json_file function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:26:12.747", "Id": "14049", "Score": "0", "body": "here my code: def read_json_file(name):\n with open(name,'r') as f:\n return json.loads(f.read())\n \ndef compute_time(s):\n return 60 * int(s[11:13]) + int(s[14:16]) \n\nd = (read_json_file(n) for n in filename)\nu = list(map(compute_time, (x['time'] for x in d)))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:30:31.487", "Id": "14050", "Score": "0", "body": "I've edited my answer with what I *think* might solve the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:45:12.457", "Id": "14051", "Score": "0", "body": "could you explain this line please: j = (obj for iterable in d for obj in iterable) I think it should be just j = (obj for iterable in d)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T06:50:56.750", "Id": "14052", "Score": "0", "body": "The new `read_json_file(...)` function returns a list of objects loaded from the json file. That means that each element of `d` will be a list of objects, not a single object. To get an iterable of single objects we need to flatten `d` and that is what the line of code does. See [this other stack overflow question](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) for more detail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T08:32:17.683", "Id": "14053", "Score": "1", "body": "There is a great piece about generators and doing this exact kind of work available here - http://www.dabeaz.com/generators/" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T04:30:36.957", "Id": "8966", "ParentId": "8963", "Score": "3" } } ]
<p>The problem I want to solve is to replace a given string inside tags.</p> <p>For example, if I'm given:</p> <blockquote> <p>Some text abc [tag]some text abc, more text abc[/tag] still some more text</p> </blockquote> <p>I want to replace <code>abc</code> for <code>def</code> but only inside the tags, so the output would be:</p> <blockquote> <p>Some text abc [tag]some text def, more text def[/tag] still some more text</p> </blockquote> <p>We may assume that the tag nesting is well formed. My solution is the following:</p> <pre><code>def replace_inside(text): i = text.find('[tag]') while i &gt;= 0: j = text.find('[/tag]', i+1) snippet = text[i:j].replace('abc', 'def') text = text[:i] + snippet + text[j:] i = text.find('[tag]', j) return text </code></pre> <p>I was wondering if it can be solved in a more elegant way, for example, using regex.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:59:54.327", "Id": "14235", "Score": "0", "body": "This reminds me of bbcode ... could this help: http://www.codigomanso.com/en/2010/09/bbcodeutils-bbcode-parser-and-bbcode-to-html-for-python/" } ]
{ "AcceptedAnswerId": "9074", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T00:17:09.643", "Id": "9072", "Score": "2", "Tags": [ "python", "regex" ], "Title": "Replace match inside tags" }
9072
accepted_answer
[ { "body": "<p>Your code is incorrect. See the following case:</p>\n\n<pre><code>print replace_inside(\"[tag]abc[/tag]abc[tag]abc[/tag]\")\n</code></pre>\n\n<p>You can indeed use regular expressions</p>\n\n<pre><code>pattern = re.compile(r\"\\[tag\\].*?\\[/tag\\]\")\nreturn pattern.sub(lambda match: match.group(0).replace('abc','def') ,text)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:54:28.453", "Id": "14234", "Score": "1", "body": "doesn't it need to be `r\"\\[tag\\].*?\\[/tag\\]\"` for a non-greedy `*`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T21:37:31.493", "Id": "14268", "Score": "0", "body": "@Winston Ewert♦: you're right, I fixed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T21:38:55.547", "Id": "14269", "Score": "0", "body": "I agree with @James Khoury, it's necessary to use the non-greed version, otherwise it will fail in your test case too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T06:12:27.237", "Id": "14279", "Score": "1", "body": "@JamesKhoury, thanks. It seems I don't do regular expressions enough." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T01:10:15.363", "Id": "9074", "ParentId": "9072", "Score": "1" } } ]
<p>I'm not a programmer, but am playing around with a binary tree Class in Python and would like help with a recursive method to count interior nodes of a given tree.</p> <p>The code below seems to work, but is this solution the clearest, in terms of logic, for counting interior nodes? I'm keen that the code is the cleanest and most logical solution, whilst remaining recursive.</p> <p>The qualifier for being an interior node, as far as I'm aware here is, that an interior node should have a parent, and at least one child node.</p> <pre><code>def count_interior_nodes(self, root): """Return number of internal nodes in tree""" if(root.parent == None): # Root node so don't count, but recurse tree return self.count_interior_nodes(root.left) + self.count_interior_nodes(root.right) + 0 elif (root.left != None or root.right != None): # Has parent, but isn't leaf node, so count and recurse return self.count_interior_nodes(root.left) + self.count_interior_nodes(root.right) + 1 else: # Leaf node, so return zero return 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:42:02.770", "Id": "14300", "Score": "0", "body": "Just to get your head thinking about this, suppose we were at the root node (so `parent` == `None`), what would happen if one of the children were `None`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:58:03.423", "Id": "14301", "Score": "0", "body": "Hi @Jeff, All nodes have a `left` and `right` attribute, so leaf nodes would both be set to `None` in which case `root.left == None and root.right == None` and would return `0` up the recursion tree, this would be a base case wouldn't it? So zero would be added to the cumulative total." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T18:02:18.840", "Id": "14302", "Score": "0", "body": "I guess you need a specific example to see what I'm hinting at. Consider the tree where you have the root and it has a left child which is a leaf and no right child. So something like this: `Tree(left = Tree(left = None, right = None), right = None)`. Step through this with your code (or run it) and see what happens." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T23:30:42.133", "Id": "14312", "Score": "1", "body": "The more classic way of implementing this recursively is not to care if you are the root. `If you are NULL then it is 0. Otherwise it is 1 + Count(left) + Count(right)`. You can the wrap this with a function that prints information and calls Count(root)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T10:34:31.007", "Id": "14317", "Score": "0", "body": "@Jeff, Is it that I haven't accounted for the exception where `root == None`? @Loki I'm looking to count interior nodes only, so the node must have a parent and should have at most one `Null` child node (i.e not interested in counting all nodes)." } ]
{ "AcceptedAnswerId": "9148", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-18T17:23:37.727", "Id": "9115", "Score": "1", "Tags": [ "python" ], "Title": "Method to count interior nodes of a binary tree" }
9115
accepted_answer
[ { "body": "<p>So after our little discussion, I hope you see that you're missing some key cases here, when the <code>root</code> given is <code>None</code>.</p>\n\n<p>Some things that should be pointed out, when comparing to <code>None</code>, you should be checking if it <code>is</code> or <code>is not</code> <code>None</code>. Don't use (in)equality here, it is just not correct.</p>\n\n<p>Assuming this is a method on your tree node objects, I'd rewrite this to make use of <code>self</code>. That way we don't even need to worry about the case when <code>self</code> is <code>None</code>, that just shouldn't happen.</p>\n\n<pre><code>def count_interior_nodes(self):\n count = 0\n hasLeft, hasRight = self.left is not None, self.right is not None\n if hasLeft:\n count += self.left.count_interior_nodes()\n if hasRight:\n count += self.right.count_interior_nodes()\n if (hasLeft or hasRight) and self.parent is not None:\n count += 1\n return count\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T22:29:47.347", "Id": "14483", "Score": "0", "body": "Hi @Jeff, thanks for the great advice. So when the `root is None` the `count` is returned? Good to make use of `self` as it is indeed a method of the Tree Node object. I didn't know and the rule when comparing `None` either, so I've gone through and corrected all my code on this note! I've also some other methods, such as `get_height()` I've also got them to make use of `self`. Great advice. Cheers Alex" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T23:51:22.203", "Id": "14492", "Score": "0", "body": "In your code, the big issue is that when the `root` given is `None`, you'll get an attribute error on the `None` object (which is equivalent to a \"NullReferenceException\" in other languages). In that case, the `count` wouldn't be returned. In fact, nothing is returned since an exception was raised and unhandled. That should not be an issue when running the code I've provided. We can assume that `self` will always be set to an instance of your class so we avoid that case. We're also checking beforehand if the children are `None` so no chance of the attribute error." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T17:48:27.873", "Id": "9148", "ParentId": "9115", "Score": "1" } } ]
<p>the question is simple, for a input [apple, banana, orange, apple, banana, apple], the program will count it as a map: {apple : 3, orange: 1, banana: 2}, then sort this map by it's values, get [(apple, 3), (banana, 2), (orange, 1)] below is my go version, I'm a go newbie, could you please review it and lecture me how to polish the code? I add a python version for reference</p> <pre><code>package main //input, a url.log file, like "apple\nbanana\norange\napple\nbanana\napple\n" //output, a output.txt file, should be "apple: 3\nbanana: 2\norange: 1\n" import ( "fmt" "bufio" "os" "sort" "strings" "io" ) func main() { m := make(map[string]int) // read file line by line filename := "url.log" f, err := os.Open(filename) if err != nil { fmt.Println(err) return } defer f.Close() r := bufio.NewReader(f) for line, err := r.ReadString('\n'); err == nil; { url := strings.TrimRight(line, "\n") m[url] += 1 // build the map line, err = r.ReadString('\n') } if err != nil { fmt.Println(err) return } //sort the map by it's value vs := NewValSorter(m) vs.Sort() // output f_out, _ := os.Create("output.go.txt") defer f_out.Close() var line string for i, k := range vs.Keys { line = fmt.Sprintf("%s: %d\n", k, vs.Vals[i]) io.WriteString(f_out, line) } } type ValSorter struct { Keys []string Vals []int } func NewValSorter(m map[string]int) *ValSorter { vs := &amp;ValSorter { Keys: make([]string, 0, len(m)), Vals: make([]int, 0, len(m)), } for k, v := range m { vs.Keys = append(vs.Keys, k) vs.Vals = append(vs.Vals, v) } return vs } func (vs *ValSorter) Sort() { sort.Sort(vs) } func (vs *ValSorter) Len() int { return len(vs.Vals) } func (vs *ValSorter) Less(i, j int) bool { return vs.Vals[i] &gt; vs.Vals[j] } func (vs *ValSorter) Swap(i, j int) { vs.Vals[i], vs.Vals[j] = vs.Vals[j], vs.Vals[i] vs.Keys[i], vs.Keys[j] = vs.Keys[j], vs.Keys[i] } </code></pre> <p>python version:</p> <pre><code>from collections import Counter def main(): count = Counter() with open("url.log", "rb") as f: for line in f: url = line.rstrip() count[url] += 1 with open("output.py.txt", "wb") as f: for key, value in count.most_common(): f.write("%s: %d\n" %(key, value)) if __name__ == "__main__": main() </code></pre>
[]
{ "AcceptedAnswerId": "12396", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T14:03:36.133", "Id": "9146", "Score": "3", "Tags": [ "python", "go" ], "Title": "code review for count then sort problems (go lang)" }
9146
accepted_answer
[ { "body": "<p>In Go, I would write:</p>\n\n<pre><code>package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"io\"\n \"os\"\n \"sort\"\n)\n\ntype Key string\ntype Count int\n\ntype Elem struct {\n Key\n Count\n}\n\ntype Elems []*Elem\n\nfunc (s Elems) Len() int {\n return len(s)\n}\n\nfunc (s Elems) Swap(i, j int) {\n s[i], s[j] = s[j], s[i]\n}\n\ntype ByReverseCount struct{ Elems }\n\nfunc (s ByReverseCount) Less(i, j int) bool {\n return s.Elems[j].Count &lt; s.Elems[i].Count\n}\n\nfunc main() {\n m := make(map[Key]Count)\n fi, err := os.Open(\"keys.txt\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer fi.Close()\n r := bufio.NewReader(fi)\n for {\n line, err := r.ReadString('\\n')\n if err != nil {\n if err == io.EOF &amp;&amp; len(line) == 0 {\n break\n }\n fmt.Println(err)\n return\n }\n key := line[:len(line)-1]\n m[Key(key)] += 1\n }\n fi.Close()\n\n e := make(Elems, 0, len(m))\n for k, c := range m {\n e = append(e, &amp;Elem{k, c})\n }\n sort.Sort(ByReverseCount{e})\n\n fo, err := os.Create(\"counts.txt\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer fo.Close()\n for _, e := range e {\n line := fmt.Sprintf(\"%s: %d\\n\", e.Key, e.Count)\n fo.WriteString(line)\n }\n}\n</code></pre>\n\n<p>Input (<code>keys.txt</code>):</p>\n\n<pre><code>apple\nbanana\norange\napple\nbanana\napple\n</code></pre>\n\n<p>Output (<code>counts.txt</code>):</p>\n\n<pre><code>apple: 3\nbanana: 2\norange: 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T17:44:03.120", "Id": "12396", "ParentId": "9146", "Score": "4" } } ]
<p>the question is simple, for a input [apple, banana, orange, apple, banana, apple], the program will count it as a map: {apple : 3, orange: 1, banana: 2}, then sort this map by it's values, get [(apple, 3), (banana, 2), (orange, 1)] below is my go version, I'm a go newbie, could you please review it and lecture me how to polish the code? I add a python version for reference</p> <pre><code>package main //input, a url.log file, like "apple\nbanana\norange\napple\nbanana\napple\n" //output, a output.txt file, should be "apple: 3\nbanana: 2\norange: 1\n" import ( "fmt" "bufio" "os" "sort" "strings" "io" ) func main() { m := make(map[string]int) // read file line by line filename := "url.log" f, err := os.Open(filename) if err != nil { fmt.Println(err) return } defer f.Close() r := bufio.NewReader(f) for line, err := r.ReadString('\n'); err == nil; { url := strings.TrimRight(line, "\n") m[url] += 1 // build the map line, err = r.ReadString('\n') } if err != nil { fmt.Println(err) return } //sort the map by it's value vs := NewValSorter(m) vs.Sort() // output f_out, _ := os.Create("output.go.txt") defer f_out.Close() var line string for i, k := range vs.Keys { line = fmt.Sprintf("%s: %d\n", k, vs.Vals[i]) io.WriteString(f_out, line) } } type ValSorter struct { Keys []string Vals []int } func NewValSorter(m map[string]int) *ValSorter { vs := &amp;ValSorter { Keys: make([]string, 0, len(m)), Vals: make([]int, 0, len(m)), } for k, v := range m { vs.Keys = append(vs.Keys, k) vs.Vals = append(vs.Vals, v) } return vs } func (vs *ValSorter) Sort() { sort.Sort(vs) } func (vs *ValSorter) Len() int { return len(vs.Vals) } func (vs *ValSorter) Less(i, j int) bool { return vs.Vals[i] &gt; vs.Vals[j] } func (vs *ValSorter) Swap(i, j int) { vs.Vals[i], vs.Vals[j] = vs.Vals[j], vs.Vals[i] vs.Keys[i], vs.Keys[j] = vs.Keys[j], vs.Keys[i] } </code></pre> <p>python version:</p> <pre><code>from collections import Counter def main(): count = Counter() with open("url.log", "rb") as f: for line in f: url = line.rstrip() count[url] += 1 with open("output.py.txt", "wb") as f: for key, value in count.most_common(): f.write("%s: %d\n" %(key, value)) if __name__ == "__main__": main() </code></pre>
[]
{ "AcceptedAnswerId": "12396", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T14:03:36.133", "Id": "9146", "Score": "3", "Tags": [ "python", "go" ], "Title": "code review for count then sort problems (go lang)" }
9146
accepted_answer
[ { "body": "<p>In Go, I would write:</p>\n\n<pre><code>package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"io\"\n \"os\"\n \"sort\"\n)\n\ntype Key string\ntype Count int\n\ntype Elem struct {\n Key\n Count\n}\n\ntype Elems []*Elem\n\nfunc (s Elems) Len() int {\n return len(s)\n}\n\nfunc (s Elems) Swap(i, j int) {\n s[i], s[j] = s[j], s[i]\n}\n\ntype ByReverseCount struct{ Elems }\n\nfunc (s ByReverseCount) Less(i, j int) bool {\n return s.Elems[j].Count &lt; s.Elems[i].Count\n}\n\nfunc main() {\n m := make(map[Key]Count)\n fi, err := os.Open(\"keys.txt\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer fi.Close()\n r := bufio.NewReader(fi)\n for {\n line, err := r.ReadString('\\n')\n if err != nil {\n if err == io.EOF &amp;&amp; len(line) == 0 {\n break\n }\n fmt.Println(err)\n return\n }\n key := line[:len(line)-1]\n m[Key(key)] += 1\n }\n fi.Close()\n\n e := make(Elems, 0, len(m))\n for k, c := range m {\n e = append(e, &amp;Elem{k, c})\n }\n sort.Sort(ByReverseCount{e})\n\n fo, err := os.Create(\"counts.txt\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer fo.Close()\n for _, e := range e {\n line := fmt.Sprintf(\"%s: %d\\n\", e.Key, e.Count)\n fo.WriteString(line)\n }\n}\n</code></pre>\n\n<p>Input (<code>keys.txt</code>):</p>\n\n<pre><code>apple\nbanana\norange\napple\nbanana\napple\n</code></pre>\n\n<p>Output (<code>counts.txt</code>):</p>\n\n<pre><code>apple: 3\nbanana: 2\norange: 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T17:44:03.120", "Id": "12396", "ParentId": "9146", "Score": "4" } } ]
<p>the question is simple, for a input [apple, banana, orange, apple, banana, apple], the program will count it as a map: {apple : 3, orange: 1, banana: 2}, then sort this map by it's values, get [(apple, 3), (banana, 2), (orange, 1)] below is my go version, I'm a go newbie, could you please review it and lecture me how to polish the code? I add a python version for reference</p> <pre><code>package main //input, a url.log file, like "apple\nbanana\norange\napple\nbanana\napple\n" //output, a output.txt file, should be "apple: 3\nbanana: 2\norange: 1\n" import ( "fmt" "bufio" "os" "sort" "strings" "io" ) func main() { m := make(map[string]int) // read file line by line filename := "url.log" f, err := os.Open(filename) if err != nil { fmt.Println(err) return } defer f.Close() r := bufio.NewReader(f) for line, err := r.ReadString('\n'); err == nil; { url := strings.TrimRight(line, "\n") m[url] += 1 // build the map line, err = r.ReadString('\n') } if err != nil { fmt.Println(err) return } //sort the map by it's value vs := NewValSorter(m) vs.Sort() // output f_out, _ := os.Create("output.go.txt") defer f_out.Close() var line string for i, k := range vs.Keys { line = fmt.Sprintf("%s: %d\n", k, vs.Vals[i]) io.WriteString(f_out, line) } } type ValSorter struct { Keys []string Vals []int } func NewValSorter(m map[string]int) *ValSorter { vs := &amp;ValSorter { Keys: make([]string, 0, len(m)), Vals: make([]int, 0, len(m)), } for k, v := range m { vs.Keys = append(vs.Keys, k) vs.Vals = append(vs.Vals, v) } return vs } func (vs *ValSorter) Sort() { sort.Sort(vs) } func (vs *ValSorter) Len() int { return len(vs.Vals) } func (vs *ValSorter) Less(i, j int) bool { return vs.Vals[i] &gt; vs.Vals[j] } func (vs *ValSorter) Swap(i, j int) { vs.Vals[i], vs.Vals[j] = vs.Vals[j], vs.Vals[i] vs.Keys[i], vs.Keys[j] = vs.Keys[j], vs.Keys[i] } </code></pre> <p>python version:</p> <pre><code>from collections import Counter def main(): count = Counter() with open("url.log", "rb") as f: for line in f: url = line.rstrip() count[url] += 1 with open("output.py.txt", "wb") as f: for key, value in count.most_common(): f.write("%s: %d\n" %(key, value)) if __name__ == "__main__": main() </code></pre>
[]
{ "AcceptedAnswerId": "12396", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-19T14:03:36.133", "Id": "9146", "Score": "3", "Tags": [ "python", "go" ], "Title": "code review for count then sort problems (go lang)" }
9146
accepted_answer
[ { "body": "<p>In Go, I would write:</p>\n\n<pre><code>package main\n\nimport (\n \"bufio\"\n \"fmt\"\n \"io\"\n \"os\"\n \"sort\"\n)\n\ntype Key string\ntype Count int\n\ntype Elem struct {\n Key\n Count\n}\n\ntype Elems []*Elem\n\nfunc (s Elems) Len() int {\n return len(s)\n}\n\nfunc (s Elems) Swap(i, j int) {\n s[i], s[j] = s[j], s[i]\n}\n\ntype ByReverseCount struct{ Elems }\n\nfunc (s ByReverseCount) Less(i, j int) bool {\n return s.Elems[j].Count &lt; s.Elems[i].Count\n}\n\nfunc main() {\n m := make(map[Key]Count)\n fi, err := os.Open(\"keys.txt\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer fi.Close()\n r := bufio.NewReader(fi)\n for {\n line, err := r.ReadString('\\n')\n if err != nil {\n if err == io.EOF &amp;&amp; len(line) == 0 {\n break\n }\n fmt.Println(err)\n return\n }\n key := line[:len(line)-1]\n m[Key(key)] += 1\n }\n fi.Close()\n\n e := make(Elems, 0, len(m))\n for k, c := range m {\n e = append(e, &amp;Elem{k, c})\n }\n sort.Sort(ByReverseCount{e})\n\n fo, err := os.Create(\"counts.txt\")\n if err != nil {\n fmt.Println(err)\n return\n }\n defer fo.Close()\n for _, e := range e {\n line := fmt.Sprintf(\"%s: %d\\n\", e.Key, e.Count)\n fo.WriteString(line)\n }\n}\n</code></pre>\n\n<p>Input (<code>keys.txt</code>):</p>\n\n<pre><code>apple\nbanana\norange\napple\nbanana\napple\n</code></pre>\n\n<p>Output (<code>counts.txt</code>):</p>\n\n<pre><code>apple: 3\nbanana: 2\norange: 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T17:44:03.120", "Id": "12396", "ParentId": "9146", "Score": "4" } } ]
<p>This is a script I have written to calculate the population standard deviation. I feel that this can be simplified and also be made more pythonic. </p> <pre><code>from math import sqrt def mean(lst): """calculates mean""" sum = 0 for i in range(len(lst)): sum += lst[i] return (sum / len(lst)) def stddev(lst): """calculates standard deviation""" sum = 0 mn = mean(lst) for i in range(len(lst)): sum += pow((lst[i]-mn),2) return sqrt(sum/len(lst)-1) numbers = [120,112,131,211,312,90] print stddev(numbers) </code></pre>
[]
{ "AcceptedAnswerId": "9224", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T11:03:27.313", "Id": "9222", "Score": "10", "Tags": [ "python", "statistics" ], "Title": "Calculating population standard deviation" }
9222
accepted_answer
[ { "body": "<p>The easiest way to make <code>mean()</code> more pythonic is to use the <code>sum()</code> built-in function.</p>\n\n<pre><code>def mean(lst):\n return sum(lst) / len(lst)\n</code></pre>\n\n<p>Concerning your loops on lists, you don't need to use <code>range()</code>. This is enough:</p>\n\n<pre><code>for e in lst:\n sum += e\n</code></pre>\n\n<p>Other comments:</p>\n\n<ul>\n<li>You don't need parentheses around the return value (check out <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> when you have a doubt about this).</li>\n<li>Your docstrings are useless: it's obvious from the name that it calculates the mean. At least make them more informative (\"returns the mean of lst\"). </li>\n<li>Why do you use \"-1\" in the return for stddev? Is that a bug?</li>\n<li>You are computing the standard deviation using the variance: call that \"variance\", not sum!</li>\n<li>You should type pow(e-mn,2), not pow((e-mn),2). Using parentheses inside a function call could make the reader think he's reading a tuple (eg. pow((e,mn),2) is valid syntax)</li>\n<li>You shouldn't use pow() anyway, ** is enough.</li>\n</ul>\n\n<p>This would give:</p>\n\n<pre><code>def stddev(lst):\n \"\"\"returns the standard deviation of lst\"\"\"\n variance = 0\n mn = mean(lst)\n for e in lst:\n variance += (e-mn)**2\n variance /= len(lst)\n\n return sqrt(variance)\n</code></pre>\n\n<p>It's still way too verbose! Since we're handling lists, why not using list comprehensions?</p>\n\n<pre><code>def stddev(lst):\n \"\"\"returns the standard deviation of lst\"\"\"\n mn = mean(lst)\n variance = sum([(e-mn)**2 for e in lst]) / len(lst)\n return sqrt(variance)\n</code></pre>\n\n<p>This is not perfect. You could add tests using <a href=\"http://docs.python.org/library/doctest.html\" rel=\"nofollow noreferrer\">doctest</a>. Obviously, you should not code those functions yourself, except in a small project. Consider using Numpy for a bigger project.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-22T08:23:14.387", "Id": "14515", "Score": "0", "body": "Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-30T20:09:27.300", "Id": "214384", "Score": "0", "body": "@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T16:41:52.520", "Id": "267801", "Score": "0", "body": "Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T19:19:50.133", "Id": "267841", "Score": "0", "body": "@CodyA.Ray Your Rev 2 corrected the result, but it was not the [right](https://en.wikipedia.org/wiki/Variance#Discrete_random_variable) fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T22:09:11.203", "Id": "267867", "Score": "0", "body": "@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the \"return\" line. But the equation seems correct for non-sampled std dev: http://libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/page_19.htm" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T22:13:54.703", "Id": "267868", "Score": "0", "body": "@CodyA.Ray See Rev 3. By [definition](https://en.wikipedia.org/wiki/Variance), \"variance\" is the expected squared deviation from the mean. It is therefore important to put the division in the right place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T14:53:10.330", "Id": "425972", "Score": "0", "body": "@Quentin Pradet the -1 is a compensation factor to deal with outliers. To see the difference between stdev on sample space vs population: https://statistics.laerd.com/statistical-guides/measures-of-spread-standard-deviation.php" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-21T13:01:11.207", "Id": "9224", "ParentId": "9222", "Score": "14" } } ]
<p>I've been learning Python and in order to put my skills to the test, I created a simple program that returns the sum of all of the multiples of number <code>num</code> up to 1000.</p> <pre><code>def get_multiple_sum(num): sum = 0 i = 0 for i in range(0, 1001): if i % num == 0: sum += i else: continue return sum </code></pre> <p>Is this the fastest way to do this? I'm always looking for ways to make my code more efficient.</p>
[]
{ "AcceptedAnswerId": "9348", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T23:12:09.153", "Id": "9347", "Score": "1", "Tags": [ "python", "algorithm", "performance" ], "Title": "Returning the sum of all multiples of a number up to 1000" }
9347
accepted_answer
[ { "body": "<p><code>range</code> takes an optional third argument, which is the step size for the sequence. For example:</p>\n\n<pre><code>range(0, 10, 3) # Returns [0, 3, 6, 9]\n</code></pre>\n\n<p>Python also has a built-in <code>sum</code> function that adds up all the numbers in an array, so you could refactor your code to look like this:</p>\n\n<pre><code>def get_multiple_sum(num):\n return sum(range(0, 1000, num))\n</code></pre>\n\n<p>Performance-wise, this should be much faster, as it doesn't perform 1000 remainder operations and uses a library function which may be optimized by the interpreter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T01:43:59.383", "Id": "14725", "Score": "1", "body": "I think for the correct answer, that `1` should be `0`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T01:17:27.963", "Id": "9348", "ParentId": "9347", "Score": "4" } } ]
<p>My disgusting list comprehension in the <code>return</code> statement is quite a headful.</p> <pre><code>"""Hopefully this function will save you the trip to oocalc/excel. """ def rangeth(start, stop=None, skip=1): """rangeth([start,] stop[, skip]) returns a list of strings as places in a list (1st, 2nd, etc) &gt;&gt;&gt; rangeth(4) ['0th', '1st', '2nd', '3rd'] """ if stop is None: stop, start = start, 0 places = {'1':'st', '2':'nd', '3':'rd'} return ["{}{}".format(i, places.get(i[-1], 'th')) \ if i[-2:] not in ['11', '12', '13'] else "{}{}".format(i, 'th') \ for i in map(str, range(start, stop, skip))] </code></pre> <p>Also, can someone explain to me how <code>range</code> accepts it's parameters? I have my ugly little boilerplate here that I wish didn't exist. I can't find the source for range, as I gave up after thinking it's probably some header file in <code>include</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T17:55:56.660", "Id": "14775", "Score": "0", "body": "Range - http://docs.python.org/library/functions.html#range. Which version of Python are you using? I'm a novice at python, but one thing I know is that `yield` (http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained) would allow using loops which would most likely make this code much more readable (but maybe not as efficient, I don't know)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T18:21:03.193", "Id": "14776", "Score": "0", "body": "This won't work `version <= 2.6` due to the `.format()` function. Also, your link to the doc, though appreciated, isn't what I was after. If you look at the calltip in IDLE for range, there are no default values given. My function posts `rangeth(start, stop=None...`, which I don't like." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T18:29:23.057", "Id": "14777", "Score": "0", "body": "Aha! [I found what I was looking for](http://stackoverflow.com/questions/6644537/how-does-the-python-range-function-have-a-default-parameter-before-the-actual-on)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-25T03:36:14.150", "Id": "14813", "Score": "0", "body": "I think your new version fails for 121." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T17:20:46.370", "Id": "15402", "Score": "1", "body": "There is a module: `inflect` http://pypi.python.org/pypi/inflect/0.2.1 It has an ordinal-function which may be an alternate solution! ;-)" } ]
{ "AcceptedAnswerId": "9382", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T17:04:49.817", "Id": "9375", "Score": "1", "Tags": [ "python" ], "Title": "Range of ordinal numbers" }
9375
accepted_answer
[ { "body": "<p>Firstly, I'd suggest not duplicating the overloading logic of range. Instead:</p>\n\n<pre><code>def rangeth(*args):\n print range(*args)\n</code></pre>\n\n<p>Just take your arguments and pass them onto to range. </p>\n\n<p>Secondly, I'd write a function that takes a single number and produces the \"th\"ified version.</p>\n\n<pre><code>def as_th(number):\n number = str(number)\n if number[-2:] in ['11','12','13]:\n return \"{}{}\".format(number, 'th')\n else:\n return \"{}{}\".format(number, places.get(number[-1], 'th'))\n</code></pre>\n\n<p>I think that makes it easier to follow.</p>\n\n<p>Then have you rangeth function be:</p>\n\n<pre><code>def rangeth(*args):\n return map(as_th, range(*args))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-25T01:09:35.247", "Id": "14810", "Score": "0", "body": "I didn't like returning the `map` object. I just used `return [ nth(x) for x in range(*args) ]`. But, +1 for producing the stand-alone `nth(n)` function, which is nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-25T01:20:17.387", "Id": "14811", "Score": "0", "body": "Follow up: didn't realize that Python 3k returns [map objects](http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-1), which is why I wasn't getting a list back." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T18:52:50.983", "Id": "9382", "ParentId": "9375", "Score": "3" } } ]
<p>I have this code:</p> <pre><code> lengths = [] lengths.append(len(self.download_links)) lengths.append(len(self.case_names)) lengths.append(len(self.case_dates)) lengths.append(len(self.docket_numbers)) lengths.append(len(self.neutral_citations)) lengths.append(len(self.precedential_statuses)) </code></pre> <p>Unfortunately, any of those object properties can be <code>None</code>, so I need to check each with either an <code>if not None</code> block or a <code>try/except</code> block. Checking each individually will blow up the size and conciseness of the code. </p> <p>I assume there must be a better way for this kind of pattern, right?</p>
[]
{ "AcceptedAnswerId": "9383", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T18:21:34.580", "Id": "9377", "Score": "4", "Tags": [ "python" ], "Title": "Better way to do multiple try/except in Python" }
9377
accepted_answer
[ { "body": "<p>Firstly, consider whether these shouldn't be <code>None</code>, but instead should be empty lists. Most of the time <code>None</code> is better replaced by something else like an empty list.</p>\n\n<p>If that's not an option, you can use a list:</p>\n\n<pre><code>for item in [self.download_links, self.case_name...]:\n if item is not None:\n length.append( len(item) )\n</code></pre>\n\n<p>or a function</p>\n\n<pre><code>def add_length(obj):\n if obj is not None:\n lengths.append(len(obj))\n\nadd_length(self.download_links)\nadd_length(self.case_name)\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T19:50:32.330", "Id": "14784", "Score": "0", "body": "I think `None` is better semantically in this case than [], but this will do it, and makes sense, thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T12:31:36.507", "Id": "15395", "Score": "0", "body": "@mlissner: If something could be `None` or a `list` I'd say it's a bad design choice." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-24T18:58:41.717", "Id": "9383", "ParentId": "9377", "Score": "6" } } ]
<p>How could I improve the following code that runs a simple linear regression using matrix algebra? I import a .csv file (<a href="https://docs.google.com/open?id=0B0iAUHM7ljQ1dDM3UVJWaGZRZlNoNnFyZ3h1ekpydw" rel="nofollow noreferrer">link here</a>) called 'cdd.ny.csv', and perform the matrix calculations that <a href="http://en.wikipedia.org/wiki/Linear_regression" rel="nofollow noreferrer">solve for the coefficients</a> (intercept and regressor) of Y = XB (i.e., $(X'X)^{-1}X'Y$):</p> <pre><code>import numpy from numpy import * import csv df1 = csv.reader(open('cdd.ny.csv', 'rb'),delimiter=',') tmp = list(df1) b = numpy.array(tmp).astype('string') b1 = b[1:,3:5] b2 = numpy.array(b1).astype('float') nrow = b1.shape[0] intercept = ones( (nrow,1), dtype=int16 ) b3 = empty( (nrow,1), dtype = float ) i = 0 while i &lt; nrow: b3[i,0] = b2[i,0] i = i + 1 X = numpy.concatenate((intercept, b3), axis=1) X = matrix(X) Y = b2[:,1] Y = matrix(Y).T m1 = dot(X.T,X).I m2 = dot(X.T,Y) beta = m1*m2 print beta #[[-7.62101913] # [ 0.5937734 ]] </code></pre> <p>To check my answer:</p> <pre><code>numpy.linalg.lstsq(X,Y) </code></pre>
[]
{ "AcceptedAnswerId": "9435", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-26T00:49:27.857", "Id": "9433", "Score": "1", "Tags": [ "python", "numpy" ], "Title": "Linear Regression and data manipulation" }
9433
accepted_answer
[ { "body": "<pre><code>import numpy\nfrom numpy import *\nimport csv\n\ndf1 = csv.reader(open('cdd.ny.csv', 'rb'),delimiter=',')\ntmp = list(df1)\nb = numpy.array(tmp).astype('string')\nb1 = b[1:,3:5]\nb2 = numpy.array(b1).astype('float')\n</code></pre>\n\n<p>Firstly, I'd avoid all these abbreviated variables. It makes it hard to follow your code. You can also combine the lines a lot more</p>\n\n<pre><code>b2 = numpy.array(list(df1))[1:,3:5].astype('float')\n</code></pre>\n\n<p>That way we avoid creating so many variables. </p>\n\n<pre><code>nrow = b1.shape[0]\nintercept = ones( (nrow,1), dtype=int16 )\n\nb3 = empty( (nrow,1), dtype = float )\n\ni = 0\nwhile i &lt; nrow:\n b3[i,0] = b2[i,0]\n i = i + 1\n</code></pre>\n\n<p>This whole can be replaced by <code>b3 = b2[:,0]</code></p>\n\n<pre><code>X = numpy.concatenate((intercept, b3), axis=1)\nX = matrix(X)\n</code></pre>\n\n<p>If you really want to use matrix, combine these two lines. But really, its probably better to use just array not matrix. </p>\n\n<pre><code>Y = b2[:,1]\nY = matrix(Y).T\n\nm1 = dot(X.T,X).I\nm2 = dot(X.T,Y)\n\nbeta = m1*m2\n\n\n\nprint beta\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-26T17:50:23.483", "Id": "14877", "Score": "0", "body": "Thanks! However, the line `X = numpy.concatenate((intercept, b3), axis=1)` now gives the error \"ValueError: arrays must have same number of dimensions\" -- this is the reason I added the while loop. Any way around this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-26T18:39:46.237", "Id": "14878", "Score": "0", "body": "@baha-kev, use `b3 = b2[:,0].reshape(-1, 1)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-26T19:16:07.183", "Id": "14879", "Score": "0", "body": "Thanks; you mention it's probably better to use arrays - how do you invert an array? The `.I` command only works on matrix objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-26T19:27:45.773", "Id": "14881", "Score": "0", "body": "@baha-kev, use the `numpy.lingalg.inv` function." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-26T03:40:54.993", "Id": "9435", "ParentId": "9433", "Score": "1" } } ]
<p>I use 3 lists to store field name, its value and score. If field name is already added to according list, then I just need to update other 2 lists. If it is not there, then I need to add it. I do the following:</p> <pre><code>user = User.get_by_key_name(user_key_name) if user: field_names = user.field_names field_values = user.field_values field_scores = user.field_scores if field_name in user.field_names: # field_names[field_index] = field_name field_index = user.field_names.index(field_name) field_values[field_index] = field_value field_scores[field_index] = field_score else: field_names.append(field_name) field_values.append(field_value) field_scores.append(field_score) user.field_names = field_names user.field_values = field_values user.field_scores = field_scores user.put() </code></pre> <p>Is it correct approach?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-26T19:14:11.240", "Id": "9448", "Score": "1", "Tags": [ "python", "google-app-engine" ], "Title": "How to verify if value already added to the list and if so, then update the value?" }
9448
max_votes
[ { "body": "<pre><code>user = User.get_by_key_name(user_key_name)\nif user:\n</code></pre>\n\n<p>Python convention is to use <code>user is None</code> when checking against <code>None</code></p>\n\n<pre><code> field_names = user.field_names\n field_values = user.field_values\n field_scores = user.field_scores\n</code></pre>\n\n<p>Why copy these references? It doesn't help you much.</p>\n\n<pre><code> if field_name in user.field_names:\n # field_names[field_index] = field_name\n field_index = user.field_names.index(field_name)\n</code></pre>\n\n<p>Use index to check if field_name is present. That way it doesn't have to search through the lists twice.</p>\n\n<pre><code> field_values[field_index] = field_value\n field_scores[field_index] = field_score\n</code></pre>\n\n<p>If possible, avoid maintaing parrallel lists. In this case, it looks like maybe you should have a dictionary of strings to tuples.</p>\n\n<pre><code> else:\n field_names.append(field_name)\n field_values.append(field_value)\n field_scores.append(field_score)\n user.field_names = field_names\n user.field_values = field_values \n user.field_scores = field_scores\n</code></pre>\n\n<p>Unless user does something odd, this has no effect. Assignment doesn't copy in python, it just copies the references. </p>\n\n<pre><code> user.put()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T18:41:23.543", "Id": "14947", "Score": "0", "body": "I wanted to mention that in tags, but there is no GAE tag. So, this code is used with GAE.\n\nIf I use `field_index` to identify if value is there and it is not, then I get `ValueError`.\n\nNot sure how to save tuples in GAE datastore - http://stackoverflow.com/questions/9442860/how-to-properly-save-data-in-gae-datastore/9447170#9447170" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T21:49:47.297", "Id": "14962", "Score": "0", "body": "@LA_, you should catch the ValueError and handle it. I don't know GAE, and you may not able to store tuples." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-26T20:27:23.420", "Id": "9452", "ParentId": "9448", "Score": "3" } } ]
<p>I instantiate GtkInfobars a lot in my GTK+ application in order to communicate with the user. There are various types of infobars, depending on the message. Basically, any infobar could be a combination of the 4 different infobar message types and 5 different icons (which are painted on the left side of the infobar).</p> <p>Initially, I would call my custom <code>infobar</code> function like this:</p> <pre><code>infobar("Message. Woo.", type=gtk.MESSAGE_INFO, icon=gtk.STOCK_DIALOG_WARNING, timeout=5) </code></pre> <p>After a while I decided I wanted to simplify all the creation calls... so I modified my <code>infobar</code> function so that I could do this:</p> <pre><code>infobar("Message. Woo.", type=(1,3), timeout=3) </code></pre> <p>I feel like the second way is better and that it's worth the code obfuscation, but I suspect not everyone will agree with me.</p> <pre><code>def infobar(self, msg=None, type=(1,1), timeout=3, vbox=None): """Popup a new auto-hiding InfoBar.""" # List of possible infobar message types msgtypes = [0, gtk.MESSAGE_INFO, # 1 gtk.MESSAGE_QUESTION, # 2 gtk.MESSAGE_WARNING, # 3 gtk.MESSAGE_ERROR] # 4 # List of possible images to show in infobar imgtypes = [gtk.STOCK_APPLY, # 0 gtk.STOCK_DIALOG_INFO, # 1 gtk.STOCK_DIALOG_QUESTION, # 2 gtk.STOCK_DIALOG_WARNING, # 3 gtk.STOCK_DIALOG_ERROR] # 4 ibar = gtk.InfoBar() ibar.set_message_type (msgtypes[type[0]]) if vbox: # If specific vbox requested: assume ibar for filemode, add cancel button ibar.add_button (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) ibar.connect ('response', self.cleanup_filemode) else: # If no specific vbox requested: do normal ibar at the top of message area vbox = self.vbox_ibar ibar.add_button (gtk.STOCK_OK, gtk.RESPONSE_OK) ibar.connect ('response', lambda *args: ibar.destroy()) vbox.pack_end (ibar, False, False) content = ibar.get_content_area() img = gtk.Image() img.set_from_stock (imgtypes[type[1]], gtk.ICON_SIZE_LARGE_TOOLBAR) content.pack_start (img, False, False) img.show () if msg: # If msg was specified, show it, but change the default color label = gtk.Label() label.set_markup ("&lt;span foreground='#2E2E2E'&gt;{}&lt;/span&gt;".format(msg)) content.pack_start (label, False, False) label.show () # FIXME: Why doesn't Esc trigger this close signal? ibar.connect ('close', lambda *args: ibar.destroy()) ibar.show() if timeout: glib.timeout_add_seconds(timeout, ibar.destroy) return ibar </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T15:33:30.807", "Id": "14927", "Score": "0", "body": "What do you think you've saved by doing this? I.e. to your mind, what's the purpose of being concise?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T20:25:34.127", "Id": "14956", "Score": "0", "body": "@WinstonEwert: Hello again. Well, I call this function a lot.. with multiline messages containing custom .format() substitution and all combinations of the 5 icons, 4 message types, and various timeouts. It just makes the code much simpler-looking, not to mention makes it easier to stick to Pythonic rules of line-width. But seeing the reaction from you and the one answerer..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T21:47:38.503", "Id": "14961", "Score": "0", "body": "@ryan, I think you are seeing a valid problem but I'm not sure you've solved it in the best way. Can you share more example of calling the function that show how its giving you trouble?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T22:42:31.837", "Id": "14963", "Score": "0", "body": "@Winston: You could search for self.infobar on [this page](https://github.com/ryran/pyrite/blob/master/modules/core.py) to see all cases where it's called, but I'm gonna change it. It's not really giving me trouble--I mean.. I guess I saw a problem (and came up with a crazy \"solution\") where there wasn't really a problem." } ]
{ "AcceptedAnswerId": "9502", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T09:25:02.863", "Id": "9471", "Score": "3", "Tags": [ "python", "gtk" ], "Title": "GtkInfobars for a GTK+ application" }
9471
accepted_answer
[ { "body": "<p>I'd move all of those message into an external resource file something like:</p>\n\n<pre><code>&lt;message id=\"file.open.fail\" type=\"warning\" icon=\"error\" delay=\"5\"&gt;\n &lt;b&gt;Error. Could not open file:&lt;i&gt;&lt;tt&gt;&lt;small&gt;{filename}&lt;/small&gt;&lt;/tt&gt;&lt;/i&gt;&lt;/b&gt;\n&lt;/message&gt;\n</code></pre>\n\n<p>Then I'd simply pop the message using:</p>\n\n<pre><code>self.infobar('file.open.fail', filename = filename)\n</code></pre>\n\n<p>That should cleanup the calls to infobar, and make it easier to do things like provide strings for a different language. </p>\n\n<p>EDIT:</p>\n\n<p>Quick hack of an implementation</p>\n\n<pre><code>from xml.etree.ElementTree import XML, tostring\n\n# of course, you'd want to load this from an external file\nmessage_file = XML(\"\"\"\n&lt;messages&gt;\n &lt;message id=\"file.open.fail\" type=\"warning\" icon=\"error\" delay=\"5\"&gt;\n &lt;b&gt;Error. Could not open file:&lt;i&gt;&lt;tt&gt;&lt;small&gt;{filename}&lt;/small&gt;&lt;/tt&gt;&lt;/i&gt;&lt;/b&gt;\n &lt;/message&gt;\n &lt;message id=\"file.open.good\" type=\"warning\" icon=\"error\" delay=\"5\"&gt;\n &lt;b&gt;File opened!&lt;/b&gt;\n &lt;/message&gt;\n&lt;/messages&gt;\n\"\"\")\n\nmessages = {}\nfor message in message_file.findall(\"message\"):\n messages[message.attrib['id']] = message\n\ndef message(id, **kwargs):\n message_detail = messages[id]\n text = ''.join( tostring(node) for node in message_detail)\n return text.strip().format(**kwargs)\n\nprint message('file.open.fail', filename = 'file.txt')\nprint message('file.open.good', filename = 'file.txt')\n</code></pre>\n\n<p>Doesn't try to handle type/icon/delay. You'll probably also want to consider how you want to do whitespace.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T04:09:42.217", "Id": "14975", "Score": "0", "body": "Ohhh I like it. At some point I had that idea -- to move all the messages into a single place, but scrapped it because of (1) inability to envision an elegant way to deal with the variable stuff like filenames and (2) the feeling that there were just too many messages. Hmmmm.... External file you say? XML too? Hmm. Innnteresting. Never would have thought of that. Already just went through a intro-tutorial on xml.etree.ElementTree (tho couldn't get it to import--weird), but before I reeally start trying to figure out implementation: why is xml the best solution for storage of this stuff?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T04:24:21.140", "Id": "14976", "Score": "0", "body": "@ryan, I went for xml because the message content was already xml." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T14:19:14.097", "Id": "14991", "Score": "0", "body": "Agh. So I've read through the [ElementTree page](http://docs.python.org/library/xml.etree.elementtree.html) in the docs, have gone through a few minimal tutorials, and have even gone through a few questions here and on stackoverflow (even one where you answered), but I'm having trouble doing the most basic thing--finding a message by id and returning the text. Can you point me to any resources Winston?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T17:26:13.980", "Id": "15009", "Score": "0", "body": "@ryan, your best bet is probably to load all of the messages on startup and then store them in a dictionary by the id. To load a tag by the id directly from the xml, you'd need something like XPath, but thats probably not in your base python install." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T20:36:16.257", "Id": "15019", "Score": "0", "body": "Hmm. Well I like the idea, but honestly this just leaves me back at square one -- I thought of this weeks ago but dismissed it because I couldn't see how to implement it. And I still don't. Oh well. In any case, thanks again for your time Winston." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T20:59:14.367", "Id": "15020", "Score": "0", "body": "**Nested dictionaries.** ..... Well that's a start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T21:29:06.777", "Id": "15022", "Score": "0", "body": "@ryran, (I've been mispelling your name all this time?) Anyways, I've edited in a quick of hack of an implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T22:28:32.533", "Id": "15027", "Score": "0", "body": "HEY! So I spoke to soon. I put together something. Edited OP. I have NO IDEA how this will rate in terms of Pythonic..ness, but it seems much simpler (to me) than going the full xml route. What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T22:40:20.297", "Id": "15030", "Score": "0", "body": "@ryran, that's actually a pretty good approach. I've added some comments to my answer on your new version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T00:43:27.157", "Id": "15035", "Score": "0", "body": "Awesome! Glad to know the solution I came up with wasn't just totally crazy. Thanks for giving it a look. I've been creating in a vacuum since I started with Python two months ago, so I _really_ appreciate the feedback, Mr. Ewert." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T01:17:51.053", "Id": "9502", "ParentId": "9471", "Score": "4" } } ]
<p>I have created a simple palindrome function that works only on single words. It is working as intended, but I feel that it definitely needs improvement.</p> <pre><code>def is_palindrome(w): if not isinstance(w, str): return "ERROR: input is not a string." elif len(w) &gt; 2: if w[0] == w[-1]: while len(w) &gt; 2: w = w[1:-1] is_palindrome(w) if len(w) == 1: return True else: return False else: return "ERROR: input contains two or less characters." print is_palindrome('aibohphobia') print is_palindrome('definitely') </code></pre> <p>Can you please review my function and post your suggestions?</p> <p>Also, is it better to do <code>w[:] = w[1:-1]</code> instead of <code>w = w[1:-1]</code>?</p>
[]
{ "AcceptedAnswerId": "9526", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T17:34:52.233", "Id": "9515", "Score": "1", "Tags": [ "python", "palindrome" ], "Title": "Simple palindrome function for single words" }
9515
accepted_answer
[ { "body": "<p>Firstly, your testing is insufficient. This code thinks that \"defad\" is a palindrome and that \"deed\" is not. You algorithm is completely broken.</p>\n\n<pre><code>def is_palindrome(w):\n\n if not isinstance(w, str):\n return \"ERROR: input is not a string.\"\n</code></pre>\n\n<p>Don't check types. Just treat it like a string, and trust the caller to pass the right kind of object. Also don't return strings as errors, throw exceptions.</p>\n\n<pre><code> elif len(w) &gt; 2:\n if w[0] == w[-1]:\n while len(w) &gt; 2:\n w = w[1:-1]\n is_palindrome(w)\n</code></pre>\n\n<p>You call the function but you don't do anything with the result. </p>\n\n<pre><code> if len(w) == 1:\n return True\n\n else:\n return False\n</code></pre>\n\n<p>This is equivalent to: <code>return len(w) == 1</code> </p>\n\n<pre><code> else:\n return \"ERROR: input contains two or less characters.\"\n</code></pre>\n\n<p>Why can't palindromes be zero or one characters? Also, throw exceptions, don't return strings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-28T22:29:37.550", "Id": "9526", "ParentId": "9515", "Score": "4" } } ]
<p>I have spent all night whipping up this recipe. It's my first Python decorator. I feel like I have a full understanding of how decorators work now and I think I came up with a good object-oriented algorithm to automatically provide memoization. Please let me know what you think.</p> <p>I made a few quick changes after pasting it in here so please let me know if my changes broke something (don't have an interpreter on hand).</p> <pre><code>"""This provides a way of automatically memoizing a function. Using this eliminates the need for extra code. Below is an example of how it would be used on a recursive Fibonacci sequence function: def fib(n): if n in (0, 1): return n return fib(n - 1) + fib(n - 2) fib = memoize(fib) That's all there is to it. That is nearly identical to the following: _memos = {} def fib(n): if n in _memos: return _memos[n] if n in (0, 1): _memos[n] = n return _memos[n] _memos[n] = fib(n - 1) + fib(n - 2) return _memos[n] The above is much more difficult to read than the first method. To make things even simpler, one can use the memoize function as a decorator like so: @memoize def fib(n): if n in (0, 1): return n return fib(n - 1) + fib(n - 2) Both the first and third solutions are completely identical. However, the latter is recommended due to its elegance. Also, note that functions using keywords will purposely not work. This is because this memoization algorithm does not store keywords with the memos as it HEAVILY increases the CPU load. If you still want this functionality, please implement it at your own risk.""" class memoize: """Gives the class it's core functionality.""" def __call__(self, *args): if args not in self._memos: self._memos[args] = self._function(*args) return self._memos[args] def __init__(self, function): self._memos = {} self._function = function # Please don't ask me to implement a get_memo(*args) function. """Indicated the existence of a particular memo given specific arguments.""" def has_memo(self, *args): return args in self._memos """Returns a dictionary of all the memos.""" @property def memos(self): return self._memos.copy() """Remove a particular memo given specific arguments. This is particularly useful if the particular memo is no longer correct.""" def remove_memo(self, *args): del self._memos[args] """Removes all memos. This is particularly useful if something that affects the output has changed.""" def remove_memos(self): self._memos.clear() """Set a particular memo. This is particularly useful to eliminate double-checking of base cases. Beware, think twice before using this.""" def set_memo(self, args, value): self._memos[args] = value """Set multiple memos. This is particular useful to eliminate double-checking of base cases. Beware, think twice before using this.""" def set_memos(self, map_of_memos): self._memos.update(map_of_memos) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T09:55:50.113", "Id": "15056", "Score": "1", "body": "Why would you need anything else than `__call__` and `__init__`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T17:12:56.470", "Id": "15098", "Score": "0", "body": "Did you read the comments for the `set_memo(self, args, value)` and `set_memos(self, map_of_memos)`? Eliminating particular base cases will usually not make too big of a difference. Also, something that the function uses may update and one may want to remove some or all values to recalculate them. I can't think of examples where one would want to do this, but I thought I'd throw it in there for the heck of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T02:02:38.527", "Id": "15313", "Score": "1", "body": "`__contains__` instead of `has_memo` ? Then you can ask `10 in fib`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T20:46:37.270", "Id": "15355", "Score": "0", "body": "@AdrianPanasiuk, ah, didn't think about that. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-27T18:23:51.157", "Id": "427530", "Score": "0", "body": "is it like lru cash, cause its in standart python there" } ]
{ "AcceptedAnswerId": "9589", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T07:54:20.873", "Id": "9538", "Score": "2", "Tags": [ "python", "python-3.x", "memoization" ], "Title": "Python memoization decorator" }
9538
accepted_answer
[ { "body": "<p>The first thing that came to mind looking at your code was: <em>style</em>.</p>\n\n<p>There's a particular reason for placing your doc-strings above the functions instead of below? The way you're doing it will show <code>None</code> in the <code>__doc__</code> attribute.</p>\n\n<p>IMHO Some of that strings are not even doc-strings:</p>\n\n<blockquote>\n<pre><code>def __call__(self, *args)\n \"\"\"Gives the class its core functionality.\"\"\"\n # ...\n</code></pre>\n</blockquote>\n\n<p>It doesn't really say much. Keep also in mind that comments are for the programmers, docstrings for the users. </p>\n\n<ul>\n<li><a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> tells you all about this style guide,</li>\n<li>and <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">PEP257</a> is specifically about Docstring Conventions.</li>\n</ul>\n\n<p>Also I didn't like very much that you put the <code>__call__</code> method before <code>__init__</code>, but I don't know if that is just me, or there's some convention about that.</p>\n\n<p>Cleared this, I'm failing in founding the point in all your methods that you've written beside <code>__init__</code> and <code>__call__</code>. What's their use? Where your code is using them?<br>\nIf you need something write the code for it, otherwise don't. Or you'll be writing for something that you don't need and that will probably not match your hypothetical requires of tomorrow.</p>\n\n<p>I get that you were probably doing an exercise to learn about decorators, but when implementing something, don't ever write code just <em>for the heck of it</em>.</p>\n\n<hr>\n\n<p>Let's take a deeper look at your non-doc strings, like this one:</p>\n\n<blockquote>\n<pre><code>\"\"\"Removes all memos. This is particularly useful if something that affects the output has changed.\"\"\"\ndef remove_memos(self):\n self._memos.clear()\n</code></pre>\n</blockquote>\n\n<p>That should probably just be:</p>\n\n<pre><code>def remove_memos(self):\n \"\"\"Removes all memos.\"\"\"\n self._memos.clear()\n</code></pre>\n\n<p>And nothing more. What on earth does <em>\"This is particularly useful if something that affects the output has changed.\"</em> this means? \"something that affects the output has changed\"? It's all very strange and confusing. Also, <strong>how will your decorator know that \"something that affects the output has changed\"?</strong> </p>\n\n<p>There's nothing in here:</p>\n\n<blockquote>\n<pre><code>def __call__(self, *args):\n if args not in self._memos:\n self._memos[args] = self._function(*args)\n return self._memos[args]\n</code></pre>\n</blockquote>\n\n<p>that does that or that uses any of the other methods. Also you seem to not being able to provide a scenario where they might be used (and even if you could there's still no way to use them).</p>\n\n<p>My point is that all those additional methods are useless, probably it wasn't write them if you learned some Python, but that is as far as their use is gone.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T21:12:14.757", "Id": "15188", "Score": "0", "body": "I haven't really used docstrings that much so thank you for the tips. I sorted the methods in alphabetical order. (It's easier to find a method that way). But that really doesn't matter at all. Perhaps I was gold plating but I can see the extra methods' purposes so I went ahead and implemented them. They can be useful in some scenarios. There's no requirement to use them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T12:35:49.713", "Id": "15219", "Score": "0", "body": "@TylerCrompton: *(1)* Don't applay the alphabetical order to \\_\\_init__, because others are expecting to find it at the beginning if it's implemented. (Take a look into the python standard library code :) I can't also stress this enough: your coding style is important if you want others to read/use/share your code. *(2)* Which scenario? If you can't provide one they're useless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T08:20:23.570", "Id": "15283", "Score": "0", "body": "In regards to number 2, have a look at the docstrings. Surely those will provide enough information as to what scenarios that they would be good for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T22:08:43.090", "Id": "15296", "Score": "0", "body": "@TylerCrompton: No offense, but I've already read your non-doc strings, yet I don't see how those methods could be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-04T20:45:55.057", "Id": "15354", "Score": "0", "body": "Perhaps you misunderstand. I do understand the my docstrings are wrong. I get that. The \"something that affects the output has changed\" phrase means if one is accessing global variables and that variable changes and by doing so affects the output. The decorator isn't supposed to know when it changes. It's the programmers responsibility to detect that. If I want to clear the memos. I would just do `function_name.remove_memos()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T22:01:15.713", "Id": "17526", "Score": "0", "body": "@TylerCrompton: I just stumbled in [YAGNI](http://c2.com/cgi/wiki?YouArentGonnaNeedIt) and thought about this old discussion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-23T05:18:57.663", "Id": "17669", "Score": "0", "body": "While both answers are insightful, they are different. Since you put far more work in your answer, I marked yours as accepted." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T11:47:28.917", "Id": "9589", "ParentId": "9538", "Score": "3" } } ]
<p>For flexing my newly acquired Django &amp; Python muscles, I have set up a mobile content delivery system via Wap Push (Ringtones, wallpapers, etc).</p> <p>The idea is that a keyword comes in from an sms via an URL, let's say the keyword is "LOVE1" and the program should search if this keyboard points to a Ringtone or an Image. For this I have created a parent model class called "Categoria" (Category) and two subclasses "Ringtone" and "Wallpaper". This subclasses have a variable called "archivo" (filename) which points to the actual path of the content.</p> <p>Dynpath is a dynamic URL which has been created to download the content, so it is available only for X amount of time. After that a Celery scheduled task deletes this dynamic URL from the DB.</p> <p>I have a piece which has "code smell" which I would like to have some input from everyone here.</p> <h2>Model</h2> <pre><code>class Contenido(models.Model): nombre = models.CharField(max_length=100) fecha_creacion = models.DateTimeField('fecha creacion') keyword = models.CharField(max_length=100) class Ringtone(Contenido): grupo = models.ManyToManyField(Artista) archivo = models.FileField(upload_to="uploads") def __unicode__(self): return self.nombre class Wallpaper(Contenido): categoria = models.ForeignKey(Categoria) archivo = models.ImageField(upload_to="uploads") def __unicode__(self): return self.nombre class Dynpath(models.Model): created = models.DateField(auto_now=True) url_path = models.CharField(max_length=100) payload = models.ForeignKey(Contenido) sms = models.ForeignKey(SMS) def __unicode__(self): return str(self.url_path) </code></pre> <h2>View</h2> <p>Here is my view which checks that the Dynamic URL exists and here is where the code (which works) gets a little suspicious/ugly:</p> <pre><code> def tempurl(request,hash): p = get_object_or_404(Dynpath, url_path=hash) try: fname = str(p.payload.wallpaper.archivo) except DoesNotExist: fname = str(p.payload.ringtone.archivo) fn = open(fname,'rb') response = HttpResponse(fn.read()) fn.close() file_name = os.path.basename(fname) type, encoding = mimetypes.guess_type(file_name) if type is None: type = 'application/octet-stream' response['Content-Type'] = type response['Content-Disposition'] = ('attachment; filename=%s') % file_name return response </code></pre> <p>I am talking explictitly this snippet:</p> <pre><code> try: fname = str(p.payload.wallpaper.archivo) except DoesNotExist: fname = str(p.payload.ringtone.archivo) </code></pre> <p>I would have loved to do something like:</p> <pre><code>fname = p.payload.archivo </code></pre> <p>But it would not let me do that, from the docs:</p> <p><em>Django will raise a FieldError if you override any model field in any ancestor model.</em></p> <p>I took a look at generics, but could not make it work with them. Any ideas on a better way of doing this?</p>
[]
{ "AcceptedAnswerId": "9570", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T13:24:36.157", "Id": "9555", "Score": "3", "Tags": [ "python", "django" ], "Title": "Mobile content delivery system" }
9555
accepted_answer
[ { "body": "<p>You have 2 models (Ringtone extends Contenido). As I understand you store same <code>nombre</code>, <code>fecha_creacion</code>, <code>keyword</code> in both models and every update/delete/insert operation on the first model must be synchronized with another one. You can avoid this, make foreign key to base model:</p>\n\n<pre><code>class Contenido(models.Model):\n nombre = models.CharField(max_length=100)\n fecha_creacion = models.DateTimeField('fecha creacion')\n keyword = models.CharField(max_length=100)\n\nclass Ringtone(models.Model):\n contenido = models.ForeignKey(Contenido)\n grupo = models.ManyToManyField(Artista)\n archivo = models.FileField(upload_to=\"uploads\")\n\nclass Wallpaper(models.Model):\n contenido = models.ForeignKey(Contenido) \n categoria = models.ForeignKey(Categoria)\n archivo = models.ImageField(upload_to=\"uploads\")\n</code></pre>\n\n<p>Then in your <strong>Views</strong></p>\n\n<pre><code>def tempurl(request,hash):\n p = get_object_or_404(Dynpath, url_path=hash)\n try:\n obj=Wallpaper.objects.get(contenido_id=p.id)\n except Wallpaper.DoesNotExist:\n try:\n obj=Ringtone.objects.get(contenido_id=p.id)\n except Ringtone.DoesNotExist:\n raise Http404 \n fname = str(obj.archivo)\n\n # use with statement\n with open(fname,'rb') as fn:\n response = HttpResponse(fn.read())\n</code></pre>\n\n<p>Uhh.. Is it still complicated? If you can retrieve content type (ringtone or wallpaper) and save it in Dynpath field, solution will be easier.</p>\n\n<p>P.S. Please write your code in English not Spanish )</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T10:17:53.593", "Id": "15154", "Score": "0", "body": "Thank you for review. I am not quite sure I am getting your point: As the relationship between Ringtone->Contenido is one to one, as is the case also for the relationship between Wallpaper->Contenido. and adding this foreign key would imply a many to one relationship. In other words, one keyword can only correspond to one file (archivo). My question was more about, what happens when I have not only Wallpaper and Ringtones.. lets say I must add a Game category, I would have to keep editing the code in tempurl view. Sorry about the spanish :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T11:36:11.533", "Id": "15167", "Score": "0", "body": "@AlexR Yes, you can use OneToOne relationship instead of OneToMany and it will be more strict and correct. But you inherited Ringtone and Wallpaper from base model Contenido, what is bad. In your case, if you want to add Game category you will have to fix template view. As I have written in the end of my answer, you can add content type to your Dynpath model and then calculate related model class `Model`. Then you will do `obj=Model.objects.get(contenido_id=p.id)` and get filename" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-29T20:30:34.523", "Id": "9570", "ParentId": "9555", "Score": "1" } } ]
<p>I'm working on some code that deals with mangled C++ function names. I'm displaying these to the user, so to help with readability of some of the really long C++ template class/function names, I'm removing some of the template arguments based on how deeply nested the template argument is.</p> <p>The code below works fine, but it seems fairly clunky. It feels like I'm "writing C in any language". I'm wondering if I can improve it, shorten it, and make it more pythonic.</p> <pre><code>def removeTemplateArguments(str, depthToRemove): """ Remove template arguments deeper than depthToRemove so removeTemplateArguments("foo&lt;int&gt;()", 1) gives foo&lt;&gt;() removeTemplateArguments("foo&lt; bar&lt;int&gt; &gt;()", 1) gives foo&lt; &gt;() removeTemplateArguments("foo&lt; bar&lt;int&gt; &gt;()", 2) gives foo&lt; bar&lt;&gt; &gt;()""" if depthToRemove &lt;= 0: return str currDepth = 0 res = "" for c in str: if currDepth &lt; depthToRemove: res += c if c == "&lt;": currDepth += 1 elif c == "&gt;": currDepth -= 1 if currDepth &lt; depthToRemove: res += "&gt;" return res </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-02T17:12:32.953", "Id": "160487", "Score": "2", "body": "This is a C++ comment rather than a Python answer, but, please be aware that attempting to parse C++ template names with hand-written code places you in a state of sin just as much as if you were [considering arithmetical methods of producing random digits](https://en.wikiquote.org/wiki/John_von_Neumann). Consider how your code will handle `bool_< 1<2 >` or `bool_< (1>2) >` or `bool_< 1>= 2 >` (assuming `template<bool X> using bool_ = std::integral_constant<bool,X>` of course), and then consider whether you are *really* helping your users with this code." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T12:53:24.207", "Id": "9592", "Score": "2", "Tags": [ "python" ], "Title": "Removing C++ template arguments from a C++ function name" }
9592
max_votes
[ { "body": "<p>For that kind of parsing <a href=\"http://docs.python.org/py3k/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a> is the right tool.</p>\n<p>With <code>groupby</code>, as I used it down below, every group is either: <code>&lt;</code>,<code>&gt;</code> or an actual piece of code (like <code>foo</code>). So the only thing left to do is to increment/decrement the depth level and decide if the group should be appended or not to the final result list.</p>\n<pre><code>from itertools import groupby\n\ndef remove_arguments(template, depth):\n res = []\n curr_depth = 0\n for k,g in groupby(template, lambda x: x in ['&lt;', '&gt;']):\n text = ''.join(g) # rebuild the group as a string\n if text == '&lt;':\n curr_depth += 1\n\n # it's important to put this part in the middle\n if curr_depth &lt; depth:\n res.append(text)\n elif k and curr_depth == depth: # add the inner &lt;&gt;\n res.append(text)\n\n if text == '&gt;':\n curr_depth -= 1\n\n return ''.join(res) # rebuild the complete string\n</code></pre>\n<p>It's important to put the depth-level check in between the increment and decrement part, because it has to be decided if the <code>&lt;</code>/<code>&gt;</code> are <em>in</em> or <em>out</em> the current depth level.</p>\n<p>Output examples:</p>\n<pre><code>&gt;&gt;&gt; remove_arguments('foo&lt;int&gt;()', 1)\nfoo&lt;&gt;()\n&gt;&gt;&gt; remove_arguments('foo&lt; bar&lt;int&gt; &gt;()', 1)\nfoo&lt;&gt;()\n&gt;&gt;&gt; remove_arguments('foo&lt; bar&lt;int&gt; &gt;()', 2)\nfoo&lt; bar&lt;&gt; &gt;()\n&gt;&gt;&gt; remove_arguments('foo&lt; bar &gt;()', 2)\nfoo&lt; bar &gt;()\n</code></pre>\n<p>Also, a couple of quick style notes:</p>\n<ul>\n<li>Don't use <code>str</code> as variable name or you'll shadow the builitin <a href=\"http://docs.python.org/py3k/library/functions.html#str\" rel=\"nofollow noreferrer\"><code>str</code></a>.</li>\n<li>Don't use <code>CamelCase</code> for functions/variable names (look at <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>).</li>\n</ul>\n<hr />\n<p>Inspired by <em>lvc</em> comment, I've grouped here possible lambdas/functions to be used in <code>groupby</code>:</p>\n<pre><code>groupby(template, lambda x: x in ['&lt;', '&gt;']) # most obvious one\ngroupby(template, lambda x: x in '&lt;&gt;') # equivalent to the one above\ngroupby(template, '&lt;&gt;'.__contains__) # this is ugly ugly\ngroupby(template, '&lt;&gt;'.count) # not obvious, but looks sweet\n</code></pre>\n<hr />\n<h3>Update</h3>\n<p>To handle cases like: <code>foo&lt;bar&lt;int&gt;&gt;()</code>, you'll need a better <code>groupby</code> key function. To be specific, a key function that return the current depth-level for a given charachter.</p>\n<p>Like this one:</p>\n<pre><code>def get_level(ch, level=[0]):\n current = level[0]\n if ch == '&lt;':\n level[0] += 1\n if ch == '&gt;':\n level[0] -= 1\n current = level[0]\n\n return current\n</code></pre>\n<p>That take advantage of the mutable argument <code>level</code> to perform some kind of memoization.</p>\n<p>Observe that <code>remove_arguments</code> will now be more simple:</p>\n<pre><code>def remove_arguments(template, depth):\n res = []\n for k,g in groupby(template, get_level):\n if k &lt; depth:\n res.append(''.join(g))\n return ''.join(res)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T00:26:47.713", "Id": "15196", "Score": "0", "body": "You don't need a list in the lambda - `x in '<>'` does the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T08:12:25.613", "Id": "15207", "Score": "0", "body": "`Template` is actually a class from `string`, we both got that wrong. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T15:53:43.477", "Id": "15237", "Score": "0", "body": "What about something like `foo<bar<int>>`? Its legal in the new standard (and likely to get used inadvertently regardless)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T20:07:53.883", "Id": "15267", "Score": "0", "body": "@WinstonEwert: Thanks for noticing that. I didn't thought/known of that case, it requires a better `groupby` key function to handle it. I've updated my answer :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T15:06:41.907", "Id": "9596", "ParentId": "9592", "Score": "5" } } ]
<p>I try to implement a simple RLE compression algorithm as a learning task. In the first step, i need to split my source list to sequences of repeating and non-repeating elements. I've done it, but code seems to be so ugly. Can I simplify it?</p> <pre><code>src = [1,1,2,3,3,4,2,1,3,3,4,3,3,3,3,3,4,5] from itertools import izip isRepeat = False sequence = [] def out(sequence): if sequence: print sequence def testRepeate(a, b, pr): global isRepeat global sequence if a == b: if isRepeat: sequence.append(pr) else: out(sequence) sequence = [] sequence.append(pr) isRepeat = True else: if isRepeat: sequence.append(pr) out(sequence) sequence = [] isRepeat = False else: sequence.append(pr) for a, b in izip(src[:-1], src[1:]): testRepeate(a, b, a) testRepeate(src[-2], src[-1], src[-1]) out(sequence) </code></pre>
[]
{ "AcceptedAnswerId": "9728", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T18:33:55.590", "Id": "9721", "Score": "3", "Tags": [ "python" ], "Title": "List splitting for RLE compression algorithm" }
9721
accepted_answer
[ { "body": "<p>First of all I must tell you that Python makes astonishing easy to write a <a href=\"http://en.wikipedia.org/wiki/Run-length_encoding\" rel=\"nofollow\">Run-length encoding</a>:</p>\n\n<pre><code>&gt;&gt;&gt; src = [1,1,2,3,3,4,2,1,3,3,4,3,3,3,3,3,4,5]\n&gt;&gt;&gt; from itertools import groupby\n&gt;&gt;&gt;\n&gt;&gt;&gt; [(k, sum(1 for _ in g)) for k,g in groupby(src)]\n[(1, 2), (2, 1), (3, 2), (4, 1), (2, 1), (1, 1), (3, 2), (4, 1), (3, 5), (4, 1), (5, 1)]\n</code></pre>\n\n<p>Take a look at how <a href=\"http://docs.python.org/library/itertools.html#itertools.groupby\" rel=\"nofollow\"><code>itertools.groupby()</code></a> to see how a generator will be a good choice for this kind of task</p>\n\n<hr>\n\n<p>But that doesn't mean that it wasn't a bad idea try to implement it yourself. So let's take a deeper look at your code :)</p>\n\n<p><strong>The best use of <code>global</code> is usually the one that doesn't use <code>global</code> at all</strong></p>\n\n<p>The use of the <code>global</code> keyword among beginners is almost always a sign of trying to program using some other language's mindset. Usually, if a function need to know the value of somthing, pass that something along as an argument.</p>\n\n<p>In your case, what you need, is a function that loops through your list holding the value of <code>isRepeat</code>.</p>\n\n<p>Something like this:</p>\n\n<pre><code>def parse(seq):\n is_repeat = False\n old = None\n for num in seq:\n is_repeat = num == old # will be True or False\n if is_repeat:\n # ...\n</code></pre>\n\n<p>I didn't go too far since, as you may have already noticed, the <code>is_repeat</code> flag is a bit useless now, so we'll get rid of that later.</p>\n\n<p>You may have also noted that I called <code>isReapeat</code> <code>is_repeat</code>, I did that to follow some naming style guide (see <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> for more info).</p>\n\n<p><strong>Cleared this, let's get at your statement:</strong></p>\n\n<blockquote>\n <p>In the first step, I need to split my source list to sequences of repeating and non-repeating elements.</p>\n</blockquote>\n\n<p>Ok, to split a sequence we'll have to parse it item by item, so while we'll be at it why don't already count how many times an item occurs?</p>\n\n<p>The wrong step was to build a <code>testRepeat</code> function, such function should act on 2 items at the time, but that will lose the \"view\" of the whole sequence one item after the other. Well ok, a recursive solution could also be found, but I can't go through all the possible solutions.</p>\n\n<p>So, to do achive our goal one could:</p>\n\n<ul>\n<li>parse the list item by item.</li>\n<li>see if an item is the same as the previous one.</li>\n<li>if it is <code>count += 1</code>.</li>\n<li>else store that item with its count.</li>\n</ul>\n\n<p>This might be the code:</p>\n\n<pre><code>def rle(seq):\n result = []\n old = seq[0]\n count = 1\n for num in seq[1:]:\n if num == old:\n count += 1\n else:\n result.append((old, count)) # appending a tuple\n count = 1 # resetting the counting\n old = num\n result.append((old, count)) # appending the last counting\n return result\n</code></pre>\n\n<p>There could still be room for improvement (also it doesn't handle empty list like <em>hdima</em> noticed), but I just wanted to show an easy example and premature optimization is the root of (most) evil. (Also, there's groupby waiting to be used.)</p>\n\n<p><strong>Notes</strong></p>\n\n<p>It's very common to fall in some of the mistakes you did. Keep trying and you'll get better. Keep also in mind some of the following:</p>\n\n<ul>\n<li>Think hard about the your design.</li>\n<li>Do you really need an <code>out</code> function? Couldn't you just place the code there?</li>\n<li>Do you really want to not print at all, if you get an empty list? I would really like to see what my code is returning, so I wouldn't block its output.</li>\n<li>Don't write cryptic code, write readable one.<br>\nWhat are <code>a</code>, <code>b</code> and <code>pr</code>. A variable name should be something that reflect what it holds.</li>\n<li>The same could be said for <code>sequence</code>, if <code>sequece</code> is the resulting sequence call it <code>result</code> or something like that.</li>\n<li>Whorship <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">The Zen of Python</a> as an almighty guide!</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:15:14.907", "Id": "15408", "Score": "0", "body": "The `rle()` function needs to be fixed. Currently it's always lose the last element and raise `IndexError` for empty `seq`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:53:33.893", "Id": "15413", "Score": "0", "body": "@Nativeborn: Yes `groupby` is the right tool. Knowing the standard library is a must, but I hope you got that the main point was to learn something and improve one's own coding skills :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T20:46:43.443", "Id": "9728", "ParentId": "9721", "Score": "5" } } ]
<p>I try to implement a simple RLE compression algorithm as a learning task. In the first step, i need to split my source list to sequences of repeating and non-repeating elements. I've done it, but code seems to be so ugly. Can I simplify it?</p> <pre><code>src = [1,1,2,3,3,4,2,1,3,3,4,3,3,3,3,3,4,5] from itertools import izip isRepeat = False sequence = [] def out(sequence): if sequence: print sequence def testRepeate(a, b, pr): global isRepeat global sequence if a == b: if isRepeat: sequence.append(pr) else: out(sequence) sequence = [] sequence.append(pr) isRepeat = True else: if isRepeat: sequence.append(pr) out(sequence) sequence = [] isRepeat = False else: sequence.append(pr) for a, b in izip(src[:-1], src[1:]): testRepeate(a, b, a) testRepeate(src[-2], src[-1], src[-1]) out(sequence) </code></pre>
[]
{ "AcceptedAnswerId": "9728", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T18:33:55.590", "Id": "9721", "Score": "3", "Tags": [ "python" ], "Title": "List splitting for RLE compression algorithm" }
9721
accepted_answer
[ { "body": "<p>First of all I must tell you that Python makes astonishing easy to write a <a href=\"http://en.wikipedia.org/wiki/Run-length_encoding\" rel=\"nofollow\">Run-length encoding</a>:</p>\n\n<pre><code>&gt;&gt;&gt; src = [1,1,2,3,3,4,2,1,3,3,4,3,3,3,3,3,4,5]\n&gt;&gt;&gt; from itertools import groupby\n&gt;&gt;&gt;\n&gt;&gt;&gt; [(k, sum(1 for _ in g)) for k,g in groupby(src)]\n[(1, 2), (2, 1), (3, 2), (4, 1), (2, 1), (1, 1), (3, 2), (4, 1), (3, 5), (4, 1), (5, 1)]\n</code></pre>\n\n<p>Take a look at how <a href=\"http://docs.python.org/library/itertools.html#itertools.groupby\" rel=\"nofollow\"><code>itertools.groupby()</code></a> to see how a generator will be a good choice for this kind of task</p>\n\n<hr>\n\n<p>But that doesn't mean that it wasn't a bad idea try to implement it yourself. So let's take a deeper look at your code :)</p>\n\n<p><strong>The best use of <code>global</code> is usually the one that doesn't use <code>global</code> at all</strong></p>\n\n<p>The use of the <code>global</code> keyword among beginners is almost always a sign of trying to program using some other language's mindset. Usually, if a function need to know the value of somthing, pass that something along as an argument.</p>\n\n<p>In your case, what you need, is a function that loops through your list holding the value of <code>isRepeat</code>.</p>\n\n<p>Something like this:</p>\n\n<pre><code>def parse(seq):\n is_repeat = False\n old = None\n for num in seq:\n is_repeat = num == old # will be True or False\n if is_repeat:\n # ...\n</code></pre>\n\n<p>I didn't go too far since, as you may have already noticed, the <code>is_repeat</code> flag is a bit useless now, so we'll get rid of that later.</p>\n\n<p>You may have also noted that I called <code>isReapeat</code> <code>is_repeat</code>, I did that to follow some naming style guide (see <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> for more info).</p>\n\n<p><strong>Cleared this, let's get at your statement:</strong></p>\n\n<blockquote>\n <p>In the first step, I need to split my source list to sequences of repeating and non-repeating elements.</p>\n</blockquote>\n\n<p>Ok, to split a sequence we'll have to parse it item by item, so while we'll be at it why don't already count how many times an item occurs?</p>\n\n<p>The wrong step was to build a <code>testRepeat</code> function, such function should act on 2 items at the time, but that will lose the \"view\" of the whole sequence one item after the other. Well ok, a recursive solution could also be found, but I can't go through all the possible solutions.</p>\n\n<p>So, to do achive our goal one could:</p>\n\n<ul>\n<li>parse the list item by item.</li>\n<li>see if an item is the same as the previous one.</li>\n<li>if it is <code>count += 1</code>.</li>\n<li>else store that item with its count.</li>\n</ul>\n\n<p>This might be the code:</p>\n\n<pre><code>def rle(seq):\n result = []\n old = seq[0]\n count = 1\n for num in seq[1:]:\n if num == old:\n count += 1\n else:\n result.append((old, count)) # appending a tuple\n count = 1 # resetting the counting\n old = num\n result.append((old, count)) # appending the last counting\n return result\n</code></pre>\n\n<p>There could still be room for improvement (also it doesn't handle empty list like <em>hdima</em> noticed), but I just wanted to show an easy example and premature optimization is the root of (most) evil. (Also, there's groupby waiting to be used.)</p>\n\n<p><strong>Notes</strong></p>\n\n<p>It's very common to fall in some of the mistakes you did. Keep trying and you'll get better. Keep also in mind some of the following:</p>\n\n<ul>\n<li>Think hard about the your design.</li>\n<li>Do you really need an <code>out</code> function? Couldn't you just place the code there?</li>\n<li>Do you really want to not print at all, if you get an empty list? I would really like to see what my code is returning, so I wouldn't block its output.</li>\n<li>Don't write cryptic code, write readable one.<br>\nWhat are <code>a</code>, <code>b</code> and <code>pr</code>. A variable name should be something that reflect what it holds.</li>\n<li>The same could be said for <code>sequence</code>, if <code>sequece</code> is the resulting sequence call it <code>result</code> or something like that.</li>\n<li>Whorship <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">The Zen of Python</a> as an almighty guide!</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:15:14.907", "Id": "15408", "Score": "0", "body": "The `rle()` function needs to be fixed. Currently it's always lose the last element and raise `IndexError` for empty `seq`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T21:53:33.893", "Id": "15413", "Score": "0", "body": "@Nativeborn: Yes `groupby` is the right tool. Knowing the standard library is a must, but I hope you got that the main point was to learn something and improve one's own coding skills :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T20:46:43.443", "Id": "9728", "ParentId": "9721", "Score": "5" } } ]
<p>I just started programming in Python this morning, and it is (more or less) my first programming language. I've done a bit of programming before, but never really did much except for "Hello World" in a few languages. I searched around for some Python FizzBuzz solutions, and they all seem significantly more complicated then mine, so I think I must be missing something, even though it works correctly. Could you guys point out any errors I've made, or things I can improve?</p> <pre><code>count = 0 while (count &lt; 101): if (count % 5) == 0 and (count % 3) == 0: print "FizzBuzz" count = count +1 elif (count % 3) == 0: print "Fizz" count = count + 1 elif (count % 5) == 0: print "Buzz" count = count +1 else: print count count = count + 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T09:06:01.113", "Id": "35931", "Score": "3", "body": "Only slightly related to your question but this pages contains a few tricks quite interesting if you are starting to learn Python : http://www.reddit.com/r/Python/comments/19dir2/whats_the_one_code_snippetpython_tricketc_did_you/ . One of them leads to a pretty concise (and quite obscure) solution of the Fizzbuzz problem : `['Fizz'*(not i%3) + 'Buzz'*(not i%5) or i for i in range(1, 100)]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-21T16:45:55.467", "Id": "299827", "Score": "0", "body": "Nice solution! To actually print the items one per line, as most Fizzbuzz questions require, not just show a list of results, this needs to be: `print '\\n'.join(['Fizz'*(not i%3) + 'Buzz'*(not i%5) or str(i) for i in range(1, 101)])`. Also note the 101 - `range(1, 100)` returns 1 to 99." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T14:32:50.613", "Id": "9751", "Score": "21", "Tags": [ "python", "beginner", "fizzbuzz" ], "Title": "Ultra-Beginner Python FizzBuzz ... Am I missing something?" }
9751
max_votes
[ { "body": "<h2>Lose the useless brackets</h2>\n\n<p>This:</p>\n\n<pre><code>while (count &lt; 101):\n</code></pre>\n\n<p>can just be:</p>\n\n<pre><code>while count &lt; 101:\n</code></pre>\n\n<h2>Increment out of the <code>if</code>s</h2>\n\n<p>Wouldn't be easier to do:</p>\n\n<pre><code>count = 0\nwhile count &lt; 101:\n if count % 5 == 0 and count % 3 == 0:\n print \"FizzBuzz\"\n elif count % 3 == 0:\n print \"Fizz\"\n elif count % 5 == 0:\n print \"Buzz\"\n else:\n print count\n\n count = count + 1 # this will get executed every loop\n</code></pre>\n\n<h2>A <code>for</code> loop will be better</h2>\n\n<pre><code>for num in xrange(1,101):\n if num % 5 == 0 and num % 3 == 0:\n print \"FizzBuzz\"\n elif num % 3 == 0:\n print \"Fizz\"\n elif num % 5 == 0:\n print \"Buzz\"\n else:\n print num\n</code></pre>\n\n<p>I've also renamed <code>count</code> to <code>num</code> since it doesn't count much, is just a number between 1 and 100.</p>\n\n<h2>Let's use only one <code>print</code></h2>\n\n<p>Why do 4 different print, when what is really changing is the printed message?</p>\n\n<pre><code>for num in xrange(1,101):\n if num % 5 == 0 and num % 3 == 0:\n msg = \"FizzBuzz\"\n elif num % 3 == 0:\n msg = \"Fizz\"\n elif num % 5 == 0:\n msg = \"Buzz\"\n else:\n msg = str(num)\n print msg\n</code></pre>\n\n<h2>Light bulb!</h2>\n\n<p><code>\"FizzBuzz\"</code> is the same of <code>\"Fizz\" + \"Buzz\"</code>.</p>\n\n<p>Let's try this one:</p>\n\n<pre><code>for num in xrange(1,101):\n msg = ''\n if num % 3 == 0:\n msg += 'Fizz'\n if num % 5 == 0: # no more elif\n msg += 'Buzz'\n if not msg: # check if msg is an empty string\n msg += str(num)\n print msg\n</code></pre>\n\n<p>Copy and paste this last piece of code <a href=\"http://people.csail.mit.edu/pgbovine/python/tutor.html#mode=edit\">here</a> to see what it does. </p>\n\n<p>Python is a very flexible and powerful language, so I'm sure there could be other hundred and one different possible solutions to this problem :)</p>\n\n<h2>Edit: Improve more</h2>\n\n<p>There's still something \"quite not right\" with these lines:</p>\n\n<pre><code>if not msg:\n msg += str(num)\n</code></pre>\n\n<p>IMHO it would be better to do:</p>\n\n<pre><code>for num in xrange(1,101):\n msg = ''\n if num % 3 == 0:\n msg += 'Fizz'\n if num % 5 == 0:\n msg += 'Buzz'\n print msg or num\n</code></pre>\n\n<p>There! Now with:</p>\n\n<pre><code>print msg or num\n</code></pre>\n\n<p>is clear that <code>num</code> is the default value to be printed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:04:04.803", "Id": "15467", "Score": "0", "body": "**Let's use only one print** would work well without converting `num` to a string. It's as if you were already anticipating the need for the conversion on **Light bulb!**? Or maybe it was the purity of keeping `msg` a string?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T18:11:59.177", "Id": "15468", "Score": "2", "body": "@Tshepang: yeah I know, but it would have been more strange to have a `msg` variable that one time is a `str` and another an `int`. Also it isn't a very good practice to have a variable that could have different types. So I'd say that is the **following of the good practices that will lead you towards the light bulb :)** [Edit: Yes, I'd like to think it was number 2.]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T20:04:33.080", "Id": "53404", "Score": "0", "body": "One interesting exercise - what if you want a space between Fizz and Buzz, and no newlines but rather commas. ie `1, 2, fizz, ... 14, fizz buzz, fizz, ...`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-11T00:24:57.590", "Id": "93907", "Score": "1", "body": "You reach the best solution about half way through this post and then start making it cuter and less readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-07T13:44:12.547", "Id": "163295", "Score": "4", "body": "@MikeGraham I disagree. I think the last version is very readable. Honestly I think appending Buzz to Fizz when n is divisible by 3 and 5 is part of the reason it's in the question in the first place, written as it is. The `print msg or num` is very pythonic in terms of \"do this otherwise use the fallback\". If it were another language you might explicitly set the output for msg." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-18T12:21:04.423", "Id": "165120", "Score": "0", "body": "@JordanReiter, the fact that there is a cutesy solution is an important part of fizzbuzz -- people who avoid it have shown good sense. The \"A for loop will be better\" is plainly more readable than the final solution, which unnecessarily is cute and subtle and less plain. If someone didn't know what the code was supposed to do, they would very, very likely understand precisely what it does quicker reading the \"A for loop will be better\" solution than the final solution. Code should be as simple as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-18T16:16:38.083", "Id": "165157", "Score": "2", "body": "We'll just have to agree to disagree. If I were interviewing, I'd immediately follow with: \"I've changed my mind. I want 7 instead of 5, and instead of Fizz I want Fooz\". In the loop solution, you have to rewrite 5 lines of code; in the \"custesy\" solution, you only have to rewrite 2 lines of code. The \"straightforward\" solution includes repeating yourself: you check whether something is divisible by 5 twice and you print \"Fizz\" (on its own or as part of another word) twice. Can we at least agree that the \"Let's use only one print\" is *far* better then calling print numerous times?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-06T15:04:11.887", "Id": "9755", "ParentId": "9751", "Score": "44" } } ]
<p>In a data processing and analysis application I have a dataCleaner class that conducts a series of functions that help me to clean raw time series data. </p> <p>One of the problems I see in my data is that they often include large gaps at the beginning and end. This is due to the occasional corruption of the timestamp, a behaviour that I cannot influence but can lead to arbitrary timings of individual data records. </p> <p>Imagine an hourly dataset covering November 2011. Sometimes one of the timestamps is corrupted and may end up recording a date of January 2011. Since the data are sorted by date this puts a point at the beginning which needs to be removed. It is possible that this corruption can occur more than once in any given dataset. I need to detect and remove these outliers if they exist.</p> <p>So I designed this function to trim off contiguous values at each end of the data if the time gap is considered large. My data arrive into this function in the form of two numpy arrays (timestamps and values) and must be filtered together.</p> <pre><code>@staticmethod def _trimmed_ends(timestamps, values, big_gap = 60*60*24*7): """ Uses timestamps array to identify and trim big gaps at either end of a dataset. The values array is trimmed to match. """ keep = np.ones(len(timestamps), dtype=bool) big_gaps = (np.diff(timestamps) &gt;= big_gap) n = (0, 0) for i in xrange(len(keep)): if big_gaps[i]: keep[i] = False n[0] += 1 else: break for i in xrange(len(keep)): if big_gaps[::-1][i]: keep[::-1][i] = False n[1] += 1 else: break if sum(n) &gt; 0: logging.info("%i points trimmed (%i from beginning, %i from end)" % (sum(n), n[0], n[1])) else: logging.info("No points trimmed") return timestamps[keep], values[keep] </code></pre> <p>Is this a pythonic way to do this? I have been advised that I might want to convert this into an iterator but I'm not sure it that is possible, let alone desirable. As I understand it, I need to attack the array twice, once forwards and once backwards in order to achieve the desired result.</p>
[]
{ "AcceptedAnswerId": "9823", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T15:12:22.633", "Id": "9809", "Score": "0", "Tags": [ "python" ], "Title": "Pythonic data processing? Should I use an iterator?" }
9809
accepted_answer
[ { "body": "<p>Firstly, a loopless solution (not actually tested)</p>\n\n<pre><code>big_gaps = np.diff(timestamps) &gt;= big_gap\n</code></pre>\n\n<p>As you did</p>\n\n<pre><code>front_gaps = np.logical_and.accumulate(big_gaps)\n</code></pre>\n\n<p>This produces an array which is <code>True</code> until the first <code>False</code> in big_gaps. </p>\n\n<pre><code>end_gaps = np.logical_and.accumulate(big_gaps[::-1])[::-1]\n</code></pre>\n\n<p>We do the same thing again, but this time we apply on the reversed array.</p>\n\n<pre><code>big_gaps = np.logical_or(front_gaps, end_gaps)\n</code></pre>\n\n<p>Now that we have arrays for the front and end portions, combine them</p>\n\n<pre><code>n = np.sum(front_gaps), np.sum(end_gaps)\n</code></pre>\n\n<p>Take the sums of the gaps arrays, 1 = <code>True</code>, 0 = <code>False</code> to figure out the values for <code>n</code></p>\n\n<pre><code>keep = np.logical_not(big_gaps)\n</code></pre>\n\n<p>Invert the logic to figure out which ones to keep</p>\n\n<pre><code>return timestamps[keep], values[keep]\n</code></pre>\n\n<p>Produce your actual values</p>\n\n<p>A few comments on pieces of your code</p>\n\n<pre><code>@staticmethod\ndef _trimmed_ends(timestamps, values, big_gap = 60*60*24*7):\n</code></pre>\n\n<p>I'd make a constant: <code>ONE_WEEK = 60*60*24*7</code>, as I think it would make this clearer</p>\n\n<pre><code>big_gaps = (np.diff(timestamps) &gt;= big_gap)\n</code></pre>\n\n<p>You don't need those parens</p>\n\n<pre><code>n = (0, 0)\n</code></pre>\n\n<p>This is a tuple here, but you modify it later. That won't work.</p>\n\n<p>And finally, no you shouldn't use an iterator, for the reasons you mention.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T19:39:59.803", "Id": "15610", "Score": "0", "body": "thanks This is great. From looking at it I think it does the job nicely and without a loop. Now to test it. (I probably should have written a test first and posted that with my code)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T20:54:58.453", "Id": "15616", "Score": "0", "body": "There is a slight problem, the np.diff leads to big_gaps being one element shorter than timestamps. This propagates through and leads to at least one point being trimmed every time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T21:02:31.093", "Id": "15619", "Score": "0", "body": "This works: `front_gaps, end_gaps = np.logical_and.accumulate(np.append(big_gaps, False)), np.logical_and.accumulate(np.append(False, big_gaps)[::-1])[::-1]`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T17:53:05.817", "Id": "9823", "ParentId": "9809", "Score": "2" } } ]
<p>I'm a fairly new programmer (just started yesterday!). I decided to tackle Project Euler #2 today, as I did #1 yesterday without many problems. I came up with what seems to me to be a working solution, but I feel like I did it in an exceedingly ugly way. Could anyone suggest improvements to my code and/or logic?</p> <blockquote> <p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote> <pre><code>fib = 1 fib2 = 2 temp = 0 total = 0 while temp &lt;=4000000: temp = fib2 if temp % 2 == 0: total += temp temp = fib + fib2 fib = fib2 fib2 = temp print total </code></pre> <p>I just sort of used my <code>temp</code> variable as a holding ground for the results, and then juggled some variables around to make it do what I wanted... Seems like quite a mess. But it does result in <code>4613732</code>, which seems to be correct!</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T19:40:36.567", "Id": "9830", "Score": "12", "Tags": [ "python", "beginner", "project-euler", "fibonacci-sequence" ], "Title": "Python Solution for Project Euler #2 (Fibonacci Sums)" }
9830
max_votes
[ { "body": "<p>I would use separately Fibonacci generator</p>\n\n<pre><code>def even_fib(limit):\n a, b = 0, 1\n while a &lt; limit:\n if not a % 2: \n yield a\n a, b = b, a + b\n</code></pre>\n\n<p>And <code>sum</code> function to calculate sum of items</p>\n\n<pre><code>print sum(even_fib(4000000))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:41:18.657", "Id": "15654", "Score": "1", "body": "+1. Aside from the use of a generator, this refactor has two improvements that bear mentioning explicitly. The first is tuple assignment to drop `temp` - another way to achieve the same is: `a = a + b; b = a + b`, but the tuple assignment logic is much more straightforward. The other one is `if not a%2` is, at least arguably, better than comparing against zero." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:23:06.527", "Id": "9849", "ParentId": "9830", "Score": "14" } } ]
<p>I'm a fairly new programmer (just started yesterday!). I decided to tackle Project Euler #2 today, as I did #1 yesterday without many problems. I came up with what seems to me to be a working solution, but I feel like I did it in an exceedingly ugly way. Could anyone suggest improvements to my code and/or logic?</p> <blockquote> <p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote> <pre><code>fib = 1 fib2 = 2 temp = 0 total = 0 while temp &lt;=4000000: temp = fib2 if temp % 2 == 0: total += temp temp = fib + fib2 fib = fib2 fib2 = temp print total </code></pre> <p>I just sort of used my <code>temp</code> variable as a holding ground for the results, and then juggled some variables around to make it do what I wanted... Seems like quite a mess. But it does result in <code>4613732</code>, which seems to be correct!</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T19:40:36.567", "Id": "9830", "Score": "12", "Tags": [ "python", "beginner", "project-euler", "fibonacci-sequence" ], "Title": "Python Solution for Project Euler #2 (Fibonacci Sums)" }
9830
max_votes
[ { "body": "<p>I would use separately Fibonacci generator</p>\n\n<pre><code>def even_fib(limit):\n a, b = 0, 1\n while a &lt; limit:\n if not a % 2: \n yield a\n a, b = b, a + b\n</code></pre>\n\n<p>And <code>sum</code> function to calculate sum of items</p>\n\n<pre><code>print sum(even_fib(4000000))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:41:18.657", "Id": "15654", "Score": "1", "body": "+1. Aside from the use of a generator, this refactor has two improvements that bear mentioning explicitly. The first is tuple assignment to drop `temp` - another way to achieve the same is: `a = a + b; b = a + b`, but the tuple assignment logic is much more straightforward. The other one is `if not a%2` is, at least arguably, better than comparing against zero." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:23:06.527", "Id": "9849", "ParentId": "9830", "Score": "14" } } ]
<p>I'm a fairly new programmer (just started yesterday!). I decided to tackle Project Euler #2 today, as I did #1 yesterday without many problems. I came up with what seems to me to be a working solution, but I feel like I did it in an exceedingly ugly way. Could anyone suggest improvements to my code and/or logic?</p> <blockquote> <p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote> <pre><code>fib = 1 fib2 = 2 temp = 0 total = 0 while temp &lt;=4000000: temp = fib2 if temp % 2 == 0: total += temp temp = fib + fib2 fib = fib2 fib2 = temp print total </code></pre> <p>I just sort of used my <code>temp</code> variable as a holding ground for the results, and then juggled some variables around to make it do what I wanted... Seems like quite a mess. But it does result in <code>4613732</code>, which seems to be correct!</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-08T19:40:36.567", "Id": "9830", "Score": "12", "Tags": [ "python", "beginner", "project-euler", "fibonacci-sequence" ], "Title": "Python Solution for Project Euler #2 (Fibonacci Sums)" }
9830
max_votes
[ { "body": "<p>I would use separately Fibonacci generator</p>\n\n<pre><code>def even_fib(limit):\n a, b = 0, 1\n while a &lt; limit:\n if not a % 2: \n yield a\n a, b = b, a + b\n</code></pre>\n\n<p>And <code>sum</code> function to calculate sum of items</p>\n\n<pre><code>print sum(even_fib(4000000))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:41:18.657", "Id": "15654", "Score": "1", "body": "+1. Aside from the use of a generator, this refactor has two improvements that bear mentioning explicitly. The first is tuple assignment to drop `temp` - another way to achieve the same is: `a = a + b; b = a + b`, but the tuple assignment logic is much more straightforward. The other one is `if not a%2` is, at least arguably, better than comparing against zero." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-09T07:23:06.527", "Id": "9849", "ParentId": "9830", "Score": "14" } } ]
<p>This is a simple Python program I wrote. I hope some one could help me optimize this program. If you found any bad habits, please tell me.</p> <pre><code>#!/usr/bin/python import urllib2 def GetURLs(srcURL=""): if srcURL == "": return -1 Content = urllib2.urlopen(srcURL, None, 6) oneLine = Content.readline() while oneLine: print oneLine oneLine = Content.readline() Content.close() return 0 GetURLs("http://www.baidu.com") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:55:58.290", "Id": "15718", "Score": "1", "body": "For starters, dont start your method name with capital letters.Try getURLS() instead of GetURLs same goes for Content (begins with capital letter). In general class names start with capital letters not method or variable names. And I am not sure what are you trying to do with while online: routine. Try to read this book\nhttp://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670 for best practices in programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:03:21.983", "Id": "15719", "Score": "0", "body": "yes, maybe I should follow your advice.Thx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:04:15.087", "Id": "15720", "Score": "7", "body": "You should really follow PEP 8: http://www.python.org/dev/peps/pep-0008/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:11:42.213", "Id": "15721", "Score": "2", "body": "One piece of 'non-pythonic' code is the guard clause. While often good practice in other languages in python exceptions are light weight and recommended practice. So rather than checking if the url=='' just pass it the urllib2 and deal with the exception using try: except:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T23:23:41.113", "Id": "16220", "Score": "1", "body": "@DavidHall: In all honesty, I wouldn't call guard clauses 'non-pythonic', and furthermore I wouldn't call throwing exceptions as being Pythonic, necessarily. It's more of a matter of preference, one of which has a distinct (but insignificant) performance advantage. Here's the [case for guard clauses](http://blog.mafr.de/2009/06/12/a-case-for-guard-clauses/), although, granted, it does not discuss Python directly. Above all, though, if you're working on an existing project, maintaining consistency with the existing convention should be the number one priority." } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:49:17.887", "Id": "9879", "Score": "8", "Tags": [ "python", "url" ], "Title": "Function for getting URLs" }
9879
max_votes
[ { "body": "<p>You asked for comments on coding style, so here goes:</p>\n\n<ul>\n<li><p>It's <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python style</a> to use CapitalizedNames for classes and lower_case_names for functions, methods and variables.</p></li>\n<li><p>Functions should have docstrings that describe their arguments and what they do.</p></li>\n<li><p>Names starting with \"get\" are normally used for functions that return the value they get. Your function <em>prints</em> the content at the URL, so it would be better to call it something like <code>print_url</code>.</p></li>\n<li><p>The value of 6 for the <code>timeout</code> argument to <a href=\"http://docs.python.org/library/urllib2.html#urllib2.urlopen\" rel=\"nofollow noreferrer\"><code>urlopen</code></a> seems arbitrary. It would be better either to leave this out (the caller can always use <a href=\"http://docs.python.org/library/socket.html#socket.setdefaulttimeout\" rel=\"nofollow noreferrer\"><code>socket.setdefaulttimeout</code></a> if they need to set a timeout), or to allow the caller to pass it as a keyword argument.</p></li>\n<li><p>You can pass the <code>timeout</code> argument as a keyword argument to avoid having to specify <code>None</code> for the <code>data</code> argument.</p></li>\n<li><p>Having a default value for <code>srcURL</code> is pointless, especially since it's an invalid value! Omit this.</p></li>\n<li><p>The return value is useless: it's -1 if the argument was an empty string, or 0 if it wasn't. If the caller needs to know this, they can look at the argument they are about to supply. (Or they can catch the <code>ValueError</code> that <code>urlopen</code> raises if passed an empty string.)</p></li>\n<li><p>The <code>Content</code> object does not get closed if the <code>readline</code> function raises an error. You can ensure that it gets closed by using Python's <code>try: ... finally: ...</code> statement. (Or <a href=\"http://docs.python.org/library/contextlib.html#contextlib.closing\" rel=\"nofollow noreferrer\"><code>contextlib.closing</code></a> if you prefer.)</p></li>\n</ul>\n\n<p>Applying all of these improvements, plus the <a href=\"https://stackoverflow.com/a/9646592/68063\">one suggested by Lev</a>, yields this function:</p>\n\n<pre><code>def print_url(url, timeout=6):\n \"\"\"\n Print the content at the URL `url` (but time out after `timeout` seconds).\n \"\"\"\n content = urllib2.urlopen(url, timeout=timeout)\n try:\n for line in content:\n print line\n finally:\n content.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T14:52:24.847", "Id": "15722", "Score": "0", "body": "Can't you just use a `with`-block to handle closing? I.e. never mind `contextlib.closing`; doesn't the object returned by `urllib2.urlopen` already implement the context-manager protocol?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T15:35:52.800", "Id": "15723", "Score": "0", "body": "@Karl: try it and see!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:32:27.843", "Id": "9881", "ParentId": "9879", "Score": "16" } } ]
<p>This is a simple Python program I wrote. I hope some one could help me optimize this program. If you found any bad habits, please tell me.</p> <pre><code>#!/usr/bin/python import urllib2 def GetURLs(srcURL=""): if srcURL == "": return -1 Content = urllib2.urlopen(srcURL, None, 6) oneLine = Content.readline() while oneLine: print oneLine oneLine = Content.readline() Content.close() return 0 GetURLs("http://www.baidu.com") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:55:58.290", "Id": "15718", "Score": "1", "body": "For starters, dont start your method name with capital letters.Try getURLS() instead of GetURLs same goes for Content (begins with capital letter). In general class names start with capital letters not method or variable names. And I am not sure what are you trying to do with while online: routine. Try to read this book\nhttp://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670 for best practices in programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:03:21.983", "Id": "15719", "Score": "0", "body": "yes, maybe I should follow your advice.Thx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:04:15.087", "Id": "15720", "Score": "7", "body": "You should really follow PEP 8: http://www.python.org/dev/peps/pep-0008/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:11:42.213", "Id": "15721", "Score": "2", "body": "One piece of 'non-pythonic' code is the guard clause. While often good practice in other languages in python exceptions are light weight and recommended practice. So rather than checking if the url=='' just pass it the urllib2 and deal with the exception using try: except:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T23:23:41.113", "Id": "16220", "Score": "1", "body": "@DavidHall: In all honesty, I wouldn't call guard clauses 'non-pythonic', and furthermore I wouldn't call throwing exceptions as being Pythonic, necessarily. It's more of a matter of preference, one of which has a distinct (but insignificant) performance advantage. Here's the [case for guard clauses](http://blog.mafr.de/2009/06/12/a-case-for-guard-clauses/), although, granted, it does not discuss Python directly. Above all, though, if you're working on an existing project, maintaining consistency with the existing convention should be the number one priority." } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:49:17.887", "Id": "9879", "Score": "8", "Tags": [ "python", "url" ], "Title": "Function for getting URLs" }
9879
max_votes
[ { "body": "<p>You asked for comments on coding style, so here goes:</p>\n\n<ul>\n<li><p>It's <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python style</a> to use CapitalizedNames for classes and lower_case_names for functions, methods and variables.</p></li>\n<li><p>Functions should have docstrings that describe their arguments and what they do.</p></li>\n<li><p>Names starting with \"get\" are normally used for functions that return the value they get. Your function <em>prints</em> the content at the URL, so it would be better to call it something like <code>print_url</code>.</p></li>\n<li><p>The value of 6 for the <code>timeout</code> argument to <a href=\"http://docs.python.org/library/urllib2.html#urllib2.urlopen\" rel=\"nofollow noreferrer\"><code>urlopen</code></a> seems arbitrary. It would be better either to leave this out (the caller can always use <a href=\"http://docs.python.org/library/socket.html#socket.setdefaulttimeout\" rel=\"nofollow noreferrer\"><code>socket.setdefaulttimeout</code></a> if they need to set a timeout), or to allow the caller to pass it as a keyword argument.</p></li>\n<li><p>You can pass the <code>timeout</code> argument as a keyword argument to avoid having to specify <code>None</code> for the <code>data</code> argument.</p></li>\n<li><p>Having a default value for <code>srcURL</code> is pointless, especially since it's an invalid value! Omit this.</p></li>\n<li><p>The return value is useless: it's -1 if the argument was an empty string, or 0 if it wasn't. If the caller needs to know this, they can look at the argument they are about to supply. (Or they can catch the <code>ValueError</code> that <code>urlopen</code> raises if passed an empty string.)</p></li>\n<li><p>The <code>Content</code> object does not get closed if the <code>readline</code> function raises an error. You can ensure that it gets closed by using Python's <code>try: ... finally: ...</code> statement. (Or <a href=\"http://docs.python.org/library/contextlib.html#contextlib.closing\" rel=\"nofollow noreferrer\"><code>contextlib.closing</code></a> if you prefer.)</p></li>\n</ul>\n\n<p>Applying all of these improvements, plus the <a href=\"https://stackoverflow.com/a/9646592/68063\">one suggested by Lev</a>, yields this function:</p>\n\n<pre><code>def print_url(url, timeout=6):\n \"\"\"\n Print the content at the URL `url` (but time out after `timeout` seconds).\n \"\"\"\n content = urllib2.urlopen(url, timeout=timeout)\n try:\n for line in content:\n print line\n finally:\n content.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T14:52:24.847", "Id": "15722", "Score": "0", "body": "Can't you just use a `with`-block to handle closing? I.e. never mind `contextlib.closing`; doesn't the object returned by `urllib2.urlopen` already implement the context-manager protocol?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T15:35:52.800", "Id": "15723", "Score": "0", "body": "@Karl: try it and see!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:32:27.843", "Id": "9881", "ParentId": "9879", "Score": "16" } } ]
<p>This is a simple Python program I wrote. I hope some one could help me optimize this program. If you found any bad habits, please tell me.</p> <pre><code>#!/usr/bin/python import urllib2 def GetURLs(srcURL=""): if srcURL == "": return -1 Content = urllib2.urlopen(srcURL, None, 6) oneLine = Content.readline() while oneLine: print oneLine oneLine = Content.readline() Content.close() return 0 GetURLs("http://www.baidu.com") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:55:58.290", "Id": "15718", "Score": "1", "body": "For starters, dont start your method name with capital letters.Try getURLS() instead of GetURLs same goes for Content (begins with capital letter). In general class names start with capital letters not method or variable names. And I am not sure what are you trying to do with while online: routine. Try to read this book\nhttp://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670 for best practices in programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:03:21.983", "Id": "15719", "Score": "0", "body": "yes, maybe I should follow your advice.Thx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:04:15.087", "Id": "15720", "Score": "7", "body": "You should really follow PEP 8: http://www.python.org/dev/peps/pep-0008/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:11:42.213", "Id": "15721", "Score": "2", "body": "One piece of 'non-pythonic' code is the guard clause. While often good practice in other languages in python exceptions are light weight and recommended practice. So rather than checking if the url=='' just pass it the urllib2 and deal with the exception using try: except:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T23:23:41.113", "Id": "16220", "Score": "1", "body": "@DavidHall: In all honesty, I wouldn't call guard clauses 'non-pythonic', and furthermore I wouldn't call throwing exceptions as being Pythonic, necessarily. It's more of a matter of preference, one of which has a distinct (but insignificant) performance advantage. Here's the [case for guard clauses](http://blog.mafr.de/2009/06/12/a-case-for-guard-clauses/), although, granted, it does not discuss Python directly. Above all, though, if you're working on an existing project, maintaining consistency with the existing convention should be the number one priority." } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T12:49:17.887", "Id": "9879", "Score": "8", "Tags": [ "python", "url" ], "Title": "Function for getting URLs" }
9879
max_votes
[ { "body": "<p>You asked for comments on coding style, so here goes:</p>\n\n<ul>\n<li><p>It's <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python style</a> to use CapitalizedNames for classes and lower_case_names for functions, methods and variables.</p></li>\n<li><p>Functions should have docstrings that describe their arguments and what they do.</p></li>\n<li><p>Names starting with \"get\" are normally used for functions that return the value they get. Your function <em>prints</em> the content at the URL, so it would be better to call it something like <code>print_url</code>.</p></li>\n<li><p>The value of 6 for the <code>timeout</code> argument to <a href=\"http://docs.python.org/library/urllib2.html#urllib2.urlopen\" rel=\"nofollow noreferrer\"><code>urlopen</code></a> seems arbitrary. It would be better either to leave this out (the caller can always use <a href=\"http://docs.python.org/library/socket.html#socket.setdefaulttimeout\" rel=\"nofollow noreferrer\"><code>socket.setdefaulttimeout</code></a> if they need to set a timeout), or to allow the caller to pass it as a keyword argument.</p></li>\n<li><p>You can pass the <code>timeout</code> argument as a keyword argument to avoid having to specify <code>None</code> for the <code>data</code> argument.</p></li>\n<li><p>Having a default value for <code>srcURL</code> is pointless, especially since it's an invalid value! Omit this.</p></li>\n<li><p>The return value is useless: it's -1 if the argument was an empty string, or 0 if it wasn't. If the caller needs to know this, they can look at the argument they are about to supply. (Or they can catch the <code>ValueError</code> that <code>urlopen</code> raises if passed an empty string.)</p></li>\n<li><p>The <code>Content</code> object does not get closed if the <code>readline</code> function raises an error. You can ensure that it gets closed by using Python's <code>try: ... finally: ...</code> statement. (Or <a href=\"http://docs.python.org/library/contextlib.html#contextlib.closing\" rel=\"nofollow noreferrer\"><code>contextlib.closing</code></a> if you prefer.)</p></li>\n</ul>\n\n<p>Applying all of these improvements, plus the <a href=\"https://stackoverflow.com/a/9646592/68063\">one suggested by Lev</a>, yields this function:</p>\n\n<pre><code>def print_url(url, timeout=6):\n \"\"\"\n Print the content at the URL `url` (but time out after `timeout` seconds).\n \"\"\"\n content = urllib2.urlopen(url, timeout=timeout)\n try:\n for line in content:\n print line\n finally:\n content.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T14:52:24.847", "Id": "15722", "Score": "0", "body": "Can't you just use a `with`-block to handle closing? I.e. never mind `contextlib.closing`; doesn't the object returned by `urllib2.urlopen` already implement the context-manager protocol?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T15:35:52.800", "Id": "15723", "Score": "0", "body": "@Karl: try it and see!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T13:32:27.843", "Id": "9881", "ParentId": "9879", "Score": "16" } } ]
<p>Just needed a quick way to convert an elementtree element to a dict. I don't care if attributes/elements clash in name, nor namespaces. The XML files are small enough. If an element has multiple children which have the same name, create a list out of them:</p> <pre><code>def elementtree_to_dict(element): d = dict() if hasattr(element, 'text') and element.text is not None: d['text'] = element.text d.update(element.items()) # element's attributes for c in list(element): # element's children if c.tag not in d: d[c.tag] = elementtree_to_dict(c) # an element with the same tag was already in the dict else: # if it's not a list already, convert it to a list and append if not isinstance(d[c.tag], list): d[c.tag] = [d[c.tag], elementtree_to_dict(c)] # append to the list else: d[c.tag].append(elementtree_to_dict(c)) return d </code></pre> <p>Thoughts? I'm particularly un-fond of the <code>not instance</code> part of the last <code>if</code>.</p>
[]
{ "AcceptedAnswerId": "10414", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-28T13:07:28.167", "Id": "10400", "Score": "6", "Tags": [ "python", "xml" ], "Title": "Convert elementtree to dict" }
10400
accepted_answer
[ { "body": "<pre><code>def elementtree_to_dict(element):\n d = dict()\n</code></pre>\n\n<p>I'd avoid the name <code>d</code> its not very helpful</p>\n\n<pre><code> if hasattr(element, 'text') and element.text is not None:\n d['text'] = element.text\n</code></pre>\n\n<p><code>getattr</code> has a third parameter, default. That should allow you to simplify this piece of code a bit</p>\n\n<pre><code> d.update(element.items()) # element's attributes\n\n for c in list(element): # element's children\n</code></pre>\n\n<p>The <code>list</code> does nothing, except waste memory.</p>\n\n<pre><code> if c.tag not in d: \n d[c.tag] = elementtree_to_dict(c)\n # an element with the same tag was already in the dict\n else: \n # if it's not a list already, convert it to a list and append\n if not isinstance(d[c.tag], list): \n d[c.tag] = [d[c.tag], elementtree_to_dict(c)]\n # append to the list\n else: \n d[c.tag].append(elementtree_to_dict(c))\n</code></pre>\n\n<p>Yeah this whole block is a mess. Two notes:</p>\n\n<ol>\n<li>Put everything in lists to begin with, and then take them out at the end</li>\n<li><p>call <code>elementtree_to_dict</code> once</p>\n\n<pre><code>return d\n</code></pre></li>\n</ol>\n\n<p>This whole piece of code looks like a bad idea. </p>\n\n<pre><code>&lt;foo&gt;\n &lt;bar id=\"42\"/&gt;\n&lt;/foo&gt;\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>{\"bar\" : {\"id\": 42}}\n</code></pre>\n\n<p>Whereas</p>\n\n<pre><code>&lt;foo&gt;\n &lt;bar id=\"42\"/&gt;\n &lt;bar id=\"36\"/&gt;\n&lt;/foo&gt;\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>{\"bar\" : [{\"id\" : 42}, {\"id\": 36}]}\n</code></pre>\n\n<p>The XML schema is the same, but the python \"schema\" will be different. It'll be annoying writing code that correctly handles both of these cases.</p>\n\n<p>Having said that, here's my cleanup of your code:</p>\n\n<pre><code>def elementtree_to_dict(element):\n node = dict()\n\n text = getattr(element, 'text', None)\n if text is not None:\n node['text'] = text\n\n node.update(element.items()) # element's attributes\n\n child_nodes = {}\n for child in element: # element's children\n child_nodes.setdefault(child, []).append( elementtree_to_dict(child) )\n\n # convert all single-element lists into non-lists\n for key, value in child_nodes.items():\n if len(value) == 1:\n child_nodes[key] = value[0]\n\n node.update(child_nodes.items())\n\n return node\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T08:08:15.897", "Id": "16642", "Score": "0", "body": "Yep, having stuff which is 0,1+ makes stuff be sometimes lists and sometimes not. Of course this can only be fixed by either having lists always (not nice) or knowing about the XML schema and forcing stuff to be lists even though there's only one (or zero!) elements." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-28T19:16:55.000", "Id": "10414", "ParentId": "10400", "Score": "5" } } ]
<p>I am writing a scraper, using Scrapy, in which I need to populate items with default values at first.</p> <p>Could my method be improved?</p> <pre><code> def sp_offer_page(self, response): item = MallCrawlerItem() for key, value in self.get_default_item_dict().iteritems(): item[key] = value item['is_coupon'] = 1 item['mall'] = 'abc' # some other logic yield item def get_default_item_dict(self): # populate item with Default Values return {'mall': 'null', 'store': 'null', 'bonus': 'null', 'per_action': 0, 'more_than': 0, 'up_to': 0, 'deal_url': 'null', 'category': 'null', 'expiration': 'null', 'discount': 'null', 'is_coupon': 0, 'code': 'null'} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T13:49:01.933", "Id": "97665", "Score": "0", "body": "Item has [default values](http://readthedocs.org/docs/scrapy/en/latest/topics/loaders.html?highlight=item%20loader#declaring-input-and-output-processors). Why don't you use them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-03T07:21:48.310", "Id": "97666", "Score": "0", "body": "i tried default values in item but its not working like \n\ncategory = Field(default='null')" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T11:32:04.417", "Id": "10439", "Score": "3", "Tags": [ "python", "scrapy" ], "Title": "Default initialization of items using Scrapy" }
10439
max_votes
[ { "body": "<p>You can use Field() default values as suggested.</p>\n\n<pre><code>class MalCrawlerItem(Item):\n mall = Field(default='null')\n store = Field(default='null')\n bonus= Field(default='null')\n per_action = Field(default='null')\n more_than = Field(default='null')\n up_to = Field(default='null')\n deal_url = Field(default='null')\n category = Field(default='null')\n expiration = Field(default='null')\n discount = Field(default='null')\n is_coupon = Field(default='null')\n code = Field(default='null')\n</code></pre>\n\n<p>You can also use Item copy in the constructor.</p>\n\n<pre><code>#initialize default item\ndefault = MallCrawlerItem()\ndefault['mall'] ='null'\ndefault['store'] = 'null'\ndefault['bonus'] = 'null'\ndefault['per_action'] = 0\ndefault['more_than'] = 0\ndefault['up_to'] = 0\ndefault['deal_url'] = 'null'\ndefault['category'] = 'null'\ndefault['expiration'] = 'null'\ndefault['discount'] = 'null'\ndefault['is_coupon'] = 0\ndefault['code'] = 'null'\n\n#copy to new instance\nitem = MallCrawlerItem(default)\n</code></pre>\n\n<p>The benefits of this approach are:</p>\n\n<ul>\n<li>constructor copy is the fastest method outside of class definition</li>\n<li>you can create specific default item for your current function. e.g. initializing fixed fields of item before entering a for loop</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-30T05:34:33.810", "Id": "55661", "ParentId": "10439", "Score": "3" } } ]
<p>I've written some class which allows me to derive from it to make objects lazy-instantiated. Do you see notational improvements or maybe even cases where this method might not work (multiple inheritance etc.)? What else could I try?</p> <pre><code>class LazyProxy(object): def __init__(self, cls, *params, **kwargs): self.__dict__["_cls"]=cls self.__dict__["_params"]=params self.__dict__["_kwargs"]=kwargs self.__dict__["_obj"]=None def __getattr__(self, name): if self.__dict__["_obj"] is None: self.__init_obj() return getattr(self.__dict__["_obj"], name) def __setattr__(self, name, value): if self.__dict__["_obj"] is None: self.__init_obj() setattr(self.__dict__["_obj"], name, value) def __init_obj(self): self.__dict__["_obj"]=object.__new__(self.__dict__["_cls"], *self.__dict__["_params"], **self.__dict__["_kwargs"]) self.__dict__["_obj"].__init__(*self.__dict__["_params"], **self.__dict__["_kwargs"]) class LazyInit(object): def __new__(cls, *params, **kwargs): return LazyProxy(cls, *params, **kwargs) class A(LazyInit): # classes meant to be lazy loaded are derived from LazyInit def __init__(self, x): print("Init A") self.x=14+x a=A(1) print("Go") print("15=", a.x) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T11:43:59.207", "Id": "10481", "Score": "3", "Tags": [ "python", "lazy" ], "Title": "Lazy class instantiation in Python" }
10481
max_votes
[ { "body": "<p>Would be cool as a class decorator.</p>\n\n<pre><code>@Lazy\nclass MyFoo:\n ...\n</code></pre>\n\n<p>To me it seems like it would fit nicely as a class decorator because it's independent of what the class is representing. It has more to do with the way the class works internally than it does with the thing that the class embodies.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T15:15:24.893", "Id": "16712", "Score": "0", "body": "Possibly. What would be differences? In particular inheritance? Since I will actually add some class functionality to LazyInit, I decided to go with the above solution to have \"all-in-one\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T13:51:20.260", "Id": "10492", "ParentId": "10481", "Score": "2" } } ]
<p>I use Python dictionaries to count words in a corpus:</p> <p><code>words[a]</code> = number of times I saw <code>a</code> in the corpus.</p> <p>Every time before incrementing a counter (<code>words[a] += 1</code>), I need to check a condition: does the dictionary entry <code>words[a]</code> actually exists?</p> <p>My code:</p> <pre><code> if a in words: words[a] += 1 else: words[a] = 1 </code></pre> <p>It there a way to improve it?</p>
[]
{ "AcceptedAnswerId": "10527", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T12:53:21.213", "Id": "10526", "Score": "4", "Tags": [ "python" ], "Title": "Constantly checking existence of dictionary elements in Python: a better way?" }
10526
accepted_answer
[ { "body": "<p>For Python >= 2.5 you can use <a href=\"http://docs.python.org/library/collections.html#collections.defaultdict\" rel=\"noreferrer\">defaultdict</a> instead of dict:</p>\n\n<pre><code> from collections import defaultdict\n words = defaultdict(int)\n corpus = [\"your\", \"word\", \"corpus\"]\n for a in corpus:\n words[a]+=1\n print words\n</code></pre>\n\n<p>For Python >= 2.7 you can use <a href=\"http://docs.python.org/library/collections.html#collections.Counter\" rel=\"noreferrer\">Counter</a>:</p>\n\n<pre><code>from collections import Counter\ncorpus = [\"your\", \"word\", \"corpus\"]\nwords = Counter(corpus)\nprint words\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T15:30:36.203", "Id": "16747", "Score": "1", "body": "Might be worth pointing out `collections.Counter` as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T16:11:02.893", "Id": "16750", "Score": "0", "body": "@WinstonEwert: excellent suggestion, updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-01T06:49:52.380", "Id": "16767", "Score": "0", "body": "For insanely old versions of Python, there's also the option of `words.setdefault(a, 0) += 1`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-01T17:36:51.930", "Id": "16774", "Score": "0", "body": "For Python < 2.7 you can use this Counter: http://code.activestate.com/recipes/576611/ ." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T12:58:13.870", "Id": "10527", "ParentId": "10526", "Score": "9" } } ]
<p>This code will be brute force specific site using http POST method. </p> <pre><code> def BruteForce(url, username, password): userfile = open(username, "r") userlist = userfile.read() userlist = userlist.split("\n") passfile = open(password, "r") passlist = passfile.read() passlist = passlist.split("\n") for i in userlist: for j in passlist: data = {"username":i, "password": j} data2 = {"username":i, "password": j} data = urllib.urlencode(data) request = urllib2.Request(url, data) response = urllib2.urlopen(request) payload = response.read() isconnect = "True" if(payload.find(isconnect)&gt;=0): print "Found, the password is: " + data2["password"] + " and the username is: " + data2["username"] return else: pass </code></pre> <p>Is this code efficient? How I can improve my code? Should I use multithreading mechanism to speed up my script?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T09:52:12.830", "Id": "16977", "Score": "0", "body": "It's probably a good idea to `close()` your files explicitly." } ]
{ "AcceptedAnswerId": "10537", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T20:18:54.527", "Id": "10536", "Score": "3", "Tags": [ "python", "http", "authentication" ], "Title": "Try every username and password from a list on a website" }
10536
accepted_answer
[ { "body": "<p>First, improving the code:</p>\n\n<ol>\n<li><p>Reading lines from a file is as easy as <code>open(name, 'r').readlines()</code>. No need for three lines where one is enough.</p></li>\n<li><p><code>data</code> and <code>data2</code>, are on the face of it redundant (and are badly named). The redundancy is only resolved because you reuse <code>data</code> – not a good idea. Use proper variable naming and use <em>new</em> variables for a new purpose, don’t reuse variables. </p>\n\n<p>(And in general, choose more relevant names.)</p></li>\n<li><p>If you don’t use the <code>else</code> branch in a conditional, don’t write it.</p></li>\n<li><p>Separation of concerns! This method tries to find a way into a website, <em>not</em> print stuff to the console. Return the result instead. That way, the function can be properly used.</p></li>\n</ol>\n\n<p>This leaves us with:</p>\n\n<pre><code>def BruteForce(url, userlist_file, passlist_file):\n userlist = open(userlist_file, 'r').readlines()\n passlist = open(passlist_file, 'r').readlines()\n\n for username in userlist:\n for password in passlist:\n data = { 'username': username, 'password': password }\n encoded = urllib.urlencode(data)\n request = urllib2.Request(url, encoded)\n response = urllib2.urlopen(request)\n payload = response.read()\n\n isconnect = 'True'\n if(payload.find(isconnect) &gt;= 0):\n return data\n\n return { } # Nothing found\n</code></pre>\n\n<p>Now to your question:</p>\n\n<blockquote>\n <p>Is this code efficient?</p>\n</blockquote>\n\n<p>Not really. The problem isn’t so much the code in itself, it’s more the fact that HTTP requests are generally quite slow, but the most time is spent waiting for data. If you do them sequentially (and you do), most of the script’s running time is spent <em>waiting</em>.</p>\n\n<p>This can be drastically improved by sending several requests concurrently. This doesn’t even need multithreading – you can just open several connections in a loop, and <em>then</em> start reading from them. Even better would be to read asynchronously. Unfortunately, urllib doesn’t support this – but <a href=\"http://asynchttp.sourceforge.net/\" rel=\"nofollow\">other libraries do</a>.</p>\n\n<p>That said, you cannot simply bombard the web server with tons of requests. After all, your script is malicious and you don’t want the web server to notice you. So you need to fly under the radar – send just as many concurrent requests as the server allows without being blocked immediately.</p>\n\n<p>Finding this number is tricky and requires guesswork and a bit of luck. If you are lucky, the server is badly configured and won’t mind lots of connections. If you want to stay on the safe side, stay way low.</p>\n\n<p>I have no idea, nor much interest in, how to engineer such an attack.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T21:36:13.527", "Id": "16756", "Score": "0", "body": "thx! I have learned a lot from your comment!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-04T15:21:46.150", "Id": "16951", "Score": "0", "body": "There is no asynchttp library documentation :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T09:53:59.070", "Id": "16978", "Score": "1", "body": "One minor thing. It's usually a good idea to explicitly close your file objects. OP could do this with a `with` bloc however." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-28T23:44:00.623", "Id": "506534", "Score": "0", "body": "@JoelCornett AttributeError: 'list' object has no attribute 'close'" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T21:22:23.230", "Id": "10537", "ParentId": "10536", "Score": "4" } } ]
<p>I have a function that takes a point, and given its velocity, and acceleration, calculates the time(s) for the point to collide with the line:</p> <pre><code>def ParabolaLineCollision(pos, vel, acc, line): """A pure function that returns all intersections.""" pass </code></pre> <p>I have another function that wants to calculate the smallest intersection time between two entities, where an entity has a velocity/acceleration, and a list of vertices.</p> <p>The algorithm of entity_intersection creates lines for each objects' list of vertices, and then calls ParabolaLineCollision on each point of each object, with each line of the other object. My current algorithm runs slowly, and thus I would like to be able to parallelize the algorithm.</p> <p>My problem is that <code>entity_intersections</code> is a bit hard to read, and I think that there may be some code duplication, which might possibly be eliminated. Here's the algorithm, and </p> <pre><code>class Entity # ... @property def lines(self): """ Get a list of lines that connect self.points. If self.enclosed, then the last point will connect the first point. """ # type(self.enclosed) == bool # # I included this, as this may be where there is logic duplication with entity_intersections. # # It's also not very readable. return [(self.points[i-1], self.points[i]) for i in range((1-int(self.enclosed)), len(self.points))] # ... def entity_intersections(entity, other): """ Find all intersection times between two entities. type(entity) == type(other) == Entity """ # Find relative velocity/acceleration a12 = entity.acceleration - other.acceleration a21 = other.acceleration - entity.acceleration v12 = entity.velocity - other.velocity v21 = other.velocity - entity.velocity entity_points, other_points = entity.points, other.points entity_lines, other_lines = entity.lines, other.lines results = [] # Get all intersections between each object's point and the other object's line for point in entity_points: for line in other_lines: results.append((point, v12, a12, line)) for point in other_points: for line in entity_lines: results.append((point, v21, a21, line)) # Return results of ParabolaLineCollision with each list of arguments in results # Pseudo-code to achieve this (I haven't done the parallizing yet): # return min(map(ParabolaLineCollision, results)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T10:58:46.833", "Id": "17021", "Score": "0", "body": "How does your entity behave? Instead of calling \"ParabolaLineCollision on each point of each object\" which is very expensive, couldn't you just track the two mass center trajectory and check for an overlapping of the shapes of the two entities?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T16:56:18.827", "Id": "17031", "Score": "0", "body": "This is how I check the overlapping shapes, as this is the shapes of the two entities. I don't have a mass center trajectory. In addition, this is A Priori collision, and this is only done whenever an object's trajectory changes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T17:16:39.630", "Id": "17032", "Score": "0", "body": "There's a particular reason for not having one? It should really speed things up. I don't understand what it has to do if the computation is a priori or not, it's still a computation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T17:44:05.787", "Id": "17033", "Score": "0", "body": "I'm not sure what you're indicating as a way of doing collision. I don't have one because I don't need one. I say it's A priori to indicate that this doesn't happen every frame.\n\nI need to know when the shapes are going to hit each other, so that I can resolve the collision as it occurs (instead of after). I define my objects' shapes as a set of consecutive points. At the time that two consecutive points of an object become collinear with any other objects' point, there is a collision." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T18:39:47.733", "Id": "17035", "Score": "0", "body": "I'm indicating a way of just let those entity be, I'd build some kind of (repulsive) interaction between them to trigger when they'll get near enough. To keep the picture in sync with the physics underneath use different refresh rate. You wouldn't need to pre-compute anything and just let the physics flow. This way you should save you a \"very CPU-intensive function\" :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-06T20:31:20.530", "Id": "17037", "Score": "0", "body": "I plan on using space partitioning in the long run, and I am also considering using AABB collision detection as a way of knowing when two objects are likely to collide. My current solution allows frames to do nothing but compute position, until a collision occurs, which is a nice efficiency bonus in comparison to post-collision detection." } ]
{ "AcceptedAnswerId": "10652", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T19:40:29.850", "Id": "10650", "Score": "2", "Tags": [ "python" ], "Title": "Logic/Code duplication, improve readability?" }
10650
accepted_answer
[ { "body": "<p>Not a lot of changes, but maybe a bit more legible. </p>\n\n<pre><code>a12 = entity.acceleration - other.acceleration\na21 = -a12\nv12 = entity.velocity - other.velocity\nv21 = -v12\n\nresult = [ (p, v12, a12, l) for l in other.lines for p in entity.points ] +\n [ (p, v21, a21, l) for l in entity.lines for p in other.points ]\n</code></pre>\n\n<p>Obviously you could inline the v21 and a21 variables, but it's actually somewhat descriptive of what they represent to use those names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T20:29:15.240", "Id": "10652", "ParentId": "10650", "Score": "3" } } ]
<p>I was preparing myself for an interview at a well known .com firm. One of the question that they often ask is an algorithm to solve sudokus (that have one solution). Here is what came to my mind. Any hints criticisms or suggestions to tune it up? </p> <pre><code>import itertools sudoku_str="""003020600 900305001 001806400 008102900 700000008 006708200 002609500 800203009 005010300""" sudoku=[[int(i) for i in j] for j in sudoku_str.splitlines()] while not any([0 in line for line in sudoku]): for x,y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2)): #Find the elements in the line line=set([i for i in sudoku[y] if i]) #Find the elements in the column column=set([xline[x] for xline in sudoku if xline[x]]) #Create some shifts to get the start (x,y) position for the area computation e.g. for 1,1 =&gt; 0,0 and for 3,8=&gt;1,3 shifts=dict(zip(range(9),[0]*3+[3]*3+[6]*3)) #Find the elements in the area area=filter(None,reduce(lambda x,y: x.add(y), sudoku[shifts[y]:shifts[y]+3], set())) #What could be in that position? outcomes=set(range(1,10))-line-column-area if len(outcomes)==1: #One outcome? replace the zero sudoku[y][x]=outcomes.pop() print "\n".join([" | ".join(str(k) for k in i) for i in sudoku]) </code></pre>
[]
{ "AcceptedAnswerId": "10690", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:39:37.747", "Id": "10688", "Score": "4", "Tags": [ "python", "algorithm", "sudoku" ], "Title": "Sudoku solving algorithm - Revision needed" }
10688
accepted_answer
[ { "body": "<p>This is far too complicated:</p>\n\n<pre><code>for x,y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2)):\n</code></pre>\n\n<p>It is equivalent to this:</p>\n\n<pre><code>[(x, y) for x in range(9) for y in range(9) if not sudoku[y][x]]\n</code></pre>\n\n<p>More generally, this code feels like it is trying too hard to be clever at the expense of both clarity and potentially accuracy.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>To answer the question of speed posed by the op:</p>\n\n<pre><code>$ python -m timeit 'sudoku_str=\"\"\"003020600900305001001806400008102900700000008006708200002609500800203009005010300\"\"\";sudoku = [[int(i) for i in sudoku_str[j:j+9]] for j in range(0, 81, 9)];b = [(x, y) for x in range(9) for y in range(9) if not sudoku[y][x]];'\n10000 loops, best of 3: 68.1 usec per loop\n\n$ python -m timeit 'import itertools; sudoku_str=\"\"\"003020600900305001001806400008102900700000008006708200002609500800203009005010300\"\"\";sudoku = [[int(i) for i in sudoku_str[j:j+9]] for j in range(0, 81, 9)];a =[(x, y) for x, y in itertools.ifilter(lambda x: sudoku[x[1]][x[0]]==False, itertools.product(*[range(9)]*2))];'\n10000 loops, best of 3: 91.9 usec per loop\n</code></pre>\n\n<p>A simple list comprehension is both clearer and faster.</p>\n\n<p>Here's another example of unnecessary cleverness:</p>\n\n<pre><code>&gt;&gt;&gt; shifts=dict(zip(range(9),[0]*3+[3]*3+[6]*3))\n&gt;&gt;&gt; shifts\n{0: 0, 1: 0, 2: 0, 3: 3, 4: 3, 5: 3, 6: 6, 7: 6, 8: 6}\n&gt;&gt;&gt; clear_shifts = {x:(x/3)*3 for x in range(9)}\n&gt;&gt;&gt; clear_shifts\n{0: 0, 1: 0, 2: 0, 3: 3, 4: 3, 5: 3, 6: 6, 7: 6, 8: 6}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:47:12.247", "Id": "17050", "Score": "0", "body": "Definitely cleaner. Would abandoning itertools comport any noticeable decrease in the speed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:02:58.130", "Id": "17052", "Score": "0", "body": "@luke14free abandoning itertools would significantly increase the speed: see my edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:09:31.577", "Id": "17055", "Score": "0", "body": "Yes, this should be because of the lambda function. If you use ifilterfalse and put \"None\" instead of the lambda block itertools are about 10usec faster than simple lists.\n\npython -m timeit 'import itertools; sudoku_str=\"\"\"003020600900305001001806400008102900700000008006708200002609500800203009005010300\"\"\";sudoku = [[int(i) for i in sudoku_str[j:j+9]] for j in range(0, 81, 9)];a =[(x, y) for x, y in itertools.ifilterfalse(None, itertools.product(*[range(9)]*2))];'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T22:17:14.157", "Id": "17056", "Score": "0", "body": "Great answer anyhow. I love criticisms. Anyhow set([i for i in sudoku[y] if i]) is used because:\n\na) I need a set for the \"set subtraction\".\n\nb) I cannot accept zeros. -\n\nI don't see the reason of your struggling on it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-07T21:44:01.353", "Id": "10690", "ParentId": "10688", "Score": "5" } } ]
<p>This is a simple filter that I have been using for a project reading data over a serial connection, and thought it would be good to use it as my first attempt to write docstrings. Does anyone have any suggestions? I have been reading PEP 257. As it is a class, should the keyword arguments come after the <code>__init__</code> ?</p> <p>If there is a better way to write any part of it (not only the docstrings), I would appreciate it if people could point me in the right direction. </p> <pre><code>class Filter(object) : """Return x if x is greater than min and less than max - else return None. Keyword arguments: min -- the minimum (default 0) max -- the maximum (default 0) Notes: Accepts integers and integer strings """ def __init__(self, min=0, max=0) : self.min = min self.max = max def __call__(self, input) : try : if int(input) &lt;= self.max and int(input) &gt;= self.min : return int(input) except : pass </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:36:01.197", "Id": "17090", "Score": "0", "body": "For better commentary, how about including a sample of usage?" } ]
{ "AcceptedAnswerId": "10711", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:22:04.923", "Id": "10709", "Score": "4", "Tags": [ "python" ], "Title": "Filter for reading data over a serial connection" }
10709
accepted_answer
[ { "body": "<pre><code>class Filter(object) :\n \"\"\"Return x if x is greater than min and less than max - else return None. \n</code></pre>\n\n<p>How about \"if x is between min and mix\"?</p>\n\n<pre><code> Keyword arguments:\n min -- the minimum (default 0)\n max -- the maximum (default 0)\n\n Notes:\n Accepts integers and integer strings\n \"\"\"\n def __init__(self, min=0, max=0) :\n</code></pre>\n\n<p>min and max are builtin python functions. I suggest not using the same names if you can help it.</p>\n\n<pre><code> self.min = min\n self.max = max\n def __call__(self, input) :\n try :\n if int(input) &lt;= self.max and int(input) &gt;= self.min : \n</code></pre>\n\n<p>In python you can do: <code>if self.min &lt; int(input) &lt;= self.max</code></p>\n\n<pre><code> return int(input)\n\n except : pass\n</code></pre>\n\n<p>Don't ever do this. DON'T EVER DO THIS! ARE YOU LISTENING TO ME? DON'T EVER DO THIS.</p>\n\n<p>You catch and ignore any possible exception. But in python everything raises exceptions, and you'll not be notified if something goes wrong. Instead, catch only the specific exceptions you are interested in, in this, case <code>ValueError</code>.</p>\n\n<p>Futhermore, having a filter that tries to accept string or integers like this just a bad idea. Convert your input to integers before you use this function, not afterwards.</p>\n\n<p>The interface you provide doesn't seem all that helpful. The calling code is going to have to deal with <code>None</code> which will be a pain. Usually in python we'd do something operating on a list or as a generator.</p>\n\n<p>Perhaps you want something like this:</p>\n\n<pre><code>return [int(text) for text in input if min &lt; int(text) &lt; max]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:44:02.460", "Id": "17083", "Score": "0", "body": "I know I was being super lazy with the except:pass, it got the job done... but you words have not fallen on deaf ears :) Ideally I didn't want it to return anything if it was not within the range. Again the conversion of str -> int was out of lazyness, I had another function for that. So I should keep things clean, and shouldn't mix things that shouldn't be mixed..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:49:14.407", "Id": "17084", "Score": "0", "body": "One question... what exactly is the 'interface'. I didn't think Python did interfaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:56:39.763", "Id": "17086", "Score": "0", "body": "@user969617, interface refers to how you use the function. Stuff like names, return values, parameters, that sorta thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T22:01:27.540", "Id": "17087", "Score": "0", "body": "@Winston... gotcha" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-08T21:38:11.050", "Id": "10711", "ParentId": "10709", "Score": "4" } } ]
<p>I'm just getting my feet on the ground with Python (maybe 3 days now). The only issue with teaching my self is that I have no one to critique my work.</p> <p>Correct me if I'm wrong but I think my algorithm/method for solving this problem is quite promising; but, the code not so much.</p> <p>The program basically strips a web-page and puts it in to the designated directory. My favorite part is the method for deciding the image's extensions :)</p> <pre><code>import os, re, urllib def Read(url): uopen = urllib.urlopen(url) uread = '' for line in uopen: uread += line return uread def Find(what, where): found = re.findall(what, where) match = [] for i in found: i = i[9:-1] match.append(i) return match def Retrieve(urls, loc): loc = os.path.realpath(loc) os.system('mkdir ' + loc +'/picretrieved') loc += '/picretrieved' x = 0 exts = ['.jpeg', '.jpg', '.gif', '.png'] for url in urls: x += 1 for i in exts: ext = re.search(i, url) if ext != None: ext = ext.group() urllib.urlretrieve(url, loc + '/' + str(x) + ext) else: continue print 'Placed', str(x), 'pictures in:', loc def main(): url = raw_input('URL to PicRetrieve (google.com): ') url = 'http://' + url loc = raw_input('Location for PicRetrieve older ("." for here): ') html = Read(url) urls = Find('img src=".*?"', html) print urls Retrieve(urls, loc) if __name__ == '__main__': main() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-11T22:36:19.000", "Id": "10804", "Score": "4", "Tags": [ "python", "beginner", "web-scraping" ], "Title": "Saving images from a web page" }
10804
max_votes
[ { "body": "<pre><code>import os, re, urllib\n\ndef Read(url):\n</code></pre>\n\n<p>Python convention is to name function lowercase_with_underscores</p>\n\n<pre><code> uopen = urllib.urlopen(url)\n</code></pre>\n\n<p>I recommend against abbreviations</p>\n\n<pre><code> uread = ''\n for line in uopen: uread += line\n return uread\n</code></pre>\n\n<p>Use <code>uopen.read()</code> it'll read the whole file</p>\n\n<pre><code>def Find(what, where):\n found = re.findall(what, where)\n match = []\n for i in found:\n</code></pre>\n\n<p>avoid single letter variable names</p>\n\n<pre><code> i = i[9:-1]\n match.append(i)\n return match \n</code></pre>\n\n<p>Combine short lines of code</p>\n\n<pre><code> for i in re.findall(what, where):\n match.append(i[9:-1])\n</code></pre>\n\n<p>I think its cleaner this way. Also use capturing groups rather then indexes.</p>\n\n<pre><code>def Retrieve(urls, loc):\n loc = os.path.realpath(loc)\n os.system('mkdir ' + loc +'/picretrieved')\n</code></pre>\n\n<p>Use <code>os.mkdir</code> rather than using system</p>\n\n<pre><code> loc += '/picretrieved'\n</code></pre>\n\n<p>Use os.path.join to construct paths</p>\n\n<pre><code> x = 0\n exts = ['.jpeg', '.jpg', '.gif', '.png']\n for url in urls:\n x += 1\n</code></pre>\n\n<p>use <code>for x, url in enumerate(urls):</code></p>\n\n<pre><code> for i in exts:\n ext = re.search(i, url)\n</code></pre>\n\n<p>Don't use regular expressions to search for simple strings. In this case I think you really want to use <code>url.endswith(i)</code>. Also, stop using <code>i</code> everywhere.</p>\n\n<pre><code> if ext != None:\n ext = ext.group()\n urllib.urlretrieve(url, loc + '/' + str(x) + ext)\n else:\n continue\n</code></pre>\n\n<p>This continue does nothing</p>\n\n<pre><code> print 'Placed', str(x), 'pictures in:', loc\n</code></pre>\n\n<p>You don't need to use str when you are using print. It does it automatically.</p>\n\n<pre><code>def main():\n url = raw_input('URL to PicRetrieve (google.com): ')\n url = 'http://' + url\n loc = raw_input('Location for PicRetrieve older (\".\" for here): ')\n html = Read(url)\n urls = Find('img src=\".*?\"', html)\n</code></pre>\n\n<p>Generally, using an html parser is preferred to using a regex on html. In this simple case you are ok.</p>\n\n<pre><code> print urls\n Retrieve(urls, loc)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T00:29:36.127", "Id": "10807", "ParentId": "10804", "Score": "3" } } ]
<p>Can anyone suggest any improvements to this <code>RangeFinder</code> class?</p> <pre><code>import serial from collections import deque def str2int(x): try: return int(x) except ValueError: pass class RangeFinder(object): def __init__(self, mem=3) : self.mem = deque(maxlen=mem) self.absmax = -10**10 self.absmin = 10**10 self.relmax = None self.relmin = None def __call__(self, input) : try: self.mem.append(input) if len(self.mem) == self.mem.maxlen : self.relmax = max(self.mem) if self.relmax &gt; self.absmax : self.absmax = max(self.mem) self.relmin = min(self.mem) if self.relmin &lt; self.absmin : self.absmin = self.relmin except TypeError: pass dev = '/dev/tty.usbserial-A60085VG' baud = 9600 serial_reader = serial.Serial(dev,baud) rf = RangeFinder(5) for data in serial_reader: rf(str2int(data)) print( rf.mem ) </code></pre> <p>I have printed the output of the short term memory used to give a relative max / min and test for absolute max and min:</p> <blockquote> <pre><code>sh &gt; python3 serial_helper2.py deque([877], maxlen=5) deque([877, 877], maxlen=5) deque([877, 877, 877], maxlen=5) deque([877, 877, 877, 877], maxlen=5) deque([877, 877, 877, 877, 877], maxlen=5) deque([877, 877, 877, 877, 877], maxlen=5) deque([877, 877, 877, 877, 877], maxlen=5) deque([877, 877, 877, 877, 876], maxlen=5) deque([877, 877, 877, 876, 876], maxlen=5) deque([877, 877, 876, 876, 876], maxlen=5) deque([877, 876, 876, 876, 875], maxlen=5) deque([876, 876, 876, 875, 875], maxlen=5) </code></pre> </blockquote>
[]
{ "AcceptedAnswerId": "10833", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:01:40.853", "Id": "10830", "Score": "1", "Tags": [ "python", "interval" ], "Title": "RangeFinder class" }
10830
accepted_answer
[ { "body": "<pre><code>import serial\nfrom collections import deque\n\ndef str2int(x):\n try: \n return int(x)\n except ValueError:\n pass\n</code></pre>\n\n<p>returning <code>None</code> is rarely more useful then throwing the exception. Learn to love exceptions, and don't write functions like this that just turn them into <code>None</code></p>\n\n<pre><code>class RangeFinder(object):\n\n def __init__(self, mem=3) :\n self.mem = deque(maxlen=mem)\n self.absmax = -10**10\n self.absmin = 10**10\n self.relmax = None\n self.relmin = None\n\n def __call__(self, input) :\n</code></pre>\n\n<p>callable objects are rarely the right thing. Its usually clearer to just use a regular method</p>\n\n<pre><code> try:\n self.mem.append(input)\n</code></pre>\n\n<p>So you pass None in here and then stick in on the queue. That doesn't seem like a good idea. Probably, you should avoid calling this when the data was invalid</p>\n\n<pre><code> if len(self.mem) == self.mem.maxlen : \n self.relmax = max(self.mem)\n if self.relmax &gt; self.absmax :\n self.absmax = max(self.mem) \n</code></pre>\n\n<p>You can write this as <code>self.absmax = max(self.absmax, self.relmax)</code></p>\n\n<pre><code> self.relmin = min(self.mem) \n if self.relmin &lt; self.absmin :\n self.absmin = self.relmin\n except TypeError:\n pass\n</code></pre>\n\n<p>Presumably you've done this to handle the None that you introduced because you used str2int. See how you only made things worse? Because a lot of things in Python throw TypeError, this is a really bad idea because you could catch a lot of errors you didn't mean to catch.</p>\n\n<p>Here's how I would structure your main loop to handle the invalid data</p>\n\n<pre><code>for data in serial_reader:\n try:\n value = int(data)\n except ValueError:\n pass # ignore invalid data\n else:\n rf(value)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T21:11:54.523", "Id": "17253", "Score": "0", "body": "I have been re-writing it and am trying out just using `if input != None:` which gets me out of using the `try / except` condition. - and also stops None going into the queue. (im also thinking about using deques (maxlen=2) for the min/max. To be honest I don't know how to `handle exceptions` - all I need is for it to keep running - which is why I thought letting it pass (and handling any `None`'s when they came along) would be the easiest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T03:57:30.717", "Id": "17257", "Score": "1", "body": "@user969617, I've added a bit at the end to show how I'd handle the reading loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-12T20:42:55.903", "Id": "10833", "ParentId": "10830", "Score": "2" } } ]
<p>I've written a small markov chain monte carlo function that takes samples from a posterior distribution, based on a prior and a binomial (Bin(N, Z)) distribution.</p> <p>I'd be happy to have it reviewed, especially perhaps, regarding how to properly pass functions as arguments to functions (as the function <code>prior_dist()</code> in my code). In this case, I'm passing the function <code>uniform_prior_distribution()</code> showed below, but it's quite likely I'd like to pass other functions, that accept slightly different arguments, in the future. This would require me to rewrite <code>mcmc()</code>, unless there's some smart way around it...</p> <pre><code>def mcmc(prior_dist, size=100000, burn=1000, thin=10, Z=3, N=10): import random from scipy.stats import binom #Make Markov chain (Monte Carlo) mc = [0] #Initialize markov chain while len(mc) &lt; thin*size + burn: cand = random.gauss(mc[-1], 1) #Propose candidate ratio = (binom.pmf(Z, N, cand)*prior_dist(cand, size)) / (binom.pmf(Z, N, mc[-1])*prior_dist(mc[-1], size)) if ratio &gt; random.random(): #Acceptence criteria mc.append(cand) else: mc.append(mc[-1]) #Take sample sample = [] for i in range(len(mc)): if i &gt;= burn and (i-burn)%thin == 0: sample.append(mc[i]) sample = sorted(sample) #Estimate posterior probability post = [] for p in sample: post.append(binom.pmf(Z, N, p) * prior_dist(p, size)) return sample, post, mc def uniform_prior_distribution(p, size): prior = 1.0/size return prior </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-27T04:41:55.547", "Id": "179822", "Score": "0", "body": "is it possible to replace `binom.pmf` with some more simple implementation" } ]
{ "AcceptedAnswerId": "10855", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T09:02:04.380", "Id": "10851", "Score": "3", "Tags": [ "python", "performance", "markov-chain" ], "Title": "Small Markov chain Monte Carlo implementation" }
10851
accepted_answer
[ { "body": "<h2>Function Passing</h2>\n\n<p>To pass functions with possibly varying argument lists consider using <a href=\"http://docs.python.org/release/2.5.2/tut/node6.html#SECTION006740000000000000000\" rel=\"nofollow\">argument unpacking</a>.</p>\n\n<p>By using a dictionary at the call site, we can use the arguments that are relevant to the chosen function whilst discarding those which aren't.</p>\n\n<pre><code>def uniform_prior_distribution(p, size, **args): #this args is neccesary to discard parameters not intended for this function\n prior = 1.0/size\n return prior\n\ndef foo_prior_distribution(p, q, size, **args):\n return do_something_with(p, q, size)\n\ndef mcmc(prior_dist, size=100000, burn=1000, thin=10, Z=3, N=10):\n import random\n from scipy.stats import binom\n #Make Markov chain (Monte Carlo)\n mc = [0] #Initialize markov chain\n while len(mc) &lt; thin*size + burn:\n cand = random.gauss(mc[-1], 1) #Propose candidate\n args1 = {\"p\": cand, \"q\": 0.2, \"size\": size}\n args2 = {\"p\": mc[-1], \"q\": 0.2, \"size\": size}\n ratio = (binom.pmf(Z, N, cand)*prior_dist(**args1)) / (binom.pmf(Z, N, mc[-1])*prior_dist(**args2))\n</code></pre>\n\n<p>Depending on how you use the mcmc function you may want to pass the args1 and args2 dicts directly as parameters to mcmc.</p>\n\n<p>However, this approach with only work if the common parameters (in this case p and size) can remain constant between different functions. Unfortunately I don't know enough about prior distributions to know if this is the case.</p>\n\n<h2>Other points of note</h2>\n\n<p>Use </p>\n\n<pre><code>sample.sort()\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>sample = sorted(sample)\n</code></pre>\n\n<p>It's clearer and slightly more efficient (it saves a copy).</p>\n\n<p>Instead of:</p>\n\n<pre><code>for i in range(len(mc)):\n if i &gt;= burn and (i-burn)%thin == 0:\n sample.append(mc[i])\n</code></pre>\n\n<p>Use the more pythonic:</p>\n\n<pre><code>for i,s in enumerate(mc):\n if i &gt;= burn and (i-burn)%thin == 0:\n sample.append(s)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-13T11:03:29.420", "Id": "10855", "ParentId": "10851", "Score": "1" } } ]
<p>I want to know why Java is accepted over Python when it comes to runtime. On performing the following Euler problem, Python takes up less lines and runs faster (Python ~0.05s, Java ~0.3s on my machine).</p> <p>Could I optimize this Java code in any way? The problem is here (<a href="http://projecteuler.net/problem=22" rel="nofollow">http://projecteuler.net/problem=22</a>)</p> <p>Python:</p> <pre><code>def main(): names = open("names.txt", "r").read().replace("\"", "").split(",") names.sort() print sum((i + 1) * sum(ord(c) - ord('A') + 1 for c in n) for i, n in enumerate(names)) if __name__ == "__main__": main() </code></pre> <p>Java:</p> <pre><code>import java.util.Arrays; import java.lang.StringBuilder; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class euler22 { public static String readFileAsString(String path) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader( new FileReader(path)); String buffer = null; while((buffer = reader.readLine()) != null) { builder.append(buffer); } reader.close(); return builder.toString(); } public static void main(String[] args) throws IOException { String[] names = fileAsString("names.txt").replace("\"", "").split(","); int total = 0; Arrays.sort(names); for(int i = 0; i &lt; names.length; ++i) { int sum = 0; for(char c : names[i].toCharArray()) { sum += c - 'A' + 1; } total += (i + 1) * sum; } System.out.println(total); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T04:07:00.150", "Id": "17479", "Score": "2", "body": "How exactly are you compiling your java code? Try deleting the pyc file and timing the Python piece twice in a row. Also, time the io-bound piece and the cpu-bound piece for Python and Java separately. The computation is in theory parralelizable, but not in Java version. I do not know enough to be sure though. I suggest that you use `with open('file.txt', 'r') as fin: names = fin.read()...` for better safety. You also probably can speed up the Java reading piece a bit if you tokenize things manually. Java's and Python's io library must differ, and one is taking more advantage of hardware maybe" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T03:27:14.087", "Id": "17491", "Score": "8", "body": "It might just be JVM startup time...hard to compare when runtimes are so short." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T03:32:45.040", "Id": "17492", "Score": "1", "body": "Profile your code, but I think most of the time is spent on reading the input files. You read the file line by line in Java which is slower than reading all at once in Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T03:37:55.630", "Id": "17493", "Score": "4", "body": "You simply cannot benchmark a Java program without running the code being benchmarked at least ten thousand times -- enough for the JIT to kick in. Anything else isn't a fair comparison." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T05:42:04.543", "Id": "17494", "Score": "1", "body": "There are many solutions on the forum for this problem. Did none of them help? BTW: Add to the run time, the time it took you to write the code, to get the total time from when you started to when you had a solution and you might see the runtime doesn't matter in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T13:12:36.413", "Id": "17497", "Score": "2", "body": "@Louis? Not fair? Why? This code is short enough that it *doesn’t need* the JIT to kick in. Furthermore, Python hasn’t got one either. The comparison is fair – it’s just not very meaningless precisely because the problem is too small to make a difference in practice." } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T03:24:20.513", "Id": "10997", "Score": "4", "Tags": [ "java", "python", "programming-challenge" ], "Title": "Python vs. Java Runtime on Euler 22 - Name Scores" }
10997
max_votes
[ { "body": "<p>Broadly speaking try creating less objects. ;)</p>\n\n<p>You can</p>\n\n<ul>\n<li>read the entire file as a series of lines or as a string with FileUtils.</li>\n<li>iterate through each character rather than building an array which you iterate.</li>\n<li>as the program is so short, try using <code>-client</code> which has shorter start time.</li>\n</ul>\n\n<p>To maximise the performance</p>\n\n<pre><code>long start = System.nanoTime();\nlong sum = 0;\nint runs = 10000;\nfor (int r = 0; r &lt; runs; r++) {\n FileChannel channel = new FileInputStream(\"names.txt\").getChannel();\n ByteBuffer bb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());\n TLongArrayList values = new TLongArrayList();\n\n long wordId = 0;\n int shift = 63;\n while (true) {\n int b = bb.remaining() &lt; 1 ? ',' : bb.get();\n if (b == ',') {\n values.add(wordId);\n wordId = 0;\n shift = 63;\n if (bb.remaining() &lt; 1) break;\n\n } else if (b &gt;= 'A' &amp;&amp; b &lt;= 'Z') {\n shift -= 5;\n long n = b - 'A' + 1;\n wordId = (wordId | (n &lt;&lt; shift)) + n;\n\n } else if (b != '\"') {\n throw new AssertionError(\"Unexpected ch '\" + (char) b + \"'\");\n }\n }\n\n values.sort();\n\n sum = 0;\n for (int i = 0; i &lt; values.size(); i++) {\n long wordSum = values.get(i) &amp; ((1 &lt;&lt; 8) - 1);\n sum += (i + 1) * wordSum;\n }\n}\nlong time = System.nanoTime() - start;\nSystem.out.printf(\"%d took %.3f ms%n\", sum, time / 1e6);\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>XXXXXXXXX took 27.817 ms\n</code></pre>\n\n<p>Its pretty obtuse, but works around the fact its not warmed up. </p>\n\n<p>You can tell this is the case because if you repeat the code in a loop 10000 times, the time taken is only 8318 ms or 0.83 ms per run.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-19T05:42:48.847", "Id": "11010", "ParentId": "10997", "Score": "2" } } ]
<p><code>Shape</code> represents an abstract class and the other two classes inherits from it. This looks insufficiently abstract to me. How could I improve it?</p> <pre><code>import math class Point: def __init__(self,x,y): self.x = x self.y = y def move(self,x,y): self.x += x self.y += y def __str__(self): return "&lt;"+ str(self.x) + "," + str(self.y) + "&gt;" class Shape: def __init__(self, centrePoint, colour, width, height): self.centrePoint = centrePoint self.colour = colour self.width = width self.height = height self.type = "Square" def __init__(self, centrePoint, radius, colour): self.type = "Circle" self.radius = radius self.colour = colour self.centrePoint = centrePoint def move(self,x,y): self.centrePoint.move(x,y) def getArea(self): if (self.type == "Square"): return self.width * self.height elif (self.type == "Circle"): return math.pi*(self.radius**2) def __str__(self): return "Center Point: " + str(self.centrePoint) + "\nColour: "+ self.Colour + "\nType: " + self.type + "\nArea: " + self.getArea() class Rectangle (Shape): def scale(self, factor): self.scaleVertically(factor) self.scaleHorizontally(factor) def scaleVertically(self, factor): self.height *= factor def scaleHorizontally(self, factor): self.width *= factor class Circle (Shape): def scale(self, factor): self.radius * factor </code></pre>
[]
{ "AcceptedAnswerId": "11081", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-22T16:50:14.460", "Id": "11080", "Score": "3", "Tags": [ "python", "object-oriented", "python-2.x", "homework" ], "Title": "Abstractness of Shape class" }
11080
accepted_answer
[ { "body": "<p>Your class Shape knows about what kind of shape it is (circle/square). This makes it tied to the two child classes. It should not know any thing about the composition. Rather just provide methods with empty implementations that can be overridden by child classes.</p>\n\n<p>The only thing I can see that is common across all classes is the concept of a center point and a color. So</p>\n\n<pre><code>import abc\n\nclass Shape(metaclass=abc.ABCMeta): \n def __init__(self, centrePoint, colour):\n self.centrePoint = centrePoint\n self.colour = colour\n</code></pre>\n\n<p>Since move depends only on center point, it is ok to define it in base class.</p>\n\n<pre><code> def move(self,x,y):\n self.centrePoint.move(x,y)\n</code></pre>\n\n<p>This is certainly one that should be implemented by the child classes because it requires knowledge about what kind of a shape it is.</p>\n\n<pre><code> @abc.abstractmethod\n def getArea(self):\n return\n</code></pre>\n\n<p>or if you dont want to use it</p>\n\n<pre><code> def getArea(self):\n raise NotImplementedError('Shape.getArea is not overridden')\n</code></pre>\n\n<p>see \n<a href=\"http://docs.python.org/library/abc.html\" rel=\"nofollow noreferrer\">abc</a> in \n<a href=\"https://stackoverflow.com/questions/7196376/python-abstractmethod-decorator\">so</a></p>\n\n<p>And the to string method is another that should be done in child because it holds details of what shape it is. </p>\n\n<pre><code> @abc.abstractmethod\n def __str__(self):\n return\n</code></pre>\n\n<p>However, if you are going to use the same format for all shapes, then you can provide the default implementation (as below.)</p>\n\n<pre><code> def __str__(self):\n return \"Center Point: \" + str(self.centrePoint) + \"\\nColour: \"+ self.Colour + \"\\nType: \" + self.type() + \"\\nArea: \" + self.getArea()\n</code></pre>\n\n<p>I would also recommend scale as part of the base class because all shapes can be scaled.</p>\n\n<pre><code> def scale(self, factor):\n return\n</code></pre>\n\n<p>Basically all operations that make sense on any shapes should have an abstract method on the base class.</p>\n\n<p>Now for child classes</p>\n\n<pre><code>class Rectangle (Shape):\n def __init__(self, cp, color, width, height):\n super(Rectangle, self).__init__(cp, color)\n self.width = width\n self.height = height\n\n def scale(self, factor):\n self.scaleVertically(factor)\n self.scaleHorizontally(factor)\n\n def scaleVertically(self, factor):\n self.height *= factor\n\n def scaleHorizontally(self, factor):\n self.width *= factor\n\n def getArea(self):\n return self.width * self.height\n\n def type(self):\n return \"Rectangle\"\n\nclass Circle (Shape):\n def __init__(self, cp, color, radius):\n super(Rectangle, self).__init__(cp, color)\n self.radius = radius\n\n def scale(self, factor):\n self.radius * factor\n\n def getArea(self):\n return math.pi*(self.radius**2)\n\n def type(self):\n return \"Circle\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-22T17:34:47.620", "Id": "11081", "ParentId": "11080", "Score": "2" } } ]
<p>I am using an external library named <code>enchant</code> here. My problem is that I guess my program is not returning all possible English words and is slow as well for large string input.</p> <p>I am using both <code>en_US</code> and <code>en_UK</code> here:</p> <pre><code>import enchant import itertools uk = enchant.Dict("en_UK") us=enchant.Dict("en_US") a=[] # stores all possible string combinations ent=input('enter the word: ') ent=ent.rstrip('\r\n') i=3 # minimum length of words while i&lt;=len(ent): it=itertools.permutations(ent,i) for y in it: a.append("".join(y)) i+=1 a.sort(key=len,reverse=True) possible_words=[] for x in a: if uk.check(x) and x not in possible_words : possible_words.append(x) for x in a : if us.check(x) and x not in possible_words: possible_words.append(x) possible_words.sort(key=len,reverse=True) for x in possible_words: print(x) </code></pre> <p><strong>Example :</strong></p> <pre><code>enter the word: wsadfgh wash wads wags swag shag dash fads fags gash gads haws hags shaw shad was wad wag saw sad sag ash ads fwd fas fad fag gas gad haw has had hag </code></pre>
[]
{ "AcceptedAnswerId": "11308", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-24T23:28:46.127", "Id": "11151", "Score": "1", "Tags": [ "python", "optimization", "algorithm", "performance" ], "Title": "Returning all possible English dictionary words that can be formed out of a string" }
11151
accepted_answer
[ { "body": "<p>1) Since all the permutations produced by <code>itertools.permutations()</code> are unique, there's no need to check for list membership in possible_words. </p>\n\n<p>2) the permutations produced by itertools.permutations() in your (unnecessary) while loop are already ordered by length, so you don't need to sort the results, merely reverse them.</p>\n\n<p>3) you can combine the US and UK dictionary lookups into one if statement.</p>\n\n<p>In fact, it's possible to compress the entire lower half of your code comfortably into two lines:</p>\n\n<pre><code>word_perms = (\"\".join(j) for k in range(1, len(ent) + 1) for j in permutations(ent, k))\npossible_words = reversed([i for i in word_perms if us.check(i) or uk.check(i)])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-29T13:36:06.603", "Id": "11308", "ParentId": "11151", "Score": "1" } } ]
<p>How can I improve this code for counting the number of bits of a positive integer n in Python?</p> <pre><code>def bitcount(n): a = 1 while 1&lt;&lt;a &lt;= n: a &lt;&lt;= 1 s = 0 while a&gt;1: a &gt;&gt;= 1 if n &gt;= 1&lt;&lt;a: n &gt;&gt;= a s += a if n&gt;0: s += 1 return s </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T00:53:23.950", "Id": "17849", "Score": "3", "body": "My silly question :): Cant you use `math.floor(math.log(number,2)) + 1`? Or do you mean the number of bits set?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T00:29:57.943", "Id": "11181", "Score": "5", "Tags": [ "python", "algorithm", "bitwise" ], "Title": "Counting the number of bits of a positive integer" }
11181
max_votes
[ { "body": "<p>The very first thing you should do to improve it is comment it. I'm reading it for almost half an hour and still can't understand what it does. I tested it, and it indeed work as intended, but I have no idea why. What algorithm are you using?</p>\n\n<p>I pointed below parts of the code that aren't clear to me. Since @blufox already presented a simpler way to count bits (that works for non-zero numbers), I won't bother to suggest an improvement myself.</p>\n\n<pre><code>def bitcount(n):\n a = 1\n while 1&lt;&lt;a &lt;= n:\n a &lt;&lt;= 1\n</code></pre>\n\n<p>Why is <code>a</code> growing in powers of two, while you're comparing <code>1&lt;&lt;a</code> to n? The sequence you're generating in binary is <code>10 100 10000 100000000 10000000000000000 ...</code> Take n=<code>101010</code>, and notice that</p>\n\n<p><code>10000 &lt; 100000 &lt; 101010 &lt; 1000000 &lt; 10000000 &lt; 100000000</code></p>\n\n<p>i.e. there is no relation between <code>1&lt;&lt;a</code> and the number of bits in <code>n</code>. Choose a=<code>1&lt;&lt;2</code>, and <code>1&lt;&lt;a</code> is too small. Choose a=<code>1&lt;&lt;3</code> and <code>1&lt;&lt;a</code> is too big. In the end, the only fact you know is that <code>1&lt;&lt;a</code> is a power of two smaller than <code>n</code>, but I fail to see how this fact is relevant to the task.</p>\n\n<pre><code> s = 0\n while a&gt;1:\n a &gt;&gt;= 1\n if n &gt;= 1&lt;&lt;a:\n n &gt;&gt;= a\n s += a\n</code></pre>\n\n<p>This removes <code>a</code> bits from <code>n</code>, while increasing the bit count by <code>a</code>. That is correct, but I fail to understand why the resulting <code>n</code> will still have fewer bits than the next <code>1&lt;&lt;a</code> in the sequence (since they vary so wildly, by <code>2**(2**n)</code>).</p>\n\n<pre><code> if n&gt;0:\n s += 1\n\n return s\n</code></pre>\n\n<p>I see that the result is off by 1 bit, and your code correctly adjust for that. Again, no idea why it does that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T03:42:45.690", "Id": "11192", "ParentId": "11181", "Score": "7" } } ]
<p>I have Django unit tests that are pretty much the following format:</p> <pre><code>class Tests(unittest.TestCase): def check(self, i, j): self.assertNotEquals(0, i-j) for i in xrange(1, 4): for j in xrange(2, 6): def ch(i, j): return lambda self: self.check(i, j) setattr(Tests, "test_%r_%r" % (i, j), ch(i, j)) </code></pre> <p>A function that returns a lambda that is bound as a method via <code>setattr</code>, which is an eyesore and as unreadable as you can get in Python without really trying to obfuscate.</p> <p>How can I achieve the same functionality in a more readable way, preferably without <code>lambda</code>?</p> <p>For reference, see <a href="https://stackoverflow.com/q/10346239/180174">the original SO question</a> about the subject.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T18:54:37.923", "Id": "11259", "Score": "4", "Tags": [ "python", "unit-testing", "functional-programming" ], "Title": "How do I dynamically create Python unit tests in a readable way?" }
11259
max_votes
[ { "body": "<p>Don't bother with generating tests:</p>\n\n<pre><code>class Tests(unittest.TestCase):\n def check(self, i, j):\n self.assertNotEquals(0, i-j)\n\n def test_thingies(self):\n for i in xrange(1, 4):\n for j in xrange(2, 6):\n self.check(i,j)\n</code></pre>\n\n<p>It would be nicer to generate individual tests, but do you really get that much benefit out of it?</p>\n\n<p>Or write a reusable function:</p>\n\n<pre><code>data = [(i,j) for i in xrange(1,4) for j in xrange(2,6)]\nadd_data_tests(TestClass, data, 'check')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T20:08:25.457", "Id": "18095", "Score": "0", "body": "Generating tests is pretty much a must - as there will be a few things that will be checked for hundreds of items so a single \"ok\" / \"failed\" for the 1k+ individual asserts does not give enough resolution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T20:11:15.750", "Id": "18096", "Score": "0", "body": "So even though I'm using unittest I'm actually doing this to do regression testing :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T20:55:03.163", "Id": "18097", "Score": "2", "body": "@Kimvais, you don't need separate tests to get that resolution. (Albeit, that's the nicest way. Some unit testing frameworks like nose make it easy.) Just catch the exception when it fails, and add some information on the parameters being tested." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T20:02:25.147", "Id": "11264", "ParentId": "11259", "Score": "2" } } ]
<p>I have Django unit tests that are pretty much the following format:</p> <pre><code>class Tests(unittest.TestCase): def check(self, i, j): self.assertNotEquals(0, i-j) for i in xrange(1, 4): for j in xrange(2, 6): def ch(i, j): return lambda self: self.check(i, j) setattr(Tests, "test_%r_%r" % (i, j), ch(i, j)) </code></pre> <p>A function that returns a lambda that is bound as a method via <code>setattr</code>, which is an eyesore and as unreadable as you can get in Python without really trying to obfuscate.</p> <p>How can I achieve the same functionality in a more readable way, preferably without <code>lambda</code>?</p> <p>For reference, see <a href="https://stackoverflow.com/q/10346239/180174">the original SO question</a> about the subject.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T18:54:37.923", "Id": "11259", "Score": "4", "Tags": [ "python", "unit-testing", "functional-programming" ], "Title": "How do I dynamically create Python unit tests in a readable way?" }
11259
max_votes
[ { "body": "<p>Don't bother with generating tests:</p>\n\n<pre><code>class Tests(unittest.TestCase):\n def check(self, i, j):\n self.assertNotEquals(0, i-j)\n\n def test_thingies(self):\n for i in xrange(1, 4):\n for j in xrange(2, 6):\n self.check(i,j)\n</code></pre>\n\n<p>It would be nicer to generate individual tests, but do you really get that much benefit out of it?</p>\n\n<p>Or write a reusable function:</p>\n\n<pre><code>data = [(i,j) for i in xrange(1,4) for j in xrange(2,6)]\nadd_data_tests(TestClass, data, 'check')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T20:08:25.457", "Id": "18095", "Score": "0", "body": "Generating tests is pretty much a must - as there will be a few things that will be checked for hundreds of items so a single \"ok\" / \"failed\" for the 1k+ individual asserts does not give enough resolution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T20:11:15.750", "Id": "18096", "Score": "0", "body": "So even though I'm using unittest I'm actually doing this to do regression testing :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T20:55:03.163", "Id": "18097", "Score": "2", "body": "@Kimvais, you don't need separate tests to get that resolution. (Albeit, that's the nicest way. Some unit testing frameworks like nose make it easy.) Just catch the exception when it fails, and add some information on the parameters being tested." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T20:02:25.147", "Id": "11264", "ParentId": "11259", "Score": "2" } } ]
<p>Do you have any suggestions about how to make this code faster/better? Maybe suggest new features or better comments/docstrings? </p> <pre><code>from time import time, ctime, sleep from random import choice, uniform from glob import glob import os # Gets current working directory DIRECTORY_NAME = os.getcwd() def load(): """Prints loading messages""" os.system("clear") MESSAGES = ["Deleting hard drive...", "Reticulating Spines...", "Fetching Your Credit Card Number...", "Hacking your computer..."] print(choice(MESSAGES)) sleep(uniform(1, 5)) os.system("clear") def print_dir(dirname): """Prints the current directory""" print("Directory: %s" % dirname) print("-"*80) def number_of_files(dirname): """Finds the number of files in the directory using glob""" num_of_files = len(glob("*")) print(num_of_files, "files") print("-"*80) def last_access(dirname): """Prints a ctime representation of the last access to a file""" print("Last Access: ") print(ctime(os.path.getatime(dirname))) print("-"*80) def last_change(dirname): """Prints a ctime representation of the last change to a file""" print("Last Change: ") print(ctime(os.path.getmtime(dirname))) print("-"*80) def size_of_dir(dirname): """Walks through the directory, getting the cumulative size of the directory""" sum = 0 for file in os.listdir(dirname): sum += os.path.getsize(file) print("Size of directory: ") print(sum, "bytes") print(sum/1000, "kilobytes") print(sum/1000000, "megabytes") print(sum/1000000000, "gigabytes") print("-"*80) input("Press ENTER to view all files and sizes") def files_in_dir(dirname): """Walks through the directory, printing the name of the file as well as its size""" print("Files in directory: %s" % dirname) for file in os.listdir(dirname): print("{0} =&gt; {1} bytes".format(file, os.path.getsize(file))) load() print_dir(DIRECTORY_NAME) number_of_files(DIRECTORY_NAME) last_access(DIRECTORY_NAME) last_change(DIRECTORY_NAME) size_of_dir(DIRECTORY_NAME) files_in_dir(DIRECTORY_NAME) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T22:56:47.220", "Id": "11376", "Score": "1", "Tags": [ "python" ], "Title": "Directory operations" }
11376
max_votes
[ { "body": "<pre><code>from time import time, ctime, sleep\nfrom random import choice, uniform\nfrom glob import glob\nimport os\n\n# Gets current working directory \nDIRECTORY_NAME = os.getcwd()\n</code></pre>\n\n<p>Given that its global and all caps, I'd expect it to be a constant. But it's not really a constant.</p>\n\n<pre><code>def load():\n \"\"\"Prints loading messages\"\"\"\n os.system(\"clear\")\n</code></pre>\n\n<p>This isn't portable, you may want to check out: <a href=\"https://stackoverflow.com/questions/2084508/clear-terminal-in-python\">https://stackoverflow.com/questions/2084508/clear-terminal-in-python</a></p>\n\n<pre><code> MESSAGES = [\"Deleting hard drive...\", \"Reticulating Spines...\", \"Fetching Your Credit Card Number...\", \"Hacking your computer...\"]\n</code></pre>\n\n<p>I'd put this as a global outside of the function.</p>\n\n<pre><code> print(choice(MESSAGES))\n sleep(uniform(1, 5))\n os.system(\"clear\")\n\ndef print_dir(dirname):\n \"\"\"Prints the current directory\"\"\"\n</code></pre>\n\n<p>It prints the directory passed in, not the current directory</p>\n\n<pre><code> print(\"Directory: %s\" % dirname)\n print(\"-\"*80)\n</code></pre>\n\n<p>You do this several times, perhaps write a function for it</p>\n\n<pre><code>def number_of_files(dirname):\n \"\"\"Finds the number of files in the directory using glob\"\"\"\n</code></pre>\n\n<p>I wouldn't put details like how it counts the files in the docstring</p>\n\n<pre><code> num_of_files = len(glob(\"*\"))\n print(num_of_files, \"files\")\n print(\"-\"*80)\n\ndef last_access(dirname):\n \"\"\"Prints a ctime representation of the last access to a file\"\"\"\n print(\"Last Access: \")\n print(ctime(os.path.getatime(dirname)))\n print(\"-\"*80)\n\ndef last_change(dirname):\n \"\"\"Prints a ctime representation of the last change to a file\"\"\"\n print(\"Last Change: \")\n print(ctime(os.path.getmtime(dirname)))\n print(\"-\"*80)\n</code></pre>\n\n<p>These two functions are quite similar. Considering combining them, passing the os.path.xtime function as a parameter</p>\n\n<pre><code>def size_of_dir(dirname):\n \"\"\"Walks through the directory, getting the cumulative size of the directory\"\"\"\n sum = 0\n</code></pre>\n\n<p>sum isn't a great choice because there is a builtin python function by that name</p>\n\n<pre><code> for file in os.listdir(dirname):\n sum += os.path.getsize(file)\n</code></pre>\n\n<p>I'd use <code>directory_size = sum(map(os.path.getsize, os.listdir(dirname))</code></p>\n\n<pre><code> print(\"Size of directory: \")\n print(sum, \"bytes\")\n print(sum/1000, \"kilobytes\")\n print(sum/1000000, \"megabytes\")\n print(sum/1000000000, \"gigabytes\")\n print(\"-\"*80)\n input(\"Press ENTER to view all files and sizes\")\n</code></pre>\n\n<p>As palacsint mentioned, this should really be in the next function, or perhaps in your main function.</p>\n\n<pre><code>def files_in_dir(dirname):\n \"\"\"Walks through the directory, printing the name of the file as well as its size\"\"\"\n print(\"Files in directory: %s\" % dirname)\n for file in os.listdir(dirname):\n</code></pre>\n\n<p>file is builtin class in python, I'd avoid using it as a local variable name</p>\n\n<pre><code> print(\"{0} =&gt; {1} bytes\".format(file, os.path.getsize(file)))\n\n\nload()\nprint_dir(DIRECTORY_NAME)\nnumber_of_files(DIRECTORY_NAME)\nlast_access(DIRECTORY_NAME)\nlast_change(DIRECTORY_NAME)\nsize_of_dir(DIRECTORY_NAME)\nfiles_in_dir(DIRECTORY_NAME)\n</code></pre>\n\n<p>I'd suggesting putting all of these in a main() function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T00:31:14.557", "Id": "11382", "ParentId": "11376", "Score": "1" } } ]
<p>The following method is designed to display what we owe to a vendor based on 5 buckets. Basically, an aged trial balance (totals only). It also needs to be able to display the data based on any date. It shows me what the trial balance would have looked like on April 1st. By default it displays based on the date that it is run. The <code>if</code> and <code>elif</code> branching "smells".</p> <pre><code>def _get_balances(self,ref_date=None): if not ref_date: ref_date = datetime.date.today() totals = [Decimal('0.0'),Decimal('0.0'),Decimal('0.0'),Decimal('0.0'),Decimal('0.0')] for invoice in self.invoices: if invoice.date: payments = Decimal('0.0') for payment in invoice.payments: if payment.check.date &lt;= ref_date: payments += payment.amount invoice_total = invoice.amount - payments if invoice.date &gt;= ref_date - relativedelta(days=29): totals[0] += invoice_total elif invoice.date &lt;= ref_date - relativedelta(days=30) and \ invoice.date &gt;= ref_date - relativedelta(days=43): totals[1] += invoice_total elif invoice.date &lt;= ref_date - relativedelta(days=44) and \ invoice.date &gt;= ref_date - relativedelta(days=47): totals[2] += invoice_total elif invoice.date &lt;= ref_date - relativedelta(days=48) and \ invoice.date &gt;= ref_date - relativedelta(days=59): totals[3] += invoice_total elif invoice.date &lt;= ref_date - relativedelta(days=60): totals[4] += invoice_total return tuple(totals) </code></pre>
[]
{ "AcceptedAnswerId": "11485", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T17:51:26.770", "Id": "11479", "Score": "1", "Tags": [ "python", "finance" ], "Title": "Accounts payable buckets (Current,30,44,48,60)" }
11479
accepted_answer
[ { "body": "<p>I wrote methods for determining if the date falls within the desired range. This doesn't really solve the cluster of <code>if else</code> statements, but it is more readable. </p>\n\n<p>I also used a few built-in Python functions, <code>filter</code> and <code>reduce</code>. These are tailor-made for handling these kinds of boiler-plate tasks. </p>\n\n<p>I also changed <code>if ref_date</code> to <code>if ref_date is None</code>. Quoted from <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a></p>\n\n<blockquote>\n <p>beware of writing <code>if x</code> when you really mean <code>if x is not None</code></p>\n</blockquote>\n\n<p>Finally, I replaced your list initialization for <code>totals</code> to according to <a href=\"https://stackoverflow.com/questions/521674/initializing-a-list-to-a-known-number-of-elements-in-python\">this</a> SO question.</p>\n\n<pre><code>def _get_balances(self,ref_date=None):\n if ref_date is None:\n ref_date = datetime.date.today()\n totals = [Decimal('0.0')] * 5\n for invoice in self.invoices:\n if invoice.date is not None:\n payments = filter(lambda: payment.check.date &lt;= ref_date)\n total_amount_paid = reduce(lambda: total, payment: payment.amount + total, payments, 0)\n invoice_total = invoice.amount - total_amount_paid \n if self.__invoice_date_is_before(invoice.date, ref, date, 29):\n totals[0] += invoice_total\n elif self.__invoice_date_is_between(invoice.date, ref_date, 30, 43):\n totals[1] += invoice_total\n elif iself.__invoice_date_is_between(invoice.date, ref_date, 44, 47):\n totals[2] += invoice_total\n elif self.__invoice_date_is_between(invoice.date, ref_date, 48, 59):\n totals[3] += invoice_total\n elif self.__invoice_date_is_after(invoice.date, ref_date, 60):\n totals[4] += invoice_total\n return tuple(totals)\n\ndef __invoice_date_is_between(self, invoice_date, ref_date, start_of_period, end_of_period):\n return invoice_date &lt;= ref_date - relativedelta(days=start_of_period) and \\\n invoice_date &gt;= ref_date - relativedelta(days=end_of_period)\n\ndef __invoice_date_is_after(self, invoice_date, ref_date, end_of_period):\n return invoice_date &lt;= ref_date - relativedelta(days=end_of_period):\n\ndef __invoice_date_is_before(self, invoice_date, ref_date, start_of_period):\n return invoice_date &gt;= ref_date - relativedelta(days=start_of_period)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-04T18:51:56.607", "Id": "11485", "ParentId": "11479", "Score": "4" } } ]
<p>In a Mako template partial I accept an argument (<code>step</code>) that can be an instance of <code>Step</code> class, a <code>dict</code> or <code>None</code>. Can I in some way avoid repetition or do the check in other more 'pythonic' way? Or how could I gracefully avoid checking types at all?</p> <pre><code>&lt;%include file="_step.mako" args="step=step" /&gt; </code></pre> <p>and then in <code>_step.mako</code>:</p> <pre><code>&lt;%page args="step"/&gt; &lt;%! from package.models.recipe import Step %&gt; &lt;% if isinstance(step, Step): number = step.number time_value = step.time_value text = step.text elif type(step) is dict: number = step['number'] time_value = step['time_value'] text = step['text'] else: number = 1 time_value = '' text = '' %&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T16:23:08.797", "Id": "18453", "Score": "1", "body": "actually, the most pythonic way would be to avoid passing different types to this partial." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T18:58:43.517", "Id": "18457", "Score": "0", "body": "@WinstonEwert I wolud gladly avoid that, but how can I maintain a single template that is rendering a form sometimes empty and sometimes repopulated (with dict or instance of a class)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T19:21:08.137", "Id": "18458", "Score": "0", "body": "you shouldn't. You should change the rest of your code so its consistently passes the same thing to this template." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:05:27.973", "Id": "18461", "Score": "0", "body": "@WinstonEwert like create a dummy (empty) dict for none, valid or invalid data and pass that dict to the template? You know, I started with such a design but faced a problem: if I repopulate invalid data - it can only be a dict (I do not allow creating instances from invalid data) and if its valid - it is an instance and I have access to its attributes. So if I want to access its attributes in the template I have to check (or `try`) if its an instance. But if I unify the the type of object passed to the template, and it can only be a dict, I guess, no attributes like methods, can be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:17:26.430", "Id": "18466", "Score": "0", "body": "Why do you need to populate this form with invalid data? Shouldn't you just not tolerate invalid data?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:32:15.100", "Id": "18467", "Score": "0", "body": "Ok, I have a `step` entity that requires a _number_ and _text_ and an optional _time value_. A user enters number and time value but leaves the text field empty. When I redirect after failed `step` creation I want to repopulate number and time value fields and mark the empty text field with error message." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T21:33:37.520", "Id": "18468", "Score": "0", "body": "ah, I see. What web framework are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T22:49:41.707", "Id": "18470", "Score": "0", "body": "Pyramid, but it's kind of fundamental question for me - I faced the same problem while on Zend Framework. Maybe it's because I don't utilize tools like Deform (and Zend_Form) that do the render-validate-repopulate job, but that's my style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T23:22:34.740", "Id": "18471", "Score": "1", "body": "You may find it useful to look into some of those projects, just to see how they solve this problem. Basically, they would have a `StepForm` class which can hold invalid/blank/valid data. The class would have methods to convert to/from an actual Step object. In some ways, its not dissimilar to always using a dictionary. But you get some benefits of using an object as well. You don't have to go for the whole form generation technique these libraries go for, but the separation between model and form objects has been widely adopted and seems to work well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T23:32:00.953", "Id": "18472", "Score": "0", "body": "Right! I am definetely close to stepping through Deform code for the final answers. Thanks for your attention Winston!" } ]
{ "AcceptedAnswerId": "11499", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T02:35:26.960", "Id": "11495", "Score": "1", "Tags": [ "python" ], "Title": "How to (and should I) avoid repetition while assigning values from different sources?" }
11495
accepted_answer
[ { "body": "<p>1.I assume <code>if type(step) is dict:</code> should be <code>elif type(step) is dict:</code>.</p>\n\n<p>2.<code>isinstance</code> is preferable than <code>type</code> because <code>isinstance</code> caters for inheritance, while checking for equality of type does not (it demands identity of types and rejects instances of subtypes).</p>\n\n<p>3.You also can apply duck-typing. </p>\n\n<pre><code>try:\n number = step.number\nexcept AttributeError:\n try:\n number = step['number']\n except KeyError:\n number = 1\n</code></pre>\n\n<p>And these ways are quite pythonic.</p>\n\n<p>4.I suggest you can inherit your <code>Step</code> class from <code>dict</code> then you don't need to check types. Yo will just do</p>\n\n<pre><code>number = step.get('number', 1)\ntime_value = step.get('time_value', '')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T06:24:49.247", "Id": "18447", "Score": "0", "body": "Thanks for the detailed answer! I will apply duck-typing as you described for now and save inheriting `dict` for later experiments - that could finally be a perfect solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T06:41:37.673", "Id": "18448", "Score": "0", "body": "You are welcome. But consider that `number = step.get('number', 1)` is shorter version of `try: number = step['number'] except KeyError: number = 1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T06:58:01.013", "Id": "18449", "Score": "0", "body": "I will. The Step class is used as a model and an sqlalchemy mapping, thats why I'm afraid messing with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T16:59:21.030", "Id": "18455", "Score": "0", "body": "I probably wouldn't use inheritance however. Just provide an implementation of the `get()` method and let the ducks do their thing." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T06:00:35.820", "Id": "11499", "ParentId": "11495", "Score": "1" } } ]
<p>This is my solution to the <a href="http://learnpythonthehardway.org/book/ex48.html" rel="nofollow">exercise 48 of Learn Python the hard way by Zed Shaw</a>. Please visit the link for testing suite and requirements.</p> <p>I'm worried about my the word banks I have created (COMPASS, VERBS, etc...) as this seems a duplication from the testing code.</p> <p>I'm also afraid my handling might have gone overboard as all I needed it for was finding out which string items could be converted to integers.</p> <pre><code>1 COMPASS= ['north','south','east','west']$ 2 VERBS = ['go', 'kill', 'eat']$ 3 STOPS = ['the', 'in', 'of']$ 4 NOUNS = ['bear', 'princess']$ 5 $ 6 import string$ 7 def scan(sentence):$ 8 action = []$ 9 #TODO: it seems there might be a way to combine these if statments$ 10 for word in sentence.split(' '):$ 11 lword = string.lower(word)$ 12 try:$ 13 if lword in COMPASS:$ 14 action.append(('direction', word))$ 15 elif lword in VERBS:$ 16 action.append(('verb', word))-$ 17 elif lword in STOPS:$ 18 action.append(('stop', word))$ 19 elif lword in NOUNS:$ 20 action.append(('noun', word))$ 21 elif int(lword):$ 22 action.append(('number', int(word)))$ 23 except:$ 24 action.append(('error', word))$ 25 return action$ 26 $ </code></pre>
[]
{ "AcceptedAnswerId": "11509", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T20:37:51.960", "Id": "11506", "Score": "1", "Tags": [ "python", "unit-testing", "exception-handling" ], "Title": "LPTHW - ex48 - Handling exceptions and unit testing" }
11506
accepted_answer
[ { "body": "<pre><code>lword = string.lower(word) \n</code></pre>\n\n<p>There is no need to import the string module for this, you can use:</p>\n\n<pre><code>lword = word.lower()\n</code></pre>\n\n<p>As for this:</p>\n\n<pre><code>elif int(lword):\n</code></pre>\n\n<p>Probably better as</p>\n\n<pre><code>elif lword.isdigit():\n</code></pre>\n\n<p>As for your exception handling</p>\n\n<pre><code> except: \n action.append(('error', word))\n</code></pre>\n\n<p>You should almost never use a bare except. You should catch a specific exception, and put a minimal amount of code in the try block. In this case you could have done something like</p>\n\n<pre><code>try:\n actions.append( ('number', int(word) )\nexcept ValueError:\n actions.append( ('error', word) )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T21:42:03.920", "Id": "11509", "ParentId": "11506", "Score": "1" } } ]
<p>I am looking to make the below code a bit more efficient / OOP based. As can be seen by the X, Y &amp; Z variables, there is a bit of duplication here. Any suggestions on how to make this code more pythonic?</p> <p>The code functions as I wish and the end result is to import the dictionary values into a MySQL database with the keys being the column headers.</p> <pre><code>import fnmatch import os import pyexiv2 matches = [] dict1 = {} # The aim of this script is to recursively search across a directory for all # JPEG files. Each time a JPEG image is detected, the script used the PYEXIV2 # module to extract all EXIF, IPTC and XMP data from the image. Once extracted # the key (ie. "camera make" is generated and it's respective value # (ie. Canon) is then added as the value in a dictionary. for root, dirnames, filenames in os.walk('C:\Users\Amy\Desktop'): for filename in fnmatch.filter(filenames, '*.jpg'): matches.append(os.path.join(root, filename)) for entry in matches: metadata = pyexiv2.ImageMetadata(entry) metadata.read() x = metadata.exif_keys y = metadata.iptc_keys z = metadata.xmp_keys for key in x: value = metadata[key] dict1[key] = value.raw_value for key in y: value = metadata[key] dict1[key] = value.raw_value for key in z: value = metadata[key] dict1[key] = value.raw_value print dict1 </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T21:38:10.247", "Id": "11508", "Score": "1", "Tags": [ "python", "object-oriented" ], "Title": "JPEG metadata processor" }
11508
max_votes
[ { "body": "<pre><code>import fnmatch\nimport os\nimport pyexiv2\n\nmatches = []\ndict1 = {}\n</code></pre>\n\n<p><code>dict1</code> isn't a great name because its hard to guess what it might be for. </p>\n\n<pre><code># The aim of this script is to recursively search across a directory for all\n# JPEG files. Each time a JPEG image is detected, the script used the PYEXIV2\n# module to extract all EXIF, IPTC and XMP data from the image. Once extracted\n# the key (ie. \"camera make\" is generated and it's respective value\n# (ie. Canon) is then added as the value in a dictionary.\nfor root, dirnames, filenames in os.walk('C:\\Users\\Amy\\Desktop'):\n</code></pre>\n\n<p>Your code will be a bit faster if you put stuff into a function rather than at the module level. </p>\n\n<pre><code> for filename in fnmatch.filter(filenames, '*.jpg'):\n matches.append(os.path.join(root, filename))\n for entry in matches:\n</code></pre>\n\n<p>ok, you add each file you find to the matches. But then each time you go over all the matches. I doubt you meant to do that. As its stand, you are going to look at the same file over and over again</p>\n\n<pre><code> metadata = pyexiv2.ImageMetadata(entry)\n metadata.read()\n x = metadata.exif_keys\n y = metadata.iptc_keys\n z = metadata.xmp_keys\n</code></pre>\n\n<p><code>x</code> <code>y</code> and <code>z</code> aren't great variable names. But its seems you aren't really interested in them seperately, just in all the keys. In that case do</p>\n\n<pre><code>keys = metadata.exif_keys + metadata.iptc_keys + metadata.xmp_keys\n</code></pre>\n\n<p>to combine them all into one list. (I'm guessing as to what exactly these keys are but, I think I it'll work.)</p>\n\n<pre><code> for key in x:\n value = metadata[key]\n dict1[key] = value.raw_value\n</code></pre>\n\n<p>I'd combine the two lines</p>\n\n<pre><code>dict1[key] = metadata[key].raw_value\n\n\n for key in y:\n value = metadata[key]\n dict1[key] = value.raw_value\n for key in z:\n value = metadata[key]\n dict1[key] = value.raw_value\n print dict1\n</code></pre>\n\n<p>If you put combine x,y,z as above, you'll only need the one loop</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-05T22:12:52.743", "Id": "11510", "ParentId": "11508", "Score": "3" } } ]
<p>Do you have any suggestions to improve or extend this script? Any ideas for removing or adding comments/docstrings?</p> <pre><code>import dbm import subprocess import time subprocess.call("clear") try: # Tries to import cPickle, a faster implementation of pickle. import cPickle as pickle except ImportError: import pickle class PickleDB: def open_db(self): """Gets and opens the database""" self.db_name = input("Enter a database name\n") # Makes sure the database name is compatible db_parts = self.db_name.split(".") self.db_name = db_parts[0] self.db = dbm.open(self.db_name, "n") def get_data(self): """Gets data to write into the database""" subprocess.call("clear") self.raw_data = input("Enter your raw data\n") # Pickles data self.pickled_data = pickle.dumps(self.raw_data) def write_to_db(self): """Writes data into database""" # Logs time self.start = time.time() # Creates keys self.db["raw"] = self.raw_data self.db["pickled"] = self.pickled_data def close_db(self): """Closes database""" self.db.close() # Logs end time self.end = time.time() def info(self): """Prints out info about the database""" subprocess.call("clear") print("Load data from database using dbm") print("Keys: raw\tpickled") # Prints total time print("Speed:", self.end - self.start, "seconds") # Function calls pickled_db = PickleDB() pickled_db.open_db() pickled_db.get_data() pickled_db.write_to_db() pickled_db.close_db() pickled_db.info() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T22:49:27.703", "Id": "11641", "Score": "0", "Tags": [ "python", "optimization", "database" ], "Title": "How to Improve This Program, Add Comments, etc.?" }
11641
max_votes
[ { "body": "<pre><code>import dbm\nimport subprocess\nimport time\nsubprocess.call(\"clear\")\n</code></pre>\n\n<p>This isn't cross-platform. Sadly, there isn't really a cross-platform alternative</p>\n\n<pre><code>try:\n # Tries to import cPickle, a faster implementation of pickle.\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nclass PickleDB:\n def open_db(self):\n \"\"\"Gets and opens the database\"\"\"\n self.db_name = input(\"Enter a database name\\n\")\n</code></pre>\n\n<p>You really shouldn't call <code>input</code> inside of a work class. The code responsible for User I/O should be separate from that doing any actual work.</p>\n\n<pre><code> # Makes sure the database name is compatible\n db_parts = self.db_name.split(\".\")\n self.db_name = db_parts[0]\n</code></pre>\n\n<p>Ok, why are you ignoring part of the name if its not good? Shouldn't you complain to the user and ask for a new name? Also, I'd avoid assigning to <code>self.db_name</code> only the replace it again a bit later. Since you don't use it outside this function, I'd probably just have a local variable</p>\n\n<pre><code> self.db = dbm.open(self.db_name, \"n\")\n\n def get_data(self):\n \"\"\"Gets data to write into the database\"\"\"\n subprocess.call(\"clear\")\n self.raw_data = input(\"Enter your raw data\\n\")\n # Pickles data\n</code></pre>\n\n<p>This comment is a little obvious, I'd delete it</p>\n\n<pre><code> self.pickled_data = pickle.dumps(self.raw_data)\n</code></pre>\n\n<p>I'd expect a function that <code>gets</code> data to return it to the caller. Generally, functions that drop state onto the class is a sign of poor design. Methods should usually communicate by parameters and return values not object storage.</p>\n\n<pre><code> def write_to_db(self):\n \"\"\"Writes data into database\"\"\"\n # Logs time\n self.start = time.time()\n</code></pre>\n\n<p>Collecting timing information isn't something that's usually part of the actual class doing the work. Usually you'd time the class from the outside.</p>\n\n<pre><code> # Creates keys\n self.db[\"raw\"] = self.raw_data\n self.db[\"pickled\"] = self.pickled_data\n\n def close_db(self):\n \"\"\"Closes database\"\"\"\n self.db.close()\n # Logs end time\n self.end = time.time()\n\n\n def info(self):\n \"\"\"Prints out info about the database\"\"\"\n subprocess.call(\"clear\")\n print(\"Load data from database using dbm\")\n print(\"Keys: raw\\tpickled\")\n # Prints total time\n print(\"Speed:\", self.end - self.start, \"seconds\")\n</code></pre>\n\n<p>As noted, output and timing is usually something you want to do outside of the work class itself. </p>\n\n<pre><code># Function calls\npickled_db = PickleDB()\npickled_db.open_db()\npickled_db.get_data()\npickled_db.write_to_db()\npickled_db.close_db()\npickled_db.info()\n</code></pre>\n\n<p>Here's the overall thing about your code. You are using a class as a group of functions and treating the object storage like a place to put global variables. You aren't making effective use of the class. In this case, you'd be better off to use a collection of functions than a class. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T04:47:56.673", "Id": "11650", "ParentId": "11641", "Score": "3" } } ]
<p>Do you have any suggestions to improve or extend this script? Any ideas for removing or adding comments/docstrings?</p> <pre><code>import dbm import subprocess import time subprocess.call("clear") try: # Tries to import cPickle, a faster implementation of pickle. import cPickle as pickle except ImportError: import pickle class PickleDB: def open_db(self): """Gets and opens the database""" self.db_name = input("Enter a database name\n") # Makes sure the database name is compatible db_parts = self.db_name.split(".") self.db_name = db_parts[0] self.db = dbm.open(self.db_name, "n") def get_data(self): """Gets data to write into the database""" subprocess.call("clear") self.raw_data = input("Enter your raw data\n") # Pickles data self.pickled_data = pickle.dumps(self.raw_data) def write_to_db(self): """Writes data into database""" # Logs time self.start = time.time() # Creates keys self.db["raw"] = self.raw_data self.db["pickled"] = self.pickled_data def close_db(self): """Closes database""" self.db.close() # Logs end time self.end = time.time() def info(self): """Prints out info about the database""" subprocess.call("clear") print("Load data from database using dbm") print("Keys: raw\tpickled") # Prints total time print("Speed:", self.end - self.start, "seconds") # Function calls pickled_db = PickleDB() pickled_db.open_db() pickled_db.get_data() pickled_db.write_to_db() pickled_db.close_db() pickled_db.info() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T22:49:27.703", "Id": "11641", "Score": "0", "Tags": [ "python", "optimization", "database" ], "Title": "How to Improve This Program, Add Comments, etc.?" }
11641
max_votes
[ { "body": "<pre><code>import dbm\nimport subprocess\nimport time\nsubprocess.call(\"clear\")\n</code></pre>\n\n<p>This isn't cross-platform. Sadly, there isn't really a cross-platform alternative</p>\n\n<pre><code>try:\n # Tries to import cPickle, a faster implementation of pickle.\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nclass PickleDB:\n def open_db(self):\n \"\"\"Gets and opens the database\"\"\"\n self.db_name = input(\"Enter a database name\\n\")\n</code></pre>\n\n<p>You really shouldn't call <code>input</code> inside of a work class. The code responsible for User I/O should be separate from that doing any actual work.</p>\n\n<pre><code> # Makes sure the database name is compatible\n db_parts = self.db_name.split(\".\")\n self.db_name = db_parts[0]\n</code></pre>\n\n<p>Ok, why are you ignoring part of the name if its not good? Shouldn't you complain to the user and ask for a new name? Also, I'd avoid assigning to <code>self.db_name</code> only the replace it again a bit later. Since you don't use it outside this function, I'd probably just have a local variable</p>\n\n<pre><code> self.db = dbm.open(self.db_name, \"n\")\n\n def get_data(self):\n \"\"\"Gets data to write into the database\"\"\"\n subprocess.call(\"clear\")\n self.raw_data = input(\"Enter your raw data\\n\")\n # Pickles data\n</code></pre>\n\n<p>This comment is a little obvious, I'd delete it</p>\n\n<pre><code> self.pickled_data = pickle.dumps(self.raw_data)\n</code></pre>\n\n<p>I'd expect a function that <code>gets</code> data to return it to the caller. Generally, functions that drop state onto the class is a sign of poor design. Methods should usually communicate by parameters and return values not object storage.</p>\n\n<pre><code> def write_to_db(self):\n \"\"\"Writes data into database\"\"\"\n # Logs time\n self.start = time.time()\n</code></pre>\n\n<p>Collecting timing information isn't something that's usually part of the actual class doing the work. Usually you'd time the class from the outside.</p>\n\n<pre><code> # Creates keys\n self.db[\"raw\"] = self.raw_data\n self.db[\"pickled\"] = self.pickled_data\n\n def close_db(self):\n \"\"\"Closes database\"\"\"\n self.db.close()\n # Logs end time\n self.end = time.time()\n\n\n def info(self):\n \"\"\"Prints out info about the database\"\"\"\n subprocess.call(\"clear\")\n print(\"Load data from database using dbm\")\n print(\"Keys: raw\\tpickled\")\n # Prints total time\n print(\"Speed:\", self.end - self.start, \"seconds\")\n</code></pre>\n\n<p>As noted, output and timing is usually something you want to do outside of the work class itself. </p>\n\n<pre><code># Function calls\npickled_db = PickleDB()\npickled_db.open_db()\npickled_db.get_data()\npickled_db.write_to_db()\npickled_db.close_db()\npickled_db.info()\n</code></pre>\n\n<p>Here's the overall thing about your code. You are using a class as a group of functions and treating the object storage like a place to put global variables. You aren't making effective use of the class. In this case, you'd be better off to use a collection of functions than a class. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T04:47:56.673", "Id": "11650", "ParentId": "11641", "Score": "3" } } ]
<p>Do you have any suggestions to improve or extend this script? Any ideas for removing or adding comments/docstrings?</p> <pre><code>import dbm import subprocess import time subprocess.call("clear") try: # Tries to import cPickle, a faster implementation of pickle. import cPickle as pickle except ImportError: import pickle class PickleDB: def open_db(self): """Gets and opens the database""" self.db_name = input("Enter a database name\n") # Makes sure the database name is compatible db_parts = self.db_name.split(".") self.db_name = db_parts[0] self.db = dbm.open(self.db_name, "n") def get_data(self): """Gets data to write into the database""" subprocess.call("clear") self.raw_data = input("Enter your raw data\n") # Pickles data self.pickled_data = pickle.dumps(self.raw_data) def write_to_db(self): """Writes data into database""" # Logs time self.start = time.time() # Creates keys self.db["raw"] = self.raw_data self.db["pickled"] = self.pickled_data def close_db(self): """Closes database""" self.db.close() # Logs end time self.end = time.time() def info(self): """Prints out info about the database""" subprocess.call("clear") print("Load data from database using dbm") print("Keys: raw\tpickled") # Prints total time print("Speed:", self.end - self.start, "seconds") # Function calls pickled_db = PickleDB() pickled_db.open_db() pickled_db.get_data() pickled_db.write_to_db() pickled_db.close_db() pickled_db.info() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T22:49:27.703", "Id": "11641", "Score": "0", "Tags": [ "python", "optimization", "database" ], "Title": "How to Improve This Program, Add Comments, etc.?" }
11641
max_votes
[ { "body": "<pre><code>import dbm\nimport subprocess\nimport time\nsubprocess.call(\"clear\")\n</code></pre>\n\n<p>This isn't cross-platform. Sadly, there isn't really a cross-platform alternative</p>\n\n<pre><code>try:\n # Tries to import cPickle, a faster implementation of pickle.\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nclass PickleDB:\n def open_db(self):\n \"\"\"Gets and opens the database\"\"\"\n self.db_name = input(\"Enter a database name\\n\")\n</code></pre>\n\n<p>You really shouldn't call <code>input</code> inside of a work class. The code responsible for User I/O should be separate from that doing any actual work.</p>\n\n<pre><code> # Makes sure the database name is compatible\n db_parts = self.db_name.split(\".\")\n self.db_name = db_parts[0]\n</code></pre>\n\n<p>Ok, why are you ignoring part of the name if its not good? Shouldn't you complain to the user and ask for a new name? Also, I'd avoid assigning to <code>self.db_name</code> only the replace it again a bit later. Since you don't use it outside this function, I'd probably just have a local variable</p>\n\n<pre><code> self.db = dbm.open(self.db_name, \"n\")\n\n def get_data(self):\n \"\"\"Gets data to write into the database\"\"\"\n subprocess.call(\"clear\")\n self.raw_data = input(\"Enter your raw data\\n\")\n # Pickles data\n</code></pre>\n\n<p>This comment is a little obvious, I'd delete it</p>\n\n<pre><code> self.pickled_data = pickle.dumps(self.raw_data)\n</code></pre>\n\n<p>I'd expect a function that <code>gets</code> data to return it to the caller. Generally, functions that drop state onto the class is a sign of poor design. Methods should usually communicate by parameters and return values not object storage.</p>\n\n<pre><code> def write_to_db(self):\n \"\"\"Writes data into database\"\"\"\n # Logs time\n self.start = time.time()\n</code></pre>\n\n<p>Collecting timing information isn't something that's usually part of the actual class doing the work. Usually you'd time the class from the outside.</p>\n\n<pre><code> # Creates keys\n self.db[\"raw\"] = self.raw_data\n self.db[\"pickled\"] = self.pickled_data\n\n def close_db(self):\n \"\"\"Closes database\"\"\"\n self.db.close()\n # Logs end time\n self.end = time.time()\n\n\n def info(self):\n \"\"\"Prints out info about the database\"\"\"\n subprocess.call(\"clear\")\n print(\"Load data from database using dbm\")\n print(\"Keys: raw\\tpickled\")\n # Prints total time\n print(\"Speed:\", self.end - self.start, \"seconds\")\n</code></pre>\n\n<p>As noted, output and timing is usually something you want to do outside of the work class itself. </p>\n\n<pre><code># Function calls\npickled_db = PickleDB()\npickled_db.open_db()\npickled_db.get_data()\npickled_db.write_to_db()\npickled_db.close_db()\npickled_db.info()\n</code></pre>\n\n<p>Here's the overall thing about your code. You are using a class as a group of functions and treating the object storage like a place to put global variables. You aren't making effective use of the class. In this case, you'd be better off to use a collection of functions than a class. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T04:47:56.673", "Id": "11650", "ParentId": "11641", "Score": "3" } } ]
<p>Do you have any suggestions to improve or extend this script? Any ideas for removing or adding comments/docstrings?</p> <pre><code>import dbm import subprocess import time subprocess.call("clear") try: # Tries to import cPickle, a faster implementation of pickle. import cPickle as pickle except ImportError: import pickle class PickleDB: def open_db(self): """Gets and opens the database""" self.db_name = input("Enter a database name\n") # Makes sure the database name is compatible db_parts = self.db_name.split(".") self.db_name = db_parts[0] self.db = dbm.open(self.db_name, "n") def get_data(self): """Gets data to write into the database""" subprocess.call("clear") self.raw_data = input("Enter your raw data\n") # Pickles data self.pickled_data = pickle.dumps(self.raw_data) def write_to_db(self): """Writes data into database""" # Logs time self.start = time.time() # Creates keys self.db["raw"] = self.raw_data self.db["pickled"] = self.pickled_data def close_db(self): """Closes database""" self.db.close() # Logs end time self.end = time.time() def info(self): """Prints out info about the database""" subprocess.call("clear") print("Load data from database using dbm") print("Keys: raw\tpickled") # Prints total time print("Speed:", self.end - self.start, "seconds") # Function calls pickled_db = PickleDB() pickled_db.open_db() pickled_db.get_data() pickled_db.write_to_db() pickled_db.close_db() pickled_db.info() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-09T22:49:27.703", "Id": "11641", "Score": "0", "Tags": [ "python", "optimization", "database" ], "Title": "How to Improve This Program, Add Comments, etc.?" }
11641
max_votes
[ { "body": "<pre><code>import dbm\nimport subprocess\nimport time\nsubprocess.call(\"clear\")\n</code></pre>\n\n<p>This isn't cross-platform. Sadly, there isn't really a cross-platform alternative</p>\n\n<pre><code>try:\n # Tries to import cPickle, a faster implementation of pickle.\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nclass PickleDB:\n def open_db(self):\n \"\"\"Gets and opens the database\"\"\"\n self.db_name = input(\"Enter a database name\\n\")\n</code></pre>\n\n<p>You really shouldn't call <code>input</code> inside of a work class. The code responsible for User I/O should be separate from that doing any actual work.</p>\n\n<pre><code> # Makes sure the database name is compatible\n db_parts = self.db_name.split(\".\")\n self.db_name = db_parts[0]\n</code></pre>\n\n<p>Ok, why are you ignoring part of the name if its not good? Shouldn't you complain to the user and ask for a new name? Also, I'd avoid assigning to <code>self.db_name</code> only the replace it again a bit later. Since you don't use it outside this function, I'd probably just have a local variable</p>\n\n<pre><code> self.db = dbm.open(self.db_name, \"n\")\n\n def get_data(self):\n \"\"\"Gets data to write into the database\"\"\"\n subprocess.call(\"clear\")\n self.raw_data = input(\"Enter your raw data\\n\")\n # Pickles data\n</code></pre>\n\n<p>This comment is a little obvious, I'd delete it</p>\n\n<pre><code> self.pickled_data = pickle.dumps(self.raw_data)\n</code></pre>\n\n<p>I'd expect a function that <code>gets</code> data to return it to the caller. Generally, functions that drop state onto the class is a sign of poor design. Methods should usually communicate by parameters and return values not object storage.</p>\n\n<pre><code> def write_to_db(self):\n \"\"\"Writes data into database\"\"\"\n # Logs time\n self.start = time.time()\n</code></pre>\n\n<p>Collecting timing information isn't something that's usually part of the actual class doing the work. Usually you'd time the class from the outside.</p>\n\n<pre><code> # Creates keys\n self.db[\"raw\"] = self.raw_data\n self.db[\"pickled\"] = self.pickled_data\n\n def close_db(self):\n \"\"\"Closes database\"\"\"\n self.db.close()\n # Logs end time\n self.end = time.time()\n\n\n def info(self):\n \"\"\"Prints out info about the database\"\"\"\n subprocess.call(\"clear\")\n print(\"Load data from database using dbm\")\n print(\"Keys: raw\\tpickled\")\n # Prints total time\n print(\"Speed:\", self.end - self.start, \"seconds\")\n</code></pre>\n\n<p>As noted, output and timing is usually something you want to do outside of the work class itself. </p>\n\n<pre><code># Function calls\npickled_db = PickleDB()\npickled_db.open_db()\npickled_db.get_data()\npickled_db.write_to_db()\npickled_db.close_db()\npickled_db.info()\n</code></pre>\n\n<p>Here's the overall thing about your code. You are using a class as a group of functions and treating the object storage like a place to put global variables. You aren't making effective use of the class. In this case, you'd be better off to use a collection of functions than a class. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-10T04:47:56.673", "Id": "11650", "ParentId": "11641", "Score": "3" } } ]
<p><a href="http://en.wikipedia.org/wiki/Bell_number" rel="nofollow noreferrer">Bell number</a> \$B(n)\$ is defined as the number of ways of splitting \$n\$ into any number of parts, also defined as the sum of previous \$n\$ <a href="http://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind" rel="nofollow noreferrer">Stirling numbers of second kind</a>.</p> <p>Here is a snippet of Python code that Wikipedia provides (slightly modified) to print bell numbers:</p> <pre><code>def bell_numbers(start, stop): t = [[1]] ## Initialize the triangle as a two-dimensional array c = 1 ## Bell numbers count while c &lt;= stop: if c &gt;= start: yield t[-1][0] ## Yield the Bell number of the previous row row = [t[-1][-1]] ## Initialize a new row for b in t[-1]: row.append(row[-1] + b) ## Populate the new row c += 1 ## We have found another Bell number t.append(row) ## Append the row to the triangle for b in bell_numbers(1, 9): print b </code></pre> <p>But I have to print the \$n\$th bell number, so what I did was I changed the second last line of code as follows:</p> <pre><code>for b in bell_numbers(n,n) </code></pre> <p>This does the job, but I was wondering of an even better way to print the \$n\$th bell number.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-17T22:31:12.390", "Id": "276934", "Score": "1", "body": "Please check whether your code is indented correctly." } ]
{ "AcceptedAnswerId": "12121", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T10:21:14.857", "Id": "12119", "Score": "2", "Tags": [ "python", "combinatorics" ], "Title": "Printing nth bell number" }
12119
accepted_answer
[ { "body": "<p>You can use the <a href=\"http://mathworld.wolfram.com/DobinskisFormula.html\" rel=\"noreferrer\">Dobinski</a> formula for calculating Bell numbers more efficiently. </p>\n\n<p>Dobinski's formula is basically something like this line, although the actual implementation is a bit more complicated (this function neither returns precise value nor is efficient, see this <a href=\"http://fredrik-j.blogspot.com/2009/03/computing-generalized-bell-numbers.html\" rel=\"noreferrer\">blogpost</a> for more on this):</p>\n\n<pre><code>import math\nITERATIONS = 1000\ndef bell_number(N):\n return (1/math.e) * sum([(k**N)/(math.factorial(k)) for k in range(ITERATIONS)])\n</code></pre>\n\n<p>E.g. you can use the <a href=\"http://code.google.com/p/mpmath/\" rel=\"noreferrer\">mpmath</a> package to calculate the nth Bell number using this formula:</p>\n\n<pre><code>from mpmath import *\nmp.dps = 30\nprint bell(100)\n</code></pre>\n\n<p>You can check the implementation <a href=\"http://code.google.com/p/mpmath/source/browse/trunk/mpmath/functions/functions.py\" rel=\"noreferrer\">here</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T14:54:57.283", "Id": "19381", "Score": "0", "body": "The first method is returning error values as follows, the 5th bell number is actually 52 but this returns 50.767... and same is for other higher bell polynomials as well, I dont understand why this error is showing up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:26:48.673", "Id": "19383", "Score": "0", "body": "I know my `bell_number` function doesn't return precise value, it is just meant to display the general idea. The reason for the error is described in the referred [blogpost](http://fredrik-j.blogspot.com/2009/03/computing-generalized-bell-numbers.html), look for [this part](http://upload.wikimedia.org/math/2/f/e/2fe8b4e5768cc4c3b2884cab699317c0.png)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:36:42.317", "Id": "19385", "Score": "0", "body": "I see, thanks for this awesome answer, but i cant fully understand what mpmaths is, is it a pyhton library? and how to write the code that uses mpmaths in calculating Bell number,that code returns an error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T15:40:48.890", "Id": "19387", "Score": "0", "body": "mpmath is a Python module (library). You'll need to install that before you can use it. [mpmath install instructions](http://mpmath.googlecode.com/svn/trunk/doc/build/setup.html)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T13:00:10.667", "Id": "12121", "ParentId": "12119", "Score": "6" } } ]
<p>I have a code snippet below and because of habit from other programming languages I wanted to use a <code>do-while</code> loop instead. But Python offers only the construct which I show as a second code snippet instead of a <code>do-while*</code>loop. What is the best pythonic way to code this?</p> <pre><code>ch = getch() while ch != "q": do_something() ch = getch() while True: ch = getch() do_something() if ch == "q": break </code></pre>
[]
{ "AcceptedAnswerId": "12187", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-05-31T07:48:36.970", "Id": "12183", "Score": "5", "Tags": [ "python" ], "Title": "Reading a controll character in a loop in Python" }
12183
accepted_answer
[ { "body": "<p>I found a way to do this with <a href=\"http://docs.python.org/tutorial/datastructures.html\" rel=\"nofollow\">Python List Comprehension</a> (chapter 5.1.4) as follows:</p>\n\n<p>(Notice that I used <code>sys.stdin.read(1)</code> instead of <code>getch()</code>)</p>\n\n<pre><code>&gt;&gt;&gt; import sys\n&gt;&gt;&gt; while [x for x in sys.stdin.read(1) if x != 'q']:\n... print x # substitute this with your do_something()\n... \n\n\na\na\n\n\nb\nb\n\n\nc\nc\n\n\nq\n&gt;&gt;&gt;\n</code></pre>\n\n<p>You could also use, which is a bit uglier to me:</p>\n\n<pre><code>&gt;&gt;&gt; while [] != [x for x in sys.stdin.read(1) if x != 'q']:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T09:13:12.593", "Id": "19632", "Score": "0", "body": "Both of these are neat hacks, but the fact that 'x' is visible outside the list comprehension is arguably a wart in Python. I think that both alternatives in the original question express the intent better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-02T11:15:00.387", "Id": "19634", "Score": "0", "body": "@akaihola, ya when I was playing around with it, I was surprised I could get at 'x'. I'll try to think of another alternative that returns and uses a list instead, thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T09:28:43.483", "Id": "12187", "ParentId": "12183", "Score": "4" } } ]
<p>I did a quick google search, and it didn't show up.</p> <p>I haven't noticed it posted in pylint.py, or PEP8.py.</p> <p>My emacs mode doesn't warn me if my <code>import</code>s are listed arbitrarily...does anyone do this?</p> <pre><code>import longest.modulename.first import medium.sizename import short import sys import os from imports import go_at_the_bottom from length import does_matter from still import cascading </code></pre> <p>This is typically how I do it. But after a while, the list gets big!</p> <p>I think this might work better, but it's kind of ugly:</p> <pre><code>import longest.modulename.first import medium.sizename import os import short import sys from BeautifulSoup import BeautifulSoup as BS from BeautifulSoup import BeautifulStoneSoup as BSS #froms are sorted by import from imports import go_at_the_bottom from length import does_matter from mechanize import Browser as br from still import cascading </code></pre> <p>What's the standard for this? I like the look of the cascading imports, but I also like the utility of searching for what's being used in the script quickly.</p> <p>Is there another approach to this that I didn't cover that you use?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T23:27:38.393", "Id": "19763", "Score": "0", "body": "Interesting ... StyleCop can handle this for C#, and yes - system imports come first." } ]
{ "AcceptedAnswerId": "12258", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T16:04:00.827", "Id": "12220", "Score": "4", "Tags": [ "python" ], "Title": "Alphabetizing `import` Statements" }
12220
accepted_answer
[ { "body": "<p>PEP-8 <a href=\"http://www.python.org/dev/peps/pep-0008/#imports\">says</a>:</p>\n\n<blockquote>\n <p>Imports should be grouped in the following order:</p>\n \n <ol>\n <li>standard library imports</li>\n <li>related third party imports</li>\n <li>local application/library specific imports</li>\n </ol>\n \n <p>You should put a blank line\n between each group of imports.</p>\n</blockquote>\n\n<p>I follow it and then sort modules alphabetically within each group without separating <code>from</code> from the other <code>import</code>s, like this:</p>\n\n<pre><code>import re\nimport os\nfrom pprint import pprint\nimport traceback\n\nimport lxml\n\nfrom readers import SomeReader\nfrom util.stuff import (stuff_init, stuff_close, StdStuff,\n OtherStuff, BlahBlah)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T13:01:22.567", "Id": "19670", "Score": "0", "body": "+1 for quoting pep-8, useful for others to see who come across this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-28T23:14:55.633", "Id": "463040", "Score": "0", "body": "Because `pprint` the module and `pprint` the function are represented by identical strings, it's not clear whether you're alphabetizing on the module from which you're importing or the name you're actually importing. In other words, if you were importing something called `mprint` from `pprint` (i.e., importing something that comes alphabetically before `os`), would you place that before or after your `import os`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:11:24.177", "Id": "12258", "ParentId": "12220", "Score": "12" } } ]
<p>Is this a reasonable C++ wrapper function for Python's "list.count([character])" method?</p> <pre><code>int count( char CHAR, string STR ) { int counter = 0; for ( int i = 0 ; i &lt; STR.size() - 1 ; i++ ) { if ( STR[i] == CHAR ) { counter++; } } return counter; } //Edited "for( int i = 0 ; i++ &lt; STR.size-1 ; )" to "for(int i = 0 ; i &lt; STR.size ; i++)" now it counts the first char of the string =D </code></pre> <p>Tested it...works exactly like the python &lt;3</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-05T05:06:01.857", "Id": "19710", "Score": "3", "body": "you seem confused about what a wrapper function is. A wrapper function should call what it is wrapping, not reimplement it." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:25:01.090", "Id": "12265", "Score": "1", "Tags": [ "c++", "python" ], "Title": "C++ wrapper function for Python's \"list.count([character])\" method?" }
12265
max_votes
[ { "body": "<p>When STR is empty, STR.size() returns 0u. As a result, STR.size()-1 becomes maximum value of unsigned size type. i++ &lt; STR.size()-1. This will lead the function to crash.</p>\n\n<p>Also your function will not count CHAR of the first character of STR.</p>\n\n<p>You may want to use standard library.</p>\n\n<p><a href=\"http://www.cplusplus.com/reference/algorithm/count/\" rel=\"nofollow\">std::count(begin, end, CHAR)</a> is just what you are looking for.</p>\n\n<p>for example,</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;string&gt;\n\n...\nchar CHAR = 'l';\nstd::string STR(\"Hello World!\");\nptrdiff_t counter = std::count(STR.begin(), STR.end(), CHAR);\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:36:53.417", "Id": "19679", "Score": "0", "body": "Oh...im reading primer C++ n its pretty basic so i never even knew this existed in C++ :( do you have any suggestions on some great books/resources i can use to get myself up and coding in C++ the right way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T11:00:38.000", "Id": "19681", "Score": "0", "body": "@BUCKSHOT - see this FAQ-entry: http://stackoverflow.com/q/388242/1025391" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-04T10:33:10.580", "Id": "12266", "ParentId": "12265", "Score": "2" } } ]
<p>I just answered the question on project euler about finding <a href="http://projecteuler.net/problem=35" rel="nofollow">circular primes below 1 million</a> using python. My solution is below. I was able to reduce the running time of the solution from 9 seconds to about 3 seconds. I would like to see what else can be done to the code to reduce its running time further. This is strictly for educational purposes and for fun.</p> <pre><code>import math import time def getPrimes(n): """returns set of all primes below n""" non_primes = [j for j in range(4, n, 2)] # 2 covers all even numbers for i in range(3, n, 2): non_primes.extend([j for j in range(i*2, n, i)]) return set([i for i in range(2, n)]) - set(non_primes) def getCircularPrimes(n): primes = getPrimes(n) is_circ = [] for prime in primes: prime_str = str(prime) iter_count = len(prime_str) - 1 rotated_num = [] while iter_count &gt; 0: prime_str = prime_str[1:] + prime_str[:1] rotated_num.append(int(prime_str)) iter_count -= 1 if primes &gt;= set(rotated_num): is_circ.append(prime) return len(is_circ) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:21:37.733", "Id": "19907", "Score": "0", "body": "do you have any idea which region takes the most time? the getPrimes method looks like it's going to be expensive, as you're building two very large sets then subtracting one from the other." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:23:45.203", "Id": "19908", "Score": "0", "body": "getPrimes takes the most time (about 1.9s according to the python profiler)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:25:23.873", "Id": "19909", "Score": "0", "body": "and I'm fairly sure you'll be having duplicates in the `non_primes` list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:27:00.253", "Id": "19910", "Score": "0", "body": "if `getPrimes` takes 1.9s, the rest of the function is taking 7.1. if you're using a profiler it's running in debug I assume? how does it perform in release?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:30:20.280", "Id": "19911", "Score": "0", "body": "and I just don't think your method of determining circular primes is efficient. can't even work out it it's correct, tbh." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:31:54.303", "Id": "19912", "Score": "0", "body": "it is correct..you could see that if you test it and it takes approximately 3 seconds to run now not 9 seconds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T11:12:41.193", "Id": "19913", "Score": "0", "body": "sorry, misread the timing bit in your question. I think you'd get a big perfomance boost if you shifted your way of getting a list of prime numbers. You currently have something of the order of 10^12 iterations going on in generating the list of none-prime numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T13:33:41.487", "Id": "19923", "Score": "0", "body": "What happens if you replace list comprehensions with generator comprehensions (`[j for j in…]` with `(j for j in…)`)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T14:37:59.720", "Id": "19928", "Score": "0", "body": "You might look at this question to speed things up: http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T04:52:13.253", "Id": "19989", "Score": "0", "body": "http://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python" } ]
{ "AcceptedAnswerId": "12389", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T10:12:17.230", "Id": "12383", "Score": "4", "Tags": [ "python", "optimization", "project-euler", "primes" ], "Title": "Improving runtime of prime generation" }
12383
accepted_answer
[ { "body": "<p>Python 2.7: <strong>100 ms</strong>, pypy 1.8.0: <strong>60 ms</strong> (Intel Core i7-3770K, 4x 3.50GHz):</p>\n\n<pre><code>import time\n\ndef rwh_primes2(n):\n # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188\n \"\"\" Input n&gt;=6, Returns a list of primes, 2 &lt;= p &lt; n \"\"\"\n correction = (n%6&gt;1)\n n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]\n sieve = [True] * (n/3)\n sieve[0] = False\n for i in xrange(int(n**0.5)/3+1):\n if sieve[i]:\n k=3*i+1|1\n sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)\n sieve[(k*k+4*k-2*k*(i&amp;1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&amp;1))/6-1)/k+1)\n return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]\n\ndef main():\n start = time.time()\n primes = set(rwh_primes2(1000000))\n circular_primes = set()\n for prime in primes:\n include = True \n s = str(prime)\n for n in xrange(len(s)-1): \n s = s[1:] + s[:1]\n if int(s) not in primes: \n include = False\n break \n if include: \n circular_primes.add(prime)\n print(len(circular_primes))\n print(\"Time (s) : \" + str(time.time()-start))\n\nmain()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T22:55:17.613", "Id": "19973", "Score": "1", "body": "a bit of comments would help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T15:00:06.137", "Id": "12389", "ParentId": "12383", "Score": "1" } } ]
<p>I'm trying to create a generic function that takes a data structure as input and then sends each non-empty item—e.g.: str, int—individually:</p> <pre><code>def print_this(v, delim1="", delim2=""): print v, delim1, delim2 def pass_many(vals, some_funct, args=None): if vals: if type(vals) == list or type(vals) == tuple: for v in vals: if v: pass_many(v, some_funct, args) else: if args: some_funct(vals, *args) else: some_funct(vals) &gt;&gt;&gt; pass_many([['foo'],['',(5,3)]], print_this, ["newline","notnewline"]) foo newline notnewline 5 newline notnewline 3 newline notnewline </code></pre> <p>My current implementation works reasonably well, but feels hacky...</p> <p>How could I generalise it to unroll all data-structures (except strings), and make it less hacky?</p>
[]
{ "AcceptedAnswerId": "12421", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T11:34:48.273", "Id": "12414", "Score": "2", "Tags": [ "python", "generics" ], "Title": "Generic pass_many(vals, pass_one) to unroll and call pass_one(val)" }
12414
accepted_answer
[ { "body": "<p>I'd make a few changes: </p>\n\n<p>1) Take the <code>if v</code> check out of the inner loop into the function body (<code>if not vals: return</code>) - seems more consistent that way, unless you want <code>pass_many(0,print)</code> to print something but <code>pass_may([0], print)</code> not to?</p>\n\n<p>2) I'm not sure there's any reason to use <code>args=None</code> and then check for it being <code>None</code>, rather than just doing <code>args=()</code> to start with, and the implementation's shorter that way.</p>\n\n<p>3) There are definitely better ways to check whether something is a tuple/list/set/etc than using type. Unfortunately none of them are perfect... I really wish there was a good clean way of distinguishing these things from strings and dictionaries.<br>\nProbably he most general thing I can come up with, using <a href=\"http://www.python.org/dev/peps/pep-3119/\" rel=\"nofollow\">Abstract Base Classes</a> from <a href=\"http://docs.python.org/library/collections.html#collections-abstract-base-classes\" rel=\"nofollow\">the collections module</a> - it goes over all elements of iterable objects <em>except</em> for mappings (dictionaries etc - unless you want to include those?) and strings (I think the basic string type/s may be different in python3? Not sure.)</p>\n\n<pre><code>from collections import Iterable, Mapping\n\ndef pass_many(vals, some_funct, args=()):\n if not vals:\n return\n if isinstance(vals, Iterable) and not isinstance(vals, (basestring, Mapping)):\n for v in vals:\n pass_many(v, some_funct, args)\n else:\n some_funct(vals, *args)\n</code></pre>\n\n<p>Still, the ABCs aren't perfect - maybe using <code>hasattr</code> checks for whether something is an iterable or a mapping would be better. Not sure. Probably every possible way will have some downsides. </p>\n\n<p>If you want to be more stringent and just accept plain lists and tuples and no other iterables, <code>isinstance(vals, (list, tuple))</code> will be fine. It just won't work on things like iterators - whether that matters depends on the intended use. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T23:19:03.660", "Id": "20020", "Score": "0", "body": "Use `basestring` instead of `str` and `unicode`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T23:23:53.317", "Id": "20021", "Score": "0", "body": "@WinstonEwert - yes, I had just remembered that a few minutes ago. Edited, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-10T02:03:16.157", "Id": "20033", "Score": "0", "body": "I've never used the default arg of `()` before, which is why I didn't use it :). Your version seems to work quite nicely, thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-10T02:19:12.423", "Id": "20034", "Score": "0", "body": "@AT - glad it works! I still wish there was a better solution to the \"all data-structures (except strings)\" problem in python (and the \"all iterables except mappings\" one too), but this should work for all standard python types and hopefully most custom ones." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T21:52:36.440", "Id": "12421", "ParentId": "12414", "Score": "1" } } ]
<p>I have to list a integers from a text file separated by newlines into a python list. I ended up with the code above which works (for my case) but certainly is far form optimal.</p> <pre><code>def readIntegers(pathToFile): f = open(pathToFile) contents = f.read() f.close() tmpStr = "" integers = [] for char in contents: if char == '\r': integers.append(int(tmpStr)) tmpStr = "" continue if char == '\n': continue tmpStr += char return integers </code></pre> <hr> <p>Now I have much less code, but I'm not sure for which cases split() works correctly.</p> <pre><code>def readIntegers(pathToFile): with open(pathToFile) as f: a = [int(x) for x in f.read().split()] return a </code></pre>
[]
{ "AcceptedAnswerId": "12449", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-10T16:17:53.333", "Id": "12443", "Score": "8", "Tags": [ "python" ], "Title": "Reading ints line from a file in Python" }
12443
accepted_answer
[ { "body": "<p>No need for <code>split</code> (you can use <a href=\"http://docs.python.org/library/stdtypes.html#file.readlines\"><code>readlines</code></a>). But no need for <code>readlines</code>, for that matter:</p>\n\n<pre><code>def read_integers(filename):\n with open(filename) as f:\n return map(int, f)\n</code></pre>\n\n<p>or, if that’s more to your fancy:</p>\n\n<pre><code>def read_integers(filename):\n with open(filename) as f:\n return [int(x) for x in f]\n</code></pre>\n\n<p>A <code>file</code> object is simply iterable in Python, and iterates over its lines.</p>\n\n<p>Note that, contrary to what I said earlier, wrapping the file object in a <code>with</code> block is highly recommended. <a href=\"http://docs.python.org/reference/datamodel.html\">Python doesn’t actually guarantee (although it recommends it) that objects are disposed of automatically at the end of the scope.</a> Worse, it’s not guaranteed that a <code>file</code> object that is collected actually closes the underlying stream.</p>\n\n<p>(Note that I’ve adapted the method name to Python conventions.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-11T06:02:14.347", "Id": "20084", "Score": "0", "body": "Thx for your answer :) I didn't think of using map here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-10T20:16:41.270", "Id": "12449", "ParentId": "12443", "Score": "16" } } ]
<p>The "vectorizing" of fancy indexing by Python's NumPy library sometimes gives unexpected results.</p> <p>For example:</p> <pre><code>import numpy a = numpy.zeros((1000,4), dtype='uint32') b = numpy.zeros((1000,4), dtype='uint32') i = numpy.random.random_integers(0,999,1000) j = numpy.random.random_integers(0,3,1000) a[i,j] += 1 for k in xrange(1000): b[i[k],j[k]] += 1 </code></pre> <p>It gives different results in the arrays '<code>a</code>' and '<code>b</code>' (i.e. the appearance of tuple (i,j) appears as 1 in '<code>a</code>' regardless of repeats, whereas repeats are counted in '<code>b</code>').</p> <p>This is easily verified as follows:</p> <pre><code>numpy.sum(a) 883 numpy.sum(b) 1000 </code></pre> <p>It is also notable that the fancy indexing version is almost two orders of magnitude faster than the <code>for</code> loop.</p> <p>Is there an efficient way for NumPy to compute the repeat counts as implemented using the for loop in the provided example?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T16:39:59.470", "Id": "20140", "Score": "0", "body": "I'm not quite sure I understand the question. Wouldn't that always be the length of i and j? Is there a case where it isn't?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T17:06:15.043", "Id": "20141", "Score": "0", "body": "Nope. In the fancy indexing case, a[i,j] += 1, any repeated (i,j) combinations will only increment a[i,j] once. It is as if the right-hand side is evaluated all at once, a[:] + 1, where all values in 'a' are 0, and the result is saved back at once setting some values in 'a' to 1. In the for-loop case, b[i[k],j[k]] += 1, repeated (i,j) pairs each increment their count by 1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T18:10:20.700", "Id": "20142", "Score": "0", "body": "I see that the two indexing methods yield different results, but wouldn't the for-loop indexing always result in `numpy.sum(b) == j.size`? Because for each element in `i, j` some element of `b` is incremented once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T18:42:24.977", "Id": "20143", "Score": "0", "body": "Yes. The for-loop version of `b` always adds up to `j.size`. However, the result I need is the final counts in `b`. Is there a fast way to compute `b`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T18:45:25.990", "Id": "20144", "Score": "0", "body": "Ah, now I understand. You're not interested in `sum(b)`, but in `b` itself. Me blockhead today." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T18:55:53.613", "Id": "20145", "Score": "0", "body": "Some folks have suggested using `bincount()` with various reshapings. I should have mentioned that I made my example much smaller than the actual dataset I am working with. In my case `b` is a `memmap()` with > (2*10**9,4) entries, and the `i,j` combinations are only a few million with frequent repeats. My point being that the 'bincount()' output will be very sparse, and expensive in terms of memory." } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-06-12T16:34:47.097", "Id": "12503", "Score": "2", "Tags": [ "python", "numpy" ], "Title": "Compound assignment operators in Python's NumPy library" }
12503
max_votes
[ { "body": "<p>Ben,</p>\n\n<p>The following modification to your code is a more accurate reflection of my larger problem:</p>\n\n<pre><code>\n\n from timeit import timeit\n import numpy\n\n # Dimensions\n ROWS = 10000000\n SAMPLES = 10000\n COLS = 4\n\n # Number of times to run timeit\n TEST_COUNT = 100 \n\n # Matrices\n a = numpy.zeros((ROWS, COLS), dtype='uint32')\n b = numpy.zeros((ROWS, COLS), dtype='uint32')\n c = numpy.zeros((ROWS, COLS), dtype='uint32')\n\n # Indices\n i = numpy.random.random_integers(0, ROWS - 1, SAMPLES)\n j = numpy.random.random_integers(0, COLS - 1, SAMPLES)\n\n # Fancy\n def fancy():\n a[i,j] += 1\n print \"Fancy:\", timeit(\"fancy()\", setup=\"from __main__ import fancy\", number=TEST_COUNT)\n\n # Loop\n def loop():\n for k in xrange(SAMPLES):\n b[i[k],j[k]] += 1\n print \"Loop:\", timeit(\"loop()\", setup=\"from __main__ import loop\", number=TEST_COUNT)\n\n # Flat\n def flat():\n flatIndices = i*COLS + j\n sums = numpy.bincount(flatIndices)\n c.flat[:len(sums)] += sums\n\n print \"Flat:\", timeit(\"flat()\", setup=\"from __main__ import flat\", number=TEST_COUNT)\n\n # Check that for_loop and custom are equivalent\n print \"Equivalent:\", (c == b).all()\n\n</code></pre>\n\n<p>With the exception that there are probably few samples that are actually repeated in this version. Let's ignore that difference for now. On my machine, your code gave the following timings:</p>\n\n<pre><code>\n\n Fancy: 0.109203100204\n Loop: 7.37937998772\n Flat: 126.571173906\n Equivalent: True\n\n</code></pre>\n\n<p>This slowdown is largely attributable to the large sparse array output by bincount().</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T21:50:10.363", "Id": "20155", "Score": "0", "body": "See the second edit in my post. I'm off to bed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T21:02:34.803", "Id": "12507", "ParentId": "12503", "Score": "1" } } ]
<p>The goal with this function is to find one DNA sequence within another sequence, with a specified amount of mismatch tolerance. For example:</p> <ul> <li><code>dnasearch('acc','ccc',0)</code> shouldn't find a match, while</li> <li><code>dnasearch('acc','ccc',1)</code> should find one.</li> </ul> <p><strong>EDIT:</strong> Function should also be able to find pat sequence in a sequence larger than the pat sequence; furthermore it should be able to find multiple matches within that sequence if they exist. For example, <code>dnasearch('acc','acaaatc',1)</code> would find two matches: 'aca' and 'act'. Thanks to @weronika for pointing this out.</p> <p>Here's my working draft:</p> <pre><code>def dnasearch(pat,seq,mismatch_allowed=0): patset1=set([pat]) patset2=set([pat]) for number in range(mismatch_allowed): for version in patset1: for a in range(len(version)): for letter in 'actg': newpat=version[:a]+letter+version[a+1:] patset2.add(newpat) patset1|=patset2 for n in patset1: if seq.find(n) != -1: print 'At position', seq.find(n),\ 'found',n </code></pre> <p>I was wondering how to write this function:</p> <ol> <li>With fewer for-loops.</li> <li>Without the second <code>patset</code>. Originally I tried just adding new patterns to <code>patset1</code>, but I got the error: <code>RuntimeError: Set changed size during iteration.</code></li> <li>Simpler in any other way.</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T08:42:02.887", "Id": "20170", "Score": "1", "body": "Do you mean http://en.wikipedia.org/wiki/Levenshtein_distance (insertion, deletion, or substitution of a single character)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T19:01:15.993", "Id": "20219", "Score": "0", "body": "You need to add a few more examples to clarify the problem, I think. It's unclear from the current examples what should happen when the two input sequences are different lengths." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T10:20:41.573", "Id": "20245", "Score": "0", "body": "Look like InterviewStreet puzzle [\"Save Humanity\"](https://www.interviewstreet.com/challenges/dashboard/#problem/4f304a3d84b5e) :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T19:34:21.383", "Id": "20285", "Score": "0", "body": "2012: where the words \"simple\" and \"DNS sequence finder\" appear in the same sentence." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T08:19:34.183", "Id": "12522", "Score": "12", "Tags": [ "python", "bioinformatics" ], "Title": "Simple DNA sequence finder w/ mismatch tolerance" }
12522
max_votes
[ { "body": "<p>This is a solved problem in bioinformatics and there are specific algorithms depending on your specific use-case:</p>\n\n<ul>\n<li>Do you allow gaps?</li>\n<li>How many mismatches do gaps incur?</li>\n<li>… etc.</li>\n</ul>\n\n<p>In the general case, this is a <a href=\"http://en.wikipedia.org/wiki/Sequence_alignment#Global_and_local_alignments\" rel=\"nofollow\">global pairwise alignment</a> which is computed by the <a href=\"http://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm\" rel=\"nofollow\">Needleman–Wunsch algorithm</a>. If you are just interested in the score of the alignment, rather than the complete alignment, this can be simplified by not performing the backtracking.</p>\n\n<p>Now, if you have a threshold and are only interested in finding matches below said threshold, then a more efficient variant employs the Ukkonen trick – unfortunately, references for this are hard to find online, and the print literature is quite expensive. But what it does is essentially break the recurrence in the above-mentioned algorithm once the score exceeds the threshold chosen before (using the insight that the error score can only <em>increase</em>, never <em>decrease</em> in a given column).</p>\n\n<p><strong>But</strong> all this is unnecessary if you don’t allow gaps. In that case, the algorithm is as straightforward as walking over both strings at once and looking whether the current positions match.</p>\n\n<p>And this can be expressed in a single line:</p>\n\n<pre><code>def distance(a, b):\n return sum(map(lambda (x, y): 0 if x == y else 1, zip(a, b)))\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>def distance_less_than(k, a, b):\n return distance(a, b) &lt; k\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T19:24:10.143", "Id": "20220", "Score": "0", "body": "Thanks for the answer Konrad--I love the distance function in your answer. I did forget an important detail in my question though, pointed out by weronika, which is that the function should also be able to find the pattern sequence in a sequence larger than itself. And yes, I'm not worrying about gaps for the time being." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-07T12:30:52.063", "Id": "155283", "Score": "0", "body": "The distance function can be written more simply\n\n `def distance(a, b):\n return sum(x == y for x, y in zip(a, b)))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-07T14:08:14.423", "Id": "155295", "Score": "0", "body": "@Caridorc That’s indeed correct. However, I prefer not muddling boolean and numeric types. In fact, I wish Python *wouldn’t* allow your solution, because it relies on weak typing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-07T15:14:53.453", "Id": "155317", "Score": "0", "body": "That is impossibile because Python is strongly typed, bool is a subset of int." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-07T15:28:33.007", "Id": "155320", "Score": "1", "body": "@Caridorc “strongly typed” is a relative, not an absolute statement. Python is indeed relatively strongly typed (compared to other languages), which is why I have zero tolerance for this “a bool is an integer” nonsense. Logically, a boolean is a quite distinct concept from a nominally unbounded integer number, and it rarely makes sense to treat one as a subtype of the other (in fact, it leads to a ton of nonsense; case in point: if we treat booleans as numbers then they are obviously a ring modulo 2 and `True+True` should either be `False` or `True`, not 2, because of modular arithmetic rules)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-13T14:53:48.733", "Id": "12542", "ParentId": "12522", "Score": "4" } } ]
<p>Is there a way to speed up the following python code:</p> <pre><code>auxdict = {0:0} divdict = {} def divisors(n): divisors = [] for i in range(1, int(n**0.5) + 1): if (n % i == 0): divisors.extend([i, n/i]) divisors = list(set(divisors)) divisors.sort() return divisors def aux(k): if k in auxdict: return auxdict[k] else: if not k in divdict: divdict[k] = divisors(k) r = sum(map(aux, divdict[k][:len(divdict[k])-1])) auxdict[k] = (k+1)**3 - k**3 - r return auxdict[k] def lines(k): result = 0 for i in range(int(k/2),0,-1): result += int(k/i-1) * aux(i) return (k+1)**3 - result - 1 for i in [10**6, 10**10]: print i, lines(i) </code></pre> <p>It is a modified version of a Mathematica code I found. The code finds the maximum number of distinct lines in a 3D cube of lattices of size n: <a href="http://oeis.org/A090025" rel="nofollow">http://oeis.org/A090025</a></p> <p>The problem is the code is very slow and doesn't work for larger values. I want to evaluate lines(10**10)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:22:19.933", "Id": "20262", "Score": "5", "body": "Um, that first for loop will go over `10 ** 10 / 2` values; even if you could get each call to `aux` down to a millisecond that'd take two months. You'll need a different algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:23:41.667", "Id": "20263", "Score": "0", "body": "What OS is this to be run on?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:24:23.320", "Id": "20264", "Score": "0", "body": "@Vijay I'm running Mac OS X 10.6 .. Does the OS type matter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:26:36.300", "Id": "20265", "Score": "2", "body": "You probably want to use `xrange` instead of `range` so you don't have a list of 5 billion integers. Not that it will help *all* that much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:26:49.900", "Id": "20266", "Score": "0", "body": "In Linux you could so something like: \nsort myfile.txt | uniq -uc <- call that using \"subprocess.Popen\", I assume in OSX there is a similar function... Assuming they are actually stored in \"lines\" in a file ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:30:52.833", "Id": "20267", "Score": "0", "body": "How/where is this data stored before you have it in PY?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:37:01.860", "Id": "20268", "Score": "0", "body": "there are better algorithm on the oeis page you linked" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:42:39.147", "Id": "20269", "Score": "0", "body": "@Wooble I used xrange .. still very slow" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:42:56.773", "Id": "20270", "Score": "0", "body": "@Vijay I'm not storing any data. As Dougal mentioned, the algorithm itself is slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:43:08.710", "Id": "20271", "Score": "0", "body": "@Simon Which one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:46:38.643", "Id": "20272", "Score": "0", "body": "@OsamaGamal I thought that perhaps you were reading the data in from a file, if you were then I would have another idea on how you could speed it up, where would the data originate from when this method is executed in the real world?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:51:37.097", "Id": "20273", "Score": "0", "body": "@Vijay Check this: http://projecteuler.net/problem=388" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:56:42.230", "Id": "20274", "Score": "1", "body": "`a(n) = Sum(moebius(k)*((floor(n/k)+1)^3-1), k=1..n)` Don't know if it is correct though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T17:05:36.607", "Id": "20275", "Score": "0", "body": "@OsamaGamal I'll whip something up... Or I'll find my PE login and grab my old solution :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T17:38:17.920", "Id": "20277", "Score": "0", "body": "Don't you get overflow error with 10**10? I do..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T17:39:56.060", "Id": "20278", "Score": "0", "body": "My laptop hangs and start asking for force closing apps after a while :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T18:03:49.027", "Id": "20279", "Score": "0", "body": "@Wooble EDIT: You are right. I was thinking he could use a parallel algorithm, and I would have swore Amazon offer distributed computing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T19:21:02.530", "Id": "20281", "Score": "1", "body": "use `sqrt(n)` instead of `n**0.5`. It's a bit faster" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T19:31:16.463", "Id": "20284", "Score": "1", "body": "Also, if you are using python 2.x, integer division is the default. There is no need to type cast k/2 as `int()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T19:58:40.203", "Id": "20295", "Score": "0", "body": "@JoelCornett It's far better to do `k // 2` than using `k / 2` as integer division." } ]
{ "AcceptedAnswerId": "12588", "CommentCount": "20", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T16:19:07.707", "Id": "12587", "Score": "3", "Tags": [ "python" ], "Title": "Speeding up an algorithm for finding the number of distinct lines" }
12587
accepted_answer
[ { "body": "<p>You can improve your divisors function:</p>\n\n<p><strong>Version 1:</strong> (not includes n)</p>\n\n<pre><code>def divisors(n):\n \"\"\"Return the divisors of n (including 1)\"\"\"\n if(n == 1):\n return (0)\n\n divs = set([1])\n r = floor(sqrt(n))\n if(r**2 == n):\n divs.add(r)\n\n f = 2\n step = 1\n if(n &amp; 1 == 1):\n f = 3\n step = 2\n\n while(f &lt;= r):\n if(n % f == 0):\n divs.add(n/f)\n divs.add(f)\n f = f + step\n\n return sorted(divs)\n</code></pre>\n\n<p><strong>Version 2:</strong> (includes n) from <a href=\"http://numericalrecipes.wordpress.com/2009/05/13/divisors/\" rel=\"nofollow\">here</a></p>\n\n<pre><code>def divisors2(n) :\n \"\"\"\n Generates all divisors, unordered, from the prime factorization.\n \"\"\"\n factors = factorI(n)\n ps = sorted(set(factors))\n omega = len(ps)\n\n def rec_gen(n = 0) :\n if n == omega :\n yield 1\n else :\n pows = [1]\n for j in xrange(factors.count(ps[n])) :\n pows += [pows[-1] * ps[n]]\n for q in rec_gen(n + 1) :\n for p in pows :\n yield p * q\n\n for p in rec_gen() :\n yield p\n</code></pre>\n\n<p>where <code>factorI</code> is:</p>\n\n<pre><code>def factorI(n):\n \"\"\"Returns the factors of n.\"\"\"\n lst = []\n num = int(n)\n if(num &amp; 1 == 0):\n lst.append(2)\n num /= 2\n while(num &amp; 1 == 0):\n lst.append(2)\n num /= 2\n\n factor = 3\n maxFactor = sqrt(num)\n while num&gt;1 and factor &lt;= maxFactor:\n if(num % factor == 0):\n num /= factor\n lst.append(factor)\n while(num % factor == 0):\n lst.append(factor)\n num /= factor\n maxFactor = sqrt(num)\n factor += 2\n\n if(num &gt; 1):\n lst.append(num)\n return lst\n</code></pre>\n\n<p>For efficiency reasons you could also make generator functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T19:26:08.733", "Id": "20283", "Score": "0", "body": "I tried it .. It's 20seconds slower than mine for solving N=10**6 .. I'm not sure why" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T19:51:25.987", "Id": "20292", "Score": "0", "body": "@OsamaGamal: There's an extra `pow()` operation at the beginning of this one. Also, the while loop is slower than iterating over the elements of `range()` or `xrange()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-15T05:16:06.653", "Id": "20331", "Score": "0", "body": "Thats kind of weird. The first pow operations is just for checking for perfect squares. But the while loop must be faster, due to the heavily reduced interations. I will have a look at it if i found some time" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-15T05:41:48.087", "Id": "20333", "Score": "0", "body": "Ok. Found another algorithm based on factorization. Will updating the post..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T14:59:25.073", "Id": "21071", "Score": "0", "body": "That's better. Now it is running a little bit faster for 10**6. I just had to update the line number 5 in the aux(k) function to: divdict[k] = sorted(list(divisors(k)))" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T18:10:38.157", "Id": "12588", "ParentId": "12587", "Score": "1" } } ]
<p>I am wondering if anyone has any ideas for improving the following. Personally I am 'happy' with it, apart from the first <code>for</code> loop. I was thinking of another way of writing this, but perhaps it is ok.</p> <pre><code>def findnodepaths(nodepaths, graph, *nodes): # nodepaths == list() # graph == defaultdict(set) # *nodes == 'foo','bar',... possible items in the graph nodeset = set(nodes) &amp; set(graph.keys()) # nodeset == nodes that are in the graph ... avoids try / if nodepaths = [(nodeA,weight,nodeB) for nodeA in nodeset for (nodeB,weight) in graph[nodeA]] for path in nodepaths: # for every item in list *xs, nodeA = path # nodeA == last value added, xs == all the rest for (nodeB,weight) in graph[nodeA]: # search again ... just like we all ready have if nodeB not in xs: # if new val not in the triple / quadruple ... nodepaths.append( path + (weight,nodeB) ) # add new item to list based on its match # repeat until no new paths can be found return nodeset, nodepaths # return nodes that were found + all of their paths </code></pre>
[]
{ "AcceptedAnswerId": "12645", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-16T20:40:44.093", "Id": "12641", "Score": "1", "Tags": [ "python", "pathfinding" ], "Title": "Finding node paths" }
12641
accepted_answer
[ { "body": "<pre><code>def findnodepaths(nodepaths, graph, *nodes):\n</code></pre>\n\n<p>By python convention, you should really separate the words with underscores. i.e. <code>find_node_paths</code>. I'd also wonder if it makes sense to take *nodes, rather then expecting a list to be sent in. </p>\n\n<pre><code># nodepaths == list()\n</code></pre>\n\n<p>Its not clear why you pass this in, rather then just make it here</p>\n\n<pre><code># graph == defaultdict(set)\n# *nodes == 'foo','bar',... possible items in the graph\n</code></pre>\n\n<p>This sort of documentation should be in a doctoring, not comments</p>\n\n<pre><code> nodeset = set(nodes) &amp; set(graph.keys())\n</code></pre>\n\n<p><code>set(graph.keys()) == set(graph)</code>, although you may prefer to be explicit. </p>\n\n<pre><code># nodeset == nodes that are in the graph ... avoids try / if \n\n nodepaths = [(nodeA,weight,nodeB) for nodeA in nodeset for (nodeB,weight) in graph[nodeA]]\n</code></pre>\n\n<p>I'd store a path as a list, not a tuple. </p>\n\n<pre><code> for path in nodepaths:\n# for every item in list\n</code></pre>\n\n<p>That's not a very helpful comment, the syntax already told me that.</p>\n\n<pre><code> *xs, nodeA = path\n# nodeA == last value added, xs == all the rest\n</code></pre>\n\n<p>consider renaming your variable rather then using comments</p>\n\n<pre><code> for (nodeB,weight) in graph[nodeA]:\n</code></pre>\n\n<p>Parens are unnecessary</p>\n\n<pre><code># search again ... just like we all ready have\n</code></pre>\n\n<p>Again, noisy comment</p>\n\n<pre><code> if nodeB not in xs:\n# if new val not in the triple / quadruple ...\n nodepaths.append( path + (weight,nodeB) )\n</code></pre>\n\n<p>You shouldn't be modifying lists currently having a for loop operating on them. Its considered bad style</p>\n\n<pre><code># add new item to list based on its match\n# repeat until no new paths can be found\n\n return nodeset, nodepaths\n# return nodes that were found + all of their paths\n</code></pre>\n\n<p>I'd write this as a recursive function:</p>\n\n<pre><code>def _findnodepaths(graph, path, weights):\n for node, weight in graph[path[-1]]:\n if node not in path:\n yield _findnodepaths(graph, path + [node], weights + [node])\n yield path\n\ndef findnodepaths(graph, nodes):\n nodeset = set(nodes) &amp; set(graph)\n subgraph = dict( (key, value) for key, value in graph.items())\n\n nodepaths = []\n for key in graph:\n nodepaths.extend(_findnodepaths(subgraph, [key], [])\n return nodeset, node paths\n</code></pre>\n\n<p>Whether that's better or not is subjective, I think it shows the algorithm better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-17T00:55:06.767", "Id": "20384", "Score": "0", "body": "thanks for the break down. I must admit the documentation was only for this site. I'm interested in your comment about modifying lists while working on them. That part made me happy :) ... is it a purely stylistic guide? Agree about the list being passed in. I have changed that already. Thank you for the re-write. It is fascinating seeing how others would approach a problem. Algorithm wise, does it seem ok though?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-17T01:16:16.577", "Id": "20385", "Score": "0", "body": "one question: why are you creating a subgraph? if the graph contains 1000 keys, this is a bit pointless no? am i missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-17T01:36:04.050", "Id": "20386", "Score": "0", "body": "@user969617, adding to the list works in the current implementation, but I believe no guarantees are made that it will always work. I figured the subgraph might simplify the code a bit, but it didn't really work out that way." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-17T00:24:26.433", "Id": "12645", "ParentId": "12641", "Score": "3" } } ]