body
stringlengths
144
5.58k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have this prime factor generator for some number <code>n</code>. It returns list of all prime factors. In other words, product of the list equals <code>n</code>.</p> <pre><code>def prime_factors_generate(n): a = [] prime_list = sorted(primes()) pindex = 0 p = prime_list[pindex] num = n while p != num: if num % p == 0: a.append(p) num //= p else: pindex += 1 p = prime_list[pindex] return a </code></pre> <p>The <code>primes()</code> function uses the <a href="http://plus.maths.org/content/os/issue50/features/havil/index" rel="nofollow noreferrer">Sundaram Sieve</a> from <a href="https://stackoverflow.com/a/2073279/596361">here</a> and returns a <em>set</em> of all primes below some limit, by default 10<sup>6</sup>.</p> <p>How can I make this code functional? I want to get rid of the <code>while</code>-loop, list appending and mutated state.</p>
[]
[ { "body": "<p>The implementation of sundaram's sieve that you've mentioned returns primes in sorted order. So, <code>sorted()</code> is not needed.</p>\n\n<p>Also, it is best to define <code>prime_list = primes()</code> outside the definition of <code>prime_factors_generate</code> (This will reduce calls to primes()). You can argue that that will make the code less functional but that would be nitpicking [Even the definition of primes() isn't functional]</p>\n\n<hr>\n\n<p>EDIT: As pointed out in a comment by mteckert, my earlier solution will not provide the desired result. This EDIT will work though (It'll return [2, 2, 2, 3] instead of [2, 3] for prime_factors_generate(24))</p>\n\n<pre><code>def max_pow(n, x):\n if n%x == 0:\n return max_pow(n/x, x)+1\n else:\n return 0\n\ndef prime_factors_generate(n): #Variables added just for convenience. Can be removed.\n prime_list = primes()\n nested_ans = map(lambda x: [x]*max_pow(n, x), prime_list)\n ans = [item for sublist in nested_ans for item in sublist]\n return ans\n</code></pre>\n\n<p>One liners (if you're interested in them) for max_pow and prime_factors generator:</p>\n\n<pre><code>max_pow = lambda n, x: max_pow(n/x, x)+1 if n%x==0 else 0\nprime_factors_generate = lambda n: [item for sublist in map(lambda x: [x]*max_pow(n, x), primes()) for item in sublist]\n</code></pre>\n\n<p>End of EDIT. I'm leaving my earlier solution intact (which returns [2, 3] for prime_factors_generate(24)).</p>\n\n<hr>\n\n<p>This should work:</p>\n\n<pre><code>def prime_factors_generate(n): #Variables added just for convenience. Can be removed.\n prime_list = primes()\n prime_factors = filter(lambda x: n % x == 0, prime_list)\n return prime_factors\n</code></pre>\n\n<p>Or if you're into one liners:</p>\n\n<pre><code>prime_factors_generate = lambda n: filter(lambda x: n % x == 0, primes())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T06:19:20.710", "Id": "31252", "Score": "0", "body": "Your code finds prime factors, but since the problem requires that the \"product of the list equals `n`,\" a full prime factorization is necessary. For example, `f(100)` should return `[2, 2, 5, 5]` and not `[2, 5]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T07:07:44.917", "Id": "31254", "Score": "0", "body": "Yeah. sorry about this. Will edit shortly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T09:46:22.260", "Id": "31259", "Score": "0", "body": "Yeah, just found list comprehensions in http://docs.python.org/2/howto/functional.html Will modify codes appropriately." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T13:57:20.437", "Id": "31263", "Score": "0", "body": "@mteckert This is a comment on your solution - not enough reputation to comment directly. 1) Although primes need not be computed to get the correct answer, computing them and running over them alone will be faster. 2) If given the input p^q where p is a large prime, each recursive call will run from 2 to p. This can be avoided by using an auxiliary function that takes the number to start checking from as input, i.e., instead of `(x for x in range(2, ceil(sqrt(n))+1) if n%x == 0)` you can use `(x for x in range(s, ceil(sqrt(n))+1) if n%x == 0)` where s is an input to the aux. function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T00:58:34.110", "Id": "31307", "Score": "0", "body": "While there are many ways to optimize the code the focus is on making it more functional, not more performant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T05:18:33.793", "Id": "31315", "Score": "0", "body": "@mteckert I understand. But I feel that your implementation changes the identity of the original code, in the sense that the underlying algo. has changed. Instead of checking from 2 to 1st factor, then from 1st factor to 2nd..., you're doing 2 to 1st, 2 to 2nd... Kind of similar to implementing merge-sort in FP when asked to implement some other sorting algo. Just wanted to point out that this is not unavoidable in this case. Introducing an aux. function to your code won't make it any less functional and will implement the original algo. Just my opinion though." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T05:56:47.910", "Id": "19521", "ParentId": "19509", "Score": "2" } }, { "body": "<p>There are a few things you can do to make your code more functional. First note that it isn't necessary to have a list of primes beforehand. As you eliminate factors from the bottom up, there cannot be a composite \"false positive\" since its prime factors will have been accounted for already. </p>\n\n<p>Here is a more functional version of your code:</p>\n\n<pre><code>from math import ceil, sqrt\n\ndef factor(n):\n if n &lt;= 1: return []\n prime = next((x for x in range(2, ceil(sqrt(n))+1) if n%x == 0), n)\n return [prime] + factor(n//prime)\n</code></pre>\n\n<p><strong>Generator expression</strong></p>\n\n<p>This is a <a href=\"http://docs.python.org/3.3/tutorial/classes.html#generator-expressions\" rel=\"nofollow\">generator expression</a>, which is a <a href=\"http://docs.python.org/3.3/tutorial/classes.html#generators\" rel=\"nofollow\">generator</a> version of <a href=\"http://docs.python.org/3.3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehensions</a>:</p>\n\n<pre><code>(x for x in range(2, ceil(sqrt(n))+1) if n%x == 0)\n</code></pre>\n\n<p>Note that in Python 2.7.3, <code>ceil</code> returns a <code>float</code> and <code>range</code> accepts <code>ints</code>.</p>\n\n<p>Basically, for every number from 2 to <code>ceil(sqrt(n))</code>, it generates all numbers for which <code>n%x == 0</code> is true. The call to <code>next</code> gets the first such number. If there are no valid numbers left in the expression, <code>next</code> returns <code>n</code>.</p>\n\n<p><strong>Recursion</strong></p>\n\n<p>This is a <a href=\"http://en.wikipedia.org/wiki/Recursion_%28computer_science%29\" rel=\"nofollow\">recursive</a> call, that appends to our list the results of nested calls:</p>\n\n<pre><code>return [prime] + factor(n//prime)\n</code></pre>\n\n<p>For example, consider <code>factor(100)</code>. Note that this is just a simplification of the call stack.</p>\n\n<p>The first prime will be 2, so:</p>\n\n<pre><code>return [2] + factor(100//2)\n</code></pre>\n\n<p>Then when the first recursive call is to this point, we have:</p>\n\n<pre><code>return [2] + [2] + factor(50//2)\nreturn [2] + [2] + [5] + factor(25//5)\nreturn [2] + [2] + [5] + [5] + factor(5//5)\n</code></pre>\n\n<p>When <code>factor</code> is called with an argument of <code>1</code>, it breaks the recursion and returns an empty list, at <code>if n &lt;= 1: return []</code>. This is called a <a href=\"http://en.wikipedia.org/wiki/Base_case\" rel=\"nofollow\">base case</a>, a construct vital to functional programming and mathematics in general. So finally, we have:</p>\n\n<pre><code>return [2] + [2] + [5] + [5] + []\n[2, 2, 5, 5]\n</code></pre>\n\n<p><strong>Generator version</strong></p>\n\n<p>We can create a generator version of this ourselves like this: </p>\n\n<pre><code>from math import ceil, sqrt\n\ndef factorgen(n):\n if n &lt;= 1: return\n prime = next((x for x in range(2, ceil(sqrt(n))+1) if n%x == 0), n)\n yield prime\n yield from factorgen(n//prime)\n</code></pre>\n\n<p>The keyword <code>yield</code> freezes the state of the generator, until <code>next</code> is called to grab a value. The <code>yield from</code> is just syntactic sugar for</p>\n\n<pre><code>for p in factorgen(n//prime):\n yield p\n</code></pre>\n\n<p>which was introduced in <a href=\"http://docs.python.org/3/whatsnew/3.3.html\" rel=\"nofollow\">Python 3.3</a>.</p>\n\n<p>With this version, we can use a for loop, convert to a list, call <code>next</code>, etc. Generators provide <a href=\"http://en.wikipedia.org/wiki/Lazy_evaluation\" rel=\"nofollow\">lazy evaluation</a>, another important tool in a functional programmer's arsenal. This allows you to create the \"idea\" for a sequence of values without having to bring it into existence all at once, so to speak.</p>\n\n<p>Though I didn't use it here, I can't resist mentioning a very nice Python library named <a href=\"http://docs.python.org/3.3/library/itertools.html\" rel=\"nofollow\"><code>itertools</code></a>, which can help you immensely with functional-style programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T07:09:21.173", "Id": "19523", "ParentId": "19509", "Score": "2" } } ]
{ "AcceptedAnswerId": "19523", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:46:03.297", "Id": "19509", "Score": "1", "Tags": [ "python", "algorithm", "functional-programming", "primes" ], "Title": "Functional prime factor generator" }
19509
<p>I have a function for finding factors of a number in Python</p> <pre><code>def factors(n, one=True, itself=False): def factors_functional(): # factors below sqrt(n) a = filter(lambda x: n % x == 0, xrange(2, int(n**0.5)+1)) result = a + map(lambda x: n / x, reversed(a)) return result </code></pre> <p><code>factors(28)</code> gives <code>[2, 4, 7, 14]</code>. Now i want this function to also include 1 in the beginning of a list, if <code>one</code> is true, and 28 in the end, if <code>itself</code> is true.</p> <pre><code>([1] if one else []) + a + map(lambda x: n / x, reversed(a)) + ([n] if itself else []) </code></pre> <p>This is "clever" but inelegant.</p> <pre><code>if one: result = [1] + result if itself: result = result + [n] </code></pre> <p>This is straight-forward but verbose.</p> <p>Is it possible to implement optional one and itself in the output with the most concise yet readable code possible? Or maybe the whole idea should be done some other way - like the function <code>factors</code> can be written differently and still add optional 1 and itself?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T03:46:51.630", "Id": "31249", "Score": "0", "body": "The straight forward way isn't that verbose. I don't see a different way to do it the doesn't sacrifice readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T04:34:05.523", "Id": "31250", "Score": "0", "body": "You may think it is verbose but it is self explanatory and can easily be commented out without messing around with the core code." } ]
[ { "body": "<p>What about this?</p>\n\n<pre><code>[1] * one + result + [n] * itself\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T05:37:14.763", "Id": "31316", "Score": "1", "body": "I was thinking `[1]*int(one) + result + [n]*int(itself)`, scrolled down and saw this beauty. Didn't know this could be done. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:47:22.787", "Id": "31370", "Score": "0", "body": "interesting... but please don't actually do this. \"Programs must be written for people to read and only incidentally for machines to execute.\" This takes me way longer to read than the 4-liner." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T12:37:44.743", "Id": "19528", "ParentId": "19510", "Score": "5" } } ]
{ "AcceptedAnswerId": "19528", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T23:15:37.983", "Id": "19510", "Score": "3", "Tags": [ "python", "functional-programming" ], "Title": "Function to find factors of a number, optionally including 1 and the number itself" }
19510
<p>I've got dictionary of lists of tuples. Each tuple has timestamp as first element and values in others. Timestamps could be different for other keys:</p> <pre><code>dict = { 'p2': [(1355150022, 3.82), (1355150088, 4.24), (1355150154, 3.94), (1355150216, 3.87), (1355150287, 6.66)], 'p1': [(1355150040, 7.9), (1355150110, 8.03), (1355150172, 8.41), (1355150234, 7.77)], 'p3': [(1355150021, 1.82), (1355150082, 2.24), (1355150153, 3.33), (1355150217, 7.77), (1355150286, 6.66)], } </code></pre> <p>I want this convert to list of lists:</p> <pre><code>ret = [ ['time', 'p1', 'p2', 'p3'], [1355149980, '', 3.82, 1.82], [1355150040, 7.9, 4.24, 2.24], [1355150100, 8.03, 3.94, 3.33], [1355150160, 8.41, 3.87, 7.77], [1355150220, 7.77, '', ''], [1355150280, '', 6.66, 6.66] ] </code></pre> <p>I'm making conversion with that dirty definition:</p> <pre><code>def convert_parameters_dict(dict): tmp = {} for p in dict.keys(): for l in dict[p]: t = l[0] - l[0] % 60 try: tmp[t][p] = l[1] except KeyError: tmp[t] = {} tmp[t][p] = l[1] ret = [] ret.append([ "time" ] + sorted(dict.keys())) for t, d in sorted(tmp.iteritems()): l = [] for p in sorted(dict.keys()): try: l.append(d[p]) except KeyError: l.append('') ret.append([t] + l) return ret </code></pre> <p>Maybe there is some much prettier way?</p>
[]
[ { "body": "<p>Have a look at <a href=\"http://pandas.pydata.org/\"><code>pandas</code></a>:</p>\n\n<pre><code>import pandas as pd\n\nd = {\n 'p2': [(1355150022, 3.82), (1355150088, 4.24), (1355150154, 3.94), (1355150216, 3.87), (1355150287, 6.66)],\n 'p1': [(1355150040, 7.9), (1355150110, 8.03), (1355150172, 8.41), (1355150234, 7.77)],\n 'p3': [(1355150021, 1.82), (1355150082, 2.24), (1355150153, 3.33), (1355150217, 7.77), (1355150286, 6.66)],\n} \n\nret = pd.DataFrame({k:pd.Series({a-a%60:b for a,b in v}) for k,v in d.iteritems()})\n</code></pre>\n\n<p>returns</p>\n\n<pre><code> p1 p2 p3\n1355149980 NaN 3.82 1.82\n1355150040 7.90 4.24 2.24\n1355150100 8.03 3.94 3.33\n1355150160 8.41 3.87 7.77\n1355150220 7.77 NaN NaN\n1355150280 NaN 6.66 6.66\n</code></pre>\n\n<p>It is not a list of lists, but using pandas you can do much more with this data (such as convert the unix timestamps to datetime objects with a single command).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:56:17.853", "Id": "31323", "Score": "0", "body": "Wow, now that is slick!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:55:33.260", "Id": "19573", "ParentId": "19572", "Score": "7" } }, { "body": "<p>How about...</p>\n\n<pre><code>times = sorted(set(int(y[0] / 60) for x in d.values() for y in x))\ntable = [['time'] + sorted(d.keys())]\nfor time in times:\n table.append([time * 60])\n for heading in table[0][1:]:\n for v in d[heading]:\n if int(v[0] / 60) == time:\n table[-1].append(v[1])\n break\n else:\n table[-1].append('')\nfor row in table:\n print row\n</code></pre>\n\n<p>Or, less readable but probably faster if the dictionary is long (because it only loops through each list in the dictionary once):</p>\n\n<pre><code>times = sorted(set(int(v2[0] / 60) for v in d.values() for v2 in v))\nempty_row = [''] * len(d)\ntable = ([['time'] + sorted(d.keys())] + \n [[time * 60] + empty_row for time in times])\nfor n, key in enumerate(table[0][1:]):\n for v in d[key]:\n if int(v[0] / 60) in times:\n table[times.index(v[0] / 60) + 1][n + 1] = v[1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T09:28:07.727", "Id": "31324", "Score": "0", "body": "Thank you all. Stuart, I'll use your second solution. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T08:47:45.800", "Id": "19574", "ParentId": "19572", "Score": "1" } } ]
{ "AcceptedAnswerId": "19574", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:50:28.937", "Id": "19572", "Score": "6", "Tags": [ "python", "hash-map" ], "Title": "Convert dictionary of lists of tuples to list of lists/tuples in python" }
19572
<p>This reads a list of points from a file with a certain format:</p> <blockquote> <pre><code>&lt;number of points&gt; x1 y1 x2 y2 </code></pre> </blockquote> <p>How I can make it better?</p> <pre><code>from collections import namedtuple Point = namedtuple('Point ', ['x', 'y']) def read(): ins = open("PATH_TO_FILE", "r") array = [] first = True expected_length = 0 for line in ins: if first: expected_length = int(line.rstrip('\n')) first = False else: parsed = line.rstrip('\n').split () array.append(Point(int(parsed[0]), int(parsed[1]))) if expected_length != len(array): raise NameError("error on read") return array </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T03:25:21.697", "Id": "31365", "Score": "0", "body": "If you're dealing with points you might want to use a library like Shapely, which will give you a nice Point object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T09:46:38.313", "Id": "31375", "Score": "0", "body": "@monkut, thx I'll see." } ]
[ { "body": "<p>You don't need all that <code>expected_length</code> and <code>first=True</code> stuff. You can treat a file as an iterator, and it will return objects until it quits, so you can just use the <code>.next()</code> method and throw item away, or save it to a variable if you wish. In that sense, it's best to write two functions-- one to deal with the file, and another to deal with a single line as provided by the file object. </p>\n\n<pre><code>def lineparse(line):\n ''' Parses a single line. '''\n # your code goes here\n\ndef fileparse(filepath):\n f = open(filepath, \"r\")\n n = int(f.next()) # this also advances your iterator by one line\n while True: \n yield lineparse(f.next())\n f.close()\n\ndata = list(fileparse(filepath))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T03:54:29.167", "Id": "31366", "Score": "0", "body": "`expected_length` is a check that the supposed length of the array equals the amount of data, you can't just ignore it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:08:18.050", "Id": "31367", "Score": "0", "body": "Ah ignore me, I've just noticed you use `n =` to get the expected length. Still a bit confusing that you say you don't need `expected_length` though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T23:26:20.563", "Id": "19594", "ParentId": "19588", "Score": "3" } }, { "body": "<p>Not that big a change but you don't need to worry about stripping out <code>\\n</code>s as the <code>split</code> and <code>int</code> functions will take care of that. Secondly, as already pointed out, you can grab the first line by just calling <code>.next()</code> then use a loop for the remaining lines.</p>\n\n<pre><code>def read():\n ins = open(\"FILE\", \"r\")\n array = []\n expected_length = int(ins.next())\n for line in ins:\n parsed = line.split()\n array.append(Point(int(parsed[0]), int(parsed[1])))\n if expected_length != len(array):\n raise NameError('error on read')\n ins.close()\n return array\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:10:47.597", "Id": "19600", "ParentId": "19588", "Score": "3" } }, { "body": "<p>Another improvement is to use <code>open</code> as a context manager so that you don't have to remember to <code>.close()</code> the file object even if there are errors while reading.</p>\n\n<pre><code>def read():\n with open(\"FILE\", \"r\") as f:\n array = []\n expected_length = int(f.next())\n for line in f:\n parsed = map(int, line.split())\n array.append(Point(*parsed))\n if expected_length != len(array):\n raise NameError('error on read')\n return array\n</code></pre>\n\n<p>See <a href=\"http://docs.python.org/2/library/stdtypes.html#file.close\" rel=\"nofollow\">http://docs.python.org/2/library/stdtypes.html#file.close</a> for more details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:28:24.557", "Id": "19602", "ParentId": "19588", "Score": "4" } } ]
{ "AcceptedAnswerId": "19602", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T19:52:28.513", "Id": "19588", "Score": "3", "Tags": [ "python", "file" ], "Title": "Reading data from file" }
19588
<p>I have a nested <code>for</code>-loop that populates a list with elements:</p> <pre><code>a = [] for i in range(1, limit+1): for j in range(1, limit+1): p = i + j + (i**2 + j**2)**0.5 if p &lt;= limit: a.append(p) </code></pre> <p>I could refactor it into list comprehension:</p> <pre><code>a = [i + j + (i**2 + j**2)**0.5 for i in range(1, limit+1) for j in range(1, limit+1) if i + j + (i**2 + j**2)**0.5 &lt;= limit] </code></pre> <p>But now the same complex expression is in both parts of it, which is unacceptable. Is there any way to create a list in a functional way, but more elegantly?</p> <p>I guess in Lisp I would use recursion with <code>let</code>. How it is done in more functional languages like Clojure, Scala, Haskell?</p> <p>In Racket it's possible to <a href="https://stackoverflow.com/q/14979231/596361">bind expressions</a> inside a <code>for/list</code> comprehension. I've found one solution to my problem:</p> <pre><code>[k for i in range(1, limit+1) for j in range(1, limit+1) for k in [i + j + (i**2 + j**2)**0.5] k &lt;= limit] </code></pre> <p>I'm not sure how pythonic it is.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T18:56:55.870", "Id": "31637", "Score": "0", "body": "Just pointing out that you can divide limit by 2 in the range function (since you square the numbers anyway) and you'll still get the full set of results. Also, I would write a `transform` function that handled the math and run a list comprehension over it." } ]
[ { "body": "<p>You can rewrite it with two separate comprehensions. One to generate the values and one to filter them out. You can use <a href=\"http://docs.python.org/2/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a> to get the cartesian product.</p>\n\n<pre><code>a = [x for x in (i + j + (i**2 + j**2)**0.5\n for i, j in itertools.product(range(1, limit+1), repeat=2))\n if x &lt;= limit]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T15:29:31.167", "Id": "19612", "ParentId": "19611", "Score": "3" } }, { "body": "<p>In the general case, Jeff's answer is the way to go : generate then filter.</p>\n\n<p>For your particular example, since the expression is increasing wrt both variables, you should stop as soon as you reach the limit.</p>\n\n<pre><code>def max_value(limit, i) :\n \"\"\"return max positive value one variable can take, knowing the other\"\"\"\n if i &gt;= limit :\n return 0\n return int(limit*(limit-2*i)/(2*(limit-i)))\n\ndef collect_within_limit(limit) :\n return [ i + j + (i**2 + j**2)**0.5\n for i in range(1,max_value(limit,1)+1)\n for j in range(1,max_value(limit,i)+1) ]\n</code></pre>\n\n<p>Now, providing this <code>max_value</code> is error prone and quite ad-hoc. We would want to keep the stopping condition based on the computed value. In your imperative solution, adding <code>break</code> when <code>p&gt;limit</code> would do the job. Let's find a functional equivalent :</p>\n\n<pre><code>import itertools\n\ndef collect_one_slice(limit,i) :\n return itertools.takewhile(lambda x: x &lt;= limit,\n (i + j + (i**2 + j**2)**0.5 for j in range(1,limit)))\n\ndef collect_all(limit) :\n return list(itertools.chain(*(collect_one_slice(limit, i)\n for i in range(1,limit))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T18:25:30.887", "Id": "19948", "ParentId": "19611", "Score": "3" } } ]
{ "AcceptedAnswerId": "19948", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T14:31:14.840", "Id": "19611", "Score": "5", "Tags": [ "python", "combinatorics" ], "Title": "Finding perimeters of right triangles with integer-length legs, up to a limit" }
19611
<p>Pythonic way of expressing the simple problem:</p> <blockquote> <p>Tell if the list <code>needle</code> is sublist of <code>haystack</code></p> </blockquote> <hr> <pre><code>#!/usr/bin/env python3 def sublist (haystack, needle): def start (): i = iter(needle) return next(i), i try: n0, i = start() for h in haystack: if h == n0: n0 = next(i) else: n0, i = start() except StopIteration: return True return False </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T03:27:04.163", "Id": "31422", "Score": "0", "body": "So, what's the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T12:30:16.977", "Id": "31427", "Score": "0", "body": "@JeffVanzella: Fair point. That's \"code review\". The question is: \"what do you think in general?\"." } ]
[ { "body": "<h3>1. Bug</h3>\n\n<p>Here's a case where your function fails:</p>\n\n<pre><code>&gt;&gt;&gt; sublist([1, 1, 2], [1, 2])\nFalse\n</code></pre>\n\n<p>this is because in the <code>else:</code> case you go back to the beginning of the needle, but you keep going forward in the haystack, possibly skipping over a match. In the test case, your function tries matching with the alignment shown below, which fails at the position marked <code>X</code>:</p>\n\n<pre><code> X\nhaystack 1,1,2\nneedle 1,2\n</code></pre>\n\n<p>Then it starts over from the beginning of the needle, but keeps going forward in the haystack, thus missing the match:</p>\n\n<pre><code> X\nhaystack 1,1,2\nneedle 1,2\n</code></pre>\n\n<p>So after a mismatch you need to go <em>backward</em> an appropriate distance in the haystack before starting over again from the beginning of the needle.</p>\n\n<h3>2. A better algorithm</h3>\n\n<p>It turns out to be better to start matching from the <em>end</em> of the needle. If this fails to match, we can skip forward several steps: possibly the whole length of the needle. For example, in this situation:</p>\n\n<pre><code> X\nhaystack 1,2,3,4,6,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>we can skip forward by the whole length of the needle (because <code>6</code> does not appear in the needle). The next alignment we need to try is this:</p>\n\n<pre><code> O O O O O\nhaystack 1,2,3,4,6,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>However, we can't always skip forward the whole length of the needle. The distance we can skip depends on the item that fails to match. In this situation:</p>\n\n<pre><code> X\nhaystack 1,2,3,4,1,2,3,4,5\nneedle 1,2,3,4,5\n</code></pre>\n\n<p>we should skip forward by 4, to bring the <code>1</code>s into alignment.</p>\n\n<p>Making these ideas precise leads to the <a href=\"http://en.wikipedia.org/wiki/Boyer-Moore-Horspool_algorithm\" rel=\"nofollow\">Boyer–Moore–Horspool</a> algorithm:</p>\n\n<pre><code>def find(haystack, needle):\n \"\"\"Return the index at which the sequence needle appears in the\n sequence haystack, or -1 if it is not found, using the Boyer-\n Moore-Horspool algorithm. The elements of needle and haystack must\n be hashable.\n\n &gt;&gt;&gt; find([1, 1, 2], [1, 2])\n 1\n\n \"\"\"\n h = len(haystack)\n n = len(needle)\n skip = {needle[i]: n - i - 1 for i in range(n - 1)}\n i = n - 1\n while i &lt; h:\n for j in range(n):\n if haystack[i - j] != needle[-j - 1]:\n i += skip.get(haystack[i], n)\n break\n else:\n return i - n + 1\n return -1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:11:56.267", "Id": "31416", "Score": "0", "body": "@Lattyware: Generally I'd agree that you should use iterators wherever it makes sense, but this is one of the exceptional cases where iterators don't make much sense. A pure-iterator search runs in O(*nm*) whereas Boyer–Moore-Horspool is O(*n*). (In the average case on random text.) Sometimes you just have to get your hands grubby." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:29:05.937", "Id": "31420", "Score": "0", "body": "Scratch all my arguments, it's impossible to do this correctly the way I was doing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T12:38:21.643", "Id": "31428", "Score": "0", "body": "Accepted. The source is strong with this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T03:14:56.147", "Id": "70305", "Score": "0", "body": "Does the dict comprehension overwrite previous values? If not you'll skip too far when you see `e` while searching for `seven`. I'd bet it does but am not sure. I do miss Python for its elegance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T10:17:39.237", "Id": "70369", "Score": "0", "body": "Yes, later items in the dict comprehension override previous items, and so `find('seven', 'even')` → `1` as required." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:00:44.667", "Id": "19629", "ParentId": "19627", "Score": "5" } } ]
{ "AcceptedAnswerId": "19629", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T22:54:25.417", "Id": "19627", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Finding sub-list" }
19627
<p>I've written a script to generate DNA sequences and then count the appearance of each step to see if there is any long range correlation.</p> <p>My program runs really slow for a length 100000 sequence 100 times replicate. I already run it for more than 100 hours without completion.</p> <pre><code>#!/usr/bin/env python import sys, random import os import math length = 10000 initial_p = {'a':0.25,'c':0.25,'t':0.25,'g':0.25} tran_matrix = {'a': {'a':0.495,'c':0.113,'g':0.129,'t':0.263}, 'c': {'a':0.129,'c':0.063,'g':0.413,'t':0.395}, 't': {'a':0.213,'c':0.495,'g':0.263,'t':0.029}, 'g': {'a':0.263,'c':0.129,'g':0.295,'t':0.313}} def fl(): def seq(): def choose(dist): r = random.random() sum = 0.0 keys = dist.keys() for k in keys: sum += dist[k] if sum &gt; r: return k return keys[-1] c = choose(initial_p) sequence = '' for i in range(length): sequence += c c = choose(tran_matrix[c]) return sequence sequence = seq() # This program takes a DNA sequence calculate the DNA walk score. #print sequence #print len u = 0 ls = [] for i in sequence: if i == 'a' : #print i u = u + 1 if i == 'g' : #print i u = u + 1 if i== 'c' : #print i u = u - 1 if i== 't' : #print i u = u - 1 #print u ls.append(u) #print ls l = 1 f = [] for l in xrange(1,(length/2)+1): lchange =1 sumdeltay = 0 sumsq = 0 for i in range(1,length/2): deltay = ls[lchange + l ] - ls[lchange] lchange = lchange + 1 sq = math.fabs(deltay*deltay) sumsq = sumsq + sq sumdeltay = sumdeltay + deltay f.append(math.sqrt(math.fabs((sumsq/length/2) - math.fabs((sumdeltay/length/2)*(sumdeltay/length/2))))) l = l + 1 return f def performTrial(tries): distLists = [] for i in range(0, tries): fl() distLists.append(fl()) return distLists def main(): tries = 10 distLists = performTrial(tries) #print distLists #print distLists[0][0] averageList = [] for i in range(0, length/2): total = 0 for j in range(0, tries): total += distLists[j][i] #print distLists average = total/tries averageList.append(average) # print total return averageList out_file = open('Markov1.result', 'w') result = str(main()) out_file.write(result) out_file.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:26:31.680", "Id": "31452", "Score": "0", "body": "Could you explain what this is supposed to do in plain English? 1) At the moment, this is a bit long to read without explanation, 2) It may help you identify the problem yourself, and 3) Stop people taking a stab at stuff that looks like it *may* be wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:35:07.817", "Id": "31453", "Score": "0", "body": "Hi, the first function is seq(), it randomly generate DNA sequences based on the transition matrix follow markov chain, each step will be either a,c,t,or g. the length is ten thousands. after the dna sequence generated, the u will be calculated. u is the total score by DNA walk, for example, at each step, if there is a|g, u + 1, if there is a c|g, u -1. Therefore we will have u from step 1 to step 10 thousands. Then we calculate the fluctuation for u from l= 1 step to l =5000 step, to see if there is a long range correlation exist. The performTrial() is using to do replicate for fl() function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:38:30.300", "Id": "31454", "Score": "0", "body": "Then the main() calculate the average score from the replications output from performTrial()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:42:08.367", "Id": "31455", "Score": "0", "body": "The f value return from fl() is the root mean fluctuation calculated from u on different length(step) scale." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:52:36.157", "Id": "31456", "Score": "0", "body": "@Frank Is there a reason your `fl()` function only operates over half the random sequence and does nothing with the other half?" } ]
[ { "body": "<p>Concerning just a little part of your code</p>\n\n<pre><code>u = 0\nls = []\nfor i in sequence:\n u += (1 if i in 'ag' else (-1))\n ls.append(u)\n\nprint ls\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>def gen(L,u = 0):\n for i in L:\n u += (1 if i in 'ag' else (-1))\n yield u\n\nprint list(gen(sequence))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T00:19:15.767", "Id": "19656", "ParentId": "19654", "Score": "1" } }, { "body": "<p>At the risk of being frivolous, two suggestions with the posted code:</p>\n\n<ol>\n<li><p>Did you really mean <code>fl()</code> on both occasions?</p>\n\n<pre><code>for i in range(0, tries):\n fl()\n distLists.append(fl())\n</code></pre></li>\n<li><p>There's no need to use <code>math.fabs</code> on values guaranteed to be positive!</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T21:44:46.393", "Id": "19675", "ParentId": "19654", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:20:57.837", "Id": "19654", "Score": "6", "Tags": [ "python", "beginner", "algorithm", "bioinformatics" ], "Title": "Generating DNA sequences and looking for correlations" }
19654
<p>Are there ways to avoid this triply nested for-loop?</p> <pre><code>def add_random_fields(): from numpy.random import rand server = couchdb.Server() databases = [database for database in server if not database.startswith('_')] for database in databases: for document in couchdb_pager(server[database]): if 'results' in server[database][document]: for tweet in server[database][document]['results']: if tweet and 'rand_num' not in tweet: print document tweet['rand_num'] = rand() server[database].save(tweet) </code></pre> <p><strong>Update</strong> </p> <p>People suggesting that I use a generator reminded me that I forgot to mention that <code>couchdb_pager</code> is a generator over the list <code>server[database]</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T05:37:54.397", "Id": "31467", "Score": "4", "body": "Fundamentally, you're descending through three separate levels of data. Unless you can flatten them or skip one, you have to use a for-loop for each level in the hierarchy. I'd suggest refactoring some of your loops out into their own functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T06:48:52.893", "Id": "31468", "Score": "0", "body": "Maybe using a generator or iterator?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T07:46:05.427", "Id": "31470", "Score": "3", "body": "As it is I don't see any problem with this code - it's readable and efficient. If you really don't like the nesting you could do something like `documents = (document for database in databases for document in couchdb_pager(server[database]) if 'results' in document)` then loop through the documents." } ]
[ { "body": "<p>I agree with the question comments - there's no real way to avoid them (unless you can restructure the databases!), but the code can be made more readable by removing the loops into a separate generator function, especially since you're not doing any processing between each loop.</p>\n\n<p>Consider something like (caution: untested):</p>\n\n<pre><code>def find_all_document_tweets( server ):\n databases = [database for database in server if not database.startswith('_')]\n for database in databases:\n for document in couchdb_pager(server[database]):\n if 'results' in server[database][document]:\n for tweet in server[database][document]['results']:\n yield database, document, tweet\n\ndef add_random_fields():\n from numpy.random import rand\n server = couchdb.Server()\n for ( database, document, tweet ) in find_all_document_tweets( server ):\n if tweet and 'rand_num' not in tweet:\n print document\n tweet['rand_num'] = rand()\n server[database].save(tweet)\n</code></pre>\n\n<p>As an extra bonus, it seems likely that the loops now in <code>find_all_document_tweets</code> will be common in your code, so that it's now usable elsewhere.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T07:56:46.643", "Id": "19658", "ParentId": "19657", "Score": "1" } }, { "body": "<p>There are a few tweaks that can improve this code:</p>\n\n<pre><code>def add_random_fields():\n from numpy.random import rand\n server = couchdb.Server()\n databases = (server[database] for database in server if not database.startswith('_'))\n # immediately fetch the Server object rather then the key, \n # changes to a generator to avoid instantiating all the database objects at once\n for database in databases:\n for document in couchdb_pager(database):\n document = database[document] \n # same here, avoid holding keys when you can have the objects\n\n for tweet in document.get('results', []):\n # rather then checking for the key, have it return a default that does the same thing\n if tweet and 'rand_num' not in tweet:\n print document\n tweet['rand_num'] = rand()\n database.save(tweet)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:27:30.333", "Id": "19694", "ParentId": "19657", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T05:07:32.170", "Id": "19657", "Score": "3", "Tags": [ "python" ], "Title": "Removing the massive amount of for-loops in this code" }
19657
<p>What do you think about this?</p> <pre><code>#utils.py def is_http_url(s): """ Returns true if s is valid http url, else false Arguments: - `s`: """ if re.match('https?://(?:www)?(?:[\w-]{2,255}(?:\.\w{2,6}){1,2})(?:/[\w&amp;%?#-]{1,300})?',s): return True else: return False #utils_test.py import utils class TestHttpUrlValidating(unittest.TestCase): """ """ def test_validating(self): """ """ self.assertEqual(utils.is_http_url('https://google.com'),True) self.assertEqual(utils.is_http_url('http://www.google.com/r-o_ute?key=value'),True) self.assertEqual(utils.is_http_url('aaaaaa'),False) </code></pre> <p>Is this enough? I'm going to insert URLs into database. Are there other ways to validate it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-22T05:23:48.827", "Id": "64943", "Score": "0", "body": "I'd use [urlparse](http://docs.python.org/2/library/urlparse.html) in the standard library to check it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T19:58:55.057", "Id": "64944", "Score": "1", "body": "You can use the rfc3987 package. `rfc3987.match('http://http://codereview.stackexchange.com/', rule='URI')`" } ]
[ { "body": "<p>I would check out <a href=\"https://github.com/django/django/blob/master/django/core/validators.py\" rel=\"nofollow\">Django's validator</a> - I'm willing to bet it's going to be decent, and it's going to be very well tested.</p>\n\n<pre><code>regex = re.compile(\n r'^(?:http|ftp)s?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|' # ...or ipv4\n r'\\[?[A-F0-9]*:[A-F0-9:]+\\]?)' # ...or ipv6\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n</code></pre>\n\n<p>This covers a few edge cases like IP addresses and ports. Obviously some stuff (like FTP links) you might not want to accept, but it'd be a good place to start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-04T20:48:21.603", "Id": "356316", "Score": "0", "body": "This code example seems mostly copied from that SO answer. I think it should have proper attribution. https://stackoverflow.com/a/7160778/172132\n(Unlike the original answer this checks for IPv6 URLs, though.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T20:06:23.763", "Id": "19670", "ParentId": "19663", "Score": "2" } } ]
{ "AcceptedAnswerId": "19670", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T15:53:42.797", "Id": "19663", "Score": "3", "Tags": [ "python", "regex", "validation", "url", "http" ], "Title": "HTTP URL validating" }
19663
<p>I have a Python file with several function definitions in it. One of the functions, named 'main' will be called as soon as the Python file is run.</p> <p>Example:</p> <pre><code>myFile.py import sys def main(arg1....): ---code--- --more functions-- main() </code></pre> <p>When a person wants to run my file they'll type:</p> <pre><code>python myFile.py arg1 arg2 ... </code></pre> <p>The main function is supposed to accept in x number of arguments, however, in case the user doesn't wish to pass in any arguments we're supposed to have default values.</p> <p>My program looks something like this and I'm hoping there is actually a better way to do this than what I have:</p> <pre><code>myFile.py import sys #Even though my function has default values, if the user doesn't wish #to input in any parameter values, they still must pass in the word False #otherwise, pls pass in parameter value def main(name = "Bill", age = 22, num_pets=5, hobby = "soccer"): if len(sys) &gt; 1: i =0 while i &lt; len(sys): if i == 0: if sys.argv[i] == "False": i += 1 continue else: name = sys.argv[i] i += 1 continue elif i == 1: if sys.argv[i] == "False": --------etc. etc.----------- </code></pre>
[]
[ { "body": "<p>You can use the <a href=\"http://docs.python.org/2/tutorial/controlflow.html#tut-unpacking-arguments\" rel=\"nofollow\">apply</a> operator (<code>*</code>):</p>\n\n<pre><code>import sys\n\ndef main(name = \"Bill\", age = 22, num_pets=5, hobby = \"soccer\"):\n pass\n\nif __name__ = \"__main__\":\n main(*sys.argv[1:])\n</code></pre>\n\n<p>You can also use <a href=\"http://pypi.python.org/pypi/argparse\" rel=\"nofollow\">argparse</a> to sanitize the contents of sys.argv before applying them to <code>main()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T05:57:20.100", "Id": "19722", "ParentId": "19707", "Score": "2" } }, { "body": "<p>In case the number of arguments is really long then you can use **kwargs to avoid cluttering up arguments in function definition block. I would also avoid naming the function as \"main\" and replace it with something like \"execute\".</p>\n\n<pre><code>def execute(**kwargs):\n name = kwargs.get('name', 'Bill')\n # get other values\n pass\n\nif __name__ = \"__main__\":\n execute(*sys.argv[1:])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T09:26:06.103", "Id": "19725", "ParentId": "19707", "Score": "4" } }, { "body": "<p>You can also use <a href=\"http://docs.python.org/2/library/optparse.html\" rel=\"nofollow\">optparse</a></p>\n\n<p>Here is an example:</p>\n\n<pre><code>import optparse\n...\nif __name__ == '__main__':\n parser = optparse.OptionParser()\n parser.add_option('-s', '--string', dest = 'someVar', default = 'default', help = '-s with a small s. With default Value')\n parser.add_option('-S', '--boolean', action = 'store_true', dest = 'someBool', help = 'i am a flag :). Use me with a capital S')\n\n (options, args) = parser.parse_args()\n\n main(options)\n</code></pre>\n\n<p>Then your users have to call it like</p>\n\n<pre><code>python script.py -s HerpDerp\n</code></pre>\n\n<p>or</p>\n\n<pre><code>python script.py -h\n</code></pre>\n\n<p>to see a list of available arguments</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:19:30.487", "Id": "31548", "Score": "0", "body": "optparse seems to be deprecated since version 2.7" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:42:34.230", "Id": "31549", "Score": "0", "body": "@Kinjal You are right. But there is [argparse](http://docs.python.org/3.3/library/argparse.html#module-argparse) which has a similar syntax." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T10:00:04.403", "Id": "19729", "ParentId": "19707", "Score": "0" } }, { "body": "<p>I'd suggest using high-level fool-proof libraries like <a href=\"http://docs.python.org/dev/library/argparse.html\" rel=\"nofollow\">argparse</a>.</p>\n\n<p>The problem with argparse is that its syntax is too verbose, so I developed <a href=\"https://argh.readthedocs.org\" rel=\"nofollow\">Argh</a>. It helps maintain the code simple and pythonic:</p>\n\n<pre><code>import argh\n\ndef main(name, age=22, num_pets=5, hobby='soccer'):\n yield 'This is {name}, {age}'.format(name=name, age=age)\n yield 'He has ' + ('one pet' if num_pets &lt; 2 else 'many pets')\n\nargh.dispatch_command(main)\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>$ ./script.py Bill\nThis is Bill, 22\nHe has many pets\n\n$ ./script.py John -a 50 --num-pets=1 --hobby sleeping\nThis is John, 50\nHe has one pet\n</code></pre>\n\n<p>This can be easily tuned if you don't mind diving into the documentation.</p>\n\n<p>Of course it's not the only library in this field.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T08:54:59.080", "Id": "20370", "ParentId": "19707", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T19:15:33.640", "Id": "19707", "Score": "3", "Tags": [ "python" ], "Title": "Python file with several function definitions" }
19707
<p>I had a question regarding my code which downloads a file from S3 with the highest (most recent) timedated filename format:</p> <p>YYYYMMDDHHMMSS.zip</p> <pre><code>from boto.s3.connection import S3Connection from boto.s3.key import Key import sys conn = S3Connection('____________________', '________________________________________') bucket = conn.get_bucket('bucketname') rs = bucket.list("FamilyPhotos") for key in rs: print key.name keys = [(key,datetime.strptime(key.name,'%Y%m%d%H%M%S.zip')) for key in rs] sorted(keys, key = lambda element : element[1]) latest = keys[0][1] latest.get_contents_to_filename() </code></pre> <p>I havent done a lot of python before so I would really appreciate some feedback.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:16:27.860", "Id": "31553", "Score": "0", "body": "What are you looking for specifically?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:34:22.500", "Id": "31555", "Score": "1", "body": "The part of the script that works out the most recently dated filename. I am sure there is a better way of doing it." } ]
[ { "body": "<p>The names will properly compare lexically even without converting them to datetimes, and you can just use the <a href=\"http://docs.python.org/2/library/functions.html#max\" rel=\"nofollow\"><code>max</code></a> function:</p>\n\n<pre><code>from boto.s3.connection import S3Connection\nfrom boto.s3.key import Key\n\nconn = S3Connection(XXX, YYY)\nbucket = conn.get_bucket('bucketname')\nrs = bucket.list(\"FamilyPhotos\")\nlatest = max(rs, key=lambda k: k.name)\nlatest.get_contents_to_filename()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T07:14:41.163", "Id": "19768", "ParentId": "19727", "Score": "3" } } ]
{ "AcceptedAnswerId": "19768", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T09:37:04.007", "Id": "19727", "Score": "2", "Tags": [ "python", "amazon-s3" ], "Title": "Python Boto Script - Sorting based on date" }
19727
<p>I've been on stackoverflow looking for an alternative to the ugly if-elif-else structure shown below. The if-else structure takes three values as input and returns a pre-formatted string used for an SQL query. The code works right now, but it is difficult to explain, ugly, and I don't know a better way to do re-format it. </p> <p>I need a solution that is more readable. I was thinking a dictionary object, but I can't wrap my mind how to implement one with the complex if/else structure I have below. An ideal solution will be more readable. </p> <pre><code>def _getQuery(activity,pollutant,feedstock): if feedstock.startswith('CG') and pollutant.startswith('VOC'): pass if feedstock == 'FR' and activity == 'Harvest': return 'FR' elif feedstock == 'FR': return 'No Activity' elif(activity == 'Fertilizer' and pollutant != 'NOx' and pollutant != 'NH3'): return 'No Activity' elif(activity == 'Chemical' and pollutant != 'VOC'): return 'No Activity' elif( (feedstock == 'CS' or feedstock == 'WS') and (activity == 'Non-Harvest' or activity == 'Chemical')): return 'No Activity' elif( ( ( pollutant.startswith('CO') or pollutant.startswith('SO') ) and ( activity == 'Non-Harvest' or activity == 'Harvest' or activity == 'Transport' ) ) or ( pollutant.startswith('VOC') and not ( feedstock.startswith('CG') or feedstock.startswith('SG') ) ) ): rawTable = feedstock + '_raw' return """ with activitySum as (select distinct fips, sum(%s) as x from %s where description ilike '%s' group by fips), totalSum as (select distinct r.fips, sum(r.%s) as x from %s r group by r.fips), ratios as (select t.fips, (a.x/t.x) as x from activitySum a, totalSum t where a.fips = t.fips), maxRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x desc limit 1), minRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x asc limit 1) select mx.x, mn.x from maxRatio mx, minRatio mn; """ % (pollutant, rawTable, '%'+activity+'%', pollutant, rawTable) elif( (pollutant[0:2] == 'PM') and (activity == 'Non-Harvest' or activity == 'Harvest' or activity == 'Transport')): rawTable = feedstock + '_raw' return """ with activitySum as (select distinct fips, (sum(%s) + sum(fug_%s)) as x from %s where description ilike '%s' group by fips), totalSum as (select distinct r.fips, (sum(r.%s) + sum(r.fug_%s)) as x from %s r group by r.fips), ratios as (select t.fips, (a.x/t.x) as x from activitySum a, totalSum t where a.fips = t.fips), maxRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x desc limit 1), minRatio as (select r.fips, r.x as x from ratios r group by r.fips, r.x order by x asc limit 1) select mx.x, mn.x from maxRatio mx, minRatio mn; """ % (pollutant, pollutant, rawTable, '%'+activity+'%', pollutant, pollutant, rawTable) . . . Lots more complex elif statements </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T21:03:41.157", "Id": "31588", "Score": "1", "body": "I'm not sure it's possible to answer this without knowing more about the range of possible parameters and return values. It might be worth creating more variables with meaningful names that would help make clear why certain combinations of parameter values result in a particular output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T22:19:50.857", "Id": "31590", "Score": "0", "body": "@Stuart, should I include the full if/elif structure in the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T00:03:34.130", "Id": "31594", "Score": "0", "body": "It might help if it's not *terribly* long. To start with, though, I would note that there is a lot of repetition in the long query string `\"\"\"with activitySum etc.` which appears twice with only minor changes. Maybe see if you can use the `if/elif` structure to set values of variables with meaningful names which are then sanitised and fed into a single 'template' query string at the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T16:24:03.633", "Id": "31630", "Score": "0", "body": "@Stuart, thanks for pointing out the code duplicate, by removing the duplicates, the code is looking more reasonable. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T20:40:02.157", "Id": "31639", "Score": "0", "body": "It can't be right to return a SQL query in some cases, and the string `'No Activity'` in others." } ]
[ { "body": "<p>My thought would be to create a collection of objects that can be iterated over. Each object would have an interface like the following.</p>\n\n<pre><code>def _getQuery(activity,pollutant,feedstock):\n for matcher in MATCHERS:\n if matcher.matches(activity,pollutant,feedstock):\n return matcher.get_result(activity,pollutant,feedstock)\n raise Exception('Not matched')\n</code></pre>\n\n<p>Then you build up the set of matcher classes for the various cases and ad an instance of each to <code>MATCHERS</code>. Just remember that earlier elements in the list take precedence to later ones. So the most specific cases should be first in the list ans the most general cases should be at the end.</p>\n\n<p><strong>NOTE</strong>: \nYour string building code is vulnerable to <a href=\"http://en.wikipedia.org/wiki/SQL_injection\">SQL-injection</a>. If you do go forward with manually building your selection strings, your input needs to be more thoroughly sanitized.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T16:24:51.607", "Id": "31631", "Score": "0", "body": "thanks for your comments, especially the part about SQL-injection! I was hoping for a more object-oriented approach and this seems quite reasonable!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T22:36:48.600", "Id": "19756", "ParentId": "19753", "Score": "6" } } ]
{ "AcceptedAnswerId": "19756", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T19:54:14.617", "Id": "19753", "Score": "2", "Tags": [ "python", "sql" ], "Title": "Constructing an SQL expression from three parameters" }
19753
<p>I've written a couple of functions to check if a consumer of the API should be authenticated to use it or not.</p> <p>Have I done anything blatantly wrong here?</p> <p><strong>Config</strong></p> <pre><code>API_CONSUMERS = [{'name': 'localhost', 'host': '12.0.0.1:5000', 'api_key': 'Ahth2ea5Ohngoop5'}, {'name': 'localhost2', 'host': '127.0.0.1:5001', 'api_key': 'Ahth2ea5Ohngoop6'}] </code></pre> <p><strong>Exceptions</strong></p> <pre><code>class BaseException(Exception): def __init__(self, logger, *args, **kwargs): super(BaseException, self).__init__(*args, **kwargs) logger.info(self.message) class UnknownHostException(BaseException): pass class MissingHashException(BaseException): pass class HashMismatchException(BaseException): pass </code></pre> <p><strong>Authentication methods</strong></p> <pre><code>import hashlib from flask import request from services.exceptions import (UnknownHostException, MissingHashException, HashMismatchException) def is_authenticated(app): """ Checks that the consumers host is valid, the request has a hash and the hash is the same when we excrypt the data with that hosts api key Arguments: app -- instance of the application """ consumers = app.config.get('API_CONSUMERS') host = request.host try: api_key = next(d['api_key'] for d in consumers if d['host'] == host) except StopIteration: raise UnknownHostException( app.logger, 'Authentication failed: Unknown Host (' + host + ')') if not request.headers.get('hash'): raise MissingHashException( app.logger, 'Authentication failed: Missing Hash (' + host + ')') hash = calculate_hash(request.method, api_key) if hash != request.headers.get('hash'): raise HashMismatchException( app.logger, 'Authentication failed: Hash Mismatch (' + host + ')') return True def calculate_hash(method, api_key): """ Calculates the hash using either the url or the request content, plus the hosts api key Arguments: method -- request method api_key -- api key for this host """ if request.method == 'GET': data_to_hash = request.base_url + '?' + request.query_string elif request.method == 'POST': data_to_hash = request.data data_to_hash += api_key return hashlib.sha1(data_to_hash).hexdigest() </code></pre>
[]
[ { "body": "<p>Building on @Drewverlee's answer, I would consider renaming <code>BaseException</code> to <code>APIException</code>, or something of the like.</p>\n\n<p>Also, I don't think passing app as an argument is best practice, I would recommend using the function as a decorator on your endpoints instead:</p>\n\n<pre><code># Your imports\nfrom application import app # Or whatever your non-relative reference is\n\ndef is_authenticated(func):\n def func_wrapper():\n # Your code here without the original def call\n return func_wrapper\n</code></pre>\n\n<p>You can then use this on each endpoint, adding the <code>@is_authenticated</code> decorator, to ensure the app is properly authenticated.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-26T23:41:59.233", "Id": "136029", "ParentId": "19786", "Score": "4" } } ]
{ "AcceptedAnswerId": "136029", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T19:10:36.143", "Id": "19786", "Score": "4", "Tags": [ "python", "authentication", "web-services", "flask" ], "Title": "Authentication for a Flask API" }
19786
<p>I have view and it works correct, but very slow</p> <pre><code>class Reading(models.Model): meter = models.ForeignKey(Meter, verbose_name=_('meter')) reading = models.FloatField(verbose_name=_('reading')) code = models.ForeignKey(ReadingCode, verbose_name=_('code')) date = models.DateTimeField(verbose_name=_('date')) class Meta: get_latest_by = 'date' ordering = ['-date', ] def __unicode__(self): return u'%s' % (self.date,) @property def consumption(self): try: end = self.get_next_by_date(code=self.code, meter=self.meter) return (end.reading - self.reading) / (end.date - self.date).days except: return 0.0 @property def middle_consumption(self): data = [] current_year = self.date.year for year in range(current_year - 3, current_year): date = datetime.date(year, self.date.month, self.date.day) try: data.append(Reading.objects.get( date = date, meter = self.meter, code = self.code ).consumption) except: data.append(0.0) for i in data: if not i: data.pop(0) return sum(data) / len(data) class DataForDayChart(TemplateView): def get(self, request, *args, **kwargs): output = [] meter = Meter.objects.get(slug=kwargs['slug']) # TODO: Make it faster for reading in meter.readings_for_period().order_by('date'): output.append({ "label": reading.date.strftime("%d.%m.%Y"), "reading": reading.reading, "value": reading.consumption / 1000, "middle": reading.middle_consumption / 1000 }) return HttpResponse(output, mimetype='application/json') </code></pre> <p>What should I change to make it faster?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T08:18:32.167", "Id": "31790", "Score": "0", "body": "How slow it is? How many records the view returns?\nLooks like you have a loots of SQL Queries there, try to reduce amount of queries." } ]
[ { "body": "<p>There's nothing intrinsically time-consuming here code-wise - I think the best approach is to make sure that your database tables are set up correctly with the required indices. Perhaps create a view on the db to push some work onto that rather than select in code?</p>\n\n<p>I am a little puzzled however by your middle_consumption function. The inner loop contents do something like:</p>\n\n<pre><code>get a date, x years ago from present day\nget a reading on that date, or 0 on failure\nadd that reading to the results\ngo through the results\n if the current item is 0, delete the **first** item\n</code></pre>\n\n<p>This seems wrong.</p>\n\n<ol>\n<li>What happens on February 29th? It would be better to add 365 days if that's appropriate for your application.</li>\n<li><p>Why add a value only to (presumably want to) delete it again? Would something like this be better?</p>\n\n<pre><code>try:\n current_value = Reading.objects.get(\n date = date_of_reading,\n meter = self.meter,\n code = self.code\n ).consumption\nexcept Reading.DoesNotExist: # or suitable exception\n current_value = 0\nif current_value &gt; 0:\n anniversary_values.append( current_value )\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T08:57:33.763", "Id": "19887", "ParentId": "19886", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T06:24:10.340", "Id": "19886", "Score": "2", "Tags": [ "python", "django" ], "Title": "Django how to make this view faster?" }
19886
<p>My solution to this feels 'icky' and I've got calendar math falling out of my ears after working on similar problems for a week so I can't think straight about this.</p> <p>Is there a better way to code this?</p> <pre><code>import datetime from dateutil.relativedelta import relativedelta def date_count(start, end, day_of_month=1): """ Return a list of datetime.date objects that lie in-between start and end. The first element of the returned list will always be start and the last element in the returned list will always be: datetime.date(end.year, end.month, day_of_month) If start.day is equal to day_of_month the second element will be: start + 1 month If start.day is after day_of_month then the second element will be: the day_of_month in the next month If start.day is before day_of_month then the second element will be: datetime.date(start.year, start.month, day_of_month) &gt;&gt;&gt; start = datetime.date(2012, 1, 15) &gt;&gt;&gt; end = datetime.date(2012, 4, 1) &gt;&gt;&gt; date_count(start, end, day_of_month=1) #doctest: +NORMALIZE_WHITESPACE [datetime.date(2012, 1, 15), datetime.date(2012, 2, 1), datetime.date(2012, 3, 1), datetime.date(2012, 4, 1)] Notice that it's not a full month between the first two elements in the list. If you have a start day before day_of_month: &gt;&gt;&gt; start = datetime.date(2012, 1, 10) &gt;&gt;&gt; end = datetime.date(2012, 4, 1) &gt;&gt;&gt; date_count(start, end, day_of_month=15) #doctest: +NORMALIZE_WHITESPACE [datetime.date(2012, 1, 10), datetime.date(2012, 1, 15), datetime.date(2012, 2, 15), datetime.date(2012, 3, 15), datetime.date(2012, 4, 15)] Notice that it's not a full month between the first two elements in the list and that the last day is rounded to datetime.date(end.year, end.month, day_of_month) """ last_element = datetime.date(end.year, end.month, day_of_month) if start.day == day_of_month: second_element = start + relativedelta(start, months=+1) elif start.day &gt; day_of_month: _ = datetime.date(start.year, start.month, day_of_month) second_element = _ + relativedelta(_, months=+1) else: second_element = datetime.date(start.year, start.month, day_of_month) dates = [start, second_element] if last_element &lt;= second_element: return dates while dates[-1] &lt; last_element: next_date = dates[-1] + relativedelta(dates[-1], months=+1) next_date = datetime.date(next_date.year, next_date.month, day_of_month) dates.append(next_date) dates.pop() dates.append(last_element) return dates </code></pre>
[]
[ { "body": "<p>How about...</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n dates = [start]\n next_date = start.replace(day=day_of_month)\n if day_of_month &gt; start.day:\n dates.append(next_date)\n while next_date &lt; end.replace(day=day_of_month):\n next_date += relativedelta(next_date, months=+1)\n dates.append(next_date)\n return dates\n</code></pre>\n\n<p>And by the way it seems like a nice opportunity to use yield, if you wanted to.</p>\n\n<pre><code>def date_count2(start, end, day_of_month=1):\n yield start\n next_date = start.replace(day=day_of_month)\n if day_of_month &gt; start.day:\n yield next_date\n while next_date &lt; end.replace(day=day_of_month):\n next_date += relativedelta(next_date, months=+1)\n yield next_date\n</code></pre>\n\n<p>Another possibility - discard the first value if it is earlier than the start date:</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n dates = [start.replace(day=day_of_month)]\n while dates[-1] &lt; end.replace(day=day_of_month):\n dates.append(dates[-1] + relativedelta(dates[-1], months=+1))\n if dates[0] &gt; start:\n return [start] + dates\n else:\n return [start] + dates[1:]\n</code></pre>\n\n<p>Or use a list comprehension to iterate over the number of months between start and end.</p>\n\n<pre><code>def date_count(start, end, day_of_month=1):\n round_start = start.replace(day=day_of_month)\n gap = end.year * 12 + end.month - start.year * 12 - start.month + 1\n return [start] + [round_start + relativedelta(round_start, months=i) \n for i in range(day_of_month &lt;= start.day, gap)]\n</code></pre>\n\n<p>Finally, I don't know dateutil but <a href=\"http://labix.org/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57\" rel=\"nofollow\">it seems you can use <code>rrule</code></a>:</p>\n\n<pre><code>from dateutil import rrule\ndef date_count(start, end, day_of_month=1):\n yield start\n for date in rrule(MONTHLY, \n dtstart=start.replace(day=day_of_month),\n until=end.replace(day=day_of_month)):\n if date &gt; start:\n yield date\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T22:38:05.560", "Id": "31862", "Score": "0", "body": "Excellent answer. Not sure which solution I will use, but thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T22:52:39.313", "Id": "19907", "ParentId": "19903", "Score": "3" } } ]
{ "AcceptedAnswerId": "19907", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T19:49:00.440", "Id": "19903", "Score": "6", "Tags": [ "python", "datetime" ], "Title": "Building a list of dates between two dates" }
19903
<p>I am working on a P2P streaming sim (which I think is correct), however I've discovered a huge bottleneck in my code. During the run of my sim, the function I've included below gets called about 25000 times and takes about 560 seconds from a total of about 580 seconds (I used pycallgraph).</p> <p>Can anyone identify any way I could speed the execution up, by optimizing the code (I think I won't be able to reduce the times it gets executed)? The basics needed to understand what the function does, is that the incoming messages consist of <code>[sender_sequence nr</code>, <code>sender_id</code>, <code>nr_of_known_nodes_to_sender</code> (or -1 if the sender departs the network), <code>time_to_live</code>], while the <code>mCache</code> entries these messages update, consist of the same data (except for the third field, which cannot be -1, instead if such a message is received the whole entry will be deleted), with the addition of a fifth field containing the update time.</p> <pre><code>def msg_io(self): # Node messages (not datastream) control # filter and sort by main key valid_sorted = sorted((el for el in self.incoming if el[3] != 0), key=ig(1)) self.incoming = [] # ensure identical keys have highest first element first valid_sorted.sort(key=ig(0), reverse=True) # group by second element grouped = groupby(valid_sorted, ig(1)) # take first element for each key internal = [next(item) for group, item in grouped] for j in internal: found = False if j[3] &gt; 0 : # We are only interested in non-expired messages for i in self.mCache[:]: if j[1] == i[1]: # If the current mCache entry corresponds to the current incoming message if j[2] == -1: # If the message refers to a node departure self.mCache.remove(i) # We remove the node from the mCache self.partnerCache = [partner for partner in self.partnerCache if not partner.node_id == j[1]] else: if j[0] &gt; i[0]: # If the message isn't a leftover (i.e. lower sequence number) i[:4] = j[:] # We update the relevant mCache entry i[4] = turns # We add the current time for the update found = True else: k = j[:] #k[3] -= 1 id_to_node[i[1]].incoming.append(k) # and we forward the message if not j[2] == -1 and not found and (len(self.mCache) &lt; maxNodeCache): # If we didn't have the node in the mCache temp = j[:] temp.append(turns) # We insert a timestamp... self.mCache.append(temp) # ...and add it to the mCache self.internal.remove(j) </code></pre>
[]
[ { "body": "<p><code>valid_sorted</code> is created using <code>sorted</code> function, and then it is sorted again. I don't see how the first sort is helping in any way. Maybe I'm wrong..</p>\n\n<hr>\n\n<p>You create the iterator <code>grouped</code> with the function <code>groupby</code>, but then you turn it into list and then <strong>iterate over it</strong> again. instead - you can do this:</p>\n\n<pre><code>grouped = groupby(valid_sorted, ig(1))\nfor group, item in grouped:\n j = next(item)\n ...\n</code></pre>\n\n<p>That way - you only iterate over it once. :)</p>\n\n<hr>\n\n<p>The inner loop iterating over <code>self.mCache[:]</code> - I don't see why you can't just iterate over <code>self.mCache</code> and that's it. If its members are lists - it will change weither you use <code>[:]</code> or not.</p>\n\n<p>When you use <code>[:]</code> - you create a copy of the list, and that's why It can be bad for memory and speed.</p>\n\n<hr>\n\n<p>The <code>remove</code> function can be quite slow, if you can find a better way to implement your algorithm without using this function - it can be faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T16:22:00.390", "Id": "31851", "Score": "0", "body": "First of all, many thank! I can see the point in removing the sorted (I'm already applying some of the changes), however the reasoning behind the grouped() modifications eludes me...aren't we doing the iteration I'm doing via list comprehension, using an explicit for loop? Isn't that more inefficient?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T16:32:08.247", "Id": "31852", "Score": "0", "body": "Another thing that bothers me, is that since I use remove() on the mCache list, I wonder if it is safe to not slice it when I iterate over it, as you suggest. I think I saw a suggestion somewhere, about a reverse iteration, which should be removal safe" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T13:33:42.617", "Id": "31876", "Score": "0", "body": "As @winston's commet says - it seems like groupby doesn't do what we thought it does, so I guess it doesn't matter anymore :)\nAbout the `remove` use - I think it is ok to use it like you do, and if you'll reverse it - it will have the same effect in my opinion." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T13:43:19.413", "Id": "19924", "ParentId": "19922", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-25T11:07:55.517", "Id": "19922", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "P2P streaming sim" }
19922
<p>I'm currently using SciPy's mode function to find the most occurring item in different iterable objects. I like the mode function because it works on every object type I've thrown at it (strings, <code>float</code>s, <code>int</code>s).</p> <p>While this function seems reliable, it is very slow on bigger lists:</p> <pre><code>from scipy.stats import mode li = range(50000) li[1] = 0 %timeit mode(li) 1 loops, best of 3: 7.55 s per loop </code></pre> <p>Is there a better way to get the mode for a list? If so, would the implementation be different depending on the item type?</p>
[]
[ { "body": "<p>Originally I thought you must have been doing something wrong, but no: the <code>scipy.stats</code> implementation of <code>mode</code> scales with the number of unique elements, and so will behave very badly for your test case.</p>\n\n<p>As long as your objects are hashable (which includes your three listed object types of strings, floats, and ints), then probably the simplest approach is to use <a href=\"http://docs.python.org/2/library/collections.html#counter-objects\" rel=\"noreferrer\">collections.Counter</a> and the <code>most_common</code> method:</p>\n\n<pre><code>In [33]: import scipy.stats\n\nIn [34]: li = range(50000); li[1] = 0\n\nIn [35]: scipy.stats.mode(li)\nOut[35]: (array([ 0.]), array([ 2.]))\n\nIn [36]: timeit scipy.stats.mode(li)\n1 loops, best of 3: 10.7 s per loop\n</code></pre>\n\n<p>but</p>\n\n<pre><code>In [37]: from collections import Counter\n\nIn [38]: Counter(li).most_common(1)\nOut[38]: [(0, 2)]\n\nIn [39]: timeit Counter(li).most_common(1)\n10 loops, best of 3: 34.1 ms per loop\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T22:00:26.980", "Id": "32001", "Score": "1", "body": "Wow! What an improvement!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T21:28:59.897", "Id": "20033", "ParentId": "20030", "Score": "5" } } ]
{ "AcceptedAnswerId": "20033", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-29T19:33:13.343", "Id": "20030", "Score": "3", "Tags": [ "python", "python-2.x" ], "Title": "Finding the mode of an array/iterable" }
20030
<p>At first I tried using a timedelta but it doesn't accept months as an argument, so my next working example is this:</p> <pre><code>from datetime import datetime current_date = datetime.now() months = [] for month_adjust in range(2, -3, -1): # Order by new to old. # If our months are out of bounds we need to change year. if current_date.month + month_adjust &lt;= 0: year = current_date.year - 1 elif current_date.month + month_adjust &gt; 12: year = current_date.year + 1 else: year = current_date.year # Keep the months in bounds. month = (current_date.month + month_adjust) % 12 if month == 0: month = 12 months.append(current_date.replace(year, month=month, day=1)) </code></pre> <p>Is there a cleaner way?</p>
[]
[ { "body": "<p>Based on <a href=\"https://stackoverflow.com/questions/546321/how-do-i-calculate-the-date-six-months-from-the-current-date-using-the-datetime\">this answer</a>, I would do something like :</p>\n\n<pre><code>from datetime import date\nfrom dateutil.relativedelta import relativedelta\ntoday = date.today()\nmonths = [today + relativedelta(months = +i) for i in range(2,-3,-1)]\n</code></pre>\n\n<p>It's always better not to have to play with the dates manually as so many things can go wrong.</p>\n\n<p>(I don't have access to a machine with relativedelta here so it's not tested but I'm pretty confident it should work)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T23:35:41.697", "Id": "32326", "Score": "0", "body": "That is wonderful, thanks! BTW you can drop the `+` in `+i`. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T23:41:46.643", "Id": "32327", "Score": "0", "body": "Also you don't need the `.month` in the list compression as I need the date object." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T23:33:25.933", "Id": "20217", "ParentId": "20216", "Score": "4" } } ]
{ "AcceptedAnswerId": "20217", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-06T22:31:19.160", "Id": "20216", "Score": "1", "Tags": [ "python" ], "Title": "Is there a cleaner way of building a list of the previous, next months than this?" }
20216
<p>I wrote code that queries a data structure that contains various triples - 3-item tuples in the form subject-predicate-object. I wrote this code based on an exercise from <em><a href="http://shop.oreilly.com/product/9780596153823.do" rel="nofollow noreferrer">Programming the Semantic Web</a></em> textbook.</p> <pre><code>def query(clauses): bindings = None for clause in clauses: bpos = {} qc = [] for pos, x in enumerate(clause): if x.startswith('?'): qc.append(None) bpos[x] = pos else: qc.append(x) rows = list(triples(tuple(qc))) if bindings == None: # 1st pass bindings = [{var: row[pos] for var, pos in bpos.items()} for row in rows] else: # &gt;2 pass, eliminate wrong bindings for binding in bindings: for row in rows: for var, pos in bpos.items(): if var in binding: if binding[var] != row[pos]: bindings.remove(binding) continue else: binding[var] = row[pos] return bindings </code></pre> <p>The function invocation looks like:</p> <pre><code>bg.query([('?person','lives','Chiapas'), ('?person','advocates','Zapatism')]) </code></pre> <p>The function <code>triples</code> inside it accepts 3-tuples and returns list of 3-tuples. It can be found <a href="https://codereview.stackexchange.com/q/19470/12332">here</a>.</p> <p>The function <code>query</code> loops over each clause, tracks variables (strings that start with '?'), replaces them with None, invokes <code>triples</code>, receives rows, tries to fit values to existing bindings.</p> <p>How can I simplify this code? How can I make it more functional-style, without nested <code>for</code>-loops, <code>continue</code> keyword and so on?</p>
[]
[ { "body": "<ol>\n<li>Your code would be helped by splitting parts of it out into functions.</li>\n<li>Your <code>continue</code> statement does nothing</li>\n<li>Rather then having a special case for the first time through, initialize <code>bindings</code> to <code>[{}]</code> for the same effect. </li>\n</ol>\n\n<p>My version:</p>\n\n<pre><code>def clause_to_query(clause):\n return tuple(None if term.startswith('?') else term for term in clause)\n\ndef compatible_bindings(clause, triples):\n for triple in triples:\n yield { clause_term : fact_term\n for clause_term, fact_term in zip(clause, row) if clause_term.startswith('?')\n }\n\ndef merge_bindings(left, right):\n shared_keys = set(left.keys()).intersection(right.keys)\n\n if all(left[key] == right[key] for key in shared_keys):\n bindings = left.copy()\n bindings.update(right)\n return bindings\n else:\n return None # indicates that a binding cannot be merged\n\n\ndef merge_binding_lists(bindings_left, bindings_right):\n new_bindings = []\n for left, right in itertools.product(bindings_left, bindings_right):\n merged_binding = merge_bindings(left, right)\n if merged_binding is not None:\n new_bindings.append( merged_binding )\n\n return new_bindings\n\n\ndef query(clauses):\n bindings = [{}]\n for clause in clauses:\n query = clause_to_query(clause)\n new_bindings = compatible_bindings(clause, triples(query))\n bindings = merge_binding_lists(bindings, new_bindings)\n\n return bindings\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T20:02:00.293", "Id": "20295", "ParentId": "20278", "Score": "4" } } ]
{ "AcceptedAnswerId": "20295", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T16:48:24.977", "Id": "20278", "Score": "3", "Tags": [ "python", "functional-programming" ], "Title": "Querying a data structure that contains various triples" }
20278
<p>I have a system that needs to be able to reboot a different piece of hardware partway through a script that programs it. It used to wait for me to come and reboot the hardware halfway through, but I've since automated that. I use <a href="http://code.google.com/p/usbnetpower8800/source/browse/trunk/usbnetpower8800.py" rel="nofollow">this</a> python script to control a USB Net Power 8800. </p> <p>I have two setups to show you: First is a system that I'm sure is secure, but is pretty annoying to maintain; I'm sure the second is insecure.</p> <h2>First:</h2> <h3>/usr/bin/power (not set-uid)</h3> <pre><code>#!/bin/sh if [ -e /opt/usbnetpower/_powerwrapper_$1 ] ; then /opt/usbnetpower/_powerwrapper_$1 else /opt/usbnetpower/_powerwrapper_ fi </code></pre> <h3>/opt/usbnetpower/_powerwrapper_reboot.c (The source code to one of six almost identical set-uid programs)</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; int main() { setuid( 0 ); system( "/usr/bin/python /opt/usbnetpower/usbnetpower8800.py reboot" ); return 0; } </code></pre> <p>The reason why there are six is that I didn't trust myself to write correct sanitization code in C that wasn't vulnerable to buffer overflows and the like. </p> <h3>/opt/usbnetpower/usbnetpower8800.py (not set-uid)</h3> <p>Essentially <a href="http://code.google.com/p/usbnetpower8800/source/browse/trunk/usbnetpower8800.py" rel="nofollow">this</a>, but modified to add a <code>reboot</code> command.</p> <p>This setup is what I am currently using.</p> <h2>Second:</h2> <h3>/opt/usbnetpower/usbnetpower8800.py (set-uid)</h3> <p>Much simpler, but I'm concerned that a vulnerability like this would apply. Also, suid python programs appear to be disabled on my system. (CentOS 6)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T22:37:27.413", "Id": "41046", "Score": "1", "body": "Personally I gradually abandon all set-uid things in my system. I primarily use daemons listening UNIX sockets which nonprivileged programs can connect to and ask commands. That way you control what exactly is being used (instead of just all user environment by default). I've developed [a program](https://vi-server.org/vi/dive) to start other programs over UNIX sockets in controlled way." } ]
[ { "body": "<p>Both of your programs are insecure. The problem is that I can set <code>PYTHONPATH</code> to anything I like before executing the program. I can set it to something so that it loads my own <code>usb</code> module which can execute whatever code I like. At that point, I'm executing code as the root user and can do whatever I please. That's why set-uid doesn't work on scripts, and your binary C program wrapper doesn't change that at all.</p>\n\n<p>For more information see: <a href=\"https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts\">https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts</a></p>\n\n<p>In your case, what you should be doing is changing the permissions so that your user has access to the USB device you are supposed to be controlling. That way you don't need to run the script as another user. That's what this portion of the script you are using is referring to:</p>\n\n<pre><code># If you have a permission error using the script and udev is used on your\n# system, it can be used to apply the correct permissions. Example:\n# $ cat /etc/udev/rules.d/51-usbpower.rules\n# SUBSYSTEM==\"usb\", ATTR{idVendor}==\"067b\", MODE=\"0666\", GROUP=\"plugdev\"\n</code></pre>\n\n<p>Discussion of how to adjust your system to give you permission to access the USB device is out of scope for this site. I'm also not really an expert on that. So you may need to ask elsewhere for that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T00:48:52.037", "Id": "38010", "Score": "0", "body": "`In your case, what you should be doing is changing the permissions so that your user has access to the USB device you are supposed to be controlling. ` This is what I ended up doing; [I open-sourced my changes](https://github.com/nickodell/usbnetpower)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T00:35:28.513", "Id": "20307", "ParentId": "20304", "Score": "3" } } ]
{ "AcceptedAnswerId": "20307", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T23:16:59.930", "Id": "20304", "Score": "2", "Tags": [ "python", "c", "security", "linux" ], "Title": "Are these set-uid scripts/binaries secure?" }
20304
<p>This is a script to access the Stack Exchange API for the genealogy site and create a list of user dictionaries. It contains a snippet at end to validate. The data obtained is stored in YAML format in a file for use by other programs to analyze the data.</p> <pre><code>''' This is a script to access the stackexchange api for the genealogy site and create a list of user dictionaries ''' # use requests module # - see http://docs.python-requests.org/en/latest/user/install/#install import requests # use YAML to store output for use by other programs # see http://pyyaml.org/wiki/PyYAML import yaml OUTFILENAME = "users.yaml" # use se api and access genealogy site # see https://api.stackexchange.com/docs/users for api info URL ='https://api.stackexchange.com/2.1/users' url_params = { 'site' : 'genealogy', 'pagesize' : 100, 'order' : 'desc', 'sort' : 'reputation', } page = 1 not_done = True user_list = [] # replies are paginated so loop thru until none left while not_done: url_params['page'] = page # get next page of users api_response = requests.get(URL,params=url_params) json_data = api_response.json() # pull the list of users out of the json answer user_list.extend( json_data['items'] ) # show progress each time thru loop print api_response.url #note only so many queries allowed per day print '\tquota remaining: %s' % json_data['quota_remaining'] print "\t%s users after page %s" % (len(user_list),page) # prepare for next iteration if needed page += 1 not_done = json_data['has_more'] # output list of users to a file in yaml, a format easily readable by humans and parsed # note safe_dump is used for security reasons # since dump allows executable python code # Sidebenefit of safe_dump is cleaner text outFile = open(OUTFILENAME,"w") yaml.safe_dump(user_list, outFile) outFile.close() # validate it wrote correctly # note this shows example of how to read infile = open(OUTFILENAME) readList = yaml.safe_load(infile) infile.close() print 'wrote list of %d users as yaml file %s' % (len(readList),OUTFILENAME) </code></pre> <p>I wrote this code because I wanted the data it gets from the genealogy site but also:</p> <ul> <li>to learn APIs in general</li> <li>to learn the Stack Exchange API</li> <li>to get back into programming which I hadn't done much lately</li> <li>I thought I'd try YAML</li> </ul> <p>Since it's such a simple script I didn't bother with objects, but I would be interested in how it could be remade in the functional programming paradigm which I'm not as familiar with.</p>
[]
[ { "body": "<pre><code>'''\nThis is a script to access the stackexchange api\n for the genealogy site \n and create a list of user dictionaries\n'''\n\n# use requests module - see http://docs.python-requests.org/en/latest/user/install/#install\nimport requests\n\n# use pretty print for output\n</code></pre>\n\n<p>That's a pretty useless comment. It doesn't really tell me anything I didn't already know from the import</p>\n\n<pre><code>import pprint\n\n\n\n# save output in file in format compatable with eval\n# I didn't use json or yaml since my intent is to continue on using \n# the parsed output so saves a parse step\n</code></pre>\n\n<p><code>eval</code> also has a parse step. So you aren't saving anything by avoiding json.</p>\n\n<pre><code>pytFilename = \"users.pyt\"\n</code></pre>\n\n<p>python convention is for constants to be in ALL_CAPS</p>\n\n<pre><code># use se api and access genealogy site\n# see https://api.stackexchange.com/docs/users for api info\nurl='https://api.stackexchange.com/2.1/users'\nsite = 'genealogy'\n\nurlParams = {}\nurlParams['site'] = site\nurlParams['pagesize'] = 100\nurlParams['order'] = 'desc'\nurlParams['sort'] = 'reputation'\n</code></pre>\n\n<p>Why not put all these parameters into a single dict literal?</p>\n\n<pre><code>page = 1\nnotDone = True\nuserList = []\n</code></pre>\n\n<p>Python convention is for local variables to be mixed_case_with_underscores.</p>\n\n<pre><code># replies are paginated so loop thru until none left\nwhile notDone:\n urlParams['page'] = page\n # get next page of users\n r = requests.get(url,params=urlParams)\n</code></pre>\n\n<p>avoid single letter variable names. It makes it harder to figure out what you are doing. </p>\n\n<pre><code> # pull the list of users out of the json answer\n userList += r.json()['items']\n</code></pre>\n\n<p>I'd use <code>userList.extend( r.json()['items']). Also given the number of times you access the json, I'd have a</code>json = r.json()` line and access the json data through that.</p>\n\n<pre><code> # show progress each time thru loop, note only so many queries allowed per day\n print r.url\n print '\\tquota remaining: %s' % r.json()['quota_remaining'] \n print \"\\t%s users after page %s\" % (len(userList),page)\n\n # prepare for next iteration if needed\n page += 1\n notDone = r.json()['has_more']\n</code></pre>\n\n<p>I'd do: </p>\n\n<pre><code>json = {'has_more' : True}\nwhile json['has_more']:\n ...\n json = r.json()\n ...\n</code></pre>\n\n<p>As I think it's easier to follow then a boolean flag. </p>\n\n<pre><code># output list of users to a file in a format readable by eval\nopen(pytFilename,\"w\").write( pprint.pformat(userList) )\n</code></pre>\n\n<p>This isn't recommended practice. In CPython this will close the file, but it won't if you are using one of the other pythons. Instead, it's recommend to do:</p>\n\n<pre><code>with open(pytFilename, 'w') as output:\n output.write( pprint.pformat(userList) )\n</code></pre>\n\n<p>And that will close the file in all implementations of python.</p>\n\n<pre><code># validate it wrote correctly \n# note this shoasw example of how to read \nreadList = eval( open(pytFilename,\"r\").read() )\n\n\nprint 'wrote %s as python evaluatable list of users' % pytFilename\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T16:55:37.477", "Id": "20335", "ParentId": "20323", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T12:43:43.470", "Id": "20323", "Score": "0", "Tags": [ "python", "stackexchange" ], "Title": "Script to access genealogy API for list of users and attributes" }
20323
<p>I frequently run a script similar to the one below to analyze an arbitrary number of files in parallel on a computer with 8 cores. </p> <p>I use Popen to control each thread, but sometimes run into problems when there is much stdout or stderr, as the buffer fills up. I solve this by frequently reading from the streams. I also print the streams from one of the threads to help me follow the progress of the analysis.</p> <p>I'm curious on alternative methods to thread using Python, and general comments about the implementation, which, as always, has room for improvement. Thanks!</p> <pre><code>import os, sys import time import subprocess def parallelize(analysis_program_path, filenames, N_CORES): ''' Function that parallelizes an analysis on a list of files on N_CORES number of cores ''' running = [] sys.stderr.write('Starting analyses\n') while filenames or running: while filenames and len(running) &lt; N_CORES: # Submit new analysis filename = filenames.pop(0) cmd = '%s %s' % (analysis_program_path, filename) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sys.stderr.write('Analyzing %s\n' % filename) running.append((cmd, p)) i = 0 while i &lt; len(running): (cmd, p) = running[i] returncode = p.poll() st_out = p.stdout.read() st_err = p.stderr.read() # Read the buffer! Otherwise it fills up and blocks the script if i == 0: # Just print one of the processes sys.stderr.write(st_err) if returncode is not None: st_out = p.stdout.read() st_err = p.stderr.read() sys.stderr.write(st_err) running.remove((cmd, p)) else: i += 1 time.sleep(1) sys.stderr.write('Completely done!\n') </code></pre>
[]
[ { "body": "<p>Python has what you want built into the standard library: see the <a href=\"http://docs.python.org/2/library/multiprocessing.html\" rel=\"noreferrer\"><code>multiprocessing</code> module</a>, and in particular the <a href=\"http://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map\" rel=\"noreferrer\"><code>map</code> method</a> of the <a href=\"http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool\" rel=\"noreferrer\"><code>Pool</code> class</a>.</p>\n\n<p>So you can implement what you want in one line, perhaps like this:</p>\n\n<pre><code>from multiprocessing import Pool\n\ndef parallelize(analysis, filenames, processes):\n '''\n Call `analysis` for each file in the sequence `filenames`, using\n up to `processes` parallel processes. Wait for them all to complete\n and then return a list of results.\n '''\n return Pool(processes).map(analysis, filenames, chunksize = 1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T17:23:54.503", "Id": "20514", "ParentId": "20416", "Score": "5" } } ]
{ "AcceptedAnswerId": "20514", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T12:47:40.057", "Id": "20416", "Score": "4", "Tags": [ "python", "multithreading" ], "Title": "Python parallelization using Popen" }
20416
<p>This morning I was trying to find a good way of using <code>os.path</code> to load the content of a text file into memory, which exists in the root directory of my current project.</p> <p><a href="http://halfcooked.com/blog/2012/06/01/python-path-relative-to-application-root/" rel="noreferrer">This approach</a> strikes me as a bit hackneyed, but after some thought it was exactly what I was about to do, except with <code>os.path.normpath(os.path.join(__file__, '..', '..'))</code> </p> <p>These relative operations on the path to navigate to a <em>static</em> root directory are brittle.</p> <p>Now, if my project layout changes, these associations to the (former) root directory change with it. I wish I could assign the path to find a target, or a destination, instead of following a sequence of navigation operations.</p> <p>I was thinking of making a special <code>__root__.py</code> file. Does this look familiar to anyone, or know of a better implementation?</p> <pre><code>my_project | | __init__.py | README.md | license.txt | __root__.py | special_resource.txt | ./module |-- load.py </code></pre> <p>Here is how it is implemented:</p> <pre><code>"""__root__.py""" import os def path(): return os.path.dirname(__file__) </code></pre> <p>And here is how it could be used:</p> <pre><code>"""load.py""" import __root__ def resource(): return open(os.path.join(__root__.path(), 'special_resource.txt')) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:41:47.363", "Id": "33095", "Score": "0", "body": "You should choose an answer or provide more information." } ]
[ { "body": "<p>I never heard of <code>__root__.py</code> and don't think that is a good idea.</p>\n\n<p>Instead create a <code>files.py</code> in a <code>utils</code> module:</p>\n\n<pre><code>MAIN_DIRECTORY = dirname(dirname(__file__))\ndef get_full_path(*path):\n return join(MAIN_DIRECTORY, *path)\n</code></pre>\n\n<p>You can then import this function from your <code>main.py</code>:</p>\n\n<pre><code>from utils.files import get_full_path\n\npath_to_map = get_full_path('res', 'map.png')\n</code></pre>\n\n<p>So my project directory tree looks like this:</p>\n\n<pre><code>project_main_folder/\n utils/\n __init__.py (empty)\n files.py\n main.py\n</code></pre>\n\n<p>When you import a module the Python interpreter searches if there's a built-in module with that name (that's why your module name should be different or you should use <a href=\"http://docs.python.org/2/tutorial/modules.html#intra-package-references\" rel=\"nofollow\">relative imports</a>). If it hasn't found a module with that name it will (among others in <code>sys.path</code>) search in the directory containing your script. You can find further information in the <a href=\"http://docs.python.org/2/tutorial/modules.html#the-module-search-path\" rel=\"nofollow\">documentation</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T03:17:33.217", "Id": "32884", "Score": "0", "body": "But how do you import `main` without knowing where the main directory is already?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T16:28:32.857", "Id": "32919", "Score": "0", "body": "I modified my answer to include the import line and also put the function in the module `utils.files`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T01:23:28.473", "Id": "32966", "Score": "0", "body": "My question remains the same: how do you import `utils.files` without knowing where `utils` is?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T15:54:35.510", "Id": "32994", "Score": "0", "body": "When you put the code that imports `utils.files` in `main.py` Python will automatically figure it out. I added further information to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T20:08:40.777", "Id": "33022", "Score": "0", "body": "Oh. What if I'm in `dir1/module1.py` and I want to `import dir2.module2`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T20:52:36.303", "Id": "33025", "Score": "0", "body": "Note that `dir1` and `dir2` need to contain an `__init__.py` to be considered as a module. Then you could probably (not tested) use relative imports: `from ..dir2.module2 import get_bla`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T21:26:20.993", "Id": "20449", "ParentId": "20428", "Score": "4" } }, { "body": "<p>A standard way to achieve this would be to use the <code>pkg_resources</code> module which is part of the <code>setuptools</code> module. <code>setuptools</code> is used to create an installable python package.</p>\n\n<p>You can use pkg_resources to return the contents of your desired file as a string and you can use pkg_resources to get the actual path of the desired file on your system.</p>\n\n<p>Let's say that you have a module called <code>stackoverflow</code>.</p>\n\n<pre><code>stackoverflow/\n|-- app\n| `-- __init__.py\n`-- resources\n |-- bands\n | |-- Dream\\ Theater\n | |-- __init__.py\n | |-- King's\\ X\n | |-- Megadeth\n | `-- Rush\n `-- __init__.py\n\n3 directories, 7 files\n</code></pre>\n\n<p>Now let's say that you want to access the file <code>Rush</code>. Use <code>pkg_resources.resouces_filename</code> to get the path to <code>Rush</code> and <code>pkg_resources.resource_string</code> to get the contents of <code>Rush</code>, thusly:</p>\n\n<pre><code>import pkg_resources\n\nif __name__ == \"__main__\":\n print pkg_resources.resource_filename('resources.bands', 'Rush')\n print pkg_resources.resource_string('resources.bands', 'Rush')\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>/home/sri/workspace/stackoverflow/resources/bands/Rush\nBase: Geddy Lee\nVocals: Geddy Lee\nGuitar: Alex Lifeson\nDrums: Neil Peart\n</code></pre>\n\n<p>This works for all packages in your python path. So if you want to know where lxml.etree exists on your system:</p>\n\n<pre><code>import pkg_resources\n\nif __name__ == \"__main__\":\n print pkg_resources.resource_filename('lxml', 'etree')\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>/usr/lib64/python2.7/site-packages/lxml/etree\n</code></pre>\n\n<p>The point is that you can use this standard method to access files that are installed on your system (e.g pip install xxx) and files that are within the module that you're currently working on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-29T13:37:17.713", "Id": "174315", "ParentId": "20428", "Score": "0" } } ]
{ "AcceptedAnswerId": "20449", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T15:09:55.653", "Id": "20428", "Score": "6", "Tags": [ "python" ], "Title": "Accessing the contents of a project's root directory in Python" }
20428
<p>I'm tasked with getting emails from a .csv file and using them to submit a form. I am using the csv and mechanize Python libraries to achieve this.</p> <pre><code>import re import mechanize import csv def auto_email(email): br = mechanize.Browser() br.open("URL") br.select_form(name="vote_session") br['email_add'] = '%s' % (email) #email address br.submit() def csv_emails(): ifile = open('emails.csv', "rb") reader = csv.reader(ifile) rownum = 1 for row in reader: auto_email(row[0]) print "%d - %s processed" %(rownum, row[0]) rownum += 1 print 'List processed. You are done.' ifile.close() print csv_emails() </code></pre> <p>The code works, but I am very much a beginner in Python.</p> <p>I was wondering whether I have any inefficiencies that you can help me get rid of and optimize the script?</p>
[]
[ { "body": "<p>I would suggest to use</p>\n\n<pre><code>with open('emails.csv', \"rb\") as ifile\n</code></pre>\n\n<p>see here for details: <a href=\"http://www.python.org/dev/peps/pep-0343/\">http://www.python.org/dev/peps/pep-0343/</a>\nin this case you don't need to do <code>ifile.close</code> at the end</p>\n\n<p>instead of incrementing rownum by yourself, you can use</p>\n\n<pre><code>for row, rownum in enumerate(reader):\n</code></pre>\n\n<p>I don't see the reason to do this</p>\n\n<pre><code>br['email_add'] = '%s' % (email) #email address\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>br['email_add'] = email\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:03:04.940", "Id": "32921", "Score": "0", "body": "`email` comes from a row returned by `csv.reader` so it's always a string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:04:55.650", "Id": "32922", "Score": "0", "body": "so in this case `br['email_add'] = email` is enough. I edited my answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T17:01:27.540", "Id": "20549", "ParentId": "20548", "Score": "6" } } ]
{ "AcceptedAnswerId": "20549", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T16:16:16.327", "Id": "20548", "Score": "3", "Tags": [ "python", "beginner", "python-2.x", "csv", "email" ], "Title": "CSV email script efficiency" }
20548
<p>I wrote a solution to the <a href="http://en.wikipedia.org/wiki/Knapsack_problem">Knapsack problem</a> in Python, using a bottom-up dynamic programming algorithm. It correctly computes the optimal value, given a list of items with values and weights, and a maximum allowed weight.</p> <p>Any critique on code style, comment style, readability, and best-practice would be greatly appreciated. I'm not sure how Pythonic the code is; filling in a matrix seems like a natural way of implementing dynamic programming, but it doesn't "feel" Pythonic (and is that a bad thing, in this case?).</p> <p>Note that the comments are a little on the verbose side; as I was writing the algorithm, I tried to be as explicit about each step as possible, since I was trying to understand it to the fullest extent possible. If they are excessive (or just plain incorrect), feel free to comment (hah!) on it.</p> <pre><code>import sys def knapsack(items, maxweight): # Create an (N+1) by (W+1) 2-d list to contain the running values # which are to be filled by the dynamic programming routine. # # There are N+1 rows because we need to account for the possibility # of choosing from 0 up to and including N possible items. # There are W+1 columns because we need to account for possible # "running capacities" from 0 up to and including the maximum weight W. bestvalues = [[0] * (maxweight + 1) for i in xrange(len(items) + 1)] # Enumerate through the items and fill in the best-value table for i, (value, weight) in enumerate(items): # Increment i, because the first row (0) is the case where no items # are chosen, and is already initialized as 0, so we're skipping it i += 1 for capacity in xrange(maxweight + 1): # Handle the case where the weight of the current item is greater # than the "running capacity" - we can't add it to the knapsack if weight &gt; capacity: bestvalues[i][capacity] = bestvalues[i - 1][capacity] else: # Otherwise, we must choose between two possible candidate values: # 1) the value of "running capacity" as it stands with the last item # that was computed; if this is larger, then we skip the current item # 2) the value of the current item plus the value of a previously computed # set of items, constrained by the amount of capacity that would be left # in the knapsack (running capacity - item's weight) candidate1 = bestvalues[i - 1][capacity] candidate2 = bestvalues[i - 1][capacity - weight] + value # Just take the maximum of the two candidates; by doing this, we are # in effect "setting in stone" the best value so far for a particular # prefix of the items, and for a particular "prefix" of knapsack capacities bestvalues[i][capacity] = max(candidate1, candidate2) # Reconstruction # Iterate through the values table, and check # to see which of the two candidates were chosen. We can do this by simply # checking if the value is the same as the value of the previous row. If so, then # we say that the item was not included in the knapsack (this is how we arbitrarily # break ties) and simply move the pointer to the previous row. Otherwise, we add # the item to the reconstruction list and subtract the item's weight from the # remaining capacity of the knapsack. Once we reach row 0, we're done reconstruction = [] i = len(items) j = maxweight while i &gt; 0: if bestvalues[i][j] != bestvalues[i - 1][j]: reconstruction.append(items[i - 1]) j -= items[i - 1][1] i -= 1 # Reverse the reconstruction list, so that it is presented # in the order that it was given reconstruction.reverse() # Return the best value, and the reconstruction list return bestvalues[len(items)][maxweight], reconstruction if __name__ == '__main__': if len(sys.argv) != 2: print('usage: knapsack.py [file]') sys.exit(1) filename = sys.argv[1] with open(filename) as f: lines = f.readlines() maxweight = int(lines[0]) items = [map(int, line.split()) for line in lines[1:]] bestvalue, reconstruction = knapsack(items, maxweight) print('Best possible value: {0}'.format(bestvalue)) print('Items:') for value, weight in reconstruction: print('V: {0}, W: {1}'.format(value, weight)) </code></pre> <p>The input file that it expects is as follows:</p> <pre><code>165 92 23 57 31 49 29 68 44 60 53 43 38 67 63 84 85 87 89 72 82 </code></pre> <p>The first line contains the maximum weight allowed, and subsequent lines contain the items, represented by value-weight pairs.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T00:18:33.647", "Id": "52860", "Score": "5", "body": "An old post, I know, but if you haven't run into it already `enumerate` allows you to specify the starting index (e.g. `for i,item in enumerate(items,1):` would have `i` begin at 1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T04:44:36.323", "Id": "52869", "Score": "0", "body": "@SimonT: Fantastic! I've programmed in Python for 2+ years now, and I had never seen `enumerate` used that way. I'll definitely keep it in mind." } ]
[ { "body": "<p>For the first section of code involving nested loops, if you should choose to<br>\n - use <code>curr</code> instead of <code>i</code>,<br>\n - assign <code>prev = curr - 1</code> and<br>\n - use <code>enumerate(items, 1)</code>, </p>\n\n<p>the code will literally document itself.</p>\n\n<pre><code>for curr, (value, weight) in enumerate(items, 1):\n prev = curr - 1\n for capacity in range(maxweight + 1):\n if weight &gt; capacity:\n bestvalues[curr][capacity] = bestvalues[prev][capacity]\n else:\n candidate1 = bestvalues[prev][capacity]\n candidate2 = bestvalues[prev][capacity - weight] + value\n\n bestvalues[curr][capacity] = max(candidate1, candidate2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T18:46:13.557", "Id": "237793", "ParentId": "20569", "Score": "2" } } ]
{ "AcceptedAnswerId": "20581", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-01-16T05:52:50.383", "Id": "20569", "Score": "56", "Tags": [ "python", "algorithm", "dynamic-programming", "knapsack-problem" ], "Title": "Dynamic programming knapsack solution" }
20569
<p>I have this code in a class that gets a string, parses it, and makes some adjustments to get a valid <code>datetime</code> format from the string.</p> <p>An input string for this function could be = "A0X031716506774"</p> <pre><code>import datetime def _eventdatetime(self, string): base_date = datetime.datetime.strptime("1980-1-6 0:0", "%Y-%m-%d %H:%M") weeks = datetime.timedelta(weeks = int(string[5:9])) days = datetime.timedelta(days = int(string[9])) seconds = datetime.timedelta(seconds = int(string[10:15])) stamp = base_date + weeks + days + seconds adjustUTC = datetime.timedelta(hours = 3) stamp = stamp - adjustUTC return str(stamp) </code></pre> <p>Total time: 0.0483931 s</p> <p>How can I improve the performance for this? The third line seems to be the slowest.</p>
[]
[ { "body": "<pre><code>import datetime\ndef _eventdatetime(self, string):\n base_date = datetime.datetime.strptime(\"1980-1-6 0:0\", \"%Y-%m-%d %H:%M\")\n</code></pre>\n\n<p>Why are you specifying the date as a string only to parse it? Just do: <code>base_date = datetime.datetime(1980,1,6,0,0)</code>. You should also make it a global constant so as not to recreate it all the time.</p>\n\n<pre><code> weeks = datetime.timedelta(weeks = int(string[5:9]))\n days = datetime.timedelta(days = int(string[9]))\n seconds = datetime.timedelta(seconds = int(string[10:15]))\n</code></pre>\n\n<p>There is no need to create several timedelta objects, you can do <code>datetime.timedelta(weeks = ..., days = ..., seconds = ...)</code></p>\n\n<pre><code> stamp = base_date + weeks + days + seconds\n\n adjustUTC = datetime.timedelta(hours = 3) \n stamp = stamp - adjustUTC\n</code></pre>\n\n<p>I'd use <code>stamp -= datetime.timedelta(hours = 3) # adjust for UTC</code></p>\n\n<pre><code> return str(stamp)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T19:10:25.343", "Id": "33015", "Score": "0", "body": "Thanks for your time Winston! Your advise is very useful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T18:22:42.437", "Id": "20595", "ParentId": "20593", "Score": "3" } } ]
{ "AcceptedAnswerId": "20595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T17:45:56.693", "Id": "20593", "Score": "1", "Tags": [ "python", "performance", "datetime", "formatting" ], "Title": "Getting a valid datetime format from a string" }
20593
<p>I'm trying to improve some code in order to get a better perfomance, I have to do a lot of pattern matching for little tags on medium large strings, for example:</p> <pre><code>import re STR = "0001x10x11716506872xdc23654&amp;xd01371600031832xx10xID=000110011001010\n" def getID(string): result = re.search('.*ID=(\d+)', string) if result: print result.group(1) else: print "No Results" </code></pre> <p>Taking in mind the perfomance I rewrite it:</p> <pre><code>def getID2(string): result = string.find('ID=') if result: result += 3 print string[result:result+15] else: print 'No Results' </code></pre> <p>Are there a better way to improve these approaches? Any comments are welcome...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:17:23.493", "Id": "33093", "Score": "5", "body": "Is this the actual code that you are trying to improve the performance of? As it stands, `print` will be more expensive then anything else and relative to that no other change will really matter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T15:54:33.223", "Id": "33096", "Score": "0", "body": "This a getter from a class that get the string at the constructor" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T16:44:32.320", "Id": "33104", "Score": "1", "body": "If its a getter you should be referencing `self` and `return`ing the answer. If you want help you need to show your actual code! As it stands this is totally useless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-03T08:41:25.473", "Id": "39899", "Score": "0", "body": "Also, what performance improvement do you need? What are possible use cases? There's not much more you can do since find(\"ID=\") is O(n), n being the length of the string. You can get performance only by not traversing the whole string, which is not possible unless we know more about your date (ID always at the end?)." } ]
[ { "body": "<p>If you name your function <code>getSomething()</code>, I expect it to return a value with no side effects. I do not expect it to print anything. Therefore, your function should either return the found string, or <code>None</code> if it is not not found.</p>\n\n<p>Your original and revised code look for different things: the former wants as many digits as possible, and the latter wants 15 characters. Combining the two requirements, I take it that you want 15 digits.</p>\n\n<p><code>re.search()</code> lets the regular expression match any part of the string, rather than the entire string. Therefore, you can omit <code>.*</code> from the beginning of your regular expression.</p>\n\n<p>Here's how I would write it:</p>\n\n<pre><code>import re\nSTR = \"0001x10x11716506872xdc23654&amp;xd01371600031832xx10xID=000110011001010\\n\"\n\ndef getID(string):\n result = re.search('ID=(\\d{15})', string)\n return result and result.group(1)\n\nprint getID(STR) or \"No Results\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:43:02.430", "Id": "65214", "Score": "0", "body": "Out of interest, even though I prefer the look of your suggestion, do you think it will perform better than the `find(...)` option? My instinct is that RE's will be slower in general and the `\\d{15}` will do character-checking for digits which the find solution does not do..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T09:28:51.010", "Id": "38985", "ParentId": "20632", "Score": "2" } }, { "body": "<p>You are trying to get what's after <code>ID=</code>?<br>\nI'm not sure about performance (you'll have to benchmark on your own data) but I would do this: </p>\n\n<pre><code>def get_id(string):\n try:\n id = str.split('ID=')[1].strip()\n return id\n except IndexError:\n return None\n\nstring = \"0001x10x11716506872xdc23654&amp;xd01371600031832xx10xID=000110011001010\\n\"\nid = get_id(string)\n</code></pre>\n\n<p>This only works if there are 0 or 1 <code>ID=</code> parts. If there are 2 or more only the first one gets returned.</p>\n\n<p>Edit:</p>\n\n<p>This is how I would do benchmarks (I might be wrong, I don't have much experience in this):</p>\n\n<pre><code>&gt;&gt;&gt; #string with escaped '\\n' at the end:\n&gt;&gt;&gt; string = '0001x10x11716506872xdc23654&amp;xd01371600031832xx10xID=000110011001010\\\\n'\n&gt;&gt;&gt; #original regex + getting the match object:\n&gt;&gt;&gt; timeit.timeit(stmt=\"re.search(r'.*ID=(\\d+)', '{}').group(1)\".format(string), setup=\"import re\")\n3.4012476679999963\n&gt;&gt;&gt; #original regex only:\n&gt;&gt;&gt; timeit.timeit(stmt=\"re.search(r'.*ID=(\\d+)', '{}')\".format(string), setup=\"import re\")\n2.560870873996464\n&gt;&gt;&gt; #alternative regex + match object (had to use c-style string formatting):\n&gt;&gt;&gt; timeit.timeit(stmt=\"re.search(r'ID=(\\d{15})', '%s').group(1)\" % string, setup=\"import re\")\n3.0494329900029697\n&gt;&gt;&gt; #alternative regex only:\n&gt;&gt;&gt; timeit.timeit(stmt=\"re.search(r'ID=(\\d{15})', '%s')\" % string, setup=\"import re\")\n2.2219171980032115\n&gt;&gt;&gt; #str.split:\n&gt;&gt;&gt; timeit.timeit(stmt=\"'{}'.split('ID=')[1].strip()\".format(string))\n1.127366863998759\n</code></pre>\n\n<p>I think these are the benchmarks for the relevant parts. This is on a CoreDuo MacBook Pro and your results may vary. It's been my experience that using methods from the standard library usually yields the best results.\nOn the other hand, this is important only if you have a ton of data to process. Otherwise a more flexible but \"slower\" way of doing things might be better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T12:48:03.887", "Id": "65216", "Score": "1", "body": "Since the actual asker of the question is using non-existant value checking in his solution, it seems fair that the assumptions of your suggestion are very restrictive too.... but I can't believe this solution will be anything near as quick as any other alternatives so far. The `str.split` has to check **every** character in the string inclusing all of those chars after the first match.... it simply does not add up. +1 though for suggesting benchmarking.... which is the obvious review question I would ask... \"What are the benchmarks?\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T17:02:46.550", "Id": "65264", "Score": "1", "body": "@rolfl I added some benchmarks... I think they are ok but please correct me if I'm mistaken." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T11:38:38.813", "Id": "38991", "ParentId": "20632", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T13:42:52.693", "Id": "20632", "Score": "1", "Tags": [ "python", "regex" ], "Title": "Python pattern searching using re standard lib, str.find()" }
20632
<p>I know the code is full of useless data and stylistic and analysis errors and I'd really love and appreciate to have a pro's idea about it so I can learn to code (and think) better.</p> <pre><code>import os, time from ConfigParser import SafeConfigParser configfilename = "imhome.ini" scriptpath = os.path.abspath(os.path.dirname(__file__)) configfile = os.path.join(scriptpath, configfilename) parser = SafeConfigParser() parser.read(configfile) ip_smartphone = parser.get('imhome', 'ip_smartphone') mac_address_pc = parser.get('imhome', 'mac_address_pc') hometime_path = parser.get('imhome', 'hometime_path') in_path = parser.get('imhome', 'in_path') mp3_path = parser.get('imhome', 'mp3_path') maximum_time_before_logout = parser.get('imhome', 'maximum_time_before_logout') if os.path.exists(hometime_path) == False: os.system ("touch " + str(hometime_path)) if os.path.exists(in_path) == True: os.system ("rm " + str(in_path)) finished = 1 while finished == 1: check_presence = os.system ("ping -w 1 " + str (ip_smartphone) + " &gt;/dev/null") file_modification_time = (os.path.getmtime(hometime_path)) file_delta_time = time.time() - file_modification_time if check_presence == 0 : os.system ("rm " + str(hometime_path)) change_arrived=("echo " + str(check_presence) + " &gt; hometime") os.system (change_arrived) if os.path.exists(in_path) == False: # You can add any custom commands to execute when home below this row os.system ("etherwake " + str(mac_address_pc)) os.system ("mpg123 " + str(mp3_path) + " &gt;/dev/null") os.system ("touch " + str(in_path)) # stop adding commands elif check_presence == 256 and file_delta_time &gt; int(maximum_time_before_logout): if os.path.exists(in_path) == True: os.system ("rm " + str(in_path)) </code></pre>
[]
[ { "body": "<p>Neat idea with that script. It looks good; not bad for the first program. Just a few comments:</p>\n\n<ol>\n<li>I would improve some variable names: <code>file_modification_time</code> -> <code>phone_last_seen_time</code>, <code>file_delta_time</code> -> <code>phone_unseen_duration</code>. When I was reading the program it took me some time to figure out their purpose.</li>\n<li>Use <code>while True:</code> instead of <code>while finished == 1:</code> so it is immediately clear that it is an infinite loop.</li>\n<li>In the line <code>change_arrived=(\"echo \" + str(check_presence) + \" &gt; hometime\")</code> you probably want <code>str(hometime_path)</code> instead of <code>\"hometime\"</code>.</li>\n<li>It would be also good to describe purpose of some variables in comments. Mainly <code>hometime_path</code> and <code>in_path</code>.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T17:53:21.570", "Id": "20652", "ParentId": "20646", "Score": "6" } } ]
{ "AcceptedAnswerId": "20676", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T16:29:00.560", "Id": "20646", "Score": "19", "Tags": [ "python", "beginner", "child-process", "raspberry-pi" ], "Title": "Automatically turn on Computer from Raspberry Pi (based on user presence in home)" }
20646
<p>My son (9) is learning Python and wrote this temperature conversion program. He can see that there is a lot of repetition in it and would like to get feedback on ways to make it shorter.</p> <pre><code>def get_temperature(): print "What is your temperature?" while True: temperature = raw_input() try: return float(temperature) except ValueError: print "Not a valid temperature. Could you please do this again?" print "This program tells you the different temperatures." temperature = get_temperature() print "This is what it would be if it was Fahrenheit:" Celsius = (temperature - 32)/1.8 print Celsius, "degrees Celsius" Kelvin = Celsius + 273.15 print Kelvin, "Kelvin" print "This is what it would be if it was Celsius." Fahrenheit = temperature * 9 / 5 + 32 print Fahrenheit, "degrees Fahrenheit" Kelvin = temperature + 273.15 print Kelvin, "Kelvin" print "This is what it would be if it was Kelvin" Celsius = temperature - 273.15 print Celsius, "degrees Celsius" Fahrenheit = Celsius * 9 / 5 + 32 print Fahrenheit, "degrees Fahrenheit" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T12:56:32.623", "Id": "33194", "Score": "0", "body": "Out of curiosity: why didn't your son ask here himself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T12:59:52.990", "Id": "33195", "Score": "5", "body": "[`Subscriber certifies to Stack Exchange that if Subscriber is an individual (i.e., not a corporate entity), Subscriber is at least 13 years of age`](http://stackexchange.com/legal#1AccesstotheServices)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T13:12:23.787", "Id": "33197", "Score": "0", "body": "@vikingosegundo I did not know that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T13:20:42.360", "Id": "33198", "Score": "2", "body": "@svick I think it is quite common to exclude kids younger than 13. So maybe this 9-yo is very clever and poses as his father :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T19:04:41.963", "Id": "33208", "Score": "0", "body": "Although the answers already given below are useful, I would say the first thing is to consider whether he really wants to print all possible conversions, or instead allow the user to specify a unit (which as it happens would avoid the need for most of the repetition). I.e. think about the aim of the programme before implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-20T02:09:36.030", "Id": "33224", "Score": "3", "body": "I just realized the delightful detail of not adding 'degrees' in front of 'Kelvin'! I've had professors in college doing it wrong all the time..." } ]
[ { "body": "<p>He should define functions that he can re-use:</p>\n\n<pre><code>def fahrenheit_from_celsius(temprature):\n return temperature * 9 / 5 + 32\n\n\nprint fahrenheit_from_celsius(get_temperature())\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T12:24:57.323", "Id": "20709", "ParentId": "20708", "Score": "1" } }, { "body": "<p>The most repetition in that program comes from printing the converted temperatures. When a program contains repeated code, the most common solution is to <a href=\"http://en.wikipedia.org/wiki/Code_refactoring\" rel=\"nofollow\">refactor</a> the code by extracting a function. The new function would contain the common parts, and use its parameters for the differing parts.</p>\n\n<p>In your case, the function could look like this:</p>\n\n<pre><code>def print_temperatures(original_unit, first_value, first_unit, second_value, second_unit):\n print \"This is what it would be if it was\", original_unit\n print first_value, first_unit\n print second_value, second_unit\n</code></pre>\n\n<p>The code to print the temperatures (assuming the differences in punctuation are not intentional):</p>\n\n<pre><code>print \"This program tells you the different temperatures.\"\ntemperature = get_temperature()\n\nCelsius = (temperature - 32)/1.8\nKelvin = Celsius + 273.15\nprint_temperatures(\"Fahrenheit\", Celsius, \"degrees Celsius\", Kelvin, \"Kelvin\")\n\nFahrenheit = temperature * 9 / 5 + 32\nKelvin = temperature + 273.15\nprint_temperatures(\"Celsius\", Fahrenheit, \"degrees Fahrenheit\", Kelvin, \"Kelvin\")\n\nCelsius = temperature - 273.15\nFahrenheit = Celsius * 9 / 5 + 32\nprint_temperatures(\"Kelvin\", Celsius, \"degrees Celsius\", Fahrenheit, \"degrees Fahrenheit\")\n</code></pre>\n\n<p>This still leaves some repetition in the temperature conversions themselves. This could be again solved by extracting a function for each conversion. Another solution would be to <a href=\"http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29\" rel=\"nofollow\">encapsulate</a> all the conversions into a class. That way, your code could look something like:</p>\n\n<pre><code>temperature_value = get_temperature()\n\ntemperature = Temperature.from_fahrenheit(temperature_value)\nprint_temperatures(\"Fahrenheit\", temperature.Celsius, \"degrees Celsius\", temperature.Kelvin, \"Kelvin\")\n</code></pre>\n\n<p>But creating a class would make more sense if conversions were used more, it probably isn't worth it for this short program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T13:55:35.467", "Id": "20713", "ParentId": "20708", "Score": "1" } }, { "body": "<p>Some of what I am going to write may be a little too much for a 9 year old, but if he was able to produce such neat, structured code on his own, he should be ready for some further challenge.</p>\n\n<p>So to make things less repetitive, all you have to do is figure out how to make what appears different to share a common framework. For the temperature conversions, they are all of the form:</p>\n\n<pre><code>return_value = (input_value + a) * b + c\n</code></pre>\n\n<p>Lazy programmers are better programmers, so you don´t want to figure out all six possible transformations by hand, so note that the reverse transformation has the form:</p>\n\n<pre><code>input_value = (return_value - c) / b - a\n</code></pre>\n\n<p>Furthermore, even specifying three of six transformations is too many, since you can always convert, e.g. from Celsius to Kelvin and then to Fahrenheit. So we just need to choose a <code>BASE_UNIT</code> and encode a transformation to or from it to all other. This will also make it a breeze to include <a href=\"http://en.wikipedia.org/wiki/Rankine_scale\" rel=\"nofollow\">Rankine degrees</a> or any other of the weird scales if you would so desire in the future.</p>\n\n<p>So the code below is probably going to end up being longer than what you posted, but the main program is just four lines of code, there's quite a lot of error checking, and it would be a breeze to update to new units:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>UNITS = 'fck'\nBASE_UNIT = 'k'\nUNIT_NAMES = {'f' : 'Fahrenheit', 'c' : 'Celsius', 'k' : 'Kelvin'}\nCONVERSION_FACTORS = {'fk' : (-32., 5. / 9., 273.16),\n 'ck' : (273.16, 1., 0.)}\n\ndef get_temperature():\n print \"What is your temperature?\"\n while True:\n temperature = raw_input()\n try:\n return float(temperature)\n except ValueError:\n print \"Not a valid temperature. Could you please do this again?\"\n\ndef convert_temp(temp, unit_from, unit_to) :\n if unit_from != BASE_UNIT and unit_to != BASE_UNIT :\n return convert_temp(convert_temp(temp, unit_from, BASE_UNIT),\n BASE_UNIT, unit_to)\n else :\n if unit_from + unit_to in CONVERSION_FACTORS :\n a, b, c = CONVERSION_FACTORS[unit_from + unit_to]\n return (temp + a) * b + c\n elif unit_to + unit_from in CONVERSION_FACTORS :\n a, b, c = CONVERSION_FACTORS[unit_to + unit_from]\n return (temp - c) / b - a \n else :\n msg = 'Unknown conversion key \\'{0}\\''.format(unit_from + unit_to)\n raise KeyError(msg)\n\ndef pretty_print_temp(temp, unit_from) :\n if unit_from not in UNITS :\n msg = 'Unknown unit key \\'{0}\\''.format(unit_from)\n raise KeyError(msg)\n txt = 'This is what it would be if it was {0}'\n print txt.format(UNIT_NAMES[unit_from])\n for unit_to in UNITS.replace(unit_from, '') :\n print '{0:.1f} degrees {1}'.format(convert_temp(temp, unit_from,\n unit_to),\n UNIT_NAMES[unit_to])\n\nif __name__ == '__main__' :\n\n print \"This program tells you the different temperatures.\"\n temperature = get_temperature()\n\n for unit_from in UNITS :\n pretty_print_temp(temperature, unit_from)\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT</strong> As an aside, for minimal length without modifying the logic of the original code, the following would work:</p>\n\n<pre><code>print \"This program tells you the different temperatures.\"\ntemperature = get_temperature()\ntext = ('This is what it would be if it was {0}:\\n'\n '{1:.1f} {2}\\n{3:.1f} {4}')\nprint \nCelsius = (temperature - 32) / 1.8\nKelvin = Celsius + 273.15\nprint text.format('Fahrenheit', Celsius, 'degrees Celsius', Kelvin, 'Kelvin')\nFahrenheit = temperature * 9 / 5 + 32\nKelvin = temperature + 273.15\nprint text.format('Celsius', Fahrenheit, 'degrees Fahrenheit', Kelvin,\n 'Kelvin')\nCelsius = temperature - 273.15\nFahrenheit = Celsius * 9 / 5 + 32\nprint text.format('Kelvin', Celsius, 'degrees Celsius', Fahrenheit,\n 'Fahrenheit')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T20:17:20.233", "Id": "33212", "Score": "2", "body": "A solution like this might make sense if you wanted to convert between many different units. But if you expect that you won't need any unusual units, this code is way too overengineered. Besides the question is how to make the program shorter, you made it longer and much more complicated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T23:10:58.537", "Id": "33216", "Score": "0", "body": "Your temperature conversions could get lazier still, since they are actually all of the form `return_value = input_value * a + c`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T23:31:18.463", "Id": "33217", "Score": "0", "body": "@svick I'd argue that the program is actually much, much shorter: 4 lines of code. It's the temperature conversion library functions that take up more space... In any real production environment in which you had to do all six possible conversions, I really don't see coding six different functions as a good design practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T23:32:01.910", "Id": "33218", "Score": "0", "body": "@Stuart But that would actually require me to do some of the math that I can have the computer do!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-20T00:19:34.130", "Id": "33219", "Score": "1", "body": "@Jaime For me “a program” is all code I have to develop and maintain for it. And that's not 4 lines in your case. And I really do think that 6 one-line functions are better than one big, that is hard to understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-20T01:28:55.667", "Id": "33220", "Score": "0", "body": "@svick I really don´t want to get into an argument about coding styles, but I see my code as easier to maintain, because all the logic is in one place. And given the very descriptive nature of the variable names, I do not find it that hard to understand. For the purpose of this particular program, there is no point in writing **any** function, because each conversion is done only once! Yet we both agree that encapsulating that logic is a good thing, right? I like to take things a little further. You don't. Can we agree to disagree?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-20T01:47:51.623", "Id": "33221", "Score": "1", "body": "I would say the problem is more that `convert_temp` is needlessly complicated and could be reduced to a few lines and made easier to read at the same time http://pastebin.com/jQkmR8Rz" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-20T02:08:15.077", "Id": "33223", "Score": "0", "body": "@Stuart Very nice approach, indeed!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T16:07:52.717", "Id": "20717", "ParentId": "20708", "Score": "2" } }, { "body": "<p>The easiest way to remove repetition here is with nested <code>for</code> loops, going through all the combinations of units. In the code below I also use the fact that you can convert between any two scales in the following way:</p>\n\n<ol>\n<li>subtract something then divide by something to get back to Celsius, then</li>\n<li>multiply by something then add something to get to the desired unit</li>\n</ol>\n\n<p>The \"something\"s can be stored in a single tuple (list of values), making the conversions simpler.</p>\n\n<pre><code>scales = ('Celsius', 'degrees ', 1, 0), ('Farenheit', 'degrees ', 1.8, 32), ('Kelvin', '', 1, 273.15)\nvalue = get_temperature()\nfor from_unit, _, slope1, intercept1 in scales:\n print \"This is what it would be if it was\", from_unit\n celsius = (value - intercept1) / slope1\n for to_unit, prefix, slope2, intercept2 in scales:\n if to_unit != from_unit:\n print '{0} {1}{2}'.format(intercept2 + slope2 * celsius, degrees, to_unit)\n</code></pre>\n\n<p>Dividing code into functions is of course a good idea in general, but not that useful in this case. If he's interested in performing other operations on temperatures it might be interesting to go a step further and make a simple class like the following.</p>\n\n<pre><code>scales = {\n 'Celsius': ('degrees ', 1, 0),\n 'Farenheit': ('degrees ', 1.8, 32),\n 'Kelvin': ('', 1, 273.15)\n }\nclass Temperature: \n def __init__(self, value, unit = 'Celsius'):\n self.original_unit = unit\n _, slope, intercept = scales[unit]\n self.celsius = (value - intercept) / slope\n def to_unit(self, unit):\n _, slope, intercept = scales[unit]\n return slope * self.celsius + intercept\n def print_hypothetical(self):\n print \"This is what it would be if it was\", self.original_unit\n for unit, (prefix, _, _) in scales.iteritems():\n if unit != self.original_unit:\n print \"{0} {1}{2}\".format(self.to_unit(unit), prefix, unit)\nvalue = get_temperature()\nfor unit in scales:\n m = Temperature(value, unit)\n m.print_hypothetical()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T22:18:06.727", "Id": "20732", "ParentId": "20708", "Score": "4" } } ]
{ "AcceptedAnswerId": "20732", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T12:17:27.710", "Id": "20708", "Score": "3", "Tags": [ "python", "converting" ], "Title": "Temperature conversion program with a lot of repetition" }
20708
<p>This is my try at <a href="http://en.wikipedia.org/wiki/Proxy_pattern" rel="nofollow">the proxy pattern</a>.</p> <p>What do you Pythoneers think of my attempt?</p> <pre><code>class Image: def __init__( self, filename ): self._filename = filename def load_image_from_disk( self ): print("loading " + self._filename ) def display_image( self ): print("display " + self._filename) class Proxy: def __init__( self, subject ): self._subject = subject self._proxystate = None class ProxyImage( Proxy ): def display_image( self ): if self._proxystate == None: self._subject.load_image_from_disk() self._proxystate = 1 print("display " + self._subject._filename ) proxy_image1 = ProxyImage ( Image("HiRes_10Mb_Photo1") ) proxy_image2 = ProxyImage ( Image("HiRes_10Mb_Photo2") ) proxy_image1.display_image() # loading necessary proxy_image1.display_image() # loading unnecessary proxy_image2.display_image() # loading necessary proxy_image2.display_image() # loading unnecessary proxy_image1.display_image() # loading unnecessary </code></pre> <p>Output:</p> <pre><code>loading HiRes_10Mb_Photo1 display HiRes_10Mb_Photo1 display HiRes_10Mb_Photo1 loading HiRes_10Mb_Photo2 display HiRes_10Mb_Photo2 display HiRes_10Mb_Photo2 display HiRes_10Mb_Photo1 </code></pre>
[]
[ { "body": "<p>It seems like overkill to implement a class to represent the proxy pattern. <em>Design patterns are patterns, not classes.</em> What do you gain from your implementation compared to a simple approach like the one shown below?</p>\n\n<pre><code>class Image(object):\n def __init__(self, filename):\n self._filename = filename\n self._loaded = False\n\n def load(self):\n print(\"loading {}\".format(self._filename))\n self._loaded = True\n\n def display(self):\n if not self._loaded:\n self.load()\n print(\"displaying {}\".format(self._filename))\n</code></pre>\n\n<p>Some other notes on your code:</p>\n\n<ol>\n<li><p>It doesn't follow <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>. In particular, \"Avoid extraneous whitespace [...] immediately inside parentheses.\"</p></li>\n<li><p>No docstrings.</p></li>\n<li><p>It makes more sense to use <code>True</code> and <code>False</code> for a binary condition than to use <code>None</code> and <code>1</code>.</p></li>\n<li><p>It's not necessary to append the class name to all the methods. In a class called <code>Image</code>, the methods should just be called <code>load</code> and <code>display</code>, not <code>load_image</code> and <code>display_image</code>.</p></li>\n<li><p>You should use new-style classes (inheriting from <code>object</code>) to make your code portable between Python 2 and 3.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T14:08:17.773", "Id": "33356", "Score": "0", "body": "I think it can make sense to have separate `Image` and `ImageProxy` objects (though a better name might be something like `LazyImage`), because of separation of concerns. And even better (assuming the added complexity would be worth it) would be some sort of generic `LazyLoadingProxy` class, which could work with `Image`s and also other objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T14:17:05.750", "Id": "33357", "Score": "1", "body": "It's possible, but we'd only know in the context of a whole application: if there really are several different types of assets that need to be lazily loaded, then it might make sense to have a class to handle the lazy loading, but it might still be simpler to implement that class as a mixin rather than a proxy. A proxy object is usually a last resort when you don't control the code for the class you are proxying." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T13:33:10.253", "Id": "20800", "ParentId": "20798", "Score": "7" } } ]
{ "AcceptedAnswerId": "20800", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-22T13:08:25.817", "Id": "20798", "Score": "3", "Tags": [ "python", "design-patterns" ], "Title": "proxy pattern in Python" }
20798
<p>I've recently discovered the wonders of the Python world, and am quickly learning. Coming from <code>Windows/C#/.NET</code>, I find it refreshing working in <code>Python</code> on <code>Linux</code>. A day you've learned something new is not a day wasted.</p> <p>I need to unpack data received from a device. Data is received as a string of "bytes", of arbitrary length. Each packet (string) consists of samples, for eight channels. The number of samples varies, but will always be a multiple of the number of channels. The channels are interleaved. To make things a bit more complex, samples can be either 8 or 16 bits in length. Check the code, and you'll see.</p> <p>I've already got a working implementation. However, as I've just stumbled upon generators, iterators, maps and ... numpy, I suspect there might be a more efficient way of doing it. If not efficient, maybe more "pythonic". I'm curious, and if someone would spend some time giving me a pointer in the right (or any) direction, I would be very grateful. As of now, I am aware of the fact that my Python has a strong smell of C#. But I'm learning ...</p> <p>This is my working implementation. It is efficient enough, but I suspect it can be improved. Especially the de-interleaving part. On my machine it prints:</p> <pre><code>time to create generator: 0:00:00.000040 time to de-interleave data: 0:00:00.004111 length of channel A is 750: True </code></pre> <p>As you can see, creating the generator takes no amount of time. De-interleaving the data is the real issue. Maybe the data generation and de-interleaving can be done simultaneously?</p> <p>This is not my first implementation, but I never seem to be able to drop below approx <code>4 ms</code>.</p> <hr> <pre><code>from datetime import datetime def unpack_data(data): l = len(data) p = 0 while p &lt; l: # convert 'char' or byte to (signed) int8 i1 = (((ord(data[p]) + 128) % 256) - 128) p += 1 if i1 &amp; 0x01: # read next 'char' as an (unsigned) uint8 # # due to the nature of the protocol, # we will always have sufficient data # available to avoid reading past the end i2 = ord(data[p]) p += 1 yield (i1 &gt;&gt; 1 &lt;&lt; 8) + i2 else: yield i1 &gt;&gt; 1 # generate some test data ... test_data = '' for n in range(500 * 12 * 2 - 1): test_data += chr(n % 256) t0 = datetime.utcnow() # in this example we have 6000 samples, 8 channels, 750 samples/channel # data received is interleaved: A1, B1, C1, ..., A2, B2, C2, ... F750, G750, H750 channels = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H') samples = { channel : [] for channel in channels} # call unpack_data(), receive a generator gen = unpack_data(test_data) t1 = datetime.utcnow() print 'time to create generator: %s' % (t1-t0) try: while True: for channel in channels: samples[channel].append(gen.next()) except StopIteration: pass print 'time to de-interleave data: %s' % (datetime.utcnow()-t1) print 'length of channel A is 750: %s' % (len(samples['A']) == 750) </code></pre>
[]
[ { "body": "<p><em>simple unpacking</em> can be done with the zip built-in as @Lattyware has pointed out:<br>\nthat could be something like: </p>\n\n<pre><code>zip(*[data[idx:idx + num_channels] for idx in range(0, len(data), num_channels)])\n</code></pre>\n\n<p>(note the (*) which is inverting zip by handing over the items of the sequence as separate parameters).</p>\n\n<p>However, as you are transforming the values while you unpack, and even have different cases with 1 or 2 bytes per sample, I think your approach is ok.<br>\nAnyway, you won't be able to avoid iterating over all the samples. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-25T16:41:29.953", "Id": "20902", "ParentId": "20895", "Score": "2" } } ]
{ "AcceptedAnswerId": "20909", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-25T14:16:14.827", "Id": "20895", "Score": "3", "Tags": [ "python", "numpy" ], "Title": "A pythonic way of de-interleaving a list (i.e. data from a generator), into multiple lists" }
20895
<p>I'm having concerns about the readability of this piece of code:</p> <pre class="lang-py prettyprint-override"><code> messages_dict = {'error':errors, 'warning':warnings}[severity] messages_dict[field_key] = message </code></pre> <p>and I'm to use this instead:</p> <pre class="lang-py prettyprint-override"><code> if severity == 'error': messages_dict = errors elif severity == 'warning': messages_dict = warnings else: raise ValueError('Incorrect severity value') messages_dict[field_key] = message </code></pre> <p>But it looks too verbose for such a simple thing.</p> <p>I don't care too much if it's more efficient than constructing a dictionary for just two mappings. Readability and maintainability is my biggest concern here (<code>errors</code> and <code>warnings</code> are method arguments, so I cannot build the lookup dictionary beforehand and reuse it later).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-25T14:43:51.320", "Id": "33509", "Score": "0", "body": "I don't see the readability concern with the first case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-25T14:52:20.773", "Id": "33510", "Score": "0", "body": "I thought that it might puzzle an unaware reader..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-25T15:08:49.243", "Id": "33511", "Score": "0", "body": "Unaware of what? Dictionaries? They are a core Python data structure - if someone can't read that, they don't know Python. You can't write code that is readable for someone who have no idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-25T17:21:55.510", "Id": "33519", "Score": "0", "body": "I meant unaware of the 'pattern' (using a dict to choose between two options). I've seen complaints in peer reviews about using boolean operators in a similar way (like `x = something or default`, maybe a little bit more complex) because it was _obscure_ :-/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-26T14:14:55.613", "Id": "33547", "Score": "0", "body": "That's a different situation, as it's relatively unclear what is going on (and is better replaced by the ternary operator). This isn't particularly a pattern, it's just a use of dictionaries." } ]
[ { "body": "<p>They are not exactly the same, as they behave differently when given an invalid severity. For a fair comparison, the first example code should probably be something like:</p>\n<pre><code>try:\n messages_dict = {'error':errors, 'warning':warnings}[severity]\n\nexcept KeyError:\n raise ValueError(f'Incorrect severity value: {severity}.')\n\nmessages_dict[field_key] = message\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-17T03:53:41.530", "Id": "254821", "ParentId": "20896", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-01-25T14:41:37.067", "Id": "20896", "Score": "1", "Tags": [ "python", "hash-map", "lookup" ], "Title": "Readability concerns with literal dictionary lookup vs if-else" }
20896
<p>Am supposed to capture user input as an integer, convert to a binary, reverse the binary equivalent and convert it to an integer.Am getting the right output but someone says the solution is wrong. Where is the problem?</p> <pre><code>x = 0 while True: try: x = int(raw_input('input a decimal number \t')) if x in xrange(1,1000000001): y = bin(x) rev = y[2:] print("the reverse binary soln for the above is %d") %(int('0b'+rev[::-1],2)) break except ValueError: print("Please input an integer, that's not an integer") continue </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T22:28:35.517", "Id": "33596", "Score": "2", "body": "If you are asking us to find an error in your code, then I'm afraid your question if off topic on Code Review. This is site is for reviewing code that you think is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T22:55:49.733", "Id": "33597", "Score": "1", "body": "I think ist's correct since it gives the required output, I just want to know if there's something I can do to make it work better" } ]
[ { "body": "<pre><code>x = 0\n</code></pre>\n\n<p>There is no point in doing this. You just replace it anyways</p>\n\n<pre><code>while True:\n\n try:\n x = int(raw_input('input a decimal number \\t'))\n\n\n if x in xrange(1,1000000001):\n</code></pre>\n\n<p>Probably better to use <code>if 1 &lt;= x &lt;= 100000000001:</code> although I'm really not sure why you are doing this check. Also, you should probably explain to the user that you've reject the number.</p>\n\n<pre><code> y = bin(x)\n\n rev = y[2:]\n</code></pre>\n\n<p>I'd use <code>reversed = bin(x)[:1::-1]</code> rather then splitting it out across the tree lines.</p>\n\n<pre><code> print(\"the reverse binary soln for the above is %d\") %(int('0b'+rev[::-1],2)) \n</code></pre>\n\n<p>I'd convert the number before the print to seperate output from the actual math.</p>\n\n<pre><code> break\n\n except ValueError:\n print(\"Please input an integer, that's not an integer\")\n continue\n</code></pre>\n\n<p>This continue does nothing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T23:45:58.330", "Id": "20968", "ParentId": "20965", "Score": "5" } } ]
{ "AcceptedAnswerId": "20968", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-27T21:48:57.497", "Id": "20965", "Score": "3", "Tags": [ "python" ], "Title": "Python Reverse the binary equivalent of input and output the integer equivalent of the reverse binary" }
20965
<p>I've recently discovered how cool <code>reduce()</code> could be and I want to do this:</p> <pre><code>&gt;&gt;&gt; a = [1, 1] + [0] * 11 &gt;&gt;&gt; count = 1 &gt;&gt;&gt; def fib(x,n): ... global count ... r = x + n ... if count &lt; len(a) - 1: a[count+1] = r ... count += 1 ... return r &gt;&gt;&gt; &gt;&gt;&gt; reduce(fib,a,1) 610 &gt;&gt;&gt; a [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233] </code></pre> <p>But this just looks so messy and almost defeats the purpose of the last line:</p> <pre><code>reduce(fib,a,1) </code></pre> <p>What would be a better way to use Python to make a Fibonacci number with <code>reduce()</code>?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T16:14:07.087", "Id": "33681", "Score": "2", "body": "Why do you want to use reduce?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T16:18:40.630", "Id": "33682", "Score": "1", "body": "Because it seemed cool. I want to use something like reduce, or map. Because it seems like a challenge." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T23:06:09.840", "Id": "33722", "Score": "0", "body": "@CrisStringfellow It's not really the right tool for the job. A generator would be the best choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:39:31.140", "Id": "33738", "Score": "0", "body": "@Lattyware okay but a generator is just too easy." } ]
[ { "body": "<p>If you set</p>\n\n<pre><code>def fib(x, _):\n x.append(sum(x[-2:]))\n return x\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>&gt;&gt;&gt; reduce(fib, xrange(10), [1, 1])\n[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]\n</code></pre>\n\n<p>But as long as you're looking for something cool rather than something useful, how about this? In Python 3.3:</p>\n\n<pre><code>from itertools import islice\nfrom operator import add\n\ndef fib():\n yield 1\n yield 1\n yield from map(add, fib(), islice(fib(), 1, None))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T21:41:53.663", "Id": "33717", "Score": "2", "body": "I guess the second snippet tries to mimic Haskell's `fibs = 0 : 1 : zipWith (+) fibs (tail fibs)`. Unfortunately this is terribly inefficient in Python, you'd need to write it in more verbose manner using corecursion and `itertools.tee` (thus the beauty of the Haskell solution completely vanishes). http://en.wikipedia.org/wiki/Corecursion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T21:45:50.247", "Id": "33718", "Score": "0", "body": "Yes: that's why I described it as \"cool rather than useful\"!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:41:10.247", "Id": "33739", "Score": "0", "body": "I like that a lot the second snippet." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T20:53:48.787", "Id": "21004", "ParentId": "20986", "Score": "2" } }, { "body": "<p>A <code>reduce</code> (that's it, a fold) is not exactly the abstraction for the task (what input collection are you going to fold here?). Anyway, you can cheat a little bit and fold the indexes even if you don't really use them within the folding function. This works for Python 2.x:</p>\n\n<pre><code>def next_fib((x, y), n):\n return (y, x + y)\n\nreduce(next_fib, xrange(5), (1, 1))[0]\n#=&gt; 8\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T07:46:05.433", "Id": "33740", "Score": "0", "body": "That is awesome." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T21:14:06.177", "Id": "21005", "ParentId": "20986", "Score": "4" } }, { "body": "<p>In your case, the interesting part of <code>reduce</code> is to re-apply a function.\nSo, let's define :</p>\n\n<pre><code>&gt;&gt;&gt; def ncompose(f, a, n): return a if n &lt;= 0 else ncompose(f, f(a), n-1)\n</code></pre>\n\n<p>Then,</p>\n\n<pre><code>&gt;&gt;&gt; def fibo((a,b)): return (b, a+b)\n&gt;&gt;&gt; ncompose(fibo, (1,1), 5)[0]\n8\n</code></pre>\n\n<p>Since you like to play with <code>reduce</code>, let's use it to perform composition :</p>\n\n<pre><code>&gt;&gt;&gt; reduce(lambda a,f: f(a), [fibo]*5, (1,1))\n</code></pre>\n\n<p>Like @tokland's answer, it's quite artificial (building n items only as a way to iterate n times).</p>\n\n<p>A side note : Haskell and Scala should provide you even more fun'. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:49:34.360", "Id": "21038", "ParentId": "20986", "Score": "1" } } ]
{ "AcceptedAnswerId": "21005", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-28T14:29:54.510", "Id": "20986", "Score": "4", "Tags": [ "python", "fibonacci-sequence" ], "Title": "Making this reduce() Fibonacci generator better" }
20986
<p>I want to perform standard additive carry on a vector. The base is a power of 2, so we can swap modulus for bitwise AND.</p> <pre><code>def carry(z,direction='left',word_size=8): v = z[:] mod = (1&lt;&lt;word_size) - 1 if direction == 'left': v = v[::-1] accum = 0 for i in xrange(len(v)): v[i] += accum accum = v[i] &gt;&gt; word_size v[i] = v[i] &amp; mod print accum,v if direction == 'left': v = v[::-1] return accum,v </code></pre> <p>Is there any way to make this function even tinier? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:30:16.583", "Id": "33753", "Score": "0", "body": "It would be very handy if you include some `assert`s (3 ó 4) so people can test their refactors easily." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:53:27.187", "Id": "33755", "Score": "0", "body": "Good point. I will." } ]
[ { "body": "<p>I got it:</p>\n\n<pre><code>def carry2(z,direction='left',word_size=8):\n x = z[:]\n v = []\n mod = (1&lt;&lt;word_size) - 1\n if direction == 'left': x.reverse()\n def cu(a,n):\n v.append((a+n)&amp;mod)\n return (a+n) &gt;&gt; word_size\n accum = reduce(cu,x,0)\n if direction == 'left': v.reverse()\n return accum,v\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T13:34:28.187", "Id": "33754", "Score": "1", "body": "You are clearly stuck in the imperative paradigm, that's why the code is so verbose (and hard to understand). Check http://docs.python.org/2/howto/functional.html and google for \"python functional programming\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T08:56:05.947", "Id": "33803", "Score": "0", "body": "Thanks! I'm getting started. My latest code has a lot more generators, lambdas and functional style...but I am just getting started." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T10:13:25.350", "Id": "21020", "ParentId": "21019", "Score": "0" } }, { "body": "<ol>\n<li><p>Your code has a lot of copying in it. In the default case (where <code>direction</code> is <code>left</code>) you copy the array three times. This seems like a lot. There are various minor improvements you can make, for example instead of</p>\n\n<pre><code>v = v[::-1]\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>v.reverse()\n</code></pre>\n\n<p>which at least re-uses the space in <code>v</code>.</p>\n\n<p>But I think that it would be much better to reorganize the whole program so that you store your bignums the other way round (with the least significant word at the start of the list), so that you can always process them in the convenient direction.</p></li>\n<li><p>The parameters <code>direction</code> and <code>word_size</code> are part of the description of the data in <code>z</code>. So it would make sense to implement this code as a class to keep these values together. And then you could ensure that the digits always go in the convenient direction for your canonicalization algorithm.</p>\n\n<pre><code>class Bignum(object):\n def __init__(self, word_size):\n self._word_size = word_size\n self._mod = 2 ** word_size\n self._digits = []\n\n def canonicalize(self, carry = 0):\n \"\"\"\n Add `carry` and canonicalize the array of digits so that each\n is less than the modulus.\n \"\"\"\n assert(carry &gt;= 0)\n for i, d in enumerate(self._digits):\n carry, self._digits[i] = divmod(d + carry, self._mod)\n while carry:\n carry, d = divmod(carry, self._mod)\n self._digits.append(d)\n</code></pre></li>\n<li><p>Python already has built-in support for bignums, anyway, so what exactly are you trying to do here that can't be done in vanilla Python?</p>\n\n<p>Edited to add: I see from your comment that I misunderstood the context in which this function would be used (so always give us the context!). It's still the case that you could implement what you want using Python's built-in bignums, for example if you represented your key as an integer then you could write something like:</p>\n\n<pre><code>def fold(key, k, word_size):\n mod = 2 ** (k * word_size)\n accum = 0\n while key:\n key, rem = divmod(key, mod)\n accum += rem\n return accum % mod\n</code></pre>\n\n<p>but if you prefer to represent the key as a list of words, then you could still implement the key-folding operation directly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import izip_longest\n\nclass WordArray(object):\n def __init__(self, data = [], word_size = 8):\n self._word_size = word_size\n self._mod = 1 &lt;&lt; word_size\n self._data = data\n\n def fold(self, k):\n \"\"\"\n Fold array into parts of length k, add them with carry, and return a\n new WordArray. Discard the final carry, if any.\n \"\"\"\n def folded():\n parts = [xrange(i * k, min((i + 1) * k, len(self._data))) \n for i in xrange((len(self._data) + 1) // k)]\n carry = 0\n for ii in izip_longest(*parts, fillvalue = 0):\n carry, z = divmod(sum(self._data[i] for i in ii) + carry, self._mod)\n yield z\n return WordArray(list(folded()), self._word_size)\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:04:28.820", "Id": "33756", "Score": "0", "body": "Thanks a lot. I will make my way through it. Just quickly the objective is not bignum. I fold an array into parts of length k and add these together, but I preserve the length k, so I discard any carry that falls off one end. It's a mixing step in a key scheduling part of a crypto." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:32:41.510", "Id": "33758", "Score": "0", "body": "Your approach reminded me of this: http://pyvideo.org/video/880/stop-writing-classes 'the signature of *this shouldn't be a class* is that it has two methods, one of which is `__init__`, anytime you see this you should think \"hey, maybe I only need that one method!\"'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:35:26.843", "Id": "33759", "Score": "1", "body": "@Jaime: it should be clear, I hope, that my classes aren't intended to be complete. I believe that the OP has more operations that he hasn't told us about, that in a complete implementation would become methods on these classes. (Do you think I need to explain this point?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T08:59:44.737", "Id": "33804", "Score": "0", "body": "Had a closer, look @GarethRees -- that's awesome. I really like that. Very concise on the loops in the BigNum class. Looking at the next part now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T09:04:06.150", "Id": "33805", "Score": "0", "body": "You understood me perfectly on the second part. I am pretty shocked since I gave just a tiny description. That is really clever, too. You are amazing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:38:32.257", "Id": "33812", "Score": "0", "body": "Thanks for the edit. I generally write `//` for integer (floor) division so that code is portable between Python 2 and Python 3." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T14:01:20.173", "Id": "21029", "ParentId": "21019", "Score": "2" } }, { "body": "<p>Preliminary remarks :</p>\n\n<ul>\n<li>Functional idioms and imperative mutations doesn't play well (except when they do. Cf Scala). Here, both FP and Python lovers will likely be lost !</li>\n<li>Since there is exactly 2 possible directions, use a Boolean. It will prevent typo (trying to pass 'Left' for instance).</li>\n<li>Extract the main computation to a dedicated function. First benefice : you won't have to test for direction twice, which is error prone.</li>\n<li>(1st version) : instead of copying + updating via index (awkward), generate a brand new sequence.</li>\n</ul>\n\n<p>That's an interesting question, since it requires both folding (to propagate the carry) and mapping from updated values (to apply <code>mod</code>, ie get the less significant bits). \nSince it's not that common, I suggest to stick with a standard Python approach. Don't force an idiom if it obfuscates.</p>\n\n<pre><code>def carry_from_left(z, word_size):\n mod = (1&lt;&lt;word_size) - 1\n res = []\n acc = 0\n for a in z :\n tot = a + acc\n res.append(tot &amp; mod)\n acc = tot &gt;&gt; word_size\n return (acc, res)\n\ndef carry(z, left_to_right = False, word_size=8):\n if left_to_right :\n return carry_from_left(z, word_size)\n else:\n acc, res = carry_from_left(reversed(z), word_size)\n res.reverse() #inplace. Nevermind, since it's a brand new list.\n return (acc, res)\n</code></pre>\n\n<p>Now, if this \"map+fold\" pattern occurs frequently, you can abstract it.</p>\n\n<pre><code>def fold_n_map (f, l, acc):\n \"\"\" Apply a function (x, acc) -&gt; (y, acc') cumulatively.\n Return a tuple consisting of folded (reduced) acc and list of ys.\n TODO : handle empty sequence, optional initial value, etc,\n in order to mimic 'reduce' interface\"\"\"\n res = []\n for x in l :\n y, acc = f(x, acc)\n res.append(y)\n return acc, res\n\ndef carry_fold_left(z, word_size):\n mod = (1&lt;&lt;word_size) - 1\n #Nearly a one-liner ! Replace lambda by named function for your Python fellows.\n return fold_n_map(lambda x, acc: ((x+acc) &amp; mod, (x+acc) &gt;&gt; word_size), z, 0)\n\ndef carry(z, left_to_right = False, word_size=8):\n #idem\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T02:21:37.147", "Id": "33880", "Score": "0", "body": "Cool, I like that. *Especially* the abstraction of the pattern." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T20:51:17.997", "Id": "21076", "ParentId": "21019", "Score": "1" } } ]
{ "AcceptedAnswerId": "21029", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T09:46:03.803", "Id": "21019", "Score": "2", "Tags": [ "python", "converting" ], "Title": "Convert carry-add loop to a map or reduce to one-liner" }
21019
<p>I'm trying to learn how to write functional code with Python and have found some tutorials online. Please note that I know Python is not a promoter for functional programming. I just want to try it out. <a href="http://anandology.com/python-practice-book/functional-programming.html">One tutorial</a> in particular gives this as an exercise:</p> <blockquote> <p>Write a function flatten_dict to flatten a nested dictionary by joining the keys with . character.</p> </blockquote> <p>So I decided to give it a try. Here is what I have and it works fine:</p> <pre><code>def flatten_dict(d, result={}, prv_keys=[]): for k, v in d.iteritems(): if isinstance(v, dict): flatten_dict(v, result, prv_keys + [k]) else: result['.'.join(prv_keys + [k])] = v return result </code></pre> <p>I'd like to know whether this is the best way to solve the problem in python. In particular, I really don't like to pass a list of previous keys to the recursive call. </p>
[]
[ { "body": "<p>Your solution really isn't at all functional. You should return a flattened dict and then merge that into your current dictionary. You should also not modify the dictionary, instead create it with all the values it should have. Here is my approach:</p>\n\n<pre><code>def flatten_dict(d):\n def items():\n for key, value in d.items():\n if isinstance(value, dict):\n for subkey, subvalue in flatten_dict(value).items():\n yield key + \".\" + subkey, subvalue\n else:\n yield key, value\n\n return dict(items())\n</code></pre>\n\n<p>Alternative which avoids yield</p>\n\n<pre><code>def flatten_dict(d):\n def expand(key, value):\n if isinstance(value, dict):\n return [ (key + '.' + k, v) for k, v in flatten_dict(value).items() ]\n else:\n return [ (key, value) ]\n\n items = [ item for k, v in d.items() for item in expand(k, v) ]\n\n return dict(items)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:39:53.393", "Id": "33764", "Score": "0", "body": "Thanks. I was trying to iterate through the result during each recursive step but it returns an error stating the size of the dictionary changed. I'm new to python and I barely understand yield. Is it because yield creates the value on the fly without storing them that the code is not blocked anymore?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:45:27.547", "Id": "33765", "Score": "0", "body": "One thing though. I did return a flattened dict and merged it into a current dictionary, which is the flattened result of the original dictionary. I'd like to know why it was not functional at all..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:05:55.500", "Id": "33767", "Score": "0", "body": "@LimH., if you got that error you were modifying the dictionary you were iterating over. If you are trying to be functional, you shouldn't be modifying dictionaries at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:07:34.050", "Id": "33769", "Score": "0", "body": "No, you did not return a flattened dict and merge it. You ignore the return value of your recursive function call. Your function modifies what is passed to it which is exactly that which you aren't supposed to do in functional style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:08:37.700", "Id": "33771", "Score": "0", "body": "yield does create values on the fly, but that has nothing to do with why this works. It works because it creates new objects and never attempts to modify the existing ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:09:11.227", "Id": "33772", "Score": "0", "body": "I see my mistakes now. Thank you very much :) I thought I was passing copies of result to the function. In fact, I think the author of the tutorial I'm following makes the same mistake, at least with the flatten_list function: http://anandology.com/python-practice-book/functional-programming.html#example-flatten-a-list" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:49:06.400", "Id": "33785", "Score": "0", "body": "Unfortunately, both versions are bugged for 3+ levels of recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:36:07.440", "Id": "33793", "Score": "2", "body": "@JohnOptionalSmith, I see the problem in the second version, but the first seems to work for me... test case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:17:53.050", "Id": "33807", "Score": "0", "body": "@WinstonEwert Try it with `a = { 'a' : 1, 'b' : { 'leprous' : 'bilateral' }, 'c' : { 'sigh' : 'somniphobia'} }` (actually triggers the bug with 2-level recursion)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:33:31.610", "Id": "33810", "Score": "0", "body": "My bad ! CopyPaste error ! Your first version is fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:01:49.873", "Id": "272490", "Score": "0", "body": "Thanks for this nice code snippet @WinstonEwert! Could you explain why you defined a function in a function here? Is there a benefit to doing this instead of defining the same functions outside of one another?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:20:31.280", "Id": "272493", "Score": "2", "body": "@zelusp, the benefit is organizational, the function inside the function is part of of the implementation of the outer function, and putting the function inside makes it clear and prevents other functions from using it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:33:43.197", "Id": "272496", "Score": "0", "body": "[This link](https://realpython.com/blog/python/inner-functions-what-are-they-good-for/) helped me understand better" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:20:49.623", "Id": "21035", "ParentId": "21033", "Score": "19" } }, { "body": "<p>Beside avoiding mutations, functional mindset demands to split into elementary functions, along two axes:</p>\n\n<ol>\n<li>Decouple responsibilities.</li>\n<li>By case analysis (eg pattern matching). Here scalar vs dict. </li>\n</ol>\n\n<p>Regarding 1, nested dict traversal has nothing to do with the requirement to create dot separated keys. We've better return a list a keys, and concatenate them afterward. Thus, if you change your mind (using another separator, making abbreviations...), you don't have to dive in the iterator code -and worse, modify it.</p>\n\n<pre><code>def iteritems_nested(d):\n def fetch (suffixes, v0) :\n if isinstance(v0, dict):\n for k, v in v0.items() :\n for i in fetch(suffixes + [k], v): # \"yield from\" in python3.3\n yield i\n else:\n yield (suffixes, v0)\n\n return fetch([], d)\n\ndef flatten_dict(d) :\n return dict( ('.'.join(ks), v) for ks, v in iteritems_nested(d))\n #return { '.'.join(ks) : v for ks,v in iteritems_nested(d) }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T09:27:12.087", "Id": "33806", "Score": "0", "body": "Thank you for your response. Let me see if I get this right. Basically there are two strategies here. One is to recursively construct the dictionary result and one is to construct the suffixes. I used the second approach but my mistake was that I passed a reference of the result down the recursive chains but the key part is correct. Is that right? Winston Etwert used the first approach right? What's wrong with his code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:25:24.513", "Id": "33808", "Score": "0", "body": "The point is to (a) collect keys until deepest level and (b) concatenate them. You indeed did separate the two (although packed in the same function). Winston concatenate on the fly without modifying (mutating) anything, but an issue lies in recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:34:48.367", "Id": "33811", "Score": "0", "body": "My bad : Winston's implementation with yield is ok !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:38:34.250", "Id": "33818", "Score": "0", "body": "Is packing multiple objectives in the same function bad? I.e., is it bad style or is it conceptually incorrect?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:01:43.017", "Id": "33859", "Score": "0", "body": "@LimH. [Both !](http://www.cs.utexas.edu/~shmat/courses/cs345/whyfp.pdf). It can be necessary for performance reason, since Python won't neither inline nor defer computation (lazy programming). To alleviate this point, you can follow the opposite approach : provide to the iterator the way to collect keys -via a folding function- (strategy pattern, kind of)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:47:57.963", "Id": "21045", "ParentId": "21033", "Score": "9" } } ]
{ "AcceptedAnswerId": "21035", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:08:41.920", "Id": "21033", "Score": "14", "Tags": [ "python", "functional-programming" ], "Title": "Flatten dictionary in Python (functional style)" }
21033
<p>Could I code differently to slim down the point of this Python source code? The point of the program is to get the user's total amount and add it to the shipping cost. The shipping cost is determined by both country (Canada or USA) and price of product: The shipping of a product that is $125.00 in Canada is $12.00.</p> <pre><code>input ('Please press "Enter" to begin') while True: print('This will calculate shipping cost and your grand total.') totalAmount = int(float(input('Enter your total amount: ').replace(',', '').replace('$', ''))) Country = str(input('Type "Canada" for Canada and "USA" for USA: ')) usa = "USA" canada = "Canada" lessFifty = totalAmount &lt;= 50 fiftyHundred = totalAmount &gt;= 50.01 and totalAmount &lt;= 100 hundredFifty = totalAmount &gt;= 100.01 and totalAmount &lt;= 150 twoHundred = totalAmount if Country == "USA": if lessFifty: print('Your shipping is: $6.00') print('Your grand total is: $',totalAmount + 6) elif fiftyHundred: print('Your shipping is: $8.00') print('Your grand total is: $',totalAmount + 8) elif hundredFifty: print('Your shipping is: $10.00') print('Your grand total is: $',totalAmount + 10) elif twoHundred: print('Your shipping is free!') print('Your grand total is: $',totalAmount) if Country == "Canada": if lessFifty: print('Your shipping is: $8.00') print('Your grand total is: $',totalAmount + 8) elif fiftyHundred: print('Your shipping is: $10.00') print('Your grand total is: $',totalAmount + 10) elif hundredFifty: print('Your shipping is: $12.00') print('Your grand total is: $',totalAmount + 12) elif twoHundred: print('Your shipping is free!') print('Your grand total is: $',totalAmount) endProgram = input ('Do you want to restart the program?') if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'): break </code></pre>
[]
[ { "body": "<p>Sure you can condense some things, and improve the input loop. But I find your original code easy to read, whereas this is probably harder to read : </p>\n\n<pre><code>banner = 'Now we\\'ll calculate your total charge, including shipping.'\ncost_prompt = 'Enter your total purchase amount : '\ncountry_prompt = 'Where are you shipping to ?\\nEnter \"USA\" for the USA or \"Canada\" for Canada : '\nshippingis = 'Your shipping is '\ngrandtotalis = 'Your grand total is: '\nexit_prompt = 'Type q to quit, or enter to continue: '\nshiplaw = {\n 'USA' : {\n 0 : 6, 1 : 8, 2 : 10, 3 : 0\n },\n 'CANADA' : {\n 0 : 8, 1 : 10, 2 : 12, 3 : 0\n }\n }\n\ndef get_int(prompt):\n try: return int(float(raw_input(prompt).replace(',','').replace('$','')))\n except: return None\n\ndef dollars_n_cents(*vals):\n return '$' + str(int(sum(vals))) + '.00'\n\ndef response(total,shipping):\n shippingstr = 'free!' if shipping == 0 else dollars_n_cents(shipping)\n return (shippingis + shippingstr, grandtotalis + dollars_n_cents(total,shipping))\n\n\ndef run():\n while True:\n print banner\n total_amount = get_int(cost_prompt)\n while total_amount is None: total_amount = get_int(cost_prompt)\n country_str = raw_input(country_prompt)\n while country_str.upper() not in shiplaw: country_str = raw_input(country_prompt)\n result = response(total_amount,shiplaw[country_str.upper()][min(3,total_amount/50)])\n print '\\n'.join(result)\n try : \n if raw_input(exit_prompt)[0] == 'q': break\n except : pass\n\nimport sys\nif __file__ == sys.argv[0]:\n run()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T06:31:57.707", "Id": "21097", "ParentId": "21113", "Score": "0" } }, { "body": "<ul>\n<li><p>First thing is you don't perform much test on the user input. That's fine if that's just a little tool for yourself but I you plan to make it available for other users, it might be a good idea to have a few more checks.</p></li>\n<li><p>You are storing \"USA\" and \"Canada\" in variables which looks like a good idea. However, you don't use it later on. You could do something like : <code>Country = str(input('Type \"', canada, '\" for Canada and \"', usa, '\" for USA: '))</code> and then <code>if Country == canada:</code> and <code>if Country == usa:</code></p></li>\n<li><p>A string can't be both \"Canada\" and \"Usa\". Thus, <code>if Country == canada:</code> could become <code>elif Country == canada:</code></p></li>\n<li><p>As this \"print('Your shipping is: $X.00') print('Your grand total is: $',totalAmount + X)\" is repeted many times. It would probably be a could thing to make it a function taking a shippingFee and totalAmount as arguments and doing all the printing for you. Otherwise, instead of having the printing everywhere, you could just update a shippingFee variable and make the printing at the end.</p></li>\n<li><p>I'm not sure that storing the result of the comparison in variables is a really good idea, especially if you give them names containing written numbers : if you want to change one thing, you'll end up changing everything. On top of that, your conditions are dependant on each other : if you've already checked that <code>totalAmount &lt;= 50</code>, if your elif condition, you already know that <code>totalAmount &gt; 50</code>. Thus, your logic could be : <code>if totalAmount &lt;= 50: foo elif totalAmount &lt;=100: bar elif totalAmount &lt;= 150: foobar else: barfoo</code></p></li>\n<li><p>Other variables have non conventional names. For instance, <code>country</code> would be better than <code>Country</code></p></li>\n<li><p>It might be interesting to check the amount before considering the country.</p></li>\n</ul>\n\n<p>In conclusion, the code could be like (it doesn't behave exactly like your and I haven't tested it):</p>\n\n<pre><code>usa = \"USA\"\ncanada = \"Canada\"\n\ninput ('Please press \"Enter\" to begin')\nwhile True:\n print('This will calculate shipping cost and your grand total.')\n\n totalAmount = int(float(input('Enter your total amount: ').replace(',', '').replace('$', '')))\n country = str(input('Type \"', canada, '\" for Canada and \"', usa, '\" for USA: '))\n if country not in (canada, usa):\n print \"Invalid country\"\n continue\n\n shippingFee = 0\n if totalAmount&lt;50:\n shippingFee = 6\n elif totalAmount &lt; 100:\n shippingFee = 8\n elif totalAmount &lt; 150:\n shippingFee = 10\n\n if shippingFee != 0 and country == canada:\n shippingFee = shippingFee+2\n\n if shippingFee: # this could be using a ternary operator but that's a detail\n print('Your shipping is: Free')\n else:\n print('Your shipping is: $',shippingFee)\n print('Your grand total is: $',totalAmount + shippingFee)\n\n endProgram = input ('Do you want to restart the program?')\n if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'):\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T08:57:26.383", "Id": "33886", "Score": "0", "body": "`if shippingFee` should probably be `if not shippingFee`. For consistency, `if shippingFee != 0` can also be written as just `if shippingFee`. Rather than listing all case variations of 'no' and 'false', just use call `lower()` on `input`. On a final note, in Python generally underscore_style is preferred over camelCase." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T09:58:57.210", "Id": "33889", "Score": "0", "body": "line 9, in <module>\n country = str(input('Type \"', canada, '\" for Canada and \"', usa, '\" for USA: '))\nTypeError: input expected at most 1 arguments, got 5" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T06:45:55.010", "Id": "21098", "ParentId": "21113", "Score": "2" } }, { "body": "<p>I would not hard-code the fee logic, but instead store it as pure data. It's easier to maintain, even allowing to load it from a file.\nThen, it boils down to a range-based lookup, which is quite classical (cf <code>HLOOKUP</code> in spreadsheet software, with so called \"approximate search\").</p>\n\n<p>In Python, we can perform such a search via <code>bisect</code>, relying on lexicographic order (and infinity as an unreachable upper bound).</p>\n\n<p>Separated core logic would look like :</p>\n\n<pre><code>from bisect import bisect\n\n#For each country, list of (x,y) = (cost_threshold, fee)\n#For first x such cost &lt;= x, pick y for fee.\ninf = float(\"inf\")\nshippingFees = { 'USA' : [ (50, 6), (100, 8), (150, 10), (inf, 0) ],\n 'CANADA' : [ (50, 8), (100, 10), (150, 12), (inf, 0) ]\n }\n#Make sure it is sorted (required for lookup via bisect)\n#FIXME : Actually it would be better to assert it is already sorted,\n# since an unsorted input might reveal a typo.\nfor fee in shippingFees.values() : fee.sort()\n\ndef getShippingFee(amount, country):\n fees = shippingFees[country.upper()] #raise KeyError if not found.\n idx = bisect(fees, (amount,) )\n return fees[idx][1]\n</code></pre>\n\n<hr>\n\n<h2>Update</h2>\n\n<p>Here is a sample of \"working application\" using the helper function, assuming you have saved the code snippet above as <code>prices.py</code> (which should be stored in a module, but that's another story).</p>\n\n<p>NB : I have dropped the exit part, since I don't like to type <code>no</code> when I can hit CTRL+C.</p>\n\n<pre><code>#!/usr/bin/python2\n\"\"\" Your description here \"\"\"\n\nfrom prices import getShippingFee\n\nprint('This will calculate shipping cost and your grand total.')\n\nwhile True:\n\n #TODO : proper input processing, python3 compatible.\n totalAmount = float(raw_input('Enter your total amount: ').replace(',', '').replace('$', ''))\n country = raw_input('Type \"Canada\" for Canada and \"USA\" for USA: ').strip().upper()\n\n try : #TODO : proper country check.\n shippingFee = getShippingFee(totalAmount, country)\n grandTotal = totalAmount + shippingFee\n if shippingFee :\n print('Your shipping cost is: %.2f' % shippingFee)\n else :\n print('Your shipping is free!')\n print('Your grand total is: %.2f' % grandTotal)\n\n except KeyError :\n print (\"Sorry, we don't ship to this hostile country : %s\" % country)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:36:20.053", "Id": "33895", "Score": "0", "body": "Could you explain more into your script? I don't understand how to make it work into a working application." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T10:42:31.687", "Id": "33974", "Score": "0", "body": "This is a great answer especially in a production environment where the code is liable to be changed by someone other than the original author. Someone could easily guess how to add another country or modify the fees structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T19:04:48.813", "Id": "34015", "Score": "1", "body": "@sotapme Thank you ! The main benefit is that the very same data structure can be reused, to generate shipping cost table in web page for instance. This follows [DRY](http://c2.com/cgi/wiki?DontRepeatYourself) principle : _Every piece of knowledge must have a single, unambiguous, authoritative representation within a system._" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:17:57.743", "Id": "21108", "ParentId": "21113", "Score": "10" } }, { "body": "<p>One thing you could do is to calculate the shippingCost first, and then print with this logic</p>\n\n<pre><code>if shippingCost = 0\n print: free shipping\nelse \n print: your shipping is shippingCost\nend\nprint: grandtotal = totalAmount+shippingCost\n</code></pre>\n\n<p>It should not be too hard to translate this into proper python.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T13:40:17.327", "Id": "21114", "ParentId": "21113", "Score": "0" } }, { "body": "<ul>\n<li>Your example is broken. I don't think <code>while True: print(...)</code> is what you are looking for.</li>\n<li>I cannot see why you are eliminating all the commas from the input <code>totalAmount</code> and use <code>int(float(...))</code> anyway.</li>\n<li>Your <code>elif twoHundred:</code> will fail for <code>0</code>.</li>\n</ul>\n\n<p>I suggest to put input validation into a for loop with some error handling. Just as a recommendation.</p>\n\n<pre><code># Get total amount and country\nwhile True:\n try:\n total_amount = input('Enter your total amount: ')\n total_amount = total_amount.replace('$', '').replace(',', '.')\n total_amount = float(total_amount)\n break\n except ValueError:\n print('Invalid floating point value')\n</code></pre>\n\n<p>More importantly, it's considered best practice to compare lowercase strings to allow the user to not care about case sensitivity. You are currently not using the <code>usa</code> and <code>canada</code> variables.</p>\n\n<pre><code>usa = \"usa\"\ncanada = \"canada\"\n\nif Country.lower() == usa:\n ...\nif Country.lower() == canada:\n ...\n\nif endProgram.lower() in ('no', 'false'):\n break\n</code></pre>\n\n<p>And Dennis' answer helps as well.</p>\n\n<pre><code>#!/usr/bin/env python3\n\nprint('This will calculate shipping cost and your grand total.')\ninput('Please press \"Enter\" to begin ')\n\n# Get total amount and country\nwhile True:\n try:\n total_amount = input('Enter your total amount: ')\n total_amount = total_amount.replace('$', '').replace(',', '.')\n total_amount = float(total_amount)\n break\n except ValueError:\n print('Invalid floating point value')\n\ncountry = input('Type \"Canada\" for Canada and \"USA\" for USA: ')\n\n# evaluation of user data\nusa = \"usa\"\ncanada = \"canada\"\nless_fifty = total_amount &lt;= 50\nfifty_hundred = total_amount &gt; 50.0 and total_amount &lt;= 100\nhundred_fifty = total_amount &gt; 100.0 and total_amount &lt;= 150\n\nif country == usa:\n if less_fifty:\n shipping = 6\n elif fifty_hundred:\n shipping = 8\n elif hundred_fifty:\n shipping = 10\n else:\n shipping = None\n\nelif country == canada:\n if less_fifty:\n shipping = 8\n elif fifty_hundred:\n shipping = 10\n elif hundred_fifty:\n shipping = 12\n elif twoHundred:\n shipping = None\n\n# print output\nif shipping is None:\n print('Your shipping is free!')\n shipping = 0\nelse:\n print('Your shipping is: $', shipping)\nprint('Your grand total is: $', total_amount + shipping)\n\nendProgram = input ('Do you want to restart the program? ')\nif endProgram.lower() in ('no', 'false'):\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T14:20:09.517", "Id": "33903", "Score": "0", "body": "Damn, a duplicate. I don't think it's on purpose, he was told to go here, and his previous question has been automatically migrated too. Voting to close this one, please answer to the other question which has been around for a longer time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T14:10:34.510", "Id": "21117", "ParentId": "21113", "Score": "5" } }, { "body": "<p>First make sure the script work: proper indenting, shebang, correct logic. When the user enters 170$, you give him free shipping only because <code>twoHundred</code> evaluates to <code>totalAmount</code> which evaluates to true, so it seems simple to just say \"otherwise, it's free\". You also don't handle errors. I decided to handle the \"wrong country\" error, but many things could go wrong when inputing the total amount. As other said, first separate printing from application logic:</p>\n\n<pre><code>#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\ninput ('Please press \"Enter\" to begin')\n\nwhile True:\n print('This will calculate shipping cost and your grand total.')\n totalAmount = int(float(input('Enter your total amount: ') \\\n .replace(',', '').replace('$', '')))\n Country = str(input('Type \"Canada\" for Canada and \"USA\" for USA: '))\n\n lessFifty = totalAmount &lt;= 50\n fiftyHundred = totalAmount &gt;= 50.01 and totalAmount &lt;= 100\n hundredFifty = totalAmount &gt;= 100.01 and totalAmount &lt;= 150\n\n if Country == \"USA\":\n if lessFifty: shippingCost = 6\n elif fiftyHundred: shippingCost = 8\n elif hundredFifty: shippingCost = 10\n else: shippingCost = 0\n elif Country == \"Canada\":\n if lessFifty: shippingCost = 8\n elif fiftyHundred: shippingCost = 10\n elif hundredFifty: shippingCost = 12\n else: shippingCost = 0\n else:\n print(\"Unknown country.\")\n break\n\n print('Your shipping cost is: ${:.2f}'.format(shippingCost))\n print('Your grand total is: ${:.2f}'.format(totalAmount + shippingCost))\n\n endProgram = input ('Do you want to restart the program?')\n if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'):\n break\n</code></pre>\n\n<p>You can notice that the if blocks are still repetitive. You can use a dictionary to store the shipping costs.</p>\n\n<pre><code>#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\ninput ('Please press \"Enter\" to begin')\n\nwhile True:\n print('This will calculate shipping cost and your grand total.')\n totalAmount = int(float(input('Enter your total amount: ') \\\n .replace(',', '').replace('$', '')))\n country = str(input('Type \"Canada\" for Canada and \"USA\" for USA: '))\n\n if country not in ['Canada', 'USA']:\n print(\"Unknown country.\")\n break\n\n if totalAmount &lt;= 50: amountCategory = 'lessFifty'\n elif totalAmount &gt;= 50.01 and totalAmount &lt;= 100: amountCategory = 'fiftyHundred'\n elif totalAmount &gt;= 100.01 and totalAmount &lt;= 150: amountCategory ='hundredFifty'\n else: amountCategory = 'free'\n\n shippingCosts = {\n 'USA': {'lessFifty': 6, 'fiftyHundred': 8, 'hundredFifty': 10, 'free': 0},\n 'Canada': {'lessFifty': 8, 'fiftyHundred': 10, 'hundredFifty': 12, 'free': 0}\n }\n\n shippingCost = shippingCosts[country][amountCategory]\n\n print('Your shipping cost is: ${:.2f}'.format(shippingCost))\n print('Your grand total is: ${:.2f}'.format(totalAmount + shippingCost))\n\n endProgram = input ('Do you want to restart the program?')\n if endProgram in ['no', 'No', 'NO', 'false', 'False', 'FALSE']:\n break\n</code></pre>\n\n<p>I also used a list instead of a tuple to check for endProgram since it's more idiomatic. I don't think there's much more to do at this point to reduce size. You could find a smarter way to compute the shipping cost (see <a href=\"http://en.wikipedia.org/wiki/Kolmogorov_complexity\" rel=\"nofollow\">Kolmogorov complexity</a>) but that would make it harder to change the rules for no good reason. The block which compute amountCategory isn't too nice but since <code>if</code>s are not expressions in Python you can't write <code>amountCategory = if ...: 'lessFifty' else: 'free'</code>. You could use a function if you wanted.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T14:20:28.940", "Id": "21119", "ParentId": "21113", "Score": "2" } }, { "body": "<p>Just to add that you can do <code>a &lt;= x &lt; y</code> in Python, which to me is a lot easier to write and read than setting up three variables just to say what range the total amount is within:</p>\n\n<pre><code>shipping = None\nif total_amount &lt;= 50:\n shipping = 6\nelif 50 &lt; total_amount &lt;= 100:\n shipping = 8\nelif 100 &lt; total_amount &lt;= 150:\n shipping = 10\nif country == 'canada' and shipping:\n shipping += 2\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T21:25:28.367", "Id": "21138", "ParentId": "21113", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T12:48:53.977", "Id": "21113", "Score": "5", "Tags": [ "python" ], "Title": "Calculate shipping cost" }
21113
<p>I am new to Python and I want to see how can I improve my code to make it faster and cleaner. Below you can see the code of Margrabe's Formula for pricing Exchange Options. </p> <p>I think the part where I check if the argument is None and if not take predetermined values, can be improved but i don't know how to do it. Is using scipy.stats.norm for calculating the pdf and cdf of the normal distribution faster than manually coding it myself?</p> <pre><code> from __future__ import division from math import log, sqrt, pi from scipy.stats import norm s1 = 10 s2 = 20 sigma1 = 1.25 sigma2 = 1.45 t = 0.5 rho = 0.85 def sigma(sigma1, sigma2, rho): return sqrt(sigma1**2 + sigma2**2 - 2*rho*sigma1*sigma2) def d1(s1, s2, t, sigma1, sigma2, rho): return (log(s1/s2)+ 1/2 * sigma(sigma1, sigma2, rho)**2 * t)/(sigma(sigma1, sigma2, rho) * sqrt(t)) def d2(s1, s2, t, sigma1, sigma2, rho): return d1(s1,s2,t, sigma1, sigma2, rho) - sigma(sigma1, sigma2, rho) * sqrt(t) def Margrabe(stock1=None, stock2=None, sig1=None, sig2=None, time=None, corr=None): if stock1 == None: stock1 = s1 if stock2 == None: stock2 = s2 if time == None: time = t if sig1 == None: sig1 = sigma1 if sig2 == None: sig2 = sigma2 if corr==None: corr = rho dd1 = d1(stock1, stock2, time, sig1, sig2, corr) dd2 = d2(stock1, stock2, time, sig1, sig2, corr) return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2) print "Margrabe = " + str(Margrabe()) </code></pre>
[]
[ { "body": "<p>First of all, when you compare to <code>None</code>, you are better off using <code>if stock1 is None:</code> - an object can define equality, so potentially using <code>==</code> could return <code>True</code> even when <code>stock1</code> is not <code>None</code>. Using <code>is</code> checks <em>identity</em>, so it will only return <code>True</code> in the case it really is <code>None</code>.</p>\n\n<p>As to simplifying your code, you can simply place the default values directly into the function definition:</p>\n\n<pre><code>def margrabe(stock1=s1, stock2=s2, sig1=t, sig2=sigma1, time=sigma2, corr=rho):\n dd1 = d1(stock1, stock2, time, sig1, sig2, corr)\n dd2 = d2(stock1, stock2, time, sig1, sig2, corr)\n return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2)\n</code></pre>\n\n<p>This makes your code significantly more readable, and much shorter.</p>\n\n<p>It is also worth a note that <code>CapWords</code> is reserved for classes in Python - for functions, use <code>lowercase_with_underscores</code> - this is defined in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP-8</a> (which is a great read for making your Python more readable), and helps code highlighters work better, and your code more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T22:06:25.540", "Id": "21140", "ParentId": "21139", "Score": "1" } } ]
{ "AcceptedAnswerId": "21140", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T22:01:59.283", "Id": "21139", "Score": "2", "Tags": [ "python" ], "Title": "Improving my code of Margrabe Formula in Python" }
21139
<p>The problem with computing a radix using a non-imperative style of programming is you need to calculate a list of successive quotients, each new entry being the quotient of the last entry divided by the radix. The problem with this is (short of using despicable hacks like log) there is no way to know how many divisions an integer will take to reduce to 0. </p> <p>I'm fine with doing this with a generator :</p> <pre><code>def rep_div(n,r): while n != 0: yield n n /= r </code></pre> <p>But I don't like this for some reason. I feel there must be a clever way of using a lambda, or some functional construction, without building a list like is done here :</p> <pre><code>def rep_div2(n,r): return reduce(lambda v,i: v+[v[-1]/r],question_mark,[n]) </code></pre> <p>Once the repeated divisions can be generated radix is easy :</p> <pre><code>def radix2(n,r): return map(lambda ni: ni % r,(x for x in rep_div(n,r))) </code></pre> <p>So my question is : is it possible to rewrite <code>rep_div</code> as a more concise functional construction, on one line?</p>
[]
[ { "body": "<p>From my perspective, I'd say use the generator. It's concise and easily readable to most people familiar with Python. I'm not sure if you can do this in a functional sense easily without recreating some of the toolkit of functional programming languages. For example, if I wanted to do this in Haskell (which I am by no means an expert in, so this may be a horrible way for all I know), I'd do something like:</p>\n\n<pre><code>radix :: Int -&gt; Int -&gt; [Int]\nradix x n = takeWhile (&gt; 0) $ iterate (\\z -&gt; z `div` n) x\n</code></pre>\n\n<p>You can certainly recreate <code>takeWhile</code> and <code>iterate</code>, however, this only works due to lazy evaluation. The other option is, as you've said, using <code>log</code> and basically recreating <code>scanl</code>:</p>\n\n<pre><code>def scanl(f, base, l):\n yield base\n for x in l:\n base = f(base, x)\n yield base\n\ndef radix(n, r):\n return scanl(operator.__floordiv__, n, (r for x in range((int)(log(n, r)))))\n</code></pre>\n\n<p>So my answer is going to be \"No\" (predicated on the fact that someone smarter than me will probably find a way). However, unless you are playing Code Golf, I'd again suggest sticking with the generator version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T04:04:00.543", "Id": "21155", "ParentId": "21151", "Score": "1" } } ]
{ "AcceptedAnswerId": "21155", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T03:18:20.403", "Id": "21151", "Score": "2", "Tags": [ "python", "functional-programming" ], "Title": "Most concise Python radix function using functional constructions?" }
21151
<p>I have a list of strings of variable lengths, and I want to pretty-print them so they are lining up in columns. I have the following code, which works as I want it to currently, but I feel it is a bit ugly. How can I simplify it/make it more pythonic (without changing the output behaviour)?</p> <p>For starters I think I could probably use the alignment <code>'&lt;'</code> option of the <a href="http://docs.python.org/2/library/string.html#formatstrings"><code>str.format</code></a> stuff if I could just figure out the syntax properly...</p> <pre><code>def tabulate(words, termwidth=79, pad=3): width = len(max(words, key=len)) ncols = max(1, termwidth // (width + pad)) nrows = len(words) // ncols + (1 if len(words) % ncols else 0) #import itertools #table = list(itertools.izip_longest(*[iter(words)]*ncols, fillvalue='')) # row-major table = [words[i::nrows] for i in xrange(nrows)] # column-major return '\n'.join(''.join((' '*pad + x.ljust(width) for x in r)) for r in table) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:20:20.877", "Id": "33959", "Score": "1", "body": "Not worth an answer, but you can get your rounded-up-not-down integer division to compute `nrows` in a much more compact form as `nrows = (len(words) - 1) // ncols + 1`. Seee e.g. http://en.wikipedia.org/wiki/Floor_and_ceiling_functions#Quotients" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T12:26:36.657", "Id": "33980", "Score": "0", "body": "Thanks, I knew there was a better way when I was writing that... I'd just forgotten the usual trick (which, actually, I usually used adding the denominator - 1 to the numerator, i.e. `(len(words) + ncols - 1) // ncols` ... it seems to be equivalent to your trick" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T02:26:45.017", "Id": "35302", "Score": "0", "body": "I found a nice alternative, after `pip install prettytable`. No need to reinvent the wheel I guess .." } ]
[ { "body": "<p>A slightly more readable version:</p>\n\n<pre><code>def tabulate(words, termwidth=79, pad=3):\n width = len(max(words, key=len)) + pad\n ncols = max(1, termwidth // width)\n nrows = (len(words) - 1) // ncols + 1\n table = []\n for i in xrange(nrows):\n row = words[i::nrows]\n format_str = ('%%-%ds' % width) * len(row)\n table.append(format_str % tuple(row))\n return '\\n'.join(table)\n</code></pre>\n\n<p>Most notably, I've defined <code>width</code> to include padding and using string formatting to generate a format string to format each row ;).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T22:42:59.757", "Id": "22941", "ParentId": "21159", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T06:34:47.553", "Id": "21159", "Score": "5", "Tags": [ "python", "strings" ], "Title": "Nicely tabulate a list of strings for printing" }
21159
<p>The following functional program factors an integer by trial division. I am not interested in improving the efficiency (but not in decreasing it either), I am interested how it can be made better or neater using functional constructions. I just seem to think there are a few tweaks to make this pattern more consistent and tight (this is hard to describe), without turning it into boilerplate. </p> <pre><code>def primes(limit): return (x for x in xrange(2,limit+1) if len(factorization(x)) == 1) def factor(factors,p): n = factors.pop() while n % p == 0: n /= p factors += [p] return factors+[n] if n &gt; 1 else factors def factorization(n): from math import sqrt return reduce(factor,primes(int(sqrt(n))),[n]) </code></pre> <p>For example, <code>factorization(1100)</code> yields:</p> <pre><code>[2,2,5,5,11] </code></pre> <p>It would be great if it could all fit on one line or into two functions that looked a lot tighter -- I'm sure there must be some way, but I can not see it yet. What can be done?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:44:41.827", "Id": "33965", "Score": "0", "body": "so `factorization` is the function you want out of this? because you don't need `primes` to get it (note also that factorization calls primes and primes calls factorization, that does not look good)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:54:08.487", "Id": "33966", "Score": "0", "body": "Why would that not be good? I thought it looked cool. Please explain." } ]
[ { "body": "<p>A functional recursive implementation:</p>\n\n<pre><code>def factorization(num, start=2):\n candidates = xrange(start, int(sqrt(num)) + 1)\n factor = next((x for x in candidates if num % x == 0), None)\n return ([factor] + factorization(num / factor, factor) if factor else [num]) \n\nprint factorization(1100)\n#=&gt; [2, 2, 5, 5, 11]\n</code></pre>\n\n<p>Check <a href=\"https://github.com/tokland/pyeuler/blob/master/pyeuler/toolset.py\" rel=\"nofollow\">this</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:54:26.567", "Id": "33967", "Score": "0", "body": "Cool thanks. But I dislike recursion because of stack overflows or max recursion depth. I will try to understand your code though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:55:33.400", "Id": "33968", "Score": "0", "body": "I like get_cardinal_name !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:09:27.743", "Id": "33969", "Score": "0", "body": "Note that the function only calls itself for factors of a number, not for every n being tested, so you'll need a number with thousands of factor to reach the limit. Anyway, since you are learning on Python and functional programming, a hint: 1) lists (arrays) don't play nice with functional programming. 2) not having tail-recursion hinders functional approaches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:23:18.430", "Id": "33970", "Score": "0", "body": "Okay, cool tips about those things. Thanks. I will try to understand this better!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T08:43:23.810", "Id": "21168", "ParentId": "21165", "Score": "2" } } ]
{ "AcceptedAnswerId": "21168", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T07:58:40.743", "Id": "21165", "Score": "1", "Tags": [ "python", "functional-programming", "integer" ], "Title": "How to improve this functional python trial division routine?" }
21165
<p>I have the following python functions for <a href="http://en.wikipedia.org/wiki/Exponentiation_by_squaring" rel="nofollow noreferrer">exponentiation by squaring</a> :</p> <pre><code>def rep_square(b,exp): return reduce(lambda sq,i: sq + [sq[-1]*sq[-1]],xrange(len(radix(exp,2))),[b]) def exponentiate(b,exp): return reduce(lambda res,(sq,p): res*sq if p == 1 else res,zip(rep_square(b,exp),radix(exp,2)),1) </code></pre> <p>They work. Calling <code>print exponentiate(2,10), exponentiate(3,37)</code> yields :</p> <pre><code>1024 450283905890997363 </code></pre> <p>as is proper. But I am not happy with them because they need to calculate a <strong>list</strong> of squares. This seems to be a problem that could be resolved by functional programming because : </p> <ol> <li>Each item in the list only depends on the previous one</li> <li>Repeated squaring is recursive</li> </ol> <p>Despite <a href="https://codereview.stackexchange.com/questions/21165/how-to-improve-this-functional-python-trial-division-routine#comment33965_21165">people mentioning that recursion is a good thing to employ in functional programming, and that lists are not good friends</a> -- I am not sure how to turn this recursive list of squares into a recursive generator of the values that would avoid a list. I know I could use a <em>stateful</em> generator with <code>yield</code> but I like something that can be written in one line. </p> <p>Is there a way to do this with tail recursion? Is there a way to make this into a generator expression? </p> <p>The only thing I have thought of is this <em>particularly ugly</em> and also broken recursive generator : </p> <pre><code>def rep_square(n,times): if times &lt;= 0: yield n,n*n yield n*n,list(rep_square(n*n,times-1)) </code></pre> <p>It never returns. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T10:16:07.310", "Id": "33973", "Score": "0", "body": "A bit of a naive question but why don't you just rewrite the definition of Function exp-by-squaring(x,n) from Wikipedia in proper python ? It seems fine as far as I can tell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:48:38.967", "Id": "35759", "Score": "0", "body": "@Josay because I want to make one myself." } ]
[ { "body": "<p>You haven't said anything against <a href=\"http://docs.python.org/2/library/itertools.html\" rel=\"nofollow\"><code>itertools</code></a>, so here's how I'd do it with generators:</p>\n\n<pre><code>from itertools import compress\nfrom operator import mul\n\ndef radix(b) :\n while b :\n yield b &amp; 1\n b &gt;&gt;= 1\n\ndef squares(b) :\n while True :\n yield b\n b *= b\n\ndef fast_exp(b, exp) :\n return reduce(mul, compress(squares(b), radix(exp)), 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:17:53.700", "Id": "34011", "Score": "0", "body": "I like that. Both these answers are awesome. Showing the beautiful ways of looking at it from two different and complimentary perspectives. Coolness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:49:58.310", "Id": "35760", "Score": "0", "body": "I chose this as the answer because although we have a *tail recursion* version, as asked, and this *generator expression* as asked, I really liked the use of `compress` and the idea of selectors -- which was new for me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T16:35:54.627", "Id": "21183", "ParentId": "21169", "Score": "1" } }, { "body": "<p>A tail recursive version could look something like this:</p>\n\n<pre><code>def rep_square_helper(x, times, res):\n if times == 1:\n return res * x\n if times % 2:\n return rep_square_helper(x * x, times // 2, res * x)\n else:\n return rep_square_helper(x * x, times // 2, res)\n\ndef rep_square(n, times):\n return rep_square_helper(n, times, 1)\n</code></pre>\n\n<p>Note that in python there is no real advantage to using tail recursion (as opposed to, say, ML where the compiler can <a href=\"http://c2.com/cgi/wiki?TailCallOptimization\" rel=\"nofollow\">reuse stack frames</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:16:28.820", "Id": "34010", "Score": "0", "body": "Oh I like that, that's *really* neat and clean. Exposes the algorithm logic perfectly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T10:15:58.700", "Id": "34101", "Score": "0", "body": "Why do we consider times=1 as the default case instead of times=0 ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T17:01:37.547", "Id": "34105", "Score": "0", "body": "Because using this logic `times=0` is an edge case (but you're right, it should be dealt with)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:52:12.083", "Id": "35761", "Score": "0", "body": "@cmh What does ML stand for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T20:57:44.537", "Id": "35766", "Score": "1", "body": "@CrisStringfellow http://fr.wikipedia.org/wiki/ML_(langage)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:14:45.457", "Id": "21186", "ParentId": "21169", "Score": "1" } }, { "body": "<p>One of the things I do not like that much about python is the possibility and trend to crunch everything in one line for whatever reasons (no, do not compare with perl).</p>\n\n<p>For me, a more readable version:</p>\n\n<pre><code>def binary_exponent(base, exponent):\n \"\"\"\\\n Binary Exponentiation\n\n Instead of computing the exponentiation in the traditional way,\n convert the exponent to its reverse binary representation.\n\n Each time a 1-bit is encountered, we multiply the running total by\n the base, then square the base.\n \"\"\"\n # Convert n to base 2, then reverse it. bin(6)=0b110, from second index, reverse\n exponent = bin(exponent)[2:][::-1]\n\n result = 1\n for i in xrange(len(exponent)):\n if exponent[i] is '1':\n result *= base\n base *= base\n return result\n</code></pre>\n\n<p>source (slightly modified): <a href=\"http://blog.madpython.com/2010/08/07/algorithms-in-python-binary-exponentiation/\" rel=\"nofollow\">http://blog.madpython.com/2010/08/07/algorithms-in-python-binary-exponentiation/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T18:03:39.223", "Id": "21194", "ParentId": "21169", "Score": "1" } } ]
{ "AcceptedAnswerId": "21183", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T09:36:59.913", "Id": "21169", "Score": "1", "Tags": [ "python", "functional-programming", "recursion" ], "Title": "How to improve this functional python fast exponentiation routine?" }
21169
<p>I have two classes with similar first checking codes, but different behaviors. I suppose there is a way to refactor the code, so I don't need to retype it every time. Is it possible to refactor this, or I must retype this code every time?</p> <pre><code># Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: </code></pre> <p>The code is simple. Forget about my way to render the page, is a method over my own <code>PageHandler</code> class that works.</p> <pre><code># Check for actual logged user def checkLoggedUser(): # Get actual logged user user = users.get_current_user() # Don't allow to register for a logged user if user: return True, "You are already logged in." else: return False, None # Get and post for the login page class Login(custom.PageHandler): def get(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: self.renderPage('login.htm') def post(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: # Make the login # bla, bla bla... code for login the user. # Get and post for the register page class Register(custom.PageHandler): def get(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: self.renderPage("registerUser.htm") def post(self): # Get actual logged user user, msg = checkLoggedUser() if user: self.renderPage("customMessage.htm", custom_msg=msg) else: # Store in vars the form values # bla, bla bla... code for register the user. </code></pre>
[]
[ { "body": "<p>Create a class</p>\n\n<pre><code>class MyPageHandler(custom.PageHandler):\n def veryUserNotLoggedIn(self):\n if users.getCurrentUser():\n self.renderPage(\"customMessage.htm\", custom_msg=msg)\n return False\n else:\n return True\n</code></pre>\n\n<p>Then you can write you class like</p>\n\n<pre><code>class Login(MyPageHandler):\n def get(self):\n if self.verifyUserNotLoggedIn():\n self.renderPage('login.htm')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T21:35:17.533", "Id": "34031", "Score": "0", "body": "you are a number one! :) 2 refactors, 2 new knowledges for me. Thank you a lot (I'm a little rusty, I come from VB6... but learning a lot now)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T17:00:58.667", "Id": "21184", "ParentId": "21178", "Score": "1" } } ]
{ "AcceptedAnswerId": "21184", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-01T15:20:37.023", "Id": "21178", "Score": "1", "Tags": [ "python", "logging" ], "Title": "Checking for a logged user" }
21178
<p>I've a web form that allows users to create clusters of three sizes: small, medium and large. The form is sending a string of small, medium or large to a message queue, were job dispatcher determines how many jobs (cluster elements) it should build for a given cluster, like that:</p> <pre><code># determine required cluster size if cluster['size'] == 'small': jobs = 3 elif cluster['size'] == 'medium': jobs = 5 elif cluster['size'] == 'large': jobs = 8 else: raise ConfigError() </code></pre> <p>While it works, its very ugly and non flexible way of doing it - in case I'd want to have more gradual sizes, I'd increase number of <code>elif</code>'s. I could send a number instead of string straight from the form, but I dont want to place the application logic in the web app. Is there a nicer and more flexible way of doing something like that? </p>
[]
[ { "body": "<p>I'd write:</p>\n\n<pre><code>jobs_by_cluster_size = {\"small\": 3, \"medium\": 5, \"large\": 8}\njobs = jobs_by_cluster_size.get(cluster[\"size\"]) or raise_exception(ConfigError())\n</code></pre>\n\n<p><code>raise_exception</code> is just a wrapper over <code>raise</code> (statement) so it can be used in expressions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:16:30.080", "Id": "34058", "Score": "1", "body": "I'm afraid that's not valid python" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:25:39.763", "Id": "34059", "Score": "0", "body": "@WinstonEwert: Oops, I had completely forgotten `raise` is an statement in Python and not a function/expression (too much Ruby lately, I am afraid). Fixed (kind of)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T12:49:52.837", "Id": "21227", "ParentId": "21219", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T09:15:49.903", "Id": "21219", "Score": "2", "Tags": [ "python", "strings", "form" ], "Title": "Flexible multiple string comparision to determine variable value" }
21219
<p>Below is the code for knowing all the prime factors of a number. I think there must be some better way of doing the same thing. Also, please tell me if there are some flaws in my code.</p> <pre><code>def factorize(num): res2 = "%s: "%num res = [] while num != 1: for each in range(2, num + 1): quo, rem = divmod(num, each) if not rem: res.append(each) break num = quo pfs = set(res) for each in pfs: power = res.count(each) if power == 1: res2 += str(each) + " " else: res2 += str(each) + '^' + str(power) + " " return res2 </code></pre>
[]
[ { "body": "<pre><code>def factorize(num):\n res2 = \"%s: \"%num\n</code></pre>\n\n<p>You'd be much better off to put the string stuff in a seperate function. Just have this function return the list of factors, i.e. <code>res</code> and have a second function take <code>res</code> as a parameter and return the string. That'd make your logic simpler for each function.</p>\n\n<pre><code> res = []\n</code></pre>\n\n<p>Don't needlessly abbreviate. It doesn't save you any serious amount of typing time and makes it harder to follow your code.</p>\n\n<pre><code> while num != 1:\n for each in range(2, num + 1):\n</code></pre>\n\n<p>To be faster here, you'll want recompute the prime factors of the numbers. You can use the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a>. Just keep track of the prime factors found, and you'll just be able to look them up.</p>\n\n<pre><code> quo, rem = divmod(num, each)\n if not rem:\n res.append(each)\n break\n num = quo\n</code></pre>\n\n<p>Your function dies here if you pass it a zero.</p>\n\n<pre><code> pfs = set(res)\n</code></pre>\n\n<p>Rather than a set, use <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a>, it'll let you get the counts at the same time rather then recounting res.</p>\n\n<pre><code> for each in pfs:\n power = res.count(each)\n if power == 1:\n res2 += str(each) + \" \"\n else:\n res2 += str(each) + '^' + str(power) + \" \"\n</code></pre>\n\n<p>String addition is inefficient. I'd suggest using <code>\"{}^{}\".format(each, power)</code>. Also, store each piece in a list and then use <code>\" \".join</code> to make them into a big string at the end.</p>\n\n<pre><code> return res2\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T14:15:06.070", "Id": "21231", "ParentId": "21229", "Score": "6" } } ]
{ "AcceptedAnswerId": "21231", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-02T13:15:50.493", "Id": "21229", "Score": "2", "Tags": [ "python", "primes" ], "Title": "Code review needed for my Prime factorization code" }
21229
<p>I am in two minds about function calls as parameters for other functions. The doctrine that readability is king makes me want to write like this:</p> <pre><code>br = mechanize.Browser() raw_html = br.open(__URL) soup = BeautifulSoup(raw_html) </code></pre> <p>But in the back of my mind I feel childish doing so, which makes me want to write this:</p> <pre><code>br = mechanize.Browser() soup = BeautifulSoup(br.open(__URL)) </code></pre> <p>Would it actually look unprofessional to do it the first way? Is there any serious reason to choose one method over the other?</p>
[]
[ { "body": "<p>\"readable\" is a relational predicate. It does not depend on the text alone, but also on the person looking at it. So learning a language means to get familiar with statements like</p>\n\n<pre><code>soup = BeautifulSoup(mechanize.Browser().open(__URL))\n</code></pre>\n\n<p>that only use standard names to refer to often used components. The more you use this style, the more 'natural' it gets.</p>\n\n<p>Using unnecessary variables</p>\n\n<pre><code>brow = mechanize.Browser()\n...\nbr = \"&lt;br /\"\n...\nraw_html = br.open(__URL)\nsoup = BeautifulSoup(rwa_html)\n</code></pre>\n\n<p>forces you to invent non-standard (good for the specific context) names and increases the risk of typos or confusion - mistakes that happen randomly even to a pro.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T07:58:49.653", "Id": "21281", "ParentId": "21278", "Score": "3" } }, { "body": "<p>I'm typically an advocate of liberal use of space, but in this situation, I'd go with the third option:</p>\n\n<pre><code>soup = BeautifulSoup(mechanize.Browser().open(__URL))\n</code></pre>\n\n<p>(I'm not actually sure if that's valid syntax or not. I'm not very familiar with Python [I think it's Python?].)</p>\n\n<p>I find that just as readable. There are of course situations where you must separate it though. The first thing that comes to mind is error handling. I suspect that <code>open</code> throws exceptions, but if it were to return boolean <code>false</code> on failure rather than a string, then I would be a fan of option two. Option two would still be brief, but would allow for properly checking for the <code>false</code> return.</p>\n\n<hr>\n\n<p>I think this really comes down to personal taste. There's no magical rule book for this type of thing (though I'm sure there are convoluted, borderline-dogmatic metrics somewhere that support one way or the other).</p>\n\n<p>I tend to just eyeball things like this and see if they make me visually uncomfortable or not.</p>\n\n<p>For example:</p>\n\n<pre><code>superLongVariableNameHere(someParamWithLongName, someFunctionLong(param1, param2), someFunc3(param, func4(param1, param2, func5(param)))\n</code></pre>\n\n<p>Makes me cry a little whereas:</p>\n\n<pre><code>func(g(x), y(z))\n</code></pre>\n\n<p>Seems perfectly fine. I just have some weird mental barrier of what length/nesting level becomes excessive.</p>\n\n<hr>\n\n<p>While I'm at it, I'd also disagree with Juann Strauss' dislike of JavaScript's practically idiomatic use of anonymous and inline-defined functions. Yes, people go overboard sometimes with a 30 line callback, but for the most part, there's nothing wrong with a 1-10 line anonymous function as long as it's used in one and only one place and it doesn't overly clutter its context.</p>\n\n<p>In fact, to have a closure, you often have to define functions in the middle of scopes (well, by definition you do). Often in that situation you might as well inline it within another function call rather than defining it separately (once again, provided the body is brief).</p>\n\n<p>If he means this though, then yeah, I'd agree 95% of the time:</p>\n\n<pre><code>f((function(x) { return x * x; }(5))\n</code></pre>\n\n<p>That gets ugly fast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T08:11:07.963", "Id": "34147", "Score": "1", "body": "+0.5 for pointing out that sometimes variables are necessary for error checking; +0.5 for disagreement with Juann's personal feelings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-02T00:03:56.510", "Id": "98050", "Score": "0", "body": "+1 This is the reverse of Introduce Explaining Variable and IMHO a good example of when the refactoring isn't needed. The raw HTML is used just once right away, and it's pretty clear that opening a URL would produce HTML. The one-line statement is clear and concise. Introducing temporary variables in this case could mislead the reader to think there's more going on here than there is." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T07:59:01.227", "Id": "21282", "ParentId": "21278", "Score": "5" } } ]
{ "AcceptedAnswerId": "21282", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T06:37:42.507", "Id": "21278", "Score": "3", "Tags": [ "python" ], "Title": "Function calls as parameters for other functions" }
21278
<p>I wanted to implemented an algorithm in Python 2.4 (so the odd construction for the conditional assignment) where given a list of ranges, the function returns another list with all ranges that overlap in the same entry.</p> <p>I would appreciate other options (more elegant or efficient) than the one I took. </p> <pre><code>ranges = [(1,4),(1,9),(3,7),(10,15),(1,2),(8,17),(16,20),(100,200)] def remove_overlap(rs): rs.sort() def process (rs,deviation): start = len(rs) - deviation - 1 if start &lt; 1: return rs if rs[start][0] &gt; rs[start-1][1]: return process(rs,deviation+1) else: rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] &lt; rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] &gt; rs[start][1]]) del rs[start] return process(rs,0) return process(rs,0) print remove_overlap(ranges) </code></pre>
[]
[ { "body": "<p>Firstly, modify or return, don't do both. </p>\n\n<p>Your <code>process</code> method returns lists as well as modify them. Either you should construct a new list and return that, or modify the existing list and return nothing.</p>\n\n<p>Your <code>remove_overlap</code> function does the same thing. It should either modify the incoming list, or return a new list not both. </p>\n\n<p>You index <code>[0]</code> and <code>[1]</code> on the tuples a lot to fetch the start and end. That's best avoided because its not easy to tell whats going on. </p>\n\n<p><code>rs[start-1] = ((rs[start][0],rs[start-1][0])[rs[start-1][0] &lt; rs[start][0]],(rs[start][1],rs[start-1][1])[rs[start-1][1] &gt; rs[start][1]])</code></p>\n\n<p>Ouch! That'd be much better off broken into several lines. You shouldn't need to check which of the starts is lower because sorting the array should mean that the earlier one is always lower. I'd also use the <code>max</code> function to select the larger item, (if you don't have it in your version of python, I'd just define it)</p>\n\n<p>Your loop is backwards, working from the end. That complicates the code and makes it harder to follow. I'd suggest reworking it work from the front. </p>\n\n<pre><code>return process(rs,0)\n</code></pre>\n\n<p>You start the checking process over again whenever you merge two ranges. But that's not so great because you'll end up rechecking all the segments over and over again. Since you've already verified them you shouldn't check them again. </p>\n\n<p>Your recursion process can be easily rewritten as a while loop. All you're doing is moving an index forward, and you don't really need recursion.</p>\n\n<p>This is my implementation:</p>\n\n<pre><code>def remove_overlap(ranges):\n result = []\n current_start = -1\n current_stop = -1 \n\n for start, stop in sorted(ranges):\n if start &gt; current_stop:\n # this segment starts after the last segment stops\n # just add a new segment\n result.append( (start, stop) )\n current_start, current_stop = start, stop\n else:\n # segments overlap, replace\n result[-1] = (current_start, stop)\n # current_start already guaranteed to be lower\n current_stop = max(current_stop, stop)\n\n return result\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T11:18:12.577", "Id": "34223", "Score": "0", "body": "`remove_overlap([(-1,1)])` → `IndexError: list assignment index out of range`. Maybe start with `float('-inf')` instead of `-1`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T13:53:40.937", "Id": "34227", "Score": "0", "body": "@GarethRees, that'll work if you need negative ranges. I assumed the ranges were positive as typically negatives ranges are non-sensical (not always)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T18:09:21.930", "Id": "21309", "ParentId": "21307", "Score": "8" } }, { "body": "<p>In addition to Winston Ewert's comments, I'd add:</p>\n\n<ol>\n<li><p>There's no docstring. How are users to know how what this function does and how to call it?</p></li>\n<li><p>This is an ideal function to give a couple of <a href=\"http://docs.python.org/2/library/doctest.html\" rel=\"noreferrer\">doctests</a> to show how to use it and to test that it works.</p></li>\n<li><p>The name <code>remove_overlap</code> could be improved. Remove overlap from what? And remove it how? And anyway, you don't just want to merge <em>overlapping</em> ranges (like 1–3 and 2–4), you want to merge <em>adjacent</em> ranges too (like 1–2 and 2–3). So I'd use <code>merge_ranges</code>.</p></li>\n<li><p>It's simpler and more flexible to implement the function as a generator, rather than repeatedly appending to a list. </p></li>\n<li><p>Winston's implementation doesn't work if any of the ranges are negative.</p></li>\n</ol>\n\n<p>So I would write:</p>\n\n<pre><code>def merge_ranges(ranges):\n \"\"\"\n Merge overlapping and adjacent ranges and yield the merged ranges\n in order. The argument must be an iterable of pairs (start, stop).\n\n &gt;&gt;&gt; list(merge_ranges([(5,7), (3,5), (-1,3)]))\n [(-1, 7)]\n &gt;&gt;&gt; list(merge_ranges([(5,6), (3,4), (1,2)]))\n [(1, 2), (3, 4), (5, 6)]\n &gt;&gt;&gt; list(merge_ranges([]))\n []\n \"\"\"\n ranges = iter(sorted(ranges))\n current_start, current_stop = next(ranges)\n for start, stop in ranges:\n if start &gt; current_stop:\n # Gap between segments: output current segment and start a new one.\n yield current_start, current_stop\n current_start, current_stop = start, stop\n else:\n # Segments adjacent or overlapping: merge.\n current_stop = max(current_stop, stop)\n yield current_start, current_stop\n</code></pre>\n\n<h3>Update</h3>\n\n<p>Winston Ewert notes in comments that it's not exactly obvious how this works in the case when <code>ranges</code> is the empty list: in particular, the call <code>next(ranges)</code> looks suspicious.</p>\n\n<p>The explanation is that when <code>ranges</code> is empty, <code>next(ranges)</code> raises the exception <code>StopIteration</code>. And that's exactly what we want, because we are writing a generator function and raising <code>StopIteration</code> is one of the ways that a generator can signal that it is finished.</p>\n\n<p>This is a common pattern when building one iterator from another: the outer iterator keeps reading elements from the inner iterator, relying on the inner iterator to raise <code>StopIteration</code> when it is empty. Several of the recipes in the <a href=\"http://docs.python.org/2/library/itertools.html\" rel=\"noreferrer\"><code>itertools</code> documentation</a> use this pattern, for example <a href=\"http://docs.python.org/2/library/itertools.html#itertools.imap\" rel=\"noreferrer\"><code>imap</code></a> and <a href=\"http://docs.python.org/2/library/itertools.html#itertools.islice\" rel=\"noreferrer\"><code>islice</code></a>.</p>\n\n<p>Supposing that you think this is a bit ugly, and you wanted to make the behaviour explicit, what would you write? Well, you'd end up writing something like this:</p>\n\n<pre><code>try:\n current_start, current_stop = next(ranges)\nexcept StopIteration: # ranges is empty\n raise StopIteration # and so are we\n</code></pre>\n\n<p>I hope you can see now why I didn't write it like that! I prefer to follow the maxim, \"<a href=\"http://drj11.wordpress.com/2008/10/02/c-return-and-parentheses/\" rel=\"noreferrer\">program as if you know the language</a>.\"</p>\n\n<h3>Update 2</h3>\n\n<p>The idiom of deferring from one generator to another via <code>next</code> will no longer work in Python 3.6 (see <a href=\"http://legacy.python.org/dev/peps/pep-0479/\" rel=\"noreferrer\">PEP 479</a>), so for future compatibility the code needs to read:</p>\n\n<pre><code>try:\n current_start, current_stop = next(ranges)\nexcept StopIteration:\n return\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T13:56:09.720", "Id": "34228", "Score": "0", "body": "I'm pretty sure it'll fail on `ranges = []` due to trying to fetch the next item from an empty list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:29:09.573", "Id": "34241", "Score": "0", "body": "There's already a doctest for that case. (And it passes.) When `ranges` is empty, the call to `next` raises the exception `StopIteration`, which is exactly what we need." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:50:57.900", "Id": "34244", "Score": "0", "body": "Oh, subtle. I didn't think of the fact that `StopIteration` would trigger the end of the generator. Honestly, that feels ugly to me, but that may just be taste." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T16:58:57.690", "Id": "34245", "Score": "0", "body": "It's a natural pattern for building one iterator out of another: the outer iterator reads items from the inner iterator, relying on the inner one to raise `StopIteration` when it's empty. Many of the recipes in the [`itertools` module](http://docs.python.org/2/library/itertools.html) use this pattern. See for example `imap` and `islice`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T17:39:02.400", "Id": "34248", "Score": "0", "body": "I reserve my right to still find it ugly. :) Maybe its just a matter of not being used to it, but I don't like the implicit way it handles the case." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-05T11:11:55.133", "Id": "21333", "ParentId": "21307", "Score": "8" } }, { "body": "<p>I think there is an error in the algorithm. Example:</p>\n\n<ul>\n<li>ranges = [(1,5), (2,4), (8,9)]</li>\n</ul>\n\n<p>Expected response:</p>\n\n<ul>\n<li>ranges2 = [(1,5), (8,9)]</li>\n</ul>\n\n<p>Response obtained:</p>\n\n<ul>\n<li>ranges2 = [(1,4), (8,9)]</li>\n</ul>\n\n<p>A small change and the error is fixed.</p>\n\n<pre><code>def remove_overlap(ranges):\n result = []\n current_start = -1\n current_stop = -1 \n\n for start, stop in sorted(ranges):\n if start &gt; current_stop:\n # this segment starts after the last segment stops\n # just add a new segment\n current_start, current_stop = start, stop\n result.append( (start, stop) )\n else:\n # segments overlap, replace\n # current_start already guaranteed to be lower\n current_stop = max(current_stop, stop)\n result[-1] = (current_start, current_stop)\n\n return result\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:24:47.243", "Id": "237636", "ParentId": "21307", "Score": "-1" } } ]
{ "AcceptedAnswerId": "21309", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T17:04:46.913", "Id": "21307", "Score": "9", "Tags": [ "python", "performance", "algorithm", "python-2.x", "interval" ], "Title": "Consolidate list of ranges that overlap" }
21307
<p>I am looking for a memory efficient python script for the following script. The following script works well for smaller dimension but the dimension of the matrix is 5000X5000 in my actual calculation. Therefore, it takes very long time to finish it. Can anyone help me how can I do that?</p> <pre><code>def check(v1,v2): if len(v1)!=len(v2): raise ValueError,"the lenght of both arrays must be the same" pass def d0(v1, v2): check(v1, v2) return dot(v1, v2) import numpy as np from pylab import * vector=[[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]] rav= np.mean(vector,axis=0) #print rav #print vector m= vector-rav corr_matrix=[] for i in range(0,len(vector)): tmp=[] x=sqrt(d0(m[i],m[i])) for j in range(0,len(vector)): y=sqrt(d0(m[j],m[j])) z=d0(m[i],m[j]) w=z/(x*y) tmp.append(w) corr_matrix.append(tmp) print corr_matrix </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:27:08.100", "Id": "34309", "Score": "0", "body": "\"... memory efficient ... very long time ...\" Do you want to optimize memory usage or runtime?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T18:24:46.373", "Id": "34329", "Score": "0", "body": "I am looking for both." } ]
[ { "body": "<p>I noticed one of your issues is that you are calculating the same thing over and over again when it is possible to pre-calculate the values before looping. First of all:</p>\n<pre><code>x = sqrt(d0(m[i], m[i]))\n</code></pre>\n<p>and:</p>\n<pre><code>y = sqrt(d0(m[j], m[j]))\n</code></pre>\n<p>are doing the exact same thing. You are calculating the sqrt() of dot product of the entire length of the vector length^2 times! For your 5000 element vector list, that's 25,000,000 times.</p>\n<p>When it comes to iterating over giant mounds of data, try to pre-calculate as much as possible. Try this:</p>\n<pre><code>pre_sqrt = [sqrt(d0(elem, elem)) for elem in m]\npre_d0 = [d0(i, j) for i in m for j in m]\n</code></pre>\n<p>Then, to reduce the amount of repetitive calls to <code>len()</code> and <code>range()</code>:</p>\n<pre><code>vectorLength = len(vector)\niterRange = range(vectorLength)\n</code></pre>\n<p>Finally, this is how your for loops should look:</p>\n<pre><code>for i in iterRange:\n\n tmp = [] \n x = pre_sqrt[i]\n \n for j in iterRange:\n\n y = pre_sqrt[j]\n z = pre_d0[i*vectorLength + j]\n \n w = z / (x * y)\n\n tmp.append(w)\n\n corr_matrix.append(tmp)\n</code></pre>\n<p>When I timed your implementation vs mine these were the average speeds over 10000 repetitions:</p>\n<blockquote>\n<p><strong>Old:</strong> .150 ms</p>\n<p><strong>Mine:</strong> .021 ms</p>\n</blockquote>\n<p>That's about a 7 fold increase over your small sample vector. I imagine the speed increase will be even better when you enter the 5000 element vector.</p>\n<p>You should also be aware that there could be some Python specific improvements to be made. For example, using lists vs numpy arrays to store large amounts of data. Perhaps someone else can elaborate further on those types of speed increases.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T05:01:49.013", "Id": "21364", "ParentId": "21362", "Score": "4" } }, { "body": "<p>Use a profiler to know your hot spots: <a href=\"http://docs.python.org/2/library/profile.html\" rel=\"nofollow\">http://docs.python.org/2/library/profile.html</a></p>\n\n<hr>\n\n<p>Follow the advices from TerryTate.</p>\n\n<hr>\n\n<p>Describe your algorithm. It is not directly clear what should happen in this loop. If you abstract the algorithm inside a specification, you can perhaps simplify the abstract specification to get a better algorithm.</p>\n\n<hr>\n\n<p>Correlates to the previous one: Use meaningful names.<br>\nFor example:</p>\n\n<pre><code>vector=[[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]]\n</code></pre>\n\n<p>Sure, this is a vector for a vector space over a R^5 field, but you could call it a matrix and everyone can follow it.</p>\n\n<pre><code>def check(v1,v2):\n if len(v1)!=len(v2):\n raise ValueError,\"the lenght of both arrays must be the same\"\n</code></pre>\n\n<p>What does it check? (And i think, you do not need it. Because dot from numpy will already raise an error for illegal arguments)</p>\n\n<pre><code>def d0(v1, v2):\n check(v1, v2)\n return dot(v1, v2)\n</code></pre>\n\n<p>What is d0? Call it get_inner_product or something like this (I even do not like the numpy name, but well)</p>\n\n<p>and some more</p>\n\n<hr>\n\n<p>from pylab import *</p>\n\n<p>Try to avoid import everything. This will lead to problems, sometimes hard to read code and namespace problems.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:41:55.697", "Id": "21377", "ParentId": "21362", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T02:19:53.197", "Id": "21362", "Score": "1", "Tags": [ "python" ], "Title": "Looking for efficient python program for this following python script" }
21362
<p>Here's my attempt at Project Euler Problem #5, which is looking quite clumsy when seen the first time. Is there any better way to solve this? Or any built-in library that already does some part of the problem?</p> <pre><code>''' Problem 5: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 What is the smallest number, that is evenly divisible by each of the numbers from 1 to 20? ''' from collections import defaultdict def smallest_number_divisible(start, end): ''' Function that calculates LCM of all the numbers from start to end It breaks each number into it's prime factorization, simultaneously keeping track of highest power of each prime number ''' # Dictionary to store highest power of each prime number. prime_power = defaultdict(int) for num in xrange(start, end + 1): # Prime number generator to generate all primes till num prime_gen = (each_num for each_num in range(2, num + 1) if is_prime(each_num)) # Iterate over all the prime numbers for prime in prime_gen: # initially quotient should be 0 for this prime numbers # Will be increased, if the num is divisible by the current prime quotient = 0 # Iterate until num is still divisible by current prime while num % prime == 0: num = num / prime quotient += 1 # If quotient of this priime in dictionary is less than new quotient, # update dictionary with new quotient if prime_power[prime] &lt; quotient: prime_power[prime] = quotient # Time to get product of each prime raised to corresponding power product = 1 # Get each prime number with power for prime, power in prime_power.iteritems(): product *= prime ** power return product def is_prime(num): ''' Function that takes a `number` and checks whether it's prime or not Returns False if not prime Returns True if prime ''' for i in xrange(2, int(num ** 0.5) + 1): if num % i == 0: return False return True if __name__ == '__main__': print smallest_number_divisible(1, 20) import timeit t = timeit.timeit print t('smallest_number_divisible(1, 20)', setup = 'from __main__ import smallest_number_divisible', number = 100) </code></pre> <p>While I timed the code, and it came out with a somewhat ok result. The output came out to be:</p> <pre><code>0.0295362259729 # average 0.03 </code></pre> <p>Any inputs?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T12:07:04.760", "Id": "34279", "Score": "0", "body": "I think you can adapt [Erathosthenes' prime sieve](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to compute is_prime plus the amount of factors in one go." } ]
[ { "body": "<p>You are recomputing the list of prime numbers for each iteration. Do it just once and reuse it. There are also better ways of computing them other than trial division, the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a> is very simple yet effective, and will get you a long way in Project Euler. Also, the factors of <code>n</code> are all smaller than <code>n**0.5</code>, so you can break out earlier from your checks.</p>\n\n<p>So add this before the <code>num</code> for loop:</p>\n\n<pre><code>prime_numbers = list_of_primes(int(end**0.5))\n</code></pre>\n\n<p>And replace <code>prime_gen</code> with :</p>\n\n<pre><code>prime_gen =(each_prime for each_prime in prime_numbers if each_prime &lt;= int(num**0.5))\n</code></pre>\n\n<p>The <code>list_of_primes</code> function could be like this using trial division :</p>\n\n<pre><code>def list_of_primes(n)\n \"\"\"Returns a list of all the primes below n\"\"\"\n ret = []\n for j in xrange(2, n + 1) :\n for k in xrange(2, int(j**0.5) + 1) :\n if j % k == 0 :\n break\n else :\n ret.append(j)\n return ret\n</code></pre>\n\n<p>But you are better off with a very basic <a href=\"http://numericalrecipes.wordpress.com/2009/03/16/prime-numbers-2-the-sieve-of-erathostenes/\" rel=\"nofollow\">sieve of Erathostenes</a>:</p>\n\n<pre><code>def list_of_primes(n) :\n sieve = [True for j in xrange(2, n + 1)]\n for j in xrange(2, int(sqrt(n)) + 1) :\n i = j - 2\n if sieve[j - 2]:\n for k in range(j * j, n + 1, j) :\n sieve[k - 2] = False\n return [j for j in xrange(2, n + 1) if sieve[j - 2]]\n</code></pre>\n\n<hr>\n\n<p>There is an alternative, better for most cases, definitely for Project Euler #5, way of going about calculating the least common multiple, using the greatest common divisor and <a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"nofollow\">Euclid's algorithm</a>:</p>\n\n<pre><code>def gcd(a, b) :\n while b != 0 :\n a, b = b, a % b\n return a\n\ndef lcm(a, b) :\n return a // gcd(a, b) * b\n\nreduce(lcm, xrange(start, end + 1))\n</code></pre>\n\n<p>On my netbook this gets Project Euler's correct result lightning fast:</p>\n\n<pre><code>In [2]: %timeit reduce(lcm, xrange(1, 21))\n10000 loops, best of 3: 69.4 us per loop\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:46:49.650", "Id": "34318", "Score": "0", "body": "I agree, using gcd is the easiest way here. I am quite sure it had to be written before or anywhere else anyway. (For very large numbers, this approach has some problems, but well, 20 is not a very large number)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:27:25.840", "Id": "34344", "Score": "0", "body": "Hello @Jaime. Thanks for your response. I tried to use your `list_of_prime` method, but the problem is: - `end ** 0.5` range generates just `[2, 3]` as prime numbers below `20`. So, it's not considering `5`, which is a valid prime diviser. Same in the case of `10`. It's not considering `5`. And hence I'm loosing some factors. Also, for numbers like `5`, or `7`, again it is not considering `5` and `7` respectively, which we should consider right? So, does that mean that `range(2, int(end**0.5))` is not working well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T03:30:09.453", "Id": "34345", "Score": "0", "body": "However, if I replace the range with `range(2, end)`, and in list comprehension also: - `each_prime <= num`, it's giving me correct result." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:24:13.717", "Id": "21375", "ParentId": "21367", "Score": "7" } }, { "body": "<p>You can use the Sieve of Erathosthenes just once AND count the factors while you filter the primes:</p>\n\n<pre><code>def computeMultiplicity(currentPrime, n):\n result = 0\n while n % currentPrime == 0:\n n = n / currentPrime\n result = result + 1\n return result\n\ndef euler5(n):\n result = 1\n isPrime = [True for _ in range(n + 1)]\n\n for currentPrime in range(2, n + 1):\n if isPrime[currentPrime]:\n multiplicity = 1 \n for multiple in range(2 * currentPrime, n + 1, currentPrime):\n isPrime[multiple] = False\n multiplicity = max(multiplicity, computeMultiplicity(currentPrime, multiple))\n result *= currentPrime ** multiplicity\n\n return result\n\nif __name__ == '__main__':\n print(euler5(20))\n\n from timeit import timeit\n print(timeit('euler5(20)', setup='from __main__ import euler5', number=100))\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>0.00373393183391\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T15:12:53.207", "Id": "53972", "Score": "0", "body": "This code does not appear to be in Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T15:46:15.350", "Id": "53974", "Score": "0", "body": "@GarethRees You are most observant ;) It is a Java implementation of a (way) more efficient algorithm. Shouldn't be too hard to port to python since it's all simple arithmetic computations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T16:42:24.750", "Id": "53977", "Score": "0", "body": "@GarethRees Ported to Python. Better? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T18:10:39.683", "Id": "53981", "Score": "0", "body": "Yes, that's better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T20:07:07.307", "Id": "64367", "Score": "0", "body": "`isPrime = [True for _ in range(n + 1)]` can be written as `isPrime = [True] * (n + 1)`. I would also add a comment that `isPrime[0]` and `isPrime[1]` are erroneous but inconsequential." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T20:08:22.140", "Id": "64368", "Score": "0", "body": "Write `n = n / currentPrime` as `n = n // currentPrime` (explicit integer division) for compatibility with Python 3. Or, `n //= currentPrime`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T14:31:03.190", "Id": "21376", "ParentId": "21367", "Score": "3" } }, { "body": "<p>For a \"small\" problem like this, performance is a non-issue, and clarity should be the primary consideration. I would decompose the problem into well recognized and testable primitives.</p>\n\n<p>Furthermore, you can eliminate the <code>is_prime()</code> test, as it is just unnecessary extra work. (Why?)</p>\n\n<pre><code>def prime_factors(n):\n '''\n Returns the prime factorization of n as a dict-like object whose keys\n are prime factors and whose values are their powers.\n\n &gt;&gt;&gt; [(k, v) for k, v in prime_factors(360).iteritems()]\n [(2, 3), (3, 2), (5, 1)]\n '''\n # This is a simplistic, non-optimized implementation. For better\n # performance with larger inputs, you could terminate the loop earlier, use\n # memoization, or implement the Sieve of Eratosthenes.\n factors_and_powers = defaultdict(int)\n for i in range(2, n+1):\n while n % i == 0:\n factors_and_powers[i] += 1\n n //= i\n return factors_and_powers\n\ndef product(factors_and_powers):\n '''\n Given a dict-like object whose keys are factors and whose values\n are their powers, returns the product.\n\n &gt;&gt;&gt; product({})\n 1\n &gt;&gt;&gt; product({3: 1})\n 3\n &gt;&gt;&gt; product({2: 3, 3: 2, 5: 1})\n 360\n '''\n return reduce(lambda mult, (factor, power): mult * (factor ** power),\n factors_and_powers.iteritems(),\n 1)\n\ndef least_common_multiple(numbers):\n '''\n Returns the least common multiple of numbers, which is an iterable\n that yields integers.\n\n &gt;&gt;&gt; least_common_multiple([1])\n 1\n &gt;&gt;&gt; least_common_multiple([2])\n 2\n &gt;&gt;&gt; least_common_multiple([6])\n 6\n &gt;&gt;&gt; least_common_multiple([4, 6])\n 12\n '''\n lcm_factors = defaultdict(int)\n for n in numbers:\n for factor, power in prime_factors(n).iteritems():\n lcm_factors[factor] = max(lcm_factors[factor], power)\n return product(lcm_factors)\n\ndef smallest_number_divisible(start, end):\n '''\n Calculates the LCM of all the numbers from start to end, inclusive. It\n breaks each number into its prime factorization, keeping track of highest\n power of each prime factor.\n\n &gt;&gt;&gt; smallest_number_divisible(1, 10)\n 2520\n '''\n return least_common_multiple(xrange(start, end + 1))\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n print smallest_number_divisible(1, 20)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:04:21.950", "Id": "54040", "Score": "0", "body": "By the way, this version completes in about 1/3 of the time of the original code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T19:00:51.827", "Id": "33752", "ParentId": "21367", "Score": "0" } }, { "body": "<p>There is no least common multiple function in the built-in library. However, there is a greatest common divisor function. You can take advantage of the fact that LCM(<em>a</em>, <em>b</em>) × GCD(<em>a</em>, <em>b</em>) = <em>a b</em>.</p>\n\n<pre><code>from fractions import gcd\n\ndef lcm(a, b):\n return (a * b) // gcd(a, b)\n\nreduce(lcm, range(1, 20 + 1))\n</code></pre>\n\n<p><a href=\"http://docs.python.org/2/library/functions.html#reduce\" rel=\"nofollow\"><code>reduce()</code></a> calls <code>lcm()</code> repeatedly, as in <code>lcm(… lcm(lcm(lcm(1, 2), 3), 4), … 20)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T08:28:32.220", "Id": "38486", "ParentId": "21367", "Score": "0" } } ]
{ "AcceptedAnswerId": "21375", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-06T10:09:49.247", "Id": "21367", "Score": "5", "Tags": [ "python", "project-euler", "primes" ], "Title": "Any better way to solve Project Euler Problem #5?" }
21367
<p>I am writing a program which calculates the scores for participants of a small "Football Score Prediction" game.</p> <p>Rules are:</p> <ol> <li>if the match result(win/loss/draw) is predicted correctly: 1 point</li> <li>if the match score is predicted correctly(exact score): 3 points (and +1 point because 1st rule is automatically satisfied)</li> </ol> <p>Score is calculated after every round of matches (10 matches in a round).</p> <p>The program I've written is as follows:</p> <pre><code>import numpy as np import re players = {0:'Alex',1:'Charlton',2:'Vineet'} results = np.array(range(40),dtype='a20').reshape(4,10) eachPrediction = np.array(range(20),dtype='a2').reshape(2,10) score = np.zeros(3) correctScore=3 correctResult=1 allPredictions = [] done = False def takeFixtures(): filename='bplinput.txt' file = open(filename) text = file.readlines() fixtures = [line.strip() for line in text] file.close() i=0 for eachMatch in fixtures: x=re.match("(.*) ([0-9]+) ?- ?([0-9]+) (.*)", eachMatch) results[0,i]=x.group(1) results[1,i]=x.group(2) results[2,i]=x.group(3) results[3,i]=x.group(4) i+=1 def takePredictions(noOfParticipants): for i in range(0,noOfParticipants): print("Enter predictions by "+players[i]+" in x-y format") for i in range(0,10): eachFixturePrediction = raw_input("Enter prediction for "+results[0,i]+" vs "+results[3,i]+": ") x=eachFixturePrediction.split('-') eachPrediction[0,i]=str(x[0]) eachPrediction[1,i]=str(x[1]) allPredictions.append(eachPrediction) def scoreEngine(): for i in range(0,len(players)): for j in range(0,10): resultH=int(results[1,j]) resultA=int(results[2,j]) result=resultH-resultA predictionH=int(allPredictions[i][0][j]) predictionA=int(allPredictions[i][1][j]) pResult = predictionH-predictionA if result == pResult or (result&lt;0 and pResult&lt;0) or (result&gt;0 and pResult&gt;0): score[i]+=correctResult if resultH==predictionH and resultA==predictionA: score[i]+=correctScore noOfParticipants=len(players) takeFixtures() takePredictions(noOfParticipants) scoreEngine() print("Scores are:") print(score) for player in players: print(players[player]+" has scored "+ str(score[player])+" points" ) </code></pre> <p>The file used to take list of fixtures looks like this:</p> <pre><code>West Bromwich Albion 0-1 Tottenham Hotspur Manchester City 2-2 Liverpool Queens Park Rangers 0-0 Norwich City Arsenal 1-0 Stoke City Everton 3-3 Aston Villa Newcastle United 3-2 Chelsea Reading 2-1 Sunderland West Ham United 1-0 Swansea City Wigan Athletic 2-2 Southampton Fulham 0-1 Manchester United </code></pre> <p>I want advice on how this program can be improved in any way (decreasing the code/ making it efficient).</p>
[]
[ { "body": "<p>First thing, let's talk about the <code>players</code> array : </p>\n\n<ul>\n<li>you define it with <code>players = {0:'Alex',1:'Charlton',2:'Vineet'}</code>.</li>\n<li><p>you iterate on it using :</p>\n\n<pre><code>for i in range(0,noOfParticipants):\n # Something about : players[i]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for player in players:\n # Something about : players[player] and str(score[player])\n</code></pre></li>\n</ul>\n\n<p>First passing the length of an array without passing the array is a bit awkward (not to say useless). Then, the way you loop is not very pythonic. If what you want is a list of names, define it as a list of names: <code>players = ['Alex','Charlton','Vineet']</code> (if you define the index yourself and you iterate using only the size of the loop, you might get troubles). Then, if you want to iterate over the names, it's pretty straightforward: <code>for player in players:</code>. You want the index as well ? Enumerate is what you want: <code>for i,name in enumerate(players)</code>. How cool is this ?</p>\n\n<p>However, it might be a good idea to make this array a little bit more complicated and use it to store not only the players' names but also their prediction and their score. Then, a dictionary would be a good solution.</p>\n\n<p>Then, a few details :</p>\n\n<ul>\n<li><p>I think you should get rid of the magic numbers: I have no idea what the different numbers are for.</p></li>\n<li><p>I think <code>correctScore</code> and <code>correctResult</code> are not very good names to express number of points (<code>pointCorrectScore</code> and <code>pointCorrectResult</code> are my suggestions) but storing this in variable is a pretty good idea. Also, I would advise you to create a function returning the score from an estimation and an actual score. Your variables <code>correctScore</code> and <code>correctResult</code> could then be local to your function.</p></li>\n</ul>\n\n<p>I have no time to go further in the code I didn't quite understand at first glance but I'll try to do it eventually.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T09:29:36.267", "Id": "21412", "ParentId": "21408", "Score": "5" } }, { "body": "<h2>Style</h2>\n\n<p>The first thing to do is to follow PEP 8: it's a style guide that says how you should indent your code, name your variables, and so on. For example, prefer <code>results[0, i] = x.group(1)</code> to <code>results[0,i]=x.group(1)</code>.</p>\n\n<h2>Files</h2>\n\n<p>Opening files in Python should be done using the <a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow\"><code>with</code> idiom</a>: your file is then guaranteed to be close correctly. <code>takeFixtures</code> now becomes:</p>\n\n<pre><code>def takeFixtures():\n with open('bplinput.txt') as file:\n for eachMath in file:\n x=re.match(\"(.*) ([0-9]+) ?- ?([0-9]+) (.*)\", eachMatch.strip)\n results[0,i]=x.group(1)\n results[1,i]=x.group(2)\n results[2,i]=x.group(3)\n results[3,i]=x.group(4)\n i+=1\n</code></pre>\n\n<h2>Data structures</h2>\n\n<p>I you didn't use numpy, you could have written <code>results[i] = x.groups()</code>, and then used <code>zip(*results)</code> to transpose the resulting matrix. More generally, as pointed out by Josay, you should use Python data structures, and only switch to numpy if you find out that this is where the inefficiency lies.</p>\n\n<h2>Formatting</h2>\n\n<p>The last thing that the other reviewers didn't mention is that concatenating strings is poor style, and <code>format()</code> should be preferred since it's more readable and more efficient:</p>\n\n<pre><code>for player in players:\n print(\"{} has scored {} points\".format(players[player], score[player]))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T15:29:14.560", "Id": "34409", "Score": "0", "body": "thanks,Can you give me suggestion on a better way to take input from all the players? right now I have to manually input the score predictions by all players, and if there is some mistake i have to do it all over again. ie. one mistake and i have to input 30 predictions all over again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T16:14:28.623", "Id": "34413", "Score": "1", "body": "You need to catch the [exception](http://docs.python.org/2/tutorial/errors.html) that comes out and ask the input to be made again. You would need some kind of loop to make the input until it worked correctly. This would be a good question on StackOverflow unless it has alread been asked." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:11:11.890", "Id": "21416", "ParentId": "21408", "Score": "6" } } ]
{ "AcceptedAnswerId": "21416", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T05:51:57.967", "Id": "21408", "Score": "4", "Tags": [ "python", "optimization", "game" ], "Title": "Calculating scores for predictions of football scores" }
21408
<p>Is there a better way of creating this terminal animation without having a series of conditional statements (i.e. <code>if ... elif ... elif...)</code>?</p> <pre><code>import sys, time count = 100 i = 0 num = 0 def animation(): global num if num == 0: num += 1 return '[= ]' elif num == 1: num += 1 return '[ = ]' elif num == 2: num += 1 return '[ = ]' elif num == 3: num += 1 return '[ = ]' elif num == 4: num += 1 return '[ = ]' elif num == 5: num += 1 return '[ = ]' elif num == 6: num += 1 return '[ =]' elif num == 7: num += 1 return '[ =]' elif num == 8: num += 1 return '[ = ]' elif num == 9: num += 1 return '[ = ]' elif num == 10: num += 1 return '[ = ]' elif num == 11: num += 1 return '[ = ]' elif num == 12: num += 1 return '[ = ]' elif num == 13: num = 0 return '[= ]' while i &lt; count: sys.stdout.write('\b\b\b') sys.stdout.write(animation()) sys.stdout.flush() time.sleep(0.2) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:06:17.480", "Id": "34488", "Score": "0", "body": "I guess that a progress bar, shouldn't you write \\b 9 times?" } ]
[ { "body": "<p>You can build up the string like this:</p>\n\n<pre><code>def animation(counter, length):\n stage = counter % (length * 2 + 2)\n if stage &lt; length + 1:\n left_spaces = stage\n else:\n left_spaces = length * 2 - 1 - stage\n return '[' + ' ' * left_spaces + '=' + ' ' * (length - left_spaces) + ']'\n\nfor i in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation(i, 6))\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>Alternatively store the animation strings in a tuple or list:</p>\n\n<pre><code>animation_strings = ('[= ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[ = ]', '[ =]', '[ =]',\n '[ = ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[= ]')\nfor i in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation_strings[i % len(animation_strings)])\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>You can replace the animation function with <a href=\"http://docs.python.org/2/library/itertools.html#itertools.cycle\"><code>cycle</code> from <code>itertools</code></a>:</p>\n\n<pre><code>import sys, time\nfrom itertools import cycle\nanimation = cycle('[= ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[ = ]', '[ =]', '[ =]',\n '[ = ]', '[ = ]', '[ = ]', '[ = ]',\n '[ = ]', '[= ]')\n# alternatively:\n# animation = cycle('[' + ' ' * n + '=' + ' ' * (6 - n) + ']' \n# for n in range(7) + range(6, -1, -1))\n\nfor _ in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation.next())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>Finally, you could make your own generator function.</p>\n\n<pre><code>def animation_generator(length):\n while True:\n for n in range(length + 1):\n yield '[' + ' ' * n + '=' + ' ' * (length - n) + ']'\n for n in range(length + 1):\n yield '[' + ' ' * (length - n) + '=' + ' ' * n + ']'\n\nanimation = animation_generator(6)\nfor _ in range(100):\n sys.stdout.write('\\b\\b\\b')\n sys.stdout.write(animation.next())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n\n<p>EDIT: made the above suggestions less reliant on global variables</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T12:11:56.170", "Id": "34452", "Score": "3", "body": "+1 for `itertools.cycle`. (But I think you'd want to build up the animation programmatically so that it would be easy to change its length.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T00:42:39.453", "Id": "34531", "Score": "0", "body": "Alternatively, you could `sys.stdout.write('\\r')` instead of the `\\b\\b\\b`, since the animation steps have equal length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T11:12:38.307", "Id": "34551", "Score": "0", "body": "@AttilaO. thanks, I use IDLE and don't actually know how these terminal characters work but I'll take your word for it..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:41:43.353", "Id": "21464", "ParentId": "21462", "Score": "16" } }, { "body": "<p>Notes: </p>\n\n<ul>\n<li>Don't use global variables without a good (an extremely good) justification. A function is (should be) a black box that gets values and returns values (unless you have unavoidable side-effects to perform, for example reading a file or printing to the screen). </li>\n<li>It's very cumbersome and inflexible to write every possible string of the progressbar by hand, use code instead to build them.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>import sys\nimport time\n\ndef render(size, position):\n return \"[\" + (\" \" * position) + \"=\" + (\" \" * (size - position - 1)) + \"]\" \n\ndef draw(size, iterations, channel=sys.stdout, waittime=0.2): \n for index in range(iterations):\n n = index % (size*2)\n position = (n if n &lt; size else size*2 - n - 1)\n bar = render(size, position)\n channel.write(bar + '\\r')\n channel.flush()\n time.sleep(waittime) \n\nif __name__ == '__main__':\n draw(6, 100, channel=sys.stdout)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:53:26.030", "Id": "34462", "Score": "0", "body": "Does not replicate the original animation" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T14:03:44.280", "Id": "34465", "Score": "0", "body": "@Stuart. I know, I thought it looked more beautiful without stopping at the limits. I'll update it. But I guess `\\b` is expected to match the string length, otherwise it makes no sense." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T13:44:17.150", "Id": "21467", "ParentId": "21462", "Score": "4" } }, { "body": "<p>Try this:</p>\n\n<pre><code>import time\nj = 0\nwhile True:\n for j in range(6):\n print(\"[\",j*\" \",\"=\",(6-j)*\" \",\"]\",end=\"\\r\", sep=\"\")\n time.sleep(0.2)\n for j in range(6):\n print(\"[\",(6-j)*\" \", \"=\",(j)*\" \",\"]\",end=\"\\r\", sep=\"\")\n time.sleep(0.2)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-09T12:35:02.833", "Id": "351897", "Score": "1", "body": "[Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers](https://codereview.stackexchange.com/help/how-to-answer): argue *how* this is `better way`, why drop the `count`(100) limit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-09T16:39:45.527", "Id": "351941", "Score": "0", "body": "While the OP asked \"_Is there a better way of doing this terminal animation without having a load of `if ... elif ...`?_\", which does seem like it might be asking for just alternative code, \"_[Short answers are acceptable](http://meta.codereview.stackexchange.com/questions/1463/short-answers-and-code-only-answers), **as long as you explain your reasoning**._\" -see [How to answer](https://codereview.stackexchange.com/help/how-to-answer). That page also states: \"_Every answer must make at least one **insightful observation** about the code in the question._\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-09T11:29:24.100", "Id": "184649", "ParentId": "21462", "Score": "0" } }, { "body": "<p>A liitle modification:\n*Also reduce the size of python shell window</p>\n<pre><code>import sys, time\ncount = 100\ni = 0\nnum = 0\n\ndef animation():\n global num\n if num == 0:\n num += 1\n return '[= ]'\n elif num == 1:\n num += 1\n return '[ = ]'\n elif num == 2:\n num += 1\n return '[ = ]'\n elif num == 3:\n num += 1\n return '[ = ]'\n elif num == 4:\n num += 1\n return '[ = ]'\n elif num == 5:\n num += 1\n return '[ = ]'\n elif num == 6:\n num += 1\n return '[ =]'\n elif num == 7:\n num += 1\n return '[ =]'\n elif num == 8:\n num += 1\n return '[ = ]'\n elif num == 9:\n num += 1\n return '[ = ]'\n elif num == 10:\n num += 1\n return '[ = ]'\n elif num == 11:\n num += 1\n return '[ = ]'\n elif num == 12:\n num += 1\n return '[ = ]'\n elif num == 13:\n num = 0\n return '[= ]'\n\nwhile i &lt; count:\n sys.stdout.write('\\b\\b\\b\\n')\n sys.stdout.write(animation())\n sys.stdout.flush()\n time.sleep(0.2)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-16T12:03:22.263", "Id": "512132", "Score": "1", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-16T11:14:06.620", "Id": "259614", "ParentId": "21462", "Score": "-2" } } ]
{ "AcceptedAnswerId": "21464", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-08T11:13:04.773", "Id": "21462", "Score": "9", "Tags": [ "python" ], "Title": "Python terminal animation" }
21462
<p>I am trying to understand how genetic algorithms work. As with everything, I learn by attempting to write something on my own;however, my knowledge is very limited and I am not sure if I am doing this right.</p> <p>The purpose of this algorithm is to see how long it will take half of a herd to be infected by a disease if half of that population are already infected. It is just an example I came up with in my head so I am not sure if this would even be a viable example. </p> <p>Some feedback on how I can improve my knowledge would be nice.</p> <p>Here is the code:</p> <pre><code>import random def disease(): herd = [] generations = 0 pos = 0 for x in range(100): herd.append(random.choice('01')) print herd same = all(x == herd[0] for x in herd) while same == False: same = all(x == herd[0] for x in herd) for animal in herd: try: if pos != 0: after = herd[pos+1] before = herd[pos-1] if after == before and after == '1' and before == '1' and animal == '0': print "infection at", pos herd[pos] = '1' #print herd pos += 1 except IndexError: pass pos = 0 generations += 1 random.shuffle(herd) #print herd print "Took",generations,"generations to infect all members of herd." if __name__ == "__main__": disease() </code></pre> <p>I am looking for comments based on the logic of this algorithm. What can be improved, and what has to be improved to make this a true genetic algorithm if it isn't one already.</p>
[]
[ { "body": "<pre><code>import random\n\ndef disease():\n herd = []\n generations = 0\n pos = 0\n</code></pre>\n\n<p>Don't assign variables ahead of their use</p>\n\n<pre><code> for x in range(100):\n herd.append(random.choice('01'))\n print herd\n same = all(x == herd[0] for x in herd)\n while same == False:\n same = all(x == herd[0] for x in herd)\n</code></pre>\n\n<p>Firstly, don't check for <code>== False</code>, use <code>not</code>. Also, there isn't any point in storing it in same, just test it:</p>\n\n<pre><code> while not all(x == herd[0] for x in herd):\n</code></pre>\n\n<p>I'd suggest testing using:</p>\n\n<pre><code>while len(set(herd)) != 1:\n</code></pre>\n\n<p>Which will be more efficient.</p>\n\n<pre><code> for animal in herd:\n try:\n if pos != 0:\n after = herd[pos+1]\n before = herd[pos-1]\n if after == before and after == '1' and before == '1' and animal == '0':\n</code></pre>\n\n<p>There is no point in checking if <code>after == before</code> if you are already checking that after and before are both equal to '1'. I'd consider doing:</p>\n\n<pre><code>if (after, animal, before) == ('1','0','1'):\n</code></pre>\n\n<p>which in this case I think shows more clearly what's going on.</p>\n\n<pre><code> print \"infection at\", pos\n herd[pos] = '1'\n #print herd\n pos += 1\n except IndexError:\n pass\n</code></pre>\n\n<p>Its generally not a good idea to catch an IndexError. Its too easy to get an accidental IndexError and then have your code miss the real problem. It also doesn't communicate why you are getting an index error.</p>\n\n<p>Instead of updating pos, I suggest you use</p>\n\n<pre><code>for pos, animal in enumerate(herd):\n</code></pre>\n\n<p>However, since you don't want the first and last elements anyways, I'd suggest</p>\n\n<pre><code> for pos in xrange(1, len(herd) - 1):\n before, animal, after = herd[pos-1,pos+2]\n</code></pre>\n\n<p>Back to your code:</p>\n\n<pre><code> pos = 0\n</code></pre>\n\n<p>You should reset things just before a loop, not afterwards. That way its easier to follow. Although its even better if you can avoid the resting altogether</p>\n\n<pre><code> generations += 1\n random.shuffle(herd)\n #print herd\n print \"Took\",generations,\"generations to infect all members of herd.\"\nif __name__ == \"__main__\":\n disease()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T01:42:23.037", "Id": "34582", "Score": "0", "body": "This was an amazing response. Thank you for breaking down my code, it was really informative." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T15:53:47.347", "Id": "21515", "ParentId": "21495", "Score": "3" } } ]
{ "AcceptedAnswerId": "21511", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T05:14:55.343", "Id": "21495", "Score": "1", "Tags": [ "python", "algorithm", "random" ], "Title": "What is wrong with my Genetic Algorithm?" }
21495
<p>I'm trying to learn Python by working my way through problems on the Project Euler website. I managed to solve problem #3, which is </p> <blockquote> <p>What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <p>However, my code looks horrible. I'd really appreciate some advice from experienced Python programmers.</p> <pre><code>import math import unittest def largestPrime(n, factor): """ Find the largest prime factor of n """ def divide(m, factor): """ Divide an integer by a factor as many times as possible """ if m % factor is 0 : return divide(m / factor, factor) else : return m def isPrime(m): """ Determine whether an integer is prime """ if m is 2 : return True else : for i in range(2, int(math.floor(math.sqrt(m))) + 1): if m % i is 0 : return False return True # Because there is at most one prime factor greater than sqrt(n), # make this an upper limit for the search limit = math.floor(math.sqrt(n)) if factor &lt;= int(limit): if isPrime(factor) and n % factor is 0: n = divide(n, factor) if n is 1: return factor else: return largestPrime(n, factor + 2) else: return largestPrime(n, factor + 2) return n </code></pre>
[]
[ { "body": "<p>Some thoughts:</p>\n\n<p><code>Divide</code> function has been implemented recursively. In general, recursive implementations provide clarity of thought despite being inefficient. But in this case, it just makes the code cumbersome.</p>\n\n<pre><code>while m % factor == 0:\n m /= factor\nreturn m\n</code></pre>\n\n<p>should do the job.</p>\n\n<hr>\n\n<p>A lot of computational work is done by <code>isPrime</code> which is unnecessary. Eg: when <code>factor</code> 15 is being considered, the original n would've been already <code>Divide</code>d by 3 and 5. So, if <code>factor</code> is not a prime then n%factor will not be 0.</p>\n\n<hr>\n\n<p>So, the following should do:</p>\n\n<pre><code>import math\ndef largestPF(n):\n limit = int(math.sqrt(n)) + 1\n for factor in xrange(2, limit+1):\n while n % factor == 0:\n n /= factor\n if n == 1:\n return factor\n return n\n</code></pre>\n\n<p>You can of course, include the 'run through factors in steps of 2' heuristic if you want.</p>\n\n<hr>\n\n<p>PS: Be careful with the <code>is</code> statement for verifying equality. It might lead to unexpected behaviour. Check out <a href=\"https://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why\">https://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T10:04:35.397", "Id": "21507", "ParentId": "21497", "Score": "5" } } ]
{ "AcceptedAnswerId": "21507", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-09T06:35:13.020", "Id": "21497", "Score": "4", "Tags": [ "python", "project-euler", "primes" ], "Title": "Largest Prime Factor" }
21497
<p>My data is in this format:</p> <blockquote> <p>龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\n</p> </blockquote> <p>And I want to return:</p> <pre><code>('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/') </code></pre> <p>In C I could do this in one line with <code>sscanf</code>, but I seem to be f̶a̶i̶l̶i̶n̶g̶ writing code like a schoolkid with Python:</p> <pre><code> working = line.rstrip().split(" ") trad, simp = working[0], working[1] working = " ".join(working[2:]).split("]") pinyin = working[0][1:] english = working[1][1:] return trad, simp, pinyin, english </code></pre> <p>Can I improve?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:04:27.373", "Id": "34604", "Score": "0", "body": "This is a little hard to parse because the logical field separator, the space character, is also a valid character inside the last two fields. This is disambiguated with brackets and slashes, but that obviously make the parse harder and uglier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T16:08:16.803", "Id": "34615", "Score": "1", "body": "If your code doesn't work correctly, then this question is off topic here. See the [FAQ]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:07:16.690", "Id": "34616", "Score": "3", "body": "@svick it works perfectly - by \"failing\" I meant \"failing to write neat code\"" } ]
[ { "body": "<p>My goal here is clarity above all else. I think a first step is to use the <code>maxsplit</code> argument of <a href=\"http://docs.python.org/2/library/stdtypes.html#str.split\" rel=\"nofollow\"><code>split</code></a> to get the first two pieces and the remainder:</p>\n\n<pre><code>trad, simp, remainder = line.rstrip().split(' ', 2)\n</code></pre>\n\n<p>Now, to parse the leftovers I'm afraid I only see slightly ugly choices. Some people like regular expressions and others hate them. Without regular expressions, I think it's easiest to view the remainder as two field separated with <code>\"] \"</code></p>\n\n<pre><code>pinyin, english = remainder.split(\"] \")\npinyin = pinyin[1:] # get rid of leading '['\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:34:52.573", "Id": "21540", "ParentId": "21539", "Score": "2" } }, { "body": "<p>I would split around the square brackets first</p>\n\n<pre><code>def parse_string(s):\n a, b = s.rstrip().split(' [', 2)\n return a.split(' ') + b.split('] ', 2)\n</code></pre>\n\n<p>or more explicitly</p>\n\n<pre><code>def parse_string(s):\n first, rest = s.rstrip().split(' [', 2)\n trad, simp = first.split(' ', 2)\n pinyin, english = rest.split('] ', 2)\n return trad, simp, pinyin, english\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T13:51:37.160", "Id": "21541", "ParentId": "21539", "Score": "0" } }, { "body": "<p>You can use <a href=\"https://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow\">Regular Expressions</a> with <a href=\"http://docs.python.org/2.7/library/re.html\" rel=\"nofollow\">re</a> module. For example the following regular expression works with binary strings and Unicode string (I'm not sure which version of Python you use).</p>\n\n<p>For Python 2.7.3:</p>\n\n<pre><code>&gt;&gt;&gt; s = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; u = s.decode(\"utf-8\")\n&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", s).groups()\n('\\xe9\\xbe\\x8d\\xe8\\x88\\x9f', '\\xe9\\xbe\\x99\\xe8\\x88\\x9f', 'long2 zhou1', '/dragon boat/imperial boat/')\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", u).groups()\n(u'\\u9f8d\\u821f', u'\\u9f99\\u821f', u'long2 zhou1', u'/dragon boat/imperial boat/')\n</code></pre>\n\n<p>For Python 3.2.3:</p>\n\n<pre><code>&gt;&gt;&gt; s = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; b = s.encode(\"utf-8\")\n&gt;&gt;&gt; import re\n&gt;&gt;&gt; re.match(r\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", s).groups()\n('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/')\n&gt;&gt;&gt; re.match(br\"^([^ ]+) ([^ ]+) \\[([^]]+)\\] (.+)\", b).groups()\n(b'\\xe9\\xbe\\x8d\\xe8\\x88\\x9f', b'\\xe9\\xbe\\x99\\xe8\\x88\\x9f', b'long2 zhou1', b'/dragon boat/imperial boat/')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T18:21:43.390", "Id": "34619", "Score": "0", "body": "`groups()` and `groupdict()` are great!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T14:05:11.600", "Id": "21543", "ParentId": "21539", "Score": "5" } }, { "body": "<p>You could perhaps try using the <a href=\"http://pypi.python.org/pypi/parse\" rel=\"nofollow\">parse</a> module, which you need to download from <a href=\"http://pypi.python.org\" rel=\"nofollow\">pypi</a>. It's intended to function in the opposite manner from the <code>format</code> method.</p>\n\n<pre><code>&gt;&gt;&gt; import parse\n&gt;&gt;&gt; data = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; match = \"{} {} [{}] {}\\n\"\n&gt;&gt;&gt; result = parse.parse(match, data)\n&gt;&gt;&gt; print result\n&lt;Result ('龍舟', '龙舟', 'long2 zhou1', '/dragon boat/imperial boat/') {}&gt;\n&gt;&gt;&gt; print result[0] \n'龍舟'\n</code></pre>\n\n<p>If you want to be able to access the result as a dictionary, you could name each of the parameters inside the brackets:</p>\n\n<pre><code>&gt;&gt;&gt; import parse\n&gt;&gt;&gt; data = \"龍舟 龙舟 [long2 zhou1] /dragon boat/imperial boat/\\n\"\n&gt;&gt;&gt; match = \"{trad} {simp} [{pinyin}] {english}\\n\"\n&gt;&gt;&gt; result = parse.parse(match, data)\n&gt;&gt;&gt; print result\n&lt;Result () {'english': '/dragon boat/imperial boat/', 'trad': '龍舟', 'simp': '龙舟', 'pinyin': 'long2 zhou1'}&gt;\n&gt;&gt;&gt; print result['trad'] \n'龍舟'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:38:01.657", "Id": "34618", "Score": "0", "body": "Is there some way to specify that the first two groups shouldn't contain spaces? Because I think unexpected input should cause an error, not silently return unexpected results." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T17:20:32.417", "Id": "21547", "ParentId": "21539", "Score": "0" } } ]
{ "AcceptedAnswerId": "21543", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T12:37:25.733", "Id": "21539", "Score": "3", "Tags": [ "python", "strings", "parsing", "unicode" ], "Title": "String parsing with multiple delimeters" }
21539
<p>I'm trying to see if there is a better way to design this. I have a class Animal that is inherited by Male and Female classes (Female class has an additional attribute). I also have a class called Habitat, an instance of each would contain any number of Animals including 0.</p> <pre><code>class Animal: def __init__(self, life_span=20, age=0): self.__life_span = life_span self.__age = age def get_life_span(self): return self.__life_span def get_age(self): return self.__age def age(self): self.__age += 1 class Female(Animal): __gender = 'female' def __init__(self, pregnant=False): self.__pregnant = pregnant def impregnate(self): self.__pregnant = True class Male(Animal): __gender = 'male' class Habitat: def __init__(self, list_of_animals=[Male(), Female()]): self.__list_of_animals = list_of_animals def __add_male(self): self.__list_of_animals.append(Male()) def __add_female(self): self.__list_of_animals.append(Female()) def add_animal(self): if random.choice('mf') == 'm': self.__add_male() else: self.__add_female() def get_population(self): return self.__list_of_animals.__len__() </code></pre> <p>Before I add any more functionality, I would like to find out if that's a proper way to design these classes. Maybe there is a design pattern I can use? I'm new to OOP, any other comments/suggestions are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:40:10.843", "Id": "34636", "Score": "2", "body": "FWIW, don't call `obj.__len__()`, use `len(obj)` instead. Also, no need to use name mangling (double leading underscores): Just use `self.age` or `self._age`, especially use the former in favor of trivial getters (you can later replace them with a `property`, *if* you need that extra power, without changing the way client code works with your objects)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:41:06.173", "Id": "34637", "Score": "0", "body": "@tallseth: already flagged as such. OP: if the moderators agree, your question will be automatically migrated for you. Please do not double-post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:41:05.957", "Id": "34638", "Score": "0", "body": "It would appear you're new to OOP in general - what's your experience?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:46:59.060", "Id": "34639", "Score": "0", "body": "@JonClements somehow I managed to avoid the whole thing and it's been bugging me for years, so now I'm trying to get a grip of it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:48:45.100", "Id": "34640", "Score": "0", "body": "@MartijnPieters thanks, can I do it myself without waiting for moderators?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:49:17.600", "Id": "34641", "Score": "0", "body": "Good first attempt - but IMHO - not correct - an Animal is either Male or Female (possibly both given some species), no need to subclass a Gender" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:53:20.873", "Id": "34642", "Score": "0", "body": "@dfo: No, you can't. It is a moderator-level descision I'm afraid." } ]
[ { "body": "<p>In <code>Habitat.__init__</code>, you've committed a classic beginner's fallacy: using a list as a default argument.</p>\n\n<p>In Python, every call to a function with a default argument will use the same default object. If that object is mutable (e.g. a list) any mutations to that object (e.g. <code>.append</code>) will affect that one object. In effect, all your <code>Habitat</code>s will end up using the exact same list unless you specify a non-default argument.</p>\n\n<p>Instead, use <code>None</code> as the default argument, and test for it:</p>\n\n<pre><code>def __init__(self, animals=None):\n if animals is None:\n animals = [Male(), Female()]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:40:46.243", "Id": "21560", "ParentId": "21559", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-10T00:37:16.780", "Id": "21559", "Score": "0", "Tags": [ "python", "object-oriented", "design-patterns" ], "Title": "Instance of one class to contain arbitrary number of instances of another class in Python" }
21559
<p>I have a web scraping application that contains long string literals for the URLs. What would be the best way to present them (keeping in mind that I would like to adhere to <a href="http://www.python.org/dev/peps/pep-0008/#maximum-line-length" rel="nofollow">PEP-8</a>.</p> <pre><code>URL = "https://www.targetwebsite.co.foo/bar-app/abc/hello/world/AndThen?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea" br = mechanize.Browser() br.open(URL) </code></pre> <p>I had thought to do this:</p> <pre><code>URL_BASE = "https://www.targetwebsite.co.foo/" URL_SUFFIX = "bar-app/abc/hello/world/AndThen" URL_ARGUMENTS = "?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea" br = mechanize.Browser() br.open(URL_BASE + URL_SUFFIX + URL_ARGUMENTS) </code></pre> <p>But there are many lines and it's not a standard way of representing a URL.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T14:25:55.910", "Id": "96329", "Score": "1", "body": "I would put the URLS in a config file, or take them as a parameter." } ]
[ { "body": "<p>You could use continuation lines with <code>\\</code>, but it messes the indentation:</p>\n\n<pre><code>URL = 'https://www.targetwebsite.co.foo/\\\nbar-app/abc/hello/world/AndThen\\\n?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea'\n</code></pre>\n\n<p>Or you could use the fact that string literals next to each other are automatically concatenated, in either of these two forms:</p>\n\n<pre><code>URL = ('https://www.targetwebsite.co.foo/'\n 'bar-app/abc/hello/world/AndThen'\n '?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea')\n\nURL = 'https://www.targetwebsite.co.foo/' \\\n 'bar-app/abc/hello/world/AndThen' \\\n '?whatever=123&amp;this=456&amp;theother=789&amp;youget=the_idea'\n</code></pre>\n\n<p>I often use the parenthesized version, but the backslashed one probably looks cleaner.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T14:23:01.137", "Id": "21660", "ParentId": "21658", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T12:57:03.020", "Id": "21658", "Score": "5", "Tags": [ "python", "url" ], "Title": "Presenting long string literals (URLs) in Python" }
21658
<p>This is a Python module I have just finished writing which I plan to use at Project Euler. Please let me know how I have done and what I could do to improve it.</p> <pre><code># This constant is more or less an overestimate for the range in which # n primes exist. Generally 100 primes exist well within 100 * CONST numbers. CONST = 20 def primeEval(limit): ''' This function yields primes using the Sieve of Eratosthenes. ''' if limit: opRange = [True] * limit opRange[0] = opRange[1] = False for (ind, primeCheck) in enumerate(opRange): if primeCheck: yield ind for i in range(ind*ind, limit, ind): opRange[i] = False def listToNthPrime(termin): ''' Returns a list of primes up to the nth prime. ''' primeList = [] for i in primeEval(termin * CONST): primeList.append(i) if len(primeList) &gt;= termin: break return primeList def nthPrime(termin): ''' Returns the value of the nth prime. ''' primeList = [] for i in primeEval(termin * CONST): primeList.append(i) if len(primeList) &gt;= termin: break return primeList[-1] def listToN(termin): ''' Returns a list of primes up to the number termin. ''' return list(primeEval(termin)) def lastToN(termin): ''' Returns the prime which is both less than n and nearest to n. ''' return list(primeEval(termin))[-1] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-15T08:24:01.633", "Id": "34936", "Score": "0", "body": "It is a good idea to always follow PEP-0008 style guidolines: http://www.python.org/dev/peps/pep-0008/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-03T13:04:28.620", "Id": "161558", "Score": "0", "body": "See [this answer](http://codereview.stackexchange.com/a/42439/11728)." } ]
[ { "body": "<pre><code># This constant is more or less an overestimate for the range in which\n# n primes exist. Generally 100 primes exist well within 100 * CONST numbers.\nCONST = 20\n\ndef primeEval(limit):\n</code></pre>\n\n<p>Python convention says that functions should named lowercase_with_underscores</p>\n\n<pre><code> ''' This function yields primes using the\n Sieve of Eratosthenes.\n\n '''\n if limit:\n</code></pre>\n\n<p>What is this for? You could be trying to avoid erroring out when limit=0, but it seems to me that you still error at for limit=1.</p>\n\n<pre><code> opRange = [True] * limit\n</code></pre>\n\n<p>As with functions, lowercase_with_underscore</p>\n\n<pre><code> opRange[0] = opRange[1] = False\n\n for (ind, primeCheck) in enumerate(opRange):\n</code></pre>\n\n<p>You don't need the parens around <code>ind, primeCheck</code></p>\n\n<pre><code> if primeCheck:\n yield ind\n for i in range(ind*ind, limit, ind):\n opRange[i] = False\n\n\ndef listToNthPrime(termin):\n ''' Returns a list of primes up to the nth\n prime.\n '''\n primeList = []\n for i in primeEval(termin * CONST):\n primeList.append(i)\n if len(primeList) &gt;= termin:\n break\n return primeList\n</code></pre>\n\n<p>You are actually probably losing out by attempting to stop the generator once you pass the number you wanted. You could write this as:</p>\n\n<pre><code> return list(primeEval(termin * CONST))[:termin]\n</code></pre>\n\n<p>Chances are that you gain more by having the loop be in the loop function than you gain by stopping early. </p>\n\n<pre><code>def nthPrime(termin):\n ''' Returns the value of the nth prime.\n\n '''\n primeList = []\n for i in primeEval(termin * CONST):\n primeList.append(i)\n if len(primeList) &gt;= termin:\n break\n return primeList[-1]\n\ndef listToN(termin):\n ''' Returns a list of primes up to the\n number termin.\n '''\n return list(primeEval(termin))\n\ndef lastToN(termin):\n ''' Returns the prime which is both less than n\n and nearest to n.\n\n '''\n return list(primeEval(termin))[-1]\n</code></pre>\n\n<p>All of your functions will recalculate all the primes. For any sort of practical use you'll want to avoid that and keep the primes you've calculated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T23:39:43.093", "Id": "34831", "Score": "0", "body": "Are you suggesting that I just omit the loop within the functions nthPrime and listToNthPrime, or that I change the function primeEval to include a parameter which will allow it to terminate early? I just tested the calling functions without the loop. I was surprised the loop provides only 3% increase in speed. Also, what do you mean by \"keep primes you've calculated\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T23:43:04.793", "Id": "34832", "Score": "0", "body": "@JackJ, I'm suggesting you omit the loop. By keeping the primes, I mean that you should run sieve of erasthones once to find all the primes you need and use that data over and over again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-14T00:57:53.387", "Id": "34837", "Score": "0", "body": "@JackJ, store it in a variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-14T00:58:23.293", "Id": "34838", "Score": "0", "body": "Sorry, but how would I reuse that data? By saving the output of the sieve to a file? Also, is the reason for omitting the loop to increase readability?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T22:51:07.823", "Id": "21682", "ParentId": "21659", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T13:38:43.503", "Id": "21659", "Score": "3", "Tags": [ "python", "programming-challenge", "primes" ], "Title": "Project Euler: primes in Python" }
21659
<p>I have to define a lot of values for a Python library, each of which will represent a statistical distribution (like the Normal distribution or Uniform distribution). They will contain describing features of the distribution (like the mean, variance, etc). After a distribution is created it doesn't really make sense to change it.</p> <p>I also expect other users to make their own distributions, simplicity is an extra virtue here.</p> <p>Scala has really nice syntax for classes in cases like this. Python seems less elegant, and I'd like to do better. </p> <p>Scala:</p> <pre><code>class Uniform(min : Double, max : Double) { def logp(x : Double) : Double = 1/(max - min) * between(x, min, max) def mean = (max + min)/2 } </code></pre> <p>Python:</p> <pre><code>class Uniform(object): def __init__(self, min, max): self.min = min self.max = max self.expectation = (max + min)/2 def logp(self, x): return 1/(self.max - self.min) * between(x, self.min, self.max) </code></pre> <p>It's not <em>terrible</em>, but it's not great. There are a lot of extra <code>self</code>s in there and the constructor part seems pretty boilerplate.</p> <p>One possibility is the following nonstandard idiom, a function which returns a dictionary of locals:</p> <pre><code>def Uniform(min, max): def logp(x): return 1/(max - min) * between(x, min, max) mean = (max + min)/2 return locals() </code></pre> <p>I like this quite a bit, but does it have serious drawbacks that aren't obvious?</p> <p>It returns a dict instead of an object, but that's good enough for my purposes and <a href="https://stackoverflow.com/questions/1305532/convert-python-dict-to-object">would be easy to fix with a that made it return an object</a>.</p> <p>Is there anything better than this? Are there serious problems with this?</p>
[]
[ { "body": "<p>I'm not sure how Pythonic this is, but how about something like this:</p>\n\n<pre><code>class DynaObject(object):\n def __init__(self, *args, **kwargs):\n for (name, value) in kwargs.iteritems():\n self.__setattr__(name, value)\n\nclass Uniform(DynaObject):\n __slots__ = [\"min\", \"max\"]\n\n def logp(self, x): \n return 1/(self.max - self.min) * between(x, self.min, self.max)\n\n def mean(self): return (self.max + self.min)/2\n</code></pre>\n\n<p>You would then construct a <code>Uniform</code> object like:</p>\n\n<pre><code>u = Uniform(min=1, max=2)\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Since answering I saw a <a href=\"http://www.reddit.com/r/programming/comments/18pg2w/a_python_function_decorator_that_automatically/\" rel=\"nofollow\">post on Reddit</a> for a <a href=\"https://github.com/nu11ptr/PyInstanceVars\" rel=\"nofollow\">GitHub project</a> that offers a similar solution using a function decorator instead of sub-classing. It would allow you to have a class like:</p>\n\n<pre><code>class Uniform(object):\n @instancevars\n def __init__(self, min, max): \n pass\n\n def logp(self, x): \n return 1/(self.max - self.min) * between(x, self.min, self.max)\n\n @property\n def mean(self): return (self.max + self.min)/2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T06:18:14.087", "Id": "34812", "Score": "0", "body": "Recommendation: Use `@property` before `mean` so that `mean` acts like a (read-only) property." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T06:11:40.623", "Id": "21667", "ParentId": "21666", "Score": "6" } }, { "body": "<p>You might prefer to use <a href=\"http://docs.python.org/2/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a> for the attributes, and the <a href=\"http://docs.python.org/2/library/functions.html#property\" rel=\"nofollow noreferrer\"><code>property</code></a> decorator for <code>mean</code>. Note that <code>mean</code> is now computed every time it's accessed - maybe you don't want this, or maybe it makes sense since <code>max</code> and <code>min</code> are mutable.</p>\n\n<pre><code>from collections import namedtuple\n\nclass Uniform(namedtuple('Uniform', ('min', 'max'))):\n\n def logp(self, x):\n return 1/(self.max - self.min) * between(x, self.min, self.max)\n\n @property\n def mean(self):\n return 0.5*(self.min + self.max)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-14T17:17:47.343", "Id": "82630", "Score": "1", "body": "+1 but it's nicer to pass in the field names as a list of names though, not as a space separated string :) in fact I don't even know why the latter \"syntax\" is allowed in Python in the first place." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-02-13T06:18:37.220", "Id": "21668", "ParentId": "21666", "Score": "9" } }, { "body": "<p>This mostly comes down to a difference of style. Python really prefers explicit rather than implicit, hence explicit <code>self</code>, assignment in <code>__init__</code>, etc. It will never support a syntax like you see in Scala. This is the same reason <code>locals()</code> isn't much liked in Python--it is implicit state rather than explicit parseable syntax.</p>\n\n<p>Getting your <code>def mean</code> behavior is easy with the <code>@property</code> decorator, however. That's a non-issue. I'll focus on the initialization and implicit <code>self</code>.</p>\n\n<p>The drawbacks of your approach are that it is non-standard, it is less explicit about <code>self</code>, and the object it creates lacks a normal class. We can make it look more standard, though. The namedtuple approach from @detly is perfect if you want to make an immutable object. If you need mutable objects or a more complex initialization signature, you can use a class decorator that wraps the <code>__init__</code> call with a function that updates the instance dictionary. This is made really easy by <a href=\"http://docs.python.org/2/library/inspect.html#inspect.getcallargs\"><code>inspect.getcallargs</code></a>.</p>\n\n<pre><code>import inspect\n\ndef implicit_init(cls):\n def pass_(self):\n pass\n original_init = getattr(cls, '__init__', pass_)\n def assigning_init(self, *args, **kwds):\n # None stands in place of \"self\"\n callargs = inspect.getcallargs(original_init, None, *args, **kwds)\n self.__dict__.update(callargs)\n original_init(self, *args, **kwds)\n\n cls.__init__ = assigning_init\n\n return cls\n\n\n@implicit_init\nclass Uniform(object):\n # an init is still necessary for the creation signature\n # you can \n def __init__(self, min, max):\n # you can put stuff here, too.\n # self.min etc will already be set\n pass\n\n @property #makes readonly\n def mean(self):\n return (self.max + self.min) / 2\n\n def logp(self, x):\n return 1/(self.max - self.min) * between(x, self.min, self.max)\n</code></pre>\n\n<p>Notice there is still a bunch of <code>self</code>s in there. Python style <em>really</em> likes those, so I recommend you go no further. If you really want to get rid of them, you have to be a little ugly. The problem is that your approach conflates class creation with instance creation, approaching a prototype-style. It is not possible (without reading internal details of function objects and bytecode) to know which vars are class vars and which are instance vars. Python has support for <em>class</em> metaprogramming because there are various metaclass hooks where one can customize class creation and where the class namespace is separated neatly into its name, bases and dict (see the three-argument form of <a href=\"http://docs.python.org/2/library/functions.html#type\"><code>type()</code></a>). But it's not easy to do the same for <em>functions</em>.</p>\n\n<p>We can get around this by <em>delaying initialization of the class</em> (i.e., dynamically modifying the class) until right before the first instance is created. (I'm not going to write this because it's quite an involved bit of code, but it requires a decorator.) You might also be able to come up with a semantic you like by inspecting the <code>Uniform</code> function's code object and building a class dynamically from there.</p>\n\n<pre><code>&gt;&gt;&gt; def Uniform(min, max):\n... def logp(x):\n... return 1/(max-min) * between(x,min,max)\n... mean = (max+min)/2\n... return locals()\n... \n&gt;&gt;&gt; uco = Uniform.func_code\n&gt;&gt;&gt; uco.co_varnames\n('min', 'max', 'logp', 'mean')\n&gt;&gt;&gt; uco.co_consts\n(None, &lt;code object logp at 0x108f8a1b0, file \"&lt;stdin&gt;\", line 2&gt;, 2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T10:34:56.420", "Id": "21669", "ParentId": "21666", "Score": "6" } }, { "body": "<p>It is possible with Python 3.5+ to pass the variable types for type hints, too. This makes it even more similar to a Scala CaseClass:</p>\n\n<pre><code>import typing\nclass Uniform(typing.NamedTuple(\"GenUniform\",[('min',float),('max',float)])):\n def logp(self, x: float) -&gt; float:\n return 1/(max - min) * between(x, min, max)\np1 = Uniform(**{'min': 0.5, 'max': 1.0})\np2 = Uniform(min=0.2, max=0.3)\np3 = Uniform(0.1, 0.2)\n</code></pre>\n\n<p>See following answer for reference:\n<a href=\"https://stackoverflow.com/a/34269877/776847\">https://stackoverflow.com/a/34269877/776847</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-31T15:15:02.803", "Id": "262357", "Score": "0", "body": "I'm not very good with python and I don't know scala at all, but how does this help the original code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-31T15:39:57.000", "Id": "262371", "Score": "0", "body": "I added a function. Does it make more sense? The additional value lies in code hinting and typisation respectively." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-31T12:19:27.383", "Id": "140114", "ParentId": "21666", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T05:55:06.033", "Id": "21666", "Score": "10", "Tags": [ "python", "scala" ], "Title": "Scala inspired classes in Python" }
21666
<p>I have written a piece of python code in response to the following question and I need to know if it can be "tidied up" in any way. I am a beginner programmer and am starting a bachelor of computer science.</p> <blockquote> <p><strong>Question:</strong> Write a piece of code that asks the user to input 10 integers, and then prints the largest odd number that was entered. if no odd number was entered, it should print a message to that effect.</p> </blockquote> <p>My solution:</p> <pre><code>a = input('Enter a value: ') b = input('Enter a value: ') c = input('Enter a value: ') d = input('Enter a value: ') e = input('Enter a value: ') f = input('Enter a value: ') g = input('Enter a value: ') h = input('Enter a value: ') i = input('Enter a value: ') j = input('Enter a value: ') list1 = [a, b, c, d, e, f, g, h, i, j] list2 = [] # used to sort the ODD values into list3 = (a+b+c+d+e+f+g+h+i+j) # used this bc all 10 values could have used value'3' # and had the total value become an EVEN value if (list3 % 2 == 0): # does list 3 mod 2 have no remainder if (a % 2 == 0): # and if so then by checking if 'a' has an EVEN value it rules out # the possibility of all values having an ODD value entered print('All declared variables have even values') else: for odd in list1: # my FOR loop to loop through and pick out the ODD values if (odd % 2 == 1):# if each value tested has a remainder of one to mod 2 list2.append(odd) # then append that value into list 2 odd = str(max(list2)) # created the variable 'odd' for the highest ODD value from list 2 so i can concatenate it with a string. print ('The largest ODD value is ' + odd) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T21:02:21.650", "Id": "35021", "Score": "0", "body": "Thanks everyone for your input, i really appreciate that ! i will take a look at the extra code and try to understand how, where and why it fits in. !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T21:09:03.643", "Id": "35024", "Score": "17", "body": "If you have 10 lines that are pretty much the same chances are good that you are doing it wrong and want a loop instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T21:28:17.270", "Id": "35026", "Score": "1", "body": "great site great people ! :) whoever cant become a skilled programmer these days with all this help deserves to sit and wonder why they not moving forward.. thank you !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T02:00:32.880", "Id": "35040", "Score": "4", "body": "You seem to have a logic problem is your solution. Entering `2,1,1,2,2,2,2,2,2,2` returns `All declared variables have even values`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T07:21:04.357", "Id": "35049", "Score": "0", "body": "AHA . never saw that ! thought i had removed the logic error... good eye!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T11:07:09.847", "Id": "35057", "Score": "0", "body": "@Caramdir: I think this kind of comments should be answers. I'd upvote it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-19T04:16:35.020", "Id": "35170", "Score": "1", "body": "@palacsint at least we can up vote the comments 0:)" } ]
[ { "body": "<p>Here are a couple of places you might make your code more concise:</p>\n\n<p>First, lines 2-11 take a lot of space, and you repeat these values again below when you assign list1. You might instead consider trying to combine these lines into one step. A <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\">list comprehension</a> might allow you to perform these two actions in one step:</p>\n\n<pre><code>&gt;&gt;&gt; def my_solution():\n numbers = [input('Enter a value: ') for i in range(10)]\n</code></pre>\n\n<p>A second list comprehension might further narrow down your results by removing even values:</p>\n\n<pre><code> odds = [y for y in numbers if y % 2 != 0]\n</code></pre>\n\n<p>You could then see if your list contains any values. If it does not, no odd values were in your list. Otherwise, you could find the max of the values that remain in your list, which should all be odd:</p>\n\n<pre><code> if odds:\n return max(odds)\n else:\n return 'All declared variables have even values.'\n</code></pre>\n\n<p>In total, then, you might use the following as a starting point for refining your code:</p>\n\n<pre><code>&gt;&gt;&gt; def my_solution():\n numbers = [input('Enter a value: ') for i in range(10)]\n odds = [y for y in numbers if y % 2 != 0]\n if odds:\n return max(odds)\n else:\n return 'All declared variables have even values.'\n\n\n&gt;&gt;&gt; my_solution()\nEnter a value: 10\nEnter a value: 101\nEnter a value: 48\nEnter a value: 589\nEnter a value: 96\nEnter a value: 74\nEnter a value: 945\nEnter a value: 6\nEnter a value: 3\nEnter a value: 96\n945\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T21:35:24.023", "Id": "35028", "Score": "2", "body": "Good answer, but `if len(list2) != []:` is not really pythonic. You could simply do: `if len(list2):`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T22:18:00.027", "Id": "35030", "Score": "1", "body": "Welcome to Code Review and thanks for the excellent answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T22:34:17.333", "Id": "35031", "Score": "0", "body": "Thanks to you both for sharing your knowledge and improvements. I updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T23:37:45.727", "Id": "35034", "Score": "8", "body": "@Zenon couldn't you just do `if list2:`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T08:08:14.357", "Id": "35050", "Score": "1", "body": "@SnakesandCoffee yes you could and shouldd, because it's much better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T10:27:11.087", "Id": "35110", "Score": "0", "body": "@user1775603 A micro optimization to test whether a number is odd is y & 1 == 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:35:10.643", "Id": "58320", "Score": "0", "body": "For further optimisation, generators and trys could replace lists and conditionals: `n = (input('Enter..') for i in xrange(10))` and `o = (y for y in n if n%2)`. `try: return max(o)` `except ValueError: return 'All declared...'`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:42:03.050", "Id": "58324", "Score": "0", "body": "This gist shows the above changes. https://gist.github.com/ejrb/7581712" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T20:55:48.690", "Id": "22793", "ParentId": "22784", "Score": "31" } }, { "body": "<p>No-one has given the code I would write, which doesn't create a list but instead tracks the answer in a loop. The logic is a little more complex, but it avoids storing values (here it doesn't really matter, since it's only 10 values, but a similar problem with input from another program, might have more data than fits in memory).</p>\n\n<pre><code>maxOdd = None\nfor _ in range(10):\n value = int(input('Enter a value: '))\n if (value % 2 and (maxOdd is None or value &gt; maxOdd)):\n maxOdd = value\nif maxOdd:\n print('The largest odd value entered was', maxOdd)\nelse:\n print('No odd values were entered.')\n</code></pre>\n\n<p>Note that I am treating non-zero values as <code>True</code>, so <code>value % 2</code> is a test for oddness (because it gives a non-zero remainder, and Python treats non-zero values as <code>true</code>). Similarly, <code>if maxOdd</code> tests that <code>maxOdd</code> is not <code>None</code> (nor zero, but it cannot be zero, because that is even).</p>\n\n<p>Another way, closer to the other answers, in that it treats the numbers as a sequence, but still avoiding storing everything in memory, is to use a generator:</p>\n\n<pre><code>from itertools import islice\n\ndef numbers():\n while True:\n yield input('Enter a value: ')\n\ndef odd(n):\n return n % 2\n\ntry:\n print('The largest odd value entered was',\n max(filter(odd, map(int, islice(numbers(), 10)))))\nexcept ValueError:\n print('No odd values were entered.')\n</code></pre>\n\n<p>This is more \"advanced\", but <code>numbers()</code> creates a <em>generator</em>, and the chain of functions <code>max, filter, map, islice</code> effectively call that for each value (simplifying slightly). So the end result is a kind of pipeline that, again, avoids keeping everything in memory.</p>\n\n<p>(The <code>ValueError</code> happens when <code>max</code> doesn't receive any values.)</p>\n\n<p>Another way of writing that would be (note the lack of square brackets):</p>\n\n<pre><code>try:\n print('The largest odd value entered was',\n max(filter(odd,\n map(int, (input('Enter a value: ')\n for _ in range(10))))))\nexcept ValueError:\n print('No odd values were entered.')\n</code></pre>\n\n<p>where <code>(input ...)</code> is a generator expression.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T06:50:55.897", "Id": "35048", "Score": "0", "body": "thank you, ur right, it is a little advanced for me right now, although i like the idea of not storing the values. any suggestions on a good reading material related to computer logic?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T23:19:37.690", "Id": "22798", "ParentId": "22784", "Score": "14" } }, { "body": "<p>I would do it something like this:</p>\n\n<pre><code>def is_odd(x):\n return x &amp; 1 and True or False\n\n\nolist = []\n\nfor i in xrange(10):\n while True:\n try:\n n = int(raw_input('Enter a value: '))\n break\n except ValueError:\n print('It must be an integer.')\n continue\n\n if is_odd(n):\n olist.append(n)\n\ntry:\n print 'The largest ODD value is %d' % max(olist)\nexcept ValueError:\n print 'No ODD values were entered'\n</code></pre>\n\n<p>The <code>is_odd</code> function is checking the last bit of the integer to see if it is set (1) or not (0). If it's set then it must be odd. Eg: 010 (2 is not odd) 011 (3 is odd).</p>\n\n<p>Also, I would filter odds on the fly so I don't need to parse the list multiple times and I would use xrange (a generator) to keep memory \"safe\".</p>\n\n<p>For this case those \"optimizations\" wouldn't be necessary as the list is only size 10 and there isn't much computation but if you had to take a lot of integers you would need to consider it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T09:11:16.157", "Id": "35051", "Score": "0", "body": "With python3, I prefer range since it is optimized to do lazy evaluation. xrange.. doesn't feel good while reading. :P" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T23:49:21.817", "Id": "22800", "ParentId": "22784", "Score": "3" } }, { "body": "<p>Since you didn't specify whether you're using Python 2 or Python 3, I'm not sure if the below answer is relevant. In Python 2, <code>input</code> is risky. In Python 3, <code>input</code> is fine.</p>\n\n<p>Although some answers have replaced <code>input(...)</code> by <code>int(raw_input(...))</code>, I don't think anybody has explained yet <em>why</em> this is recommended.</p>\n\n<h2><code>input</code> considered harmful in Python 2.x</h2>\n\n<p>In Python 2.x, <code>input(x)</code> is equivalent to <code>eval(raw_input(x))</code>. See, for example, the documentation for <code>input</code> in <a href=\"http://docs.python.org/2/library/functions.html#input\" rel=\"nofollow\">Python 2.7</a>, and <a href=\"http://docs.python.org/2/library/functions.html#raw_input\" rel=\"nofollow\">the documentation for <code>raw_input</code></a>. This means that <em>a user can execute an arbitrary Python expression</em>, such as:</p>\n\n<pre><code>&gt;&gt;&gt; input(\"Number? \")\nNumber? os.unlink(\"/path/to/file\") \n</code></pre>\n\n<p>Therefore, in Python 2, <strong>always use <code>raw_input</code> rather than <code>input</code></strong>.</p>\n\n<p>Some explanation: <code>raw_input</code> returns a string, for example, <code>'10'</code>. This string you need to convert to a number. The function <code>int</code> can do this for you (<a href=\"http://docs.python.org/2/library/functions.html#int\" rel=\"nofollow\">see documentation in Python 2.7</a>). So wherever you use <code>input</code> to get a whole number, you would rather want <code>int(raw_input(...))</code>. This will take the input as a string, and immediately convert it to an integer. This will raise an exception if the input cannot be converted to an integer: </p>\n\n<pre><code>&gt;&gt;&gt; int(raw_input(\"Number? \"))\nNumber? os.unlink(\"/path/to/file\")\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nValueError: invalid literal for int() with base 10: 'os.unlink(\"/path/to/file\")'\n</code></pre>\n\n<p>In Python 3, <code>input</code> is equivalent to Python 2 <code>raw_input</code>, see for example, the documentation for <code>input</code> in <a href=\"http://docs.python.org/3.3/library/functions.html#input\" rel=\"nofollow\">Python 3.3</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T10:56:15.807", "Id": "35055", "Score": "0", "body": "I see. i was trying to create this program and it wouldnt run when i used raw_input, im using python2.7, but it took input and worked. why would that be? and thanks for the insight" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T11:00:31.163", "Id": "35056", "Score": "0", "body": "@RyanSchreiber I added some explanation" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T11:07:20.883", "Id": "35058", "Score": "0", "body": "fantastic, okay, i understand now why it never worked! another note on that, why would i as a programmer, want to have the text inputted as a string and converted to an integer ? is this a secure way of programming and if so what is the reason behind that? and btw, yes, i will read the documentation, would just like another outside view on it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T13:55:48.423", "Id": "35062", "Score": "0", "body": "surely you mean `raw_input` rather than `input`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T14:39:29.230", "Id": "35065", "Score": "0", "body": "@Ysangkok Oops, yes I do of course, now fixed." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T10:54:05.937", "Id": "22813", "ParentId": "22784", "Score": "3" } }, { "body": "<p>I think in this case, performance is of no concern and so the priority is making workings of the program as immediately obvious as possible.</p>\n\n<pre><code>user_input = [input('Enter a value: ') for x in range(10)]\nnumbers = map(int, user_input)\nodd_numbers = [n for n in numbers if n % 2 != 0]\nif odd_numbers:\n print(max(odd_numbers))\nelse:\n print(\"All the numbers are even\")\n</code></pre>\n\n<p>Here each line is a new logical and concise step.</p>\n\n<ol>\n<li>Get numbers from user as strings using <code>input</code> in Python 3 or <code>raw_input</code> in Python 2.</li>\n<li>Convert the strings to ints.</li>\n<li>Extract all the odd numbers from the list of numbers.</li>\n<li>Print the biggest odd number or a message.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-10T15:08:23.043", "Id": "29591", "ParentId": "22784", "Score": "0" } }, { "body": "<p>This is the finger exercise from Ch.2 of Introduction to Computation and Programming Using Python by John V. Guttag. It's the recommended text for the MITx: 6.00x Introduction to Computer Science and Programming. The book is written to be used with Python 2.7.</p>\n\n<p>At this point the book has only introduced variable assignment, conditional branching programs and while loops as well as the print function. I know as I'm working through it. To that end this is the code I wrote:</p>\n\n<pre><code>counter = 10\nwhile counter &gt; 0:\n x = int(raw_input('Please type in integer: '))\n if counter == 10 or (x%2 and x &gt; ans):\n ans = x\n if ans%2 == 0: # Even Number Safeguard\n ans = x \n counter = counter -1\nif ans%2 != 0:\n print 'The largest odd number entered was', str(ans)\nelse:\n print 'No odd number was entered'`\n</code></pre>\n\n<p>Seems to work. It can probably be shortened but the idea was to use only the limited concepts that have been covered in the book.</p>\n\n<p><strong>EDITED</strong> to include commments to shorten code. Still meets the criteria of using the limited concepts introduced in the book.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T02:46:29.453", "Id": "54795", "Score": "0", "body": "I was referring to the exact question from the text. I've change it now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T02:48:00.240", "Id": "54796", "Score": "0", "body": "Oh, okay. It seemed like a new question at first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T14:04:03.893", "Id": "56860", "Score": "1", "body": "`ans = ans` does nothing, and you could simplify all the `if...else...elif` conditions to a single one: `if counter == 10 or (x % 2 and x > ans): ans = x`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T04:29:15.283", "Id": "57106", "Score": "0", "body": "Yep, it can definitely be shortened. I'll get my head round the computational way of thinking, eventually." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T18:26:33.670", "Id": "57316", "Score": "0", "body": "I suggest: `ans = None` at the top, `if x % 2 and (ans is None or x > ans)` inside the loop, and `if ans is not None` after the loop. Not repeating `10` and `% 2` makes the code more maintainable. (That ends up being @andrewcooke's answer, except without using `range()`.)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T02:42:19.557", "Id": "34087", "ParentId": "22784", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T19:07:26.577", "Id": "22784", "Score": "28", "Tags": [ "python", "beginner" ], "Title": "Asks the user to input 10 integers, and then prints the largest odd number" }
22784
<p>I have been trying to make a simple "quiz" program in Python. What I plan to make is, say, a quiz of 3 rounds and each round having 3 questions. And at the end of the every round, the program will prompt the user to go for the "bonus" question or not.</p> <pre><code>print("Mathematics Quiz") question1 = "Who is president of USA?" options1 = "a.Myslef\nb. His dad\nc. His mom\nd. Barack Obama\n" print(question1) print(options1) while True: response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n") if response == "d": break else: print("Incorrect!!! Try again.") while True: response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n") if response == "d": stop = True break else: print("Incorrect!!! You ran out of your attempts") stop = True break if stop: break # DO the same for the next questions of your round (copy-paste-copy-paste). # At the end of the round, paste the following code for the bonus question. # Now the program will ask the user to go for the bonus question or not while True: bonus = input("Would you like to give a try to the bonus question?\nHit 'y' for yes and 'n' for no.\n") if bonus == "y": print("Who invented Facebook?") print("a. Me\nb. His dad\nc. Mark Zuckerberg\nd. Aliens") while True: response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n") if response == "c": break else: print("Incorrect!!! Try again.") while True: response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n") if response == "c": stop = True break else: print("Incorrect!!! You ran out of your attempts") stop = True break if stop: break break elif bonus == "n": break else: print("INVALID INPUT!!! Only hit 'y' or 'n' for your response") # Now do the same as done above for the next round and another bonus question. </code></pre> <p>Now this code is very long for a single question and I don't think this is the "true" programming. I don't want to copy-paste it again and again. I was wondering is there any way to shorten the code using <code>class</code> or defining functions or something like that?</p>
[]
[ { "body": "<pre><code>asking = True\nattempts = 0\nwhile asking == True:\n response = input(\"Hit 'a', 'b', 'c' or 'd' for your answer\\n\")\n\n if response == \"d\":\n asking = False\n else:\n if attempts &lt; 1: # 1 = Max Attempts\n print(\"Incorrect!!! Try again.\")\n attempts += 1\n else:\n print(\"Incorrect!!! You ran out of your attempts\")\n asking = False\n</code></pre>\n\n<p>The second part follows the same pattern and serves as a good exercise.</p>\n\n<p>The main thing here is to note you're chaining while loops to loop, instead of actually letting the while loop loop. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T12:44:04.697", "Id": "35066", "Score": "0", "body": "Yeah, but still I have to copy-paste the code for every question, don't I?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T12:45:23.540", "Id": "35067", "Score": "0", "body": "@PreetikaSharma Look into functions, I gave you a link in the comments to your question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T12:48:31.787", "Id": "35068", "Score": "0", "body": "Just parametrize what varies for each question and move it into a function, as suggested." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T12:49:07.120", "Id": "35069", "Score": "0", "body": "@JonasWielicki Oops, I thought, that was just the comment. Let me see now." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T12:31:41.907", "Id": "22823", "ParentId": "22822", "Score": "1" } }, { "body": "<p>As Jonas Wielicki said, your best option would be to use <a href=\"http://docs.python.org/2/tutorial/controlflow.html#defining-functions\" rel=\"nofollow\">functions</a>.</p>\n\n<p>However, you can shorten the code first to the answer Javier Villa gave: </p>\n\n<pre><code> asking = True\n attempts = 0\n while asking == True:\n response = input(\"Hit 'a', 'b', 'c' or 'd' for your answer\\n\")\n\n if response == \"d\":\n asking = False\n else:\n if attempts &lt; 1: # 1 = Max Attempts\n print(\"Incorrect!!! Try again.\")\n attempts += 1\n\n else: print(\"Incorrect!!! You ran out of your attempts\")\n asking = False\n</code></pre>\n\n<p>For more tips on improving the speed and performance, see <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow\">performance tips</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T13:24:00.153", "Id": "22824", "ParentId": "22822", "Score": "0" } }, { "body": "<pre><code>import string\n\nNUMBER_OF_ATTEMPTS = 2\nENTER_ANSWER = 'Hit %s for your answer\\n'\nTRY_AGAIN = 'Incorrect!!! Try again.'\nNO_MORE_ATTEMPTS = 'Incorrect!!! You ran out of your attempts'\n\ndef question(message, options, correct, attempts=NUMBER_OF_ATTEMPTS):\n '''\n message - string \n options - list\n correct - int (Index of list which holds the correct answer)\n attempts - int\n '''\n optionLetters = string.ascii_lowercase[:len(options)]\n print message\n print ' '.join('%s: %s' % (letter, answer) for letter, answer in zip(optionLetters, options))\n while attempts &gt; 0:\n response = input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 3\n #response = raw_input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 2\n if response == optionLetters[correct]:\n return True\n else:\n attempts -= 1\n print TRY_AGAIN\n\n print NO_MORE_ATTEMPTS\n return False\n\n\nprint(\"Mathematics Quiz\")\n\n# question1 and question2 will be 'True' or 'False' \nquestion1 = question('Who is president of USA?', ['myself', 'His Dad', 'His Mom', 'Barack Obama'], 3)\nquestion2 = question('Who invented Facebook?', ['Me', 'His Dad', 'Mark Zuckerberg', 'Aliens', 'Someone else'], 2)\n</code></pre>\n\n<p>I'm not sure which python you are using. Try both line 20 or line 21 to see which works best for you. </p>\n\n<p>Overall this function allows you to enter in questions with as many responses as you want and it will do the rest for you.</p>\n\n<p>Good luck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T14:32:26.023", "Id": "35070", "Score": "0", "body": "Thank you. It worked. Only I had to change `string.lowercase` to `string.ascii_lowercase` since I am using Python 3x. I think I need some good practice with defining functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T14:56:31.683", "Id": "35071", "Score": "0", "body": "Good spot, I updated my answer. Seems both Python 2 and 3 have ascii_lowercase, but lowercase got removed in 3. Indeed use functions where ever you can." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T16:03:20.920", "Id": "35074", "Score": "0", "body": "You still skipped the print parentheses at these places: \n`print(message)`, `print` statement below that, `print` statements after `attempts -=1`. I apologize for not mentioning them before." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T14:13:41.547", "Id": "22825", "ParentId": "22822", "Score": "4" } }, { "body": "<p>You can also use dictionary to prepare questions and then simply ask them in some order (random in this case):</p>\n\n<pre><code>import random\n\n# Dictionary of questions and answers\n\nquestions = {\n 'Who is president of USA?':\n ('\\na. Myslef\\nb. His dad\\nc. His mom\\nd. Barack Obama\\n', 'd'),\n 'What is the capital of USA?':\n ('\\na. Zimbabwe\\nb. New York\\nc. Washington\\nd. Do not exist', 'c')\n }\n\ndef ask_question(questions):\n '''Asks random question from 'questions 'dictionary and returns\n players's attempt and correct answer.'''\n\n item = random.choice(list(questions.items()))\n question = item[0]\n (variants, answer) = item[1]\n print(question, variants)\n attempt = input('\\nHit \\'a\\', \\'b\\', \\'c\\' or \\'d\\' for your answer\\n')\n return (attempt, answer)\n\n# Questions loop\ntries = 0\nfor questions_number in range(5):\n while True: # Asking 1 question\n attempt, answer = ask_question(questions)\n if attempt not in {'a', 'b', 'c', 'd'}:\n print('INVALID INPUT!!! Only hit \\'y\\' or \\'n\\' for your response')\n elif attempt == answer:\n print('Correct')\n stop_asking = False\n break\n elif tries == 1: # Specify the number of tries to fail the answer \n print('Incorrect!!! You ran out of your attempts')\n stop_asking = True\n break\n else:\n tries += 1\n print('Incorrect!!! Try again.')\n if stop_asking:\n break\n</code></pre>\n\n<p>You can use this as template and modify code a bit to add bonus check or just enclose part of loop in another function which will be called in main loop.</p>\n\n<p>Plus with minor edit you can import questions and answers from text file.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-30T11:08:19.820", "Id": "142894", "ParentId": "22822", "Score": "3" } } ]
{ "AcceptedAnswerId": "22825", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T12:25:37.470", "Id": "22822", "Score": "3", "Tags": [ "python", "quiz" ], "Title": "Simple quiz program" }
22822
<p>I have just started to learn programming with Python. I have been going through several online classes for the last month or two. Please bear with me if my questions are noobish.</p> <p>One of the classes I am taking asked us to solve this problem.</p> <pre><code># Define a procedure, check_sudoku, # that takes as input a square list # of lists representing an n x n # sudoku puzzle solution and returns the boolean # True if the input is a valid # sudoku square and returns the boolean False # otherwise. # A valid sudoku square satisfies these # two properties: # 1. Each column of the square contains # each of the whole numbers from 1 to n exactly once. # 2. Each row of the square contains each # of the whole numbers from 1 to n exactly once. # You may assume the the input is square and contains at # least one row and column. </code></pre> <p>After a while of trying to come up with the best code I can, this is what I ended up with.</p> <pre><code>def check_sudoku(sudlist): x = range(1, len(sudlist)+1) # makes a list of each number to be found rows = [[row[i] for row in sudlist] for i in range(len(sudlist))] # assigns all the rows to a flat list z = range(len(sudlist)) for num in x: for pos in z: if num not in sudlist[pos] or num not in rows[pos]: return False return True </code></pre> <p>This code does work and passed all checks the class asked for. I just wonder what problems could the code have or how would you improve it?</p> <p>I am just trying to improve by getting input from others. I appreciate any suggestions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T22:58:29.257", "Id": "35094", "Score": "0", "body": "The problem seems poorly stated. A Sudoku grid has *three* types of constraint: rows, columns, and *blocks*. A grid that only has row and column constraints is known as a [Latin square](http://en.wikipedia.org/wiki/Latin_square)." } ]
[ { "body": "<p>I would use <a href=\"http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset\"><code>set</code></a> to do the checks, and you can build the columns using some <a href=\"http://docs.python.org/2/library/functions.html#zip\"><code>zip</code></a> magic:</p>\n\n<pre><code>def check_sudoku(sudlist) :\n numbers = set(range(1, len(sudlist) + 1))\n if (any(set(row) != numbers for row in sudlist) or\n any(set(col) != numbers for col in zip(*sudlist))) :\n return False\n return True\n</code></pre>\n\n<p>I have tested it with the following samples:</p>\n\n<pre><code>a = [[1, 2, 3, 4, 5],\n [2, 3, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [5, 4, 1, 3, 2]] # latin square\n\nb = [[1, 2, 3, 4, 5],\n [2, 3, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [3, 4, 1, 5, 2]] # 1st and 4th elements of last row interchanged\n\nc = [[1, 2, 3, 4, 5],\n [2, 4, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [5, 3, 1, 3, 2]] #1st and 5th elements of second column intechanged\n\n\n&gt;&gt;&gt; check_sudoku(a)\nTrue\n&gt;&gt;&gt; check_sudoku(b)\nFalse\n&gt;&gt;&gt; check_sudoku(c)\nFalse\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T23:58:31.987", "Id": "22841", "ParentId": "22834", "Score": "8" } }, { "body": "<pre><code>def check_sudoku(sudlist):\n x = range(1, len(sudlist)+1) # makes a list of each number to be found'\n</code></pre>\n\n<p>Avoid storing things in single-letter variable names. It just makes it hearder to folllow your code</p>\n\n<pre><code> rows = [[row[i] for row in sudlist] for i in range(len(sudlist))] # assigns all the rows to a flat list\n</code></pre>\n\n<p>You could actually do <code>rows = zip(*sudlist)</code> which will do the same thing. Admittedly, if you've not seen the trick before its non-obvious.</p>\n\n<pre><code> z = range(len(sudlist))\n for num in x:\n</code></pre>\n\n<p>There's not really any reason to store the list in x, and then iterate over it later. Just combine the lines.</p>\n\n<pre><code> for pos in z:\n</code></pre>\n\n<p>Instead use <code>for column, row in zip(sudlist, rows):</code> and you won't need to use the pos index</p>\n\n<pre><code> if num not in sudlist[pos] or num not in rows[pos]:\n return False\n return True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T11:00:25.527", "Id": "35121", "Score": "1", "body": "You're right that the OP's variable names are poorly chosen, but I don't think that \"avoid single-letter names\" is quite the right criterion. What names would you prefer here: `def quadratic(a, b, c): return [(-b + sign * sqrt(b ** 2 - 4 * a * c)) / (2 * a) for sign in (-1,+1)]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T15:08:02.440", "Id": "35133", "Score": "1", "body": "@GarethRees, agreed that its not absolute, that's why I said \"avoid\" not \"never do this\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T03:52:05.883", "Id": "22844", "ParentId": "22834", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T21:28:47.017", "Id": "22834", "Score": "5", "Tags": [ "python", "beginner", "sudoku" ], "Title": "Check_sudoku in Python" }
22834
<p>I tried to refactoring someone else's code and I found that there is alot of this pattern</p> <pre><code>def train(a, b, c, d, e, f, g, h, i, j, k): #Real code has longer name and around 10-20 arguments x = Dostuff() y = DoMoreStuff(b,c,d,e,f,g,h,x) z = DoMoreMoreStuff(a,b,d,e,g,h,j,y) def DoMoreStuff(b,c,d,e,f,g,h): DoPrettyStuff(b,c,d,e,f,g,h) # The actually depth of function call is around 3-4 calls </code></pre> <p>I though that it would it be better to collect all of that a,b,c,d into one dictionary. I got this idea when I was reading about rail rack's middleware. </p> <pre><code>env = {"a":1, "b", 2.......} def train(env): x = Dostuff() y = DoMoreStuff(env.update({"x":x})) z = DoMoreMoreStuff(env.update({"y":y})) def DoMoreStuff(env) DoPrettyStuff(env) </code></pre> <p>But I am not sure if there is any downside about this approach ? If it does help, every function here has a side-effect.</p> <p>EDIT: For more clarification. I think most of my problem are about the propagation of variables. The call pattern has very deep and wide hierarchy. Any further suggestion about this one ?</p> <pre><code>def main(a,b,c,d,e,f,g,h,i,j,k,l,m....z): Do(...) #maybe other function() def Do(a,b,c,d,e,f,g,h,i,j,k,l): Do1(d,e,f,g,h,i,j,k,l) def Do1(d,e,f,g,h,i,j,k,l) Do2(f,g,h,i,j,k,l) def Do2(f,g,h,i,j,k,l) Do3(f,g,h,i) Do4(j,k,l) </code></pre> <p>EDIT 2: Well, my intention is that I want the code more easier to read and followed. Performance in python code does not matter much since the program spend most of the time on SVM and machine learning stuff. If anyone interest and don't mind a very dirty code that I still working on it. Here is the real code <a href="https://github.com/yumyai/TEES/tree/30b3aeaab011e30dcdc3c1151062697861ddcae1" rel="nofollow">https://github.com/yumyai/TEES/tree/30b3aeaab011e30dcdc3c1151062697861ddcae1</a> </p> <p>The code start with train.py (training model), classify.py (classify using model). In this case I'll use train.py as an example. <a href="https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/train.py" rel="nofollow">https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/train.py</a>: line 136 where it start to call everything under it and pass a gigantic arguments to. These arguments are pass down to <a href="https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/Detectors/EventDetector.py" rel="nofollow">https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/Detectors/EventDetector.py</a>: line 49. And then EventDetector pass these argument to it members (line 24-28).</p> <p>Some argument is reused throughout the code, for example, def train(.......exampleStyles). exampleStyles is passed around to several member that is called by train. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T07:31:48.753", "Id": "35241", "Score": "5", "body": "If you asked me, if you have a function that requires that many independent parameters, it's trying to do too much. You could also consider changing it so the function uses keyword arguments, than way you can switch between the two forms easily." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T07:43:00.497", "Id": "35243", "Score": "0", "body": "Thanks for the suggestion. I was planning to break down function into bite-side too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T10:21:09.700", "Id": "35253", "Score": "2", "body": "I really would like to see your real methods signatures. I'm pretty sure we could help you in more detail if we know what your are going to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T10:54:34.020", "Id": "35254", "Score": "0", "body": "@mnhg I want to make code more easier to follow and easy to read. This code is actually a NLP analysis pipeline that I fork from and several parameters/arguments are either\n1. Doing to many thing at one method as others suggest\n2. Keep everything in sync, because it rely alot on external file/arguments. Each function is bloat with argument mostly because of this.\nI'll EDIT my question to post a my code then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T11:00:50.190", "Id": "35255", "Score": "0", "body": "Pipeline is the keyword. If you follow a data-driven approach you should easily be able to pack your data in a kind of a work package which you can pipe throw your line. Has this to be parallelisable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T11:17:49.470", "Id": "35256", "Score": "0", "body": "Where can I learn more about this \"data-driven approach\" ? Parallelism is not needed but preferred, if it does not take much time or too hard. I haven't full understand the whole code yet but I think most of the function could run as a parallel pipeline." } ]
[ { "body": "<blockquote>\n <p>I though that it would it be better to collect all of that a,b,c,d into one dictionary.</p>\n</blockquote>\n\n<p>In this particular case, rather than dictionary, I'd say it's probably better to declare a class. In python, objects is a syntax sugar for dictionary anyway.</p>\n\n<pre><code>class A(object):\n def __init__(self, **params):\n assert {'a', 'b'}.issubset(d) # required parameters\n for k,v in dict(c=None, d=4): params.setdefault(k,v)\n self.__dict__.update(params)\n\n def train(self):\n print self.a, self.b\n self.Dostuff()\n self.DoMoreStuff(self.c)\n self.DoMoreStuff(self.d)\n self.DoMoreMoreStuff()\n\na = A(a=1, b=2, ...)\n</code></pre>\n\n<p>of course you don't have to stuff it all in a single class, you might want to split the parameters into multiple classes where it makes sense to do so according to OOP principles.</p>\n\n<blockquote>\n <p>most functions in the code usually has some \"core\" argument that keep repeating throughout</p>\n</blockquote>\n\n<p>that is a good candidate to put them into a single class.</p>\n\n<blockquote>\n <p>Is there any downside to define a function that use one dictionary as an argument instead of several (+10) arguments?</p>\n</blockquote>\n\n<p>Yes, you lose parameter checking that is usually done by the interpreter so you'd have to do them yourself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T14:02:53.457", "Id": "22928", "ParentId": "22911", "Score": "2" } } ]
{ "AcceptedAnswerId": "22921", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T06:50:32.060", "Id": "22911", "Score": "3", "Tags": [ "python" ], "Title": "Is there any downside to define a function that use one dictionary as an argument instead of several (+10) arguments?" }
22911
<p>Here I have some simple code that worries me, look at the second to last line of code, I have to return spam in order to change spam in the global space. Also is it bad to be writing code in this space and I should create a function or class to call from that space which contains most my code?</p> <p>I found out very recently that I never even understood the differences between Python's identifiers compared to C or C++'s variables. This helps put into perspective why I always have so many errors in Python.</p> <p>I do not want to continue writing code and get into a bad habit and this is why I want your opinion.</p> <p>I also have a tendency to do things like <code>spam = fun()</code> because I do not know how to correctly make Python call a function which changes a variable in the scope of where the function was called. Instead I simply return things from the functions never learning how to correctly write code, I want to change that as soon as possible.</p> <pre><code>import random MAX = 20 def randomize_list(the_list, x=MAX): for i in range(len(the_list)): the_list[i] = random.randint(1, x) def lengthen_list(the_list, desired_length, x=MAX): if len(the_list) &gt;= desired_length: print "erroneous call to lengthen_list(), desired_length is too small" return the_list while(len(the_list) &lt; desired_length): the_list.append(random.randint(1, x)) # organize the_set the_list = set(the_list) the_list = list(the_list) return the_list spam = list(range(10)) randomize_list(spam, MAX) print "the original list:" print spam, '\n' spam = set(spam) spam = list(spam) print "the set spam:" print spam print "the set spam with length 10" spam = lengthen_list(spam, 10, MAX) print spam </code></pre> <p>Please help me adopt a style which correctly fixes, in particular, the second to last line of code so that I do not need the function to do return things in order to work, if this is even possible.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:07:22.220", "Id": "35318", "Score": "0", "body": "Well, I am not a python expert and this is more like my general convention than python convention. You should not reuse variable name. For example, set(spam) and list(spam) should not be assign to the same variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:14:50.947", "Id": "35319", "Score": "0", "body": "@Tg. Yes I know what you mean. The point of the code I think you are talking about changes spam to a set and then back to a list. This is a quick and dirty way of removing repetitious values in the list and organizing them least to greatest in value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:28:26.850", "Id": "35321", "Score": "1", "body": "Well, others already comment on most of your concern. For about your quick and dirty way, here is the better version.\n\nuniqSpam = list(set(spam))\n\nYou should avoid any one-time-use intermediate variable if it does not cluttering much on the right hand side." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-24T14:06:50.190", "Id": "306783", "Score": "0", "body": "Since you wrote this question, our standards have been updated. Could you read [ask] and update your question to match what it is now?" } ]
[ { "body": "<blockquote>\n <p>I also have a tendency to do things like spam = fun() because I do not\n know how to correctly make Python call a function which changes a\n variable in the scope of where the function was called.</p>\n</blockquote>\n\n<p>You can't. You cannot replace a variable in an outer scope. So in your case, you cannot replace the list with a new list, although you can modify the list. To make it clear</p>\n\n<pre><code>variable = expression\n</code></pre>\n\n<p>replaces a variable, whereas pretty much anything else:</p>\n\n<pre><code>variable[:] = expression\nvariable.append(expression)\ndel variable[:]\n</code></pre>\n\n<p>Modifies the object. The bottom three will take effect across all references to the object. Whereas the one before replaces the object with another one and won't affect any other references.</p>\n\n<p>Stylistically, it somestimes makes sense to have a function modify a list, and other times it makes sense for a function to return a whole new list. What makes sense depends on the situation. The one rule I'd pretty much always try to follow is to not do both. </p>\n\n<pre><code>def randomize_list(the_list, x=MAX):\n for i in range(len(the_list)):\n the_list[i] = random.randint(1, x)\n</code></pre>\n\n<p>This isn't a good place to use a modified list. The incoming list is ignored except for the length. It'd be more useful as a function that returns a a new list given a size something like:</p>\n\n<pre><code>def random_list(length, maximum = MAX):\n random_list = []\n for _ in range(length):\n random_list.append( random.randint(1, maximum) )\n return random_list\n\ndef lengthen_list(the_list, desired_length, x=MAX):\n if len(the_list) &gt;= desired_length:\n print \"erroneous call to lengthen_list(), desired_length is too small\"\n</code></pre>\n\n<p>Don't report errors by print, raise an exception</p>\n\n<pre><code> raise Exception(\"erroneous call...\")\n\n\n return the_list\n while(len(the_list) &lt; desired_length):\n the_list.append(random.randint(1, x))\n # organize the_set\n the_list = set(the_list)\n the_list = list(the_list)\n</code></pre>\n\n<p>That's not an efficient way to do that. You constantly convert back between a list and set. Instead do something like</p>\n\n<pre><code> new_value = random.randint(1, maximum)\n if new_value not in the_list:\n the_list.append(new_value)\n</code></pre>\n\n<p>That way you avoid the jumping back and forth, and it also modifies the original object rather then creating a new list.</p>\n\n<pre><code> return the_list\n</code></pre>\n\n<p>This particular function could go either way in terms of modifying or returning the list. Its a judgement call which way to go. </p>\n\n<blockquote>\n <p>Also is it bad to be writing code in this space and I should create a\n function or class to call from that space which contains most my code?</p>\n</blockquote>\n\n<p>Yes, you should really put everything in a function and not at the main level for all but the most trivial scripts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:21:29.633", "Id": "35320", "Score": "0", "body": "I have not seen code like yours such as: `for _ in range(length):`, does the underscore just mean that we are not going to use some value from the range, we are instead going to do something `length` times?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T11:03:38.803", "Id": "35331", "Score": "0", "body": "@Leonardo: yes, it's conventional to use `_` for a loop variable that's otherwise unused. See [here](http://stackoverflow.com/q/1739514/68063) or [here](http://stackoverflow.com/q/5893163/68063)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:16:23.067", "Id": "22952", "ParentId": "22951", "Score": "4" } } ]
{ "AcceptedAnswerId": "22952", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T04:57:04.963", "Id": "22951", "Score": "2", "Tags": [ "python" ], "Title": "What parts of my Python code are adopting a poor style and why?" }
22951
<p>I needed short, unique, seemingly random URLs for a project I'm working on, so I put together the following after some research. I believe it's working as expected, but I want to know if there's a better or simpler way of doing this. Basically, it takes an integer and returns a string of the specified length using the character list. I'm new to Python, so help is much appreciated.</p> <pre><code>def genkey(value, length=5, chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', prime=694847539): digits = [] base = len(chars) seed = base ** (length - 1) domain = (base ** length) - seed num = ((((value - 1) + seed) * prime) % domain) + seed while num: digits.append(chars[num % base]) num /= base return ''.join(reversed(digits)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T08:18:10.170", "Id": "35328", "Score": "1", "body": "Without knowing your concrete requirements: What do you think about hashing your value and take the first x characters? Maybe you will need some additional checking for duplicates." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T16:33:51.083", "Id": "35366", "Score": "0", "body": "@mnhg I thought about that as well. This sort of became an exercise for its own sake at some point. How would you suggest handling duplicates?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T05:02:15.627", "Id": "35444", "Score": "0", "body": "As this seems not performance critical, I would simple check the existing in the indexed database column that is storing the short url mapping. (Might also be a hashmap.) If I find a conflict I would a attached the current time/spaces/whatever and try it again or just rehash the hash once again." } ]
[ { "body": "<p>The trouble with using a pseudo-random number generator to produce your shortened URLs is, <em>what do you do if there is a collision?</em> That is, what happens if there are values <code>v</code> and <code>w</code> such that <code>v != w</code> but <code>genkey(v) == genkey(w)</code>? Would this be a problem for your application, or would it be entirely fine?</p>\n\n<p>Anyway, if I didn't need to solve the collision problem, I would use Python's <a href=\"http://docs.python.org/2/library/random.html\" rel=\"nofollow\">built-in pseudo-random number generator</a> for this instead of writing my own. Also, I would add a docstring and some <a href=\"http://docs.python.org/2/library/doctest.html\" rel=\"nofollow\">doctests</a>.</p>\n\n<pre><code>import random\nimport string\n\ndef genkey(value, length = 5, chars = string.ascii_letters + string.digits):\n \"\"\"\n Return a string of `length` characters chosen pseudo-randomly from\n `chars` using `value` as the seed.\n\n &gt;&gt;&gt; ' '.join(genkey(i) for i in range(5))\n '0UAqF i0VpE 76dfZ oHwLM ogyje'\n \"\"\"\n random.seed(value)\n return ''.join(random.choice(chars) for _ in xrange(length))\n</code></pre>\n\n<p><strong>Update:</strong> you clarified in comments that you <em>do</em> need to avoid collisions, and moreover you know that <code>value</code> is a number between 1 and <code>domain</code> inclusive. In that case, you're right that your transformation is an injection, since <code>prime</code> is coprime to <code>domain</code>, so your method is fine, but there are several things that can be done to simplify it:</p>\n\n<ol>\n<li><p>As far as I can see, there's no need to subtract 1 from <code>value</code>.</p></li>\n<li><p>There's no need to use the value <code>seed</code> at all. You're using this to ensure that you have at least <code>length</code> digits in <code>num</code>, but it's easier just to generate exactly <code>length</code> digits. (This gives you a bigger domain in any case.)</p></li>\n<li><p>There's no need to call <code>reversed</code>: the reverse of a pseudo-random string is also a pseudo-random string.</p></li>\n</ol>\n\n<p>Applying all those simplifications yields the following:</p>\n\n<pre><code>def genkey(value, length=5, chars=string.ascii_letters + string.digits, prime=694847539):\n \"\"\"\n Return a string of `length` characters chosen pseudo-randomly from\n `chars` using `value` as the seed and `prime` as the multiplier.\n `value` must be a number between 1 and `len(chars) ** length`\n inclusive.\n\n &gt;&gt;&gt; ' '.join(genkey(i) for i in range(1, 6))\n 'xKFbV UkbdG hVGer Evcgc 15HhX'\n \"\"\"\n base = len(chars)\n domain = base ** length\n assert(1 &lt;= value &lt;= domain)\n n = value * prime % domain\n digits = []\n for _ in xrange(length):\n n, c = divmod(n, base)\n digits.append(chars[c])\n return ''.join(digits)\n</code></pre>\n\n<p>A couple of things you might want to beware of:</p>\n\n<ol>\n<li><p>This pseudo-random scheme is not cryptographically strong: that is, it's fairly easy to go back from the URL to the value that produced it. This can be a problem in some applications.</p></li>\n<li><p>The random strings produced by this scheme may include real words or names in human languages. This could be unfortunate in some applications, if the resulting words were offensive or otherwise inappropriate.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T16:29:09.780", "Id": "35365", "Score": "0", "body": "With the system I have in place now, collisions would be a problem. I'm under the impression that the code I wrote would not produce collisions for values within the `domain` (901,356,496 for length=5 and base=62). Do you know of any ways to test this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T20:44:47.753", "Id": "35399", "Score": "0", "body": "Thanks for the great in-depth answer. How would you go about getting the initial value from the URL?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T20:49:18.643", "Id": "35401", "Score": "0", "body": "[Extended Euclidean algorithm](http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T11:25:57.170", "Id": "22957", "ParentId": "22954", "Score": "5" } } ]
{ "AcceptedAnswerId": "22957", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T05:51:44.350", "Id": "22954", "Score": "6", "Tags": [ "python" ], "Title": "Unique short string for URL" }
22954
<p>This code loads the data for <a href="http://projecteuler.net/problem=18" rel="nofollow">Project Euler problem 18</a>, but I feel that there must be a better way of writing it. Maybe with a double list comprehension, but I couldn't figure out how I might do that. It is a lot more difficult since the rows to split up are not uniform in length.</p> <pre><code>def organizeVar(): triangle = "\ 75,\ 95 64,\ 17 47 82,\ 18 35 87 10,\ 20 04 82 47 65,\ 19 01 23 75 03 34,\ 88 02 77 73 07 63 67,\ 99 65 04 28 06 16 70 92,\ 41 41 26 56 83 40 80 70 33,\ 41 48 72 33 47 32 37 16 94 29,\ 53 71 44 65 25 43 91 52 97 51 14,\ 70 11 33 28 77 73 17 78 39 68 17 57,\ 91 71 52 38 17 14 91 43 58 50 27 29 48,\ 63 66 04 68 89 53 67 30 73 16 69 87 40 31,\ 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23" triangle = [row for row in list(triangle.split(","))] adjTriangle = [] for row in range(len(triangle)): adjTriangle.append([int(pos) for pos in triangle[row].split(" ")]) return adjTriangle </code></pre> <p>The code converts this string into a list of lists of <code>int</code>s where the first list contains 75, the second list 95, 64, the third list 17, 47, 82, the fourth list 18, 35, 87, 10 and so on to the bottom row.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T13:28:28.237", "Id": "35340", "Score": "0", "body": "Also there's no need to `list()` the `trianle.split(\",\")`, `split` will *always* return a list." } ]
[ { "body": "<ol>\n<li><p>Avoid the need to escape the newlines by using Python's <a href=\"http://docs.python.org/2/reference/lexical_analysis.html#string-literals\" rel=\"nofollow\">triple-quoted strings</a> that can extend over multiple lines:</p>\n\n<pre><code>triangle = \"\"\"\n75\n95 64\n17 47 82\n18 35 87 10\n20 04 82 47 65\n19 01 23 75 03 34\n88 02 77 73 07 63 67\n99 65 04 28 06 16 70 92\n41 41 26 56 83 40 80 70 33\n41 48 72 33 47 32 37 16 94 29\n53 71 44 65 25 43 91 52 97 51 14\n70 11 33 28 77 73 17 78 39 68 17 57\n91 71 52 38 17 14 91 43 58 50 27 29 48\n63 66 04 68 89 53 67 30 73 16 69 87 40 31\n04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\n\"\"\"\n</code></pre></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.strip\" rel=\"nofollow\"><code>strip</code> method</a> to remove the whitespace at the beginning and end.</p></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.splitlines\" rel=\"nofollow\"><code>splitlines</code> method</a> to split the string into lines.</p></li>\n<li><p>Use the <a href=\"http://docs.python.org/2/library/stdtypes.html#str.split\" rel=\"nofollow\"><code>split</code> method</a> to split each line into words.</p></li>\n<li><p>Use the built-in <a href=\"http://docs.python.org/2/library/functions.html#map\" rel=\"nofollow\"><code>map</code> function</a> to call <code>int</code> on each word.</p></li>\n</ol>\n\n<p>Putting that all together in a list comprehension:</p>\n\n<pre><code>&gt;&gt;&gt; [map(int, line.split()) for line in triangle.strip().splitlines()]\n[[75],\n [95, 64],\n [17, 47, 82],\n [18, 35, 87, 10],\n [20, 4, 82, 47, 65],\n [19, 1, 23, 75, 3, 34],\n [88, 2, 77, 73, 7, 63, 67],\n [99, 65, 4, 28, 6, 16, 70, 92],\n [41, 41, 26, 56, 83, 40, 80, 70, 33],\n [41, 48, 72, 33, 47, 32, 37, 16, 94, 29],\n [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],\n [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],\n [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],\n [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],\n [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]\n</code></pre>\n\n<p>In Python 3 <code>map</code> doesn't return a list, so you have to write</p>\n\n<pre><code>[list(map(int, line.split())) for line in triangle.strip().splitlines()]\n</code></pre>\n\n<p>instead. If you prefer a double list comprehension you can write it like this:</p>\n\n<pre><code>[[int(word) for word in line.split()] for line in triangle.strip().splitlines()]\n</code></pre>\n\n<p>but the version with <code>map</code> is shorter, and, I think, clearer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T12:51:38.207", "Id": "35337", "Score": "0", "body": "Wow, that is awesome. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:46:43.270", "Id": "35409", "Score": "0", "body": "Using Python 3.3 I haven't quite gotten this to work. The closest I get while trying to use the map form is:`[line.strip().split(' ') for line in triangle.strip().splitlines()]`. This returns everything correctly except ints. When I try to use map, as in `map(int, line.strip().split(' ')` or even just `map(int, line.split())` I get a bunch of these: `<map object at 0x0000000002F469E8>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:52:31.480", "Id": "35410", "Score": "0", "body": "See revised answer. (Also, it's usually better to write `.split()` instead of `.split(\" \")` unless you really want `'a  b'` to split into `['a', '', 'b']`.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:03:15.463", "Id": "35412", "Score": "0", "body": "I think also, if you try to put this into a function, you have to strip it twice; once for the two outside lines, and once for the indentation. If you don't, map will try to turn the extra space into ints, but will give an error when that happens... I didn't read your above comment in time. Alternatively I could just do that .split() to make it work. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:07:03.840", "Id": "35414", "Score": "0", "body": "No, that's not necessary: `' a b '.split()` → `['a', 'b']`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T12:48:47.570", "Id": "22960", "ParentId": "22959", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T12:25:39.773", "Id": "22959", "Score": "2", "Tags": [ "python", "programming-challenge" ], "Title": "Organizing a long string into a list of lists" }
22959
<p>I have a grid as </p> <pre><code>&gt;&gt;&gt; data = np.zeros((3, 5)) &gt;&gt;&gt; data array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]] </code></pre> <p>i wrote a function in order to get the ID of each tile.</p> <pre><code>array([[(0,0), (0,1), (0,2), (0,3), (0,4)], [(1,0), (1,1), (1,2), (1,3), (1,4)], [(2,0), (2,1), (2,2), (2,3), (2,4)]] def get_IDgrid(nx,ny): lstx = list() lsty = list() lstgrid = list() for p in xrange(ny): lstx.append([p]*nx) for p in xrange(ny): lsty.append(range(0,nx)) for p in xrange(ny): lstgrid.extend(zip(lstx[p],lsty[p])) return lstgrid </code></pre> <p>where nx is the number of columns and ny the number of rows</p> <pre><code>test = get_IDgrid(5,3) print test [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)] </code></pre> <p>this function will be embed inside a class</p> <pre><code>class Grid(object): __slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell") def __init__(self,xMin,yMax,nx,ny,xDist,yDist): self.xMin = xMin self.yMax = yMax self.nx = nx self.ny = ny self.xDist = xDist self.yDist= yDist self.ncell = nx*ny </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:28:44.323", "Id": "35382", "Score": "2", "body": "Good question. The only thing I'd suggest is actually having `get_IDgrid` in the class rather than saying that it will be embedded." } ]
[ { "body": "<p>Numpy has built in functions for most simple tasks like this one. In your case, <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html\" rel=\"nofollow\"><code>numpy.ndindex</code></a> should do the trick:</p>\n\n<pre><code>&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; [j for j in np.ndindex(3, 5)]\n[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]\n</code></pre>\n\n<p>You can get the same result in a similarly compact way using <a href=\"http://docs.python.org/2/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a> :</p>\n\n<pre><code>&gt;&gt;&gt; import itertools\n&gt;&gt;&gt; [j for j in itertools.product(xrange(3), xrange(5))]\n[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]\n</code></pre>\n\n<p><strong>EDIT</strong> Note that the (now corrected) order of the parameters is reversed with respect to the OP's <code>get_IDgrid</code>.</p>\n\n<p>Both expressions above require a list comprehension, because what gets returned is a generator. You may want to consider whether you really need the whole list of index pairs, or if you could consume them one by one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:28:55.673", "Id": "35374", "Score": "0", "body": "Thanks @jaime. Do you think insert the def of [j for j in np.ndindex(5, 3)] in the class can be correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:33:07.450", "Id": "35376", "Score": "0", "body": "@Gianni It is kind of hard to tell without knowing what exactly you are trying to accomplish. I can't think of any situation in which I would want to store a list of all possible indices to a numpy array, but if you really do need it, then I guess it is OK." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:34:34.857", "Id": "35379", "Score": "0", "body": "@jamie with [j for j in np.ndindex(5, 3)] return a different result respect my function and the Grid (see the example). Just invert the example :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:47:24.460", "Id": "35381", "Score": "1", "body": "@Gianni I did notice that, it is now corrected. What `np.ndindex` does is what is known as [row major order](http://en.wikipedia.org/wiki/Row-major_order) arrays, which is the standard in C language, and the default in numpy. What your function is doing is column major order, which is the Fortran and Matlab way. If you are using numpy, it will probably make your life easier if you stick to row major." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:27:13.847", "Id": "22973", "ParentId": "22968", "Score": "4" } } ]
{ "AcceptedAnswerId": "22973", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T16:33:57.390", "Id": "22968", "Score": "1", "Tags": [ "python", "optimization", "performance" ], "Title": "python Improve a function in a elegant way" }
22968
<p>I wrote function to generate nearly sorted numbers:</p> <pre><code>def nearly_sorted_numbers(n): if n &gt;= 100: x = (int)(n/10) elif n &gt;= 10: x = 9 else: x = 4 numbers = [] for i in range(1,n): if i%x==0: numbers.append(random.randint(0,n)) else: numbers.append(i) return numbers </code></pre> <p>Have you any idea how improve my code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T19:58:55.010", "Id": "35394", "Score": "0", "body": "What's the purpose of this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T20:26:58.053", "Id": "35398", "Score": "0", "body": "I want to make performance test for sorting algorithms and this function should prepare input data according to x parameter (length of input data)." } ]
[ { "body": "<pre><code>def nearly_sorted_numbers(n):\n if n &gt;= 100:\n x = (int)(n/10)\n</code></pre>\n\n<p>Use <code>int(n//10)</code>, the <code>//</code> explicitly request integer division and python doesn't have casts</p>\n\n<pre><code> elif n &gt;= 10:\n x = 9\n else:\n x = 4 \n</code></pre>\n\n<p>I wouldn't name the variable <code>x</code>, as it gives no hint as to what it means. I'd also wonder whether it wouldn't be better as a parameter to this function. It seems out of place to be deciding that here.</p>\n\n<pre><code> numbers = [] \n for i in range(1,n):\n if i%x==0: \n numbers.append(random.randint(0,n))\n else:\n numbers.append(i)\nreturn numbers\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T21:20:33.740", "Id": "22982", "ParentId": "22974", "Score": "1" } } ]
{ "AcceptedAnswerId": "22982", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:33:46.550", "Id": "22974", "Score": "2", "Tags": [ "python" ], "Title": "Function to generate nearly sorted numbers" }
22974
<p>first of all sorry for this easy question. I have a class</p> <pre><code>class Grid(object): __slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell","IDtiles") def __init__(self,xMin,yMax,nx,ny,xDist,yDist): self.xMin = xMin self.yMax = yMax self.nx = nx self.ny = ny self.xDist = xDist self.yDist= yDist self.ncell = nx*ny self.IDtiles = [j for j in np.ndindex(ny, nx)] if not isinstance(nx, int) or not isinstance(ny, int): raise TypeError("an integer is required for nx and ny") </code></pre> <p>where</p> <pre><code>xMin = minimum x coordinate (left border) yMax = maximum y coordinate (top border) nx = number of columns ny = number of rows xDist and yDist = resolution (e.g., 1 by 1) </code></pre> <p>nx and ny need to be an integer. I wish to ask where is the most elegant position for the TypeError. Before all self. or in the end?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:40:58.530", "Id": "35384", "Score": "0", "body": "Ideally, you should write your whole Grid class and then show it to us. Then we'd suggest all the ways in which it could be improved rather then asking lots of specific questions." } ]
[ { "body": "<pre><code>class Grid(object):\n __slots__= (\"xMin\",\"yMax\",\"nx\",\"ny\",\"xDist\",\"yDist\",\"ncell\",\"IDtiles\")\n def __init__(self,xMin,yMax,nx,ny,xDist,yDist):\n</code></pre>\n\n<p>Python convention says that argument should be lowercase_with_underscores</p>\n\n<pre><code> self.xMin = xMin\n self.yMax = yMax\n</code></pre>\n\n<p>The same convention holds for your object attributes</p>\n\n<pre><code> self.nx = nx\n self.ny = ny\n self.xDist = xDist\n self.yDist= yDist\n self.ncell = nx*ny\n self.IDtiles = [j for j in np.ndindex(ny, nx)]\n</code></pre>\n\n<p>This is the same as <code>self.IDtiles = list(np.ndindex(ny,nx))</code></p>\n\n<pre><code> if not isinstance(nx, int) or not isinstance(ny, int):\n raise TypeError(\"an integer is required for nx and ny\")\n</code></pre>\n\n<p>This would be more conventialy put at the top. But in python we prefer duck typing, and don't check types. You shouldn't really be checking the types are correct. Just trust that the user of the class will pass the right type or something close enough.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:45:17.073", "Id": "35385", "Score": "0", "body": "Thanks @Winston Ewert. I didn't get about \"duck typing\". Do you suggest to avoid the \"TypeError\"? and the argument should be lowercase_with_underscores do you intend example self.__xMin = xMin?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:49:02.503", "Id": "35386", "Score": "1", "body": "@Gianni, xMin should be x_min. There should be no capital letters in your names. Basically, only class names are named using capital letters. Re: duck typing. Just don't throw the TypeError. The python convention is to not check the types and just allow exceptions to be thrown when the type is used in an invalid manner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:58:11.073", "Id": "35387", "Score": "0", "body": "Thank Winston really useful post for me. I have just the last question to clarify my doubts. inside a class if i have a function def get_distance_to_origin(xPoint,yPoint):\n#do some stuff (es euclidean distance). Do i need to write x_point and y_point in order to respect the style?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T19:00:47.677", "Id": "35388", "Score": "0", "body": "@Gianni, yes, that is correct" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:40:14.643", "Id": "22978", "ParentId": "22977", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T18:17:04.027", "Id": "22977", "Score": "1", "Tags": [ "python", "optimization" ], "Title": "Python right position for a Error message in a class" }
22977
<p>I'm starting to learn Python and am trying to optimize this bisection search game.</p> <pre><code>high = 100 low = 0 guess = (high + low)/2 print('Please think of a number between 0 and 100!') guessing = True while guessing: print('Is your secret number ' + str(guess) + '?') pointer = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.") if pointer == 'h': high = guess guess = (low + guess)/2 elif pointer == 'l': low = guess guess = (high + guess)/2 elif pointer == 'c': guessing = False else: print('Sorry, I did not understand your input.') print('Game over. Your secret number was: ' + str(guess)) </code></pre>
[]
[ { "body": "<p>Some things I think would improve your code, which is quite correct:</p>\n\n<ul>\n<li>Having variables for <code>high</code> and <code>low</code>, you shouldn't hard code their values in the opening <code>print</code>.</li>\n<li>You should use <code>//</code> to make sure you are getting integer division.</li>\n<li>You can write <code>guess = (low + high) // 2</code> only once, if you place it as the first line inside the <code>while</code> loop.</li>\n<li>When checking for <code>pointer</code>, you may want to first convert it to lower case, to make sure both <code>h</code> and <code>H</code> are understood.</li>\n<li>Make your code conform to <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> on things like maximum line length.</li>\n<li>Using the <code>format</code> method of <code>str</code> can make more clear what you are printing.</li>\n</ul>\n\n<p>Putting it all together:</p>\n\n<pre><code>high, low = 100, 0\n\nprint('Please think of a number between {0} and {1}!'.format(low, high))\n\nguessing = True\nwhile guessing:\n guess = (low + high) // 2\n print('Is your secret number {0}?'.format(guess))\n pointer = raw_input(\"Enter 'h' to indicate the guess is too high. \"\n \"Enter 'l' to indicate the guess is too low. \"\n \"Enter 'c' to indicate I guessed correctly.\").lower()\n if pointer == 'h' :\n high = guess\n elif pointer == 'l' :\n low = guess\n elif pointer == 'c':\n guessing = False\n else:\n print('Sorry, I did not understand your input.')\n\nprint('Game over. Your secret number was {0}.'.format(guess))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T00:44:11.667", "Id": "22992", "ParentId": "22984", "Score": "8" } }, { "body": "<p>Completing the reply given by Jamie, with a remark:</p>\n\n<p>When you type <code>'c'</code> , even if the number is not the one you think of, always prints this part of code <code>print('Game over. Your secret number was {0}.'</code></p>\n\n<p>So, to avoid that, you must test also <code>(str(numbers) == str(guess))</code> on the branch of <code>(response == 'c')</code>:</p>\n\n<pre><code>high, low = 100, 0\nguess = (low + high) // 2\n\nnumbers = raw_input('Please think of a number between {0} and {1}!'.format(low, high))\n\nguessing = True\nwhile guessing:\n\n print('Is your secret number {0}?'.format(guess))\n response = raw_input(\"Enter 'h' to indicate the guess is too high. \"\n \"Enter 'l' to indicate the guess is too low. \"\n \"Enter 'c' to indicate I guessed correctly.\").lower()\n if response == 'h' :\n high = guess\n elif response == 'l' :\n low = guess\n elif (response == 'c') and (str(numbers) == str(guess)) : \n print('Game over. Your secret number was {0}.'.format(guess))\n break\n else:\n print('Sorry, I did not understand your input.')\n guess = (low + high) // 2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-16T05:04:20.793", "Id": "315843", "Score": "0", "body": "The point of this guessing game is that the user never inputs the actual number since that is a _secret_." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-07T10:31:15.713", "Id": "104018", "ParentId": "22984", "Score": "1" } } ]
{ "AcceptedAnswerId": "22992", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:01:04.830", "Id": "22984", "Score": "6", "Tags": [ "python", "beginner", "number-guessing-game" ], "Title": "Bisection search game" }
22984
<p>I'm trying to become more proficient in Python and have decided to run through the Project Euler problems. </p> <p>In any case, the problem that I'm on (<a href="http://projecteuler.net/problem=17" rel="nofollow">17</a>) wants me to count all the letters in the English words for each natural number up to 1,000. In other words, one + two would have 6 letters, and so on continuing that for all numbers to 1,000.</p> <p>I wrote this code, which produces the correct answer (21,124). However, I'm wondering if there's a more pythonic way to do this.</p> <p>I have a function (<code>num2eng</code>) which translates the given integer into English words but does not include the word "and". </p> <pre><code>for i in range (1, COUNTTO + 1): container = num2eng(i) container = container.replace(' ', '') print container if i &gt; 100: if not i % 100 == 0: length = length + container.__len__() + 3 # account for 'and' in numbers over 100 else: length = length + container.__len__() else: length = length + container.__len__() print length </code></pre> <p>There is some repetition in my code and some nesting, both of which seem un-pythonic.</p> <p>I'm specifically looking for ways to make the script shorter and with simpler loops; I think that's my biggest weakness in general.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:36:38.837", "Id": "35424", "Score": "0", "body": "Your question isn't very specific; it's pretty open ended. We like specific programming questions here with a clear answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:39:51.883", "Id": "35425", "Score": "5", "body": "Don’t call magic methods directly, just use `len(container)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:07:05.217", "Id": "35426", "Score": "0", "body": "I know it doesn't relate to the programming question, but integers should never be written out or spoken with \"and.\" \"And\" is used only for fractions. 1234 is \"one thousand twenty-four\" with no \"and\", but 23.5 is twenty-three and one half." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T00:56:28.790", "Id": "35432", "Score": "0", "body": "@askewchan: that's far from a universal standard, and I definitely don't think it rises to the level of \"should never be\". Even Americans, I believe, tend to include the \"and\" when writing on cheques. Unfortunately continued discussion would be off-topic, but for my part, let a thousand (and one) flowers bloom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T05:23:31.840", "Id": "35446", "Score": "0", "body": "@Hiroto Edited to make more specific, thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T08:31:18.670", "Id": "35452", "Score": "0", "body": "If you _have_ to ask, then yes it _can_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T18:21:01.390", "Id": "35515", "Score": "0", "body": "I think my question should have been \"how can\", since I believe virtually any code \"can\" be improved. Changed to reflect that, thanks!" } ]
[ { "body": "<p>The more pythonic version:</p>\n\n<pre><code>for i in range(1, COUNTTO + 1):\n container = num2eng(i).replace(' ', '')\n length += len(container)\n if i % 100:\n length += 3 # account for 'and' in numbers over 100\n\nprint length\n</code></pre>\n\n<p>code golf:</p>\n\n<pre><code>print sum(len(num2eng(i).replace(' ', '')) + bool(i &gt; 100 and i % 100) * 3\n for i in range(1, COUNTTO + 1))\n</code></pre>\n\n<p>:)</p>\n\n<p>Don't do that in real code, of course.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:40:25.177", "Id": "22994", "ParentId": "22993", "Score": "1" } }, { "body": "<p>You can make it a bit shorter</p>\n\n<pre><code>length += len(container) + 3 if (i &gt; 100 and i % 100) else 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:46:18.427", "Id": "35427", "Score": "0", "body": "`i % 100` can't be `0` for `1 <= i <= 100`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:47:22.703", "Id": "35428", "Score": "0", "body": "but for 1 <= i <= 100 there's no 'and' in the word" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:49:52.820", "Id": "35429", "Score": "0", "body": "Ah yes. Excuse me." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:42:15.373", "Id": "22995", "ParentId": "22993", "Score": "0" } }, { "body": "<p>Here are a few things:</p>\n\n<ul>\n<li><code>container.__len__()</code> – You should never call magic methods directly. Just use <code>len(container)</code>.</li>\n<li><p>As you don’t know to what amount you need to increment (i.e. your <code>COUNTTO</code>), it would make more sense to have a while loop that keeps iterating until you reach your final length result:</p>\n\n<pre><code>while length &lt; 1000:\n # do stuff with i\n length += # update length\n i += 1\n</code></pre></li>\n<li><p>You could also make use of <a href=\"http://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"nofollow\"><code>itertools.count</code></a>:</p>\n\n<pre><code>length = 0\nfor i in itertools.count(1):\n length += # update length\n if length &gt; 1000:\n break\n</code></pre></li>\n<li><code>not i % 100 == 0</code> – When you already have a operator (<code>==</code>) then don’t use <code>not</code> to invert the whole condition, but just use the inverted operator: <code>i % 100 != 0</code></li>\n<li><p>Also having additional counting logic outside of your <code>num2eng</code> does not seem to be appropriate. What does that function do exactly? Shouldn’t it rather produce a real number using a complete logic? Ideally, it should be as simple as this:</p>\n\n<pre><code>length = 0\nfor i in itertools.count(1):\n length += len(num2eng(i))\n if length &gt; 1000:\n break\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:10:16.997", "Id": "35430", "Score": "0", "body": "I think the reason to have some logic outside of `num2eng` is to avoid counting the letters in `'hundred'` and `'thousand'` so many times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:13:58.527", "Id": "35431", "Score": "0", "body": "@askewchan Huh? That doesn’t make much sense to me, as you still do that. Also I’d expect a function `num2eng` to return a complete written English representation of the number I pass in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T05:19:16.370", "Id": "35445", "Score": "0", "body": "You're correct. The function num2eng returns the English representation of the numbers provided. For instance, 102 becomes one hundred two. It's doesn't include \"and\" though and the scope of the challenge required \"and\" to be included (e.g., one hundred and two), hence the addition. But it would makes sense to modify num2eng instead of making up for it here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T05:25:41.577", "Id": "35448", "Score": "0", "body": "Thank you so much for this feedback, this is exactly what I was looking for!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:44:02.690", "Id": "22996", "ParentId": "22993", "Score": "2" } } ]
{ "AcceptedAnswerId": "22996", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T22:34:46.893", "Id": "22993", "Score": "1", "Tags": [ "python", "programming-challenge" ], "Title": "Number letter counts" }
22993
<p>I have a function that needs to return the call to another function that have some parameters. Let's say, for example, the following:</p> <pre><code>def some_func(): iss = do_something() example = do_something_else() return some_long_name('maybe long string', {'this': iss, 'an': example, 'dictionary': 'wich is very long'}) </code></pre> <p>I want to adjust it so it will comply with PEP 8. I tried:</p> <pre><code>def some_func(): iss = do_something() example = do_something_else() return some_long_name('maybe long string', {'this': iss, 'an': example, 'dictionary': 'wich is very long'}) </code></pre> <p>But it still goes way beyond 80 characters. So I did a two step 'line continuation', but don't know if it's how it's done.</p> <pre><code>def some_func(): iss = do_something() example = do_something_else() return some_long_name('maybe long string', { 'this': iss, 'an': example, 'dictionary': 'wich is very long' }) </code></pre> <p>Or should it be something like:</p> <pre><code>def some_func(): iss = do_something() example = do_something_else() return some_long_name('maybe long string', {'this': iss, 'an': example, 'dictionary': 'wich is very long'}) </code></pre> <p>I would appreciate some insight so I can maintain a better code because PEP8 doesn't explain it very well.</p>
[]
[ { "body": "<p>PEP-0008 suggests this approach (see the first example group there):</p>\n\n<pre><code>return some_long_name(\n 'maybe long string',\n {'this': iss,\n 'an': example,\n 'dictionary': 'wich is very long'})\n</code></pre>\n\n<p>As for the dict formatting style, in my opinion, not having lines with only braces on them is more readable, navigatable and editable. The PEP does not mention any specific style for dict formatting.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T08:29:15.013", "Id": "23007", "ParentId": "23006", "Score": "1" } }, { "body": "<p>In my opinion, use Explaining Variables or Summary Variables express the dict. I like this coding style as follows.</p>\n\n<pre><code>keyword = {\n 'this': iss,\n 'an': example,\n 'dictionary': 'wich is very long',\n}\nreturn some_long_name('maybe long string', keyword)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T12:52:08.637", "Id": "23014", "ParentId": "23006", "Score": "2" } } ]
{ "AcceptedAnswerId": "23014", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T07:05:59.650", "Id": "23006", "Score": "1", "Tags": [ "python" ], "Title": "Python Line continuation dictionary" }
23006
<p>This function takes in a number and returns all divisors for that number. <code>list_to_number()</code> is a function used to retrieve a list of prime numbers up to a limit, but I am not concerned over the code of that function right now, only this divisor code. I am planning on reusing it when solving various Project Euler problems.</p> <pre><code>def list_divisors(num): ''' Creates a list of all divisors of num ''' orig_num = num prime_list = list_to_number(int(num / 2) + 1) divisors = [1, num] for i in prime_list: num = orig_num while not num % i: divisors.append(i) num = int(num / i) for i in range(len(divisors) - 2): for j in range(i + 1, len(divisors) - 1): if i and j and j != num and not orig_num % (i * j): divisors.append(i * j) divisors = list(set(divisors)) divisors.sort() return divisors </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T09:38:25.387", "Id": "35455", "Score": "0", "body": "I've changed the bottom for loop to be `for i in range(1, len(divisors) - 2):\n for j in range(i + 1, len(divisors) - 1):\n if not orig_num % (i * j):\n divisors.append(i * j)` but it doesn't read well here." } ]
[ { "body": "<ul>\n<li>Don't reset <code>num</code> to <code>orig_num</code> (to fasten division/modulo) </li>\n<li>Think functionnaly :\n<ul>\n<li>From your prime factors, if you generate a <em>new</em> collection with all possible combinations, no need to check your products.</li>\n<li>It makes harder to introduce bugs. Your code is indeed broken and won't output 20 or 25 (...) as divisors of 100.</li>\n<li>You can re-use existing (iter)tools.</li>\n</ul></li>\n<li>Avoid unnecessary convertions (<code>sorted</code> can take any iterable)</li>\n<li>Compute primes as you need them (eg, for 10**6, only 2 and 5 will suffice). Ie, use a generator.</li>\n</ul>\n\n<p>This leads to :</p>\n\n<pre><code>from prime_sieve import gen_primes\nfrom itertools import combinations, chain\nimport operator\n\ndef prod(l):\n return reduce(operator.mul, l, 1)\n\ndef powerset(lst):\n \"powerset([1,2,3]) --&gt; () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n return chain.from_iterable(combinations(lst, r) for r in range(len(lst)+1))\n\ndef list_divisors(num):\n ''' Creates a list of all divisors of num\n '''\n primes = gen_primes()\n prime_divisors = []\n while num&gt;1:\n p = primes.next()\n while not num % p:\n prime_divisors.append(p)\n num = int(num / p)\n\n return sorted(set(prod(fs) for fs in powerset(prime_divisors)))\n</code></pre>\n\n<p>Now, the \"factor &amp; multiplicity\" approach like in suggested link is really more efficient.\nHere is my take on it :</p>\n\n<pre><code>from prime_sieve import gen_primes\nfrom itertools import product\nfrom collections import Counter\nimport operator\n\ndef prime_factors(num):\n \"\"\"Get prime divisors with multiplicity\"\"\"\n\n pf = Counter()\n primes = gen_primes()\n while num&gt;1:\n p = primes.next()\n m = 0\n while m == 0 :\n d,m = divmod(num,p)\n if m == 0 :\n pf[p] += 1\n num = d\n return pf\n\ndef prod(l):\n return reduce(operator.mul, l, 1)\n\ndef powered(factors, powers):\n return prod(f**p for (f,p) in zip(factors, powers))\n\n\ndef divisors(num) :\n\n pf = prime_factors(num)\n primes = pf.keys()\n #For each prime, possible exponents\n exponents = [range(i+1) for i in pf.values()]\n return sorted([powered(primes,es) for es in product(*exponents)])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T13:06:57.343", "Id": "23015", "ParentId": "23008", "Score": "3" } } ]
{ "AcceptedAnswerId": "23015", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T08:55:46.097", "Id": "23008", "Score": "4", "Tags": [ "python", "primes" ], "Title": "Returning a list of divisors for a number" }
23008
<p>I'm reading the awesome Head First Design Patterns book. As an exercise I converted first example (or rather a subset of it) to Python. The code I got is rather too simple, i.e. there is no abstract nor interface declarations, it's all just 'classes'. Is that the right way to do it in Python? My code is below, original Java code and problem statement can be found at <a href="http://books.google.com/books?id=LjJcCnNf92kC&amp;pg=PA18">http://books.google.com/books?id=LjJcCnNf92kC&amp;pg=PA18</a></p> <pre><code>class QuackBehavior(): def __init__(self): pass def quack(self): pass class Quack(QuackBehavior): def quack(self): print "Quack!" class QuackNot(QuackBehavior): def quack(self): print "..." class Squeack(QuackBehavior): def quack(self): print "Squeack!" class FlyBehavior(): def fly(self): pass class Fly(): def fly(self): print "I'm flying!" class FlyNot(): def fly(self): print "Can't fly..." class Duck(): def display(self): print this.name def performQuack(self): self.quackBehavior.quack() def performFly(self): self.flyBehavior.fly() class MallardDuck(Duck): def __init__(self): self.quackBehavior = Quack() self.flyBehavior = Fly() if __name__ == "__main__": mallard = MallardDuck() mallard.performQuack() mallard.performFly() mallard.flyBehavior = FlyNot() mallard.performFly() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-24T20:04:40.450", "Id": "35602", "Score": "0", "body": "This looked [very familiar](http://codereview.stackexchange.com/questions/20718/the-strategy-design-pattern-for-python-in-a-more-pythonic-way/20719#20719) - you might want to take a look at my answer to that question." } ]
[ { "body": "<pre><code>class QuackBehavior():\n</code></pre>\n\n<p>Don't put <code>()</code> after classes, either skip it, or put <code>object</code> in there</p>\n\n<pre><code> def __init__(self):\n pass\n</code></pre>\n\n<p>There's no reason to define a constructor if you aren't going to do anything, so just skip it</p>\n\n<pre><code> def quack(self):\n pass\n</code></pre>\n\n<p>You should probably at least <code>raise NotImplementedError()</code>, so that if anyone tries to call this it'll complain. That'll also make it clear what this class is doing.</p>\n\n<p>You don't really need this class at all. The only reason to provide classes like this in python is documentation purposes. Whether or not you think that's useful enough is up to you.</p>\n\n<pre><code>class Quack(QuackBehavior):\n def quack(self):\n print \"Quack!\"\n\nclass QuackNot(QuackBehavior):\n def quack(self):\n print \"...\"\n\nclass Squeack(QuackBehavior):\n def quack(self):\n print \"Squeack!\"\n\nclass FlyBehavior():\n def fly(self):\n pass\n\nclass Fly():\n</code></pre>\n\n<p>If you are going to defined FlyBehavior, you should really inherit from it. It just makes it a litle more clear what you are doing.</p>\n\n<pre><code> def fly(self):\n print \"I'm flying!\"\n\nclass FlyNot():\n def fly(self):\n print \"Can't fly...\"\n\nclass Duck():\n</code></pre>\n\n<p>I'd define a constructor taking the quack and fly behavior here.</p>\n\n<pre><code> def display(self):\n print this.name\n\n def performQuack(self):\n self.quackBehavior.quack()\n\n def performFly(self):\n self.flyBehavior.fly()\n\nclass MallardDuck(Duck):\n def __init__(self):\n self.quackBehavior = Quack()\n self.flyBehavior = Fly()\n</code></pre>\n\n<p>There's not really a reason for this to be a class. I'd make a function that sets up the Duck and returns it. </p>\n\n<pre><code>if __name__ == \"__main__\":\n mallard = MallardDuck()\n mallard.performQuack()\n mallard.performFly()\n mallard.flyBehavior = FlyNot()\n mallard.performFly()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T18:35:43.547", "Id": "23038", "ParentId": "23033", "Score": "7" } }, { "body": "<p>In Python, you can pass functions as argument. This simplifies the \"Strategy\" Design pattern, as you don't need to create classes just for one method or behavior. See this <a href=\"https://stackoverflow.com/questions/963965/how-is-this-strategy-pattern-written-in-python-the-sample-in-wikipedia\">question</a> for more info.</p>\n\n<pre><code>def quack():\n print \"Quack!\"\n\ndef quack_not():\n print \"...\"\n\ndef squeack():\n print \"Squeack!\"\n\ndef fly():\n print \"I'm flying!\"\n\ndef fly_not():\n print \"Can't fly...\"\n\n\nclass Duck:\n def display(self):\n print this.name\n\n def __init__(self, quack_behavior, fly_behavior):\n self.performQuack = quack_behavior\n self.performFly = fly_behavior\n\nclass MallardDuck(Duck):\n def __init__(self):\n Duck.__init__(self, quack, fly)\n\nif __name__ == \"__main__\":\n duck = Duck(quack_not, fly_not)\n duck.performQuack()\n mallard = MallardDuck()\n mallard.performQuack()\n mallard.performFly()\n mallard.performFly = fly_not\n mallard.performFly()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>...\nQuack!\nI'm flying!\nCan't fly...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-23T15:08:54.087", "Id": "35550", "Score": "0", "body": "I picked this answer because it actually shows what @WinstonEwert's only proposed. However, this code lets you create a generic Duck, which was not possible in original Java example (that class is abstract). I assumed not having \\_\\_init__ in Duck() would make it kind-of-abstract in Python... Is that a correct assumption?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-25T23:27:35.507", "Id": "35677", "Score": "0", "body": "Yes, here's some more info on that: http://fw-geekycoder.blogspot.com/2011/02/creating-abstract-class-in-python.html\nThe reason I had the `__init__` was for my own reasons of testing the script." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T23:35:22.530", "Id": "23044", "ParentId": "23033", "Score": "5" } } ]
{ "AcceptedAnswerId": "23044", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-22T17:46:59.227", "Id": "23033", "Score": "5", "Tags": [ "python", "object-oriented", "design-patterns" ], "Title": "Strategy Design Pattern in Python" }
23033
<p>I am trying to combine two programs that analyze strings into one program. The result should look at a parent string and determine if a sub-string has an exact match or a "close" match within the parent string; if it does it returns the location of this match </p> <p>i.e. parent: abcdefefefef sub cde is exact and returns 2 sub efe is exact and returns 4, 6, 8 sub deg is close and returns 3 sub z has no match and returns None</p> <p>The first program I wrote locates exact matches of a sub-string within a parent string:</p> <pre><code>import string def subStringMatchExact(): print "This program will index the locations a given sequence" print "occurs within a larger sequence" seq = raw_input("Please input a sequence to search within: ") sub = raw_input("Please input a sequence to search for: ") n = 0 for i in range(0,len(seq)): x = string.find(seq, sub, n, len(seq)) if x == -1: break print x n = x + 1 </code></pre> <p>The second analyzes whether or not there is an close match within a parent string and returns True if there is, and false if there isn't. Again a close match is an exact match or one that differs by only one character.</p> <pre><code>import string def similarstrings(): print "This program will determine whether two strings differ" print "by more than one character. It will return True when they" print "are the same or differ by one character; otherwise it will" print "return False" str1 = raw_input("Enter first string:") str2 = raw_input("Enter second string:") x = 0 for i in range(len(str1)): if str1[i] == str2[i]: x = x + 1 else: x = x if x &gt;= len(str1) - 1: print True else: print False </code></pre> <p>Any suggestions on how to combine the two would be much appreciated.</p>
[]
[ { "body": "<p>Firstly, a quick review of what you've done:</p>\n\n<p><code>import string</code> is unnecessary really. You utilize <code>string.find</code>, but you can simply call the find method on your first argument, that is, <code>seq.find(sub, n, len(seq))</code>. </p>\n\n<p>In your second method, you have:</p>\n\n<pre><code>if str1[i] == str2[i]:\n x = x + 1\nelse:\n x = x\n</code></pre>\n\n<p>The <code>else</code> statement is completely redundant here, you don't need it.</p>\n\n<p>I think we can simplify the logic quite a bit here. I'm going to ignore <code>raw_input</code> and take the strings as arguments instead, but it doesn't change the logic (and is arguably better style anyway). Note that this is not fantastically optimized, it can definitely be made faster:</p>\n\n<pre><code>def similar_strings(s1, s2):\n '''Fuzzy matches s1 with s2, where fuzzy match is defined as\n either all of s2 being contained somewhere within s1, or\n a difference of only one character. Note if len(s2) == 1, then\n the character represented by s2 must be found within s1 for a match\n to occur.\n\n Returns a list with the starting indices of all matches.\n\n '''\n block_size = len(s2)\n match = []\n for j in range(0, len(s1) - block_size):\n diff = [ord(i) - ord(j) for (i, j) in zip(s1[j:+block_size],s2)]\n if diff.count(0) and diff.count(0) &gt;= (block_size - 1):\n match.append(j)\n if not match:\n return None\n return match\n</code></pre>\n\n<p>How does this work? Well, it basically creates a \"window\" of size <code>len(s2)</code> which shifts along the original string (<code>s1</code>). Within this window, we take a slice of our original string (<code>s1[j:j+block_size]</code>) which is of length <code>len(s2)</code>. <code>zip</code> creates a list of tuples, so, for example, <code>zip(['a','b','c'], ['x','y','z'])</code> will give us back <code>[(a, x), (b, y), (c, z)</code>].</p>\n\n<p>Then, we make a difference of all the characters from our <code>s2</code> sized block of <code>s1</code> and our actual <code>s2</code> - <code>ord</code> gives us the (integer) value of a character. So the rather tricky line <code>diff = [ord(i) - ord(j) for (i, j) in zip(s1[j:+block_size],s2)]</code> will give us a list of size <code>len(s2)</code> which has all the differences between characters. As an example, with <code>s1</code> being <code>abcdefefefef</code> and <code>s2</code> being <code>cde</code>, our first run through will give us the slice <code>abc</code> to compare with <code>cde</code> - which gives us <code>[-2, -2, -2]</code> since all characters are a distance of 2 apart.</p>\n\n<p>So, given <code>diff</code>, we want to see how many 0's it has, as two characters will be the same when their <code>ord</code> difference is 0. However, we need to make sure there is at least 1 character the same in our block (if you simply pass in <code>z</code>, or any string length 1, diff will always have length 1, and <code>block_size - 1</code> will be 0. Hence <code>diff.count(0) &gt;= 0</code> will always be <code>True</code>, which is not what we want). Thus <code>diff.count(0)</code> will only be true if it is greater than 0, which protects us from this. When that's true, look at the block size, make sure it is at least <code>len(s2) - 1</code>, and if so, add that index to <code>match</code>.</p>\n\n<p>Hopefully this gives you an idea of how you'd do this, and I hope the explanation is detailed enough to make sense of some python constructs you may not have seen before.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T02:41:03.293", "Id": "23142", "ParentId": "23141", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T01:35:09.573", "Id": "23141", "Score": "2", "Tags": [ "python" ], "Title": "Python: Combing two programs that analyze strings" }
23141
<p>I like the radix function and found a really neat way to compute its inverse in Python with a lambda and <code>reduce()</code> (so I really feel like I'm learning my cool functional programming stuff):</p> <pre><code>def unradix(source,radix): # such beauty return reduce(lambda (x,y),s: (x*radix,y+s*x), source, (1,0)) </code></pre> <p>where:</p> <pre><code>&gt;&gt;&gt; unradix([1,0,1,0,1,0,1],2) (128,85) </code></pre> <p>But its dizygotic twin is unable to use the same pattern without an ugly hack:</p> <pre><code>def radix(source,radix): import math hack = 1+int(math.floor(math.log(source)/math.log(radix))) # ^^^^ ... _nearly_ , such beauty return reduce(lambda (x,y),s: (x/radix,y+[x%radix]), xrange(hack), (source,[])) </code></pre> <p>where:</p> <pre><code>&gt;&gt;&gt; radix(85,2) (0, [1, 0, 1, 0, 1, 0, 1]) </code></pre> <p>How can I remove the hack from this pattern? Or failing that, how can I rewrite this pair of functions and inverse so they use the same pattern, and only differ in "mirror-symmetries" as much as possibly?</p> <p>By mirror symmetry I mean something like the way <em>increment</em> and <em>decrement</em> are mirror images, or like the juxtaposition of <code>x*radix</code> versus <code>x/radix</code> in the same code location as above.</p>
[]
[ { "body": "<p>The reverse operation to folding is unfolding. To be honest, I'm not very\nfluent in python and I couldn't find if python has an unfolding function.\n(In Haskell we have\n<a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v%3afoldr\" rel=\"nofollow\">foldr</a>\nand its complement \n<a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v%3aunfoldr\" rel=\"nofollow\">unfoldr</a>.)</p>\n\n<p>Nevertheless, we can easily construct one:</p>\n\n<pre><code>\"\"\"\nf accepts a value and returns None or a pair.\nThe first element of the pair is the next seed,\nthe second element is the value to yield.\n\"\"\"\ndef unfold(f, r):\n while True:\n t = f(r);\n if t:\n yield t[1];\n r = t[0];\n else: \n break;\n</code></pre>\n\n<p>It iterates a given function on a seed until it returns <code>None</code>, yielding intermediate results. It's dual to <code>reduce</code>, which takes a function and an iterable and produces a value. On the other hand, <code>unfold</code> takes a value and a generating function, and produces a generator. For example, to create a list of numbers from 0 to 10 we could write:</p>\n\n<pre><code>print list(unfold(lambda n: (n+1, n) if n &lt;= 10 else None, 0));\n</code></pre>\n\n<p>(we call <code>list</code> to convert a generator into a list).</p>\n\n<p>Now we can implement <code>radix</code> quite nicely:</p>\n\n<pre><code>def radix(source, radix):\n return unfold(lambda n: divmod(n, radix) if n != 0 else None, source);\n\nprint list(radix(12, 2));\n</code></pre>\n\n<p>prints <code>[0, 0, 1, 1]</code>.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Folding (<code>reduce</code>) captures the pattern of consuming lists. Any function that sequentially consumes a list can be eventually written using <code>reduce</code>. The first argument to <code>reduce</code> represents the core computation and the third argument, the accumulator, the state of the loop. Similarly, unfolding (my <code>unfold</code>) represents the pattern of producing lists. Again, any function that sequentially produces a list can be eventually rewritten using <code>unfold</code>.</p>\n\n<p>Note that there are functions that can be expressed using either of them, as we can look at them as functions that produce or consume lists. For example, we can implement <code>map</code> (disregarding any efficiency issues) as</p>\n\n<pre><code>def map1(f, xs):\n return reduce(lambda rs, x: rs + [f(x)], xs, [])\n\ndef map2(f, xs):\n return unfold(lambda xs: (xs[1:], f(xs[0])) if xs else None, xs)\n</code></pre>\n\n<hr>\n\n<p>The duality of <code>reduce</code> and <code>unfold</code> is nicely manifested in a technique called <a href=\"https://en.wikipedia.org/wiki/Deforestation_%28computer_science%29\" rel=\"nofollow\">deforestation</a>. If you know that you create a list using <code>unfold</code> only to consume it immediately with <code>reduce</code>, you can combine these two operations into a single, higher-order function that doesn't build the intermediate list:</p>\n\n<pre><code>def deforest(foldf, init, unfoldf, seed):\n while True:\n t = unfoldf(seed);\n if t:\n init = foldf(t[1], init);\n seed = t[0];\n else:\n return init;\n</code></pre>\n\n<p>For example, if we wanted to compute the sum of digits of 127 in base 2, we could call</p>\n\n<pre><code>print deforest(lambda x,y: x + y, 0, # folding part\n lambda n: divmod(n, 2) if n != 0 else None, # unfolding\n 127); # the seed\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T21:47:34.107", "Id": "35769", "Score": "0", "body": "A beautiful and symmetric radix! A *great* explanation as well. Thanks for teach me, and \"us\", something!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T22:33:46.853", "Id": "35772", "Score": "0", "body": "(in spirit) +1 for deforest, that *soo* cool." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T22:47:30.013", "Id": "35773", "Score": "0", "body": "@PetrPudlák so I understand, we are using our function (that would have been in unfold) on init, one time, then we are using our fold function on the yield value of that 'unfold' function, and accumulating that into init. And we are 're'-unfolding with the seed value. So we interleave folding into init, and unfolding out of seed. If we were to capture the sequences of seed and init, they would reproduce the lists being produced and consumed at each step of the deforest while loop. Does that sound right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T08:01:45.600", "Id": "35795", "Score": "0", "body": "@CrisStringfellow Yes, it's just like you say." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-27T08:02:43.853", "Id": "35796", "Score": "0", "body": "@PetrPudlák good to know, thanks. Now I have learnt something else. :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T21:37:19.217", "Id": "23188", "ParentId": "23180", "Score": "4" } }, { "body": "<p>I modified the answer by Petr Pudlák slightly, changing the <strong>unfold</strong> function to yield the last seed before exhaustion as it ends. </p>\n\n<pre><code>def unfold(f, r):\n while True:\n t = f(r)\n if t:\n yield t[1]\n r = t[0]\n else: \n yield r #&lt;&lt; added\n break\n</code></pre>\n\n<p>This enables some kind of accumulated value to be kept, like in the original <strong>unradix</strong> we can keep the highest power of the base greater than the source number. </p>\n\n<p>Using the modified <strong>unfold</strong> function we can keep it here, too. To do so I modified the radix like so:</p>\n\n<pre><code>def radix(source,radix):\n return unfold(lambda (n,maxpow): ((n/radix, maxpow*radix), n%radix) if n !=0 else None, (source,1))\n</code></pre>\n\n<p>I prefer my version better, since it keeps the first seed tuple <code>(source,1)</code> which is similar to the one for <strong>unradix</strong> , <code>(1,0)</code> each containing the appropriate identity for multiplicative or additive accumulation. And it outputs the radix as well as the highest power. </p>\n\n<pre><code>&gt;&gt;&gt; list(totesweird.radix(121,3))\n[1, 1, 1, 1, 1, (0, 243)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T22:20:44.630", "Id": "23190", "ParentId": "23180", "Score": "0" } } ]
{ "AcceptedAnswerId": "23188", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-26T18:25:39.303", "Id": "23180", "Score": "3", "Tags": [ "python", "functional-programming", "lambda" ], "Title": "Removing hackery from pair of radix functions" }
23180
<p>I'm implementing a checkers engine for a scientific experiment. I found out through profiling that this is one of the functions that takes up a lot of time. I'm not looking for an in-depth analysis, because I don't expect you to dive super deep into my code.</p> <p>Just: <strong>are there any obvious inefficiencies here?</strong> Like, is it slow to do those starting for loops (<code>dx, dy</code>) just for 2 values each?</p> <pre><code>def captures(self, (py, px), piece, board, captured=[], start=None): """ Return a list of possible capture moves for given piece in a checkers game. :param (py, px): location of piece on the board :param piece: piece type (BLACK/WHITE|MAN/KING) :param board: the 2D board matrix :param captured: list of already-captured pieces (can't jump twice) :param start: from where this capture chain started. """ if start is None: start = (py, px) # Look for capture moves for dx in [-1, 1]: for dy in [-1, 1]: dist = 1 while True: jx, jy = px + dist * dx, py + dist * dy # Jumped square # Check if piece at jx, jy: if not (0 &lt;= jx &lt; 8 and 0 &lt;= jy &lt; 8): break if board[jy, jx] != EMPTY: tx, ty = px + (dist + 1) * dx, py + (dist + 1) * dy # Target square # Check if it can be captured: if ((0 &lt;= tx &lt; 8 and 0 &lt;= ty &lt; 8) and ((ty, tx) == start or board[ty, tx] == EMPTY) and (jy, jx) not in captured and ((piece &amp; WHITE) and (board[jy, jx] &amp; BLACK) or (piece &amp; BLACK) and (board[jy, jx] &amp; WHITE)) ): # Normal pieces cannot continue capturing after reaching last row if not piece &amp; KING and (piece &amp; WHITE and ty == 0 or piece &amp; BLACK and ty == 7): yield (NUMBERING[py, px], NUMBERING[ty, tx]) else: for sequence in self.captures((ty, tx), piece, board, captured + [(jy, jx)], start): yield (NUMBERING[py, px],) + sequence break else: if piece &amp; MAN: break dist += 1 yield (NUMBERING[py, px],) </code></pre>
[]
[ { "body": "<p>A couple of little things that caught my eye:</p>\n\n<p>You could simplify this</p>\n\n<pre><code>dist = 1 \nwhile True:\n jx, jy = px + dist * dx, py + dist * dy \n dist += 1\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>jx, jy = px, py\nwhile True:\n jx += dx\n jy += dy\n</code></pre>\n\n<hr>\n\n<p>You don't need this range check</p>\n\n<pre><code>if not (0 &lt;= jx &lt; 8 and 0 &lt;= jy &lt; 8):\n break\nif board[jy, jx] != EMPTY:\n</code></pre>\n\n<p>because, assuming <code>board</code> is a dict indexed by tuple, you can just catch <code>KeyError</code> when out of bounds:</p>\n\n<pre><code>try:\n if board[jy, jx] != EMPTY:\n ...\nexcept KeyError:\n break\n</code></pre>\n\n<hr>\n\n<p>Instead of</p>\n\n<pre><code>((piece &amp; WHITE) and (board[jy, jx] &amp; BLACK) or\n (piece &amp; BLACK) and (board[jy, jx] &amp; WHITE))\n</code></pre>\n\n<p>you could use <code>board[jy, jx] &amp; opponent</code> if you determine the opponent's color in the beginning of the function:</p>\n\n<pre><code>opponent = BLACK if piece &amp; WHITE else WHITE\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T17:19:11.613", "Id": "23626", "ParentId": "23323", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T16:31:35.090", "Id": "23323", "Score": "3", "Tags": [ "python", "recursion", "generator", "checkers-draughts" ], "Title": "Efficiency of Recursive Checkers Legal Move Generator" }
23323
<p>I made a Python function that takes an XML file as a parameter and returns a JSON. My goal is to convert some XML get from an old API to convert into Restful API.</p> <p>This function works, but it is really ugly. I try to clean everything, without success.</p> <p>Here are my tests:</p> <pre class="lang-python prettyprint-override"><code> def test_one_node_with_more_than_two_children(self): xml = '&lt;a id="0" name="foo"&gt;&lt;b id="00" name="moo" /&gt;&lt;b id="01" name="goo" /&gt;&lt;b id="02" name="too" /&gt;&lt;/a&gt;' expected_output = { "a": { "@id": "0", "@name": "foo", "b": [ { "@id": "00", "@name": "moo" }, { "@id": "01", "@name": "goo" }, { "@id": "02", "@name": "too" } ] } } self.assertEqual(expected_output, self.parser.convertxml2json(xml)) </code></pre> <p>And my function:</p> <pre class="lang-python prettyprint-override"><code>from xml.dom.minidom import parseString, Node class Parser(object): def get_attributes_from_node(self, node): attributes = {} for attrName, attrValue in node.attributes.items(): attributes["@" + attrName] = attrValue return attributes def convertxml2json(self, xml): parsedXml = parseString(xml) return self.recursing_xml_to_json(parsedXml) def recursing_xml_to_json(self, parsedXml): output_json = {} for node in parsedXml.childNodes: attributes = "" if node.nodeType == Node.ELEMENT_NODE: if node.hasAttributes(): attributes = self.get_attributes_from_node(node) if node.hasChildNodes(): attributes[node.firstChild.nodeName] = self.recursing_xml_to_json(node)[node.firstChild.nodeName] if node.nodeName in output_json: if type(output_json[node.nodeName]) == dict: output_json[node.nodeName] = [output_json[node.nodeName]] + [attributes] else: output_json[node.nodeName] = [x for x in output_json[node.nodeName]] + [attributes] else: output_json[node.nodeName] = attributes return output_json </code></pre> <p>Can someone give me some tips to improve this code?<br> <code>def recursing_xml_to_json(self, parsedXml)</code> is really bad.<br> I am ashamed to produce it :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T19:07:29.333", "Id": "36326", "Score": "0", "body": "Could you explain the intent, and add some comments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:33:47.853", "Id": "36596", "Score": "0", "body": "i updated my question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:22:17.250", "Id": "62799", "Score": "0", "body": "What about [XMLtoDict](https://github.com/martinblech/xmltodict) ?\nIt seems similar to what you created, no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T11:15:27.707", "Id": "62800", "Score": "0", "body": "After studying the source code of this application, I thought there was an easier way to do. It allowed me to improve myself." } ]
[ { "body": "<p>There is a structural issue with your code: the recursive function works at two levels. 1) It constructs a dict representing a node, and 2) it does some work in constructing the representation for the children. This makes it unnecessarily complicated. Instead, the function should focus on handling one node, and delegate the creation of child nodes to itself via recursion.</p>\n\n<p>You seem to have requirements such as:</p>\n\n<ol>\n<li>A node that has no children nor attributes converts to an empty string. My implementation: <code>return output_dict or \"\"</code></li>\n<li>Multiple children with same nodeName convert to a list of dicts, while a single one converts to just a dict. My implementation makes this explicit by constructing lists first, then applying this conversion: <code>v if len(v) &gt; 1 else v[0]</code></li>\n<li>A node with children but no attributes raises a TypeError. I suspect this is an oversight and did not reproduce the behavior.</li>\n</ol>\n\n<p>Note that (2) means that a consumer of your JSON that expects a variable number of nodes must handle one node as a special case. I don't think that is good design.</p>\n\n<pre><code>def get_attributes_from_node(self, node):\n attributes = {}\n if node.attributes:\n for attrName, attrValue in node.attributes.items():\n attributes[\"@\" + attrName] = attrValue\n return attributes\n\ndef recursing_xml_to_json(self, node):\n d = collections.defaultdict(list)\n for child in node.childNodes:\n if child.nodeType == Node.ELEMENT_NODE:\n d[child.nodeName].append(self.recursing_xml_to_json(child))\n\n output_dict = self.get_attributes_from_node(node)\n output_dict.update((k, v if len(v) &gt; 1 else v[0])\n for k, v in d.iteritems())\n\n return output_dict or \"\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:33:26.653", "Id": "36595", "Score": "0", "body": "This answer is really amazing" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T20:44:52.960", "Id": "23551", "ParentId": "23324", "Score": "2" } } ]
{ "AcceptedAnswerId": "23551", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T16:36:00.630", "Id": "23324", "Score": "5", "Tags": [ "python", "unit-testing", "xml", "json", "recursion" ], "Title": "Recursive XML2JSON parser" }
23324
<p>I believe this is essentially the same method as the <code>itertools.combinations</code> function, but is there any way to make this code more more perfect in terms of speed, code size and readability :</p> <pre><code>def all_subsets(source,size): index = len(source) index_sets = [()] for sz in xrange(size): next_list = [] for s in index_sets: si = s[len(s)-1] if len(s) &gt; 0 else -1 next_list += [s+(i,) for i in xrange(si+1,index)] index_sets = next_list subsets = [] for index_set in index_sets: rev = [source[i] for i in index_set] subsets.append(rev) return subsets </code></pre> <p>Yields:</p> <pre><code>&gt;&gt;&gt; Apriori.all_subsets(['c','r','i','s'],2) [['c', 'r'], ['c', 'i'], ['c', 's'], ['r', 'i'], ['r', 's'], ['i', 's']] </code></pre> <p>There is probably a way to use generators or functional concepts, hopefully someone can suggest improvements.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-02T23:53:25.477", "Id": "36021", "Score": "0", "body": "Why aren't you using itertools.combinations? It's reasonable to do this for learning purposes, but if you are actually doing a bigger project you'll want to use the itertools version." } ]
[ { "body": "<p>This type of problems lend themselves very well to <a href=\"http://en.wikipedia.org/wiki/Recursion\" rel=\"nofollow\">recursion</a>. A possible implementation, either in list or generator form could be:</p>\n\n<pre><code>def all_subsets(di, i) :\n ret = []\n for j, item in enumerate(di) :\n if i == 1 :\n ret = [(j,) for j in di]\n elif len(di) - j &gt;= i :\n for subset in all_subsets(di[j + 1:], i - 1) :\n ret.append((item,) + subset)\n return ret\n\ndef all_subsets_gen(di, i) :\n for j, item in enumerate(di) :\n if i == 1 :\n yield (j,)\n elif len(di) - j &gt;= i :\n for subset in all_subsets(di[j + 1:], i - 1) :\n yield (item,) + subset\n\n&gt;&gt;&gt; all_subsets(range(4), 3)\n[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]\n&gt;&gt;&gt; list(all_subsets_gen(range(4), 3))\n[(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]\n</code></pre>\n\n<p>If you are going to run this on large sets, you may want to <a href=\"http://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow\">memoize</a> intermediate results to speed things up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:14:46.120", "Id": "36045", "Score": "0", "body": "RE the memorization, do you mean if the function is going to be run more than once? Otherwise I don't see how memorization would help here, since isn't there only *one path* down through the recursion, with each size of subsets being created just once?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:47:23.860", "Id": "36047", "Score": "0", "body": "@CrisStringfellow In my example above, the `(0, 2, 3)` and the `(1, 2, 3)` are both calling `all_subsets([2, 3], 2)` and it gets worse for larger sets, especially with a small `i`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:50:22.550", "Id": "36049", "Score": "0", "body": "Got it. I was wrong. But couldn't that be subtly changed by making the call to 2,3 and then prepending the first element/s? Is this what you mean by memorization?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-02T23:54:14.707", "Id": "23371", "ParentId": "23363", "Score": "2" } } ]
{ "AcceptedAnswerId": "23371", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-02T19:38:14.427", "Id": "23363", "Score": "1", "Tags": [ "python", "functional-programming", "combinatorics" ], "Title": "Any way to optimize or improve this python combinations/subsets functions?" }
23363
<p>I got a ton of helpful tips last time I posted some code, so I thought I would come back to the well.</p> <p>My function is deciding whether or not the <code>secretWord</code> has been guessed in my hangman game. I am trying to accomplish this by taking a list, <code>lettersGuessed</code>, and comparing it to the char in each index of the string <code>secretWord</code>. My code works, but I feel as though it is not optimal nor formatted well.</p> <pre><code>def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' chars = len(secretWord) place = 0 while place &lt; chars: if secretWord[0] in lettersGuessed: place += 1 return isWordGuessed(secretWord[1:], lettersGuessed) else: return False return True </code></pre> <p>I tried to use a for loop (<code>for i in secretWord:</code>) originally, but I could not get my code to return both True and False. It would only do one or the other, which is how I ended up with the while loop. It seems that <code>while</code> loops are discouraged/looked at as not very useful. Is this correct?</p> <p>Also, I am wondering if the recursive call is a good way of accomplishing the task.</p>
[]
[ { "body": "<p>Because we always return from the inside of the while, we'll never perform the loop more than once. Thus, your while actually acts like an <code>if</code>. Thus the value of <code>place</code> is not really used and you can get rid of it : <code>if place &lt; chars</code> becomes <code>if 0 &lt; chars</code> which is <code>if chars</code> which is <code>if len(secretWord)</code> which is really <code>if secretWord</code> because of the way Python considers the empty string as a false value.\nThus, you code could be :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n if secretWord:\n if secretWord[0] in lettersGuessed:\n return isWordGuessed(secretWord[1:], lettersGuessed)\n else:\n return False\n return True\n</code></pre>\n\n<p>Which can be re-written as :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n if secretWord:\n return secretWord[0] in lettersGuessed and isWordGuessed(secretWord[1:], lettersGuessed)\n return True\n</code></pre>\n\n<p>which is then nothing but :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n return not secretWord or secretWord[0] in lettersGuessed and isWordGuessed(secretWord[1:], lettersGuessed)\n</code></pre>\n\n<p>Now, if I was to write the same function, because it is so easy to iterate on strings in Python, I'd probably avoid the recursion and so something like :</p>\n\n<pre><code>def isWordGuessed(secretWord, lettersGuessed):\n for letter in secretWord:\n if letter not in lettersGuessed:\n return False\n return True\n</code></pre>\n\n<p>Then, there might be a way to make this a one-liner but I find this to be pretty easy to understand and pretty efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-18T00:15:37.170", "Id": "401411", "Score": "0", "body": "If you wanted a one-liner for your final code, you could do `return all(letter in lettersGuessed for letter in secretWord)`; the Python default built-ins [`all()`](https://docs.python.org/3/library/functions.html#all) and [`any()`](https://docs.python.org/3/library/functions.html#any) are good tricks to have up your sleave for crafting concise Python code. I actually think it's equally clear too, so (IMO) it's even better than your current final version." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T06:51:44.373", "Id": "23378", "ParentId": "23375", "Score": "7" } }, { "body": "<p>You could think in sets of letters:</p>\n\n<pre><code>def is_word_guessed(secret_word, letters_guessed):\n\n return set(secret_word) &lt;= set(letters_guessed)\n</code></pre>\n\n<p>Edit: to improve the answer as codesparkle suggested:</p>\n\n<p>The main benefit is the clarity of expression - the reader of the code doesn't need to run a double loop, or a recursive function in his/her head to understand it.</p>\n\n<p>The function and parameter names were changed in order to comply with <a href=\"http://www.python.org/dev/peps/pep-0008/#id32\" rel=\"noreferrer\" title=\"PEP8\">the Style Guide for Python Code</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T21:37:14.173", "Id": "36437", "Score": "0", "body": "Interesting answer! Could you explain the benefits of using sets and maybe explain your renaming of the method to conform to python naming conventions? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T18:59:24.637", "Id": "525352", "Score": "0", "body": "@pjz I don't think `==` works either because that would only tell you if the two sets were identical (i.e., the guessed letters exactly matched the secret letters and had no additional extra letters). Personally my first thought was to use sets, but I'd probably use the built in functions, namely `issubset`. This would then be `set(secret_word).issubset(set(letters_guessed)` which would tell you if all the letters in your secret word are contained in your guessed letters. The built in functions should be more clear than `<=` about their purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-12T20:25:45.950", "Id": "525429", "Score": "1", "body": "@zephyr I completely misread the code. You're completely correct. That said, I think the `all(letter in letters_guessed for letter in secret_word)` is the most readable solution." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T21:30:01.477", "Id": "23631", "ParentId": "23375", "Score": "7" } } ]
{ "AcceptedAnswerId": "23378", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T05:01:59.713", "Id": "23375", "Score": "5", "Tags": [ "python", "hangman" ], "Title": "In my Hangman game, one of my functions is correct but messy" }
23375
<p>This is my python solution to the first problem on Project Euler:</p> <pre><code>n = 1 rn = 0 while n &lt; 1000: if n%3 == 0 or n%5 == 0: rn += n n = n + 1 print(rn) </code></pre> <p>I would like to find a way to keep everything in this python code to as little number of lines as possible (maybe even a one liner??), and possibly improve the speed (it's currently around 12 ms). By the way, this is the problem: <blockquote>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> <p>Find the sum of all the multiples of 3 or 5 below 1000.</blockquote>Suggestions?<br />Thanks.<br /></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-29T21:28:10.807", "Id": "63715", "Score": "1", "body": "`sum(n for n in range(1000) if not n%3 or not n%5)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-04T08:50:05.540", "Id": "232506", "Score": "0", "body": "I like your solution to the problem. It is much more efficiently coded than another Project Euler #1 code question I just read." } ]
[ { "body": "<p><strong>Python hint number 1:</strong></p>\n\n<p>The pythonic way to do :</p>\n\n<pre><code>n = 1\nwhile n &lt; 1000:\n # something using n\n n = n + 1\n</code></pre>\n\n<p>is :</p>\n\n<pre><code>for n in range(1,1000):\n # something using n\n</code></pre>\n\n<p><strong>Python hint number 2:</strong></p>\n\n<p>You could make your code a one-liner by using list comprehension/generators :</p>\n\n<pre><code>print sum(n for n in range(1,1000) if (n%3==0 or n%5==0))\n</code></pre>\n\n<p>Your code works fine but if instead of 1000, it was a much bigger number, the computation would take much longer. A bit of math would make this more more efficient.</p>\n\n<p><strong>Math hint number 1 :</strong></p>\n\n<p>The sum of all the multiples of 3 or 5 below 1000 is really the sum of (the sum of all the multiples of 3 below 1000) plus (the sum of all the multiples of 5 below 1000) minus the numbers you've counted twice.</p>\n\n<p><strong>Math hint number 2 :</strong></p>\n\n<p>The number you've counted twice are the multiple of 15.</p>\n\n<p><strong>Math hint number 3 :</strong></p>\n\n<p>The sum of the multiple of 3 (or 5 or 15) below 1000 is the <a href=\"http://en.wikipedia.org/wiki/Arithmetic_progression#Sum\">sum of an arithmetic progression.</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T13:02:15.763", "Id": "36037", "Score": "0", "body": "Oh, sorry, my mistake, I inputted `100` instead of `1000` @Josay" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T17:04:20.053", "Id": "36050", "Score": "2", "body": "Math hint #4: every number that is divideable by an odd number is an odd number itself (so you can skip half of the loop iterations). @Lewis" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T12:37:59.057", "Id": "23380", "ParentId": "23379", "Score": "8" } } ]
{ "AcceptedAnswerId": "23380", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T11:41:15.993", "Id": "23379", "Score": "5", "Tags": [ "python", "project-euler" ], "Title": "Project Euler Problem 1" }
23379
<p>You might have read my question on shortening my code to a one-liner for Problem 1. So, I was wondering, is there any more tricks of the trade to shorten my <a href="http://projecteuler.net/problem=2" rel="nofollow">Problem 2</a> solution:</p> <pre><code>fib = [0, 1] final = 1 ra = 0 while final &lt; 4000000: fib.append(fib[-1] + fib[-2]) final = fib[-1] fib.pop() for a in fib: if a%2 == 0: ra += a print(ra) </code></pre> <p>Down to one line??<br /> This is the official Problem 2 question:<blockquote>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</blockquote> Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T15:59:51.477", "Id": "36044", "Score": "5", "body": "Writing everything in a single line is rarely a good idea. Why not strive for the most expressive, readable version, regardless of the number of lines?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T08:52:43.310", "Id": "36084", "Score": "0", "body": "please note that the sharing projecteuler solutions outside the scope of the website is not appreciated. See http://projecteuler.net/about (after loggin in)" } ]
[ { "body": "<p>The first few are probably OK, but you really shouldn't be publishing solutions to Project Euler problems online: don't spoil the fun for others!</p>\n\n<p>This said, there are several things you could consider to improve your code. As you will find if you keep doing Project Euler problems, eventually efficiency becomes paramount. So to get the hang of it, you may want to try and write your program as if being asked for a much, much larger threshold. So some of the pointers I will give you would generally be disregarded as micro optimizations, and rightfully so, but that's the name of the game in Project Euler!</p>\n\n<p>Keeping the general structure of your program, here are a few pointers:</p>\n\n<ul>\n<li>Why start with <code>[0, 1]</code> when they tell you to go with <code>[1, 2]</code>? The performance difference is negligible, but it is also very unnecessary.</li>\n<li>You don't really need several of your intermediate variables.</li>\n<li>You don't need to <code>pop</code> the last value, just ignore it when summing.</li>\n<li>An important thing is that in the Fibonacci sequence even numbers are every third element of the sequence, so you can avoid the divisibility check.</li>\n</ul>\n\n<p>Putting it all together:</p>\n\n<pre><code>import operator\n\ndef p2bis(n) :\n fib = [1, 2]\n while fib[-1] &lt; n :\n fib.append(fib[-1] + fib[-2])\n return reduce(operator.add, fib[1:-1:3])\n</code></pre>\n\n<p>This is some 30% faster than your code, not too much, but the idea of not checking divisibility, but stepping in longer strides over a sequence, is one you want to hold to:</p>\n\n<pre><code>In [4]: %timeit p2(4000000)\n10000 loops, best of 3: 64 us per loop\n\nIn [5]: %timeit p2bis(4000000)\n10000 loops, best of 3: 48.1 us per loop\n</code></pre>\n\n<p>If you wanted to really streamline things, you could get rid of the list altogether and keep a running sum while building the sequence:</p>\n\n<pre><code>def p2tris(n) :\n a, b, c = 1, 1, 2\n ret = 2\n while c &lt; n :\n a = b + c\n b = c + a\n c = a + b\n ret += c\n return ret - c\n</code></pre>\n\n<p>This gives a 7x performance boost, not to mention the memory requirements:</p>\n\n<pre><code>In [9]: %timeit p2tris(4000000)\n100000 loops, best of 3: 9.21 us per loop\n</code></pre>\n\n<p>So now you can compute things that were totally unthinkable before:</p>\n\n<pre><code>In [19]: %timeit p2tris(4 * 10**20000)\n1 loops, best of 3: 3.49 s per loop\n</code></pre>\n\n<p>This type of optimization eventually becomes key in solving more advanced problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T20:09:36.963", "Id": "36065", "Score": "0", "body": "`p2tris` seems to be computing something slightly different than `p2bis`: it's off by 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T05:20:07.447", "Id": "36081", "Score": "0", "body": "@DSM Thanks for checking my code! It is solved now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:31:49.990", "Id": "23387", "ParentId": "23383", "Score": "2" } }, { "body": "<p>Rather than trying to cram everything into one line, I'd try to put things in small discrete units which map closely to the problem requirements.</p>\n\n<p>We need to sum (1) the terms in the Fibonacci sequence (2) whose values don't exceed 4 million (3) which are even.</p>\n\n<p>And so I'd write something like this:</p>\n\n<pre><code>from itertools import takewhile\n\ndef gen_fib():\n f0, f1 = 0, 1\n while True:\n yield f0\n f0, f1 = f1, f0+f1\n\nlimit = 4000000\nlow_fibs = takewhile(lambda x: x &lt;= limit, gen_fib())\neven_total = sum(f for f in low_fibs if f % 2 == 0)\nprint(even_total)\n</code></pre>\n\n<p>where <code>gen_fib</code> yields the Fibonacci terms in sequence, <code>low_fibs</code> is an iterable object which yields terms until (and not including) the first term which is > 4000000, and <code>even_total</code> is the sum of the even ones. You could combine the last two into one line, if you wanted, but why?</p>\n\n<p>This has the advantage of never materializing one big list, as the terms are produced and consumed as needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T19:46:16.133", "Id": "36061", "Score": "0", "body": "I was doing some timings, and with Python 2.7 `sum` appeared to be extremely slow compared to `reduce` or plain summing in a for loop. Maybe I had numpy running in the background, and there was something going on there, but I was very surprised." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T20:08:57.010", "Id": "36063", "Score": "0", "body": "@Jaime: I can't reproduce that. genexps often show performance hits relative to loops/listcomps, but I don't see a major difference. `sum(i for i in xrange(10) if i % 2 == 0)` is only ~20% slower than the equivalent for loop version, and the difference becomes negligible in longer cases." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T16:41:12.940", "Id": "23388", "ParentId": "23383", "Score": "2" } }, { "body": "<p>In one line (plus an <code>import</code>):</p>\n\n<pre><code>from math import floor, log, sqrt\n(int(round((pow((1+sqrt(5))/2,2+floor(log(4e6*sqrt(5),(1+sqrt(5))/2)))/sqrt(5))))-1)//2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T20:43:39.540", "Id": "36067", "Score": "2", "body": "Congratulations on a successful *defactoring* of the original code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T18:42:12.963", "Id": "23395", "ParentId": "23383", "Score": "0" } } ]
{ "AcceptedAnswerId": "23387", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T13:44:49.857", "Id": "23383", "Score": "2", "Tags": [ "python", "project-euler", "fibonacci-sequence" ], "Title": "Project Euler - Shortening Problem 2" }
23383
<p>I'd like to know any ways of shortening this UI window for Maya, at the moment, because I couldn't find very detailed documentation and not very skilled with python, I have just built this UI with the knowledge that I have already, I know it's not the best way of doing it (using empty text elements to fill gaps etc)</p> <p>Can someone provide me with an example on how to shorten this code or structure it properly?</p> <pre><code>import maya.cmds as cmds class randomScatter(): def __init__(self): if cmds.window("randSelection", exists=1): cmds.deleteUI("randSelection") cmds.window("randSelection", t="Scatter Objects - Shannon Hochkins", w=405, sizeable=0) cmds.rowColumnLayout(nc=3,cal=[(1,"right")], cw=[(1,100),(2,200),(3,105)]) cmds.text(l="Prefix ") cmds.textField("prefix") cmds.text(l="") cmds.text(l="Instanced object(s) ") cmds.textField("sourceObj", editable=0) cmds.button("sourceButton", l="Select") cmds.text(l="Target ") cmds.textField("targetObj", editable=0) cmds.button("targetButton", l="Select") cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.text(l='Copy Options ') cmds.radioButtonGrp('copyOptions', labelArray2=['Duplicate', 'Instance'], numberOfRadioButtons=2, sl=2) cmds.text(l="") cmds.text(l="Rotation Options ") cmds.radioButtonGrp('orientation', labelArray2=['Follow Normals', 'Keep original'], numberOfRadioButtons=2, sl=1) cmds.text(l="") cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.text(l="") cmds.checkBox('copyCheck', l='Stick copies to target mesh.') cmds.text(l="") cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.text('maxNumber', l="Copies ") cmds.intFieldGrp("totalCopies", nf=1, v1=10, cw1=100) cmds.text(l="") cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.separator( height=20, style='in') cmds.text(l='') cmds.text(l=" From To", align='left') cmds.text(l='') cmds.text(l="Random Rotation") cmds.floatFieldGrp("rotValues", nf=2, v1=0, v2=0, cw2=[100,100]) cmds.text(l="") cmds.text(l="Random Scale") cmds.floatFieldGrp("scaleValues", nf=2, v1=0, v2=0, cw2=[100,100]) cmds.text(l="") cmds.setParent("..") cmds.rowColumnLayout(w=405) cmds.separator( height=20, style='in') cmds.text("Progress", height=20) cmds.progressBar('buildGridProgBar', maxValue=100, width=250) cmds.separator( height=20, style='in') cmds.button("excute", l="Scatter Objects", w=403, al="right") cmds.showWindow("randSelection") randomScatter() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T13:59:48.320", "Id": "51163", "Score": "0", "body": "You have alot of cmds.separator lines in a group of 3. Put them in for loops. Allmost everytime when the code looks repetetive, there can be used a loop to shorten it." } ]
[ { "body": "<p>(1) You define <code>random_scatter</code> as a class but then call it like a function, which works but is confusing. With your programme as it currently stands, there is no reason for it to be a class, so better simply to define <code>random_scatter</code> as a function (use <code>def random_scatter():</code> at the top). </p>\n\n<p>(2) You can remove repetition and make the code more readable using functions and loops, e.g. write a function</p>\n\n<pre><code>def insert_seperators(number):\n for _ in range(number):\n cmds.separator(height=20, style='in')\n</code></pre>\n\n<p>then you can replace </p>\n\n<pre><code> cmds.separator( height=20, style='in')\n cmds.separator( height=20, style='in')\n cmds.separator( height=20, style='in')\n</code></pre>\n\n<p>with</p>\n\n<pre><code> insert_separators(3)\n</code></pre>\n\n<p>(3) If you have other functions doing similar things with <code>cmds</code> then try to see what they have in common and put that in a single function, which accepts parameters according to what changes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T13:09:51.487", "Id": "30559", "ParentId": "23413", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T06:02:07.410", "Id": "23413", "Score": "2", "Tags": [ "python" ], "Title": "Shorten Python/Maya Window UI code" }
23413
<p>This script extracts all urls from a specific HTML div block (with BeautifulSoup 4) : </p> <pre><code>raw_data = dl("http://somewhere") links = [] soup = BeautifulSoup(raw_data) data = str(soup.find_all('div', attrs={'class' : "results"})) for link in BeautifulSoup(data, parse_only = SoupStrainer('a')): links.append(urllib.parse.unquote_plus(link['href'])) return links </code></pre> <p>Is there a more efficient and clean way to do it ?</p>
[]
[ { "body": "<p>AFAIK, you can use <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">List comprehension</a> to make it more efficient </p>\n\n<pre><code>raw_data = dl(\"http://somewhere\")\nsoup = BeautifulSoup(raw_data)\ndata = str(soup.find_all('div', attrs={'class' : \"results\"}))\nreturn [ urllib.parse.unquote_plus(link['href']) for link in BeautifulSoup(data, parse_only = SoupStrainer('a'))]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T12:45:56.947", "Id": "23426", "ParentId": "23416", "Score": "1" } }, { "body": "<p>I would use <strong>lmxl.html</strong> + <strong>xpath</strong></p>\n\n<p>Let's say, the html you get from \"url\" is:</p>\n\n<pre><code> &lt;html&gt;\n &lt;body&gt;\n &lt;div class=\"foo\"&gt;\n &lt;a href=\"#foo1\"&gt;foo1&lt;/a&gt;\n &lt;a href=\"#foo2\"&gt;foo2&lt;/a&gt;\n &lt;/div&gt;\n &lt;div class=\"results\"&gt;\n &lt;a href=\"#res1\"&gt;res1&lt;/a&gt;\n &lt;a href=\"#res2\"&gt;res2&lt;/a&gt;\n &lt;/div&gt;\n &lt;div class=\"bar\"&gt;\n &lt;a href=\"#bar1\"&gt;bar1&lt;/a&gt;\n &lt;a href=\"#bar2\"&gt;bar2&lt;/a&gt;\n &lt;/div&gt;\n &lt;div id=\"abc\"&gt;\n &lt;a href=\"#abc\"&gt;abc&lt;/a&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;a href=\"#nothing\"&gt;nothing&lt;/a&gt;\n &lt;/div&gt;\n &lt;a href=\"#xyz\"&gt;xyz&lt;/a&gt;\n &lt;/body&gt;\n &lt;/html&gt;\n</code></pre>\n\n<p>Here is how I would do:</p>\n\n<pre><code>from StringIO import StringIO\nfrom lxml.html import parse\n\nif __name__ == '__main__':\n\n tree = parse(url)\n hrefs = tree.xpath(\"//div[@class='results']/a/@href\")\n\n print hrefs\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>['#res1', '#res2']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T08:59:08.537", "Id": "24075", "ParentId": "23416", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T09:40:40.713", "Id": "23416", "Score": "1", "Tags": [ "python" ], "Title": "URLs extraction from specific block" }
23416
<p>So I am essentially a complete newbie to programming, and have been attempting to learn Python by completing the Project Euler problems. I haven't gotten very far, and this is my code for <a href="http://projecteuler.net/problem=3" rel="nofollow">problem #3</a> :</p> <blockquote> <p>The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <p>Although my solution works, I'd like to know how I can improve.</p> <pre><code>primes = [2] factors = [] def isPrime(x): a = 1 if x == 1: return False while a &lt; x: a += 1 if x % a == 0 and a != x and a != 1: return False break return True def generatePrime(): a = primes[-1]+1 while isPrime(a) == False: a += 1 primes.append(a) def primeFactor(x): a = primes[-1] while a &lt;= x: if x % a == 0: factors.append(a) x /= a generatePrime() a = primes[-1] primeFactor(input("Enter the number: ")) print("The prime factors are: " + str(factors) + "\nThe largest prime factor is: " + str(sorted(factors)[-1])) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T14:06:48.310", "Id": "36112", "Score": "0", "body": "You should replace `while a < x:` with `while a < math.sqrt(x):` You can also check whether x is even and > 2, in that case it is not a prime, also google for 'prime sieve'." } ]
[ { "body": "<p>You can save quite a bit time on your prime generation. What you should keep in mind is that a prime is a number which is no multiple of a prime itself; all other numbers are.</p>\n\n<p>So in your <code>isPrime</code> function you can just go through your primes list and check if each prime is a divisor of the number. If not, then it is a prime itself. Of course you would need to make sure that you fill your primes list enough first.</p>\n\n<p>As the most basic idea, you only need to check until <code>sqrt(n)</code>, so you only generate numbers this far. And you can also just skip every even number directly. You could also make similar assumptions for numbers dividable by 3 etc., but the even/uneven is the simplest one and enough to get fast results for not too big numbers.</p>\n\n<p>So a prime generation algorithm, for possible prime divisors up to <code>n</code>, could look like this:</p>\n\n<pre><code>primes = [2]\nfor i in range(3, int(math.sqrt(n)), 2):\n isPrime = not any(i % p == 0 for p in primes)\n if isPrime:\n primes.append(i)\n</code></pre>\n\n<p>Then to get the prime factors of <code>n</code>, you just need to check those computed primes:</p>\n\n<pre><code>primeFactors = []\nm = n\nfor p in primes:\n while m % p == 0:\n m = m / p\n primeFactors.append(p)\n if m == 0:\n break\n\nprint('The prime factorization of `{0}` is: {1}'.format(n, '×'.join(map(str,primeFactors))))\n</code></pre>\n\n<p>For the euler problem 3 with <code>n = 317584931803</code>, this would produce the following output:</p>\n\n<blockquote>\n <p>The prime factorization of <code>317584931803</code> is: 67×829×1459×3919</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T18:42:02.080", "Id": "36164", "Score": "0", "body": "If you are not going to sieve to calculate your primes, you should at least bring together your prime calculation and factor testing together, so that as soon as you find the `67` factor, your largest prime to calculate is reduced from `563546` to `68848`, and by the time you know `829` is a prime to `2391`, and once `1459` is known as a prime you don't calculate any more primes to test as factors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T19:19:03.887", "Id": "36167", "Score": "0", "body": "@Jaime Sure, you can again save a lot when combining those two. My original solution for problem 3 (which btw. doesn’t even require factorization) is a lot more concise too. But given OP’s original code structure I thought it would make more sense to show separated and reusable pieces. With my example I could once generate the primes and then just run the factorization against multiple numbers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T16:58:58.283", "Id": "23447", "ParentId": "23429", "Score": "5" } }, { "body": "<p>My code takes 2 milliseconds to execute from tip to tail ...</p>\n\n<pre><code># 600851475143\n\nimport math\n\nimport time\n\nnumber = int(input(\"&gt; \"))\n\nstart_time = time.time()\n\n\ndef prime_factors(number):\n\n prime_factorization = []\n\n box = number\n\n while number &gt; 1:\n for i in range(math.floor(math.log2(number))):\n for j in range(2, number + 1):\n if number % j == 0:\n prime_factorization.append(j)\n number = number//j\n last_factor = j\n if last_factor &gt; math.sqrt(box):\n return prime_factorization\n break\n return prime_factorization\n\n\nprint(f\"Prime factors = {prime_factors(number)}\")\n\nprint(f\"execution time = {time.time() - start_time} seconds\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T07:50:22.943", "Id": "475391", "Score": "2", "body": "Hey, welcome to Code Review! Please add some more explanation on *how* and *why* your code is better (faster). Otherwise this is just an alternative solution, which alone is not enough for an answer here. Have a look at our [help-center](https://codereview.stackexchange.com/help/how-to-answer) for more information." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T06:32:46.730", "Id": "242243", "ParentId": "23429", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T13:17:46.433", "Id": "23429", "Score": "8", "Tags": [ "python", "project-euler", "primes" ], "Title": "Project Euler #3 - how inefficient is my code?" }
23429
<p>I've never had a serious attempt at writing an encryption algorithm before, and haven't read much on the subject. I have tried to write an encryption algorithm (of sorts), I would just like to see if anyone thinks it's any good. (Obviously, it's not going to be comparable to those actually used, given that it's a first attempt)</p> <p>Without further adieu:</p> <pre><code>def encode(string, giveUserKey = False, doubleEncode = True): encoded = [] #Numbers representing encoded characters keys = [] #Key numbers to unlonk code fakes = [] #Which items in "encoded" are fake #All of these are stored in a file if giveUserKey: userkey = random.randrange(2 ** 10, 2 ** 16) # Key given to the user, entered during decryption for confirmation # Could change range for greater security else: userkey = 1 for char in string: ordChar = ord(char) key = random.randrange(sys.maxsize) encoded.append(hex((ordChar + key) * userkey)) keys.append(hex(key)) if random.randrange(fakeRate) == 0: fake = hex(random.randrange(sys.maxsize) * userkey) encoded.append(fake) fakes.append(fake) if doubleEncode: encoded = [string.encode() for string in encoded] keys = [string.encode() for string in keys] fakes = [string.encode() for string in fakes] hashValue = hex(hash("".join([str(obj) for obj in encoded + keys + fakes]))).encode() return encoded, keys, hashValue, fakes, userkey def decode(encoded, keys, hashValue, fakes, userkey = 1): if hash("".join([str(obj) for obj in encoded + keys + fakes])) != eval(hashValue): #File has been tampered with, possibly attempted reverse-engineering return "ERROR" for fake in fakes: encoded.remove(fake) decoded = "" for i in range(len(keys)): j = eval(encoded[i]) / userkey decoded += chr(int(j - eval(keys[i]))) return decoded </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T16:49:41.997", "Id": "36238", "Score": "0", "body": "usually an encryption algo takes input `data` and a `key`(private/symmetric) then outputs `cipher`. What's with `fakes` and `keys` in your case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T16:53:09.137", "Id": "36239", "Score": "0", "body": "\"fakes\" are fake bits of data inserted in to the code. \"keys\" are the keys from the file used to determine what the characters should actually be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T16:55:52.487", "Id": "36240", "Score": "0", "body": "If two parties say `A` & `B`, then isn't it necessary to exchange these `fakes`, `keys` along with actual `cipher` and `Key`(public/symmetric)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T17:01:12.870", "Id": "36241", "Score": "0", "body": "I don't quite know what you mean. fakes and keys are exchanged in that they are written in to the file which is exchanged. (There is then \"userkey\" which is not written in to the file. It can be specified by the encryptor whether this is needed. It is then told to them and needs to be entered for decryption)." } ]
[ { "body": "<p>Firstly, your encryption is useless. Just run this one line of python code:</p>\n\n<pre><code>print reduce(fractions.gcd, map(eval, encoded))\n</code></pre>\n\n<p>And it will tell you what your user key is (with a pretty high probability). </p>\n\n<p>Your algorithm is really obfuscation, not encrytion. Encryption is designed so that even if you know the algorithm, but not the key, you can't decryt the message. But your algorithm is basically designed to make it less obvious what the parts mean, not make it hard to decrypt without the key. As demonstrated, retrieving the key is trivial anyways. </p>\n\n<pre><code>def encode(string, giveUserKey = False, doubleEncode = True):\n</code></pre>\n\n<p>Python convention is lowercase_with_underscores for local names</p>\n\n<pre><code> encoded = [] #Numbers representing encoded characters\n keys = [] #Key numbers to unlonk code\n fakes = [] #Which items in \"encoded\" are fake\n #All of these are stored in a file\n\n if giveUserKey:\n userkey = random.randrange(2 ** 10, 2 ** 16)\n # Key given to the user, entered during decryption for confirmation\n # Could change range for greater security\n</code></pre>\n\n<p>Why isn't the key a parameter?</p>\n\n<pre><code> else:\n userkey = 1\n\n for char in string:\n ordChar = ord(char)\n key = random.randrange(sys.maxsize)\n encoded.append(hex((ordChar + key) * userkey))\n keys.append(hex(key))\n</code></pre>\n\n<p>These just aren't keys. Don't call them that.</p>\n\n<pre><code> if random.randrange(fakeRate) == 0:\n fake = hex(random.randrange(sys.maxsize) * userkey)\n encoded.append(fake)\n fakes.append(fake)\n\n if doubleEncode:\n encoded = [string.encode() for string in encoded]\n keys = [string.encode() for string in keys]\n fakes = [string.encode() for string in fakes]\n</code></pre>\n\n<p>Since these are all hex strings, why in the world are you encoding them?</p>\n\n<pre><code> hashValue = hex(hash(\"\".join([str(obj) for obj in encoded + keys + fakes]))).encode()\n\n return encoded, keys, hashValue, fakes, userkey\n\ndef decode(encoded, keys, hashValue, fakes, userkey = 1):\n if hash(\"\".join([str(obj) for obj in encoded + keys + fakes])) != eval(hashValue):\n #File has been tampered with, possibly attempted reverse-engineering\n return \"ERROR\"\n</code></pre>\n\n<p>Do not report errors by return value, use exceptions.</p>\n\n<pre><code> for fake in fakes:\n encoded.remove(fake)\n</code></pre>\n\n<p>What if coincidentally one of the fakes looks just like one of the data segments?</p>\n\n<pre><code> decoded = \"\"\n\n for i in range(len(keys)):\n</code></pre>\n\n<p>Use <code>zip</code> to iterate over lists in parallel</p>\n\n<pre><code> j = eval(encoded[i]) / userkey\n</code></pre>\n\n<p>Using <code>eval</code> is considered a bad idea. It'll execute any python code passed to it and that could be dangerous.</p>\n\n<pre><code> decoded += chr(int(j - eval(keys[i])))\n</code></pre>\n\n<p>It's better to append strings into a list and join them.</p>\n\n<pre><code> return decoded\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T21:20:47.527", "Id": "23506", "ParentId": "23492", "Score": "5" } } ]
{ "AcceptedAnswerId": "23506", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-05T16:42:35.983", "Id": "23492", "Score": "4", "Tags": [ "python", "algorithm" ], "Title": "Is this a good encryption algorithm?" }
23492
<p>My context is a very simple filter-like program that streams lines from an input file into an output file, filtering out lines the user (well, me) doesn't want. The filter is rather easy, simply requiring a particular value for some 'column' in the input file. Options are easily expressed with <code>argparse</code>:</p> <pre><code>parser.add_argument('-e', '--example', type=int, metavar='EXAMPLE', help='require a value of %(metavar)s for column "example"') </code></pre> <p>There's a few of these, all typed. As the actual filter gets a line at some point, the question whether to include such a line is simple: split the line and check all the required filters:</p> <pre><code>c1, c2, c3, *_ = line.split('\t') c1, c2, c3 = int(c1), int(c2), int(c3) # ← this line bugs me if args.c1 and args.c1 != c1: return False </code></pre> <p>The second line of which bugs me a bit: as the values are initially strings and I need them to be something else, the types need to be changed. Although short, I'm not entirely convinced this is the best solution. Some other options:</p> <ul> <li>create a separate function to hide the thing that bugs me;</li> <li>remove the <code>type=</code> declarations from the options (also removes automatic user input validation);</li> <li>coerce the arguments back to <code>str</code>s and do the comparison with <code>str</code>s (would lead to about the same as what I've got).</li> </ul> <p>Which of the options available would be the 'best', 'most pythonic', 'prettiest'? Or am I just overthinking this...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T13:59:23.147", "Id": "36310", "Score": "0", "body": "`int()` skips leading and trailing whitespace and leading zeros. So, a string comparison is not quite the same. Which do you need?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T14:34:26.357", "Id": "36313", "Score": "0", "body": "I need the numeric value. My data doesn't contain extraneous whitespace or zeroes, thought that doesn't much matter for the issue at hand." } ]
[ { "body": "<h3>1. Possible bugs</h3>\n\n<p>I can't be certain that these are bugs, but they look dodgy to me:</p>\n\n<ol>\n<li><p>You can't filter on the number 0, because if <code>args.c1</code> is 0, then it will test false and so you'll never compare it to <code>c1</code>. Is this a problem? If it is, you ought to compare <code>args.c1</code> explicitly against <code>None</code>.</p></li>\n<li><p>If the string <code>c1</code> cannot be converted to an integer, then <code>int(c1)</code> will raise <code>ValueError</code>. Is this what you want? Would it be better to treat this case as \"not matching the filter\"?</p></li>\n<li><p>If <code>line</code> has fewer than three fields, the assignment to <code>c1, c2, c3, *_</code> will raise <code>ValueError</code>. Is this what you want? Would it be better to treat this case as \"not matching the filter\"?</p></li>\n</ol>\n\n<h3>2. Suggested improvement</h3>\n\n<p>Fixing the possible bugs listed above:</p>\n\n<pre><code>def filter_field(filter, field):\n \"\"\"\n Return True if the string `field` passes `filter`, which is\n either None (meaning no filter), or an int (meaning that \n `int(field)` must equal `filter`).\n \"\"\"\n try:\n return filter is None or filter == int(field)\n except ValueError:\n return False\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>filters = [args.c1, args.c2, args.c3]\nfields = line.split('\\t')\nif len(fields) &lt; len(filters):\n return False\nif not all(filter_field(a, b) for a, b in zip(filters, fields)):\n return False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T11:21:07.007", "Id": "36341", "Score": "0", "body": "1: figured that as well, though my current context will never 'require' a falsy value. 2: valid point, crashing isn't good, even though I'd expect only integers. 3: also a valid point, though my lines contain far more than 3 values in reality.\nFurthermore, I like your idea of using `all` and `zip`; does feel prettier to me :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T09:51:20.527", "Id": "23560", "ParentId": "23531", "Score": "1" } } ]
{ "AcceptedAnswerId": "23560", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T12:24:18.877", "Id": "23531", "Score": "3", "Tags": [ "python", "type-safety" ], "Title": "Pythonic type coercion from input" }
23531
<p>I need to run over a log file with plenty of entries (25+GB) in Python to extract some log times. </p> <p>The snippet below works. On my test file, I'm ending up with roughly <code>9:30min</code> (Python) and <code>4:30min</code> (PyPy) on 28 million records (small log).</p> <pre><code>import datetime import time import json import re format_path= re.compile( r"^\S+\s-\s" r"(?P&lt;user&gt;\S*)\s" r"\[(?P&lt;time&gt;.*?)\]" ) threshold = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S') tick = datetime.timedelta(hours=threshold.tm_hour,minutes=threshold.tm_min,seconds=threshold.tm_sec).total_seconds() zero_time = datetime.timedelta(hours=0,minutes=0,seconds=0) zero_tick = zero_time.total_seconds() format_date = '%d/%b/%Y:%H:%M:%S' obj = {} test = open('very/big/log','r') for line in test: try: chunk = line.split('+', 1)[0].split('-', 1)[1].split(' ') user = chunk[1] if (user[0] == "C"): this_time = datetime.datetime.strptime(chunk[2].split('[')[1], format_date) try: machine = obj[user] except KeyError, e: machine = obj.setdefault(user,{"init":this_time,"last":this_time,"downtime":0}) last = machine["last"] diff = (this_time-last).total_seconds() if (diff &gt; tick): machine["downtime"] += diff-tick machine["last"] = this_time except Exception: pass </code></pre> <p>While I'm ok with the time the script runs, I'm wondering if there are any obvious pitfalls regarding performance, which I'm stepping in (still in my first weeks of Python).</p> <p>Can I do anything to make this run faster?</p> <p><strong>EDIT:</strong></p> <p>Sample log entry:</p> <pre><code>['2001:470:1f14:169:15f3:824f:8a61:7b59 - SOFTINST [14/Nov/2012:09:32:31 +0100] "POST /setComputerPartition HTTP/1.1" 200 4 "-" "-" 102356'] </code></pre> <p><strong>EDIT 2:</strong></p> <p>One thing I just did, was to check if log entries have the same log time and if so, I'm using the <code>this_time</code> from the previous iteration vs calling this:</p> <pre><code>this_time = datetime.datetime.strptime(chunk[2].split('[')[1], format_date) </code></pre> <p>I checked some of logs, there are plenty of entries with the exact same time, so on the last run on <code>pypy</code> I'm down to <code>2.43min</code>.</p>
[]
[ { "body": "<pre><code>import datetime\nimport time\nimport json\nimport re\n\nformat_path= re.compile( \n r\"^\\S+\\s-\\s\" \n r\"(?P&lt;user&gt;\\S*)\\s\"\n r\"\\[(?P&lt;time&gt;.*?)\\]\" \n)\n</code></pre>\n\n<p>Python convention is ALL_CAPS for global constants. But as far as I can tell, you don't actually use this.</p>\n\n<pre><code>threshold = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')\n</code></pre>\n\n<p>Why are you putting in a string literal just to throw half of it away? Why are you converting from a string rather then creating the value directly? \n tick = datetime.timedelta(hours=threshold.tm_hour,minutes=threshold.tm_min,seconds=threshold.tm_sec).total_seconds()</p>\n\n<p>That's a way over complicated way to accomplish this. Just say <code>tick = 60</code> and skip all the rigamorle.</p>\n\n<pre><code>zero_time = datetime.timedelta(hours=0,minutes=0,seconds=0)\nzero_tick = zero_time.total_seconds()\n</code></pre>\n\n<p>You don't seem to use this...</p>\n\n<pre><code>format_date = '%d/%b/%Y:%H:%M:%S'\n\n\n\nobj = {}\ntest = open('very/big/log','r')\n</code></pre>\n\n<p>Really bad names. They don't tell me anything. Also, it's recommended to deal with files using a with statement.</p>\n\n<pre><code>for line in test:\n try:\n chunk = line.split('+', 1)[0].split('-', 1)[1].split(' ')\n</code></pre>\n\n<p>That seems way complicated. There is probably a better way to extract the data but without knowing what this log looks like I can't really suggest one.</p>\n\n<pre><code> user = chunk[1]\n if (user[0] == \"C\"):\n</code></pre>\n\n<p>You don't need the ( and )</p>\n\n<pre><code> this_time = datetime.datetime.strptime(chunk[2].split('[')[1], format_date)\n try:\n machine = obj[user]\n except KeyError, e:\n machine = obj.setdefault(user,{\"init\":this_time,\"last\":this_time,\"downtime\":0})\n</code></pre>\n\n<p>Don't use dictionaries random attribute storage. Create an a class and put stuff in there.</p>\n\n<pre><code> last = machine[\"last\"]\n diff = (this_time-last).total_seconds()\n if (diff &gt; tick):\n</code></pre>\n\n<p>You don't need the parens, and I'd combine the last two lines</p>\n\n<pre><code> machine[\"downtime\"] += diff-tick\n machine[\"last\"] = this_time\n\n except Exception:\n pass\n</code></pre>\n\n<p>Don't ever do this. DON'T EVER DO THIS. You should never never catch and then ignore all possible exceptions. Invariably, you'll end up with a bug that you'll miss because you are ignoring the exceptions. </p>\n\n<p>As for making it run faster, we'd really need to know more about the log file's contents.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:31:05.033", "Id": "36352", "Score": "0", "body": "wow. Lot of input. Let me digest. I also add a sample record above plus one thing I just did" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:00:47.967", "Id": "23572", "ParentId": "23570", "Score": "2" } } ]
{ "AcceptedAnswerId": "23589", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T16:33:24.563", "Id": "23570", "Score": "5", "Tags": [ "python", "performance", "logging" ], "Title": "Running over a log file to extract log times" }
23570
<pre><code>#!/usr/bin/env python import os, sys variable = sys.argv def enVar(variable): """ This function returns all the environment variable set on the machine or in active project. if environment variable name is passed to the enVar function it returns its values. """ nVar = len(sys.argv)-1 if len(variable) == 1: # if user entered no environment variable name for index, each in enumerate(sorted(os.environ.iteritems())): print index, each else: # if user entered one or more than one environment variable name for x in range(nVar): x+=1 if os.environ.get(variable[x].upper()): # convertes to upper if user mistakenly enters lowecase print "%s : %s" % (variable[x].upper(), os.environ.get(variable[x].upper())) else: print 'Make sure the Environment variable "%s" exists or spelled correctly.' % variable[x] enVar(variable) </code></pre> <p>i run the above file as <code>show.py</code> is their a better way to do it ?</p>
[]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li>Indent with 4 spaces (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>)</li>\n<li>Use <code>underscore_names</code> for function and variables.</li>\n<li>Use meaningful names for functions (specially) and variables.</li>\n<li>Be concise in docstrings.</li>\n<li>Don't write <code>for index in range(iterable):</code> but <code>for element in iterable:</code>.</li>\n<li>Don't write <code>variable = sys.argv</code> in the middle of the code, use it directly as an argument.</li>\n<li>Use an import for each module.</li>\n</ul>\n\n<p>I'd write (Python 3.0):</p>\n\n<pre><code>import sys\nimport os\n\ndef print_environment_variables(variables):\n \"\"\"Print environment variables (all if variables list is empty).\"\"\"\n if not variables:\n for index, (variable, value) in enumerate(sorted(os.environ.items())):\n print(\"{0}: {1}\".format(variable, value))\n else: \n for variable in variables:\n value = os.environ.get(variable)\n if value:\n print(\"{0}: {1}\".format(variable, value))\n else:\n print(\"Variable does not exist: {0}\".format(variable))\n\nprint_environment_variables(sys.argv[1:])\n</code></pre>\n\n<p>But if you asked me, I would simplify the function without second thoughts, functions are more useful when they are homogeneous (that's it, they return similar outputs for the different scenarios):</p>\n\n<pre><code>def print_environment_variables(variables):\n \"\"\"Print environment variables (all if variables list is empty).\"\"\"\n variables_to_show = variables or sorted(os.environ.keys())\n for index, variable in enumerate(variables_to_show):\n value = os.environ.get(variable) or \"[variable does not exist]\"\n print(\"{0}: {1}={2}\".format(index, variable, value))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T18:46:50.090", "Id": "23628", "ParentId": "23623", "Score": "3" } } ]
{ "AcceptedAnswerId": "23628", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T15:29:46.960", "Id": "23623", "Score": "6", "Tags": [ "python" ], "Title": "this code returns environment varibles or passed enverionment variable with values" }
23623
<p>I am writing a specialized version of the cross correlation function as used in neuroscience. The function below is supposed to take a time series <code>data</code> and ask how many of its values fall in specified bins. My function <code>xcorr</code> works but is horrifically slow even. A test data set with 1000 points (and so 0.5*(1000*999) intervals) distributed over 400 bins takes almost ten minutes.</p> <p><strong>Bottleneck</strong></p> <p>The bottleneck is in the line <code>counts = array([sum ...</code>. I assume it is there because each iteration of the <code>foreach</code> loop searches through the entire vector <code>diffs</code>, which is of length <code>len(first)**2</code>.</p> <pre><code>def xcorr(first,second,dt=0.001,window=0.2,savename=None): length = min(len(first),len(second)) diffs = array([first[i]-second[j] for i in xrange(length) for j in xrange(length)]) bins = arange(-(int(window/dt)),int(window/dt)) counts = array[sum((diffs&gt;((i-.5)*dt)) &amp; (diffs&lt;((i+.5)*dt))) for i in bins] counts -= len(first)**2*dt/float(max(first[-1],second[-1])) #Normalization if savename: cPickle.dump((bins*dt,counts),open(savename,'wb')) return (bins,counts) </code></pre>
[]
[ { "body": "<p>Here's a crack at my own question that uses built-in functions from <code>NumPy</code> </p>\n\n<p><strong>Update</strong></p>\n\n<p>The function chain <code>bincount(digitize(data,bins))</code> is equivalent to <code>histogram</code>, which allows for a more succinct expression.</p>\n\n<pre><code> def xcorr(first,second,dt=0.001,window=0.2,savename=None):\n length = min(len(first),len(second))\n diffs = array([first[i]-second[j] for i in xrange(length) for j in xrange(length)])\n counts,edges = histogram(diffs,bins=arange(-window,window,dt))\n counts -= length**2*dt/float(first[length])\n if savename:\n cPickle.dump((counts,edges[:-1]),open(savename,'wb'))\n return (counts,edges[:-1])\n</code></pre>\n\n<p>The indexing in the <code>return</code> statement comes because I want to ignore the edge bins. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:05:23.163", "Id": "23663", "ParentId": "23656", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T14:43:36.820", "Id": "23656", "Score": "3", "Tags": [ "python", "performance", "numpy", "statistics" ], "Title": "Specialized version of the cross correlation function" }
23656
<p><strong>Premise:</strong> Write a program that counts the frequencies of each word in a text, and output each word with its count and line numbers where it appears. We define a word as a contiguous sequence of non-white-space characters. Different capitalizations of the same character sequence should be considered same word (e.g. Python and python). The output is formatted as follows: each line begins with a number indicating the frequency of the word, a white space, then the word itself, and a list of line numbers containing this word. You should output from the most frequent word to the least frequent. In case two words have the same frequency, the lexicographically smaller one comes first. All words are in lower case in the output.</p> <p><strong>Solution:</strong></p> <pre><code># Amazing Python libraries that prevent re-invention of wheels. import re import collections import string from operator import itemgetter # Simulate work for terminal print 'Scanning input for word frequency...' # Text files input = open('input.txt', 'r') output = open('output.txt', 'w') # Reads every word in input as lowercase while ignoring punctuation and # returns a list containing 2-tuples of (word, frequency). list = collections.Counter(input.read().lower() .translate(None, string.punctuation).split()).most_common() # Sorts the list by frequency in descending order. list = sorted(list, key=itemgetter(0)) # Sorts the list by lexicogrpahical order in descending order while maintaining # previous sorting. list = sorted(list, key=itemgetter(1), reverse=True) # Gets the lines where each word in list appears in the input. for word in list: lineList = [] # Reads the input line by line. Stores each text line in 'line' and keeps a # counter in 'lineNum' that starts at 1. for lineNum, line in enumerate(open('input.txt'),1): # If the word is in the current line then add it to the list of lines # in which the current word appears in. The word frequency list is not # mutated. This is stored in a separate list. if re.search(r'(^|\s)'+word[0]+'\s', line.lower().translate(None, string.punctuation), flags=re.IGNORECASE): lineList.append(lineNum) # Write output with proper format. output.write(str(word[1]) + ' ' + word[0] + ' ' + str(lineList)+'\n') # End work simulation for terminal print 'Done! Output in: output.txt' </code></pre> <p>How can I get the line numbers without re-reading the text? I want to achieve sub-O(n^2) time complexity. I am new to Python so feedback on other aspects is greatly appreciated as well.</p>
[]
[ { "body": "<p>You're right, the basic point to make this program faster is to store the line numbers in the first pass.</p>\n\n<p>The <code>for word in list</code> loop will run many times. The count depends on how many words you have. Every time it runs, it reopens and rereads the whole input file. This is awfully slow.</p>\n\n<p>If you start using a more generic data structure than your <code>Counter()</code>, then you'll be able to store the line numbers. For example you could use a dictionary. The key of the dict is the word, the value is a list of line numbers. The hit count is stored indirectly as the length of the list of line numbers.</p>\n\n<p>In one pass over the input you can populate this data structure. In a second step, you can properly sort this data structure and iterate over the elements.</p>\n\n<p>An example implementation:</p>\n\n<pre><code>from collections import defaultdict\nimport sys \n\nif __name__ == \"__main__\":\n hit = defaultdict(list)\n for lineno, line in enumerate(sys.stdin, start=1):\n for word in line.split():\n hit[word.lower()].append(lineno)\n for word, places in sorted(hit.iteritems(), key=lambda (w, p): (-len(p), w)):\n print len(places), word, \",\".join(map(str, sorted(set(places))))\n</code></pre>\n\n<p>A few more notes:</p>\n\n<ol>\n<li><p>If you <code>open()</code> a file, <code>close()</code> it too. As soon as you're done with using it. (Or use <a href=\"http://docs.python.org/2/reference/compound_stmts.html#the-with-statement\" rel=\"nofollow\">the <code>with</code> statement</a> to ensure that it gets closed.)</p></li>\n<li><p>Don't hardcode input/output file names. Read from standard input (<code>sys.stdin</code>), write to standard output (<code>sys.stdout</code> or simply <code>print</code>), and let the user use his shell's redirections: <code>program &lt;input.txt &gt;output.txt</code></p></li>\n<li><p>Don't litter standard output with progress messages. If you absolutely need them use <code>sys.stderr.write</code> or get acquainted with the <code>logging</code> module.</p></li>\n<li><p>Don't use regular expressions, unless it's necessary. Prefer string methods for their simplicity and speed.</p></li>\n<li><p>Name your variables in <code>lower_case_with_underscores</code> as <a href=\"https://www.google.co.uk/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CDIQFjAA&amp;url=http://www.python.org/dev/peps/pep-0008/&amp;ei=8Pc9UfzGLKaM7AaSloB4&amp;usg=AFQjCNERHdnSYA5JWg_ZfKT_cVYU4MWGyw&amp;bvm=bv.43287494,d.ZGU\" rel=\"nofollow\">PEP8</a> recommends.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T05:38:24.860", "Id": "36524", "Score": "0", "body": "Great review. Are there any performance reasons for note 2? Also, when you say \"let the user use his shell's redirections: `program <input.txt >output.txt`\" does that mean that when I run my program from the terminal I can pass the filenames as arguments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T09:21:06.210", "Id": "36528", "Score": "1", "body": "There are cases when (2) can help in better performance. In a pipeline like `prg1 <input.txt | prg2 >output.txt` prg1 and prg2 are started in parallel (at least in unix-like OSes). prg2 does not have to wait for prg1 to finish, but can start to work when prg1 produced any output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T09:28:59.343", "Id": "36529", "Score": "1", "body": "__Can I pass the filenames as arguments?__ Yes, you can specify the filenames in the terminal. To be precise, these are not arguments, they are not processed by your program. They are called `shell redirections` and are processed by your command shell. They are extra useful, google them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:18:21.743", "Id": "36621", "Score": "0", "body": "@Gareth Rees: I'm not sure whether you have noticed, but with your edit you introduced a little semantic change. The edited code counts a word at most once per line. Previously (as in the OP) it counted multiple occurences in the same line, but later printed the line number only once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:29:44.803", "Id": "36625", "Score": "0", "body": "@rubasov: You're quite right. That was my mistake." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T22:39:58.410", "Id": "23681", "ParentId": "23662", "Score": "3" } } ]
{ "AcceptedAnswerId": "23681", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:00:50.760", "Id": "23662", "Score": "4", "Tags": [ "python", "optimization" ], "Title": "Improve efficiency for finding word frequency in text" }
23662
<p>I created this version of Hangman in Python 3. Does anyone have any tips for optimization or improvement?</p> <pre><code>import random HANGMAN = ( ''' -------+''', ''' + | | | | | -------+''', ''' -----+ | | | | | -------+''', ''' -----+ | | | | | | -------+''', ''' -----+ | | O | | | | -------+''', ''' -----+ | | O | | | | | -------+''', ''' -----+ | | O | /| | | | -------+''', ''' -----+ | | O | /|\ | | | -------+''', ''' -----+ | | O | /|\ | / | | -------+''', ''' -----+ | | O | /|\ | / \ | | -------+''') MAX = len(HANGMAN) - 1 WORDS = ('jazz', 'buzz', 'hajj', 'fuzz', 'jinx', 'jazzy', 'fuzzy', 'faffs', 'fizzy', 'jiffs', 'jazzed', 'buzzed', 'jazzes', 'faffed', 'fizzed', 'jazzing', 'buzzing', 'jazzier', 'faffing', 'fuzzing') sizeHangman = 0 word = random.choice(WORDS) hiddenWord = list('-' * len(word)) lettersGuessed = [] print('\tHANGMAN GAME\n\t\tBy Lewis Cornwall\n') while sizeHangman &lt; MAX: print('This is your hangman:' + HANGMAN[sizeHangman] + '\nThis is the word:\n' + ''.join(hiddenWord) + '\nThese are the letters you\'ve already guessed:\n' + str(lettersGuessed)) guess = input('Guess a letter: ').lower() while guess in lettersGuessed: print('You\'ve already guessed that letter!') guess = input('Guess a letter: ').lower() if guess in word: print('Well done, "' + guess + '" is in my word!') for i in range(len(word)): if guess == word[i]: hiddenWord[i] = guess if hiddenWord.count('-') == 0: print('Congratulations! My word was ' + word + '!') input('Press &lt;enter&gt; to close.') quit() else: print('Unfortunately, "' + guess + '" is not in my word.') sizeHangman += 1 lettersGuessed.append(guess) print('This is your hangman: ' + HANGMAN[sizeHangman] + 'You\'ve been hanged! My word was actually ' + word + '.') input('Press &lt;enter&gt; to close.') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T13:22:45.947", "Id": "36588", "Score": "2", "body": "Not an optimization, but you could load your words from a - possibly encrypted - text file instead of having them in your raw code :)" } ]
[ { "body": "<p>You can avoid repeating <code>guess = input('Guess a letter: ').lower()</code> by changing the inner while loop to:</p>\n\n<pre><code>while True:\n guess = input('Guess a letter: ').lower()\n if guess in lettersGuessed:\n print('You\\'ve already guessed that letter!')\n else:\n break\n</code></pre>\n\n<p>Instead of <code>for i in range(len(word))</code> use:</p>\n\n<pre><code>for i, letter in enumerate(word):\n</code></pre>\n\n<p>You could also avoid indexing by <code>i</code> altogether by using a list comprehension. I'm not sure if this is as clear in this case, though.</p>\n\n<pre><code>hiddenWord = [guess if guess == letter else hidden for letter, hidden in zip(word, hiddenWord)]\n</code></pre>\n\n<p>Instead of <code>hiddenWord.count('-') == 0</code> use:</p>\n\n<pre><code>'-' not in hiddenWord\n</code></pre>\n\n<p><a href=\"http://docs.python.org/3/library/constants.html#constants-added-by-the-site-module\">The docs</a> say <code>quit()</code> should not be used in programs. Your <code>count('-') == 0</code> check is unnecessarily inside the <code>for i</code> loop. If you move it after the loop, you could use <code>break</code> to exit the main loop. You could add an <code>else</code> clause to the main <code>with</code> statement for dealing with the \"You've been hanged\" case. The main loop becomes:</p>\n\n<pre><code>while sizeHangman &lt; MAX:\n print('This is your hangman:' + HANGMAN[sizeHangman] + '\\nThis is the word:\\n' + ''.join(hiddenWord) + '\\nThese are the letters you\\'ve already guessed:\\n' + str(lettersGuessed))\n while True:\n guess = input('Guess a letter: ').lower()\n if guess in lettersGuessed:\n print('You\\'ve already guessed that letter!')\n else:\n break\n if guess in word:\n print('Well done, \"' + guess + '\" is in my word!')\n for i, letter in enumerate(word):\n if guess == letter:\n hiddenWord[i] = guess\n if '-' not in hiddenWord:\n print('Congratulations! My word was ' + word + '!')\n break\n else:\n print('Unfortunately, \"' + guess + '\" is not in my word.')\n sizeHangman += 1\n lettersGuessed.append(guess)\nelse:\n print('This is your hangman: ' + HANGMAN[sizeHangman] + 'You\\'ve been hanged! My word was actually ' + word + '.')\ninput('Press &lt;enter&gt; to close.')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T13:36:26.593", "Id": "23733", "ParentId": "23678", "Score": "6" } }, { "body": "<p>Some ideas:</p>\n\n<ul>\n<li><p>You might want to make sure that the guess is actually a single letter.</p></li>\n<li><p><code>lettersGuessed</code> should be a <em>set</em>, so membership tests (<code>guess in lettersGuessed</code>) is a constant time operation.</p></li>\n<li><p>Similarly, you could store either the (correctly) guessed letters or the letters that still have to be (correctly) guessed in a set. For example:</p>\n\n<pre><code>word = random.choice(WORDS)\nrequiredGuesses = set(word)\nlettersGuessed = set()\n\n# then later\nif guess in lettersGuessed:\n print('You already guessed this')\nelif guess in requiredGuesses:\n print('Correct guess!')\n requiredGuesses.remove(guess)\n lettersGuessed.add(guess)\nelse:\n print('Incorrect guess')\n</code></pre>\n\n<p>This also makes the test if the whole word was guessed easier:</p>\n\n<pre><code>if not requiredGuesses:\n print('You found the word')\n</code></pre></li>\n<li><p>Instead of keeping a <code>hiddenWord</code> which you keep adjusting whenever a correct guess is made, you could just create the hidden output on the fly:</p>\n\n<pre><code>print(''.join('-' if l in requiredGuesses else l for l in word))\n</code></pre></li>\n<li><p>You might want to add a class for this game that encapsulates some of the game logic.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-25T00:44:26.487", "Id": "38054", "ParentId": "23678", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T21:43:33.187", "Id": "23678", "Score": "6", "Tags": [ "python", "optimization", "game", "python-3.x", "hangman" ], "Title": "Hangman in Python" }
23678
<p>The required output is stated just before the <code>main()</code> function. Is there a better way to achieve it? I feel like I am repeating code unnecessarily but am unable to find a better way to get the result. Not squeezing the code too much, like one liners, but reasonably using better logic.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- #Time to play a guessing game. #Enter a number between 1 and 100: 62 #Too high. Try again: 32 #Too low. Try again: 51 #Too low. Try again: 56 #Congratulations! You got it in 4 guesses. import random def main(): return 0 if __name__ == '__main__': main() print("Time to play a guessing game.") val = random.randint(1, 100) guess = 0 count = 1 guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) print("") print("randint is", val) print("") if (guess == val): print("\nCongratulations! You got it in", count, "guesses.") while(guess != val): if guess &gt; val: print("Too high. Try again:", guess) guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) count = count + 1 if guess == val: print("\nCongratulations! You got it in", count, "guesses.") break elif guess &lt; val: print("Too low. Try again:", guess) guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) count = count + 1 if guess == val: print("\nCongratulations! You got it in", count, "guesses.") break else: pass print("") </code></pre>
[]
[ { "body": "<ol>\n<li>The pythonic way to do <code>count = count + 1</code> is <code>count += 1</code></li>\n<li><p>You don't need to repeat the 'guess again' part of the game twice:</p>\n\n<pre><code>if guess &gt; val:\n print(\"Too high. Try again:\", guess) \nelif guess &lt; val:\n print(\"Too low. Try again:\", guess)\nguess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\ncount += 1\nif guess == val:\n print(\"\\nCongratulations! You got it in\", count, \"guesses.\")\n break\n</code></pre></li>\n<li><p>You don't need to add the extra <code>if</code> statement because if <code>guess != val</code>, then the loop with break anyway:</p>\n\n<pre><code>while guess != val:\n if guess &gt; val:\n print(\"Too high. Try again:\", guess) \n elif guess &lt; val:\n print(\"Too low. Try again:\", guess)\n guess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\n count += 1\nprint(\"Congratulations! You got it in\", count, \"guesses.\")\n</code></pre></li>\n<li><p>I think <code>print(\"randint is\", val)</code> was probably for testing purposes, but it's still in your code!</p></li>\n<li><p>If you execute your program outside the command module (I'm not quite sure what it's called), the program will close immediately after it's finished; it's always best to give the user the choice of when to quit, so insert this at the end of your code:</p>\n\n<pre><code>input(\"Press enter to quit\")\n</code></pre></li>\n<li><p>The first section is unneeded:</p>\n\n<pre><code>def main():`, `if __name__ == \"__main__\":\n</code></pre></li>\n<li><p>The first <code>if</code> statement is also unneeded:</p>\n\n<pre><code>if guess == val:\n</code></pre></li>\n<li><p>You don't need to define <code>guess = 0</code> the first time.</p></li>\n</ol>\n\n<p>So, all in all, my improvement of your code is:</p>\n\n<pre><code>import random\nprint(\"Time to play a guessing game.\")\nval = random.randint(1, 100)\ncount = 1 \nguess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\nwhile(guess != val): \n if guess &gt; val:\n print(\"Too high. Try again:\", guess) \n elif guess &lt; val:\n print(\"Too low. Try again:\", guess)\n guess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\n count += 1\nprint(\"\\nCongratulations! You got it in \", count, \" guesses.\")\ninput(\"Press enter to quit.\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:01:52.480", "Id": "36567", "Score": "0", "body": "I'd use instead of `while guess != val:` is `elif guess == val` then break" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-27T06:14:20.910", "Id": "261599", "Score": "0", "body": "One minor thing: `while(guess != val):` can be changed to `while guess != val:`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T15:09:37.870", "Id": "23696", "ParentId": "23694", "Score": "10" } }, { "body": "<p>How about this:</p>\n\n<pre><code>import random\n\ndef main():\n print('Time to play a guessing game.')\n\n val = random.randint(1, 100)\n count = 0\n\n guess = int(input('\\n\\tEnter a number between 1 and 100: '))\n while True:\n count += 1\n if guess == val:\n print('\\nCongratulations! You got it in ', count, 'guesses.')\n break\n elif guess &gt; val:\n msg = 'Too high.'\n else:\n msg = 'Too low.'\n guess = int(input('{}\\tTry again: '.format(msg)))\n return 0\n\nmain()\n</code></pre>\n\n<p>Maybe you can draw a flow chart, which can help you get clearer control flow to avoid unnecessary repeating.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T04:01:03.217", "Id": "23713", "ParentId": "23694", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T14:43:48.083", "Id": "23694", "Score": "12", "Tags": [ "python", "game" ], "Title": "Guessing Game: computer generated number between 1 and 100 guessed by user" }
23694
<p>The output is a random sequence, and the input is the sum of the sequence.</p> <p>My solution is generating a random number <em>rand_num</em> from (0, sum_seq) at first, then draw another number randomly from (0, sum_seq - rand_num). By the way, all random numbers are integers.</p> <pre><code>import random rand_list = [] # Random sequences buffer def generater_random_list(num) : rand_num = random.randint(0, num) rand_list.append(rand_num) if num - rand_num == 0 : return 0 else : return generater_random_list(num - rand_num) </code></pre> <p>It seems strange to create a buffer out of the function, so how can I improve it?</p>
[]
[ { "body": "<h1>Using a recursive approach -</h1>\n\n<hr>\n\n<pre><code>from random import randint\n\ndef sequence(n):\n\n a = []\n\n def f(n):\n m = randint(1, n)\n if n &gt; m:\n a.append(str(m))\n return f(n - m)\n else:\n a.append(str(n))\n return n\n\n f(n)\n return ' + '.join(a) + ' = %d' % n\n</code></pre>\n\n<hr>\n\n<h3>Test code:</h3>\n\n<pre><code>for i in xrange(10):\n print sequence(20)\n</code></pre>\n\n<hr>\n\n<h3>Output:</h3>\n\n<pre><code>7 + 11 + 2 = 20\n14 + 4 + 1 + 1 = 20\n5 + 10 + 3 + 2 = 20\n1 + 17 + 1 + 1 = 20\n1 + 5 + 13 + 1 = 20\n3 + 12 + 2 + 3 = 20\n17 + 2 + 1 = 20\n18 + 2 = 20\n3 + 12 + 3 + 2 = 20\n18 + 1 + 1 = 20\n</code></pre>\n\n<hr>\n\n<h1>Using iterative approach -</h1>\n\n<hr>\n\n<pre><code>from random import randint\n\ndef sequence(n):\n\n a, m, c = [], randint(1, n), n \n while n &gt; m &gt; 0:\n a.append(str(m))\n n -= m\n m = randint(0, n)\n if n: a += [str(n)]\n return ' + '.join(a) + ' = %d' % c\n</code></pre>\n\n<hr>\n\n<h3>Test code:</h3>\n\n<pre><code>for i in xrange(10):\n print sequence(20)\n</code></pre>\n\n<hr>\n\n<h3>Ouput:</h3>\n\n<pre><code>19 + 1 = 20\n2 + 15 + 3 = 20\n2 + 3 + 12 + 3 = 20\n19 + 1 = 20\n2 + 10 + 2 + 6 = 20\n6 + 3 + 9 + 1 + 1 = 20\n14 + 2 + 3 + 1 = 20\n3 + 7 + 4 + 4 + 2 = 20\n9 + 7 + 3 + 1 = 20\n3 + 17 = 20\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T11:54:47.407", "Id": "36584", "Score": "0", "body": "I didn't include `0`s, as I thought it was not a _sum_, and the output looks prettier without `0`s" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T11:43:50.353", "Id": "23729", "ParentId": "23728", "Score": "1" } } ]
{ "AcceptedAnswerId": "23731", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T08:45:56.317", "Id": "23728", "Score": "7", "Tags": [ "python", "random" ], "Title": "Generating random sequences while keeping sum fixed" }
23728
<p>I am trying to write a Python script that download an image from a webpage. On the webpage (I am using NASA's picture of the day page), a new picture is posted everyday, with different file names. After download, set the image as desktop. </p> <p>My solutions was to parse the HTML using <code>HTMLParser</code>, looking for "jpg", and write the path and file name of the image to an attribute (named as "output", see code below) of the HTML parser object.</p> <p>The code works, but I am just looking for comments and advice. I am new to Python and OOP (this is my first real python script ever), so I am not sure if this is how it is generally done.</p> <pre><code>import urllib2 import ctypes from HTMLParser import HTMLParser # Grab image url response = urllib2.urlopen('http://apod.nasa.gov/apod/astropix.html') html = response.read() class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, print it. if name == "href": if value[len(value)-3:len(value)]=="jpg": #print value self.output=value parser = MyHTMLParser() parser.feed(html) imgurl='http://apod.nasa.gov/apod/'+parser.output print imgurl # Save the file img = urllib2.urlopen(imgurl) localFile = open('desktop.jpg', 'wb') localFile.write(img.read()) localFile.close() # set to desktop(windows method) SPI_SETDESKWALLPAPER = 20 ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "desktop.jpg" , 0) </code></pre>
[]
[ { "body": "<pre><code># Save the file\nimg = urllib2.urlopen(imgurl)\nlocalFile = open('desktop.jpg', 'wb')\nlocalFile.write(img.read())\nlocalFile.close()\n</code></pre>\n\n<p>For opening file it's recommend to do:</p>\n\n<pre><code>with open('desktop.jpg','wb') as localFile:\n localFile.write(img.read())\n</code></pre>\n\n<p>Which will make sure the file closes regardless.</p>\n\n<p>Also, urllib.urlretrieve does this for you. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T01:27:02.603", "Id": "23761", "ParentId": "23759", "Score": "2" } }, { "body": "<p>I think your class <code>MyHTMLParser</code> is not necessary. We can use a function instead of a class.</p>\n\n<p>If you know what is <code>Regular Expression</code> you can using code below:</p>\n\n<pre><code>import re\n\ndef getImageLocation():\n with urllib2.urlopen('http://apod.nasa.gov/apod/astropix.html') as h:\n # (?&lt;=...) means \"Matches if the current position in the string \n # is preceded by a match for ... \n # that ends at the current position.\"\n loc = re.search('(?&lt;=IMG SRC=\")image/\\d+/[\\w\\d_]+.jpg', a).group())\n return 'http://apod.nasa.gov/apod/' + loc\n</code></pre>\n\n<p>Regular Expression Syntax: <a href=\"http://docs.python.org/3/library/re.html#regular-expression-syntax\" rel=\"nofollow\">http://docs.python.org/3/library/re.html#regular-expression-syntax</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T08:44:52.970", "Id": "23827", "ParentId": "23759", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T00:08:39.580", "Id": "23759", "Score": "4", "Tags": [ "python", "beginner", "parsing", "windows", "web-scraping" ], "Title": "Download an image from a webpage" }
23759
<p>I wrote a two player Noughts and Crosses game in Python 3, and came here to ask how I can improve this code.</p> <pre><code>import random cell = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] def owin(cell): return cell[0] == cell[1] == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell[1] == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8] == 'O' or cell[0] == cell[4] == cell[8] == 'O' or cell[2] == cell[4] == cell[6] == 'O' def xwin(cell): return cell[0] == cell[1] == cell[2] == 'X' or cell[3] == cell[4] == cell[5] == 'X' or cell[6] == cell[7] == cell[8] == 'X' or cell[0] == cell[3] == cell[6] == 'X' or cell[1] == cell[4] == cell[7] == 'X' or cell[2] == cell[5] == cell[8] == 'X' or cell[0] == cell[4] == cell[8] == 'X' or cell[2] == cell[4] == cell[6] == 'X' def tie(cell): return cell[0] in ('O', 'X') and cell[1] in ('O', 'X') and cell[2] in ('O', 'X') and cell[3] in ('O', 'X') and cell[4] in ('O', 'X') and cell[5] in ('O', 'X') and cell[6] in ('O', 'X') and cell[7] in ('O', 'X') and cell[8] in ('O', 'X') print('\tNOUGHTS AND CROSSES\n\t\tBy Lewis Cornwall') instructions = input('Would you like to read the instructions? (y/n)') if instructions == 'y': print('\nEach player takes turns to place a peice on the following grid:\n\n\t 1 | 2 | 3\n\t-----------\n\t 4 | 5 | 6\n\t-----------\n\t 7 | 8 | 9\n\nBy inputing a vaule when prompted. The first to 3 peices in a row wins.') player1 = input('Enter player 1\'s name: ') player2 = input('Enter player 2\'s name: ') print(player1 + ', you are O and ' + player2 + ', you are X.') nextPlayer = player1 while not(owin(cell) or xwin(cell)) and not tie(cell): print('This is the board:\n' + board) if nextPlayer == player1: move = input('\n' + player1 + ', select a number (1 - 9) to place your peice: ') cell[int(move) - 1] = 'O' board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] nextPlayer = player2 else: move = input('\n' + player2 + ', select a number (1 - 9) to place your peice: ') cell[int(move) - 1] = 'X' board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] nextPlayer = player1 if owin(cell): print('Well done, ' + player1 + ', you won!') elif xwin(cell): print('Well done, ' + player2 + ', you won!') else: print('Unfortunately, neither of you were able to win today.') input('Press &lt;enter&gt; to quit.') </code></pre>
[]
[ { "body": "<p>Some notes:</p>\n\n<blockquote>\n <p>cell = ['1', '2', '3', '4', '5', '6', '7', '8', '9']</p>\n</blockquote>\n\n<p>Try to be less verbose: <code>cell = \"123456789\".split()</code> or <code>cell = [str(n) for n in range(1, 10)]</code>. Anyway, conceptually it's very dubious you initialize the board with its number instead of its state. Also, <code>cell</code> is not a good name, it's a collection, so <code>cells</code>.</p>\n\n<pre><code>board = '\\n\\t ' + cell[0] + ...\n</code></pre>\n\n<p>Don't write such a long lines, split them to fit a sound max width (80/100/...). Anyway, here the problem is that you shouldn't do that manually, do it programmatically (<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">grouped</a> from itertools):</p>\n\n<pre><code>board = \"\\n\\t-----------\\n\\t\".join(\" | \".join(xs) for xs in grouped(cell, 3)) \n</code></pre>\n\n<blockquote>\n <p>return cell[0] == cell<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">1</a> == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">1</a> == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8]== 'O</p>\n</blockquote>\n\n<p>Ditto, use code: </p>\n\n<pre><code>groups = grouped(cell, 3)\nany(all(x == 'O' for x in xs) for xs in [groups, zip(*groups)])\n</code></pre>\n\n<p>Note that you are not checking if a cell has already a piece.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T12:23:06.963", "Id": "23787", "ParentId": "23784", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T11:42:53.097", "Id": "23784", "Score": "9", "Tags": [ "python", "game" ], "Title": "Noughts and Crosses game in Python" }
23784
<p>Here is a solution to the <a href="http://pl.spoj.com/problems/JPESEL/" rel="nofollow">SPOJ's JPESEL problem</a>. Basically the problem was to calculate cross product of 2 vectors modulo 10. If there is a positive remainder, it's not a valid <a href="http://en.wikipedia.org/wiki/PESEL" rel="nofollow">PESEL number</a>; (return <code>D</code>) if the remainder equals <code>0</code>, it's a valid number (return <code>N</code>).</p> <pre><code>import re, sys n = input() t = [1,3,7,9,1,3,7,9,1,3,1] while(n): p = map(int, re.findall('.',sys.stdin.readline())) # Another approach I've tried in orer to save some memory - didn't help: # print 'D' if sum([int(p[0]) * 1,int(p[1]) * 3,int(p[2]) * 7,int(p[3]) * 9,int(p[4]) * 1,int(p[5]) * 3,int(p[6]) * 7,int(p[7]) * 9,int(p[8]) * 1,int(p[9]) * 3,int(p[10]) * 1]) % 10 == 0 else 'N' print 'D' if ( sum(p*q for p,q in zip(t,p)) % 10 ) == 0 else 'N' n-=1 </code></pre> <p>The solution above got the following results at SPOJ:</p> <p>Time: 0.03s<br> Memory: 4.1M</p> <p>where the best solutions (submitted in Python 2.7) got:</p> <p>Time: 0.01s<br> Memory: 3.7M</p> <p>How can I optimize this code in terms of time and memory used?</p> <p>Note that I'm using different function to read the input, as <code>sys.stdin.readline()</code> is the fastest one when reading strings and <code>input()</code> when reading integers.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T17:58:26.517", "Id": "36992", "Score": "0", "body": "Why do you need to read from STDIN? I guess it will be faster with a file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:02:45.890", "Id": "36993", "Score": "0", "body": "You mean to read the whole input at once? I need STDIN because that's how the program sumbitted to SPOJ should work." } ]
[ { "body": "<p>You can try to replace <code>re</code> module with just a <code>sys.stdin.readline()</code> and replace <code>zip</code> interator with <code>map</code> and <code>mul</code> function from <a href=\"http://docs.python.org/2.7/library/operator.html\" rel=\"nofollow\">operator</a> module like this:</p>\n\n<pre><code>from sys import stdin\nfrom operator import mul\n\nreadline = stdin.readline\nn = int(readline())\nt = [1,3,7,9,1,3,7,9,1,3,1]\n\nwhile n:\n p = map(int, readline().rstrip())\n print 'D' if (sum(map(mul, t, p)) % 10) == 0 else 'N'\n n -= 1\n</code></pre>\n\n<h2>Update</h2>\n\n<p>It seems getting item from a small dictionary is faster than <code>int</code> so there is a version without <code>int</code>:</p>\n\n<pre><code>from sys import stdin\n\nreadline = stdin.readline\nval = {\"0\": 0, \"1\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6,\n \"7\": 7, \"8\": 8, \"9\": 9}\nval3 = {\"0\": 0, \"1\": 3, \"2\": 6, \"3\": 9, \"4\": 12, \"5\": 15, \"6\": 18,\n \"7\": 21, \"8\": 24, \"9\": 27}\nval7 = {\"0\": 0, \"1\": 7, \"2\": 14, \"3\": 21, \"4\": 28, \"5\": 35, \"6\": 42,\n \"7\": 49, \"8\": 56, \"9\": 63}\nval9 = {\"0\": 0, \"1\": 9, \"2\": 18, \"3\": 27, \"4\": 36, \"5\": 45, \"6\": 54,\n \"7\": 63, \"8\": 72, \"9\": 81}\n\nn = int(readline())\nwhile n:\n # Expects only one NL character at the end of the line\n p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, _ = readline()\n print 'D' if ((val[p1] + val3[p2] + val7[p3] + val9[p4]\n + val[p5] + val3[p6] + val7[p7] + val9[p8]\n + val[p9] + val3[p10] + val[p11]) % 10 == 0) else 'N'\n n -= 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T19:12:36.463", "Id": "36999", "Score": "0", "body": "Much better time: `0.02` (is it because of using `readline()` instead of `input()`?), slightly better memory: `4.0M`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T16:10:47.063", "Id": "37040", "Score": "0", "body": "(after your update) It's still slower than the best implementations on SPOJ but I've learned a few things - thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:49:19.997", "Id": "23993", "ParentId": "23981", "Score": "1" } } ]
{ "AcceptedAnswerId": "23993", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T09:30:44.913", "Id": "23981", "Score": "1", "Tags": [ "python", "optimization", "programming-challenge", "python-2.x" ], "Title": "SPOJ \"Pesel\" challemge" }
23981
<p>Looking for optimizations and cleaner, more pythonic ways of implementing the following code.</p> <pre><code>#Given an array find any three numbers which sum to zero. import unittest def sum_to_zero(a): a.sort(reverse=True) len_a = len(a) if len_a &lt; 3: return [] for i in xrange(0, len_a): j = i + 1 for k in xrange(j + 1, len_a): if a[j] + a[k] == -1 * a[i]: return [a[i], a[j], a[k]] return [] class SumToZeroTest(unittest.TestCase): def test_sum_to_zero_basic(self): a = [1, 2, 3, -1, -2, -3, -5, 1, 10, 100, -200] res = sum_to_zero(a) self.assertEqual([3, 2, -5], res, str(res)) def test_sum_to_zero_no_res(self): a = [1, 1, 1, 1] res = sum_to_zero(a) self.assertEqual(res, [], str(res)) def test_small_array(self): a = [1, 2, -3] res = sum_to_zero(a) self.assertEqual(res, [2, 1, -3], str(res)) def test_invalid_array(self): a = [1, 2] res = sum_to_zero(a) self.assertEqual(res, [], str(res)) #nosetests sum_to_zero.py </code></pre>
[]
[ { "body": "<p>Your code fails this test case:</p>\n\n<pre><code>def test_winston1(self):\n res = sum_to_zero([125, 124, -100, -25])\n self.assertEqual(res, [125,-100,-25])\n</code></pre>\n\n<p>As for the code</p>\n\n<pre><code>def sum_to_zero(a):\n a.sort(reverse=True)\n</code></pre>\n\n<p>Why sort?</p>\n\n<pre><code> len_a = len(a)\n if len_a &lt; 3:\n return []\n for i in xrange(0, len_a):\n</code></pre>\n\n<p>You can just do <code>xrange(len_a)</code>. I recommend doing <code>for i, a_i in enumerate(a)</code> to avoid having the index the array later.</p>\n\n<pre><code> j = i + 1\n</code></pre>\n\n<p>Thar be your bug, you can't assumed that j will be i + 1.</p>\n\n<pre><code> for k in xrange(j + 1, len_a):\n if a[j] + a[k] == -1 * a[i]:\n</code></pre>\n\n<p>Why this instead of <code>a[j] + a[k] + a[i] == 0</code>?</p>\n\n<pre><code> return [a[i], a[j], a[k]]\n return []\n</code></pre>\n\n<p>Not a good a choice of return value. I'd return None. An empty list isn't a natural continuation of the other outputs. </p>\n\n<p>Here is my implementation of it:</p>\n\n<pre><code>def sum_to_zero(a):\n a.sort(reverse = True)\n for triplet in itertools.combinations(a, 3):\n if sum(triplet) == 0:\n return list(triplet)\n return []\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T23:31:59.803", "Id": "37007", "Score": "1", "body": "Thanks for the feedback. I like the use of itertools.combinations... good to know." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T23:19:00.037", "Id": "23998", "ParentId": "23996", "Score": "15" } } ]
{ "AcceptedAnswerId": "23998", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T22:10:11.573", "Id": "23996", "Score": "9", "Tags": [ "python", "algorithm" ], "Title": "Given an array find any three numbers which sum to zero" }
23996
<p>i wish to improve my Progressbar in Python</p> <pre><code>from __future__ import division import sys import time class Progress(object): def __init__(self, maxval): self._seen = 0.0 self._pct = 0 self.maxval = maxval def update(self, value): self._seen = value pct = int((self._seen / self.maxval) * 100.0) if self._pct != pct: sys.stderr.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() self._pct = pct def start(self): pct = int((0.0 / self.maxval) * 100.0) sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() def finish(self): pct = int((self.maxval / self.maxval) * 100.0) sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() toolbar_width = 300 pbar = Progress(toolbar_width) pbar.start() for i in xrange(toolbar_width): time.sleep(0.1) # do real work here pbar.update(i) pbar.finish() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:05:07.600", "Id": "37061", "Score": "1", "body": "CodeReview is to get review on code which is working, not to get some help to add a feature." } ]
[ { "body": "<p>As per my comments, I've not sure SE.CodeReview is the right place to get the help you are looking for.</p>\n\n<p>However, as I didn't read your question properly at first, I had a look at your code and changed a few things (please note that it's not exactly the same behavior as it used to be):</p>\n\n<ul>\n<li>extract the display logic in a method on its own</li>\n<li>reuse update in start and finish (little changes here : this method now updates the object instead of just doing some display)</li>\n<li>removed self._seen because it didn't seem useful</li>\n</ul>\n\n<p>Here the code :</p>\n\n<pre><code>class Progress(object):\n def __init__(self, maxval):\n self._pct = 0\n self.maxval = maxval\n\n def update(self, value):\n pct = int((value / self.maxval) * 100.0)\n if self._pct != pct:\n self._pct = pct\n self.display()\n\n def start(self):\n self.update(0)\n\n def finish(self):\n self.update(self.maxval)\n\n def display(self):\n sys.stdout.write(\"|%-100s| %d%%\" % (u\"\\u2588\"*self._pct, self._pct) + '\\n')\n sys.stdout.flush()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:19:30.073", "Id": "37062", "Score": "0", "body": "Thank Josay for the review. What i wish to do is print the percentage (1%, 2%, 3%, ..., 100%) in the middle of the progress bar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:22:48.020", "Id": "37067", "Score": "0", "body": "@Gianni unfortunately, that's off-topic for Code Review. You should edit your question to be a valid code review request as defined in the [faq], otherwise it will be closed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:58:08.810", "Id": "37086", "Score": "0", "body": "@codesparkle it's a fuzzy definition about SO (= stackoverflow) or CR (code review). Normally people use this approach: code works CR, code doesn't work SO, no code Programmer. In my case the code works and i want to improve the quality. With a with a working code (no error) i think (maybe i wrong) this question is more appropriate in CD" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:11:02.147", "Id": "24024", "ParentId": "24023", "Score": "2" } } ]
{ "AcceptedAnswerId": "24024", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T23:05:03.840", "Id": "24023", "Score": "0", "Tags": [ "python", "optimization" ], "Title": "Progressbar in Python" }
24023
<p>A large .csv file I was given has a large table of flight data. A function I wrote to help parse it iterates over the column of Flight IDs, and then returns a dictionary containing the index and value of every unique Flight ID in order of first appearance.</p> <pre><code>Dictionary = { Index: FID, ... } </code></pre> <p>This comes as a quick adjustment to an older function that didn't require having to worry about <code>FID</code> repeats in the column (a few hundred thousand rows later...).</p> <p>Example:</p> <pre><code>20110117559515, ... 20110117559515, ... 20110117559515, ... 20110117559572, ... 20110117559572, ... 20110117559572, ... 20110117559574, ... 20110117559587, ... 20110117559588, ... </code></pre> <p>and so on for 5.3 million some rows.</p> <p>Right now, I have it iterating over and comparing each value in order. If a unique value appears, it only stores the first occurrence in the dictionary. I changed it to now also check if that value has already occurred before, and if so, to skip it.</p> <pre><code>def DiscoverEarliestIndex(self, number): result = {} columnvalues = self.column(number) column_enum = {} for a, b in enumerate(columnvalues): column_enum[a] = b i = 0 while i &lt; (len(columnvalues) - 1): next = column_enum[i+1] if columnvalues[i] == next: i += 1 else: if next in result.values(): i += 1 continue else: result[i+1]= next i += 1 else: return result </code></pre> <p>It's very inefficient, and slows down as the dictionary grows. The column has 5.2 million rows, so it's obviously not a good idea to handle this much with Python, but I'm stuck with it for now.</p> <p>Is there a more efficient way to write this function?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T09:20:04.877", "Id": "37238", "Score": "0", "body": "You are not always retrieving the first occurrence because \"If a value is equal to the value after it, it skips it.\"" } ]
[ { "body": "<p>One thing that slows you down is <code>if next in thegoodshit.values()</code> because it has to iterate through the values.</p>\n\n<p>A simple way to eliminate duplicate values is to first construct a dictionary where values are the key:</p>\n\n<pre><code>unique_vals = {val: i for i, val in enumerate(columnvalues)}\nreturn {i: val for val, i in unique_vals.iteritems()}\n</code></pre>\n\n<p>If there are duplicates, this will give the last index of each value, because duplicates get overwritten in the construction of <code>unique_vals</code>. To get the first index instead, iterate in reverse:</p>\n\n<pre><code>unique_vals = {val: i for i, val in reversed(list(enumerate(columnvalues)))}\nreturn {i: val for val, i in unique_vals.iteritems()}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T10:08:15.517", "Id": "24148", "ParentId": "24126", "Score": "2" } }, { "body": "<p>You've given us a small piece of your problem to review, and <a href=\"https://codereview.stackexchange.com/a/24148/11728\">Janne's suggestion</a> seems reasonable if that piece is considered on its own. But I have the feeling that this isn't the only bit of analysis that you are doing on your data, and if so, you probably want to think about using a proper database.</p>\n\n<p>Python comes with a built-in relational database engine in the form of the <a href=\"http://docs.python.org/2/library/sqlite3.html\" rel=\"nofollow noreferrer\"><code>sqlite3</code> module</a>. So you could easily read your CSV directly into a SQLite table, either using the <code>.import</code> command in SQLite's command-line shell, or via Python if you need more preprocessing:</p>\n\n<pre><code>import sqlite3\nimport csv\n\ndef load_flight_csv(db_filename, csv_filename):\n \"\"\"\n Load flight data from `csv_filename` into the SQLite database in\n `db_filename`.\n \"\"\"\n with sqlite3.connect(db_filename) as conn, open(csv_filename, 'rb') as f:\n c = conn.cursor()\n c.execute('''CREATE TABLE IF NOT EXISTS flight\n (id INTEGER PRIMARY KEY AUTOINCREMENT, fid TEXT)''')\n c.execute('''CREATE INDEX IF NOT EXISTS flight_fid ON flight (fid)''')\n c.executemany('''INSERT INTO flight (fid) VALUES (?)''', csv.reader(f))\n conn.commit()\n</code></pre>\n\n<p>(Obviously you'd need more fields in the <code>CREATE TABLE</code> statement, but since you didn't show them in your question, I can't guess what they might be.)</p>\n\n<p>And then you can analyze the data by issuing SQL queries:</p>\n\n<pre><code>&gt;&gt;&gt; db = 'flight.db'\n&gt;&gt;&gt; load_flight_csv(db, 'flight.csv')\n&gt;&gt;&gt; conn = sqlite3.connect(db)\n&gt;&gt;&gt; from pprint import pprint\n&gt;&gt;&gt; pprint(conn.execute('''SELECT MIN(id), fid FROM flight GROUP BY fid''').fetchall())\n[(1, u'20110117559515'),\n (4, u'20110117559572'),\n (7, u'20110117559574'),\n (8, u'20110117559587'),\n (9, u'20110117559588')]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T15:26:57.540", "Id": "37253", "Score": "0", "body": "Great example, sorry for skipping out on a csv information. I didn't have a good way to illustrate 41 columns by 5.3 million rows in a csv of mixed integers and strings. I've looking for an example like this, I'm still getting used to sqlite3 syntax. Upvoting as soon as I have enough rep." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T12:00:59.990", "Id": "24156", "ParentId": "24126", "Score": "3" } }, { "body": "<p>So here is what I came up with, now that I had access to a computer:</p>\n\n<p>raw_data.csv:</p>\n\n<pre><code>20110117559515,1,10,faa\n20110117559515,2,20,bar\n20110117559515,3,30,baz\n20110117559572,4,40,fii\n20110117559572,5,50,bir\n20110117559572,6,60,biz\n20110117559574,7,70,foo\n20110117559587,8,80,bor\n20110117559588,9,90,boz\n</code></pre>\n\n<p>code:</p>\n\n<pre><code>import csv\nfrom collections import defaultdict\nfrom pprint import pprint\nimport timeit\n\n\ndef method1():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n unik = set(cols[0])\n\n indexed = defaultdict(list)\n\n for x in unik:\n i = cols[0].index(x)\n indexed[i] = rows[i]\n\n return indexed\n\ndef method2():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n unik = set(cols[0])\n\n indexed = defaultdict(list)\n\n for x in unik:\n i = next(index for index,fid in enumerate(cols[0]) if fid == x)\n indexed[i] = rows[i]\n\n return indexed\n\ndef method3():\n rows = list(csv.reader(open('raw_data.csv', 'r'), delimiter=','))\n cols = zip(*rows)\n indexes = [cols[0].index(x) for x in set(cols[0])]\n\n for index in indexes:\n yield (index,rows[index])\n\n\nif __name__ == '__main__':\n\n results = method1() \n print 'indexed:'\n pprint(dict(results))\n\n print '-' * 80\n\n results = method2() \n print 'indexed:'\n pprint(dict(results))\n\n print '-' * 80\n\n results = dict(method3())\n print 'indexed:'\n pprint(results)\n\n #--- Timeit ---\n\n print 'method1:', timeit.timeit('dict(method1())', setup=\"from __main__ import method1\", number=10000)\n print 'method2:', timeit.timeit('dict(method2())', setup=\"from __main__ import method2\", number=10000)\n print 'method3:', timeit.timeit('dict(method3())', setup=\"from __main__ import method3\", number=10000)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>indexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n--------------------------------------------------------------------------------\nindexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n--------------------------------------------------------------------------------\nindexed:\n{0: ['20110117559515', '1', '10', 'faa'],\n 3: ['20110117559572', '4', '40', 'fii'],\n 6: ['20110117559574', '7', '70', 'foo'],\n 7: ['20110117559587', '8', '80', 'bor'],\n 8: ['20110117559588', '9', '90', 'boz']}\n\nmethod1: 0.283623933792\nmethod2: 0.37960600853\nmethod3: 0.293814182281\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T18:59:54.303", "Id": "37351", "Score": "0", "body": "An issue with this script, it's sucking up a TON of memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T21:26:45.067", "Id": "37373", "Score": "0", "body": "Tried with 2 other methods, but it looks like the initial one is still the fastest.\nPlease compare which is the best in terms of memory consumption on runtime, using your big data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T14:29:04.500", "Id": "37401", "Score": "0", "body": "FYI I tried to implement an 100% python way of solving your question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T20:15:10.837", "Id": "24170", "ParentId": "24126", "Score": "1" } } ]
{ "AcceptedAnswerId": "24170", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T20:40:52.533", "Id": "24126", "Score": "3", "Tags": [ "python", "performance", "parsing", "csv", "iteration" ], "Title": "Retrieving the first occurrence of every unique value from a CSV column" }
24126
<p>I am just learning how to do some multiprocessing with Python, and I would like to create a non-blocking chat application that can add/retrieve messages to/from a database. This is my somewhat primitive attempt (note: It is simplified for the purposes of this post); however, I would like to know how close/far off off the mark I am. Any comments, revisions, suggestions, etc. are greatly appreciated. </p> <p>Thank you!</p> <pre><code>import multiprocessing import Queue import time # Get all past messages def batch_messages(): # The messages list here will be attained via a db query messages = ["&gt;&gt; This is a message.", "&gt;&gt; Hello, how are you doing today?", "&gt;&gt; Really good!"] for m in messages: print m # Add messages to the DB def add_messages(q): # Retrieve from the queue message_to_add = q.get() # For testing purposes only; perfrom another DB query to add the message to the DB print "(Add to DB)" # Recieve new, inputted messages. def receive_new_message(q, new_message): # Add the new message to the queue: q.put(new_message) # Print the message to the screen print "&gt;&gt;", new_message if __name__ == "__main__": # Set up the queue q = multiprocessing.Queue() # Print the past messages batch_messages() while True: # Enter a new message input_message = raw_input("Type a message: ") # Set up the processes p_add = multiprocessing.Process(target=add_messages, args=(q,)) p_rec = multiprocessing.Process(target=receive_new_message, args=(q, input_message,)) # Start the processes p_rec.start() p_add.start() # Let the processes catch up before printing "Type a message: " again. (Shell purposes only) time.sleep(1) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:43:34.277", "Id": "37333", "Score": "0", "body": "That's quite odd that it works fine when I run it...I will look further into this. But, thank you for the feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:48:26.577", "Id": "37335", "Score": "0", "body": "I can explicitly pass it to the functions that require it, and then I assume it will work for as well, correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:48:57.300", "Id": "37336", "Score": "0", "body": "Yes, you should pass `q` as a parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T14:58:10.620", "Id": "37338", "Score": "0", "body": "`q` is now passed to the functions. Thanks." } ]
[ { "body": "<ul>\n<li>Don't create a new process for every task. Put a loop in <code>add_messages</code>; <code>q.get</code> will wait for the next task in the queue.</li>\n<li><code>receive_new_message</code> is not doing anything useful in your example. Place <code>q.put(new_message)</code> right after <code>raw_input</code> instead.</li>\n</ul>\n\n<p>:</p>\n\n<pre><code>def add_messages(q): \n while True:\n # Retrieve from the queue\n message_to_add = q.get()\n print \"(Add to DB)\"\n\nif __name__ == \"__main__\":\n q = multiprocessing.Queue()\n p_add = multiprocessing.Process(target=add_messages, args=(q,))\n p_add.start()\n\n while True: \n input_message = raw_input(\"Type a message: \")\n\n # Add the new message to the queue:\n q.put(input_message)\n\n # Let the processes catch up before printing \"Type a message: \" again. (Shell purposes only)\n time.sleep(1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T17:38:24.597", "Id": "37415", "Score": "0", "body": "Thank you for the revision! I appreciate your help. On a side note, I included the `receive_new_message` process with the thought that I would need to output messages from the queue to users' screens, and that this process should be separate from the `add_messages` (to the db) process. Is this \"concern\" a necessary one? Or can the outputting to the screen be coupled with the database querying?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T09:11:20.743", "Id": "37441", "Score": "0", "body": "@JohnZ If you need the two subprocesses, you would use two queues. For example, `receive_new_message` might read from `q1`, do some processing and forward the results to `add_messages` via `q2`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T15:33:52.110", "Id": "37443", "Score": "0", "body": "Ahhh okay. That makes sense. Thank you for the feedback!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T20:29:27.990", "Id": "24213", "ParentId": "24187", "Score": "1" } } ]
{ "AcceptedAnswerId": "24213", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T06:56:02.460", "Id": "24187", "Score": "4", "Tags": [ "python" ], "Title": "Python multiprocessing messaging code" }
24187