body
stringlengths
144
5.58k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>The code below is slow. Any thoughts on speeding up? </p> <pre><code>dict1 = {} dict2 = {} list_needed = [] for val in dict1.itervalues(): for k,v in d1ct2.iteritems(): if val == k: list_needed.append([val,v]) </code></pre>
[]
[ { "body": "<p>Perhaps,</p>\n\n<pre><code>for val in dict1.itervalues():\n if val in dict2:\n list_needed.append([val,dict2[val]])\n</code></pre>\n\n<p>This is similar to </p>\n\n<pre><code>list_needed = [[val,dict2[val]] for val in dict1.itervalues() if val in dict2]\n</code></pre>\n\n<p>My preference would be to make <code>[val,v]</code> a tuple - i.e <code>(val,v)</code> which is an immutable D.S and hence would be faster than a list. But it may not count for much.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-19T19:14:08.573", "Id": "20668", "Score": "0", "body": "like the list comprehension. But need dict2[val] for additional parse-ing" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-19T18:57:30.227", "Id": "12752", "ParentId": "12751", "Score": "4" } }, { "body": "<p>Depending on the size of the intersection expected, it might be valuable to let someone else handle the loop &amp; test:</p>\n\n<pre><code>vals = set(dict1.values())\nd2keys = set(dict2.keys())\nlist_needed = [ [val, dict2[val]) for val in vals &amp; d2keys ]\n</code></pre>\n\n<p>Or, is dict2 disposable? If so, you could do:</p>\n\n<pre><code>for k in set(dict2.keys() - set(dict1.values()):\n del dict2[k]\nlist_needed = dict2.items()\n</code></pre>\n\n<p>I just came up with those off the top of my head and have no idea how performant they really are. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T13:45:26.377", "Id": "20719", "Score": "0", "body": "list_needed = [ [val, dict2[val]) for val in vals & d2keys ] is much slower than \nlist_needed = [[val,dict2[val]] for val in dict1.itervalues() if val in dict2]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T02:38:58.353", "Id": "12760", "ParentId": "12751", "Score": "2" } } ]
{ "AcceptedAnswerId": "12752", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-19T18:45:25.203", "Id": "12751", "Score": "2", "Tags": [ "python" ], "Title": "Speed up two for-loops?" }
12751
<p>I'm a rank beginner in Python, and I am working my way through various relevant OpenCourseware modules. In response to the prompt </p> <blockquote> <p>Write a procedure that takes a list of numbers, nums, and a limit, limit, and returns a list which is the shortest prefix of nums the sum of whose values is greater than limit. Use for. Try to avoid using explicit indexing into the list.</p> </blockquote> <p>I wrote the following simple procedure</p> <pre><code>def numberlist(nums,limit): sum=0 i=0 for i in nums: sum=sum+i if sum&gt;limit: return i else: print i </code></pre> <p>It gets the job done, but the division of labor between <em>if</em> and <em>else</em> seems inelegant, as does the use of both <em>return</em> and <em>print</em>. Is there a better way to structure this basic loop? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T07:24:39.357", "Id": "20836", "Score": "0", "body": "I see now that this version was cobbling together a numberlist from the output of print and return, which would be problematic if I tried to pass the result into another function. Thanks to the commenters pointing this out!" } ]
[ { "body": "<p>Welcome to programming :) I did not understand your question first, then I realized that python might be your first language. In that case congratulations on picking a very nice language as your first language. </p>\n\n<p>Your question seems to ask for the list which is the shortest prefix of nums the sum of which is greater than the limit. Here, you might notice that it does not care about the intermediate values. Alls that the function asks is that the return value be greater than the limit. That is, this should be the output</p>\n\n<pre><code>&gt;&gt;&gt; numberlist([1,2,3,4,5], 5)\n[1,2,3]\n</code></pre>\n\n<p>No output in between. So for that goal, you need to remove the print statement in your code, and without the print, there is no need for the else. In languages like python, it is not required that there be an <code>else</code> section to an if-else conditional. Hence you can omit it. We can also use enumerate to iterate on both index and the value at index. Using all these we have,</p>\n\n<pre><code>def numberlist(nums,limit): \n sum=0 \n for index,i in enumerate(nums): \n sum += i\n if sum&gt;limit: \n return nums[:index+1]\n</code></pre>\n\n<p>Note that if you are unsatisfied with omitting the else part, you can turn it back by using <code>pass</code>. i.e</p>\n\n<pre><code> if sum&gt;limit: \n return nums[:index+1]\n else:\n pass\n</code></pre>\n\n<p>Note also that I used an array slice notation <code>nums[:index+1]</code> that means all the values from <code>0 to index+1</code> in the array <code>nums</code>\nThis is a rather nice for loop. If you are feeling more adventurous, you might want to look at list comprehensions. That is another way to write these things without using loops.</p>\n\n<p>edit: corrected for enumeration</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-19T23:20:35.213", "Id": "12755", "ParentId": "12753", "Score": "2" } }, { "body": "<p>So, a couple things:</p>\n\n<ol>\n<li><p>The problem statement says nothing about printing data, so you can omit the <code>print</code> statement, and thus the entire <code>else:</code> clause, entirely.</p></li>\n<li><p>The problem statement says to return a list, and you're just returning the last item in that list, not the entire list.</p></li>\n</ol>\n\n<p>Here's a short but inefficient way to do it:</p>\n\n<pre><code>def numberlist(nums, limit):\n i = 0\n while sum(nums[:i]) &lt; limit:\n i += 1\n return nums[:i]\n</code></pre>\n\n<p>or a more efficient but longer way:</p>\n\n<pre><code>def numberlist(nums, limit):\n prefix = []\n sum = 0\n for num in nums:\n sum += num\n prefix.append(num)\n if sum &gt; limit:\n return prefix\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T02:48:33.037", "Id": "20692", "Score": "0", "body": "I didn't realize that the question was asking for the subset. Have an upvote :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T12:26:18.953", "Id": "20712", "Score": "0", "body": "This, like blufox’ solution, uses indexing which we’ve been told to avoid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T15:46:07.787", "Id": "20725", "Score": "0", "body": "Konrad: the inefficient way does, the other way doesn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T07:27:14.237", "Id": "20837", "Score": "0", "body": "pjz: what makes the second method more efficient, in your estimation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T14:07:46.593", "Id": "20876", "Score": "0", "body": "K. Olivia: the first one runs a sum on the whole slice every time through the loop. The second only adds the newest number to the sum, which is much faster." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T02:19:28.593", "Id": "12759", "ParentId": "12753", "Score": "9" } }, { "body": "<p>The others have discussed how you aren't quite doing what the problem asks, I'll just look at your code:</p>\n\n<pre><code>def numberlist(nums,limit): \n</code></pre>\n\n<p>When the name of a function has two words it in, we recommend separate it with an _, in this case use <code>number_list</code>. Its easier to understand the name</p>\n\n<pre><code> sum=0 \n</code></pre>\n\n<p><code>sum</code> is the name of a built-in function, you should probably avoid using it</p>\n\n<pre><code> i=0 \n</code></pre>\n\n<p>This does nothing. You don't need to pre-store something in i, just use the for loop</p>\n\n<pre><code> for i in nums: \n</code></pre>\n\n<p>I really recommend against single letter variable names, it makes code hard to read</p>\n\n<pre><code> sum=sum+i \n</code></pre>\n\n<p>I'd write this as <code>sum += i</code></p>\n\n<pre><code> if sum&gt;limit: \n</code></pre>\n\n<p>I'd put space around the <code>&gt;</code> </p>\n\n<pre><code> return i \n else: \n print i\n</code></pre>\n\n<p>Your instinct is right, using both <code>return</code> and <code>print</code> is odd. As the others have noted, you shouldn't be printing at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T12:33:58.633", "Id": "20715", "Score": "0", "body": "I generally agree about the one-letter variable names but there’s a broad consensus that they’re OK as simple loop variables (among others) – even though `i` is conventionally reserved for indices …" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T15:16:24.517", "Id": "20722", "Score": "0", "body": "@KonradRudolph, I disagree with the consensus. But yes, there is one." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T04:08:16.980", "Id": "12761", "ParentId": "12753", "Score": "5" } }, { "body": "<blockquote>\n <p>Try to avoid using explicit indexing into the list.</p>\n</blockquote>\n\n<p>This part in the question was ignored in the other (good) answers. Just to fix this small shortcoming, you can write a <a href=\"http://www.python.org/dev/peps/pep-0255/\" rel=\"nofollow\">generator</a> which avoids indexing completely:</p>\n\n<pre><code>def numberlist(nums, limit):\n sum = 0\n for x in nums:\n sum += x\n yield x\n if sum &gt; limit:\n return\n</code></pre>\n\n<p>This will return an iterator that, when iterated over, will consecutively yield the desired output:</p>\n\n<pre><code>&gt;&gt;&gt; for x in numberlist([2, 4, 3, 5, 6, 2], 10):\n... print x,\n... \n2 4 3 5\n</code></pre>\n\n<p>However, strictly speaking this violates another requirement, “returns a list” – so we need to wrap this code into another method:</p>\n\n<pre><code>def numberlist(nums, limit):\n def f(nums, limit):\n sum = 0\n for x in nums:\n sum += x\n yield x\n if sum &gt; limit:\n return\n\n return list(f(nums, limit))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T12:32:46.653", "Id": "12828", "ParentId": "12753", "Score": "6" } }, { "body": "<p><strong>I just started programming in Python (well in general) a week ago</strong></p>\n\n<p>This is the analogy I used to make sense of the problem. </p>\n\n<blockquote>\n <p>You have a word like Monday. Each character in the word has a value:\n 'M' = 1, 'o' = 2, n = '3', d = '4', a = '5', y = '6'. If you added the value of each character in the word 'Monday' it would be:\n 1 + 2 + 3 + 4 + 5 + 6 = 21\n So the 'numerical value' of Monday would be 21</p>\n</blockquote>\n\n<p>Now you have a limit like 9</p>\n\n<blockquote>\n <p>The question is asking you to create a program that takes a list of numbers like [1, 2, 3, 4, 5, 6]\n And find out how many of these numbers (starting from the left because prefix means the beginning of word or in this case the list – which starts from the left i.e. 1) can be added together before their sum is greater than the limit.\n The answer would be the sum of the numbers 1, 2, 3 and 4 which is 10.\n Your prefix is the list [1, 2, 3, 4]</p>\n</blockquote>\n\n<pre><code>num = [1,2,3,4,5,6]\n\nlimit = 9\n\ndef prefixLimit(limit, num):\n sumOfPrefix = 0\n prefix = [] \n for i in num:\n if sumOfPrefix &lt; limit:\n sumOfPrefix = sumOfPrefix + i\n prefix.append(i)\n if sumOfPrefix &gt; limit:\n return prefix\n\nprint(prefixLimit(limit, num))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-01T12:47:06.010", "Id": "262502", "Score": "0", "body": "This is not a review of the provided code. At Code Review, we expect all answers to be reviews." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-03T11:16:54.647", "Id": "262877", "Score": "0", "body": "I would appreciate clarity as to what I did wrong. *I'm new to this - forum, programming - any help will be greatly beneficial to my progress*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-03T16:06:47.270", "Id": "262913", "Score": "0", "body": "Sure, take a look at the [help/how-to-answer](http://codereview.stackexchange.com/help/how-to-answer)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-01T10:29:18.493", "Id": "140196", "ParentId": "12753", "Score": "0" } } ]
{ "AcceptedAnswerId": "12759", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-19T21:54:02.620", "Id": "12753", "Score": "4", "Tags": [ "python", "beginner" ], "Title": "Taking the first few items of a list until a target sum is exceeded" }
12753
<p>How can this be improved?</p> <pre><code>def quick_sort(temp_list): #Check if the array is having one element or not if len(temp_list) == 1: return temp_list elif len(temp_list) &gt;= 2: l_list = list() g_list = list() #Choose a pivot if len(temp_list) % 2 == 0: pivot = temp_list[len(temp_list)/2 - 1] else: pivot = temp_list[len(temp_list)/2] #Make two list greater and lesser than the pivot for e in temp_list: if e &lt; pivot: l_list.append(e) elif e &gt; pivot: g_list.append(e) #Merge the two list with the pivot return merge(quick_sort(l_list),pivot,quick_sort(g_list)) def merge(list1,mid,list2): newlist = list() if not list1 and list2: newlist.append(mid) newlist.extend(list2) if not list2 and list1: newlist.extend(list1) newlist.append(mid) if list1 and list2 : newlist.extend(list1) newlist.append(mid) newlist.extend(list2) return newlist </code></pre>
[]
[ { "body": "<p>Some changes to your code, First, your code didn't handle the case of empty list very well. This was why you need a complicated merge. (Also, the operation is not really a merge. A merge kind of means interleaving.)</p>\n\n<pre><code>def quick_sort(temp_list):\n if len(temp_list) &lt;= 1: return temp_list\n pivot = temp_list[len(temp_list)/2 - (1 if len(temp_list) % 2 == 0 else 0) ]\n l_list = list()\n g_list = list()\n</code></pre>\n\n<p>by keeping a list of values equal to pivot, you can ensure that your sort works even if there are non unique values.</p>\n\n<pre><code> m_list = list()\n for e in temp_list:\n if e &lt; pivot:\n l_list.append(e)\n elif e &gt; pivot:\n g_list.append(e)\n else:\n m_list.append(e)\n return concat([quick_sort(l_list),m_list,quick_sort(g_list)])\n\ndef concat(ll):\n res = list()\n for l in ll: res.extend(l)\n return res\n\n\nprint quick_sort([8,4,5,2,1,7,9,10,4,4,4])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T11:45:40.080", "Id": "20703", "Score": "0", "body": "Quicksort isn’t necessarily in-place, and it *never* has constant space requirement. – http://stackoverflow.com/a/4105155/1968" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T12:12:39.673", "Id": "20707", "Score": "0", "body": "@KonradRudolph thanks, I removed that line." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T08:07:02.823", "Id": "12768", "ParentId": "12765", "Score": "4" } }, { "body": "<h1>On Style</h1>\n\n<ul>\n<li><p><a href=\"http://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow\">“Quicksort”</a> is customarily written as one word – the method should be called <code>quicksort</code>, not <code>quick_sort</code>. What’s more, this is an implementation detail and a public API shouldn’t reveal this (it’s subject to change), hence <code>sort</code> would be an even better name.</p></li>\n<li><p>Some of your comments are redundant: “Check if the array is having one element or not” – that is (and should be!) obvious from the code. Don’t comment here. Reserve comments to explain <em>why</em> you do something. The next comment (“choose a pivot”) is better since that’s not immediately obvious from the code. However, it would be better to <em>make</em> it obvious in code and maybe have a comment describe <em>how</em> you choose the pivot (e.g. simple median).</p>\n\n<p>The other comments are redundant again.</p></li>\n<li><p>Furthermore, indenting the comments to the correct level would increase readability. As it stands, the comments visually hack the code into pieces.</p></li>\n<li><p>Names: <code>l_list</code> and <code>g_list</code> contain unnecessary information that would easily be inferred from context – <code>list</code>, and their actual function is codified in just one letter. Rename them to <code>lesser</code> and <code>greater</code> or similar.</p>\n\n<p><code>temp_list</code> as a parameter is actually wrong: it’s not really temporary, it’s just the input. And again, <code>list</code> is a bit redundant. In fact, a one-letter identifier is acceptable here (but that’s the exception!). How about <code>a</code> for “array”?</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><p>Use the idiomatic <code>[]</code> instead of <code>list()</code> to initialise lists.</p></li>\n<li><p>The first <code>elif</code> is unnecessary, and causes the subsequent code to be indented too much. Remove it. (Also, it should logically be an <code>else</code>, not an <code>elif</code>).</p></li>\n<li><p>Your choice of the pivot is a bit weird. Why two cases? Why not just use the middle? <code>pivot = a[len(a) // 2]</code></p></li>\n<li><p>Your code discards duplicate elements: <code>quick_sort([1, 2, 3, 2])</code> will yield <code>[1, 2, 3]</code>.</p></li>\n<li><p>blufox has already remarked that your <code>merge</code> routine is more convoluted than necessary. In fact, you could just use concatenation here, <code>lesser + [pivot] + greater</code> (but this again discards duplicates)</p></li>\n<li><p>It’s also a good idea to explicitly comment invariants in such algorithmic code.</p></li>\n</ul>\n\n<h1>Putting It Together</h1>\n\n<pre><code>import itertools\n\ndef sort(a):\n def swap(i, j):\n tmp = a[i]\n a[i] = a[j]\n a[j] = tmp\n\n if len(a) &lt; 2:\n return a\n\n lesser = []\n greater = []\n # Swap pivot to front so we can safely ignore it afterwards.\n swap(0, len(a) // 2)\n pivot = a[0]\n\n # Invariant: lesser &lt; pivot &lt;= greater\n for x in itertools.islice(a, 1, None):\n if x &lt; pivot:\n lesser.append(x)\n else:\n greater.append(x)\n\n return sort(lesser) + [pivot] + sort(greater)\n</code></pre>\n\n<h1>Bonus: Algorithmic Considerations</h1>\n\n<p>As blufox noted, this implementation requires more additional memory than necessary. This is acceptable when working with immutable data structures, but becomes quite expensive when used with mutable arrays.</p>\n\n<p>A normal, mutable quicksort implementation consists of two steps:</p>\n\n<ol>\n<li>in-place partitioning along a pivot</li>\n<li>recursive sorting of the two partitions</li>\n</ol>\n\n<p>The second step is trivial; the partitioning and choice of pivot however require some sophistication, otherwise they will have degenerate worst cases (even without considering the worst-case input “sorted array”). The definitive paper in this regard is <a href=\"http://www.cs.fit.edu/~pkc/classes/writing/samples/bentley93engineering.pdf\" rel=\"nofollow\"><em>Engineering a sort function</em></a> by Bentley and McIlroy. It is one of the clearest, most thorough computer science papers ever written and I heartily recommend its reading.</p>\n\n<p>That said, no “toy” implementation will ever replace an industry-strength implementation and attempting to do so is largely a waste of time, so it’s entirely reasonable to deliberately simplify an implementation by ignoring some performance considerations.</p>\n\n<p>In this regard the implementation above fares quite well. Just for the gained understanding I would still suggest that you attempt writing a variant which uses an <a href=\"http://en.wikipedia.org/wiki/Quicksort#In-place_version\" rel=\"nofollow\">in-place partitioning step</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T12:15:30.887", "Id": "12825", "ParentId": "12765", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T06:47:59.967", "Id": "12765", "Score": "7", "Tags": [ "python", "quick-sort" ], "Title": "Quick sort in Python" }
12765
<p>I am new to Python and want to have a "pythonic" coding style from the very beginning. Following is a piece of codes I wrote to generate all combinations and permutations of a set of symbols, e.g. <code>abc</code> or <code>123</code>. I mainly seek for suggestions on code style but comments on other aspects of codes are also welcome. </p> <pre><code>import random as rd import math as m def permutationByRecursion(input, s, li): if len(s) == len(input): li.append(s) for i in range(len(input)): if input[i] not in s: s+=input[i] permutationByRecursion(input, s, li) s=s[0:-1] def combinationByRecursion(input, s, idx, li): for i in range(idx, len(input)): s+=input[i] li.append(s) print s, idx combinationByRecursion(input, s, i+1, li) s=s[0:-1] def permutationByIteration(input): level=[input[0]] for i in range(1,len(input)): nList=[] for item in level: nList.append(item+input[i]) for j in range(len(item)): nList.append(item[0:j]+input[i]+item[j:]) level=nList return nList def combinationByIteration(input): level=[''] for i in range(len(input)): nList=[] for item in level: nList.append(item+input[i]) level+=nList return level[1:] res=[] #permutationByRecursion('abc', '', res) combinationByRecursion('abc', '', 0, res) #res=permutationByIteration('12345') print res print combinationByIteration('abc') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T07:18:53.517", "Id": "20745", "Score": "1", "body": "Just in case you didn't know, python has permutations and combinations in itertools package in stdlib." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T14:54:13.820", "Id": "20881", "Score": "0", "body": "@blufox, i am aware of it, just wrote the program for practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T09:40:04.770", "Id": "21498", "Score": "0", "body": "@pegasus, I know blufox and cat_baxter pointed out itertools and I assume you've seen it but for anybody else [the python docs contain](http://docs.python.org/library/itertools.html#itertools.permutations) code samples for both permutation and combination" } ]
[ { "body": "<p>Just use the standard modules :)</p>\n\n<pre><code>import itertools\nfor e in itertools.permutations('abc'):\n print(e)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T14:55:29.370", "Id": "20882", "Score": "1", "body": "thanks, I am aware of it. Just wrote it for practicing python" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T07:08:48.337", "Id": "12860", "ParentId": "12858", "Score": "10" } }, { "body": "<p>A small change, In python, it is more idiomatic to use generators to generate items rather than to create lists fully formed. So,</p>\n\n<pre><code>def combinationG(input):\n level=['']\n</code></pre>\n\n<p>You could directly enumerate on each character here.</p>\n\n<pre><code> for v in input:\n nList=[]\n for item in level:\n new = item + v\n</code></pre>\n\n<p>Yield is the crux of a generator.</p>\n\n<pre><code> yield new\n nList.append(new)\n level+=nList\n</code></pre>\n\n<p>Using it </p>\n\n<pre><code>print list(combinationG(\"abc\"))\n</code></pre>\n\n<p>Note that if you want access to both index and value of a container you can use <code>for i,v in enumerate(input)</code></p>\n\n<p>Here is the recursive implementation of permutation. Notice that we have to yield on the value returned by the recursive call too.</p>\n\n<pre><code>def permutationG(input, s):\n if len(s) == len(input): yield s\n for i in input:\n if i in s: continue\n s=s+i\n for x in permutationG(input, s): yield x\n s=s[:-1]\n\n\nprint list(permutationG('abc',''))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T07:34:18.240", "Id": "12862", "ParentId": "12858", "Score": "7" } } ]
{ "AcceptedAnswerId": "12862", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T04:47:38.713", "Id": "12858", "Score": "8", "Tags": [ "python", "reinventing-the-wheel" ], "Title": "Generating all combinations and permutations of a set of symbols" }
12858
<p><strong>Problem</strong> Starting in the top left corner of a 22 grid, there are 6 routes (without backtracking) to the bottom right corner.</p> <p><img src="https://i.stack.imgur.com/VN3Ue.gif" alt="enter image description here"> How many routes are there through a 2020 grid?</p> <p><strong>Solution</strong> Here is my solution</p> <pre><code> def step(i,j): if(i==20 or j==20): return 1 return step(i+1,j)+step(i,j+1) print step(0,0) </code></pre> <p>But this takes too long to run, how can this be optimized?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T07:51:30.230", "Id": "20746", "Score": "2", "body": "How to add memoization? Write a decorator to store the results. This is a common homework problem so I'll leave it at that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T08:04:52.757", "Id": "20747", "Score": "0", "body": "@JeffMercado I tried doing that and it wasn't working, but it worked now :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T08:10:23.140", "Id": "20748", "Score": "0", "body": "a google search returns http://en.wikipedia.org/wiki/Central_binomial_coefficient" } ]
[ { "body": "<p>Finally my memoization technique worked and the result appears in less than a sec</p>\n\n<pre><code> cache = []\nfor i in range(20):\n cache.append([])\n for j in range(20):\n cache[i].append(0)\n\ndef step(i,j):\n if(i==2 or j==2):\n return 1\n if(cache[i][j]&gt;0):\n return cache[i][j]\n cache[i][j] = step(i+1,j)+step(i,j+1)\n return cache[i][j]\nprint step(0,0)\n</code></pre>\n\n<p>Another optimization I have added (since step(i,j) is same as step(j,i)) </p>\n\n<pre><code> cache = []\nfor i in range(20):\n cache.append([])\n for j in range(20):\n cache[i].append(0)\n\ndef step(i,j):\n if(i==20 or j==20):\n return 1\n if(cache[i][j]&gt;0):\n return cache[i][j]\n cache[i][j] = step(i+1,j)+step(i,j+1)\n cache[j][i] = cache[i][j]\n return cache[i][j]\nprint step(0,0)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T08:04:15.927", "Id": "12863", "ParentId": "12861", "Score": "3" } } ]
{ "AcceptedAnswerId": "12863", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T07:29:44.907", "Id": "12861", "Score": "2", "Tags": [ "python", "project-euler" ], "Title": "How do I add memoization to this problem?" }
12861
<p>I've been learning Python 2.7 for about a week now and have written a quick program to ask for names of batters and printing a score sheet. I have then added the names to a list which I will use more in other future functions.</p> <p>I have a few questions:</p> <ol> <li><p>I feel like there is too much repetition in my code, such as the prompting for each batter and all the printing. I am trying to figure out how I could use a loop to do these for me. Since I know I need 11 batters a <code>for</code> loop would be best but I need to make a new variable each time, how can I do this?</p></li> <li><p>I have been reading around about the use of <code>global</code>. I can't seem to get a definite answer but is this the correct use if I want to use a variable from one function in multiple others?</p></li> </ol> <p></p> <pre><code>def Input_Players(): global First, Second, Third, Fourth, Fith, Sixth, Seventh, Eigth, Ninth, Tenth, Eleventh First = [raw_input("Name of 1st Batsman &gt; ")] Second = [raw_input("Name of 2nd Batsman &gt; ")] Third = [raw_input("Name of 3rd Batsman &gt; ")] Fourth = [raw_input("Name of 4th Batsman &gt; ")] Fith = [raw_input("Name of 5th Batsman &gt; ")] Sixth = [raw_input("Name of 6th Batsman &gt; ")] Seventh = [raw_input("Name of 7th Batsman &gt; ")] Eigth = [raw_input("Name of 8th Batsman &gt; ")] Ninth = [raw_input("Name of 9th Batsman &gt; ")] Tenth = [raw_input("Name of 10th Batsman &gt; ")] Eleventh = [raw_input("Name of 11th Batsman &gt; ")] def Print_Score_Sheet(): total_chars = 56 Batsman = First + Second + Third + Fourth + Fith + Sixth + Seventh + Eigth + Ninth + Tenth + Eleventh print "1." + Batsman[0] + "." * (total_chars - len(Batsman[0]) + 2) print "2." + Batsman[1] + "." * (total_chars - len(Batsman[1]) + 2) print "3." + Batsman[2] + "." * (total_chars - len(Batsman[2]) + 2) print "4." + Batsman[3] + "." * (total_chars - len(Batsman[3]) + 2) print "5." + Batsman[4] + "." * (total_chars - len(Batsman[4]) + 2) print "6." + Batsman[5] + "." * (total_chars - len(Batsman[5]) + 2) print "7." + Batsman[6] + "." * (total_chars - len(Batsman[6]) + 2) print "8." + Batsman[7] + "." * (total_chars - len(Batsman[7]) + 2) print "9." + Batsman[8] + "." * (total_chars - len(Batsman[8]) + 2) print "10." + Batsman[9] + "." * (total_chars - len(Batsman[9]) + 1) print "11." + Batsman[10] + "." * (total_chars - len(Batsman[10]) + 1) Input_Players() Print_Score_Sheet() </code></pre>
[]
[ { "body": "<p>If you find yourself using serialized variable names (player1, player2, etc) it is a pretty sure sign you should be using a list or dictionary instead.</p>\n\n<p>Global is useful if, in a function, you are using a variable from a higher scope and need to store changes back to it. In most cases, it is better to return the result from the function instead of trying to 'smuggle it out' this way.</p>\n\n<pre><code>def get_player(n):\n return raw_input('Name of Batsman {} &gt; '.format(n)).strip()\n\ndef get_players(num_players=11):\n return [get_player(i) for i in xrange(1,num_players+1)]\n\ndef score_sheet(players, width=56, fillchar='.'):\n lines = ('{}. {} '.format(*x).ljust(width, fillchar) for x in enumerate(players, 1))\n return '\\n'.join(lines)\n\ndef main():\n print score_sheet(get_players())\n\nif __name__==\"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T20:49:12.150", "Id": "20771", "Score": "0", "body": "It is in functions, just not indented." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T20:58:32.053", "Id": "20772", "Score": "1", "body": "Writing your own rightfill is redundant: you could utilise something similar to format('test', '.<56')" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T21:06:36.357", "Id": "20773", "Score": "0", "body": "@Jon Clements: thank you, I was not aware of that. Updated to incorporate it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T21:20:53.197", "Id": "20774", "Score": "0", "body": "@Jon Clements: on second thought, I prefer Blender's str.ljust() - but still, it was a good suggestion." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T20:48:31.777", "Id": "12890", "ParentId": "12889", "Score": "2" } }, { "body": "<p>I would structure the code like this:</p>\n\n<pre><code>def input_players(total=11):\n players = []\n\n for index in range(total):\n player = raw_input('Name of Batsman {} &gt; '.format(index + 1))\n players.append(player)\n\n return players\n\ndef print_score_sheet(batsmen, total_chars=56):\n for index, batsman in enumerate(batsmen, 1):\n print '{}. {} '.format(index, batsman).ljust(total_chars, fillchar='.')\n\nif __name__ == '__main__':\n players = input_players(11)\n print_score_sheet(players)\n</code></pre>\n\n<p>Some tips:</p>\n\n<ul>\n<li>If you use a set of variables like <code>Player1</code>, <code>Player2</code>, <code>PlayerN</code>, you should be using a <code>list</code> to store them.</li>\n<li>Your functions should do what they say. <code>input_players()</code> should return a list of players, nothing more, nothing less.</li>\n<li>Get into the habit of including the <code>if __name__ == '__main__':</code> block. The stuff inside of the block is executed only if you run the Python script directly, which is good if you have multiple modules.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T21:07:13.190", "Id": "20775", "Score": "5", "body": "Minor improvement, you could use `enumerate(batsmen, 1)` which would avoid having to use `index + 1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T21:08:31.273", "Id": "20776", "Score": "0", "body": "Thanks, I didn't know there was a better way of doing the `i + 1` thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T00:13:31.260", "Id": "20777", "Score": "1", "body": "Another tip I'd add is that the OP should look at [PEP 8](http://www.python.org/dev/peps/pep-0008/), purely to get a feel for Python conventions with regard to naming. His current use of initial caps will confuse experienced devs expecting classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T07:06:32.520", "Id": "20778", "Score": "0", "body": "Thanks for the help. Yes it looks like I need to read up a bit more on manipulating lists, that .append looks like exactly what I need." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T20:52:56.237", "Id": "12891", "ParentId": "12889", "Score": "13" } } ]
{ "AcceptedAnswerId": "12891", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T20:45:44.867", "Id": "12889", "Score": "5", "Tags": [ "python", "python-2.x" ], "Title": "Printing a score sheet for baseball batters" }
12889
<pre><code>count = 0 def merge_sort(li): if len(li) &lt; 2: return li m = len(li) / 2 return merge(merge_sort(li[:m]), merge_sort(li[m:])) def merge(l, r): global count result = [] i = j = 0 while i &lt; len(l) and j &lt; len(r): if l[i] &lt; r[j]: result.append(l[i]) i += 1 else: result.append(r[j]) count = count + (len(l) - i) j += 1 result.extend(l[i:]) result.extend(r[j:]) return result unsorted = [10,2,3,22,33,7,4,1,2] print merge_sort(unsorted) print count </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T07:12:44.690", "Id": "20833", "Score": "0", "body": "Do you mean it to be a simple code review? Or is there any specific aspect of the code that you would like reviewed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T07:16:05.713", "Id": "20834", "Score": "0", "body": "I just want the code to be minimalistic and also readable... so if there is any improvement in that aspect then I would definitely like some positive criticism." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T09:56:28.700", "Id": "20853", "Score": "0", "body": "The code doesn't work as expected: change unsorted -> u_list" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-18T08:14:34.127", "Id": "198165", "Score": "1", "body": "Some of the following suggestions make the error of using pop(0). Unlike pop(), which pops the last element and takes O(1), s.pop(0) gives O(n) runtime (rearranging the positions of all other elements). This breaks the algorithmic O(nlogn) concept and turns the runtime to O(n^2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-19T05:56:02.943", "Id": "198323", "Score": "0", "body": "Added my own version for codereview here: http://codereview.stackexchange.com/questions/107928/inversion-count-via-divide-and-conquer" } ]
[ { "body": "<p>Rather than a global count, I would suggest using either a parameter, or to return a tuple that keeps the count during each recursive call. This would also assure you thread safety.</p>\n\n<pre><code>def merge_sort(li, c):\n if len(li) &lt; 2: return li \n m = len(li) / 2 \n return merge(merge_sort(li[:m],c), merge_sort(li[m:],c),c) \n\ndef merge(l, r, c):\n result = []\n</code></pre>\n\n<p>Since l and r are copied in merge_sort, we can modify them without heart burn. We first reverse the two lists O(n) so that we can use <em>s.pop()</em> from the correct end in O(1) (Thanks to @ofer.sheffer for pointing out the mistake).</p>\n\n<pre><code> l.reverse()\n r.reverse()\n while l and r:\n s = l if l[-1] &lt; r[-1] else r\n result.append(s.pop())\n</code></pre>\n\n<p>Counting is separate from the actual business of merge sort. So it is nicer to move it to a separate line.</p>\n\n<pre><code> if (s == r): c[0] += len(l)\n</code></pre>\n\n<p>Now, add what ever is left in the array</p>\n\n<pre><code> rest = l if l else r\n rest.reverse()\n result.extend(rest)\n return result\n\n\nunsorted = [10,2,3,22,33,7,4,1,2]\n</code></pre>\n\n<p>Use a mutable DS to simulate pass by reference.</p>\n\n<pre><code>count = [0]\nprint merge_sort(unsorted, count)\nprint count[0]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-18T08:12:34.617", "Id": "198163", "Score": "0", "body": "Unlike pop(), which pops the last element and takes O(1), s.pop(0) gives O(n) runtime (rearranging the positions of all other elements). This breaks the algorithmic O(nlogn) concept and turns the runtime to O(n^2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-18T23:02:03.943", "Id": "198284", "Score": "0", "body": "Thank you, I did not realize that. Since it is a major problem, would you like to make an answer of your own (I will note your comment in my answer, and point to yours if you do that)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-19T06:00:39.847", "Id": "198324", "Score": "0", "body": "I added my own version for code review here: http://codereview.stackexchange.com/questions/107928/inversion-count-via-divide-and-conquer - I used a loop over k values (subarray). For each of them I run \"A[write_index]=value\" which is O(1)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T18:13:23.393", "Id": "12956", "ParentId": "12922", "Score": "7" } } ]
{ "AcceptedAnswerId": "12956", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T06:29:05.900", "Id": "12922", "Score": "9", "Tags": [ "python", "homework", "mergesort" ], "Title": "Inversion count using merge sort" }
12922
<p>I have a working script that I wrote in Python which for e-mail messages that consist only of a plain text part + an HTML part, discards the HTML and keeps only the plain text part.</p> <p>The script is not exactly elegant and, as can be seen from the code, it smells like it is C (in particular, I simulate the use of bitmasks) and I am not exactly satisfied with some points of it.</p> <p>I know that the script has some issues (like code duplication and the hack mentioned above), but I don't know the idiomatic Pythonic way of writing it and I would appreciate <em>any</em> kind of criticism to improve it in any way to make the code elegant.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: Rogério Theodoro de Brito &lt;rbrito@ime.usp.br&gt; License: GPL-2+ Copyright: 2010-2012 Rogério Theodoro de Brito drop-alternatives is a simple Python script for those who hate emails in HTML and who prefer their inbox to have as many messages in pure text as feasible. This script is generally meant to be run as a filter with procmail or some other mail delivery agent. It tries to be moderately conservative and only act when things are moderately safe: * If the message is `multipart` and has a `text/plain` and a `text/html` part, keep the `text/plain` part only. * In all other cases keep the message intact. """ import email import email.message def compose_message(orig, body): """ Create new message with headers from `orig` and body from `body`. * `orig`: The original message. * `body`: The body that we want the new message to have. * Returns a new message. `compose_message` creates a new message with most of the fields from `orig`, with fields from `body` (if any) and with the payload of `body`. The fields excluded from `orig` are the following: * `content-length` * `content-type` * `lines` * `status` """ wanted = email.message.Message() wanted.set_payload(body.get_payload()) unwanted_fields = ["content-length", "content-type", "lines", "status"] # The dictionaries `orig` and `body` have only headers as their items. for field in unwanted_fields: del orig[field] for k, v in orig.items(): wanted[k] = v for k, v in body.items(): wanted[k] = v return wanted def sanitize(msg): """ Given an RFC-2822 message `msg`, generate its 'sanitized' version. * `msg`: The message to be sanitized. * Returns a sanitized version of `msg`. `sanitize` tries to be moderately conservative and only act when things are moderately safe: * If the message is multipart and has a `text/plain` and a `text/html` part, keep the `text/plain` part only. * In all other cases keep the message intact. """ if not msg.is_multipart(): return msg # 'composition' is a bitmask containing the kind of the parts TEXTPLAIN = 1 # text/plain TEXTHTML = 2 # text/html MISCPARTS = 4 # anything else composition = 0 text_taken = False for part in msg.walk(): if (part.get_content_maintype() == "multipart" or part.get_content_type() == "message/external-body" or part.get_payload() == ""): continue elif part.get_content_type() == "text/plain": if not text_taken: text_taken = True body = part composition |= TEXTPLAIN else: # if we are seeing a second text/plain part, stop throwing # things composition |= MISCPARTS break elif part.get_content_type() == "text/html": composition |= TEXTHTML else: composition |= MISCPARTS if composition == (TEXTPLAIN + TEXTHTML) or composition == TEXTPLAIN: return compose_message(msg, body) else: return msg if __name__ == "__main__": import sys res = sanitize(email.message_from_file(sys.stdin)) print res.as_string(unixfrom=False), </code></pre>
[]
[ { "body": "<p>I think the code is quite fine as it is. Some small notes:</p>\n\n<pre><code>if composition == (TEXTPLAIN + TEXTHTML) or composition == TEXTPLAIN:\n</code></pre>\n\n<p>Just to make sure: this code tests that <code>TEXTPLAIN</code> is set and that <code>MISCPARTS</code> is <em>not</em> set. I would make that explicit, otherwise this code is hard to understand (in particular, it’s easy to miss that <code>MISCPARTS</code> mustn’t be set):</p>\n\n<pre><code>if (composition &amp; TEXTPLAIN) != 0 and (composition &amp; MISCPARTS) == 0:\n</code></pre>\n\n<p>If you’re not happy with bit operations, you can a <code>set</code> instead.</p>\n\n<pre><code>composition = set()\n\n# …\n\nif TEXTPLAIN in composition and MISCPARTS not in composition:\n</code></pre>\n\n<p>… and define <code>TEXTPLAIN</code> etc. as simple consecutive constants rather than bitmasks.</p>\n\n<p>This is more pythonic certainly, but I actually find the use of bit masks entirely appropriate here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T15:58:37.837", "Id": "21032", "Score": "0", "body": "Thanks, @Konrad. I thought that the bitfields would be condemned in python, but as you mention right now, they even feel a bit natural. BTW, in C I would use an enum for the constants. Is there any Pythonic idiom with the same \"flavour\" as C's enums?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T12:22:09.787", "Id": "12970", "ParentId": "12967", "Score": "3" } } ]
{ "AcceptedAnswerId": "12970", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T09:04:48.460", "Id": "12967", "Score": "4", "Tags": [ "python", "email" ], "Title": "Script to drop HTML part of multipart/mixed e-mails" }
12967
<p>For reasons unknown I've recently taken up generating word squares, or more accurately <a href="http://en.wikipedia.org/wiki/Word_square#Double_word_squares" rel="nofollow">double word squares</a>. Below you can see my implementation in Python, in about 40 lines. The code uses this <a href="http://github.com/causes/puzzles/raw/master/word_friends/word.list" rel="nofollow">word list</a>. It takes around 10ms for dim=2 (2x2 word squares) and around 13 seconds for dim=3 (3x3 squares). For dim=4 it explodes to something like 3.5 hours in cpython, and causes a MemoryError in pypy. For dim=20 and dim=21 it returns 0 solutions in a few seconds, but for dim=18 and dim=19 it causes a MemoryError in both pypy and cpython.</p> <p>So, I am looking for improvements that will allow me to explore values of dim >4, but also to explore ways of solving the MemoryErrors for the values &lt;20. Small improvements of a few %, improvements in how things are expressed, as well as large improvements in the algorithm are all welcome.</p> <pre><code>import time start = time.clock() dim = 3 #the dimension of our square posmax = dim**2 #maximum positions on a dim*dim square words = open("word.list").read().splitlines() words = set([w for w in words if len(w)==dim]) print 'Words: %s' % len(words) prefs = {} for w in words: for i in xrange(0,dim): prefs[w[:i]] = prefs.get(w[:i], set()) prefs[w[:i]].add(w[i]) sq, options = ['' for i in xrange(dim)], {} for i in prefs: for j in prefs: options[(i,j)] = [(i+o, j+o) for o in prefs[i] &amp; prefs[j]] schedule = [(p/dim, p%dim) for p in xrange(posmax)] def addone(square, isquare, position=0): if position == posmax: yield square else: x,y = schedule[position] square2, isquare2 = square[:], isquare[:] for o in options[(square[x], isquare[y])]: square2[x], isquare2[y] = o for s in addone(square2, isquare2, position+1): yield s print sum(1 for s in addone(sq, sq[:])) print (time.clock() - start) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T14:36:13.857", "Id": "21148", "Score": "0", "body": "Would you like to find all word squares or just the first one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T08:04:05.923", "Id": "21199", "Score": "0", "body": "it's currently geared towards finding all squares. Finding one would be acceptable if all wasn't feasible." } ]
[ { "body": "<p>Am working on a few minor improvements, but I think the major saving to be had is in removing the line </p>\n\n<pre><code>square2, isquare2 = square[:], isquare[:]\n</code></pre>\n\n<p>Instead, do</p>\n\n<pre><code>sofar = square[x], isquare[y]\nfor o in options[sofar]:\n square[x], isquare[y] = o\n for s in addone(square, isquare, position+1):\n yield s\nsquare[x], isquare[y] = sofar\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:33:23.047", "Id": "20953", "Score": "0", "body": "great idea Paul! Gave a nice ~10% boost." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T14:52:40.600", "Id": "12977", "ParentId": "12974", "Score": "4" } }, { "body": "<pre><code>import time\nstart = time.clock()\n\ndim = 3 #the dimension of our square\nposmax = dim**2 #maximum positions on a dim*dim square\n</code></pre>\n\n<p>Python convention is to have constants be in ALL_CAPS</p>\n\n<pre><code>words = open(\"word.list\").read().splitlines()\n</code></pre>\n\n<p>Actually, a file iterates over its lines so you can do <code>words = list(open(\"words.list\"))</code></p>\n\n<pre><code>words = set([w for w in words if len(w)==dim])\n</code></pre>\n\n<p>I'd make it a generator rather then a list and combine the previous two lines</p>\n\n<pre><code>print 'Words: %s' % len(words)\n</code></pre>\n\n<p>It is generally preferred to do any actual logic inside a function. Its a bit faster and cleaner</p>\n\n<pre><code>prefs = {}\nfor w in words:\n</code></pre>\n\n<p>I'd suggest spelling out <code>word</code></p>\n\n<pre><code> for i in xrange(0,dim):\n prefs[w[:i]] = prefs.get(w[:i], set())\n prefs[w[:i]].add(w[i])\n</code></pre>\n\n<p>Actually, you can do <code>prefs.setdefault(w[:i],set()).add(w[i])</code> for the same effect.</p>\n\n<pre><code>sq, options = ['' for i in xrange(dim)], {}\n</code></pre>\n\n<p>You can do <code>sq, options = [''] * dim, {}</code> for the same effect</p>\n\n<pre><code>for i in prefs: \nfor j in prefs:\n options[(i,j)] = [(i+o, j+o) \n for o in prefs[i] &amp; prefs[j]]\n\nschedule = [(p/dim, p%dim) for p in xrange(posmax)]\n</code></pre>\n\n<p>This can be written as <code>schedule = map(divmod, xrange(posmax))</code></p>\n\n<pre><code>def addone(square, isquare, position=0):\n#for r in square: print r #prints all square-states\n</code></pre>\n\n<p>Don't leave dead code as comments, kill it!</p>\n\n<pre><code>if position == posmax: yield square\n</code></pre>\n\n<p>I'd put the yield on the next line, I think its easier to read especially if you have an else condition</p>\n\n<pre><code>else:\n x,y = schedule[position]\n square2, isquare2 = square[:], isquare[:]\n</code></pre>\n\n<p>In the one line you don't have a space after the comma, in the next line you do. I suggest always including the space.</p>\n\n<pre><code> for o in options[(square[x], isquare[y])]:\n square2[x], isquare2[y] = o\n for s in addone(square2, isquare2, position+1):\n yield s\n\nprint sum(1 for s in addone(sq, sq[:]))\n\nprint (time.clock() - start)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:36:35.023", "Id": "20956", "Score": "0", "body": "minor corrections - \nschedule = map(divmod, xrange(POS_MAX), [DIM]*POS_MAX)\n\nalso, list(open(\"words.list\")) included the \\n at the end of each word which needed some working around. In the end I fif it in 65 chars precisely:\n\nwords = set(w[:-1] for w in open(\"words.list\") if len(w)==DIM+1)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:59:07.207", "Id": "20958", "Score": "1", "body": "@AlexandrosMarinos, ok, my baew. I'd use `[divmod(x, DIM) for x in xrange(POS_MAX)]` I'd also use `w.strip()` instead of `w[:-1]` but that only IMO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T19:51:50.317", "Id": "20962", "Score": "0", "body": "w.strip() is cleaner, but it'd take me over the 65 char limit.. choices, choices :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T19:54:00.490", "Id": "20963", "Score": "0", "body": "@AlexandrosMarinos, 65 char limit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T19:58:41.587", "Id": "20965", "Score": "0", "body": "On line length.. I try to keep them under 65 chars so I don't write too complex 1-liners" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:04:21.057", "Id": "20966", "Score": "2", "body": "@AlexandrosMarinos, for what its worth: the official python style guide recommends a limit of 79 characters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:05:04.027", "Id": "20967", "Score": "0", "body": "Good to know! Don't know how I got 65 stuck in my head.." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T16:53:31.903", "Id": "12980", "ParentId": "12974", "Score": "4" } }, { "body": "<p>I tried a different schedule, it made a very small difference to the time though!</p>\n\n<pre><code>schedule = [(b-y,y)\n for b in range(DIM*2)\n for y in range(min(b+1, DIM))\n if b-y&lt; DIM]\n\nassert len(schedule) == POSMAX\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T19:54:25.337", "Id": "20964", "Score": "0", "body": "schedules are so fascinating.. I've tried a few, but the timing remains roughly the same. I do have a suspicion that a good schedule could make a difference, but I also fear that they make no difference. I was thinking of trying to generate random schedules then time them and see if anything strange comes up, or even do some genetic algos to discover interesting schedules if the random stuff points to significant gains.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T11:38:41.747", "Id": "21024", "Score": "0", "body": "so bizarre.. schedule = [tuple(reversed(divmod(x, DIM))) for x in xrange(POS_MAX)] (effectively the basic schedule but with x and y reversed) seems to be the best performing schedule on a 3x3 out of 24 possibilities. It is a slight improvement on the order of 100ms but for the life of me can't figure out why." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:41:39.130", "Id": "12984", "ParentId": "12974", "Score": "0" } }, { "body": "<p>We fill column by column with the current schedule. I tried adding a check whether we're going to be able to put anything in the next row before filling the rest of the column, but it results in a slight slowdown. </p>\n\n<pre><code>if x+1 &lt; DIM and len(FOLLOWSBOTH[(square[x+1], transpose[y])]) == 0:\n continue\n</code></pre>\n\n<p>I am still tempted to think that something like this but more thorough could still save time: checking not just this one spot, but everything remaining in the row and the column, to ensure that there are compatible letters. That needs a new, more complex data structure though!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:40:50.817", "Id": "20970", "Score": "0", "body": "maybe a 'deadends' dictionary, so we can check (square[x+1], transpose[y]) in deadends would speed this up? off to try it I am." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T21:00:30.247", "Id": "20974", "Score": "0", "body": "wait. I think this wouldn't offer anything with the normal schedule, since square[x+1] is always '', and therefore it comes down to options[transpose[y]], which is always something, if you've gotten that far. Have I missed something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T21:09:24.167", "Id": "20975", "Score": "0", "body": "deadends idea doesn't improve time at all.." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:21:44.683", "Id": "12987", "ParentId": "12974", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T13:25:58.417", "Id": "12974", "Score": "3", "Tags": [ "python" ], "Title": "Word Square generation in Python" }
12974
<p>I'm a little frustrated with the state of url parsing in python, although I sympathize with the challenges. Today I just needed a tool to join path parts and normalize slashes without accidentally losing other parts of the URL, so I wrote this:</p> <pre><code>from urlparse import urlsplit, urlunsplit def url_path_join(*parts): """Join and normalize url path parts with a slash.""" schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts)) # Use the first value for everything but path. Join the path on '/' scheme = next((x for x in schemes if x), '') netloc = next((x for x in netlocs if x), '') path = '/'.join(x.strip('/') for x in paths if x) query = next((x for x in queries if x), '') fragment = next((x for x in fragments if x), '') return urlunsplit((scheme, netloc, path, query, fragment)) </code></pre> <p>As you can see, it's not very DRY, but it does do what I need, which is this:</p> <pre><code>&gt;&gt;&gt; url_path_join('https://example.org/fizz', 'buzz') 'https://example.org/fizz/buzz' </code></pre> <p>Another example:</p> <pre><code>&gt;&gt;&gt; parts=['https://', 'http://www.example.org', '?fuzz=buzz'] &gt;&gt;&gt; '/'.join([x.strip('/') for x in parts]) # Not sufficient 'https:/http://www.example.org/?fuzz=buzz' &gt;&gt;&gt; url_path_join(*parts) 'https://www.example.org?fuzz=buzz' </code></pre> <p>Can you recommend an approach that is readable without being even more repetitive and verbose?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T05:43:32.700", "Id": "21054", "Score": "1", "body": "Why can't you just use `os.path.join` for taking care of the joining and such?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T11:31:36.060", "Id": "21057", "Score": "2", "body": "@Blender what if someone runs this code on Windows?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T19:32:44.900", "Id": "21258", "Score": "0", "body": "Could you please give more examples of the kind of input that would require your above code to accomplish? (i.e provide some test cases that should pass for the solution to be acceptable?). What about some thing simple such as `return '/'.join([x.strip('/') for x in parts])`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T12:03:14.563", "Id": "21333", "Score": "0", "body": "Sure, how about `parts=['https://', 'http://www.example.org', '?fuzz=buzz']`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-14T15:50:46.490", "Id": "234580", "Score": "1", "body": "Just got burned by `urlparse.urljoin` today because it culls any existing paths on the first parameter. _Who in the hell thought that was a great idea?_" } ]
[ { "body": "<p>I'd suggest the following improvements (in descending order of importance):</p>\n\n<ol>\n<li>Extract your redundant generator expression to a function so it only occurs <em>once</em>. To preserve flexibility, introduce <code>default</code> as an optional parameter</li>\n<li>This makes the comment redundant because <code>first</code> is a self-documenting name (you could call it <code>first_or_default</code> if you want to be more explicit), so you can remove that</li>\n<li>Rephrase your docstring to make it more readable: <em>normalize</em> and <em>with a slash</em> don't make sense together</li>\n<li><a href=\"http://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"nofollow\">PEP 8 suggests not to align variable assignments</a>, so does <em>Clean Code</em> by Robert C. Martin. However, it's more important to be consistent within your project. </li>\n</ol>\n\n<hr>\n\n<pre><code>def url_path_join(*parts):\n \"\"\"Normalize url parts and join them with a slash.\"\"\"\n schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))\n scheme = first(schemes)\n netloc = first(netlocs)\n path = '/'.join(x.strip('/') for x in paths if x)\n query = first(queries)\n fragment = first(fragments)\n return urlunsplit((scheme, netloc, path, query, fragment))\n\ndef first(sequence, default=''):\n return next((x for x in sequence if x), default)\n</code></pre>\n\n<hr>\n\n<p>If you're looking for something a bit more radical in nature, why not let <code>first</code> handle several sequences at once? (Note that unfortunately, you cannot combine default parameters with sequence-unpacking in Python 2.7, which has been fixed in Python 3.)</p>\n\n<pre><code>def url_path_join(*parts):\n \"\"\"Normalize url parts and join them with a slash.\"\"\"\n schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))\n scheme, netloc, query, fragment = first_of_each(schemes, netlocs, queries, fragments)\n path = '/'.join(x.strip('/') for x in paths if x)\n return urlunsplit((scheme, netloc, path, query, fragment))\n\ndef first_of_each(*sequences):\n return (next((x for x in sequence if x), '') for sequence in sequences)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T12:16:14.453", "Id": "24416", "ParentId": "13027", "Score": "5" } } ]
{ "AcceptedAnswerId": "24416", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T22:34:16.367", "Id": "13027", "Score": "15", "Tags": [ "python", "parsing", "url" ], "Title": "Joining url path components intelligently" }
13027
<p>I was solving problem <a href="http://projecteuler.net/problem=18" rel="nofollow noreferrer">18</a> and <a href="http://projecteuler.net/problem=67" rel="nofollow noreferrer">67</a> on Project Euler and came up with an algorithm that actually goes through <em>almost</em> all the possibilities to find the answer in O(n) time. However, ProjecEuler claims that a Brute force solution will take too long. Many have implemented this problem using trees, dp and what not.</p> <p>Is my approach not a Brute force?</p> <pre><code>n = [] for i in range(100): n.append(map(int,raw_input().split())) newresult = [int(59)] n.pop(0) for i in range(99): x = n.pop(0) result = list(newresult) newresult =[] t = len(x) for j in range(t): if(j==0): newresult.append(result[0]+x.pop(0)) elif(j==t-1): newresult.append(result[0]+x.pop(0)) else: newresult.append(max((result.pop(0)+x[0]),result[0]+x.pop(0))) print max(newresult) </code></pre> <p>UPDATE: here's a idea how my algorithm works (taking max when needed) <img src="https://i.stack.imgur.com/E3fW0.png" alt="enter image description here"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T17:06:24.517", "Id": "21350", "Score": "0", "body": "Since you seem to understand how dynamic programming works, would you kindly describe your algorithm using words?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T18:26:58.840", "Id": "21351", "Score": "0", "body": "@Leonid checkout the update :)" } ]
[ { "body": "<blockquote>\n <p>Is my approach not a Brute force?</p>\n</blockquote>\n\n<p>Nope, you've implemented dynamic programming</p>\n\n<pre><code>n = []\nfor i in range(100):\n n.append(map(int,raw_input().split()))\nnewresult = [int(59)]\n</code></pre>\n\n<p>I'm not clear why you pass 59 to int, it doesn't do anything. \n n.pop(0)</p>\n\n<p>why didn't you do <code>newresult = n.pop()</code> instead of recreating the first row in the code?</p>\n\n<pre><code>for i in range(99):\n x = n.pop(0)\n result = list(newresult)\n</code></pre>\n\n<p>This makes a copy of newresult, which is pointless here since you don't keep the original around anyways</p>\n\n<pre><code> newresult =[]\n t = len(x)\n for j in range(t):\n\n if(j==0):\n</code></pre>\n\n<p>You don't need the parens</p>\n\n<pre><code> newresult.append(result[0]+x.pop(0))\n</code></pre>\n\n<p>I think the code is a bit clearer if you don't use <code>x.pop</code> just calculate the appropriate indexes </p>\n\n<pre><code> elif(j==t-1):\n newresult.append(result[0]+x.pop(0))\n else:\n newresult.append(max((result.pop(0)+x[0]),result[0]+x.pop(0)))\n</code></pre>\n\n<p>Figuring out the logic of what happens with all this popping is tricky. Again, I think calculating the index will be more straightforward. Also it'll probably be faster since popping the first element of a list is expensive.</p>\n\n<pre><code>print max(newresult)\n</code></pre>\n\n<p>A brute force solution would iterate over every possible path down the triangle. You are iterating over every possible position in the triangle which is much much smaller.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>The dynamic programming solutions starts with a recursive definition of the solution:</p>\n\n<pre><code>cost(i) = number(i) + max( cost(j) for j in predeccesors(i) )\n</code></pre>\n\n<p>Where <code>i</code>, <code>j</code> corresponds to positions on the triangle, and <code>predecessors(i)</code> is the set of all positions which can move onto <code>i</code>. </p>\n\n<p>The top-down approach works by using memoization, remembering a value of <code>cost(j)</code> after it has been calculated. When <code>cost(j)</code> is needed again, it is simply reused. </p>\n\n<p>However, you can also use the bottom-up approach to dynamic programming. In this case, you calculate the values of <code>cost(i)</code> starting from the first cells and work your way forward. Ever cost(i) only depends on the costs of cells before the current cell, and since those have already been calculated they can be reused without even using memoization.</p>\n\n<p>If you look at your code, you'll find that the innermost loop is calculating the same formula as above. Furthermore, you'll find that it is calculating the cost of reach each cell starting from the cells at the top of the triangle and moving its way down. That's why I characterize it as dynamic programming. </p>\n\n<p>I think you don't see this as DP, because you really didn't follow any DP logic in coming up with the solution. I think you are viewing it in terms of repeatedly reducing the complexity of the problem by eliminating the top row. In the end you are doing the same calculations as the DP version although you came at it from a different angle.</p>\n\n<blockquote>\n <p>I think dp uses the same solution again and again, wheras there is\n no need of such memorization here</p>\n</blockquote>\n\n<p>All that's necessary for DP is to reuse solutions more than once. In this case, every number you calculate gets used in two places (one for the right, one for the left)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T23:38:48.330", "Id": "21358", "Score": "0", "body": "\"Nope, you've implemented dynamic programming\" - it does not look like one at first, but I guess it is. One would have to review the definition of the dynamic programming. Obviously, standard dp approach that works in reverse direction is easier to comprehend, but I am curious whether this is another technique for solving problems that I have not encountered yet, or just an over-complication of something that is easy. Perhaps it makes solutions to some other problems easier ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T04:45:45.597", "Id": "21375", "Score": "0", "body": "@Winston your explanation is appreciated, however I am more concerned of the technique and less of the code (let it be dirty its just for projectEuler). Can you explain why this is dp? I think dp uses the same solution again and again, wheras there is no need of such memoization here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T07:34:44.033", "Id": "21376", "Score": "0", "body": "@nischayn22, see edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T08:17:42.943", "Id": "21377", "Score": "0", "body": "+1 for the edit, I will try to see if this approach can be used in other dp problems" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:33:28.147", "Id": "13206", "ParentId": "13186", "Score": "6" } } ]
{ "AcceptedAnswerId": "13206", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:27:55.580", "Id": "13186", "Score": "3", "Tags": [ "python", "project-euler" ], "Title": "Isn't this dynamic programming?" }
13186
<p>I wrote this script to collect evidence of the number of days worked for the purpose of claiming some government tax credits.</p> <p>I'm looking for some ways to clean it up. I'm especially wondering if there is a cleaner way to uniqueify a list than <code>list(set(my_list)</code> and maybe a better way to do:</p> <blockquote> <pre><code>d = dict(zip(commiters, [0 for x in xrange(len(commiters))])) </code></pre> </blockquote> <pre><code>import os from pprint import pprint lines = os.popen('git log --all').read().split('\n') author_lines = filter(lambda str: str.startswith('Author'), lines) date_lines = filter(lambda str: str.startswith('Date'), lines) author_lines = map(lambda str: str[8:], author_lines) date_lines = map(lambda str: str[8:18].strip(), date_lines) lines = zip(author_lines, date_lines) lines = sorted(list(set(lines)), key = lambda tup: tup[0]) commiters = list(set(map(lambda tup: tup[0], lines))) d = dict(zip(commiters, [0 for x in xrange(len(commiters))])) for item in lines: d[item[0]] += 1 pprint(d) </code></pre>
[]
[ { "body": "<p>For this part:</p>\n\n<pre><code>author_lines = filter(lambda str: str.startswith('Author'), lines)\ndate_lines = filter(lambda str: str.startswith('Date'), lines)\nauthor_lines = map(lambda str: str[8:], author_lines)\ndate_lines = map(lambda str: str[8:18].strip(), date_lines)\n</code></pre>\n\n<p>This might be clearer, not that I have anything against map or filter, but list comprehensions do combine them nicely when you need both:</p>\n\n<pre><code>author_lines = [line[8:] for line in lines if line.startswith('Author')]\ndate_lines = [line[8:18].strip() for line in lines if line.startswith('Date')]\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>lines = sorted(list(set(lines)), key = lambda tup: tup[0])\n</code></pre>\n\n<p>Can become:</p>\n\n<pre><code>lines = sorted(set(lines), key = lambda tup: tup[0])\n</code></pre>\n\n<p>for slightly less repetition (<code>sorted</code> automatically converts to a list).<br>\nAnd are you sure the <code>key</code> is even necessary? Tuples get sorted by elements just fine, the only reason to sort specifically by only the first element is if you want to preserve the original order of lines with the same author, rather than sorting them by the date line.<br>\n... Actually, why are you even sorting this at all? I don't see anything in the rest of the code that will work any differently whether it's sorted or not.</p>\n\n<p>For this:</p>\n\n<pre><code>commiters = list(set(map(lambda tup: tup[0], lines)))\n</code></pre>\n\n<p>Why are you zipping author_lines and date_lines and then unzipping again? Just do:</p>\n\n<pre><code>commiters = set(author_lines)\n</code></pre>\n\n<p>or am I missing something?</p>\n\n<p>And this:</p>\n\n<pre><code>d = dict(zip(commiters, [0 for x in xrange(len(commiters))]))\nfor item in lines:\n d[item[0]] += 1\n</code></pre>\n\n<p>You're just getting commit counts, right? Use <code>Counter</code>:</p>\n\n<pre><code>import collections\nd = collections.Counter([author_line for author_line,_ in lines])\n</code></pre>\n\n<p>Or, if your python version doesn't have <code>collections.Counter</code>:</p>\n\n<pre><code>import collections\nd = collections.defaultdict(lambda: 0)\nfor author_line,_ in lines:\n d[author_line] += 1\n</code></pre>\n\n<p>... Wait, are you even using date_lines anywhere? If not, what are they there for?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T14:32:51.740", "Id": "21508", "Score": "1", "body": "date_lines is there so that list(set(lines)) will leave behind only the lines that have a unique author and day of commit. I'm trying to count the number of days that a particular author made a commit.\n\nIts true that they don't need to be sorted, that was left over from when I changed my algorithm slightly. I also like your version of collecting the author_lines and date_lines.\n\nI'll look into the collections library more, I'm not sure if I like Counter, but I definitely like the `for author_line,_ in lines` syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T15:25:13.317", "Id": "21510", "Score": "0", "body": "@Drew - Oh, right! That makes sense. In that case I'd probably do the `list(set(lines))` as you did and then just do a list comprehension to discard all the date lines, since you no longer need them and they only seem to get in the way later. (Also I'd probably rename some of your variables, like `lines`, to make it more obvious what they're doing, like `author_day_pairs` or something)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T21:13:28.907", "Id": "21521", "Score": "0", "body": "Oooh, getting rid of the date_lines afterwards is a great idea. Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T06:08:29.767", "Id": "13303", "ParentId": "13298", "Score": "2" } } ]
{ "AcceptedAnswerId": "13303", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T23:29:15.943", "Id": "13298", "Score": "4", "Tags": [ "python", "git" ], "Title": "Counting the number of days worked for all commiters to a git repo" }
13298
<p>What is the common practice to implement attributes that have side effects in Python? I wrote the following class which supposed to save singletons when a variable is going to get a certain value. The background is that my program had sparse data, meaning that there were a lot of objects having empty sets in their attributes which wasted a lot of memory. (my actual class is slightly more complex). Here is the solution I took:</p> <pre><code>class DefaultAttr: void="Void" def __init__(self, var_name, destroy, create): self.var_name=var_name self.destroy=destroy self.create=create def __get__(self, obj, owner=None): result=getattr(obj, self.var_name) if result is DefaultAttr.void: result=self.create() return result def __set__(self, obj, value): if value==self.destroy: value=DefaultAttr.void setattr(obj, self.var_name, value) class Test: a=DefaultAttr("_a", set(), set) def __init__(self, a): self._a=None self.a=a t=Test(set()) print(t._a, t.a) </code></pre> <p>Do you see a way to make it neater? I was wondering if I can avoid the hidden attribute <code>_a</code>. Also the <code>"Void"</code> solution seems dodgy. What would you do?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T18:47:29.497", "Id": "21518", "Score": "1", "body": "Python 2 or Python 3?" } ]
[ { "body": "<p>If you are using python 2, your code doesn't work at all. I'll assume you are using python 3.</p>\n\n<p>There a few cases where this will do unexpected things:</p>\n\n<pre><code>t=Test(set())\nt.a.add(2)\nprint t.a\n</code></pre>\n\n<p>The set will empty.</p>\n\n<pre><code>b = set()\nt = Test(b)\nb.add(2)\nprint t.a\n</code></pre>\n\n<p>The set will again be empty.</p>\n\n<p>These issues are caused because set are mutable. They go away if you only use immutable objects, such as <code>frozenset()</code>, or if you just never use the mutable operations on the sets.</p>\n\n<blockquote>\n <p>I was wondering if I can avoid the hidden attribute _a</p>\n</blockquote>\n\n<p>Instead of providing the name as a parameter, have DefaultAttr make one up such as <code>'_' + str(id(self))</code>. That'll provide a unique attribute to store data on.</p>\n\n<blockquote>\n <p>Also the \"Void\" solution seems dodgy</p>\n</blockquote>\n\n<p>Instead of <code>\"Void\"</code> use <code>object()</code>. It'll avoid a string comparison and be guaranteed unique.</p>\n\n<p>Alternately, delete the attribute using <code>delattr</code> instead of storing anything there. Absence of the attribute indicates that you should use the default value.</p>\n\n<p>Alternately, if you restrict the use of the object to immutable objects, just store a reference to the immutable object there. There is no need to use a special sentinel value. Here is my code to implement that idea:</p>\n\n<pre><code>class DefaultAttr(object):\n def __init__(self, empty):\n self._empty = empty\n self._name = '_' + str(id(self))\n\n def __get__(self, obj, owner=None):\n return getattr(obj, self._name)\n\n def __set__(self, obj, value):\n if value == self._empty:\n value = self._empty\n setattr(obj, self._name, value)\n</code></pre>\n\n<blockquote>\n <p>The background is that my program had sparse data, meaning that there\n were a lot of objects having empty sets in their attributes which\n wasted a lot of memory.</p>\n</blockquote>\n\n<p>Actually, your probably shouldn't be doing this at all. Instead, use <code>frozenset()</code>. Whenever you call <code>frozenset()</code> it returns the same set, so the empty sets won't take up excess memory. If you rework your app to use them, you should use much less memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T20:06:48.307", "Id": "21520", "Score": "0", "body": "Thanks! That's many great comments :) I think for the Void I will actually write a class which throws meaningful exceptions on most operations performed on it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T19:22:28.533", "Id": "13319", "ParentId": "13318", "Score": "3" } } ]
{ "AcceptedAnswerId": "13319", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T16:57:18.133", "Id": "13318", "Score": "1", "Tags": [ "python" ], "Title": "Attributes with special behaviour in Python" }
13318
<p>I need a NumPy matrix with comparisons among all elements in a sequence:</p> <pre><code>from numpy import matrix seq = [0, 1, 2, 3] matrix([[cmp(a, b) for a in seq] for b in seq]) </code></pre> <p>I'd like to know if there is a better way to do this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T15:02:56.917", "Id": "21653", "Score": "0", "body": "Useful reference for anyone wanting to take this on: http://www.scipy.org/NumPy_for_Matlab_Users" } ]
[ { "body": "<p>Why are you using <code>matrix</code> rather than <code>array</code>? I recommend sticking with <code>array</code></p>\n\n<p>As for a better way:</p>\n\n<pre><code>seq = numpy.array([0, 1, 2, 3])\nnumpy.clip(seq[:,None] - seq, -1, 1)\n</code></pre>\n\n<ol>\n<li><code>seq[:, None]</code>, moves the numbers into the second dimension of the array</li>\n<li><code>seq[:, None] - seq</code> broadcasts the numbers against each other, and subtracts them.</li>\n<li><code>numpy.clip</code> converts lower/higher values into 1 and -1</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T15:06:02.077", "Id": "13396", "ParentId": "13364", "Score": "5" } } ]
{ "AcceptedAnswerId": "13396", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T17:22:07.140", "Id": "13364", "Score": "1", "Tags": [ "python", "matrix", "numpy" ], "Title": "Element-comparison NumPy matrix" }
13364
<p>I am learning scheme to get something new from a programming language and this code below is the solution to Project Euler question 21 but the code runs 10x slower than the listed Python code when I use Chibi-Scheme. Can any Scheme craftsman refactor the code into the Scheme idiom for efficiency.</p> <p>Scheme Code:</p> <pre><code>(define (sum-of-amicable-pairs n) (let ((sums (make-vector n))) (for-each (lambda (i) (vector-set! sums i (reduce + 0 (filter (lambda (j) (= (remainder i j) 0)) (iota (+ 1 (quotient i 2)) 1 1))))) (iota n 0 1)) (let loop ((res (make-vector n 0)) (i 0)) (cond ((= i n) (reduce + 0 (vector-&gt;list res))) ((and (&lt; (vector-ref sums i) n) (not (= (vector-ref sums i) i)) (= (vector-ref sums (vector-ref sums i)) i)) (begin (vector-set! res i i) (vector-set! res (vector-ref sums i) (vector-ref sums i)) (loop res (+ 1 i)))) (else (loop res (+ i 1))))))) (display (sum-of-amicable-pairs 10000)) (newline) </code></pre> <p>Python code:</p> <pre><code>def amicable_pairs(n): """returns sum of all amicable pairs under n. See project euler for definition of an amicable pair""" div_sum = [None]*n amicable_pairs_set = set() for i in range(n): div_sum[i] = sum([j for j in range(1, i/2 + 1) if i%j == 0]) for j in range(n): if div_sum[j] &lt; n and div_sum[div_sum[j]] == j and div_sum[j] != j: amicable_pairs_set.add(j) amicable_pairs_set.add(div_sum[j]) #print sum(amicable_pairs_set) return sum(list(amicable_pairs_set)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-01T21:10:02.193", "Id": "130392", "Score": "1", "body": "Chibi is meant to be small and easily embedded, not a speed demon. Fast Schemes include Gambit and Chicken (both of which are compilers, and are available for Windows)." } ]
[ { "body": "<p>Well, for one thing, the python code is using a set for its amicable_pair_set, where-as you're using a large vector and setting the n'th element to n when you need to add to the set. It's a reasonable way to imitate a set, if your scheme doesn't have a set library; however, this situation doesn't need true set semantics. You can use a simple list instead, so your named let becomes:</p>\n\n<pre><code>(let loop ((res '())\n (i 0))\n (cond\n ((= i n) (reduce + 0 res))\n ((and (&lt; (vector-ref sums i) n) (not (= (vector-ref sums i) i)) \n (= (vector-ref sums (vector-ref sums i)) i))\n (loop (cons i res) (+ 1 i)))\n (else\n (loop res (+ i 1)))))\n</code></pre>\n\n<p>This keeps it close to the python code, but you could go a step further and have <code>res</code> be an integer accumulator, adding to it instead of consing to it, getting rid of the need to add the list at the end. Of course, the same optimization could be made to the python version as well.</p>\n\n<p>Unfortunately, I've optimized the part of the code that runs quick :-). The real work is being done above, when the <code>sums</code> vector is being populated. Since that is a pretty direct translation, I would chalk it up to chibi's implementation of scheme versus whatever implementation of python you're using (PyPy, for instance, is probably going to be faster). I use racket-scheme which is jit compiled. Calling your code returns an answer in ~680ms for me. Calling it with the default python 2.7.3 compiler gives me a result in ~1400ms.</p>\n\n<p>Here's a version which only calculates the sum of its proper divisors for the numbers that are needed, and then stores them for future use. Basically memoizing the results. The first run is slightly faster for me ~30ms, and then subsequent runs return in less than 1ms.</p>\n\n<pre><code>(define d\n (let ((cache (make-vector 10000 #f)))\n (lambda (n)\n (or (vector-ref cache n)\n (let ((val (reduce + 0 (filter (lambda (d) (= 0 (remainder n d)))\n (iota (quotient n 2) 1)))))\n (vector-set! cache n val)\n val)))))\n\n(define (sum-of-amicable-pairs n)\n (let loop ((a 0)\n (sum 0))\n (if (&lt; a n)\n (let ((b (d a)))\n (loop (+ a 1)\n (if (and (&lt; a b n) (= (d b) a))\n (+ sum a b)\n sum)))\n sum)))\n\n(time (sum-of-amicable-pairs 10000))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T05:12:31.587", "Id": "21827", "Score": "0", "body": "your code actually might contain a bug because when you use a list, you run into the problem of adding duplicate pairs to the list as you iterate from 0 to n-1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T15:29:19.020", "Id": "21874", "Score": "0", "body": "in each iteration, we either cons `i` to the list or we don't, and since `i` is strictly increasing, we don't ever add duplicates to the list." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T00:31:25.363", "Id": "13484", "ParentId": "13476", "Score": "3" } } ]
{ "AcceptedAnswerId": "13557", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T19:10:23.620", "Id": "13476", "Score": "4", "Tags": [ "python", "optimization", "project-euler", "scheme", "programming-challenge" ], "Title": "A little scheme programming challenge" }
13476
<p>I have a <code>FileAsset</code> class. I have a set of 'filters' with which I determine if a <code>FileAsset</code> should be written to my database. Below is a telescoped version of how the filters work now. My big question is this: Is there a better way? Any advice would be awesome!</p> <p>(By the way, the <code>Attribute</code> key in the filters allows me to test other attributes of the <code>FileAsset</code> class which I have not demonstrated for simplicity's sake, but the concept is the same.)</p> <pre><code>import os from fnmatch import fnmatch import operator class FileAsset: def __init__(self, filename): self.filename = filename @property def is_asset(self): filters = [ {'Test':'matches','Attribute':'filename','Value':'*'}, {'Test':'ends with','Attribute':'filename','Value':'txt'}, {'Test':'does not end with','Attribute':'filename','Value':'jpg'}] results = [] try: results.append(file_filter(self, filters)) except Exception as e: results.append(True) return True in results def __repr__(self): return '&lt;FileAsset: %s&gt;' % self.filename def file_filter(file_asset,filters): results = [] for f in filters: try: attribute = operator.attrgetter(f['Attribute'])(file_asset) try: result = filter_map(f['Test'])(attribute,f['Value']) results.append(result) except Exception as e: print e results.append(False) except AttributeError as e: print e results.append(False) return not False in results def filter_map(test): if test == u'is file': return lambda x, y: os.path.isfile(x) elif test == u'contains': return operator.contains elif test == u'matches': return lambda x, y: fnmatch(x,y) elif test == u'does not contain': return lambda x, y: not y in x elif test == u'starts with': return lambda x, y: x.startswith(y) elif test == u'does not start with': return lambda x, y: not x.startswith(y) elif test == u'ends with': return lambda x, y: x.endswith(y) elif test == u'does not end with': return lambda x, y: not x.endswith(y) # etc etc fa1 = FileAsset('test.txt') fa2 = FileAsset('test.jpg') print '%s goes to db: %s' % (fa1.filename, fa1.is_asset) print '%s goes to db: %s' % (fa2.filename, fa2.is_asset) </code></pre>
[]
[ { "body": "<p>You have written a small DSL to map tests to Python operations. The DSL uses <code>dict</code>s which imposes some limitations. Try this approach instead:</p>\n\n<pre><code>filter1 = FileFilter().filenameEndsWith('.txt').build()\n\nnames = ['test.txt', 'test.jpg']\nto_save = filter(filter1, names)\n</code></pre>\n\n<p>How does that work? <code>FileFilter</code> is a builder. Builders are like flexible factories. Internally, the code could look like so:</p>\n\n<pre><code>class FileFilter:\n def __init__(self):\n self.conditions = []\n\n def filenameEndsWith(self, pattern):\n def c(filename):\n return filename.endswith(pattern)\n self.conditions.append(c)\n return self\n\n def build(self):\n def f(filename, conditions=self.conditions):\n for c in conditions:\n if not c(filename): return False\n return True\n return f\n</code></pre>\n\n<p>Notes: This is just an example. You will probably use lambdas and return an object that implements the filter API in <code>build()</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T09:14:20.473", "Id": "13532", "ParentId": "13531", "Score": "2" } } ]
{ "AcceptedAnswerId": "13532", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T06:55:44.737", "Id": "13531", "Score": "2", "Tags": [ "python" ], "Title": "Filtering logic" }
13531
<p>Which of these 3 python snippets is more pythonic?</p> <p>This 1 liner list comprehensions which is a little overcomplex</p> <pre><code>users_to_sent = [(my_database.get_user_by_id(x), group['num_sent'][x]) for x in user_ids] </code></pre> <p>or this multi liner which is 'too many lines of code'</p> <pre><code>users_to_sent = [] for id in user_ids: t1 = my_database.get_user_by_id(id) t2 = group['num_sent'][id] users_to_sent.append( (t1,t2) ) </code></pre> <p>or should the 1 liner be spun out into a separate function and called from a list comprehension? </p> <pre><code>def build_tuple(x, my_database, group): return (my_database.get_user_by_id(x), group['num_sent'][x]) users_to_sent = [build_tuple(x, my_database, group) for x in user_ids] </code></pre>
[]
[ { "body": "<p>You'd definitely need to name your function something more descriptive than <code>build_tuple</code> for it to be a good idea (and same with <code>t1</code> and <code>t2</code> in the multi-liner!). </p>\n\n<p>I'd use a function if it's something you do more than once or twice, otherwise I'd probably stick with the list comprehension - I find it easier to read than the multi-liner version.</p>\n\n<p>If I was doing a function, I'd probably make it generate the whole list - is there any reason not to do that?</p>\n\n<pre><code>def make_users_to_sent(user_ids, my_database, group):\n return [(my_database.get_user_by_id(x), group['num_sent'][x]) for x in user_ids]\n\nusers_to_sent = make_users_to_sent(user_ids, my_database, group)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T18:16:01.867", "Id": "13544", "ParentId": "13541", "Score": "2" } } ]
{ "AcceptedAnswerId": "13544", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T16:14:54.093", "Id": "13541", "Score": "1", "Tags": [ "python" ], "Title": "Pythonic style guide" }
13541
<p>I have written a class which I will use as a base class, allowing other classes to extend this class.</p> <p>How can I improve this? Am I breaking any conventions or styling?</p> <pre><code>import requests import feedparser from BeautifulSoup import BeautifulSoup class BaseCrawler(object): ''' Base Class will be extended by other classes''' def __init__(self, url): self.url = url def test(self): return self.url def get_feed(self): feed = feedparser.parse(self.url) return feed def post_request(self): res = requests.post(self.url, self.data) return res def get_request(self): res = requests.get(self.url) self.raw = res.content return self.raw def build_entity(self): raise NotImplementedError("Subclasses should implement this!") def process(self): return NotImplementedError("Subclasses should implement this!") def build_query(self): return NotImplementedError("Subclasses should implement this!") </code></pre>
[]
[ { "body": "<p>I'm not sure what you're intending to do with this class so I can only offer some general tips.</p>\n\n<ol>\n<li><p>Make private variables private:</p>\n\n<pre><code>def __init__(self, url):\n self._url = url\n</code></pre></li>\n<li><p>Use properties instead of <code>get_</code> methods. For example:</p>\n\n<pre><code>@property\ndef request(self):\n return self._requests.get(self._url)\n\n# to make it writeable:\n@request.setter\ndef request(self, value):\n self._requests.set(value)\n</code></pre></li>\n<li><p>If you're using Python 3, have a look at abc.ABCMeta for better solution for abstract base classes with abstract methods.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T00:52:59.013", "Id": "13670", "ParentId": "13664", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-14T16:22:03.267", "Id": "13664", "Score": "2", "Tags": [ "python" ], "Title": "Base class for feed-parsing" }
13664
<p>I have a simple script that will take a list of hosts and ping each host (there's about 200) a single time before moving on. This is not the most effecient method I am sure, as it is very linear. And it takes a few minutes to complete. I would ideally like to run this script every minute (so each IP address is checked every minute (the actual running of the script is controlled externally).</p> <p>I was looking for some pointers on potentially making the script more effecient/dynamic.</p> <pre><code>import sys import os import platform import subprocess plat = platform.system() scriptDir = sys.path[0] hosts = os.path.join(scriptDir, 'hosts.txt') hostsFile = open(hosts, "r") lines = hostsFile.readlines() if plat == "Windows": for line in lines: line = line.strip( ) ping = subprocess.Popen( ["ping", "-n", "1", "-l", "1", "-w", "100", line], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) out, error = ping.communicate() print out print error if plat == "Linux": for line in lines: line = line.strip( ) ping = subprocess.Popen( ["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1", line], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) out, error = ping.communicate() print out print error hostsFile.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T11:41:53.960", "Id": "22127", "Score": "0", "body": "I think it may be the way I'm reading a file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T13:14:11.567", "Id": "22131", "Score": "0", "body": "Might want to take a look at [Nagios's](http://www.nagios.org/) scheduler code to get some ideas." } ]
[ { "body": "<p>Why not using threads ? You could run your pings simultaneously. </p>\n\n<p>This works quite well :</p>\n\n<pre><code>import sys\nimport os\nimport platform\nimport subprocess\nimport threading\n\nplat = platform.system()\nscriptDir = sys.path[0]\nhosts = os.path.join(scriptDir, 'hosts.txt')\nhostsFile = open(hosts, \"r\")\nlines = hostsFile.readlines()\n\ndef ping(ip):\n if plat == \"Windows\":\n ping = subprocess.Popen(\n [\"ping\", \"-n\", \"1\", \"-l\", \"1\", \"-w\", \"100\", ip],\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n\n if plat == \"Linux\":\n ping = subprocess.Popen(\n [\"ping\", \"-c\", \"1\", \"-l\", \"1\", \"-s\", \"1\", \"-W\", \"1\", ip],\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n\n out, error = ping.communicate()\n print out\n print error\n\nfor ip in lines:\n threading.Thread(target=ping, args=(ip,)).run()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T12:07:39.933", "Id": "22128", "Score": "0", "body": "When I run this, I get the following error...\n `OSError: [Errno 24] Too many open files`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T13:16:58.070", "Id": "22132", "Score": "0", "body": "seems like you exceeded your file-quota. either you raise your limit or limit the amount of threads." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T15:13:22.683", "Id": "22135", "Score": "0", "body": "How would I do that then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-08T09:57:02.477", "Id": "309409", "Score": "0", "body": "In the above code the file is being open, but never close that's why you are getting this error.." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T11:44:10.760", "Id": "13684", "ParentId": "13683", "Score": "0" } }, { "body": "<p>It's not a complete answer, but your code would be more clear (and easy to maintain) if you won't duplicate code:</p>\n\n<pre><code>import sys\nimport os\nimport platform\nimport subprocess\n\nplat = platform.system()\nscriptDir = sys.path[0]\nhosts = os.path.join(scriptDir, 'hosts.txt')\nhostsFile = open(hosts, \"r\")\nlines = hostsFile.readlines()\nfor line in lines:\n line = line.strip( )\n if plat == \"Windows\":\n args = [\"ping\", \"-n\", \"1\", \"-l\", \"1\", \"-w\", \"100\", line]\n\n elif plat == \"Linux\":\n args = [\"ping\", \"-c\", \"1\", \"-l\", \"1\", \"-s\", \"1\", \"-W\", \"1\", line]\n\n ping = subprocess.Popen(\n args,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n out, error = ping.communicate()\n print out\n print error\n\nhostsFile.close()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T12:04:04.330", "Id": "13685", "ParentId": "13683", "Score": "4" } }, { "body": "<p>Here's a solution using threads:</p>\n\n<pre><code>import sys\nimport os\nimport platform\nimport subprocess\nimport Queue\nimport threading\n\ndef worker_func(pingArgs, pending, done):\n try:\n while True:\n # Get the next address to ping.\n address = pending.get_nowait()\n\n ping = subprocess.Popen(ping_args + [address],\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n out, error = ping.communicate()\n\n # Output the result to the 'done' queue.\n done.put((out, error))\n except Queue.Empty:\n # No more addresses.\n pass\n finally:\n # Tell the main thread that a worker is about to terminate.\n done.put(None)\n\n# The number of workers.\nNUM_WORKERS = 4\n\nplat = platform.system()\nscriptDir = sys.path[0]\nhosts = os.path.join(scriptDir, 'hosts.txt')\n\n# The arguments for the 'ping', excluding the address.\nif plat == \"Windows\":\n pingArgs = [\"ping\", \"-n\", \"1\", \"-l\", \"1\", \"-w\", \"100\"]\nelif plat == \"Linux\":\n pingArgs = [\"ping\", \"-c\", \"1\", \"-l\", \"1\", \"-s\", \"1\", \"-W\", \"1\"]\nelse:\n raise ValueError(\"Unknown platform\")\n\n# The queue of addresses to ping.\npending = Queue.Queue()\n\n# The queue of results.\ndone = Queue.Queue()\n\n# Create all the workers.\nworkers = []\nfor _ in range(NUM_WORKERS):\n workers.append(threading.Thread(target=worker_func, args=(pingArgs, pending, done)))\n\n# Put all the addresses into the 'pending' queue.\nwith open(hosts, \"r\") as hostsFile:\n for line in hostsFile:\n pending.put(line.strip())\n\n# Start all the workers.\nfor w in workers:\n w.daemon = True\n w.start()\n\n# Print out the results as they arrive.\nnumTerminated = 0\nwhile numTerminated &lt; NUM_WORKERS:\n result = done.get()\n if result is None:\n # A worker is about to terminate.\n numTerminated += 1\n else:\n print result[0] # out\n print result[1] # error\n\n# Wait for all the workers to terminate.\nfor w in workers:\n w.join()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-02T09:52:03.693", "Id": "26177", "Score": "0", "body": "sorry for the delayed response this part of my project has to take a massive \"side-step\". Couple of questions... NUM_WORKERS... I assume this is the amount of pings done in one cycle, for exaample you have \"4\" this would mean 4 hosts would be pinged in one go. Also am I right in assuming I would feed my ip addresses in as `pending`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-02T18:01:57.607", "Id": "26210", "Score": "0", "body": "Each worker gets a host from the pending queue, sends a ping, and puts the reply in the done queue, repeating until the pending queue is empty. There are NUM_WORKERS workers, so there are at most concurrent pings. Note that it fills the pending queue before starting the workers. Another way of doing it is to replace \"pending.get_nowait()\" with \"pending.get()\" and put a sentinel such as None in the pending queue at the end to say that there'll be no more hosts; when a worker sees that sentinel, it puts it back into the pending queue for the other workers to see, and then breaks out of its loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-03T07:42:33.910", "Id": "26241", "Score": "0", "body": "Ha! I didn't actually scroll down on the code!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-03T08:40:41.630", "Id": "26242", "Score": "0", "body": "This is amazing! How many threads is too many? Is there a any calculations that I can perform to (i.e. using CPU and memory, etc) work out what the optimal number of threads is? - I have tried a few, and got the script to finish the list in about 13 seconds (it was in minutes before)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T13:46:10.253", "Id": "26360", "Score": "0", "body": "The optimal number of threads depends on several factors, including the ping response time, so you'll just need to test it with differing numbers of threads. I expect that increasing the number of threads will decrease the run time, but with diminishing returns, so just pick a (non-excessive) number of threads which gives you a reasonable run time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T15:37:47.033", "Id": "26366", "Score": "0", "body": "okay cool... one more thing, occasionally the script hangs once it has reached the end of the hosts file. I'm guessing this is an issue the threads not closing... is there a way to time then out, say after 30seconds?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T19:29:55.277", "Id": "26381", "Score": "0", "body": "Try adding a `finally` clause to the `try` and put the `done.put(None)` line in it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T10:01:15.127", "Id": "26396", "Score": "0", "body": "Thanks, I still see it hang occasionally... if I put a timeout in the `join()` call, will that do it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T17:56:15.467", "Id": "26407", "Score": "0", "body": "I don't know. Why did you try it? :-) I also suggest making the threads 'daemon' threads. I've edited the code to do that." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T19:31:28.377", "Id": "13691", "ParentId": "13683", "Score": "5" } } ]
{ "AcceptedAnswerId": "13691", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T11:41:14.833", "Id": "13683", "Score": "6", "Tags": [ "python", "performance", "networking", "status-monitoring" ], "Title": "Pinging a list of hosts" }
13683
<p>Any suggestions/improvements for the following custom thread-pool code?</p> <pre><code>import threading from Queue import Queue class Worker(threading.Thread): def __init__(self, function, in_queue, out_queue): self.function = function self.in_queue, self.out_queue = in_queue, out_queue super(Worker, self).__init__() def run(self): while True: if self.in_queue.empty(): break data = in_queue.get() result = self.function(*data) self.out_queue.put(result) self.in_queue.task_done() def process(data, function, num_workers=1): in_queue = Queue() for item in data: in_queue.put(item) out_queue = Queue(maxsize=in_queue.qsize()) workers = [Worker(function, in_queue, out_queue) for i in xrange(num_workers)] for worker in workers: worker.start() in_queue.join() while not out_queue.empty(): yield out_queue.get() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T21:03:07.577", "Id": "221086", "Score": "0", "body": "I recommend looking into the `multiprocessing.pool.ThreadPool` object, also explained [here](http://stackoverflow.com/questions/3033952/python-thread-pool-similar-to-the-multiprocessing-pool)." } ]
[ { "body": "<ol>\n<li><p>The function <a href=\"https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.map\" rel=\"nofollow\"><code>concurrent.futures.ThreadPoolExecutor.map</code></a> is built into Python 3 and does almost the same thing as the code in the post. If you're still using Python 2, then there's a <a href=\"https://pypi.python.org/pypi/futures/3.0.5\" rel=\"nofollow\">backport of the <code>concurrent.futures</code> package</a> on PyPI.</p></li>\n<li><p>But considered as an exercise, the code here seems basically fine (apart from the lack of documentation), and the remaining comments are minor issues.</p></li>\n<li><p><code>Worker.run</code> could be simplified slightly by writing the loop condition like this:</p>\n\n<pre><code>while not self.in_queue.empty():\n # ...\n</code></pre></li>\n<li><p>There's no need to pass a <code>maxsize</code> argument to the <a href=\"https://docs.python.org/3/library/queue.html#queue.Queue\" rel=\"nofollow\"><code>Queue</code></a> constructor—the default is that the queue is unbounded, which is fine.</p></li>\n<li><p>The only use of the <code>workers</code> list is to start the workers. But it would be easier to start each one as you create it:</p>\n\n<pre><code>for _ in range(num_workers):\n Worker(function, in_queue, out_queue).start()\n</code></pre></li>\n<li><p>The results come out in random(-ish) order because threads are nondeterministic. But for many use cases you would like to know which input corresponds to which output, and so you'd like the outputs to be in the same order as the inputs (as they are in the case of <a href=\"https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.map\" rel=\"nofollow\"><code>concurrent.futures.ThreadPoolExecutor.map</code></a>).</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-26T14:07:52.500", "Id": "142503", "ParentId": "13690", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-15T18:56:53.000", "Id": "13690", "Score": "2", "Tags": [ "python", "multithreading" ], "Title": "Custom thread-pooling" }
13690
<p>I've created these 3 functions to count the value of letters in a word.</p> <p>All these functions are functionally the same.</p> <p>Apparently List comprehensions (<code>count_word3</code>) are usually seen as the most pythonic in these situations. But to me it is the least clear of the 3 examples.</p> <p>Have I stumbled across something that is so simple that lambdas are acceptable here or is "the right thing to do" to use the list comprehension?</p> <p>Or is there something better?</p> <pre><code>def count_word1(w): def count(i, a): return i + ord(a) - 64 return reduce(count, w, 0) def count_word2(w): return reduce(lambda a,b : a + ord(b) - 64, w, 0) def count_word3(w): vals = [ord(c) - 64 for c in w] return sum(vals) </code></pre>
[]
[ { "body": "<p>how's example 3 the least readable? I would write it a little better but you've got it right already:</p>\n\n<pre><code>def count_word3(word): \n return sum(ord(c) - 64 for c in word) \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-20T13:10:01.740", "Id": "22384", "Score": "0", "body": "I've probably just done too much scala :-). \nI'm just asking for opinions from the python community to refine my python style." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-20T12:08:14.523", "Id": "13865", "ParentId": "13863", "Score": "2" } }, { "body": "<p>These are the most readable for me:</p>\n\n<pre><code>sum((ord(letter) - ord('A') + 1) for letter in word)\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>def letter_value(letter):\n return ord(letter) - ord('A') + 1\n\nsum(map(letter_value, word))\n</code></pre>\n\n<p>btw, the code might break for non-ASCII strings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-20T12:18:22.397", "Id": "13866", "ParentId": "13863", "Score": "1" } } ]
{ "AcceptedAnswerId": "13865", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-20T10:54:47.693", "Id": "13863", "Score": "1", "Tags": [ "python", "comparative-review" ], "Title": "Three ways to sum the values of letters in words" }
13863
<p>Here is a simple Python script that I wrote with lots of help from the Python mailing list. I moves all the files of subdirectories to the top level directory. It works well for my use, but if there are things that can be improved then I would like to know. I ask in the interest of being a better Python programmer and learning the language better. Thanks.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import shutil currentDir = os.getcwd() forReal = False if ( currentDir in ['/home/dotancohen', '/home/dotancohen/.bin'] ): print "Error: Will not run in "+currentDir exit() if ( len(sys.argv)&gt;1 and sys.argv[1] in ['m', 'M', 'c', 'C'] ): forReal = True else: print "\nThis is a test run. To actually perform changes, add 'm' (move) or 'c' (copy) after the program name.\n" filesList = os.walk(currentDir) for rootDir, folders, files in filesList: for f in files: if (rootDir!=currentDir): toMove = os.path.join(rootDir, f) print toMove newFilename = os.path.join(currentDir,f) renameNumber = 1 while(os.path.exists(newFilename)): newFilename = os.path.join(currentDir,f)+"_"+str(renameNumber) renameNumber = renameNumber+1 if ( forReal and sys.argv[1] in ['m', 'M'] ): os.rename(toMove, newFilename) elif ( forReal and sys.argv[1] in ['c', 'C'] ): shutil.copy(toMove, newFilename) if ( not forReal ): print "\nThis was a test run. To actually perform changes, add 'm' (move) or 'c' (copy) after the program name." </code></pre>
[]
[ { "body": "<p>I'll typically wrap the main body of my code in a python script in a function and break the code apart into more functions, allowing me to reuse that code later.</p>\n\n<pre><code>import os\nimport shutil\nimport sys\n\ndef flattenDirectory(location, action, actuallyMoveOrCopy=True):\n \"\"\" This function will move or copy all files from subdirectories in the directory location specified by location into the main directory location folder\n location - directory to flatten\n action - string containing m(ove) or M(ove) or c(opy) or C(opy)\"\"\"\n #Your code here\n\nif __name__ == \"__Main__\":\n #same code to find currentDirectory here\n actuallyMoveOrCopy = len(sys.argv)&gt;1 and sys.argv[1] in ['m', 'M', 'c', 'C']\n flattenDirectory(currentDirectory, sys.argv[1], actuallyMoveOrCopy)\n</code></pre>\n\n<p>Now you can still run this code as you normally would, but should you need it in another script you can use it in an import without having to worry about the code automatically running at the time of import.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-22T10:37:26.293", "Id": "22452", "Score": "0", "body": "Thank you. This is a good example of a script that likely _will_ be called from another program someday, so it is a good fit to this approach." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-20T16:14:00.307", "Id": "13877", "ParentId": "13876", "Score": "2" } }, { "body": "<p>Peter has already mentioned putting the code into methods. This isn’t just a personal preference, it’s a general recommendation that <em>all</em> Python code should follow.</p>\n\n<p>In fact, consider the following an idiomatic Python code outline:</p>\n\n<pre><code>import sys\n\ndef main():\n # …\n\nif __name__ == '__main__':\n sys.exit(main())\n</code></pre>\n\n<p>Implement <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8 – Style Guide for Python Code</a>. In particular, use <code>underscore_separated</code> variables instead of <code>camelCase</code>.</p>\n\n<p>Programs should follow the general flow (1) input, (2) processing, (3) output. Argument reading is part of (1); consequently, do it only once, at the start.</p>\n\n<p>Set variables depending on that input.</p>\n\n<pre><code>perform_move = sys.argv[1] in ['M', 'm']\nperform_copy = sys.argv[1] in ['C', 'c']\ndry_run = not perform_copy and not perform_move\n…\n</code></pre>\n\n<p>Note that I’ve inverted the conditional for <code>forReal</code>. First of all, because it’s more common (“dry run” is what this is usually called). Secondly, the name <code>forReal</code> is rather cryptic.</p>\n\n<p>Put the <code>['/home/dotancohen', '/home/dotancohen/.bin']</code> into a configurable constant at the beginning of the code, or even into an external configuration file. Then make it a parameter to the method which performs the actual logic.</p>\n\n<p>By contrast, the <code>filesList</code> variable is unnecessary. Just iterate directly over the result of <code>os.walk</code>.</p>\n\n<p>Operations of the form <code>renameNumber = renameNumber+1</code> should generally be written as <code>rename_number += 1</code>. Also, pay attention to consistent whitespace usage.</p>\n\n<p>I’d put the logic to find a unique target path name into its own method <code>unique_pathname</code>. Then I’d replace the concatenation by string formatting.</p>\n\n<pre><code>def unique_pathname(basename):\n unique = basename\n rename_no = 1\n while os.path.exists(unique):\n unique = '{0}_{1}'.format(basename, rename_no)\n rename_no += 1\n\n return unique\n</code></pre>\n\n<p>Notice that I’ve also removed the redundant parenthese around the loop condition here. The same should be done for all your <code>if</code> statements.</p>\n\n<pre><code>if ( forReal and sys.argv[1] in ['m', 'M'] ):\n</code></pre>\n\n<p>The test for <code>forReal</code> here is redundant anyway, it’s implied in the second condition. But we’ve got variables now anyway:</p>\n\n<pre><code>if perform_move:\n # …\nelif perform_copy:\n # …\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-22T10:38:20.507", "Id": "22453", "Score": "0", "body": "Thank you. Your explanation is quite what I was looking for, to write code that is \"more Pythonic\"." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-20T17:04:52.777", "Id": "13878", "ParentId": "13876", "Score": "2" } } ]
{ "AcceptedAnswerId": "13878", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-20T14:16:19.887", "Id": "13876", "Score": "2", "Tags": [ "python" ], "Title": "Python: flatten directories" }
13876
<p>I have a little experience with Python and am trying to become more familiar with it. As an exercise, I've tried coding a program where the ordering of a list of players is determined by the roll of a die. A higher number would place the player ahead of others with lower numbers. Ties would be broken by the tied players rolling again.</p> <p>Here is an example:</p> <blockquote> <pre><code> player 1, player 2, player 3 rolls 6, rolls 6, rolls 1 / \ / \ player 1, player 2 player 3 rolls 5, rolls 4 / \ / \ player 1 player 2 </code></pre> </blockquote> <p>Final order: player 1, player 2, player 3</p> <p>I'm interested in how I could have done this better. In particular, I'm not familiar with much of the Python style guide so making it more pythonic would be nice. Also, I'm not that familiar with unit testing. I've used unittest instead of nose since I was using an online IDE that supports it.</p> <pre><code>from random import randint from itertools import groupby import unittest def rank_players(playerList, die): tree = [playerList] nextGeneration = [] keepPlaying = True while keepPlaying: keepPlaying = False for node in tree: if len(node) == 1: nextGeneration.append(node) else: keepPlaying = True rolls = [die.roll() for i in range(len(node))] turn = sorted(zip(rolls,node), reverse=True) print 'players roll:', turn for key, group in groupby(turn, lambda x: x[0]): nextGeneration.append(list(i[1] for i in group)) tree = nextGeneration nextGeneration = [] return [item for sublist in tree for item in sublist] class Die: def __init__(self,rolls=[]): self.i = -1 self.rolls = rolls def roll(self): self.i = self.i + 1 return self.rolls[self.i] class RankingTest(unittest.TestCase): def testEmpty(self): die = Die() players = [] self.assertEquals(rank_players(players,die),[]) def testOnePlayer(self): die = Die() player = ['player 1'] self.assertEquals(rank_players(player,die),['player 1']) def testTwoPlayer(self): die = Die([6, 1]) players = ['player 1', 'player 2'] self.assertEquals(rank_players(players,die),['player 1', 'player 2']) def testThreePlayer(self): die = Die([6, 6, 1, 4, 5]) players = ['player x', 'player y', 'player z'] self.assertEquals(rank_players(players,die),['player x', 'player y','player z']) def testRunAll(self): self.testEmpty() self.testOnePlayer() self.testTwoPlayer() self.testThreePlayer() if __name__ == '__main__': unittest.main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T10:01:02.427", "Id": "22499", "Score": "0", "body": "Is there a reason for calling a dice \"die\"? BTW you can find some Python style guides [here](http://meta.codereview.stackexchange.com/a/495/10415)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T10:07:35.310", "Id": "22500", "Score": "0", "body": "Take also a look [here](http://stackoverflow.com/q/1132941/1132524) to know why you shouldn't do `def __init__(self,rolls=[]):`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T15:46:14.210", "Id": "22508", "Score": "0", "body": "Thanks for the links. I used the singular for dice, die, in an attempt to convey that each player would only do one roll for each turn. I would've liked a less ambiguous term." } ]
[ { "body": "<p>Here's one way it could be done with a lot less code:</p>\n\n<pre><code>from itertools import groupby\nfrom operator import itemgetter\nfrom random import randint\n\ndef rank_players(playerList):\n playerRolls = [(player, randint(1, 6)) for player in playerList]\n playerGroups = groupby(\n sorted(playerRolls, key=itemgetter(1), reverse=True),\n itemgetter(1))\n for key, group in playerGroups:\n grouped_players = list(group)\n if len(grouped_players) &gt; 1:\n for player in rank_players(zip(*grouped_players)[0]):\n yield player\n else:\n yield grouped_players[0]\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>&gt;&gt;&gt; print list(rank_players([\"bob\", \"fred\", \"george\"]))\n[('fred', 5), ('george', 6), ('bob', 4)]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T15:52:26.340", "Id": "22509", "Score": "0", "body": "I really appreciate your answer. I will look more carefully into it at the end of today. My impression is though, that this answer does not handle the case of two ties the way I was hoping to. For example, player 1 and player 2 tie with 5, player 3 is in the middle with 4, and player 4 and player 5 tie with 3. Thank you for your effort. I'm not sure of the procedure, but I will probably mark it as the answer by the end of today if it is the best available answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T17:14:21.390", "Id": "22520", "Score": "0", "body": "@jlim: Ah, I see (hence your use of `groupby`.) Well this solution is easily extensible to that end, since the recursion works on any set of sublists of players. I am a little preoccupied at the moment, but I can probably post a modified solution in a couple of hours." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T19:36:35.410", "Id": "22544", "Score": "0", "body": "@jlim: Updated my answer. This version will handle the possiblity of `n` ties, provided that `n` does not exceed the recursion limit ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-24T01:33:07.100", "Id": "22569", "Score": "0", "body": "Thank you for the update. Sorry I don't have enough rep to up vote yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-24T02:02:42.593", "Id": "22571", "Score": "0", "body": "@jlim: No problem man. Glad to help" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T05:28:04.250", "Id": "13921", "ParentId": "13902", "Score": "2" } } ]
{ "AcceptedAnswerId": "13921", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-22T01:13:54.113", "Id": "13902", "Score": "1", "Tags": [ "python", "random", "tree", "simulation" ], "Title": "Die-rolling for ordering" }
13902
<pre><code>a=raw_input() prefix_dict = {} for j in xrange(1,len(a)+1): prefix = a[:j] prefix_dict[prefix] = len(prefix) print prefix_dict </code></pre> <p>Is there any possibility of memory error in the above code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T04:57:24.287", "Id": "22478", "Score": "0", "body": "A memory error? Please explain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T16:02:52.827", "Id": "22510", "Score": "0", "body": "@JoelCornett The above code is a part of another code from a contest. when tried on the website it gave a memoryerroer at `prefix = a[:j]\n`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T17:15:11.250", "Id": "22521", "Score": "0", "body": "Oh, I see. What implementation of python are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T17:31:03.087", "Id": "22523", "Score": "0", "body": "@JoelCornett Sorry, but I lost you \"What implementation of python are you using?\" do u mean version or anything else??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T18:31:58.430", "Id": "22527", "Score": "0", "body": "I mean, what are you running this code on? cPython? Jython? Stackless Python? The code as given shouldn't give you an error, so any errors would be platform specific. Are you sending this code to a server?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T18:55:59.573", "Id": "22531", "Score": "0", "body": "@JoelCornett On my system its not giving any error but on the server of the website its giving an error, the server is a quad core Xeon machines running 32-bit Ubuntu (Ubuntu 12.04 LTS).For few cases its working and for few its showing memory error. FYI: I do not know the cases that they are testing but inputs are lower case alphabets." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-23T18:58:47.403", "Id": "22533", "Score": "0", "body": "I suggest that you put this question on stackoverflow.com. You'll get an answer to your question more quickly that way." } ]
[ { "body": "<p>It's hard to tell what is making the error occur without giving us the input, but it's certainly possible the input is too large for the system to store.</p>\n\n<p><code>prefix_dict</code> will contain <code>len(a)</code> entries so if your input is larger than 32-bit python allows for dictionary size on your machine, then that could be the issue. </p>\n\n<p>I will note that instead of having <code>prefix_dict[prefix] = len(prefix)</code> you could just have <code>prefix_dict[prefix] = j</code> which would stop you from needing to do an extra length calculation each time (not that this would be the cause of the memory issue).</p>\n\n<p>Take a look at the sample output (I modified the print statement and used an example string):</p>\n\n<pre><code>&gt;&gt;&gt; prefix_dict = {}\n&gt;&gt;&gt; a = 'hello'\n&gt;&gt;&gt; for j in xrange(1,len(a)+1):\n prefix = a[:j]\n prefix_dict[prefix] = len(prefix)\n print j, len(prefix), prefix_dict\n\n1 1 {'h': 1}\n2 2 {'h': 1, 'he': 2}\n3 3 {'hel': 3, 'h': 1, 'he': 2}\n4 4 {'hel': 3, 'h': 1, 'hell': 4, 'he': 2}\n5 5 {'hel': 3, 'h': 1, 'hell': 4, 'hello': 5, 'he': 2}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-22T01:33:53.587", "Id": "18901", "ParentId": "13910", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-22T12:07:51.700", "Id": "13910", "Score": "2", "Tags": [ "python", "strings", "hash-map" ], "Title": "Creating a dictionary of all prefixes of a string in Python" }
13910
<p>This craps game simulator is based on someone else's posted Python code that I've redone for practice. I'm interested in improving readability and making it more pythonic. I used <code>unittest</code> instead of <code>nose</code> because I'm using an online IDE.</p> <pre><code>from random import randrange import unittest class CrapsGame: def __init__(self): self.outcomes = {'2':False,'3':False,'12':False,'7':True,'11':True, '4&amp;4':True,'5&amp;5':True,'6&amp;6':True, '8&amp;8':True,'9&amp;9':True,'10&amp;10':True, '4&amp;7':False,'5&amp;7':False,'6&amp;7':False, '8&amp;7':False,'9&amp;7':False,'10&amp;7':False} def play(self, roll_dice): comeOut = str(roll_dice()) print 'began game with ' + comeOut if comeOut in self.outcomes: return self.outcomes[comeOut] while True: point = str(roll_dice()) print 'next roll is ' + point state = comeOut+'&amp;'+point if state in self.outcomes: return self.outcomes[state] class CrapsTest(unittest.TestCase): def testWinComeOut(self): game = CrapsGame() self.assertEquals(game.play(lambda: 7), True) def testLoseComeOut(self): game = CrapsGame() self.assertEquals(game.play(lambda: 2), False) def testWinPoint(self): game = CrapsGame() rollData = [5,6,5] self.assertEquals(game.play(lambda: rollData.pop()), True) def testLosePoint(self): game = CrapsGame() rollData = [7,5] self.assertEquals(game.play(lambda: rollData.pop()), False) if __name__ == '__main__': unittest.main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T17:37:24.210", "Id": "466862", "Score": "0", "body": "I can give my 2 cents in regard to the naming conventions. Using snake case for the variables' names would be definitely more pythonic, for example `come_out` instead of `comeOut`." } ]
[ { "body": "<p>Some general comments first.</p>\n\n<ol>\n<li><p>There's no need to make your throws in strings for the outcomes - you can use tuples instead. e.g.</p>\n\n<pre><code>self.outcomes = { (2,):False, (5,5):True }\n</code></pre></li>\n<li><p>If you pass a \"wrong\" set of dice throws (say \\$[4,5]\\$), you'll have an exception raised which isn't dealt with (and should probably be a test?).</p></li>\n<li><p><code>pop</code> removes the last element, which means you process them in reverse order - which differs from what the casual reader might expect (\\$[7,5]\\$ = 7 first, then 5).</p></li>\n</ol>\n\n<p>You may want to look at generators which would provide a nice interface to a throw. In this case, what about:</p>\n\n<pre><code>class DiceThrow:\n def __init__( self, rolls = None ):\n self.rolls = rolls\n def First( self ):\n return self.__next__()\n def __iter__( self ):\n return self\n def __next__( self ):\n if self.rolls is not None:\n if len( self.rolls ) == 0:\n raise StopIteration\n r = self.rolls[0]\n self.rolls = self.rolls[1:]\n return r\n return randrange( 1, 13 ) # may be better as randint( 1, 12 )\n</code></pre>\n\n<p>This can then be called as follows:</p>\n\n<pre><code>game.play( DiceThrow( [5,7] ) )\ngame.play( DiceThrow() ) # for a random set of throws\n</code></pre>\n\n<p>and used:</p>\n\n<pre><code>def play(self, dice_throw):\n comeOut = dice_throw.First()\n print( \"began game with %d\"%comeOut )\n if (comeOut,) in self.outcomes:\n return self.outcomes[(comeOut,)]\n for point in dice_throw:\n print( \"next roll is %d\"%point )\n state = (comeOut,point)\n if state in self.outcomes:\n return self.outcomes[state]\n print( \"Bad rolls!\" )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-25T06:28:56.250", "Id": "22626", "Score": "0", "body": "Thank you. I appreciate the effort. I like the tuples instead of strings, and the idea of using a generator sounds interesting." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-24T10:00:44.127", "Id": "13966", "ParentId": "13962", "Score": "3" } } ]
{ "AcceptedAnswerId": "13966", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-24T06:37:08.500", "Id": "13962", "Score": "2", "Tags": [ "python", "game", "random", "dice" ], "Title": "Craps dice game simulator" }
13962
<p>I setup simple CRUD in Django</p> <pre><code>from django.shortcuts import render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse_lazy from django.http import HttpResponseRedirect from intentions.models import User,Prayer,Intention from intentions.forms import IntentionForm, DeleteIntentionForm def index(request): intentions = Intention.objects.all(); return render_to_response('intentions/templates/index.html', {'intentions': intentions}, context_instance=RequestContext(request) ) def show(request, id): try: intention = Intention.objects.get(pk=id) except Intention.DoesNotExist: return render_to_response('intentions/templates/404_show.html') return render_to_response('intentions/templates/show.html', {'intention': intention, 'delete_form': DeleteIntentionForm(instance=intention)}, context_instance=RequestContext(request) ) def new(request): if request.method == 'POST': # If the form has been submitted... form = IntentionForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... intention = form.save() return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST else: form = IntentionForm() # An unbound form return render_to_response('intentions/templates/form.html', {'form': form, 'form_url': reverse_lazy('intention-new')}, context_instance=RequestContext(request) ) def edit(request, id): intention = Intention.objects.get(pk=id) if request.method == 'POST': # If the form has been submitted... form = IntentionForm(request.POST, instance=intention) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... intention = form.save() return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST else: intention = Intention.objects.get(pk=id) form = IntentionForm(instance=intention) # An unbound form return render_to_response('intentions/templates/form.html', {'form': form, 'form_url': reverse_lazy('intention-edit', args=[intention.id])}, context_instance=RequestContext(request) ) def delete(request, id): if request.method == 'POST': try: intention = Intention.objects.get(pk=id) except Intention.DoesNotExist: return render_to_response('intentions/templates/404_show.html') intention.delete() return HttpResponseRedirect('/') else: return render_to_response('intentions/templates/404_show.html') </code></pre> <p>I see some fragments for refactor, but I am newbie in Python and Django and I would like to get advices from more experienced users about refactoring this code too.</p>
[]
[ { "body": "<p>1.Using <code>render</code> shortcut function is more preferable than <code>render_to_response</code>. The difference is explained on <a href=\"https://stackoverflow.com/a/5154458/455833\">SO</a> </p>\n\n<pre><code>def index(request):\n intentions = Intention.objects.all();\n return render('intentions/templates/index.html', {'intentions': intentions})\n</code></pre>\n\n<p>2.Then django has another shortcut <a href=\"http://django.me/get_object_or_404\" rel=\"nofollow noreferrer\"><code>get_object_or_404</code></a></p>\n\n<pre><code>intention = get_object_or_404(Intention, pk=id)\n</code></pre>\n\n<p>It raises 404 Exception which is processed by middleware. You don't need to call custom <code>HttpRequest</code> for that. </p>\n\n<p>3.Here lazy version <code>reverse_lazy</code> is redundant. Call <code>reverse</code> instead.</p>\n\n<pre><code>return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST\n</code></pre>\n\n<p>4.You also can look through <a href=\"https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/\" rel=\"nofollow noreferrer\">CBV</a>. Django offers for you some base class to handle forms. It may reduce your code. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-27T05:44:40.297", "Id": "14067", "ParentId": "14047", "Score": "1" } } ]
{ "AcceptedAnswerId": "14067", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-26T14:19:14.473", "Id": "14047", "Score": "2", "Tags": [ "python", "django" ], "Title": "Need advice of refactoring views.py" }
14047
<p>I use a global variable to fit my need:</p> <pre><code>scores = {} def update(): global scores # fetch data from database scores = xxx class MyRequestHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): def choice_with_score(items): # return a key related to scores return key def get_key(): global scores return choice_with_score(scores) self.write('%s' % get_key()) self.finish() if __name__ == '__main__': # initially update update() app = tornado.web.Application([ (r'.*', MyRequestHandler), ]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(port) ioloop = tornado.ioloop.IOLoop.instance() # background update every x seconds task = tornado.ioloop.PeriodicCallback( update, 15 * 1000) task.start() ioloop.start() </code></pre> <p>Here, the function <code>update()</code> gets new data instead of updating in every incoming request, which is why I use a global variable.</p> <p><strong>Are there other ways to do the same work?</strong></p>
[]
[ { "body": "<p>You could use a class to keep your <code>scores</code> inside a defined scope and not use the globals. This way it's fairly easy to test and you don't have to deal globals. All you need to ensure is that you always pass the same instance. You could probably do it using some sort Singleton patterns.</p>\n\n<pre><code>import tornado\nimport tornado.web\n\n# I hate the name manager but couldn't come up with something good fast enough.\nclass ScoreManager(object):\n def __init__(self):\n self._scores = {}\n\n def fetch_from_database(self):\n # fetch from database\n self._scores = {'key': 'score'}\n\n def get_all(self):\n return self._scores\n\nclass MyRequestHandler(tornado.web.RequestHandler):\n # this is the way to have sort of a constructor and pass parameters to a RequestHandler\n def initialize(self, score_manager):\n self._score_manager = score_manager\n\n @tornado.web.asynchronous\n def get(self):\n def choice_with_score(items):\n # return a key related to scores\n return key\n\n def get_key():\n global scores\n return choice_with_score(self._score_manager)\n\n self.write('%s' % get_key())\n self.finish()\n\nif __name__ == '__main__':\n # initially update\n score_manager = ScoreManager()\n score_manager.fetch_from_database()\n\n app = tornado.web.Application([\n (r'.*', MyRequestHandler, dict(score_manager=score_manager)), # these params are passed to the initialize method.\n ])\n\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(port)\n ioloop = tornado.ioloop.IOLoop.instance()\n\n # background update every x seconds\n task = tornado.ioloop.PeriodicCallback(\n update,\n 15 * 1000)\n task.start()\n\n ioloop.start()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-13T07:39:31.083", "Id": "69702", "ParentId": "14094", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-28T04:38:35.750", "Id": "14094", "Score": "5", "Tags": [ "python", "tornado" ], "Title": "Is there a better way to do get/set periodically in tornado?" }
14094
<p>I need to write some code that checks thousands of websites, to determine if they are in English or not. Below is the source code. Any improvements would be appreciated.</p> <pre><code>import nltk import urllib2 import re import unicodedata ENGLISH_STOPWORDS = set(nltk.corpus.stopwords.words('english')) NON_ENGLISH_STOPWORDS = set(nltk.corpus.stopwords.words()) - ENGLISH_STOPWORDS STOPWORDS_DICT = {lang: set(nltk.corpus.stopwords.words(lang)) for lang in nltk.corpus.stopwords.fileids()} def get_language(text): words = set(nltk.wordpunct_tokenize(text.lower())) return max(((lang, len(words &amp; stopwords)) for lang, stopwords in STOPWORDS_DICT.items()), key=lambda x: x[1])[0] def checkEnglish(text): if text is None: return 0 else: text = unicode(text, errors='replace') text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore') text = text.lower() words = set(nltk.wordpunct_tokenize(text)) if len(words &amp; ENGLISH_STOPWORDS) &gt; len(words &amp; NON_ENGLISH_STOPWORDS): return 1 else: return 0 def getPage(url): if not url.startswith("http://"): url = "http://" + url print "Checking the site ", url req = urllib2.Request(url) try: response = urllib2.urlopen(req) rstPage = response.read() except urllib2.HTTPError, e: rstPage = None except urllib2.URLError, e: rstPage = None except Exception, e: rstPage = None return rstPage def getPtag(webPage): if webPage is None: return None else: rst = re.search(r'&lt;p\W*(.+)\W*&lt;/p&gt;', webPage) if rst is not None: return rst.group(1) else: return rst def getDescription(webPage): if webPage is None: return None else: des = re.search(r'&lt;meta\s+.+\"[Dd]escription\"\s+content=\"(.+)\"\s*/*&gt;', webPage) if des is not None: return des.group(1) else: return des def checking(url): pageText = getPage(url) if pageText is not None: if checkEnglish(getDescription(pageText)) == 1: return '1' elif checkEnglish(getPtag(pageText)) == 1: return '1' elif checkEnglish(pageText) == 1: return '1' else: return '0' else: return 'NULL' if __name__ == "__main__": f = open('sample_domain_list.txt').readlines() s = open('newestResult.txt', "w") for line in f[:20]: url = line.split(',')[1][1:-1] check = checking(url) s.write(url + ',' + check) s.write('\n') print check # f.close() s.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T13:57:47.007", "Id": "23972", "Score": "0", "body": "Does your code work as you intend it to? What problems do you see with it? (To help us focus on those...)" } ]
[ { "body": "<ol>\n<li>Use <code>BeautifulSoup</code> to strip the JS, HTML, and CSS formatting.</li>\n<li>Use <code>urllib</code> instead of <code>urllib2</code>.</li>\n</ol>\n\n<p></p>\n\n<pre><code>from bs4 import BeautifulSoup\nfrom urllib import urlopen\nurl = \"http://stackoverflow.com/help/on-topic\"\n\ndef getPage(url) \n html = urlopen(url).read()\n soup = BeautifulSoup(html)\n\n# remove all script and style elements\n for script in soup([\"script\", \"style\"]):\n script.extract() # remove\n\n# get text\n text = soup.get_text()\n return text\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-05T19:37:03.613", "Id": "83328", "ParentId": "14098", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-28T07:57:33.870", "Id": "14098", "Score": "2", "Tags": [ "python", "parsing", "natural-language-processing" ], "Title": "NLTK language detection code in Python" }
14098
<p>If you use capturing parenthesis in the regular expression pattern in Python's <code>re.split()</code> function, it will include the matching groups in the result (<a href="http://docs.python.org/library/re.html#re.split" rel="nofollow">Python's documentation</a>).</p> <p>I need this in my Clojure code and I didn't find an implementation of this, nor a Java method for achieving the same result.</p> <pre><code>(use '[clojure.string :as string :only [blank?]]) (defn re-tokenize [re text] (let [matcher (re-matcher re text)] (defn inner [last-index result] (if (.find matcher) (let [start-index (.start matcher) end-index (.end matcher) match (.group matcher) insert (subs text last-index start-index)] (if (string/blank? insert) (recur end-index (conj result match)) (recur end-index (conj result insert match)))) (conj result (subs text last-index)))) (inner 0 []))) </code></pre> <p>Example:</p> <pre><code>(re-tokenize #"(\W+)" "...words, words...") =&gt; ["..." "words" ", " "words" "..." ""] </code></pre> <p>How could I make this simpler and / or more efficient (maybe also more Clojure-ish)?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T20:33:50.170", "Id": "79236", "Score": "3", "body": "For what it's worth, [clojure.contrib.string/partition](http://clojuredocs.org/clojure_contrib/clojure.contrib.string/partition) does this exactly." } ]
[ { "body": "<p>You can adjust you implementation to be a lazy-seq for some added performance:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(use '[clojure.string :as string :only [blank?]])\n\n(defn re-tokenizer [re text]\n (let [matcher (re-matcher re text)]\n ((fn step [last-index]\n (when (re-find matcher)\n (let [start-index (.start matcher)\n end-index (.end matcher)\n match (.group matcher)\n insert (subs text last-index start-index)]\n (if (string/blank? insert)\n (cons match (lazy-seq (step end-index)))\n (cons insert (cons match (lazy-seq (step end-index))))))))\n 0)))\n</code></pre>\n\n<p>This implementation will be more efficient as the results will only be calculated as needed. For instance if you only needed the first 10 results from a really long string you can use:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(take 10 (re-tokenize #\"(\\W+)\" really-long-string)\n</code></pre>\n\n<p>and only the first 10 elements will be computed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-30T10:47:19.290", "Id": "16054", "ParentId": "14113", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-29T08:49:34.703", "Id": "14113", "Score": "3", "Tags": [ "python", "regex", "clojure" ], "Title": "Implementation of Python's re.split in Clojure (with capturing parentheses)" }
14113
<p>Below is an algorithm to generate all pairwise combinations for a set of random variables. <a href="http://en.wikipedia.org/wiki/All-pairs_testing" rel="nofollow">See here</a> for an explanation of what constitutes a minimal all-pairs set. The algorithm below works but I feel that it is inefficient. Any suggestions would be welcome.</p> <pre><code>from operator import itemgetter from itertools import combinations, product, zip_longest, chain, permutations def pairwise(*variables, **kwargs): num_vars = len(variables) #Organize the variable states into pairs for comparisons indexed_vars = sorted( ([(index, v) for v in vals] for index, vals in enumerate(variables)), key=len, reverse=True) var_combos = combinations(range(num_vars), 2) var_products = (product(indexed_vars[i], indexed_vars[j]) for i, j in var_combos) vars = chain.from_iterable(zip_longest(*var_products)) #Initialize the builder list builders = [] seen_pairs = set() #Main algorithm loop for pair in vars: if not pair or pair in seen_pairs: continue d_pair = dict(pair) #Linear search through builders to find an empty slot #First pass: look for sets that have intersections for builder in builders: intersection = builder.keys() &amp; d_pair.keys() if len(intersection) == 1: v = intersection.pop() if builder[v] == d_pair[v]: builder.update(d_pair) #Update seen pairs seen_pairs.update(combinations(builder.items(), 2)) break else: #Second Pass for builder in builders: intersection = builder.keys() &amp; d_pair.keys() if not len(intersection): builder.update(d_pair) #Update seen pairs seen_pairs.update(combinations(builder.items(), 2)) break else: #No empty slots/pairs identified. Make a new builder builders.append(d_pair) seen_pairs.add(pair) #Fill in remaining values complete_set = set(range(num_vars)) defaults = {var[0][0]: var[0][1] for var in indexed_vars} for builder in builders: if len(builder) == num_vars: yield tuple(val for index, val in sorted(builder.items())) else: for key in complete_set - builder.keys(): builder[key] = defaults[key] yield tuple(val for index, val in sorted(builder.items())) </code></pre> <p>Usage Example:</p> <pre><code>u_vars = [ [1, 2, 3, 4], ["A", "B", "C"], ["a", "b"], ] result = list(pairwise(*u_vars)) print(result) #prints list of length 12 </code></pre>
[]
[ { "body": "<p>This is not generating correct pairwise combinations.</p>\n\n<p>Input data</p>\n\n<pre><code>[['Requests'],\n ['Create','Edit'],\n ['Contact Name','Email','Phone','Subject','Description','Status','Product Name','Request Owner','Created By','Modified By','Request Id','Resolution','To Address','Account Name','Priority','Channel','Category','Sub Category'],\n ['None','is','isn\\'t','contains','doesn\\'t contain','starts with','ends with','is empty','is not empty'],\n ['Contact Name','Email','Phone','Subject','Description','Status','Product Name','Request Owner','Mark Spam','Resolution','To Address','Due Date','Priority','Channel','Category','Sub Category']]\n</code></pre>\n\n<p>Result by Microsoft PICT</p>\n\n<p><a href=\"http://pastebin.com/cZdND9UA\" rel=\"nofollow\">http://pastebin.com/cZdND9UA</a></p>\n\n<p>Result by your code\n<a href=\"http://pastebin.com/EC6xv4vG\" rel=\"nofollow\">http://pastebin.com/EC6xv4vG</a></p>\n\n<p>This generates only for NONE in most of cases such as this</p>\n\n<p>Requests Create Account Name None Category\nRequests Create Account Name None Channel\nRequests Create Account Name None Description\nRequests Create Account Name None Due Date</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-06T17:24:52.927", "Id": "23266", "Score": "0", "body": "Hmmm... I'm not sure why this is. When I was using smaller inputs, it was working fine. Let me find out what's wrong with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-07T00:10:04.353", "Id": "23286", "Score": "0", "body": "Apparently, the problem is nontrivial. I don't really have time to compare algorithms but here is a paper that I found useful: https://www.research.ibm.com/haifa/projects/verification/mdt/papers/AlgorithmsForCoveringArraysPublication191203.pdf" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-07T01:40:51.623", "Id": "23288", "Score": "0", "body": "Every other generator except PICT, I have tested failed in large sets not in small sets. Yes the problem is nontrivial one. I also working on it. If I port that algorithm I will post it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-07T02:18:33.767", "Id": "23290", "Score": "0", "body": "That would be awesome. I think the main problem is the heuristic I'm using to determine the order in which I add items to the array. I reformulated the code (same algorithm, just neater code) in the answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-06T04:14:48.340", "Id": "14364", "ParentId": "14120", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-29T20:02:46.787", "Id": "14120", "Score": "7", "Tags": [ "python", "algorithm", "combinatorics" ], "Title": "Pairwise Combinations Generator" }
14120
<p>This Python code parses string representations of Reversi boards and converts them into bit string suitable for use by a bitstring module: <code>b = BitArray('0b110')</code> or bitarray module: <code>a = bitarray('000111')</code> if <code>blackInit</code> and <code>whiteInit</code> are initialized as empty strings.</p> <p>I am interested in a simpler way to do this in Python. I would like to preserve the idea of having a human readable string representation of the board converted into 2 bitstrings, one for the black pieces and one for the white pieces. It seems like it could be simpler if it was just a split and then a map instead of a loop, but I wanted to be able to see the strings line by line and don't see how to workaround that.</p> <pre><code>board1 = [ '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_'] board2 = [ 'B|_|_|_|_|_|_|W', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', 'W|_|_|_|_|_|_|B'] board3 = [ 'W|W|W|W|B|B|B|B', 'W|_|_|_|_|_|_|B', 'W|_|_|_|_|_|_|B', 'W|_|_|_|_|_|_|B', 'B|_|_|_|_|_|_|W', 'B|_|_|_|_|_|_|W', 'B|_|_|_|_|_|_|W', 'B|B|B|B|W|W|W|W'] board4 = [ '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|W|B|_|_|_', '_|_|_|B|W|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_', '_|_|_|_|_|_|_|_'] board5 = [ 'W|_|_|_|_|_|_|B', '_|W|_|_|_|_|B|_', '_|_|W|_|_|B|_|_', '_|_|_|W|B|_|_|_', '_|_|_|B|W|_|_|_', '_|_|B|_|_|W|_|_', '_|B|_|_|_|_|W|_', 'B|_|_|_|_|_|_|W'] def parse_board(board): def map_black(spot): return str(int(spot == 'B')) def map_white(spot): return str(int(spot == 'W')) blackInit = '0b' whiteInit = '0b' for line in board: squares = line.split('|') blackInit = blackInit + ''.join(map(map_black,squares)) whiteInit = whiteInit + ''.join(map(map_white,squares)) return (blackInit,whiteInit) print(parse_board(board1)) print(parse_board(board2)) print(parse_board(board3)) print(parse_board(board4)) print(parse_board(board5)) </code></pre>
[]
[ { "body": "<pre><code>def parse_board(board):\n def map_black(spot):\n</code></pre>\n\n<p>This name suggests that the function is a variant on map. Whereas its actually intended to be used as a parameter on map</p>\n\n<pre><code> return str(int(spot == 'B'))\n def map_white(spot):\n return str(int(spot == 'W'))\n</code></pre>\n\n<p>Both functions are very similiar, can you refactor?</p>\n\n<pre><code> blackInit = '0b'\n whiteInit = '0b'\n</code></pre>\n\n<p>The python style guide suggest 'lowercase_with_underscores' for local variable names</p>\n\n<pre><code> for line in board:\n squares = line.split('|')\n blackInit = blackInit + ''.join(map(map_black,squares))\n whiteInit = whiteInit + ''.join(map(map_white,squares))\n</code></pre>\n\n<p>Repeatedly adding strings is not very efficient python.</p>\n\n<pre><code> return (blackInit,whiteInit)\n</code></pre>\n\n<p>Everything in your function is done twice. Once for 'B' and once for 'W'. I'd suggest you should have a function that takes 'B' or 'W' as parameter, and call that twice.</p>\n\n<p>Here's how I'd tackle this:</p>\n\n<pre><code>def bitstring_from_board(board, letter):\n bits = []\n for line in board:\n bits.extend( spot == letter for spot in line.split('|') )\n return '0b' + ''.join(str(int(x)) for x in bits)\n\ndef parse_board(board):\n return bitstring_from_board(board, 'B'), bitstring_from_board(board, 'W')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T04:37:35.093", "Id": "23027", "Score": "0", "body": "Thank you for your effort. I will avoid doing things twice in my revision." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-01T14:10:09.680", "Id": "14202", "ParentId": "14187", "Score": "1" } } ]
{ "AcceptedAnswerId": "14202", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-01T05:03:43.310", "Id": "14187", "Score": "1", "Tags": [ "python", "strings", "parsing" ], "Title": "Reversi text board parsing to bitfield" }
14187
<p>I'm only just beginning in programming. </p> <p>The goal of the program is to check to make sure images are properly rendered within a program(within a VM)</p> <p>. Below is the code, and I am asking what I can do to clean it up.</p> <p>I don't think you can tell much without the .png's, but I would appreciate it if anyone knows where/how I can optimize my code.</p> <p>Thank you very much for any help,</p> <pre><code>var=(0) #Empty Variable jpgl=0 #NUMBER PASSES vm = App("C:\Program Files (x86)\VMware\VMware Workstation\\vmware.exe") switchApp("vm") reg=( ) reg.find( ) #------------------------------------ #BEGINNING SPECIAL CASES/NAVIGATION if not exists( ): switchApp("vm") type(Key.BACKSPACE) onAppear( ,type(Key.BACKSPACE)) if exists( ): click( ) #if exists( ):#attempt to get rid of. # click( ) else: exists( ) click( ) exists( ) click( ) wait(1) if not exists ( ):#if the image hasn't already loaded, wait the maximum 5 seconds wait(5) #END FOLDER NAVIGATION #---------------------------------- #BEGIN IMAGE CHECK 1 if not exists ( ): print("B-JPEG_L-20.jpg not displayed correctly") if exists( ): print("B-JPEG_L-20.jpg Unable to play") click( ) else: jpgl=jpgl+1#if the image exists, it moves on by clicking "next" click( ) wait(1) if not exists ( ): wait(5) #DONE IMAGE CHECK 1 #---------------------------------- #BEGIN IMAGE CHECK 2 ..... #end code </code></pre>
[]
[ { "body": "<p>One way to get started improving your script is to find repeated code, then create a function to hold it.</p>\n\n<p>For example, if your code starting with #BEGIN IMAGE CHECK 1 is duplicated for subsequent image checks, it could become a function that takes a Sikuli image file name - define it somewhere near the top of your file (NOTE: This assumes the same image filename is used consistently across this entire chunk of code, which may not be true in your unedited code):</p>\n\n<pre><code>def check_image(image_filename):\n if not exists(image_filename):\n print(\"%s not displayed correctly\" % image_filename)\n if exists(image_filename):\n print(\"%s Unable to play\" % image_filename)\n click(image_filename)\n else: \n jpgl = jpgl + 1 \n click(image_filename)\n wait(1) \n if not exists (image_filename):\n wait(5) \n</code></pre>\n\n<p>Then below that you can call the function with:</p>\n\n<pre><code>check_image('foo.jpg')\n</code></pre>\n\n<p>Then you should have a starting point for incrementally refining your code. At some point creating a class to hold your test logic could be useful as well.</p>\n\n<p>I recommend reading up on functions and classes in Python - solid knowledge in those areas really helps out with Sikuli development:</p>\n\n<p><a href=\"http://docs.python.org/tutorial/controlflow.html#defining-functions\" rel=\"nofollow\">http://docs.python.org/tutorial/controlflow.html#defining-functions</a></p>\n\n<p><a href=\"http://docs.python.org/tutorial/classes.html#tut-classes\" rel=\"nofollow\">http://docs.python.org/tutorial/classes.html#tut-classes</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T00:36:03.187", "Id": "14279", "ParentId": "14215", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-31T20:26:49.303", "Id": "14215", "Score": "4", "Tags": [ "python" ], "Title": "How do I refine my code in Sikuli? Seems very long and redundant" }
14215
<p>I'm trying to get some feedback on my code for the lexicon exercise (#48) in <em>Learn Python the Hard Way</em>. I have only recently started learning Python and want to make sure I have my fundamentals down before progressing. I have some experience coding (only with kdb+/q in my work environment) but none in Python, so all advice is welcomed.</p> <pre><code>verb=['go','kill','eat'] direction=['north','south','east','west'] noun=['bear','princess'] stop=['the','in','of'] vocab={'verb':verb,'direction':direction,'noun':noun,'stop':stop} def scan(sentence): wordlist=sentence.split() result=[] #initialize an empty list for word in wordlist: found=False for key,value in vocab.items(): if word.lower() in value: #convert to lower case so that we can handle inputs with both cases result.append((key,word)) found=True break if not found: try: word=int(word) result.append(('number',word)) except ValueError: result.append(('error',word)) return result </code></pre> <p>Python version 2.6.</p>
[]
[ { "body": "<pre><code>verb=['go','kill','eat']\ndirection=['north','south','east','west']\nnoun=['bear','princess']\nstop=['the','in','of']\n</code></pre>\n\n<p>There is not a lot of point in storing these in separate variables only to stick them inside <code>vocab</code> just put the list literals inside <code>vocab</code></p>\n\n<pre><code>vocab={'verb':verb,'direction':direction,'noun':noun,'stop':stop}\n</code></pre>\n\n<p>Python convention say to make constant ALL_CAPS. I'd also not abbreviate the names. Code is read more then written, so make it easy to read not to write.</p>\n\n<pre><code>def scan(sentence):\n wordlist=sentence.split()\n result=[] #initialize an empty list\n</code></pre>\n\n<p>Pointless comment. Assume you reader understand the language. You don't need to explain what [] means.</p>\n\n<pre><code> for word in wordlist:\n</code></pre>\n\n<p>I'd use <code>for word in sentence.split():</code></p>\n\n<pre><code> found=False\n</code></pre>\n\n<p>Boolean logic flags are delayed gotos. Avoid them when you can</p>\n\n<pre><code> for key,value in vocab.items():\n if word.lower() in value: #convert to lower case so that we can handle inputs with both cases\n</code></pre>\n\n<p>Your dictionary is backwards. It maps from word types to lists of words. It'd make more sense to have a dictionary mapping from word to the word type.</p>\n\n<pre><code> result.append((key,word))\n found=True\n break\n if not found:\n</code></pre>\n\n<p>Rather then this, use an <code>else</code> block on the for loop. It'll be execute if and only if no break is executed.</p>\n\n<pre><code> try:\n word=int(word)\n result.append(('number',word))\n</code></pre>\n\n<p>Put this in the else block for the exception. Generally, try to have as little code in try blocks as possible. Also I wouldn't store the result in word again, I'd put in a new local.</p>\n\n<pre><code> except ValueError:\n result.append(('error',word))\n\n return result \n</code></pre>\n\n<p>My approach:</p>\n\n<pre><code>WORD_TYPES = {\n 'verb' : ['go', 'kill', 'eat'],\n 'direction' : ['north', 'south', 'east', 'west'],\n 'noun' : ['bear', 'princess'],\n 'stop' : ['the','in','of']\n}\n# invert the dictionary\nVOCABULARY = {word: word_type for word_type, words in WORD_TYPES.items() for word in words}\n\ndef scan(sentence):\n tokens = []\n for word in sentence.split():\n try:\n word_type = VOCABULAR[word]\n except KeyError:\n try:\n value = int(word)\n except ValueError:\n tokens.append( ('error',word) )\n else:\n tokens.append( ('int', value) )\n else:\n tokens.append( (word_type, word) )\n return tokens\n</code></pre>\n\n<p>Alternately, using some regular expressions:</p>\n\n<pre><code>classifications = []\nfor word_type, words in WORD_TYPES.items():\n word_expression = '|'.join(\"(?:%s)\" % re.escape(word) for word in words)\n expression = r\"\\b(?P&lt;%s&gt;%s)\\b\" % (word_type, word_expression)\n classifications.append(expression)\nclassifications.append(r\"\\b(?P&lt;int&gt;\\d+)\\b\")\nclassifications.append(r\"\\b(?P&lt;error&gt;\\w+)\\b\")\nparser = re.compile('|'.join(classifications))\n\ndef scan(sentence):\n return [(match.lastgroup, match.group(0)) for match in parser.finditer(sentence)]\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>If your version of python is to old to use the dict comphrensions you can use:</p>\n\n<pre><code>dict((word, word_type) for word_type, words in WORD_TYPES.items() for word in words)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T13:00:09.387", "Id": "23051", "Score": "0", "body": "thanks for the response! Very much appreciated. Would you mind walking me through the dictionary inversion? I was trying to drop it into my terminal and play with it but I get a SyntaxError:invalid syntax. It seemed to me to be some sort of variant on list comprehension where for each word in words (i.e. for each element in the value-pairs) it assigns the wordtype (i.e. the key in the original dictionary key-value pair) to that element. Not sure why it doesn't work though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T15:02:15.987", "Id": "23056", "Score": "0", "body": "@JPC, which version of python are you running? The dict comprehension is a newer feature. But you've got the right idea of how it works. I'll add an alternate way" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T17:27:02.377", "Id": "23061", "Score": "0", "body": "seem's I'm running on 2.6.4. Thanks! I appreciate it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T17:43:17.783", "Id": "23065", "Score": "0", "body": "@JPC, yeah I think you need 2.7 for the dict comp." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T04:13:48.200", "Id": "14242", "ParentId": "14238", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-08-02T01:37:03.527", "Id": "14238", "Score": "9", "Tags": [ "python", "beginner", "parsing", "python-2.x" ], "Title": "Learn Python the Hard Way #48 — lexicon exercise" }
14238
<p>I have a program that displays colorful shapes to the user. It is designed so that it is easy to add new shapes, and add new kinds of views.</p> <p>Currently, I have only two shapes, and a single text-based view. In the near future, I'm going to implement a <code>Triangle</code> shape and a <code>BezierCurve</code> shape. </p> <p>I'm also going to implement these views:</p> <ul> <li><code>GraphicalView</code> - uses a graphics library to render shapes on screen.</li> <li><code>OscilloscopeView</code> - draws the shapes on an oscilloscope.</li> <li><code>DioramaView</code> - a sophisticated AI directs robotic arms to construct the scene using construction paper, string, and a shoebox.</li> </ul> <p>The MVC pattern is essential here, because otherwise I'd have a big intermixed tangle of oscilloscope and AI and Graphics library code. I want to keep these things as separate as possible.</p> <pre><code>#model code class Shape: def __init__(self, color, x, y): self.color = color self.x = x self.y = y class Circle(Shape): def __init__(self, color, x, y, radius): Shape.__init__(self, color, x, y) self.radius = radius class Rectangle(Shape): def __init__(self, color, x, y, width, height): Shape.__init__(self, color, x, y) self.width = width self.height = height class Model: def __init__(self): self.shapes = [] def addShape(self, shape): self.shapes.append(shape) #end of model code #view code class TickerTapeView: def __init__(self, model): self.model = model def render(self): for shape in self.model.shapes: if isinstance(shape, Circle): self.showCircle(shape) if isinstance(shape, Rectangle): self.showRectangle(shape) def showCircle(self, circle): print "There is a {0} circle with radius {1} at ({2}, {3})".format(circle.color, circle.radius, circle.x, circle.y) def showRectangle(self, rectangle): print "There is a {0} rectangle with width {1} and height {2} at ({3}, {4})".format(rectangle.color, rectangle.width, rectangle.height, rectangle.x, rectangle.y) #end of view code #set up model = Model() view = TickerTapeView(model) model.addShape(Circle ("red", 4, 8, 15)) model.addShape(Circle ("orange", 16, 23, 42)) model.addShape(Circle ("yellow", 1, 1, 2)) model.addShape(Rectangle("blue", 3, 5, 8, 13)) model.addShape(Rectangle("indigo", 21, 34, 55, 89)) model.addShape(Rectangle("violet", 144, 233, 377, 610)) view.render() </code></pre> <p>I'm very concerned about the <code>render</code> method of <code>TickerTapeView</code>. In my experience, whenever you see code with a bunch of <code>isinstance</code> calls in a big <code>if-elseif</code> block, it signals that the author should have used polymorphism. But in this case, defining a <code>Shape.renderToTickerTape</code> method is forbidden, since I have resolved to keep the implementation details of the view separate from the model.</p> <p><code>render</code> is also smelly because it will grow without limit as I add new shapes. If I have 1000 shapes, it will be 2000 lines long.</p> <p>Is it appropriate to use <code>isinstance</code> in this way? Is there a better solution that doesn't violate model-view separation and doesn't require 2000-line <code>if</code> blocks?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T19:48:32.090", "Id": "23144", "Score": "0", "body": "Not sure if you are just exclusively using this pattern for your example, but the O(n) search pattern in `render()` can be replaced by a O(1) search pattern with a `dict`. (e.g. `shape_render_methods = {'circle': showCircle, 'rectangle': showRectangle}`, called like this. `for shape in shapes: shape_render_methods[shape.name]()`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T19:54:28.817", "Id": "23145", "Score": "0", "body": "Good observation. I considered using a dict, but I wasn't sure it was a portable solution. Do all object oriented languages guarantee that you can use a class name as the key to a dictionary? In my mind, this is a language-agnostic problem, so it should have a language-agnostic solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T19:57:11.097", "Id": "23146", "Score": "0", "body": "I'm not sure that they do. In any case, I think it's better that you define a `name` attribute for your shape class--that's what I meant to imply by `shape.name`. The above code was meant as an example pattern, not an actual implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T20:08:58.570", "Id": "23148", "Score": "0", "body": "Oops, I must have misread your first comment. On second look, that code is indeed language agnostic. Giving each shape subclass its own `name` would work, but I'm wary of restating type information in a new form. [Don't Repeat Yourself](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself), as they say." } ]
[ { "body": "<p>Here's one approach:</p>\n\n<pre><code>SHAPE_RENDERER = {}\n\ndef renders(shape):\n def inner(function):\n SHAPE_RENDERER[shape] = function\n return function\n return inner\n\n@renders(Circle)\ndef draw_circle(circle, view):\n ...\n\n@renders(Triangle)\ndef draw_triangle(triangle, view):\n ....\n\ndef render_shape(shape, view):\n SHAPE_RENDERER[shape.__class__](shape, view)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T20:12:12.327", "Id": "23149", "Score": "0", "body": "This nicely resolves the 2000-line method problem. But can this approach be taken in other OO languages that don't support decorators? In which case I imagine you'd need an `initialize_SHAPE_RENDERER` method which takes 2000 lines to populate the dict, and now we're back at the start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T21:20:40.823", "Id": "23152", "Score": "0", "body": "@Kevin, this depends on what other OO language. For example, in Java you could do something with reflection or annotations. In C++ you could do some magic with macros and static objects." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T15:22:40.860", "Id": "14262", "ParentId": "14257", "Score": "2" } }, { "body": "<p>This answer is a bit too easy, so may be a catch but I wonder:\nWhy don't you add a .show() method to Circle class which will be equivalent of showCircle, then the same with Rectangle etc and then just:</p>\n\n<pre><code>for shape in self.model.shapes: \n shape.show() \n</code></pre>\n\n<p>or better, .show() returns sth which a render function will take care of it if you want to do fancier things: </p>\n\n<pre><code>for shape in self.model.shapes: \n self.renderer(shape.show())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T11:59:45.460", "Id": "23121", "Score": "0", "body": "I can't put any display-specific code in my shape classes, since I have resolved to keep the implementation details of the view separate from the model. Or if you mean that `show()` only returns data that the view can use to distinguish between shape types, then that's just an `isinstance` call in disguise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T19:43:26.823", "Id": "23143", "Score": "0", "body": "@Kevin: I wonder if `show()` can return non-implementation specific rendering data. `Rectangle.show`, for example would return something in the form of \"LINE POINT1 POINT2, LINE POINT2 POINT3, LINE POINT3 POINT4, LINE POINT4 POINT1\", which can be interpreted by `render()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T20:23:27.403", "Id": "23150", "Score": "0", "body": "That would indeed work very well if every shape could be precisely defined using only lines and points. However, circles and beziers can't be represented just by straight lines, so I'd need a `CURVE` rendering object in addition to `LINE`. In which case I need a `renderRenderingObject` method which can distinguish between concrete subclasses of the `RenderingObject` class, and then we're back to my original problem, albeit at a smaller scale." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-04T01:19:00.030", "Id": "85847", "Score": "0", "body": "Each view calls <shape>.show(). Each view also provides primitives that <shape>.show() can call to display itself in that view. The sequence of primitive calls is the same regardless of the view. So view says <circle>.show(self), which says, eg, <view>.curve(x, y, r, 0, 360), where (x,y) is the center of the circle, r is the radius, and 0, 360 indicate the portion of the curve to draw. Each view implements curve() in its own terms. The view doesn't have to know which shape it's calling and the shape doesn't have to know which view is drawing it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T22:01:18.077", "Id": "14276", "ParentId": "14257", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-02T14:16:45.080", "Id": "14257", "Score": "2", "Tags": [ "python", "mvc" ], "Title": "Displaying colorful shapes to the user" }
14257
<p>I have the following code:</p> <pre><code>from Bio import AlignIO import itertools out=open("test.csv","a") align = AlignIO.read("HPV16_CG.aln.fas", "fasta") n=0 def SNP(line): result=[] result.append(str(n+1)) result.append(line[0]) result.append(align[y].id.rsplit("|")[3]) result.append(x) return result while n&lt;len(align[0]): line = align[:,n] y=0 for x in line: if line[0]!=x: print &gt;&gt; out, ','.join(map(str,SNP(line))) y=y+1 else: y=y+1 y=0 n=n+1 out.close() f=open("test.csv","rU") out=open("test_2.csv","a") lines=f.read().split() for key, group in itertools.groupby(lines, lambda line: line.partition(',')[0]): print &gt;&gt;out, ','.join(group) out.close() f.close() </code></pre> <p>As you can see, I am currently writing two files. I really only need the second file. Does anyone have any suggestions to combine both "subscripts" into one? </p> <p>The input file "HPV16_CG.aln.fas" looks like this:</p> <pre><code>&gt;gi|333031|lcl|HPV16REF.1| Alpha-9 - Human Papillomavirus 16, complete genome. ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG &gt;gi|333031|gb|K02718.1|PPH16 Human papillomavirus type 16 (HPV16), complete genome ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG &gt;gi|196170262|gb|FJ006723.1| Human papillomavirus type 16, complete genome ACTACAATAATTCATGTATAAAACTAAGGGCGTAACCGAAATCGGTTGAACCGAAACCGG </code></pre> <p>I really appreciate all the help/suggestions to help me improve this!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-03T22:02:21.873", "Id": "30872", "Score": "1", "body": "If you do not read PEP8 in its entirety, you can still run `pep8 myfile.py` and `pylint myfile.py` and `pyflakes myfile.py` (and there may be others) in order to have cleaner code." } ]
[ { "body": "<p>First of all, read <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> (all of it!) and adhere to it. This is the de facto standard of Python code.</p>\n\n<p>In the following, I’ll tacitly assume PEP8 as given.</p>\n\n<p>Secondly, it would help if you had actually written what the expected output looks like. Given your input file, the script produces <strong>empty output</strong>.</p>\n\n<p>I don’t understand what the <code>while</code> loop is supposed to do. <code>align</code> represents a single <strong>alignment record</strong> – you are reading a <em>sequence</em> file which contains <em>multiple sequences</em>. Furthermore, what is <code>align[:, n]</code>? Did you maybe intend to access the <code>seq</code> sub-object?</p>\n\n<p>Likewise, the <code>SNP</code> method doesn’t <em>at all</em> make clear what its function is. And it implicitly uses global variables. This is error-prone and unreadable: use parameters instead. The function also accesses some object <code>align[y]</code> which won’t exist when <code>y &gt; 0</code>, because <code>AlignIO.read</code> only reads a <em>single</em> alignment.</p>\n\n<p>Furthermore, if you’re handling CSV files, I’d strongly suggest using the <a href=\"http://docs.python.org/library/csv.html\" rel=\"nofollow\"><code>csv</code> module</a>. It’s not really less code in your particular case but it provides a more uniform handling and makes the code easily extensible.</p>\n\n<p>Just to show what this could look like when done cleaner, here’s the production of the <strong>first file</strong>. I’d love to show the full code but I really don’t understand what the code is supposed to do since it doesn’t work for me, and I’m unfamiliar with the function of <code>align[:,n]</code> (and I think there’s an error in the access to <code>align</code>, anyway.</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport csv\nimport itertools\nimport sys\nfrom Bio import AlignIO\n\n\ndef snp(line, alignment, n, base, pos):\n \"\"\"Documentation missing!\"\"\"\n id = alignment[pos].id.rsplit('|')[3] # why rsplit?\n return [ str(n + 1), line[0], id, base ]\n\n\ndef main():\n # TODO Use command line argumnents to provide file names\n\n alignment = Bio.AlignIO.read('HPV16_CG.aln.fas', 'fasta')\n\n with csv.writer('test.csv') as out:\n for n in range(len(alignment[0])):\n line = align[ : , n]\n for pos, base in line:\n if line[0] != x:\n out.writerow(snp(line, alignment, n, base, pos))\n\n\nif __name__ == '__main__':\n sys.exit(main())\n</code></pre>\n\n<p>In this code I tried to give the variables meaningful names but – again, since I don’t know what this is supposed to do – I had to guess quite a lot based on usage.</p>\n\n<p>And by the way, <code>range(len(x))</code> is actually kind of an anti-pattern but I can’t for the heck of it remember the “correct” usage (and even the documentation advises this).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-05T19:20:45.477", "Id": "14360", "ParentId": "14357", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-05T16:09:17.473", "Id": "14357", "Score": "5", "Tags": [ "python" ], "Title": "Using Biopython, I would like to optimize this code" }
14357
<p>In python2.7: 2 for loops are always a little inefficient, especially in python. Is there a better way to write the following filter function? It tags a line from a log file, if it is useful. Otherwise the line will be ignored. Because there are different possible interesting lines, it tries different compiled regexes for each line, until it finds one. Note that no more regexes are checked for a line, after the first one successfully matched.</p> <pre><code>def filter_lines(instream, filters): """ignore lines that aren't needed :param instream: an input stream like sys.stdin :param filters: a list of compiled regexes :yield: a tupel (line, regex) """ for line in instream: for regex in filters: if regex.match(line): yield (line,regex) break </code></pre> <p>(The "tagging" is done with the regex object itself, because it can be used later on for retrieving substrings of a line, like filename and row number in an occuring error)</p>
[]
[ { "body": "<p>I wouldn’t worry about performance of the loop here. The slow thing isn’t the loop, it’s the matching of the expressions.</p>\n\n<p>That said, I’d express the nested loops via list comprehension instead.</p>\n\n<pre><code>def filter_lines(instream, filters):\n return ((line, regex) for regex in filters for line in instream if regex.match(line))\n</code></pre>\n\n<p>Or alternatively, using higher-order list functions:</p>\n\n<pre><code>def filter_lines(instream, filters):\n return filter(lambda (line, rx): rx.match(line), itertools.product(instream, filters))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-06T15:55:09.637", "Id": "23254", "Score": "0", "body": "I can't check this right now, but my guess is that your first alternative is way, way faster then my 2 nested for loops. Anyway, it's not perfect, because it still continues to match other regexes if one already successfully matched one line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-06T16:11:10.053", "Id": "23257", "Score": "1", "body": "@erikb Ah, I completely missed that aspect, to be honest. And I’m not sure why this code should be faster than yours. Unfortunately, I don’t see a good way of breaking out of the loop early without two explicit nested loops, sorry." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-06T15:42:26.487", "Id": "14379", "ParentId": "14368", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-06T12:38:30.100", "Id": "14368", "Score": "4", "Tags": [ "python", "python-2.x", "regex", "logging" ], "Title": "Filtering lines in a log file using multiple regexes" }
14368
<p><a href="http://projecteuler.net/problem=11" rel="nofollow">Project Euler #11</a> asks to find the largest product of four numbers of a grid, where the four numbers occur consecutive to each other vertically, horizontally, or diagonally.</p> <p>Here is my solution in Python. In addition to the usual code review, I have 2 extra questions (actually confessions of my laziness):</p> <ol> <li><p>Would it be better if I compared products as in traditional way instead of using max(list)? Like:</p> <pre><code>if (current &gt; max_product): max_product = current </code></pre></li> <li><p>Would it be better if I used proper <code>for</code> loops instead of relying on <code>try</code>? Because in certain cases it gives <code>KeyError</code>. </p></li> </ol> <p>Because of these two shortcuts, I feel like I have cheated. Shall I worry about them or just ignore them?</p> <pre><code>yy = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48""" rows = yy.splitlines() d = {} x = 0 for row in rows: row_cels = row.split() y = 0 d[x] = {} for cell in row_cels: d[x].update({y: int(cell)}) y+=1 x+=1 def product(a, b, al="hori", r=4): try: res = 1 for xx in xrange(r): if al == "hori": # - res *= d[a][b+xx] elif al == "verti": # | res *= d[b+xx][a] elif al == "dia": # \ res *= d[a+xx][b+xx] elif al == "diarev": # / res *= d[a+xx][19-(b+xx)] return res except: return 0 hori = [] verti = [] dia = [] diarev = [] for x in xrange(0, 20): for y in xrange(0, 20): hori.append(product(x,y)) verti.append(product(x, y, "verti")) dia.append(product(x, y, "dia")) diarev.append(product(x, y, "diarev")) print max(max(hori), max(verti), max(dia), max(diarev)) </code></pre>
[]
[ { "body": "<p>The problem is pretty trivial and you should only check the index ranges and don't use </p>\n\n<pre><code>for x in xrange(0, 20):\n for y in xrange(0, 20):\n</code></pre>\n\n<p>but </p>\n\n<pre><code>for x in xrange(16):\n for y in xrange(16):\n</code></pre>\n\n<p>My version:</p>\n\n<pre><code>d = [map(int, row.split()) for row in open('20x20.txt').read().splitlines()]\nvalue = 0\nfor m in xrange(16):\n for n in xrange(16):\n value = max(value,\n # rows\n d[m][n] * d[m][n + 1] * d[m][n + 2] * d[m][n + 3],\n d[m + 1][n] * d[m + 1][n + 1] * d[m + 1][n + 2] * d[m + 1][n + 3],\n d[m + 2][n] * d[m + 2][n + 1] * d[m + 2][n + 2] * d[m + 2][n + 3],\n d[m + 3][n] * d[m + 3][n + 1] * d[m + 3][n + 2] * d[m + 3][n + 3],\n # cols\n d[m][n] * d[m + 1][n] * d[m + 2][n] * d[m + 3][n],\n d[m][n + 1] * d[m + 1][n + 1] * d[m + 2][n + 1] * d[m + 3][n + 1],\n d[m][n + 2] * d[m + 1][n + 2] * d[m + 2][n + 2] * d[m + 3][n + 2],\n d[m][n + 3] * d[m + 1][n + 3] * d[m + 2][n + 3] * d[m + 3][n + 3],\n # diag\n d[m][n] * d[m + 1][n + 1] * d[m + 2][n + 2] * d[m + 3][n + 3],\n d[m + 3][n] * d[m + 2][n + 1] * d[m + 1][n + 2] * d[m][n + 3])\nprint('Max value = %d' % value)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T14:26:26.827", "Id": "23406", "Score": "0", "body": "Hmm. Hardcoding all these calculations looks icky. I’d write a tiny helper functions do do the calculation given a 4-tuple of offsets in a 4x4 field (call as e.g. `get(m, n, 1, 4, 9, 13)` to get the second row in row-major layout)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T16:05:38.397", "Id": "23412", "Score": "0", "body": "May be your idea is correct for a huge code, but such hardcoding makes the code very fast (I would bet that a code optimizer just loves that :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-03T08:53:34.987", "Id": "39901", "Score": "0", "body": "Upvoted, it's a great answer, even though a version without the unrolled loops would have been nice." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T12:44:50.693", "Id": "14449", "ParentId": "14405", "Score": "1" } }, { "body": "<ol>\n<li>It's OK to use <code>max()</code>, reimplementing it yourself won't save time, especially since the Python version is possibly faster if it's written in C. It's possible to be more concise and clearer though: <code>max(hori + verti + dia + diarev)</code>.</li>\n<li>You should use a list of list to represent a matrix, not a list of dictionaries. As <code>cat_baxter</code> points out, <code>d = [map(int, row.split()) for row in open('20x20.txt').read().splitlines()]</code> is enough to populate <code>d</code>. However if you're not familiar with list comprehensions and map, it's OK to use normal loops.</li>\n<li>Python doesn't really have constants, but a convention is to do <code>VERTI = \"verti\"</code> and then use <code>VERTI</code> everywher, denoting that it is a constant (\"verti\" is not a good name, by the way, \"vertical\" is better. Use code completion.)</li>\n<li><code>try: ... except: ...</code> is bad practice, you need to catch specific exceptions (<code>KeyError</code> in this case). And you need to understand why those errors are thrown! This could be a bug in your code.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-03T08:52:54.843", "Id": "25759", "ParentId": "14405", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-07T11:30:40.377", "Id": "14405", "Score": "5", "Tags": [ "python", "programming-challenge", "matrix" ], "Title": "Finding the largest product of four consecutive numbers in a grid" }
14405
<p>This is an OOP Rock, Paper, Scissors program I wrote in Python. I am just learning about using classes and I'd appreciate some advice on improving it.</p> <pre><code># rock.py # example of OOP import random class Rock: def main(self): self.Make_players() print("Best of Five - Let's play!\n") done = False while done == False: self.p1.go_player() self.p2.go_player() print() if self.p2.go == self.p1.go: print("No winner!\n") continue else: temp = self.check(self.p1, self.p2) if temp == False: temp = self.check(self.p2, self.p1) print(self.message, end = " ") print(temp.name + " won this round.") temp.scored() print(self.p1.name + ": " + str(self.p1.score)) print(self.p2.name + ": " + str(self.p2.score)) if self.p1.score == 3: self.winner = self.p1 done = True elif self.p2.score == 3: self.winner = self.p2 done = True else: done = False input() print("The winner was " + self.winner.name + "!") def __init__(self): print("**** Welcome to Rock, Paper, Scissors!****\n") self.winner = False self.main() def Make_players(self): temp = (input("What shall we call Player 1? ")) self.p1 = Player(temp) temp = (input("What shall we call Player 2? ")) self.p2 = Player(temp) def check(self, p_a, p_b): if p_a.go == "rock" and p_b.go == "scissors": self.message = "Rock breaks scissors." return p_a elif p_a.go == "paper" and p_b.go == "rock": self.message = "Paper wraps stone." return p_a elif p_a.go == "scissors" and p_b.go == "paper": self.message = "Scissors cut paper." return p_a else: return False class Player: def __init__(self, name): self.choices = ["rock", "paper", "scissors"] self.score = 0 self.name = name print("Player:", self.name, "created!\n") def go_player(self): self.go = random.choice(self.choices) print(self.name + " chose " + self.go, end = ". ") return self.go def scored(self): self.score += 1 # Main game = Rock() </code></pre>
[]
[ { "body": "<p>I would change <code>check</code> to this</p>\n\n<pre><code>def check(self, p_a, p_b):\n messages = {\"rock\":\"Rock breaks scissors.\",\n \"paper\":\"Paper wraps stone.\",\n \"scissors\":\"Scissors cut paper.\",\n }\n if p_a.go == p_b.go:\n return False\n elif p_a.go == \"rock\" and p_b.go == \"scissors\":\n self.message = messages[p_a.go]\n return p_a\n elif p_a.go == \"paper\" and p_b.go == \"rock\":\n self.message = messages[p_a.go]\n return p_a\n elif p_a.go == \"scissors\" and p_b.go == \"paper\":\n self.message = messages[p_a.go]\n return p_a\n else:\n # if moves are not same and player1 couldn't win than it should be\n # player2 who wins that round\n self.message = messages[p_b.go]\n return p_b\n</code></pre>\n\n<p>And the part where you check moves:</p>\n\n<pre><code>temp = self.check(self.p1, self.p2)\nif not temp: \n print(\"No winner!\\n\")\n continue\n</code></pre>\n\n<p>Edit after antiloquax's comment:</p>\n\n<p>Even it will work that way I don't like it. you can use a class variable <code>messages = {\"rock\":\"...\",}</code> as I did in <code>check</code> method. While printing you just say</p>\n\n<pre><code>print(self.messages[temp.go])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T13:14:45.527", "Id": "23400", "Score": "0", "body": "Thanks savruk. I was thinking about something like that - but the \"else:\" here would just return the player without printing the message \"Paper wraps stone\" etc. I think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T13:29:07.890", "Id": "23402", "Score": "0", "body": "antiloquax, you are right. I didn't think about it. See my edited answer. As a move can only win against a certain move(rock can only beat scissors, scissors can only beat paper ...), it is easy to use a dictionary to define a message for the move." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T12:28:01.570", "Id": "14448", "ParentId": "14441", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T10:29:59.037", "Id": "14441", "Score": "2", "Tags": [ "python", "object-oriented", "game", "rock-paper-scissors" ], "Title": "OOP in Rock, Paper, Scissors program" }
14441
<p>For <a href="http://projecteuler.net/problem=14" rel="nofollow">Project Euler problem 14</a> I wrote code that runs for longer than a minute to give the answer. After I studied about <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">memoization</a>, I wrote this code which runs for nearly 10 seconds on Cpython and nearly 3 seconds on PyPy. Can anyone suggest some optimization tips?</p> <pre><code>import time d={} c=0 def main(): global c t=time.time() for x in range(2,1000000): c=0 do(x,x) k=max(d.values()) for a,b in d.items(): if b==k: print(a,b) break print(time.time()-t) def do(num,rnum): global d global c c+=1 try: c+=d[num]-1 d[rnum]=c return except: if num==1: d[rnum]=c return if num%2==0: num=num/2 do(num,rnum) else: num=3*num+1 do(num,rnum) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>I think you're over complicating your solution, my approach would be something along these lines:</p>\n\n<pre><code>def recursive_collatz(n):\n if n in collatz_map:\n return collatz_map[n]\n if n % 2 == 0:\n x = 1 + recursive_collatz(int(n/2))\n else:\n x = 1 + recursive_collatz(int(3*n+1))\n collatz_map[n] = x\n return x\n</code></pre>\n\n<p>Basically define a memoization map (collatz_map), initialized to <code>{1:1}</code>, and use it to save each calculated value, if it's been seen before, simply return.</p>\n\n<p>Then you just have to iterate from 1 to 1000000 and store two values, the largest Collatz value you've seen so far, and the number that gave you that value.</p>\n\n<p>Something like:</p>\n\n<pre><code>largest_so_far = 1\nhighest = 0\nfor i in range(1,1000000):\n temp = recursive_collatz(i)\n if temp &gt; largest_so_far:\n highest = i\n largest_so_far = temp\n</code></pre>\n\n<p>Using this approach I got:</p>\n\n<p>Problem 14's answer is: 837799.\nTook 1.70620799065 seconds to calculate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T11:25:55.080", "Id": "14446", "ParentId": "14442", "Score": "4" } } ]
{ "AcceptedAnswerId": "14446", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T10:33:42.567", "Id": "14442", "Score": "5", "Tags": [ "python", "optimization", "project-euler" ], "Title": "Optimizing Code for Project Euler Problem 14" }
14442
<p>I'm very very fresh to programming. This is one of my first experiments with Python and I'm wondering in what ways I could have made this program less clunky. Specifically, is there a way that I could have used classes instead of defining my x, y, and z variables globally?</p> <pre><code>def getx(): try: global x x = float(raw_input("Please give your weight (pounds): ")) return x except ValueError: print("Use a number, silly!") getx() def gety(): try: global y y = float(raw_input("what is your current body fat percentage? (&gt;1): ")) return y except ValueError: print("Use a number, silly!") gety() def getz(): try: global z z = float(raw_input("What is your desired body fat percentage? (&gt;1): ")) return z except ValueError: print("Use a number, silly!") getz() def output(): getx() gety() getz() A = (x*(y/100-z/100))/(1-z/100) B = x - A print("Your necessary weight loss is %.1f pounds, and \ your final weight will be %.1f pounds" % (A,B)) more() def more(): again = raw_input("Calculate again? ") if again.lower() == "yes" or \ again.lower() == "y" or \ again.lower() == "sure" or \ again.lower() == "ok" or \ again.lower() == "" or \ again.lower() == "okay": output() elif again.lower() == "no" or \ again.lower() == "n" or \ again.lower() == "nah" or \ again.lower() == "nope": end() else: more() def end(): print("Ok, see ya later!") output() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-09T19:50:05.233", "Id": "23548", "Score": "1", "body": "This belongs on codereview, but I don't see how classes would help. You might want to get rid of the global variables, however and just pass things in via function arguments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-09T19:56:38.307", "Id": "23549", "Score": "0", "body": "since all three \"get\" functions are almost identical, you can reduce them to one that takes a parameter for the input prompt. For the if statements, you can say ... if again.lower() in [\"yes\", \"y\", ...]:" } ]
[ { "body": "<p>all of your functions seem to do the same thing with a different message, so why not condense them and take the message as a parameter?</p>\n\n<pre><code>def get_num(msg):\n num = None\n while num is None:\n try:\n num = float(raw_input(msg))\n except ValueError:\n print(\"Use a number, silly!\")\n\n return num\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>def output():\n x = get_num('Please give your weight (pounds): ')\n y = get_num('what is your current body fat percentage? (&gt;1): ')\n z = get_num('What is your desired body fat percentage? (&gt;1): ')\n A = (x*(y/100-z/100))/(1-z/100)\n B = x - A\n print(\"Your necessary weight loss is %.1f pounds, and \\\nyour final weight will be %.1f pounds\" % (A,B))\n more()\n</code></pre>\n\n<p>in your more function you can condense your ifs with the <code>in</code> operator</p>\n\n<pre><code>def more():\n again = raw_input(\"Calculate again? \")\n\n if again.lower() in [\"yes\", \"y\", \"sure\" , \"ok\", \"\", \"okay\"]:\n output()\n elif again.lower() in [\"no\", \"n\", \"nah\", \"nope\"]:\n end()\n else:\n more()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-09T19:50:26.100", "Id": "14505", "ParentId": "14503", "Score": "4" } }, { "body": "<p>In <code>getx</code>, <code>gety</code> and <code>getz</code> there's no need to use <code>global</code> <em>and</em> <code>return</code>. Also, it would be better to use iteration rather than recursion, like this:</p>\n\n<pre><code>def getx():\n while True:\n try:\n return float(raw_input(\"Please give your weight (pounds): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n</code></pre>\n\n<p>You might also want to use better function and variable names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-09T19:51:18.200", "Id": "14506", "ParentId": "14503", "Score": "1" } }, { "body": "<p>Yes, you definitely can. You can try something in the lines of:</p>\n\n<pre><code>class PersonData(object):\n def __init__(self):\n pass\n\n\n def getx(self):\n try:\n self.x = float(raw_input(\"Please give your weight (pounds): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n self.getx()\n</code></pre>\n\n<p>.. and so on.</p>\n\n<p>And then in your main program:</p>\n\n<pre><code>if __name__ == \"__main__\":\n person = PersonData()\n person.getx()\n person.gety()\n\n... \n\n A = (person.x * (person.y / 100 - person.z / 100))/(1 - person.z / 100)\n</code></pre>\n\n<p>If you get my drift. This is generally if you want to use classes. Otherwise see other answers :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-09T19:54:04.527", "Id": "14507", "ParentId": "14503", "Score": "0" } }, { "body": "<p>The code below condenses your script (fewer lines and redundancy when you remove the triple quote explanations). Honestly, using classes would complicate your function, so unless you need the classes for something else, just do all in the function. Also, typically it is better to not call globals unless you need to. For your purpose, unless there is more to the script, use local variables. </p>\n\n<p>Your script suffers a lot from redundancy. It works fine, but there are easier ways to do it. Instead of reusing again.lower() ==, put all the desired responses into a list. Using 'is...in' checks if your variable is in you list (or string, etc). For example, if var in [\"y\", \"yes\"]: </p>\n\n<p>You can further reduce your redundancy by making a function to do your try/except statements, but I used while statements to show another way to do it. You can then use continue (which resets back to the beginning) if there is an exception and use break to exit the loop if you try statement succeeds. </p>\n\n<p>Note: I tested this on Pythonista for iOS using 2.7. I added in the triple quotes as explanations after confirming the script worked and using as is may throw an indentation error. Removing the triple quote explanations should run it properly. </p>\n\n<pre><code>\"\"\" Unless you are reusing variables, but it all in \nthe same function\"\"\"\n\ndef output():\n\"\"\" Put your inputs in a while statement. Continue on\nexception and break otherwise\"\"\"\n while True:\n try:\n x = float(raw_input(\"Please give your weight (pounds): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n continue\n break\n while True:\n try:\n y = float(raw_input(\"what is your current body fat percentage? (&gt;1): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n continue\n break\n while True:\n try:\n z = float(raw_input(\"What is your desired body fat percentage? (&gt;1): \"))\n except ValueError:\n print(\"Use a number, silly!\")\n continue\n break\n A = (x*(y/100-z/100))/(1-z/100)\n B = x - A\n print(\"Your necessary weight loss is %.1f pounds, and \\\nyour final weight will be %.1f pounds\" % (A,B))\n\n\"\"\" Like before put input into while statement\"\"\"\n\n while True:\n again = raw_input(\"Calculate again? \")\n\n\"\"\" Condense your input options into an if in statement\"\"\"\n if again.lower() in [\"yes\", \"y\", \"sure\", \"ok\", \"\", \"okay\"]:\n output()\n\n\"\"\" Unless No response is important, just use else\ncatchall\"\"\"\n else:\n print(\"Ok, see ya later!\")\n break\noutput()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-19T17:36:06.507", "Id": "305711", "Score": "1", "body": "How and why does this *condense* the original script? Can you explain why you did the things you did?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-19T18:13:45.800", "Id": "305730", "Score": "0", "body": "Also, please verify your indentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-19T18:51:27.013", "Id": "305746", "Score": "0", "body": "@StephenRauch It's fewer lines and less redundancy. For example, instead of rewriting each \"again.lower() ==\" line, it puts all desirable responses into a list and checks if the response is in the list. Unless 'No' is very important, any answer that isn't yes can be 'No' - otherwise, put in a list and check. I explained my changes inside of the script. The while statements removes the need for separate functions. Continue runs the previous try and break ends the statement. This can be further condensed, but I wanted to show the while/continue/break combination with try/except." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-19T18:53:49.337", "Id": "305750", "Score": "0", "body": "@200_success I wrote this on Pythonista on my phone, so indentation may be off compared to desktop version. Also, I added the notes explaining changes after I verified the function worked and the notes are throwing me the indentation errors. Remove the triple quote notes and it all runs fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-19T18:56:38.707", "Id": "305751", "Score": "0", "body": "Thanks for the feedback, but you should edit this explanation into the answer so that it is helpful for future readers. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-19T20:11:59.233", "Id": "305769", "Score": "0", "body": "@StephenRauch I fixed the response to explain better" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-19T17:28:21.173", "Id": "161238", "ParentId": "14503", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-09T19:46:02.923", "Id": "14503", "Score": "1", "Tags": [ "python", "beginner", "calculator" ], "Title": "Python beginner's body fat calculator" }
14503
<p>Basically, I have a list, <code>newtry</code> of blocks, and I want to find a value of <code>catchtype</code> that makes them all return true for <code>block.isCatchExtendable(newhandler, catchtype)</code> or report an error if this can't be done. <code>block.isCatchExtendable</code> returns two values, success and a new type to try on failure.</p> <p>My current code works, but the control flow is very convoluted, with numerous breaks and elses. I was wondering if anyone could think of a better way to arrange things. Also, these are all my own functions, so I am free to change the interfaces, etc.</p> <pre><code>while 1: ct_changed = False for block in newtry: success, newcatchtype = block.isCatchExtendable(newhandler, catchtype) if not success: if catchtype == newcatchtype: #no success and no other types to try, so just break and fail break catchtype, ct_changed = newcatchtype, True else: if ct_changed: continue else: break error('Unable to extend try block completely') </code></pre> <p><strong><code>isCatchExtendible</code>:</strong></p> <pre><code>def isCatchExtendable(self, newhandler, catchtype): return self.catchset.extendible(newhandler, catchtype, self.currentHandlers) </code></pre> <p>This then calls:</p> <pre><code>#If not extendible with current catchtype, returns suggested type as second arg def extendible(self, newhandler, catchtype, outerhs): if catchtype is None: temp = self.catchsets.get(newhandler) if temp is None: return True, None return False, temp.getSingleTType()[0] proposed = ExceptionSet.fromTops(self.env, catchtype) inner = [h for h in self.handlers if h != newhandler and h not in outerhs] outer = [h for h in self.handlers if h in outerhs] sofar = ExceptionSet.fromTops(self.env) for h in inner: sofar = sofar | self.catchsets[h] if (proposed - sofar) != self.catchsets[newhandler]: #Get a suggsted catch type to try instead suggested = (self.catchsets[newhandler] | sofar).getSingleTType() suggested = objtypes.commonSupertype(self.env, suggested, (catchtype, 0)) assert(self.env.isSubClass(suggested[0], 'java/lang/Throwable')) return False, suggested[0] for h in outer: if not proposed.isdisjoint(self.catchsets[h]): return False, catchtype return True, catchtype </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T15:31:44.010", "Id": "23656", "Score": "0", "body": "Could you share the code or algorithm for isCatchExtendable?, I suspect a better interface for that could help here. But I don't know what its doing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T16:01:32.380", "Id": "23657", "Score": "0", "body": "@Winston I added the code for isCatchExtendable. The basic idea is to determine whether adding another catch handler to a try block will preserve the semantics." } ]
[ { "body": "<p>First off, a pet peeve of mine: <code>while 1</code> makes no semantical sense. You want <code>while True</code>.</p>\n\n<p>However, in your case you actually want <code>while ct_changed</code>:</p>\n\n<pre><code>ct_changed = True\nwhile ct_changed:\n ct_changed = False\n for block in newtry:\n success, newcatchtype = block.isCatchExtendable(newhandler, catchtype)\n if not success:\n if catchtype == newcatchtype:\n break\n else:\n catchtype = newcatchtype\n ct_changed = True\n</code></pre>\n\n<p>Alternatively, you can flatten the nesting level by inverting the <code>if not success</code> conditional, and continuing:</p>\n\n<pre><code> …\n if success:\n continue\n\n if catchtype == newcatchtype:\n break\n\n catchtype = newcatchtype\n ct_changed = True\n</code></pre>\n\n<p>(In fact, I’d probably go for this.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-12T16:05:00.333", "Id": "23659", "Score": "0", "body": "How do you detect the error condition then? Edit: Nevermind, you can just put the error immediately after the `if catchtype == newcatchtype` instead of breaking." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T16:03:05.340", "Id": "14559", "ParentId": "14556", "Score": "6" } }, { "body": "<p>I think your algorithm suffers from awkward splitting of code. The suggestion logic really should be part of your algorithm, not hidden in some other code.</p>\n\n<p>If I'm understanding correctly, <code>isExtendable</code> really considers three different sets of exception classes</p>\n\n<ol>\n<li>May Catch: These exceptions are caught by handlers before the one of interest, it is safe to catch these as they will already be caught</li>\n<li>Should Catch: These are the exceptions which the given handler should be catching</li>\n<li>Must Not Catch: These are the exceptions which handlers after the one of interest catch. These must not be caught, as that would prevent the current handler from catching them.</li>\n</ol>\n\n<p>We want to pick a single exception type that fulfills the requirement. It must catch everything in Should Catch, some subset of things in May Catch, and nothing in Must Not Catch.</p>\n\n<p>We can combine all May Catch exceptions by taking their intersection across all blocks. Its only safe to catch them if they will already have been caught across all the blocks.</p>\n\n<p>We can combine all the Must Not Catch, by taking their union across all blocks. The should catch, I assume, is the same across all blocks.</p>\n\n<p>Hence your algorithm looks something like:</p>\n\n<pre><code>may_catch = intersection(block.may_catch for block in blocks)\nmay_not_catch = union(block.may_not_catch for block in blocks)\n\nfor catch_type in catch_types.iterparents():\n will_catch = catch_type.catchset()\n if will_catch - may_catch == should_catch and will_catch.isdisjoint(may_not_catch):\n break # found it\nelse:\n error('no type suffices')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:37:32.630", "Id": "23704", "Score": "0", "body": "Nice idea. I didn't think of taking the intersections across multiple blocks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-13T15:04:55.387", "Id": "14615", "ParentId": "14556", "Score": "3" } } ]
{ "AcceptedAnswerId": "14615", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-11T14:58:00.427", "Id": "14556", "Score": "4", "Tags": [ "python" ], "Title": "Checking if blocks are catch extendable" }
14556
<p>I need to solve this problem in Python 3 (within 3 sec):</p> <blockquote> <p><code>A</code> is a given (NxM) rectangle, filled with characters "a" to "z". Start from <code>A[1][1]</code> to <code>A[N][M]</code> collect all character which is only one in its row and column, print them as a string.</p> <p>Input:</p> <p>\$N\$, \$M\$ in first line (number of row and column \$1 \le N\$, \$M \le &gt; 1000\$). Next, \$N\$ lines contain exactly \$M\$ characters.</p> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>A single string </code></pre> <p>Sample input 1:</p> <pre class="lang-none prettyprint-override"><code>1 9 arigatodl </code></pre> <p>Sample output 1:</p> <pre class="lang-none prettyprint-override"><code>rigtodl </code></pre> <p>Sample input 2:</p> <pre class="lang-none prettyprint-override"><code>5 6 cabboa kiltik rdetra kelrek dmcdnc </code></pre> <p>Sample output 2:</p> <pre class="lang-none prettyprint-override"><code>codermn </code></pre> </blockquote> <p>This is still not fast enough when \$N\$, \$M\$ = 1000. I'd like suggestions on improving the speed, or any other ways to solve the given problem, as long as the solution is in Python 3 and is faster than mine.</p> <pre class="lang-py prettyprint-override"><code>from operator import itemgetter Words,Chars,answer=[],"abcdefghijklmnopqrstuvwxyz","" N,M=[int(i) for i in input().split()] for _ in range(N): Words.append(input()) # got the inputs for row,word in enumerate(Words): # going through each words Doubts=[] # collect chars only one in its row. for char in Chars: if (word.count(char)==1): Doubts.append((char,word.index(char))) for case in sorted(Doubts,key=itemgetter(1)): #sorting by index doubtless=True #checking whether 1 in its column or not. for i in range(N): if (Words[i][case[1]]==case[0] and i!=row): doubtless=False break if (doubtless): answer+=case[0] #if char is one in its row and column, adds to answer. print (answer) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T19:21:32.937", "Id": "24060", "Score": "4", "body": "Not an observation about optimization, but why aren't you using [PEP8 guidelines](http://www.python.org/dev/peps/pep-0008/) to write your code? It's not a dealbreaker by any means, but 1) Why don't you have spaces between operators and 2) Capital/CamelCase is usually reserved for class definitions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T02:31:43.377", "Id": "24078", "Score": "0", "body": "Thanks, but this time I wasn't wondering about how it looks. I was worrying about how it works :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T11:23:17.580", "Id": "24088", "Score": "0", "body": "For info, this has been [cross-posted at StackOverflow](http://stackoverflow.com/questions/11969733/optimisations-for-this-code-in-python-3)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T11:49:53.637", "Id": "24090", "Score": "0", "body": "You didn't have to delete it, just **declare** the cross-posting. Then people can use the hyperlink to determine whether you still need assistance. It's about being considerate of other people's time, and as I said on the other thread, this has been part of netiquette for thirty years or so." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T23:03:05.750", "Id": "24094", "Score": "0", "body": "I'll take a look at it a bit more in depth, but it appears that you're iterating over the elements in the matrix more times then necessary. You *should* be able to write an algorithm that does at most `N * M * k_nm` checks, where k is the number of unique letters in each row/column. (by unique I mean a member of the set of letters, I don't mean that they don't repeat in the sequence)" } ]
[ { "body": "<p>I would suggest to create a 1000x1000 testcase and measure the performance before the optimization process. Please use the following test generator:</p>\n\n<pre><code>import os\nimport random\n\nf = open('1000x1000.in','w')\nf.write('1000 1000\\n')\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\nfor _ in range(1000):\n f.write(''.join([ALPHABET[random.randint(0, len(ALPHABET)-1)] for _ in range(1000)]) + '\\n')\nf.close()\n</code></pre>\n\n<p>After that just run it and measure the performance of your application. I got about <strong>47 ms</strong> on my pretty old C2D E7200.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:26:15.317", "Id": "15140", "ParentId": "14766", "Score": "2" } }, { "body": "<p>You could improve part of your loop.</p>\n\n<pre><code>Doubts=[] \nfor char in Chars:\n if (word.count(char)==1):\n Doubts.append((char,word.index(char)))\n</code></pre>\n\n<p>Can be done with list-comprehension.</p>\n\n<pre><code> Doubts = [(char, word.index(char)) for char in Chars if word.count(char) == 1]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T12:45:45.007", "Id": "20121", "ParentId": "14766", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-17T04:54:45.727", "Id": "14766", "Score": "5", "Tags": [ "python", "performance" ], "Title": "Printing characters in a matrix as a string" }
14766
<p>I wrote a program to take a list of letters and from every permutation of them and check that against the dictionary and print out valid words. The constraints are that there is a control letter which means that letter must be in the word, and you can't repeat any letters.</p> <p>Everything works, but the running time is way too long. I'm hoping to get some feedback on how to cut down my running time in O-notation. Also, if you know the running times of the built in function, that would be great. Also, comment if my code style is not what it should be for Python.</p> <pre><code>import itertools from multiprocessing import Process, Manager dictionary_file = '/usr/share/dict/words' letter_list = ['t','b','a','n','e','a','c','r','o'] control_letter = 'e' manager = Manager() word_list = manager.list() def new_combination(i, dictionary): comb_list = itertools.permutations(letter_list,i) for item in comb_list: item = ''.join(item) if(item in dictionary): word_list.append(item) return def make_dictionary(): my_list = [] dicts = open(dictionary_file).readlines() for word in dicts: if control_letter in word: if(len(word) &gt;3 and len(word)&lt;10): word = word.strip('\n') my_list.append(word) return my_list def main(): dictionary = make_dictionary() all_processes = [] for j in range(9,10): new_combo = Process(target = new_combination, args = (j,dictionary,)) new_combo.start() all_processes.append(new_combo) while(all_processes): for proc in all_processes: if not proc.is_alive(): proc.join() all_processes = [proc for proc in all_processes if proc.is_alive()] if(len(all_processes) == 0): all_processes = None print list(set(word_list)) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T14:32:15.810", "Id": "99399", "Score": "0", "body": "This is a good question, thank you for taking the time to form it so that we can help show you the proper coding styles and techniques. We all look forward to seeing more of your posts!" } ]
[ { "body": "<pre><code>import itertools\nfrom multiprocessing import Process, Manager\n\ndictionary_file = '/usr/share/dict/words'\nletter_list = ['t','b','a','n','e','a','c','r','o']\ncontrol_letter = 'e'\n</code></pre>\n\n<p>By convention, global constant should be named in ALL_CAPS</p>\n\n<pre><code>manager = Manager()\nword_list = manager.list()\n\ndef new_combination(i, dictionary):\n comb_list = itertools.permutations(letter_list,i)\n for item in comb_list:\n item = ''.join(item)\n if(item in dictionary):\n</code></pre>\n\n<p>You don't need the parens. Also, dictionary in your code is a list. Checking whether an item is in a list is rather slow, use a set for fast checking.</p>\n\n<pre><code> word_list.append(item)\n</code></pre>\n\n<p>Having a bunch of different processes constantly adding onto a single list, performance will be decreased. You are probably better off adding onto a seperate list and then using extend to combine them at the end.</p>\n\n<pre><code> return\n</code></pre>\n\n<p>There is no point in an empty return at the end of a function </p>\n\n<pre><code>def make_dictionary():\n</code></pre>\n\n<p>I'd call this <code>read_dictionary</code>, since you aren't really making the dictionary</p>\n\n<pre><code> my_list = []\n</code></pre>\n\n<p>Name variables for what they are for, not their types</p>\n\n<pre><code> dicts = open(dictionary_file).readlines()\n for word in dicts:\n</code></pre>\n\n<p>Actually, you could just do <code>for word in open(dictionary_file)</code> for the same effect</p>\n\n<pre><code> if control_letter in word:\n if(len(word) &gt;3 and len(word)&lt;10):\n word = word.strip('\\n')\n</code></pre>\n\n<p>I recommend stripping before checking lengths, just to make it easier to follow what's going on</p>\n\n<pre><code> my_list.append(word)\n return my_list\n\ndef main():\n dictionary = make_dictionary()\n all_processes = []\n for j in range(9,10):\n new_combo = Process(target = new_combination, args = (j,dictionary,))\n</code></pre>\n\n<p>You don't need that last comma</p>\n\n<pre><code> new_combo.start()\n all_processes.append(new_combo)\n while(all_processes):\n</code></pre>\n\n<p>Parens unneeded</p>\n\n<pre><code> for proc in all_processes:\n if not proc.is_alive():\n proc.join()\n all_processes = [proc for proc in all_processes if proc.is_alive()]\n</code></pre>\n\n<p>What happens if a process finishes between the last two lines? You'll never call proc.join() on it.</p>\n\n<pre><code> if(len(all_processes) == 0):\n all_processes = None\n</code></pre>\n\n<p>an empty list is already considered false, so there is no point in this.</p>\n\n<p>Actually, there is no reason for most of this loop. All you need is </p>\n\n<pre><code>for process in all_processes:\n process.join()\n</code></pre>\n\n<p>It'll take care of waiting for all the processes to finish. It'll also be faster since it won't busy loop. </p>\n\n<pre><code> print list(set(word_list))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>I've given a few suggestions for speed along the way. But what you should really do is invert the problem. Don't look at every combination of letters to see if its a word. Look at each word in the dictionary and see if you can form it out of your letters. That should be faster because there are many fewer words in the dictionary then possible combination of letters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T15:02:26.773", "Id": "14831", "ParentId": "14828", "Score": "5" } } ]
{ "AcceptedAnswerId": "14831", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-19T11:48:10.010", "Id": "14828", "Score": "6", "Tags": [ "python", "combinatorics" ], "Title": "Generating words based on a list of letters" }
14828
<p>It's based on the <a href="http://en.wikipedia.org/wiki/Hardy%E2%80%93Weinberg_principle" rel="nofollow">Hardy-Weinberg formula</a>. I used the easygui module because I don't fully understand events in Tkinter yet. It's my first relatively useful script so any constructive criticism would be helpful.</p> <pre><code>from __future__ import division import sys from easygui import * def calculate_frequency(recessive,total): q = (recessive/total)**0.5 #square root of q^2 p = 1-q #since p + q = 1, p = 1-q hzDominantNum = round((p**2)*total,2) #number of homozygous dominant, not percent hzRecessiveNum = round((q**2)*total,2) heterozygousNum = round((2*p*q)*total,2) hzDominantFreq = round((p**2)*100,2) #frequency (percent) hzRecessiveFreq = round((q**2)*100,2) heterozygousFreq = round((2*p*q)*100,2) return hzDominantNum,hzRecessiveNum,heterozygousNum,hzDominantFreq,hzRecessiveFreq,heterozygousFreq #returns all calculations to be printed while True: #loops program until terminated msg = "Leave Total as 100 if you want to enter the percent." #main message lets user know how to input as percent fieldNames = ["How many have the recessive trait","Total population"] fieldValues = ['',100] #first one is blank, the second is defaulted to 100 to make inputing percents easier test = 0 #tests if the proper information has been entered. Test will equal 1 if the conditions are met. while test == 0: fieldValues = multenterbox(msg=msg, title='Enter information about the population', fields=fieldNames, values=fieldValues) if fieldValues == None: sys.exit() #None is returned when the user clicks "Cancel" elif not fieldValues[0].isdigit() or not fieldValues[1].isdigit(): if not ccbox("Please fill out all fields.",'ERROR',('OK','Quit')): sys.exit() elif int(fieldValues[0])&gt;int(fieldValues[1]): if not ccbox("The amount of people with the recessive trait can't be bigger than the total population.",'ERROR',('OK','Quit')): sys.exit() else: test=1 recessive = int(fieldValues[0]) total = int(fieldValues[1]) hzDominantNum,hzRecessiveNum,heterozygousNum,hzDominantFreq,hzRecessiveFreq,heterozygousFreq = calculate_frequency(recessive,total) #displays all the information msg = str(hzDominantNum)+'/'+str(total)+' ('+str(hzDominantFreq)+'%) are normal (homozygous dominant).\n'+''' '''+str(heterozygousNum)+'/'+str(total)+' ('+str(heterozygousFreq)+'%) are carriers (heterozygous).\n'+''' '''+str(hzRecessiveNum)+'/'+str(total)+' ('+str(hzRecessiveFreq)+'%) have the recessive trait (homozygous recessive).' #sees if user wants to quit or continue if not ccbox(msg=msg, title='RESULTS', choices=('Continue', 'Quit'), image=None): sys.exit() </code></pre>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>call variables <code>this_way</code> not <code>thisWay</code></li>\n<li>use less comments</li>\n<li>put your interaction with user into separate functions</li>\n<li>if code will be splited properly you will be able to user <code>return</code> and <code>while True:</code> instead of <code>test</code> variable</li>\n<li>return object or dict from <code>calculate_frequency</code> rather than long tuple</li>\n<li><p>don't create strings like that:</p>\n\n<p>str(hzDominantNum)+'/'+str(total)+' ('+str(hzDominantFreq)+'%) are normal (homozygous dominant).\\n'</p></li>\n</ul>\n\n<p>this is mutch better:</p>\n\n<pre><code>'%f/%f (%d%%) are normal (homozygous dominant).\\n' % (hzDominantNum, total, hzDominantFreq)\n</code></pre>\n\n<p>if you have to run this as a program do it this way:</p>\n\n<pre><code>def main():\n print \"test\"\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T00:21:19.837", "Id": "24142", "Score": "0", "body": "Good advice. What exactly is the purpose of adding a main loop if I want to run it as a program?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:47:03.157", "Id": "24155", "Score": "0", "body": "that's not a main _loop_, but the `if __name__ == \"__main__\":` entrypoint is used so that you can _also_ reuse `module.calculate_frequency` from another file later if you want to; this also makes it much easier to write unit tests" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T21:09:35.167", "Id": "14873", "ParentId": "14869", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-20T19:08:26.163", "Id": "14869", "Score": "2", "Tags": [ "python" ], "Title": "A simple calculator to calculate the frequency of a recessive allele" }
14869
<p>I wrote the following code to test a score-keeping class. The idea was to keep score of a game such that the score was kept across multiple classes and methods. </p> <p>I'm looking for any input on being more efficient, more 'pythonic' and/or just better.</p> <pre><code>import os class Foo(): def __init__(self): self.stored_end = 0 def account(self, a, b): c = float(a) + b print a print b print c self.stored_end = c print self.stored_end def testy(self, q, v): print "\n" print " _ " * 10 z = float(q) + v print self.stored_end self.stored_end = self.stored_end + z print " _ " * 10 print self.stored_end class Bar(): def __init__(self): pass def zippy(self, a, b): print " _ " * 10 print "this is zippy" foo.testy(a, b) class Baz(): def __init__(self): pass def cracky(self, g, m): y = g + m print " _ " * 10 print "calling stored_end" foo.stored_end = foo.stored_end + y print " _ " * 10 print "this is cracky" print "y = %r" % y print foo.stored_end os.system("clear") foo = Foo() foo.account(5, 11) foo.testy(100, 100) bar = Bar() bar.zippy(10, 100) baz = Baz() baz.cracky(1000, 1) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T13:41:33.970", "Id": "24154", "Score": "0", "body": "Like Matt, I can't really tell what you're trying to achieve: this code is obviously incomplete (there are several references to a `foo` that is never declared), and seems far from minimal. Could you show some runnable code which demonstrates (as simply as possible) what you need to do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:07:07.903", "Id": "24178", "Score": "0", "body": "This code runs when I use it. Maybe you need to scroll up to seethe bottom of the code? If not, I think you might be talking over my head." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:21:45.057", "Id": "24179", "Score": "0", "body": "Oh yeah, my mistake! Those references are to the global `foo` declared _after_ it's used, which is ... unusual." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:42:21.650", "Id": "24180", "Score": "0", "body": "Fair enough. Please rip up the code and tell me where I can do beter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T23:04:26.457", "Id": "24209", "Score": "0", "body": "Also, the fact that a piece of code runs without throwing exceptions is not the same thing as code that has the correct behavior ;)" } ]
[ { "body": "<p>I'm confused on what you are trying to achieve with the code example above, but in general it's usually a bad idea to modify the instance fields of a class from outside of that class. So updating foo.stored_end from another class directly (versus creating a method in foo that takes the new value as a parameter) is usually a bad idea. Here's an example that uses a Game class to keep track of Players and calculate a score.</p>\n\n<pre><code>class Player():\n def __init__(self):\n self.score = 0\n\n def increaseScore(self,x):\n self.score += x\n\n def decreaseScore(self,x):\n self.score -= x\n\nclass Game():\n def __init__(self):\n self.players = []\n\n def addPlayer(self,p):\n self.players.append(p)\n\n def removePlayer(self,p):\n self.players.remove(p)\n\n def printScore(self):\n score = 0\n for p in self.players:\n score += p.score\n print \"Current Score {}\".format(score)\n\np1 = Player()\np2 = Player()\n\ngame = Game()\ngame.addPlayer(p1)\ngame.addPlayer(p2)\n\np2.increaseScore(1)\np1.increaseScore(5)\ngame.printScore()\n\ngame.removePlayer(p1)\ngame.removePlayer(p2)\ngame.printScore()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T07:18:08.827", "Id": "14884", "ParentId": "14881", "Score": "0" } }, { "body": "<p>I think what you may be looking for is the <code>Borg</code> design pattern. It's meant for a single class to maintain state between multiple instances. Not exactly what you're looking for but you could modify it to also maintain state across multiple classes, perhaps by specifying a global for <code>shared state</code>:</p>\n\n<pre><code>## {{{ http://code.activestate.com/recipes/66531/ (r2)\nclass Borg:\n __shared_state = {}\n def __init__(self):\n self.__dict__ = self.__shared_state\n # and whatever else you want in your class -- that's all!\n## end of http://code.activestate.com/recipes/66531/ }}}\n</code></pre>\n\n<p>Here are some links to various code examples of this, non chronological:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/747888/1431750\">Python borg pattern problem</a></li>\n<li><a href=\"http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-stinkin-singleton-the-bo/\" rel=\"nofollow noreferrer\">Singleton? We don't need no stinkin' singleton: the Borg design pattern (Python recipe)</a></li>\n<li><a href=\"https://raw.github.com/faif/python-patterns/master/borg.py\" rel=\"nofollow noreferrer\">Usage example</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T11:28:06.683", "Id": "15024", "ParentId": "14881", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T03:30:05.403", "Id": "14881", "Score": "1", "Tags": [ "python", "classes" ], "Title": "Python: keeping track of info across classes by storing a variable to self" }
14881
<p>Let's say I want to parse audio track information into two variables like this:</p> <ul> <li><code>'2/15'</code> -> <code>track = 2, num_tracks = 15</code></li> <li><code>'7'</code> -> <code>track = 7, num_tracks = None</code></li> </ul> <p>What's an elegant way to do this in Python? For example:</p> <pre><code>track, num_tracks = track_info.split('/') </code></pre> <p>This works for the first format, but not for the second, raising <em>ValueError: need more than 1 value to unpack</em>. So I came up with this:</p> <pre><code>try: track, num_tracks = track_info.split('/', 1) except: track, num_tracks = track_info, None </code></pre> <p>How can this be more elegant or better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T07:34:41.070", "Id": "24173", "Score": "3", "body": "Don't use a bare `except` though; catch specific exceptions only. You'd be amazed how many bugs could be masked by blanket `except` statements." } ]
[ { "body": "<p>This may be overly generic, but could be reused. It \"pads\" a sequence by making it long enough to fit the requested length, adding as many repetitions as necessary of a given padding item.</p>\n\n<pre><code>def right_pad(length, seq, padding_item=None):\n missing_items = length - len(seq)\n return seq + missing_items * [ padding_item]\n</code></pre>\n\n<p>If the sequence is long enough already, nothing will be added.\nSo the idea is to extend to 2 elements with None, if the second is not present:</p>\n\n<pre><code>track, num_tracks = right_pad(2, track_info.split('/'))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T16:16:20.803", "Id": "14906", "ParentId": "14901", "Score": "6" } }, { "body": "<blockquote>\n<pre><code>try:\n track, num_tracks = track_info.split('/', 1)\nexcept:\n track, num_tracks = track_info, None\n</code></pre>\n</blockquote>\n\n<p>Honestly, this is not a terrible solution. But you should almost never use <code>except:</code>; you should catch a specific exception.</p>\n\n<p>Here is another way:</p>\n\n<pre><code>tracks, _, num_tracks = text.partition('/')\nreturn int(tracks), int(num_tracks) if num_tracks else None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-10T18:05:29.607", "Id": "107580", "Score": "1", "body": "I would remove the parameter maxsplit=1 to split. If the text contains more than one '/' it is a good thing to get an error." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-08-21T17:04:17.573", "Id": "14907", "ParentId": "14901", "Score": "19" } }, { "body": "<p>You can concatenate an array with your default value.</p>\n\n<pre><code>track, num_tracks = (track_info.split('/', 1) + [None])[:2]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-01T14:22:47.970", "Id": "200753", "ParentId": "14901", "Score": "5" } } ]
{ "AcceptedAnswerId": "14907", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T03:26:11.547", "Id": "14901", "Score": "32", "Tags": [ "python", "parsing", "error-handling", "null" ], "Title": "Using default None values in Python when assigning split() to a tuple" }
14901
<p>Here is my code;</p> <pre><code>import socket def read_line(sock): "read a line from a socket" chars = [] while True: a = sock.recv(1) chars.append(a) if a == "\n" or a == "": return "".join(chars) def read_headers(sock): "read HTTP headers from an internet socket" lines = [] while True: line = read_line(sock) if line == "\n" or line == "\r\n" or line == "": return "".join(lines) lines.append(line) def parse_headers(headerstr): "Return a dict, corresponding each HTTP header" headers = {} for line in headerstr.splitlines(): k, _, v = line.partition(":") headers[k] = v.strip() return headers http_request = """GET / HTTP/1.1 Host: {} """ site = "www.google.com.tr" conn = socket.create_connection((site,80)) conn.sendall(http_request.format(site)) headersstr = read_headers(conn) headersdict = parse_headers(headersstr) if "Transfer-Encoding" in headersdict and headersdict["Transfer-Encoding"] == "chunked": content = "" else: content = conn.recv(headersdict["Content-Length"]) print content conn.close() </code></pre> <p>Can you please comment on how I am using sockets. Is it correct practive to read characters one by one from socket as I did in read_line function? Are there any other mistakes I am doing?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T15:50:00.620", "Id": "24434", "Score": "0", "body": "Code Review strictly improves working code, we aren't here to help debug your code.You can ask on Stackoverflow, but you should narrow down your question first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T17:50:54.513", "Id": "24437", "Score": "0", "body": "@WinstonEwert I edited my question and stripped buggy part. Is it ok now? If so, can you reopen?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:35:41.310", "Id": "24456", "Score": "0", "body": "reopened your question" } ]
[ { "body": "<p>Reading one byte at a time is bad idea, because it won't buffer the input. Instead, you'll probably get a system call for each byte which will be really inefficient.</p>\n\n<p>Easiest solution is to use <code>makefile</code></p>\n\n<pre><code>myfile = sock.makefile('r') \n</code></pre>\n\n<p>Then you can treat myfile like a file, including using methods like readline. That'll be more efficient then your version.</p>\n\n<p>It seems a bit of waste to have readheaders() convert all the headers into one long string, only to have parseheaders() split it apart again.</p>\n\n<pre><code>if \"Transfer-Encoding\" in headersdict and headersdict[\"Transfer-Encoding\"] == \"chunked\":\n</code></pre>\n\n<p>I'd use <code>if headersdict.get('Transfer-Encoding') == 'chunked':</code>, if the key is not present, <code>get</code> will return None, and you'll have the same effect as before.</p>\n\n<p>Of course, for serious stuff, you'd want to use the builtin python libraries for this sort of thing. But as long as you are doing it to learn, all well and good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T21:01:06.777", "Id": "24459", "Score": "0", "body": "Thanks for the answer. Does it matter when I use makefile. Should I use it after or before I make HTTP request?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T21:30:49.520", "Id": "24460", "Score": "0", "body": "@yasar11732, shouldn't matter." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T20:07:45.003", "Id": "15074", "ParentId": "15038", "Score": "3" } } ]
{ "AcceptedAnswerId": "15074", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:45:14.523", "Id": "15038", "Score": "2", "Tags": [ "python" ], "Title": "Working with sockets" }
15038
<p>I put together this code to for the Udacity cs101 exam. It passes the test, but I feel their must be a more elegant way to manage this problem. Some help from a module (like itertools).</p> <p>Question 8: Longest Repetition</p> <p>Define a procedure, longest_repetition, that takes as input a list, and returns the element in the list that has the most consecutive repetitions. If there are multiple elements that have the same number of longest repetitions, the result should be the one that appears first. If the input list is empty, it should return None.</p> <pre><code>def longest_repetition(alist): alist.reverse() largest = [] contender = [] if not alist: return None for element in alist: if element in contender: contender.append(element) if len(contender) &gt;= len(largest): largest = contender else: contender = [] contender.append(element) if not largest: return contender[0] else: return largest[0] #For example, print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1]) # 3 print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']) # b print longest_repetition([1,2,3,4,5]) # 1 print longest_repetition([]) # None </code></pre>
[]
[ { "body": "<p>Take a look at <a href=\"http://docs.python.org/library/collections.html#collections.Counter\" rel=\"nofollow\">collections.Counter</a>. It will do your work for you.</p>\n\n<pre><code>&gt;&gt;&gt; Counter(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']).most_common(1)\n[('b', 3)]\n</code></pre>\n\n<p>UPD. Full example:</p>\n\n<pre><code>from collections import Counter\n\ndef longest_repetition(alist):\n try:\n return Counter(alist).most_common(1)[0][0]\n except IndexError:\n return None\n</code></pre>\n\n<p>If you ask more question, please ask.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T09:30:53.583", "Id": "24507", "Score": "0", "body": "The OP wanted *consecutive* repetitions, but `Counter('abbbacada').most_common(1)` returns `[('a', 4)]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T13:12:57.420", "Id": "24511", "Score": "0", "body": "I've updated my answer for you, @Gareth Rees." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T13:23:06.110", "Id": "24512", "Score": "0", "body": "According to the OP, `longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1])` should return `3`, but your updated function returns `2`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T13:31:26.580", "Id": "24514", "Score": "0", "body": "Ok, I didn't notice _consecutive_ word. So my solution doesn't work" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T05:59:55.403", "Id": "15091", "ParentId": "15089", "Score": "0" } }, { "body": "<p>First, I'll comment on your code, and then I'll discuss a more \"Pythonic\" way to do it using features in the Python standard library.</p>\n\n<ol>\n<li><p>There's no docstring. What does the function do?</p></li>\n<li><p>You start out by reversing the list. This is a destructive operation that changes the list. The caller might be surprised to find that their list has changed after they called <code>longest_repetition</code>! You could write <code>alist = reversed(alist)</code> instead, but it would be even better if you didn't reverse the list at all. By changing the <code>&gt;=</code> test to <code>&gt;</code> you can ensure that the earliest longest repetition is returned, while still iterating forwards over the input.</p></li>\n<li><p>You build up a list <code>contender</code> that contains the most recent series of repetitions in the input. This is wasteful: as <code>contender</code> gets longer, the operation <code>element in contender</code> takes longer. Since you know that this list consists only of repetitions of an element, why not just keep one instance of the element and a count of how many repetitions there have been?</p></li>\n<li><p>You only update <code>largest</code> when you found a repetition. That means that if there are no consecutive repetitions in the input, <code>largest</code> will never be updated. You work around this using an <code>if</code> statement at the end to decide what to return. But if you <em>always</em> updated <code>largest</code> (whether you found a repetition or not) then you wouldn't need the <code>if</code> statement.</p></li>\n<li><p>By suitable choice of initial values for your variables, you can avoid the <code>if not alist</code> special case. And that would allow your function to work for any Python iterable, not just for lists.</p></li>\n</ol>\n\n<p>So let's apply all those improvements:</p>\n\n<pre><code>def longest_repetition(iterable):\n \"\"\"\n Return the item with the most consecutive repetitions in `iterable`.\n If there are multiple such items, return the first one.\n If `iterable` is empty, return `None`.\n \"\"\"\n longest_element = current_element = None\n longest_repeats = current_repeats = 0\n for element in iterable:\n if current_element == element:\n current_repeats += 1\n else:\n current_element = element\n current_repeats = 1\n if current_repeats &gt; longest_repeats:\n longest_repeats = current_repeats\n longest_element = current_element\n return longest_element\n</code></pre>\n\n<hr>\n\n<p>So is there a more \"Pythonic\" way to implement this? Well, you could use <a href=\"http://docs.python.org/library/itertools.html#itertools.groupby\" rel=\"nofollow\"><code>itertools.groupby</code></a> from the Python standard library. Perhaps like this:</p>\n\n<pre><code>from itertools import groupby\n\ndef longest_repetition(iterable):\n \"\"\"\n Return the item with the most consecutive repetitions in `iterable`.\n If there are multiple such items, return the first one.\n If `iterable` is empty, return `None`.\n \"\"\"\n try:\n return max((sum(1 for _ in group), -i, item)\n for i, (item, group) in enumerate(groupby(iterable)))[2]\n except ValueError:\n return None\n</code></pre>\n\n<p>However, this code is not exactly clear and easy to understand, so I don't think it's actually an improvement over the plain and simple implementation I gave above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T12:52:37.363", "Id": "25094", "Score": "0", "body": "I realize this has been up for a while, but I wanted to point out that there's a further small optimization that could be made in the \"easy to understand\" version. You can move the `if` block that checks `current_repeats > longest_repeats` into the preceding `else` block (before the code that's already there), and avoid it running every time the longest repeated sequence gets longer. You will also need to do the test at the end of the loop, though, just before returning (in case the longest consecutive repetition is at the end)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T13:09:03.410", "Id": "25096", "Score": "0", "body": "Yes, you could do that, but you'd have to balance the optimization against the duplication of the test. I came down on the side of simplicity here, but I can understand someone else deciding the other way." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T10:03:38.387", "Id": "15095", "ParentId": "15089", "Score": "4" } }, { "body": "<p>Gareth's itertools method can be written a bit better:</p>\n\n<pre><code>def iterator_len(iterator):\n return sum(1 for _ in iterator)\n\ndef longest_repetition(iterable):\n \"\"\"\n Return the item with the most consecutive repetitions in `iterable`.\n If there are multiple such items, return the first one.\n If `iterable` is empty, return `None`.\n \"\"\"\n try:\n return max(groupby(iterable), \n key = lambda (key, items): iterator_len(items))[0]\n except ValueError:\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:40:41.797", "Id": "24568", "Score": "0", "body": "The use of `key` is a definite improvement—good spot! But the use of `len(list(items))` is not an improvement on `sum(1 for _ in items)` as it builds an unnecessary temporary list in memory that is then immediately thrown away. This makes the memory usage O(*n*) instead of O(1)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:12:40.913", "Id": "24576", "Score": "0", "body": "@GarethRees you're right. I feel like using sum isn't the most clear, and I really wish python had a builtin function for it. I made myself feel a bit better by putting it into a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:21:08.357", "Id": "24580", "Score": "0", "body": "Yes, it's a frustrating omission from `itertools`. Such a function gets proposed from time to time ([e.g. here](http://mail.python.org/pipermail/python-ideas/2010-August/007921.html)) but the opinion of the Python developers seems to be that such a function would be a bad idea because it would lead to an infinite loop if passed an infinite generator ([e.g. here](http://mail.python.org/pipermail/python-ideas/2010-August/007926.html))." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T13:04:57.493", "Id": "15139", "ParentId": "15089", "Score": "2" } } ]
{ "AcceptedAnswerId": "15095", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T04:58:16.900", "Id": "15089", "Score": "2", "Tags": [ "python" ], "Title": "pythonic longest repetition" }
15089
<p>I am studying descriptors. They work with class varibles out of the box, but I want them to operate on instance variables too, so I did this:</p> <pre><code>class NumberDescriptor(object): def __init__(self,name): self.name = name def __set__(self, instance, value): if not isinstance(value, int): raise ValueError("%s is not a number." % value) else: setattr(instance, self.name, value) def __get__(self, instance, owner): return getattr(instance, self.name) class Human(object): age = NumberDescriptor("_age") def __init__(self,age): self.age = age a = Human(12) print a.age b = Human("osman") print b.age </code></pre> <p>Is this the right way to go about this?</p>
[]
[ { "body": "<p>That looks reasonable; but you should handle the case of when the descriptor is invoked from the class: <code>Human.age</code>. In that case, <code>__get__</code> is invoked with None as an argument to instance. If you've no better use for it; you can just return the descriptor itself:</p>\n\n<pre><code>def __get__(self, instance, owner):\n if instance is None:\n return self\n else:\n return getattr(instance, self.name)\n</code></pre>\n\n<p>Another thing you can do, which is sometimes preferred, is to make the descriptor figure out its own name by inspecting the class it's attached to; this is a little more complicated, of course, but has the advantage of allowing you to specify the \"name\" of the descriptor attribute just one time.</p>\n\n<pre><code>class NumberDescriptor(object):\n def snoop_name(self, owner):\n for attr in dir(owner):\n if getattr(owner, attr) is self:\n return attr\n def __get__(self, instance, owner):\n if instance is None:\n return self\n name = self.snoop_name(self, owner)\n return getattr(instance, '_'+name)\n def __set__(self, instance, value):\n name = self.snoop_name(self, type(instance))\n setattr(instance, '_' + name, int(value))\n\nclass Human(object):\n age = NumberDescriptor()\n</code></pre>\n\n<p>Other variations to get a similar effect (without using <code>dir()</code>) would be to use a metaclass that knows to look for your descriptor and sets its name there. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:33:53.170", "Id": "24567", "Score": "0", "body": "Doesn't this make a lookup for every set and get action. It looks like a little bit waste to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:47:25.540", "Id": "24569", "Score": "0", "body": "yes, this version is a little inelegant; and meant mainly to give you some ideas about how you might use descriptors. A more reasonable implementation would probably use a metaclass or a weakref.WeakKeyDict to avoid the extra lookups, but I've decided to leave that as an exercise." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T12:33:45.957", "Id": "15131", "ParentId": "15108", "Score": "2" } }, { "body": "<p>Good question. I'm studying descriptors too.</p>\n\n<p>Why do you use <code>setattr()</code> and <code>getattr()</code>? I'm not clear on why you store <code>age</code> inside <code>instance</code>. What benefit does this have over this naive example?</p>\n\n<pre><code>class NumberDescriptor(object):\n def __set__(self, instance, value):\n if not isinstance(value, int):\n raise ValueError(\"%s is not a number.\" % value)\n else:\n self.value = value\n\n def __get__(self, instance, owner):\n return self.value\n\nclass Human(object):\n age = NumberDescriptor()\n worth = NumberDescriptor()\n\n def __init__(self,age,worth):\n self.age = age\n self.worth = worth\n\na = Human(12,5)\nprint a.age, a.worth\na.age = 13\na.worth = 6\nprint a.age, a.worth\nb = Human(\"osman\", 5.0)\nprint b.age\n</code></pre>\n\n<p>EDIT: responding to comment</p>\n\n<p>Not sure I have a firm handle on descriptors, but <a href=\"https://docs.python.org/2/howto/descriptor.html#descriptor-example\" rel=\"nofollow noreferrer\">the example</a> in the docs access <code>value</code> with <code>self</code> rather than invoking <code>getattr()</code> and <code>setattr()</code>.</p>\n\n<p>However, <a href=\"https://stackoverflow.com/a/12645321/1698426\">this answer</a> and <a href=\"https://stackoverflow.com/a/12645321/1698426\">this answer</a> do not user <code>getattr()</code>, they do not use <code>self</code> either. They access the use the <code>instance</code> argument. </p>\n\n<p>My example is slightly simpler. What are the trade-offs?</p>\n\n<p>Just as in the original question, the <code>b</code> instance demonstrates that a <code>ValueError</code> is raised. I added a <code>worth</code> attribute simply to demonstrate that there are in fact two distinct instances of <code>NumberDescriptor</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-07T22:20:18.553", "Id": "150156", "Score": "1", "body": "Welcome to Code Review and enjoy your stay! Your answer looks good except for the part where you construct `b`, as both arguments aren't `int`s, so maybe make the example runnable; you could also add a paragraph explaining directly why this setup is better than storing instance variables on the object itself rather than on the descriptor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-07T21:20:17.290", "Id": "83519", "ParentId": "15108", "Score": "1" } }, { "body": "<p>Consider this example, assume I've used your Human class and Number:</p>\n\n<pre><code>a = Human(12,5)\nprint a.age, a.worth\nb = Human(13,5)\nprint b.age, b.worth\n\n# Check if a attributes has changed:\nprint a.age, a.worth\n</code></pre>\n\n<p>Then you realize, you've overrided also 'a' instance attributes because you actually overrided class attribute :) \nThis is why your way to do it isn't exactly right when you want to have descriptor as instance-related attribute.</p>\n\n<p>When you need to have instance-related attributes which are Descriptors, you should to it in some other way, for example store in your descriptor some kind of Dict where you can identify your instance-related attributes and return then when you need them for specified instance or return some kind of default when you call attributes from class (e.g. Human.attr). It would be a good idea to use weakref.WeakKeyDictionary if you want to hold your whole instances in dict.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-25T21:29:20.603", "Id": "91751", "ParentId": "15108", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T18:10:35.773", "Id": "15108", "Score": "2", "Tags": [ "python", "object-oriented" ], "Title": "Using descriptors with instance variables to store a human's age" }
15108
<p>Here is a Python script I wrote earlier for rapidly requesting a file from a server and timing each transaction. Can I improve this script?</p> <pre><code>from time import time from urllib import urlopen # vars url = raw_input("Please enter the URL you want to test: ") for i in range(0,100): start_time = time() pic = urlopen(url) if pic.getcode() == 200: delta_time = time() - start_time print "%d" % (delta_time * 100) else: print "error" print "%d requests made. File size: %d B" % (i, len(pic.read())) </code></pre> <p>I'm new to Python, though, so I'm not sure if this is the best way to go about it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T20:53:26.160", "Id": "24534", "Score": "0", "body": "Are you trying to time the whole operation (checking the file 100 times) or just one opening? Are you interested in the number of times where you could get a proper `pic.getcode()` value, or the number of times where you tried to open the url (which is gonna be 100...) ?" } ]
[ { "body": "<p>Here are some comments on your code:</p>\n\n<ol>\n<li><p><code>raw_input</code> is a very inflexible way to get data into a program: it is only suitable for interactive use. For more general use, you should get your data into the program in some other way, for example via command-line arguments.</p></li>\n<li><p><code>urllib.urlopen</code> <a href=\"http://docs.python.org/library/urllib.html\" rel=\"nofollow\">was removed in Python 3</a>, so your program will be more forward-compatible if you use <code>urllib2.urlopen</code> instead. (You'll need to change the way your error handling works, because <code>urllib2.urlopen</code> deals with an error by raising an exception instead of returning a response object with a <code>getcode</code> method.)</p></li>\n<li><p>The comment <code># vars</code> does not seem to contain any information. Improve it or remove it.</p></li>\n<li><p>The <code>range</code> function starts at <code>0</code> by default, so <code>range(0,100)</code> can be written more simply as <code>range(100)</code>.</p></li>\n<li><p>100 seems rather arbitrary. Why not take this as a command-line parameter too?</p></li>\n<li><p>The variable <code>pic</code> seems poorly named. Is it short for <em>picture</em>? The <code>urlopen</code> function returns a <em>file-like object</em> from which the <em>resource</em> at the URL can be read. The <a href=\"http://docs.python.org/library/urllib2.html#examples\" rel=\"nofollow\">examples in the Python documentation</a> accordingly use <code>f</code> or <code>r</code> as variable names.</p></li>\n<li><p>I assume that this code is only going to be used for testing your own site. If it were going to be used to time the fetching of resources from public sites, it would be polite (a) to respect the <a href=\"http://en.wikipedia.org/wiki/Robots_exclusion_standard\" rel=\"nofollow\">robots exclusion standard</a> and (b) to not fetch resources as fast as possible, but to <code>sleep</code> for a while between each request.</p></li>\n<li><p>If an attempt to fetch the resource fails, you probably want to exit the loop rather than fail again many times.</p></li>\n<li><p>You say in your post that the code is supposed to time \"the entire transaction\", but it does not do this. It only times how long it takes to call <code>urlopen</code>. This generally completes quickly, because it just reads the headers, not the entire resource. You do read the resource once (at the very end), but outside the timing code.</p></li>\n<li><p>You multiply the time taken by 100 and then print it as an integer. This seems unnecessarily misleading: if you want two decimal places, then why not use <code>\"%.2f\"</code>?</p></li>\n<li><p>Finally, there's a built-in Python library <a href=\"http://docs.python.org/library/timeit.html\" rel=\"nofollow\"><code>timeit</code></a> for measuring the execution time of a piece of code, which compensates for things like the time taken to call <code>time</code>.</p></li>\n</ol>\n\n<p>So I might write something more like this:</p>\n\n<pre><code>from sys import argv\nfrom timeit import Timer\nfrom urllib2 import urlopen\n\nif __name__ == '__main__':\n url = argv[1]\n n = int(argv[2])\n length = 0\n\n def download():\n global length, url\n f = urlopen(url)\n length += len(f.read())\n f.close()\n\n t = Timer(download).timeit(number = n)\n print('{0:.2f} seconds/download ({1} downloads, average length = {2} bytes)'\n .format(t / n, n, length / n))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:58:35.447", "Id": "24571", "Score": "0", "body": "Great answer - lots of info! It's not working when I try to run it though. Could it be because I have Python 2.7 installed on my system? It's telling me that argv list index is out of range" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:59:29.457", "Id": "24572", "Score": "0", "body": "It takes two command-line arguments (the URL and the number of repetitions). Something like `python download.py http://my-server-address/ 100`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T15:07:42.747", "Id": "24573", "Score": "0", "body": "Okay I understand.. It's because I'm running the file directly when I should be opening it via command line so I can actually pass the arguments! Right?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:35:54.893", "Id": "15143", "ParentId": "15113", "Score": "3" } } ]
{ "AcceptedAnswerId": "15143", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T20:44:00.267", "Id": "15113", "Score": "4", "Tags": [ "python" ], "Title": "Rapidly requesting a file from a server" }
15113
<p>I have this rather verbose piece of code. How can I get it shorter and simpler?</p> <p>This function aggregate results of test by population and by different keys:</p> <pre><code>def aggregate(f): """ Aggregate population by several keys """ byMerchant = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byPlat = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byDay = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byAffiliate = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byCountry = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byType = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byPop = col.defaultdict(lambda: [0,0,0,0]) for line in f: fields = line.strip().split("^A") if fields[2] == '\\N': continue day = fields[0] popid = int(fields[1]) affiliate_id = int(fields[2]) merchant_id = int(fields[3]) clicks = int(fields[4]) displays = int(fields[5]) sales = float(fields[6]) gross = float(fields[7]) merchant_plat = partners_info[merchant_id][1] merchant_name = partners_info[merchant_id][0] publisher_name = publisher_info[affiliate_id][0] publisher_country = publisher_info[affiliate_id][1] publisher_type = publisher_info[affiliate_id][2] data = [clicks,displays,sales,gross] for k in xrange(len(data)): byMerchant[merchant_name][popid][k] += data[k] byPlat[merchant_plat][popid][k] += data[k] byAffiliate[publisher_name][popid][k] += data[k] byCountry[publisher_country][popid][k] += data[k] byDay[day][popid][k] += data[k] byType[publisher_type][popid][k] += data[k] byPop[popid][k] += data[k] return byPop, byMerchant, byPlat, byDay, byAffiliate, byCountry, byType </code></pre>
[]
[ { "body": "<p>If I try to split on the empty string I get an error:</p>\n\n<pre><code>&gt;&gt;&gt; 'a b c'.split('')\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nValueError: empty separator\n</code></pre>\n\n<p>Perhaps you meant <code>.split()</code>?</p>\n\n<p>Anyway, here are some ideas for simplifying your code.</p>\n\n<ol>\n<li><p>Use <code>from collections import defaultdict</code> to avoid the need to refer to <code>col</code> (I presume you have <code>import collections as col</code>).</p></li>\n<li><p>Put a dummy key into the <code>byPop</code> aggregation so that its structure matches the others.</p></li>\n<li><p>Put the aggregates into a dictionary instead of having a bunch of variables. That way you can manipulate them systematically in loops.</p></li>\n<li><p>Use <code>enumerate</code> in your last loop to get the index as well as the value from the <code>data</code> list.</p></li>\n</ol>\n\n<p>That leads to this:</p>\n\n<pre><code>from collections import defaultdict\n\ndef aggregate(f):\n \"\"\"\n Aggregate population by several keys.\n \"\"\"\n aggregates = 'pop merchant plat day affiliate country type'.split()\n result = dict()\n for a in aggregates:\n result[a] = defaultdict(lambda: defaultdict(lambda: [0,0,0,0]))\n\n for line in f:\n fields = line.strip().split()\n if fields[2] == '\\\\N': continue\n\n # Decode fields from this record.\n day = fields[0]\n popid = int(fields[1])\n affiliate_id = int(fields[2])\n merchant_id = int(fields[3])\n clicks = int(fields[4])\n displays = int(fields[5])\n sales = float(fields[6])\n gross = float(fields[7])\n\n # Keys under which to aggregate the data from this record.\n keys = dict(merchant = partners_info[merchant_id][0],\n plat = partners_info[merchant_id][1],\n day = day,\n affiliate = publisher_info[affiliate_id][0],\n country = publisher_info[affiliate_id][1],\n type = publisher_info[affiliate_id][2],\n pop = 0) # dummy key\n\n # Update all aggregates.\n for i, value in enumerate([clicks, displays, sales, gross]):\n for a in aggregates:\n result[a][keys[a]][popid][i] += value\n\n return (result['pop'][0],) + tuple(result[a] for a in aggregates[1:])\n</code></pre>\n\n<p>It's not really a vast improvement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T21:36:30.387", "Id": "24593", "Score": "0", "body": "The split is on a special character, sorry it has been striped during copy and paste. It is a good idea to directly import the dictionary. I did not think about the dummy key. It makes it possible to factor the code. Thank you. The resulting code is quite complex though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T23:07:24.253", "Id": "24595", "Score": "0", "body": "Yes, I couldn't simplify it all that much, sorry! Maybe some other person will have some better ideas." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T18:26:59.833", "Id": "15156", "ParentId": "15151", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:49:46.280", "Id": "15151", "Score": "2", "Tags": [ "python" ], "Title": "Aggregate by several keys" }
15151
<p>I have files with over 100 million lines in each:</p> <blockquote> <pre><code>... 01-AUG-2012 02:29:44 important data 01-AUG-2012 02:29:44 important data 01-AUG-2012 02:36:02 important data some unimportant data blahblah (also unimportant data) some unimportant data 01-AUG-2012 02:40:15 important data some unimportant data ... </code></pre> </blockquote> <p>As you can see, there are important data (starting with date and time) and unimportant data. Also in each second, there can be many lines of important data.</p> <p>My goal is to count the number of "important data" in each second (or minute or hour...) and reformat date/time format. My script also lets me count data in each minute, hour etc using <code>options.dlen</code>:</p> <blockquote> <pre><code>options.dlen = 10 takes YYYY-MM-DDD options.dlen = 13 takes YYYY-MM-DDD HH options.dlen = 16 takes YYYY-MM-DDD HH:MM options.dlen = 20 takes YYYY-MM-DDD HH:MM:SS </code></pre> </blockquote> <p>I have written the following script (this is the main part - I skip all the file openings, parameters etc).</p> <pre><code>DATA = {} # search for DD-MMM-YYYY HH:MM:SS # e.g. "01-JUL-2012 02:29:36 important data" pattern = re.compile('^\d{2}-[A-Z]{3}-\d{4} \d{2}:\d{2}:\d{2} important data') DATA = defaultdict(int) i = 0 f = open(options.infilename, 'r') for line in f: if re.match(pattern, line): if options.verbose: i += 1 # print out every 1000 iterations if i % 1000 == 0: print str(i) + '\r', # converts data date/time format to YYYY-MM-DD HH:MM:SS format (but still keep it as datetime !) d = datetime.strptime( line [0:20], '%d-%b-%Y %H:%M:%S') # converts d, which is datetime to string again day_string = d.strftime('%Y-%m-%d %H:%M:%S') DATA [ str(day_string[0:int(options.dlen)]) ] += 1 f.close() #L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1), reverse=True) #L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1)) L2 = sorted(DATA.iteritems(), key=operator.itemgetter(0)) </code></pre> <p>It takes about 3 hours to process over 100 million lines. Can you suggest performance improvements for this script?</p> <p>Update: I have just used PyPy and the same task on the same server took 45 minutes. I will try to add profile statistics.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T08:44:35.590", "Id": "24688", "Score": "0", "body": "Without proper profiling we can only guess where the bottleneck is. Create a smaller test file (http://www.manpagez.com/man/1/head/) and run your script under [profiler](http://docs.python.org/library/profile.html)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T09:06:49.460", "Id": "24690", "Score": "0", "body": "Without knowing whether your program is CPU-bound or IO-bound, it's hard to say how to optimize this. You can tell with the `time(1)` command." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T18:21:13.463", "Id": "24691", "Score": "1", "body": "One way to quickly improve your script's time would be to trim down the number of lines it has to deal with - pipe your input file through something like `grep '^[0-9]'` before your script gets to it, so that you only process the lines that are important." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T09:02:21.913", "Id": "64518", "Score": "0", "body": "You can use **Python** [**Multiprocessing**](http://docs.python.org/library/multiprocessing.html) to process the lines concurrently" } ]
[ { "body": "<pre><code>DATA = {}\n</code></pre>\n\n<p>Python convention is for ALL_CAPS to be reserved for constants</p>\n\n<pre><code># search for DD-MMM-YYYY HH:MM:SS\n# e.g. \"01-JUL-2012 02:29:36 important data\"\npattern = re.compile('^\\d{2}-[A-Z]{3}-\\d{4} \\d{2}:\\d{2}:\\d{2} important data')\n\nDATA = defaultdict(int)\ni = 0\nf = open(options.infilename, 'r')\n</code></pre>\n\n<p>I recommend using <code>with</code> to make sure the file is closed</p>\n\n<pre><code>for line in f:\n</code></pre>\n\n<p>You should put this loop in a function. Code inside a function runs faster then code at the top level</p>\n\n<pre><code> if re.match(pattern, line):\n</code></pre>\n\n<p>Do you really need a regular expression? From the file listing you gave maybe you should be checking <code>line[20:] == 'important data'</code></p>\n\n<p>Also, use <code>pattern.match(line)</code>, <code>re.match</code> works passing a precompiled pattern, but I've found that it has much worse performance.</p>\n\n<pre><code> if options.verbose:\n i += 1\n # print out every 1000 iterations\n if i % 1000 == 0:\n print str(i) + '\\r',\n\n\n\n\n # converts data date/time format to YYYY-MM-DD HH:MM:SS format (but still keep it as datetime !)\n d = datetime.strptime( line [0:20], '%d-%b-%Y %H:%M:%S')\n # converts d, which is datetime to string again\n day_string = d.strftime('%Y-%m-%d %H:%M:%S')\n DATA [ str(day_string[0:int(options.dlen)]) ] += 1\n</code></pre>\n\n<p>There's a good chance you might be better off storing the datetime object rather then the string. On the other hand, is the file already in sorted order? In that case all you need to do is check whether the time string has changed, and you can avoid storing things in a dictionary</p>\n\n<pre><code>f.close()\n#L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1), reverse=True)\n#L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1))\nL2 = sorted(DATA.iteritems(), key=operator.itemgetter(0))\n</code></pre>\n\n<p>If the incoming file is already sorted, you'll save a lot of time by maintaining that sort.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T11:49:21.287", "Id": "24712", "Score": "0", "body": "This code is in def main(): which is then run by if __name__ == \"__main__\":\n main()\nIs that what you say about putting inside function ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T12:20:56.453", "Id": "24713", "Score": "0", "body": "@przemol, yes that's what I mean by putting inside a function. If you've already done that: good." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T19:40:31.690", "Id": "15217", "ParentId": "15214", "Score": "4" } } ]
{ "AcceptedAnswerId": "15253", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T08:38:50.370", "Id": "15214", "Score": "12", "Tags": [ "python", "performance", "datetime", "regex" ], "Title": "Script for analyzing millions of lines" }
15214
<p>I made a function that returns the number displayed for pagination. I want to get something like this (parentheses is the only show where the active site):</p> <p>if pages &lt; 10</p> <pre><code>1 2 3 4 5 6 7 8 9 10 </code></pre> <p>if pages > 10</p> <pre><code>1 2 3 ... 20 [30] 40 ... 78 79 80 </code></pre> <p>where [30] is active page. If active page &lt; 3</p> <pre><code>1 2 [3] 4 ... 20 30 40 ... 78 79 80 </code></pre> <p>etc. My code:</p> <pre><code> count_all - number of all items items_on_page - items displayed on one page page - current page countpages = int(float(count_all+(items_on_page-1))/float(items_on_page)) linkitems = 10 if countpages &gt; (linkitems-1): countpagesstr = list() for i in range(1,int(float(linkitems+(2))/float(3))): countpagesstr += [str(i)] countpagesstr += ['...'] sr = int(countpages/2) for i in range(sr-1, sr+1): countpagesstr += [str(i)] countpagesstr += ['...'] for i in range(countpages-3, countpages): countpagesstr += [str(i)] else: cp = list() for c in range(1,countpages+1): cp.append(str(c)) countpagesstr = cp return countpagesstr </code></pre> <p>How to do it better?</p>
[]
[ { "body": "<ol>\n<li><p>Your code doesn't run as written. It needs a function definition.</p></li>\n<li><p>Your design needs work. Suppose the current page is 30 and the list of pages says \"... 20 [30] 40 ...\" as in your example. How do I get to page 29 or page 31? It doesn't look as if these page numbers will ever appear in the list.</p>\n\n<p>The more usual design is to always show a small number of pages at the beginning and end, and a small number of pages adjacent to the current page. So that the list of pages would look more like \"1 2 3 ... 28 29 [30] 31 32 ... 78 79 80\".</p></li>\n<li><p>The expression</p>\n\n<pre><code>int(float(count_all+(items_on_page-1))/float(items_on_page))\n</code></pre>\n\n<p>is unnecessarily complex. You can use Python's floor division operator (<code>//</code>) to achieve the same thing without converting to floats and back again:</p>\n\n<pre><code>(count_all + items_on_page - 1) // items_on_page\n</code></pre></li>\n<li><p>Your variables are poorly and unsystematically named. <code>count_all</code>, for example. All what? Or <code>countpagesstr</code>, which sounds like it might be a string, but is in fact a list. You use underscores in some cases (<code>count_all</code>) but not in others (<code>countpages</code>).</p></li>\n<li><p>It is easiest conceptually to separate the two steps of <em>deciding which page numbers to show</em> and <em>showing them in order with ellipses</em>.</p>\n\n<p>In the code below I build the set of the page numbers from the first three pages, the five pages around the current page, and the last three pages. I use Python's sets so that I can take this union without having to worry about duplicate page numbers.</p>\n\n<pre><code>def abbreviated_pages(n, page):\n \"\"\"\n Return a string containing the list of numbers from 1 to `n`, with\n `page` indicated, and abbreviated with ellipses if too long.\n\n &gt;&gt;&gt; abbreviated_pages(5, 3)\n '1 2 [3] 4 5'\n &gt;&gt;&gt; abbreviated_pages(10, 10)\n '1 2 3 4 5 6 7 8 9 [10]'\n &gt;&gt;&gt; abbreviated_pages(20, 1)\n '[1] 2 3 ... 18 19 20'\n &gt;&gt;&gt; abbreviated_pages(80, 30)\n '1 2 3 ... 28 29 [30] 31 32 ... 78 79 80'\n \"\"\"\n assert(0 &lt; n)\n assert(0 &lt; page &lt;= n)\n\n # Build set of pages to display\n if n &lt;= 10:\n pages = set(range(1, n + 1))\n else:\n pages = (set(range(1, 4))\n | set(range(max(1, page - 2), min(page + 3, n + 1)))\n | set(range(n - 2, n + 1)))\n\n # Display pages in order with ellipses\n def display():\n last_page = 0\n for p in sorted(pages):\n if p != last_page + 1: yield '...'\n yield ('[{0}]' if p == page else '{0}').format(p)\n last_page = p\n\n return ' '.join(display())\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T14:26:51.063", "Id": "15239", "ParentId": "15235", "Score": "8" } } ]
{ "AcceptedAnswerId": "15239", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T10:57:40.653", "Id": "15235", "Score": "5", "Tags": [ "python" ], "Title": "how to generate numbers for pagination?" }
15235
<p>I've written a project for handling various Facebook things and I ran into the issue where one project named the users profile <code>Profile</code> while normally they would be named <code>UserProfile</code>. When I was checking if the <code>FacebookUser</code> model was related to a <code>User</code>, I could just <code>User.objects.get(userprofile__facebook=facebook_user)</code> so I come up with a way to get the name, but it seems pretty ugly. Is there a cleaner way?</p> <pre><code>from django.conf import settings from django.contrib.auth.models import User from better_facebook.models import FacebookUser # Get the name of the AUTH profile so that we can check if the user # has a relationship with facebook. Is there a neater way of doing this? _lowercase_profile_name = settings.AUTH_PROFILE_MODULE.split(".")[1].lower() _facebook_relation = '{0}__facebook'.format(_lowercase_profile_name) class FacebookBackend(object): """ Authenticate against a facebook_user object. """ def authenticate(self, facebook_user): assert(isinstance(facebook_user, FacebookUser)) try: return User.objects.get(**{_facebook_relation: facebook_user}) except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None </code></pre>
[]
[ { "body": "<p>You can use django.contrib.auth.get_user_model() instead of importing User directly. Note that I also explicitly included the ObjectDoesNotExist exception.</p>\n\n<p><a href=\"https://docs.djangoproject.com/en/2.2/topics/auth/customizing/\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/2.2/topics/auth/customizing/</a></p>\n\n<pre><code>from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom better_facebook.models import FacebookUser\n\n\nclass FacebookBackend(object):\n \"\"\"\n Authenticate against a facebook_user object.\n \"\"\"\n def authenticate(self, facebook_user):\n assert(isinstance(facebook_user, FacebookUser))\n try:\n UserModel = get_user_model()\n return UserModel.objects.get(userprofile__facebook=facebook_user)\n except ObjectDoesNotExist:\n return None\n\n def get_user(self, user_id):\n try:\n UserModel = get_user_model()\n return UserModel.objects.get(pk=user_id)\n except ObjectDoesNotExist:\n return None\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T09:34:23.687", "Id": "224660", "ParentId": "15432", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-08T10:58:57.410", "Id": "15432", "Score": "7", "Tags": [ "python", "django" ], "Title": "Finding the profile name for a join in my Facebook auth backend" }
15432
<p>I have a library that accepts a file-like object but assumes that it has a valid <code>.name</code> unless that name is <code>None</code>. This causes it to break when I pass e.g. <code>someproc.stdout</code> as it has a name of <code>&lt;fdopen&gt;</code>. Unfortunately the attribute cannot be deleted or overwritten.</p> <p>So I've written this simple wrapper to return <code>None</code> in case the <code>name</code> attribute is requested.</p> <pre><code>class InterceptAttrWrapper(object): def __init__(self, obj, attr, value): self.obj = obj self.attr = attr self.value = value def __getattribute__(self, name): ga = lambda attr: object.__getattribute__(self, attr) if name == ga('attr'): return ga('value') return getattr(ga('obj'), name) </code></pre> <p>This seems to work fine, I'm using it like this: </p> <pre><code>proc = subprocess.Popen(..., stdout=subprocess.PIPE) some_func(InterceptAttrWrapper(proc.stdout, 'name', None)) </code></pre> <p>However, I wonder if:</p> <ul> <li>My <code>InterceptAttrWrapper</code> object is missing something that could cause problems.</li> <li>There is a better way to access attributes within <code>__getattribute__</code>. That lambda I'm using right now looks pretty ugly.</li> </ul>
[]
[ { "body": "<p>Something to watch out for with your approach is that Python calls certain special methods without looking them up via <code>__getattribute__</code>. For example, the <code>__iter__</code> method:</p>\n\n<pre><code>&gt;&gt;&gt; w = InterceptAttrWrapper(open('test'), 'attr', 'value')\n&gt;&gt;&gt; for line in w: print line\n... \nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nTypeError: 'InterceptAttrWrapper' object is not iterable\n</code></pre>\n\n<p>See the documentation on \"<a href=\"http://docs.python.org/reference/datamodel.html#new-style-special-lookup\" rel=\"nofollow\">Special method lookup for new-style classes</a>\". If this affects you, then you'll need to add to your wrapper class all the special methods that you need to support (in my example, <code>__iter__</code>, but when wrapping other objects one might need to implement <code>__getitem__</code>, <code>__repr__</code>, <code>__hash__</code>, or others).</p>\n\n<p>Here's a slightly more readable way to get at the wrapper object's own data, together with support for intercepting multiple attributes:</p>\n\n<pre><code>class InterceptAttrWrapper(object):\n \"\"\"\n Wrap an object and override some of its attributes.\n\n &gt;&gt;&gt; import sys\n &gt;&gt;&gt; stdin = InterceptAttrWrapper(sys.stdin, name = 'input')\n &gt;&gt;&gt; stdin.mode # Pass through to original object.\n 'r'\n &gt;&gt;&gt; stdin.name # Intercept attribute and substitute value.\n 'input'\n \"\"\"\n def __init__(self, obj, **attrs):\n self._data = obj, attrs\n\n def __getattribute__(self, name):\n obj, attrs = object.__getattribute__(self, '_data')\n try:\n return attrs[name]\n except KeyError:\n return getattr(obj, name)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-25T16:59:31.127", "Id": "15917", "ParentId": "15494", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T18:33:34.687", "Id": "15494", "Score": "6", "Tags": [ "python" ], "Title": "Intercept read access to a certain object attribute" }
15494
<p>I've made a simple program that can calculate the area of various 2D shapes. I'd like your expereanced eyes to asses my code. Be as harsh as you want but please be <strong>specific</strong> and offer me ways in which I can improve my coding.</p> <pre><code>shape = ("triangle","square","rectangle","circle") # This is a tuple containing the string names of all the supported shapes so far. constants = (3.14) # An object containing the value of pi. I will add more constants in future and turn this into a tuple. start_up = input("Do you want to calculate a shape's area?: ") # Fairly self explainatory if start_up != "yes" or "no": # This is to prevent the program failing if the user answers the start_up question print("Sorry but I don't understand what your saying") # with an answer outside of the simple yes/no that it requires start_up = input("Do you want to calculate a shape's area?: ") # re-iterates the start up question. while start_up == "yes": # This is the condition that obviously contains the bulk of the program. target_shape = input("Choose your shape: ") # Once again, self explainatory. if target_shape == shape[0]: # Uses the shape tuple to bring forth the case for the first shape, the triangle. h = float(input("give the height: ")) # These Two lines allow the user to input the required values to calculate the area of the triangle. b = float(input("give the base length: ")) # They are using the float funtion to increase the accuracy of the answer. area_triangle = h * 1/2 * b # The formula we all learned in school. print("the area of the %s is %.2f" % (shape[0],area_triangle)) # This generates a format string which uses both the shape tuple and the area_triangle object # to display the answer. note the %.2f operand used to specify how many decimal places for the answer. if target_shape == shape[1]: # Square l = float(input("give the length: ")) area_square = l ** 2 print("the area of the %s is %.2f" % (shape[1],area_square)) if target_shape == shape[2]: # Rectangle l = float(input("give the length: ")) w = float(input("give the width: ")) area_rectangle = l * w print("the area of the %s is %.2f" % (shape[2],area_rectangle)) if target_shape == shape[3]: # Circle r = float(input("give the radius: ")) pi = constants # In this line we are calling forth the constants object to use the value of pi. area_circle = 2 * pi * r print("the area of the %s is %.2f" %(shape[3],area_circle)) start_up = input("Do you want to calculate another shape's area?: ") # This line allows the user the chance to do just what it says in the brackets. else: # This is to safegaurd against failure in the event of the user print("That shape's not in my database") # inputing a shape non-existant in the shape tuple. start_up = input("Do you want to calculate another shape's area?: ") if start_up == "no": #This is for when the user no longer wants to use the program. print("Goodbye then!") input("Press any key to close") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T16:55:24.913", "Id": "25319", "Score": "1", "body": "The `if start_up != (\"yes\" or \"no\"):` is still wrong; `('yes' or 'no')` is `'yes'`. You're looking for `not in` or 2 inequality tests." } ]
[ { "body": "<p>Your code is very good for a beginner! As you have noticed, there are always improvements to be done, so don't worry too much about this. Here's what I feel the other answers have missed:</p>\n\n<pre><code>constants = (3.14)\n</code></pre>\n\n<p>Use <code>math.pi</code> instead!</p>\n\n<pre><code>start_up = input(\"Do you want to calculate a shape's area?: \") # Fairly self explanatory.\n</code></pre>\n\n<p>I understand that those comments help you as a Python beginner, but they should be avoided in real code. As the <a href=\"http://www.python.org/dev/peps/pep-0008/#inline-comments\" rel=\"nofollow\">PEP 8 section on online comments</a> says, inline comments that state the obvious are distracting. You're also <a href=\"http://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow\">breaking the 79 characters rule</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T10:25:09.907", "Id": "25359", "Score": "1", "body": "As noted in the comments above, `if start_up != \"yes\" or \"no\"` will *not* work, because that's not how `or` works. For similar reasons, `start_up != (\"yes\" or \"no\")` won't work either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T10:31:16.030", "Id": "25360", "Score": "1", "body": "To be specific: The \"or\" will return the first truthy value, so `(\"yes\" or \"no\")` is simply \"yes\". In the other case, if `start_up = 'yes'`, then `start_up != \"yes\" or \"no\"` will be `False or \"no\"`, which is \"no\", which is a nonempty string and thus truthy, so the branch will still be taken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T11:05:41.613", "Id": "25361", "Score": "0", "body": "Thanks! For some reason, I was assuming there was the same magic than in 1 < x < 5. I removed the wrong bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T14:00:30.440", "Id": "25370", "Score": "0", "body": "Thank you. I've started rewritting the code and I think I've managed to iron out most of my syntaxial mistakes. There however is one thing which I can't seem to implement. How can you safeguard against someone inputting either nothing or an invalid value when it asks you to provide the values to carry out the area equations?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T15:16:41.033", "Id": "25376", "Score": "1", "body": "You can catch the `ValueError` exception that `float()` is throws when the argument is empty or invalid, and ask for a value again. It's not really important, and if you want to do it, consider writing a function which you'll be able to call whenever you need this. eg. `get_float(\"I just need the length of a side: \")`. The function will be able to loop until the user gives an useful value. By the way, you should upvote questions that helped you (not only mine!), and decide on which question helped you the most. When you've rewritten your code, you can ask another question if you want to." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T09:58:39.423", "Id": "15610", "ParentId": "15572", "Score": "1" } } ]
{ "AcceptedAnswerId": "15581", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-13T13:48:37.777", "Id": "15572", "Score": "5", "Tags": [ "python", "beginner", "computational-geometry" ], "Title": "Calculating the area of various 2D shapes" }
15572
<p>I just figured out <a href="http://projecteuler.net/problem=12" rel="nofollow">Project Euler problem #12</a>. This the first one I've done in Python, so I'm putting my code out there to hopefully get some constructive criticism. </p> <p>If anyone is interested, would you mind looking over my solution and letting me know how I can improve on it, either through optimization or style?</p> <p>Thanks!</p> <pre><code>from math import* def divisorCount(n): nDivisors = 0 integerSqrt = int(sqrt(n)) if sqrt(n) == integerSqrt: nDivisors += 1 for i in range(1, integerSqrt - 1): if n % i == 0: nDivisors += 2 return nDivisors def main(): divisors = 0 incrementTriangle = 1 triangleNumber = 1 while True: divisors = divisorCount(triangleNumber) if divisors &lt; 500: incrementTriangle += 1 triangleNumber = triangleNumber + incrementTriangle elif divisors &gt;= 500: print "The first triangle number w/ 500+ divisors is", triangleNumber return 0 main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:02:03.143", "Id": "25305", "Score": "0", "body": "I quick run through the [`pep8`](http://pypi.python.org/pypi/pep8) program should point out any style improvements. [PEP-0008](http://www.python.org/dev/peps/pep-0008/) is the \"style guide\" for Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:04:51.760", "Id": "25306", "Score": "0", "body": "I think they're looking for feedback on the semantics and code design, not syntax. But yeah, this type of question is for codereview." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:05:17.573", "Id": "25307", "Score": "1", "body": ".. but before you take it over to `codereview`, you might want to test your `divisorCount` function a bit more.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:05:54.643", "Id": "25308", "Score": "1", "body": "a hint for you,take `24`, it's factors are `1,2,3,4,6,8,12,24`, i.e total `8`, and `24` can be represented in terms of it's prime factors as `24=2^3 * 3^1` , so the total number of factors are given by `(3+1)*(1+1)` i,e 8, where `3,4` are powers of the prime factors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:08:42.097", "Id": "25309", "Score": "0", "body": "related: [Project Euler #12 in python](http://stackoverflow.com/q/571488/4279). See [the code that is linked](http://gist.github.com/68515) in the comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:44:23.640", "Id": "25310", "Score": "0", "body": "Thanks for the help everyone... will move over to codereview from now on. However, DSM- I'd love to know what's wrong with divisorCount... right now it's giving me the correct answer, but you must see something that can break." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:52:04.443", "Id": "25311", "Score": "0", "body": "@tjr226: try `divisorCount(2)` or `divisorCount(6)`, for example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T12:19:42.143", "Id": "25312", "Score": "0", "body": "@tjr226 Try `for i in range(1,10): print i`." } ]
[ { "body": "<pre><code>from math import*\n</code></pre>\n\n<p>Missing space?</p>\n\n<pre><code> for i in range(1, integerSqrt - 1):\n if n % i == 0:\n nDivisors += 2\n</code></pre>\n\n<p>I'm not saying it's better here, but you can achieve a lot with list comprehensions. For example, <code>2 * len([i for i in range(1, integerSqrt -1) if n % i == 0]</code> would be equivalent. And less readable, so don't use it here!</p>\n\n<pre><code> incrementTriangle += 1\n triangleNumber = triangleNumber + incrementTriangle\n</code></pre>\n\n<p>Be consistent with increments (<code>triangleCount += incrementTriangle</code>)</p>\n\n<pre><code> elif divisors &gt;= 500:\n print \"The first triangle number w/ 500+ divisors is\", triangleNumber\n return 0\n</code></pre>\n\n<p>Using returns or breaks in a loop is usually a bad idea if it can be avoided. It means that you need to scan the whole loop to see where the loop could end earlier than expected. In this case, what's preventing you from doing <code>while divisors &lt; 500</code>. As an added bonus, you would stop mixing output and actual logic.</p>\n\n<pre><code>print \"The first triangle number w/ 500+ divisors is\", triangleNumber\n</code></pre>\n\n<p>Use the <code>print()</code> function provided in Python 2.6. It will make your code Python 3 compatible and.. more pythonic. If you want more flexibly, also consider using format strings. This would give:</p>\n\n<pre><code>print(\"The first triangle number w/ 500+ divisors is %d\" % triangleNumber)\n</code></pre>\n\n<p>So, you have a main function and call it like this:</p>\n\n<pre><code>main()\n</code></pre>\n\n<p>You should instead use the <a href=\"https://codereview.meta.stackexchange.com/a/493/11227\"><code>__main__</code></a> idiom, as it will allow your file to be imported (for example to use divisorsCount).</p>\n\n<p>And last, but not least, you should really follow the PEP 8, as others said in the comments. Consistency is really important to make your code more readable!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-14T09:44:47.490", "Id": "15608", "ParentId": "15577", "Score": "0" } }, { "body": "<p>Cygal's answer covers style, but you also asked for optimisation so here goes.</p>\n\n<p>Your <code>divisorCount</code> can be a lot more efficient. The number of divisors can be calculated cia the following formula:</p>\n\n<pre><code>d(n) = prod((k + 1)) for a^k in the prime factorisation of n\n</code></pre>\n\n<p>For example, consider the prime factorisation of 360:</p>\n\n<pre><code>360 = 2^3 * 3^2 * 5^1\n</code></pre>\n\n<p>The exponents in the prime factorisation are 3, 2, and 1, so:</p>\n\n<pre><code>d(360) = (3 + 1) * (2 + 1) * (1 + 1)\n = 24\n</code></pre>\n\n<p>Note that 360 indeed has 24 factors: <code>[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, 180, 360]</code>.</p>\n\n<p>Combine this with the fact that a number <code>n</code> can have at most one prime factor greater than <code>sqrt(n)</code>, and you get something like the following:</p>\n\n<pre><code># Calculates the number of positive integer divisors of n, including 1 and n\ndef d(n):\n divisors = 1\n stop = math.sqrt(n)\n\n primes = # Calculate prime numbers up to sqrt(n) in ascending order\n for prime in primes:\n if prime &gt; stop:\n break\n\n exponent = 0 \n while n % prime == 0:\n n /= prime\n exponent += 1\n\n if a != 0:\n divisors *= (a + 1)\n stop = max(stop, n)\n\n # At this point, n will either be 1 or the only prime factor of n &gt; root\n # in the later case, we have (n^1) as a factor so multiply divisors by (1 + 1)\n if n &gt; root:\n divisors *= 2\n\n return divisors\n</code></pre>\n\n<p>Since you are going to be calling this function many times consecutively, it makes sense to pre-calculate a list of primes and pass it to the divisor function rather than calculating it each time. One simple and efficient method is the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthanes</a> which can be implemented very easily:</p>\n\n<pre><code># Compute all prime numbers less than k using the Sieve of Eratosthanes\ndef sieve(k):\n s = set(range(3, k, 2))\n s.add(2)\n\n for i in range(3, k, 2):\n if i in s:\n for j in range(i ** 2, k, i * 2):\n s.discard(j)\n\n return sorted(s)\n</code></pre>\n\n<p>This function can also fairly easily be modified to compute a range in pieces, e.g. to calculate the primes to 1M and then to 2M without recalculating the first 1M.</p>\n\n<p>Putting this together your main loop will then look something like this:</p>\n\n<pre><code>primes = [2, 3, 5]\ntriangularNumber = 0\nincrement = 1\nmaxDivisors = 0\nwhile maxDivisors &lt; 500:\n triangularNumber += increment\n increment += 1\n\n if math.sqrt(triangularNumber) &gt; primes[-1]:\n primes = sieve(primes, primes[-1] * 4)\n\n divisors = d(triangularNumber, primes)\n maxDivisors = max(divisors, maxDivisors)\n\nprint triangularNumber, \"has\", maxDivisors, \"divisors.\"\n</code></pre>\n\n<p>As far as performance goes, here are the triangular numbers with the largest number of divisors and the times (in seconds) taken to get there (py1 is your code, py2 is using primes, c++ is the same as py2 but in c++):</p>\n\n<pre><code>TriNum Value d(n) py1 py2 c++\n 12375 76576500 576 0 0 0\n 14399 103672800 648 0 0 0\n 21735 236215980 768 1 0 0\n 41040 842161320 1024 4 0 0\n 78624 3090906000 1280 128 13 9\n 98175 4819214400 1344 350 23 15\n123200 7589181600 1512 702 38 23\n126224 7966312200 1536 749 41 24\n165375 13674528000 1728 - 74 42\n201824 20366564400 1920 - 107 61\n313599 49172323200 2304 - 633 153\n395199 78091322400 2880 - 790 259\n453375 102774672000 3072 - 910 358\n</code></pre>\n\n<p>There are probably other optimisations you can make based on the properties of triangular numbers, but I don't know the math. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-16T12:31:50.220", "Id": "15671", "ParentId": "15577", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T03:57:28.800", "Id": "15577", "Score": "2", "Tags": [ "python", "project-euler" ], "Title": "Python Code Review - Project Euler #12" }
15577
<p>I am developing a meta-data framework for monitoring systems such that I can easily create data adapters that can pull in data from different systems. One key component is the unit of measurement. To compare datasets which have different units I need to convert them to a common unit. To build adapters I need to have a system capable of describing complicated situations.</p> <p>Units are just strings that define what the numbers mean e.g. 102 kWh is 102 kiloWatt hours, this can be converted to the SI unit for energy (Joules) by multiplying by a conversion factor (3600000 in this case).</p> <p>Some data sources have built in conversion systems and provide me with data to a base unit that they specify, e.g. one database will give me energy data measured in various units (one may be called 'kWh*0.01', another 'Btu*1000'). These data will be provided along with a conversion factor to calculate the 'base unit' for that system which is e.g. GJ.</p> <p>Here is my code to define units</p> <pre><code>class Unit(object): def __init__(self, base_unit, coefficient, name, suffix): self.name = name self.suffix = suffix self.base_unit = base_unit self.coefficient = float(coefficient) def to_base(self, value): return value * self.coefficient def from_base(self, value): return value / self.coefficient def to_unit(self, value, unit): if unit.base_unit != self.base_unit: raise TypeError, "Units derived from %s and %s are incompatible." % (self.base_unit, unit.base_unit) return unit.from_base(self.to_base(value)) def __repr__(self): return "%s (%s)" % (self.name, self.suffix) class BaseUnit(Unit): def __init__(self, name, suffix): super(BaseUnit, self).__init__(self, 1.0, name, suffix) </code></pre> <p>I use these classes to represent the unit information pulled from the source database. In this case, I pass in a record from the 'units' table and use the appropriate fields to construct a unit with the given description and abbreviation that can then be converted into the base unit provided by the system (GJ for energy, M3 for water).</p> <pre><code>def convert_unit(unit): """Convert a provided unit record into my unit""" desc = unit.description.strip() suffix = unit.abbreviation.strip() if unit.type == 'energy': base = BaseUnit("GigaJoules", "GJ") return Unit(base, float(unit.units_per_gj), desc, suffix) elif unit.type == 'water': base = BaseUnit("Cubic metres", "m3") return Unit(base, float(unit.units_per_m3), desc, suffix) else: return BaseUnit(desc, suffix) </code></pre> <p>When designing my classes I had in the back of my mind an idea to enforce a common base unit (e.g. Joules) for energy across multiple data sources, I think I can do this by adding another tier and simply making the current base unit a unit with a given base (may require hard coding the conversion factor between my base unit and GJ).</p> <pre><code>def convert_unit(unit): """Convert a provided unit record into my unit""" desc = unit.description.strip() suffix = unit.abbreviation.strip() if unit.type == 'energy': base = BaseUnit("Joules", "J") source_base = Unit(base, 1000000000, "GigaJoules", "GJ") return Unit(source_base, float(unit.units_per_gj), desc, suffix) elif unit.type == 'water': base = BaseUnit("Cubic metres", "m3") return Unit(base, float(unit.units_per_m3), desc, suffix) else: return BaseUnit(desc, suffix) </code></pre> <p>The to_base, from_base and to_unit methods are intended for use with numpy arrays of measurements. I typically use the unit classes inside a dataset class that holds data as a numpy array and a unit instance.</p> <p>How does this look? It feels neat to me. Are there any style issues? </p>
[]
[ { "body": "<pre><code>raise TypeError, \"Units derived from %s and %s are incompatible.\" % (self.base_unit)\n</code></pre>\n\n<p>The python style guide recommends raising exceptions in the <code>raise TypeError(message)</code> form. TypeError is also questionable as the correct exception to throw here. The error here doesn't seem to be quite the same as making inappropriate use of python types. I'd have a UnitError class.</p>\n\n<pre><code>def __repr__(self): \n return \"%s (%s)\" % (self.name, self.suffix)\n</code></pre>\n\n<p><code>__repr__</code> is supposed to return either a valid python expression or something of the form <code>&lt;text&gt;</code></p>\n\n<pre><code>base = BaseUnit(\"Cubic metres\", \"m3\") \n</code></pre>\n\n<p>I'd make a global cubic meter object</p>\n\n<p>My overall thought is: do you really need this? My inclination would be to convert all data to the correct units as I read it. That way all data in my program would be using consistent units and I wouldn't have to worry about whether data is in some other exotic unit. Of course, depending on your exact scenario, that may not be a reasonable approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T15:14:25.433", "Id": "25652", "Score": "0", "body": "Thanks Winston, I think I need it primarily because I don't know what units the raw data will be in. This code is part of" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T15:23:04.427", "Id": "25653", "Score": "0", "body": "A system for converting the data into the required units. The required units are not always known in advance. I may want to define a custom unit (e.g. The 'cup of tea') for a particular task." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T15:29:07.963", "Id": "25654", "Score": "0", "body": "Re global units. Would these be best as separate constants in the module namespace or a single dict or set of units?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T18:43:26.513", "Id": "25746", "Score": "0", "body": "@GraemeStuart, I'd make them constants in a module namespace. I might make a module just for my standard units." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T14:26:34.163", "Id": "15734", "ParentId": "15728", "Score": "2" } } ]
{ "AcceptedAnswerId": "15734", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T11:24:08.107", "Id": "15728", "Score": "2", "Tags": [ "python", "object-oriented" ], "Title": "OOP design of code representing units of measurement" }
15728
<pre><code>def sieve_of_erastothenes(number): """Constructs all primes below the number""" big_list = [2] + range(3, number+1, 2) # ignore even numbers except 2 i = 1 # start at n=3, we've already done the even numbers while True: try: # use the next number that has not been removed already n = big_list[i] except IndexError: # if we've reached the end of big_list we're done here return big_list # keep only numbers that are smaller than n or not multiples of n big_list = [m for m in big_list if m&lt;=n or m%n != 0] i += 1 </code></pre> <p>On my computer, this code takes about half a second to calculate all primes below 10,000, fifteen seconds to do 100,000, and a very long time to calculate primes up to one million. I'm pretty sure it's correct (the first few numbers in the returned sequence are right), so what can I do to optimise it?</p> <p>I've tried a version that removes the relevant numbers in-place but that takes even longer (since it takes \$O(n)\$ to move all the remaining numbers down).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T22:36:05.073", "Id": "25666", "Score": "0", "body": "I know this could do with more tags but I'm not allowed to create them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T05:01:23.687", "Id": "25682", "Score": "1", "body": "I'm not very familiar with Python, but I might try using an array of i -> true/false (true meaning it's a prime, false meaning it's not). Your code would then go over this array and mark numbers as non-prime. I think your large growth in time is coming from copying the modified list over and over again. If you modify an array in place (modify the values, not remove them) and then generate a list based on that, I have a very strong hunch that it will be faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T09:48:52.623", "Id": "89646", "Score": "0", "body": "There are links to much faster Python implementations from [this post](http://codereview.stackexchange.com/questions/6477/sieve-of-eratosthenes-making-it-quicker). You can compare many different implementations [on Ideone](http://ideone.com/5YJkw), with the fastest one that was cited from the other post being available [here](http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188)." } ]
[ { "body": "<p>The problem is that the way this is set up, the time complexity is (close to) \\$O(n**2)\\$. For each remaining prime, you run over the entire list.</p>\n\n<p>In the last case, where you want to check for prime numbers up to 1,000,000 you end up iterating over your list 78,498 ** 2 times. 6,161,936,004 iterations is a lot to process.</p>\n\n<p>Below is an approach that crosses off the numbers instead, editing the large list of numbers in-place. This makes for a \\$O(n)\\$ solution, which times as such: </p>\n\n<ul>\n<li>range 10,000 : 549 usec per loop</li>\n<li>range 100,000 : 14.8 msec per loop</li>\n<li>range 1,000,000: 269 msec per loop</li>\n<li>range 10,000,000: 3.26 sec per loop</li>\n</ul>\n\n<hr>\n\n<pre><code>def sieve_of_erastothenes(limit):\n \"\"\"Create a list of all numbers up to `number`, mark all non-primes 0,\n leave all the primes in place. Filter out non-primes in the last step.\n \"\"\"\n sieve = range(limit + 1)\n\n # There are no prime factors larger than sqrt(number):\n test_max = int(math.ceil(limit ** 0.5))\n\n # We know 1 is not a prime factor\n sieve[1] = 0\n\n # The next is a cheat which allows us to not even consider even numbers\n # in the main loop of the program. You can leave this out and replace the\n # current xrange(3, test_max, 2) with xrange(2, test_max)\n\n # All multiples of 2 are not prime numbers, except for 2 itself:\n sieve[4::2] = (limit / 2 - 1) * [0]\n\n for prime in xrange(3, test_max, 2):\n if sieve[prime]:\n # If the number hasn't been marked a composite, it is prime.\n # For each prime number, we now mark its multiples as non-prime.\n multiples_count = limit / prime - (prime - 1)\n sieve[prime * prime::prime] = multiples_count * [0]\n # Filter out all the zeroes, we are left with only the primes\n return filter(None, sieve)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T07:55:29.763", "Id": "15790", "ParentId": "15777", "Score": "7" } } ]
{ "AcceptedAnswerId": "15790", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T22:35:29.987", "Id": "15777", "Score": "8", "Tags": [ "python", "optimization", "performance", "primes", "sieve-of-eratosthenes" ], "Title": "Why does my implementation of the Sieve of Eratosthenes take so long?" }
15777
<p>I'm teaching myself code using Zed Shaw's <a href="http://learnpythonthehardway.org/" rel="nofollow"><em>Learn Python The Hard Way</em></a>, and I got bored during one of the memorization lessons so I thought I would make a random D20 number generator for when I play RPGS. </p> <p>How can I make this code better? Is there anything stupid I'm doing? </p> <pre><code>import random name = raw_input('Please Type in your name &gt; ') print "\nHello %s &amp; welcome to the Random D20 Number Generator by Ray Weiss.\n" % (name) first_number = random.randint(1, 20) print first_number prompt = (""" Do you need another number? Please type yes or no. """) answer = raw_input(prompt) while answer == "yes": print random.randint(1, 20) answer = raw_input(prompt) if answer == "no": print "\nThank you %s for using the D20 RNG by Ray Weiss! Goodbye!\n" % (name) </code></pre> <p>Eventually I would love to add functionality to have it ask you what kind and how many dice you want to role, but for now a review of what I've done so far would really help.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T20:58:44.750", "Id": "38503", "Score": "0", "body": "Maybe incorporate some of the stuff in this answer: http://gamedev.stackexchange.com/questions/24656/random-calculations-for-strategy-based-games-in-java/24681#24681" } ]
[ { "body": "<p>Here's my take:</p>\n\n<pre><code>from random import randint\nname = raw_input('Please Type in your name &gt; ')\n\nprint \"\"\"\nHello {} &amp; welcome to the Random Number Generator by Ray Weiss.\n\"\"\".format(name)\nupper = int(raw_input('Enter the upper limit &gt; '))\nn = int(raw_input(\"How many D{} you'd like to roll? \".format(upper)))\n\nfor _ in xrange(n):\n print randint(1, upper)\nprint \"\"\"\nThank you {} for using the D{} RNG by Ray Weiss! Goodbye!\n\"\"\".format(name, upper)\n</code></pre>\n\n<p>Changes as compared to your version:</p>\n\n<ul>\n<li>directly import <code>randint</code> because it's the only function you use in <code>random</code>;</li>\n<li>use the new string formatting method (<code>str.format</code>);</li>\n<li>take the upper bound from user instead of hard-coding 20;</li>\n<li>take the number of rolls from user instead of repeatedly asking if that's enough;</li>\n<li>use a loop to make the repetition actually work. The self-repeating code asking the user if we should continue is now gone.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T21:41:46.293", "Id": "25672", "Score": "0", "body": "Thank you! This is cool, im gonna play around with it so that it continues to ask you if you want to roll more dice, some new stuff here i havent seen before. mind me asking what the _ in xrange(n) does? I can kind of discern the rest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T21:44:57.630", "Id": "25673", "Score": "1", "body": "@lerugray Here's the doc on [`xrange`](http://docs.python.org/library/functions.html#xrange). I just use it to run the loop body `n` times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T17:42:44.963", "Id": "25739", "Score": "1", "body": "@lerugray, _ in haskell means an empty name (you use it when you must supply a variable which is useless - like in this loop). I suppose it has the same meaning in python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T20:12:41.943", "Id": "25749", "Score": "0", "body": "@Aleksandar Technically, it's a fully legit name, so it _can_ be used inside the loop, but you got the idea right. I didn't know it came from Haskell (and don't know Haskell), but it makes a lot of sense." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T19:27:25.283", "Id": "15779", "ParentId": "15778", "Score": "8" } }, { "body": "<p>I don't have much to say on the style side, which is good. I think my only real comment would be that I personally find using newline characters simpler than triple-quotes for multiline strings, especially when you just want to make sure of the spacing between lines.</p>\n\n<p>I like that you're using <code>randint</code> for the rolls, instead of <code>randrange</code> or some other structure: it's inclusive for start and stop, and that exactly matches the real-world function that you're recreating here, so there's no need to fudge the parameters or the results with +1.</p>\n\n<p>Design-wise, I would split the front-end stuff, which takes input from the user and gives back information, from the actual dice-rolling. That would let you reuse the dice roller for other purposes (off the top of my head, a random treasure generator), extend the interface logic with additional kinds of functionality, or rework your logic without ripping apart the whole structure.</p>\n\n<p>And as long as you're doing that, think bigger -- 'I need to roll a d20' is just a single case of 'I need to roll some dice', and <em>that</em> problem's not much harder to solve. So here's how I would approach it:</p>\n\n<pre><code>def play():\n \"\"\"\n This function is just the user interface.\n It handles the input and output, and does not return anything.\n \"\"\"\n\n name = raw_input('Please Type in your name &gt; ')\n\n print \"\\nHello {}, &amp; welcome to the Random D20 Number Generator by Ray Weiss.\\n\".format(name)\n print \"Please type your rolls as 'NdX' (N=number of dice, X=size of dice), or 'Q' to quit.\\n\"\n\n while True:\n dice = raw_input(\"What dice do you want to roll? \").lower()\n if dice == 'q':\n break\n else:\n try:\n number, size = dice.split('d')\n results = roll_dice(int(number), int(size))\n except ValueError:\n # This will catch errors from dice.split() or roll_dice(),\n # but either case means there's a problem with the user's input.\n print \"I don't understand that roll.\\n\"\n else:\n print 'You rolled {!s}: {!s}\\n'.format(sum(results), results)\n\n print \"\\nThank you {} for using the D20 RNG by Ray Weiss! Goodbye!\\n\".format(name)\n\n\ndef roll_dice(number, size):\n \"\"\"\n number: any int; &lt; 1 is allowed, but returns an empty list.\n size: any int &gt; 1\n\n Returns: a list with `number` elements, of dice rolls from 1 to `size`\n \"\"\"\n from random import randint\n\n return [randint(1, size) for n in range(number)]\n</code></pre>\n\n<p>One functionality you would probably want to add would be modifying <code>roll_dice()</code> to accept a modifier (+ or - some amount). And if you really want to get fancy, you can start checking the results to highlight 1s or 20s, or other roll results that have special values in your game.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T18:25:34.123", "Id": "24917", "ParentId": "15778", "Score": "3" } } ]
{ "AcceptedAnswerId": "15779", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T19:02:05.540", "Id": "15778", "Score": "12", "Tags": [ "python", "beginner", "random", "simulation", "dice" ], "Title": "Random D20 number generator" }
15778
<p>I have been developing a <a href="https://github.com/santosh/capitalizr/blob/master/capitalizr" rel="nofollow noreferrer">capitalizer</a> in Python. This is actually a script that an end user will type at their terminal/command prompt. I have made this script to:</p> <ol> <li>Taking the first argument as a file name and process it.</li> <li>Don't process words that have 3 or less alphabet.</li> </ol> <p>Here's some code:</p> <pre><code>#!/usr/bin/env python #-*- coding:utf-8 -*- from os import linesep from string import punctuation from sys import argv script, givenfile = argv with open(givenfile) as file: # List to store the capitalised lines. lines = [] for line in file: # Split words by spaces. words = line.split() for i, word in enumerate(words): if len(word.strip(punctuation)) &gt; 3: # Capitalise and replace words longer than 3 letters (counts # without punctuation). if word != word.upper(): words[i] = word.capitalize() # Join the capitalised words with spaces. lines.append(' '.join(words)) # Join the capitalised lines by the line separator. capitalised = linesep.join(lines) print(capitalised) </code></pre> <p>A lot more features still have to be added but this script does the stuff it is made for.</p> <h3>What I want <em>(from you)</em>:</h3> <p>I want this script to be emerge as a command line utility. So,</p> <ol> <li>How can I make this a better command line utility?</li> <li>Could I have written in a better way?</li> <li>Can this script be faster?</li> <li>Are there any flaws?</li> <li>Other than GitHub, how can I make it available to the world <em>(so that it is easier to install for end users)</em>? because GitHub is for developers.</li> </ol> <p>Please also post links to make my script and me even more mature.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T07:00:35.923", "Id": "26051", "Score": "2", "body": "\"because GitHub is for developers.\" Non-developers tend to not use command line scripts..." } ]
[ { "body": "<p><strong>How can you make this a better command-line utility?</strong></p>\n\n<p>Along with using argparse (which is a great suggestion), I would suggest adding options for reading files from stdin, and maybe an option to write to somewhere other than stdout (to a file, for example).</p>\n\n<p><strong>Could it be written better / can it be faster?</strong></p>\n\n<p>Of course! There's always room for improvement. The biggest performance issue I can see here is that you append the output to the <code>lines</code> list, then output at the very end. The downside to this is that you must hold the entire output in memory before you return. If the file is large, it will be slow due to all the allocation/garbage-collection, and in extreme cases you could run out of memory!</p>\n\n<p>Instead of appending to <code>lines</code> and joining at the end, I'd suggest you replace this line:</p>\n\n<pre><code>lines.append(' '.join(words))\n</code></pre>\n\n<p>with</p>\n\n<pre><code>print ' '.join(words) # probably needs replaced with something that preserves whitespace.\n</code></pre>\n\n<p>Then delete all lines that refer to <code>lines</code>:</p>\n\n<p><code>lines = []</code> and <code>capitalised = linesep.join(lines)</code> and <code>print(capitalised)</code></p>\n\n<p>With this, and allowing for input from stdin, you could use it in unix pipelines, like so: <code>cat somefile | capitalizer | grep 'Foo'</code> (or something like that), and you'll see output immediately (as opposed to when the entire file is processed).</p>\n\n<p><strong>Is there an easier way for end-users to install this?</strong></p>\n\n<p>Yes, kind-of... as long as your users are not afraid of the command-line (which I assume, since this is a command-line program), you can publish this to PyPi, then it can be installed with tools like PIP and easy_install.</p>\n\n<p>Here's a simple tutorial for <a href=\"http://wiki.python.org/moin/CheeseShopTutorial\" rel=\"nofollow\">getting started with PyPi</a></p>\n\n<p>When setup properly, installation can be a simple as:</p>\n\n<p><code>easy_install capitalizer</code> or <code>pip install capitalizer</code></p>\n\n<p>Finally, discovery is a bit better than just github, as users can find your app with tools like <a href=\"http://pypi.python.org/pypi\" rel=\"nofollow\">the PyPi website</a>, and <a href=\"https://crate.io/\" rel=\"nofollow\">crate.io</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T22:39:11.513", "Id": "16016", "ParentId": "16007", "Score": "4" } } ]
{ "AcceptedAnswerId": "16016", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T12:09:18.237", "Id": "16007", "Score": "9", "Tags": [ "python", "performance", "strings", "file" ], "Title": "Command-line utility to capitalize long words in a file" }
16007
<p>In the book <em>Real World Haskell</em>, the author writes in the first line of every file that uses, for example the following: <code>file: ch05/PrettyJSON</code>. The chapter slash and the name of a module.</p> <p>I wanted to create a script which reads the first line and copies the files to the appropriate directory. In the above example we should copy the file to the directory ch05. I wanted to write this in Haskell in order to use it for "real world" applications.</p> <p>But before starting writing to Haskell I wrote it in Python:</p> <pre><code>import os import shutil current_dir = os.getcwd() current_files=os.listdir(current_dir) haskell_files=filter(lambda x:x.find(".hs")!=-1,current_files) for x in haskell_files: with open(x,"r") as f: header=f.readline() try: chIndex=header.index("ch") except ValueError as e: continue number=header[chIndex:chIndex+4] try: os.mkdir(number) shutil.copy2(x,number) except OSError as e: shutil.copy2(x,number) </code></pre> <p>And then I tried to write the same code in Haskell:</p> <pre><code>f x = dropWhile (\x-&gt; x/='c') x g x = takeWhile (\x-&gt; x=='c' || x=='h' || isDigit x) x z= do y&lt;-getCurrentDirectory e&lt;-getDirectoryContents y let b=findhs e mapM w b findhs filepaths = filter (isSuffixOf ".hs") filepaths w filename= do y&lt;-readFile filename let a=(g.f) y if "ch" `isPrefixOf` a then do createDirectoryIfMissing False a g&lt;-getCurrentDirectory writeFile (g ++"/"++ a ++ "/" ++ filename) y else return () main=z </code></pre> <p>Haskell code should be more elegant and more compact but it is not. Can you give me suggestions on making the above program more Haskellish?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T14:04:02.660", "Id": "26085", "Score": "0", "body": "A few links for scripting shell tasks in Haskell: [Haskell shell examples](http://www.haskell.org/haskellwiki/Applications_and_libraries/Operating_system#Haskell_shell_examples), [Shelly: Write your shell scripts in Haskell](http://www.yesodweb.com/blog/2012/03/shelly-for-shell-scripts), [Practical Haskell Programming: Scripting with Types](http://www.scribd.com/doc/36045849/Practical-Haskell-Programming-scripting-with-types)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T09:00:18.970", "Id": "26091", "Score": "1", "body": "Interesting question though. I think it breaks down to: How to code a completely sequential thing in \"good\" Haskell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T09:51:23.327", "Id": "26092", "Score": "1", "body": "You 've got the point @JFritsch. Can we write \"good\" sequential Haskell programs? This is the real question. Because if we want to do \"Real World Haskell\" I think that we should know how to write sequential code in Haskell." } ]
[ { "body": "<p>The first thing you note is that although haskellers like one character variable names in a small scope, we do not like one character functions in a global scope.</p>\n\n<p>There is an implicit partial function in your code. The function that gets the chapter name from the file (called <code>getChapter</code> in the code below), which takes strings (the content of the file) and gives a chapter name if it exists in the string. This seems like a good idea to make explicit using the <code>Maybe</code> type so that this fact does not need to be expressed in the control flow of the program. Note that I have split the getting of the chapter from the contents into the pure part (looking at the string) and the impure part (reading the file), this might be overkill but it's nice to remove impure functions whenever possible.</p>\n\n<pre><code>type Chapter = String\n\ngetChapter :: String -&gt; Maybe Chapter\ngetChapter ('c':'h':xs) = Just ('c':'h': takewhile isDigit xs)\ngetChapter (_:xs) = getChapter xs\ngetChapter [] = Nothing\n\nmain :: IO ()\nmain = do \n dir &lt;- getCurrentDirectory\n files &lt;- getDirectoryContents dir\n mapM_ process (filter (isPrefixOf \".hs\") files)\n\nprocess :: FilePath -&gt; IO ()\nprocess fileName = do\n chapter &lt;- liftM getChapter (readFile fileName)\n when (isJust chapter)\n (copyToChapter fileName (fromJust chapter))\n\ncopyToChapter :: FilePath -&gt; Chapter -&gt; IO ()\ncopyToChapter fileName chapter = do\n createDirectoryIfMissing False chapter\n copyFile fileName (chapter ++ \"/\" ++ fileName)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-30T11:56:36.010", "Id": "26115", "Score": "0", "body": "Your getChapter is slightly broken, as it takes only the first digit of the chapter. Also, you waste a lot of time reading the whole file, if the chapter is not specified." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-30T19:12:05.070", "Id": "26127", "Score": "0", "body": "@KarolisJuodelė I fixed the single digit thing. About wasting a lot of time: The original solution does that too (`dropWhile (/='c')`) so I just thought it was part of the specification." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T12:22:35.383", "Id": "16032", "ParentId": "16038", "Score": "3" } }, { "body": "<pre><code>getChapter :: String -&gt; IO (Maybe String)\ngetChapter name = if \".hs\" `isSuffixOf` name then do\n ln &lt;- withFile name ReadMode hGetLine\n return $ fmap (take 4) $ find (\"ch\" `isPrefixOf`) $ tails ln\n -- note, this is what your Pythod code does\n else return Nothing\n\ncopyToChapter :: String -&gt; String -&gt; IO ()\ncopyToChapter file chapter = do\n createDirectoryIfMissing False chapter\n copyFile file (chapter ++ \"/\" ++ file)\n\nprocess :: String -&gt; IO ()\nprocess file = do\n chapter &lt;- getChapter file\n maybe (return ()) (copyToChapter file) chapter\n\nmain = do \n dir &lt;- getCurrentDirectory\n files &lt;- getDirectoryContents dir\n mapM process files \n</code></pre>\n\n<p>This should be an improvement. Note that this is actually longer. Of course, you could write</p>\n\n<pre><code>getChapter name = if \".hs\" `isSuffixOf` name then withFile name ReadMode hGetLine &gt;&gt;= return . fmap (take 4) . find (\"ch\" `isPrefixOf`) . tails\n else return Nothing\ncopyToChapter file chapter = createDirectoryIfMissing False chapter &gt;&gt; copyFile file (chapter ++ \"/\" ++ file)\nprocess file = getChapter file &gt;&gt;= maybe (return ()) (copyToChapter file)\nmain = getCurrentDirectory &gt;&gt;= getDirectoryContents &gt;&gt;= mapM process\n</code></pre>\n\n<p>if you like few lines of code. I'd advise against it though.</p>\n\n<p>In general, you should not expect Haskell to be better at procedural tasks than procedural languages.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T14:18:36.793", "Id": "26093", "Score": "3", "body": "`hould not expect Haskell to be better at procedural tasks than procedural languages.` -- but note that because of monads, structuring procedural programs is a lot easier as code blocks are first class. error handling may also be simplified thanks to monads. Abstraction capaabilities always help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T10:01:43.267", "Id": "16039", "ParentId": "16038", "Score": "1" } }, { "body": "<p>Notes:</p>\n\n<ul>\n<li>don't use single letter variable names for top level bindings</li>\n<li>leave spaces around syntax like <code>=</code> and <code>&lt;-</code></li>\n<li>use meaningful variable names for system values (such as file contents)</li>\n<li>inline single uses of tiny functions, such as your <code>findhs e</code></li>\n<li>give your core algorithm, <code>w</code>, a meaningful name</li>\n<li>don't use long names for local parameters like <code>filepaths</code>. <code>fs</code> is fine.</li>\n<li>use pointfree style for arguments in the final position</li>\n<li>use <code>when</code> instead of <code>if .. then ... else return ()</code></li>\n<li>use the filepath library for nice file path construction</li>\n<li>your only use of <code>f</code> and <code>g</code> is to compose them. so do that and name the result.</li>\n<li>use section syntax for lambdas as function arguments to HOFs</li>\n<li>indent consistently</li>\n<li>use <code>mapM_</code> when the result you don't care about.</li>\n</ul>\n\n<p>Resulting in:</p>\n\n<pre><code>import Data.Char\nimport Data.List\nimport Control.Monad\nimport System.Directory\nimport System.FilePath\n\nclean = takeWhile (\\x -&gt; x == 'c' || x == 'h' || isDigit x)\n . dropWhile (/='c')\n\nprocess path = do\n y &lt;- readFile path\n\n let a = clean y\n\n when (\"ch\" `isPrefixOf` a) $ do\n createDirectoryIfMissing False a\n g &lt;- getCurrentDirectory\n writeFile (g &lt;/&gt; a &lt;/&gt; path) y\n\nmain = do\n y &lt;- getCurrentDirectory\n e &lt;- getDirectoryContents y\n mapM_ process $ filter (isSuffixOf \".hs\") e\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T15:00:17.843", "Id": "26094", "Score": "0", "body": "much nicer. `getCurrentDirectory` is superfluous though - in the `when` clause don't need `g`, and in `main`, you can replace `y` with `\".\"`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T15:08:48.447", "Id": "26095", "Score": "1", "body": "In the sense of the original python code, the name of target directory has to be computed as `take 4 <$> find (isPrefixOf \"ch\") (tails y)` where `y` is extracted from `head . lines <$> readFile path` ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T16:03:12.673", "Id": "26367", "Score": "1", "body": "`main` can be written as `main = getCurrentDirectory >>= getDirectoryContents >>= mapM_ process . filter (isSuffixOf \".hs\")`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-13T18:24:00.143", "Id": "176940", "Score": "0", "body": "@nponeccop Much more monadic!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T14:16:46.280", "Id": "16040", "ParentId": "16038", "Score": "17" } }, { "body": "<p>Other way you could write your Shell-like scripts in Haskell is using <a href=\"http://hackage.haskell.org/package/shelly\" rel=\"nofollow\">Shelly</a> library. It provides functionality specifically suited for such tasks, kind of DSL, which brings you more brevity. <a href=\"https://github.com/yesodweb/Shelly.hs/blob/master/README.md\" rel=\"nofollow\">Its GitHub page</a> contains a bunch of usefull links with examples.</p>\n\n<p>E.g. Don's program could be rewritten to:</p>\n\n<pre><code>{-# LANGUAGE OverloadedStrings #-}\nimport Data.Text.Lazy as LT\nimport Data.Text.Lazy.IO as LTIO\nimport Prelude as P hiding (FilePath)\nimport Data.Char\nimport Shelly\n\nclean = LT.takeWhile (\\x -&gt; x == 'c' || x == 'h' || isDigit x)\n . LT.dropWhile (/='c')\n\nreadFileP = liftIO . LTIO.readFile . unpack . toTextIgnore\n\nprocess path = shelly $ do\n y &lt;- readFileP path\n let a = clean y\n\n when (\"ch\" `LT.isPrefixOf` a) $ do\n let p = fromText a\n mkdir_p p\n cp path p\n\nmain = shelly $ do\n e &lt;- ls \".\"\n mapM_ process $ P.filter (hasExt \"hs\") e\n</code></pre>\n\n<p>The only flaw here is a bit bloated <code>readFileP</code>. I did not find a better way (which might be due to my beginner level). Possibly such function could become a part of <code>Shelly</code> library itself.</p>\n\n<p>So far I found combination of Haskell and Shelly quite good as \"a scripting language for every day task\" and start to rewrite my scripts utilizing Shelly. That is a nice entrance gateway to Haskell language itself for me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T17:34:07.040", "Id": "16041", "ParentId": "16038", "Score": "1" } } ]
{ "AcceptedAnswerId": "16040", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T08:26:35.393", "Id": "16038", "Score": "15", "Tags": [ "python", "haskell" ], "Title": "Script for copying files to the appropriate directory" }
16038
<p>I've been learning about Monte Carlo simulations on MIT's intro to programming class, and I'm trying to implement one that calculates the probability of flipping a coin heads side up 4 times in a row out of ten flips.</p> <p>Basically, I calculate if the current flip in a 10 flip session is equal to the prior flip, and if it is, I increment a counter. Once that counter has reached 3, I exit the loop even if I haven't done all 10 coin flips since subsequent flips have no bearing on the probability. Then I increment a counter counting the number of flip sessions that successfully had 4 consecutive heads in a row. At the end, I divide the number of successful sessions by the total number of trials. </p> <p>The simulation runs 10,000 trials.</p> <pre><code>def simThrows(numFlips): consecSuccess = 0 ## number of trials where 4 heads were flipped consecutively coin = 0 ## to be assigned to a number between 0 and 1 numTrials = 10000 for i in range(numTrials): consecCount = 0 currentFlip = "" priorFlip = "" while consecCount &lt;= 3: for flip in range(numFlips): coin = random.random() if coin &lt; .5: currentFlip = "Heads" if currentFlip == priorFlip: consecCount += 1 priorFlip = "Heads" else: consecCount = 0 priorFlip = "Heads" elif coin &gt; .5: currentFlip = "Tails" if currentFlip == priorFlip: consecCount = 0 priorFlip = "Tails" else: consecCount = 0 priorFlip = "Tails" break if consecCount &gt;= 3: print("Success!") consecSuccess += 1 print("Probability of getting 4 or more heads in a row: " + str(consecSuccess/numTrials)) simThrows(10) </code></pre> <p>The code seems to work (gives me consistent results each time that seem to line up to the analytic probability), but it's a bit verbose for such a simple task. Does anyone see where my code can get better? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T23:59:44.497", "Id": "26491", "Score": "1", "body": "Why is the priorFlip when you get Tails being set to Heads and why are you incrementing the consecCount? I'm not sure how this is going to give you the right probability?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:05:07.067", "Id": "26492", "Score": "0", "body": "Oops, accidentally pasted my old code -- the updated version has the \"Tails\" fix. As for incrementing consecCount, it's only incremented when priorFlip == consecFlip. It is reset to 0 otherwise. Once it hits 3, it exits the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:06:07.803", "Id": "26493", "Score": "1", "body": "So your current code will do either 4 Heads in a row or 4 Tails . . . is that intentional?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:08:11.043", "Id": "26494", "Score": "0", "body": "Ooops! Meant to change that to consecCount = 0 for each of the Tails cases. Now does it look okay?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:13:52.237", "Id": "26495", "Score": "0", "body": "You have several code errors . . . I've posted a simplified version, trying to stick to the spirit of your code, and pointed out some of the errors . . ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:30:12.147", "Id": "26496", "Score": "0", "body": "Made a few more optimizations after looking at this a bit more . . ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T15:21:41.967", "Id": "26529", "Score": "0", "body": "I'm being nitpicky (but for the benefit of your code!), but your code doesn't account for a random() == .500--you have less than and greater than. Since random gives you 0-1.0 (non-inclusive 1.0), you can adjust this with >= .50 on your elif or to use an unspecified ELSE instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-23T08:03:53.740", "Id": "96194", "Score": "0", "body": "Why not try out this pattern posted in April this year http://code.activestate.com/recipes/578868-monte-carlo-engine-simple-head-tail-model/" } ]
[ { "body": "<p>So a few errors/simplifications I can see:</p>\n\n<ol>\n<li>You're incrementing <code>consecCount</code> if you have either two heads or two\ntails. </li>\n<li>setting the <code>priorFlip</code> value can be done regardless of what\nthe prior flip was </li>\n<li>Your <code>while</code> loop doesn't do anything as you have a\nfor loop in it, then break right after it, so you'll always make all\n10 tosses. A while loop isn't constantly checking the value inside\nof it; only when it finishes executing the code block. As you <code>break</code> after the <code>for</code> loop, the <code>while</code> condition will never be checked</li>\n<li>There's no reason to track the previous flip, if you always reset the count on a tail</li>\n<li>while the odds are small, you'll be throwing away any toss that is equal to .5</li>\n</ol>\n\n<p>Anyway, here's my first pass at a simplified version:</p>\n\n<pre><code>def simThrows(numFlips):\n consecSuccess = 0 ## number of trials where 4 heads were flipped consecutively\n coin = 0 ## to be assigned to a number between 0 and 1\n numTrials = 10000\n for i in range(numTrials):\n consecCount = 0\n for flip in range(numFlips):\n coin = random.random()\n #since random.random() generates [0.0, 1.0), we'll make the lower bound inclusive\n if coin &lt;= .5:\n #Treat the lower half as heads, so increment the count\n consecCount += 1 \n # No need for an elif here, it wasn't a head, so it must have been a tail\n else:\n # Tails, so we don't care about anything, just reset the count\n consecCount = 0 \n #After each flip, check if we've had 4 consecutive, otherwise keep flipping\n if consecCount &gt;= 3:\n print(\"Success!\")\n consecSuccess += 1\n # we had enough, so break out of the \"for flip\" loop\n # we'll end up in the for i in range loop . . .\n break \n print(\"Probability of getting 4 or more heads in a row: \" + str(consecSuccess/numTrials))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:13:08.540", "Id": "16312", "ParentId": "16310", "Score": "2" } }, { "body": "<p>@Keith Randall showed a short soltion, but verbosity is not necessary a bad thing. Often an important thing is to decomopose the task into separate sub-tasks, which are generic and reusable:</p>\n\n<pre><code>import random\n\ndef montecarlo(experiment, trials):\n r = 0\n for i in range(trials):\n experiment.reset()\n r += 1 if experiment.run() else 0\n return r / float(trials)\n\n\nclass Coinrowflipper():\n def __init__(self, trials, headsinrow):\n self.headsinrow = headsinrow\n self.trials = trials\n self.reset()\n def reset(self):\n self.count = 0\n def run(self):\n for i in range(self.trials):\n if random.random() &lt; 0.5:\n self.count += 1\n if self.count == self.headsinrow:\n return True\n else:\n self.count = 0\n return False\n\nc = Coinrowflipper(10,4)\nprint montecarlo(c, 1000)\n</code></pre>\n\n<p>This way you have a generic monte-carlo experiment, and a generic heads-in a row solution.</p>\n\n<p>Note: using strings (<code>\"Heads\"</code>) to mark internal state is discouraged in any programming language...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:22:53.913", "Id": "16313", "ParentId": "16310", "Score": "4" } }, { "body": "<p>Based on @Karoly Horvath but different enough to be a standalone answer.</p>\n\n<p>A class is very much overkill for this problem, I have achieved the same functionality with a function.</p>\n\n<pre><code>import random\n\ndef montecarlo(experiment, trials):\n positive = 0\n for _ in range(trials):\n positive += 1 if experiment() else 0\n return positive / float(trials)\n\ndef successive_heads(trials,heads_in_a_row):\n count = 0\n for _ in range(trials):\n if random.random() &lt; 0.5:\n count += 1\n if count == heads_in_a_row:\n return True\n else:\n count = 0\n return False\n\nprint(montecarlo(lambda: successive_heads(100,10), 10000))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-13T19:02:22.530", "Id": "84036", "ParentId": "16310", "Score": "1" } } ]
{ "AcceptedAnswerId": "16314", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T23:52:10.790", "Id": "16310", "Score": "5", "Tags": [ "python", "simulation", "statistics" ], "Title": "Monte Carlo coin flip simulation" }
16310
<p>This is my first time working with classes and it's still unclear to me. I was wondering if someone can tell me if I did this right.</p> <blockquote> <p>Define a new class, Track, that has an artist (a string), a title (also a string), and an album (see below).</p> <ol> <li>Has a method <code>__init__</code>(self, artist, title, album=None). The arguments artist and and title are strings and album is an Album object (see below)</li> <li>Has a method <code>__str__</code>(self) that returns a reasonable string representation of this track</li> <li>Has a method set_album(self, album) that sets this track's album to album</li> </ol> </blockquote> <pre><code>class Track: def __init__(self, artist, title, album=None): self.artist = str(artist) self.title = str(title) self.album = album def __str__(self): return self.artist + " " + self.title + " " + self.album def set_album(self, album): self.album = album Track = Track("Andy", "Me", "Self named") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T00:54:32.897", "Id": "26563", "Score": "3", "body": "The `set_album` method is redundant and _unpythonic_: simply assign to the attribute directly in your code. If at any point in the future you need some more complicated behaviour when setting the attribute, look into using a [property](http://docs.python.org/library/functions.html#property) then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:43:39.027", "Id": "26805", "Score": "0", "body": "@PedroRomano - agreed, but it seems as though the homework question (I assume it's homework?) is explicitly asking for the method `set_album`." } ]
[ { "body": "<p>In general, looks great! A few things:</p>\n\n<ol>\n<li>This relates to 'new-style' classes in Python - make sure that they inherit from <code>object</code>. It sounds like you are learning about classes now, so I will spare an explanation of what inheritance is since you'll eventually get to it.</li>\n<li>I could be misguided in saying this, but generally I've seen/done type conversion (where you call <code>str()</code>) outside of the constructor (i.e. the <code>__init__()</code> function). The instructions says it expects a string, and you are already passing a string in the <code>Track =</code> line, so removing the <code>str()</code> parts will still result in the correct answer.</li>\n<li>The instructions say that <code>album</code> is an \"Album object\", which means that <code>Album</code> will be a class as well. I'm assuming you're just getting this started so it hasn't been created yet, but when you do, you can just pass the <code>Album</code> object into your <code>Track</code> constructor.</li>\n<li>Naming - in general, avoid naming your instances the same thing as the class (in your case, <code>Track</code> is the class). This leads to confusion, especially when you need to create a second instance (because <code>Track</code> will then an instance of Track, instead of the <code>Track</code> class.</li>\n</ol>\n\n<p>Here is your same code with a few of those adjustments. In general though, looking good!</p>\n\n<pre><code>class Track(object):\n def __init__(self, artist, title, album=None):\n self.artist = artist\n self.title = title\n self.album = album\n\n def __str__(self):\n # This is called 'string formatting' and lets you create a template string\n # and then plug in variables, like so\n return \"%s - %s (%s)\" % (self.artist, self.title, self.album)\n\n def set_album(self, album):\n self.album = album\n\nmy_track = Track(\"Andy\", \"Me\", \"Self named\")\n\n# This will show you what __str__ does\nprint my_track\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:44:32.037", "Id": "26806", "Score": "0", "body": "Regarding point 1: you don't need to inherit from `object` in Python 3.x. I can't tell what version he's using. Also, the `%` formatting operator [has been superseded by `string.format()`](http://www.python.org/dev/peps/pep-3101/) (though of course the old style is still hugely common)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T22:09:00.343", "Id": "26810", "Score": "2", "body": "@poorsod Agreed - I actually don't ever use the % operator :) Figured it would be the easier one to explain, but am looking forward to a `.format()`-only future! As to inheriting from `object`, I blindly assumed that he was using 2.x - I need to get with the future I guess :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T00:47:07.380", "Id": "16337", "ParentId": "16332", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:21:33.600", "Id": "16332", "Score": "5", "Tags": [ "python" ], "Title": "Music track class" }
16332
<p>Very simple I want to edit a virtual host files and replace the tags I made with some actual data:</p> <pre><code>import os, re with open('virt_host', 'r+') as virtual file = virtual.read() file = re.sub('{{dir}}', '/home/richard', file) file = re.sub('{{user}}', 'richard', file) file = re.sub('{{domain_name}}', 'richard.com', file) with open('new_virt', 'w+') as new_file new_file.write(file) new_file.close() </code></pre> <p>Is this the best way?</p>
[]
[ { "body": "<pre><code>import os, re\n</code></pre>\n\n<p>Here, make sure you put a colon after <code>virtual</code></p>\n\n<pre><code>with open('virt_host', 'r+') as virtual:\n</code></pre>\n\n<p>Avoid using built-in Python keywords as variables (such as <code>file</code> here)</p>\n\n<pre><code> f = virtual.read()\n</code></pre>\n\n<p>This part is explicit, which is a good thing. Depending on whether or not you have control over how your variables are defined, you could use <a href=\"http://docs.python.org/library/string.html#format-string-syntax\" rel=\"nofollow\">string formatting</a> to pass a dictionary containing your values into the read file, which would save a few function calls.</p>\n\n<pre><code> f = re.sub('{{dir}}', '/home/richard', f)\n f = re.sub('{{user}}', 'richard', f)\n f = re.sub('{{domain_name}}', 'richard.com', f)\n</code></pre>\n\n<p>Same as above regarding the colon</p>\n\n<pre><code>with open('new_virt', 'w+') as new_file:\n new_file.write(f)\n</code></pre>\n\n<p>One of the main benefits of using a context manager (such as <code>with</code>) is that it handles things such as closing by itself. Therefore, you can remove the <code>new_file.close()</code> line.</p>\n\n<p>Here is the full code with the adjustments noted. Hope it helps!</p>\n\n<pre><code>import os, re\n\nwith open('virt_host', 'r+') as virtual:\n f = virtual.read()\n f = re.sub('{{dir}}', '/home/richard', f)\n f = re.sub('{{user}}', 'richard', f)\n f = re.sub('{{domain_name}}', 'richard.com', f)\n\nwith open('new_virt', 'w+') as new_file:\n new_file.write(f)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T15:32:04.370", "Id": "26612", "Score": "0", "body": "@Jason No prob man!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T08:38:28.600", "Id": "16344", "ParentId": "16341", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T07:53:45.790", "Id": "16341", "Score": "3", "Tags": [ "python" ], "Title": "How to improve method of opening file in python then writing to another?" }
16341
<p>I would like to write a python or c++ function to print numbers like the following examples (with n as input parameter):</p> <p>When n = 3, print:</p> <pre><code>1 2 3 8 0 4 7 6 5 </code></pre> <p>When n = 4, print:</p> <pre><code>4 5 6 7 15 0 1 8 14 3 2 9 13 12 11 10 </code></pre> <p>I have an answer in the following code block, but it is not quite elegant. Does anyone have a better solution?</p> <pre><code>def print_matrix(n): l = [i for i in range(0,n*n)] start = (n-1)/2 end = n-1-start count = 0 if start ==end: l [start+ n*end] = count start -= 1 count +=1 while start &gt;=0: end = n - start for i in range(start, end-1): x= i y= start print y*n +x l[y*n +x] = count count +=1 for i in range(start, end-1): x = end-1 y = i print y*n +x l[y*n +x] = count count +=1 for i in range(end-1,start,-1): x= i y= end-1 print y*n +x l[y*n +x] = count count +=1 for i in range(end-1, start,-1): x = start y = i print y*n +x l[y*n +x] = count count +=1 start -=1 print l </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T14:37:28.987", "Id": "26841", "Score": "1", "body": "Have no idea why this has been moved here. Much more suited to stack overflow. There are also many more people on SO that can help maybe you should rephrase the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T19:32:46.140", "Id": "27845", "Score": "3", "body": "@LokiAstari, its not clear to me why you think this is off-topic here. People presenting working code and ask for more elegant solutions seems to be a large part of the questions here." } ]
[ { "body": "<p>Using a 2D array to store the matrix, we can simplify the function greatly. This uses Python 2 syntax.</p>\n\n<pre><code>def print_matrix(n):\n mat = [[0]*n for _ in xrange(n)]\n\n k = 0 # value to write\n for level in reversed(xrange(n, 0, -2)):\n start = n/2 - level/2\n pr = pc = start # current row, column indices\n if level == 1: # special case: no perimeter crawl\n mat[pr][pc] = k\n k += 1\n continue\n # walk along each edge of the perimeter\n for dr, dc in [(0,1), (1,0), (0,-1), (-1,0)]:\n for i in xrange(level - 1):\n mat[pr][pc] = k\n k, pr, pc = k+1, pr+dr, pc+dc\n\n width = len(str(n*n-1))\n for i in mat:\n for j in i:\n print '{:&lt;{width}}'.format(j, width=width),\n print\n</code></pre>\n\n<p>Samples:</p>\n\n<pre><code>&gt;&gt;&gt; print_matrix(4)\n4 5 6 7 \n15 0 1 8 \n14 3 2 9 \n13 12 11 10\n&gt;&gt;&gt; print_matrix(3)\n1 2 3\n8 0 4\n7 6 5\n&gt;&gt;&gt; print_matrix(2)\n0 1\n3 2\n&gt;&gt;&gt; print_matrix(1)\n0\n&gt;&gt;&gt; print_matrix(9)\n49 50 51 52 53 54 55 56 57\n80 25 26 27 28 29 30 31 58\n79 48 9 10 11 12 13 32 59\n78 47 24 1 2 3 14 33 60\n77 46 23 8 0 4 15 34 61\n76 45 22 7 6 5 16 35 62\n75 44 21 20 19 18 17 36 63\n74 43 42 41 40 39 38 37 64\n73 72 71 70 69 68 67 66 65\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T17:42:02.093", "Id": "16505", "ParentId": "16503", "Score": "5" } }, { "body": "<p>The important element of a shorter program is using a direction-array to set the step directions in your matrix; whether the matrix is represented via a 1D vector or a 2D matrix is less important. In a vector, the same-column cell in the next row is n elements away from the current cell.</p>\n\n<pre><code>def print_matrix(n):\n ar = [0 for i in range(n*n)]\n m, bat = n, 0\n for shell in range((n+1)//2):\n at = bat\n m = m-2\n ar[at] = val = m*m # Each shell starts with a square\n if m&lt;0:\n ar[at] = 0\n break\n for delta in [1, n, -1, -n]: # Do 4 sides of shell\n # Fill from corner to just before next corner\n for tic in range(m+1):\n ar[at] = val\n at += delta # Step to next or prev row or col\n val += 1\n bat += n+1 # Step to next-inner shell\n\n # Print matrix in n rows, n columns\n for i in range(n):\n for j in range(n):\n print \"\\t\", ar[i*n+j],\n print\n\nfor n in range(1,7):\n print \"n = \", n\n print_matrix(n)\n</code></pre>\n\n<p>This produces output like the following:</p>\n\n<pre><code>n = 1\n 0\nn = 2\n 0 1\n 3 2\nn = 3\n 1 2 3\n 8 0 4\n 7 6 5\n...\nn = 6\n 16 17 18 19 20 21\n 35 4 5 6 7 22\n 34 15 0 1 8 23\n 33 14 3 2 9 24\n 32 13 12 11 10 25\n 31 30 29 28 27 26\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T18:23:23.993", "Id": "16508", "ParentId": "16503", "Score": "2" } }, { "body": "<p>The code that you and other people posted could be simplified to the following:</p>\n\n<pre><code>def slot(n, x,y):\n ma = max(x,y)+1\n mi = min(x,y)\n o= min(n-ma,mi)\n l= max(n-2*(o+1),0)\n p= x+y - 2*o\n if x&lt;y: p= 4*(l+1)-p\n return l*l+p\n</code></pre>\n\n<p>To use the code you could do:</p>\n\n<pre><code>from sys import stdout as out\n\nn = 3\nfor y in xrange(n):\n for x in xrange(n):\n out.write(' %2d'%slot(n,x,y))\n print\n</code></pre>\n\n<p>As you can see, it doesn't need 2D arrays.<br>\nIt just calculates the values pixel-per-pixel.<br>\nIt is more robust: try to do any other program with <code>n=1000000000</code> and it will fail.</p>\n\n<p>The results are always as expected, see them <a href=\"http://ideone.com/8KakI\">at IdeOne</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T20:36:53.217", "Id": "27975", "Score": "0", "body": "nice.. :) however, I'd say that `min` and `max` have their own `if` in their implementation, so it's around 4-5 `if`s in a whole." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:34:08.167", "Id": "27981", "Score": "0", "body": "Yeah I know, but they're mathematic functions so their implementations don't count :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T19:17:10.037", "Id": "17576", "ParentId": "16503", "Score": "5" } } ]
{ "AcceptedAnswerId": "16505", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T13:14:44.300", "Id": "16503", "Score": "10", "Tags": [ "python", "algorithm" ], "Title": "Write a function to print numbers" }
16503
<p>I have created iterator and generator versions of Python's <a href="http://docs.python.org/library/functions.html#range" rel="nofollow"><code>range()</code></a>:</p> <h3>Generator version</h3> <pre><code>def irange(*args): if len(args) &gt; 3: raise TypeError('irange() expected at most 3 arguments, got %s' % (len(args))) elif len(args) == 1: start_element = 0 end_element = args[0] step = 1 else: start_element = args[0] end_element = args[1] if len(args) == 2: step = 1 elif (args[2] % 1 == 0 and args[2] != 0): step = args[2] else: raise ValueError('irange() step argument must not be zero') if((type(start_element) is str) or (type(end_element) is str) or (type(step) is str)): raise TypeError('irange() integer expected, got str') count = 0 while (( start_element + step &lt; end_element ) if 0 &lt; step else ( end_element &lt; start_element + step )) : if count == 0: item = start_element else: item = start_element + step start_element = item count +=1 yield item </code></pre> <h3>Iterator version</h3> <pre><code>class Irange: def __init__(self, start_element, end_element=None, step=1): if step == 0: raise ValueError('Irange() step argument must not be zero') if((type(start_element) is str) or (type(end_element) is str) or (type(step) is str)): raise TypeError('Irange() integer expected, got str') self.start_element = start_element self.end_element = end_element self.step = step self.index = 0 if end_element is None: self.start_element = 0 self.end_element = start_element def __iter__(self): return self def next(self): if self.index == 0: self.item = self.start_element else: self.item = self.start_element + self.step if self.step &gt; 0: if self.item &gt;= self.end_element: raise StopIteration elif self.step &lt; 0: if self.item &lt;= self.end_element: raise StopIteration self.start_element = self.item self.index += 1 return self.item </code></pre> <h3>Usage</h3> <pre><code> &gt;&gt;&gt; for i in irange(2,5): ... print i, 2 3 4 &gt;&gt;&gt; for i in irange(2,-3,-1): ... print i, 2 1 0 -1 -2 &gt;&gt;&gt; for i in Irange(3): ... print i, 0 1 2 </code></pre> <p>I would like to know if the approach is correct.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T18:10:01.257", "Id": "29647", "Score": "1", "body": "how is this different than `xrange`? Or are you just testing your ability to write generators/iterators?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T18:16:49.140", "Id": "29649", "Score": "0", "body": "This is same as xrange but using generator/iterator" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T19:03:54.870", "Id": "29651", "Score": "1", "body": "If you are looking for the behavior of an iterator, does this accomplish the same for you? `def irange(*args): return iter(xrange(*args))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T04:59:08.223", "Id": "29765", "Score": "0", "body": "this sounds good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T15:50:19.880", "Id": "44997", "Score": "0", "body": "In python 2 xrange is an iterable returning an Iterator http://stackoverflow.com/a/10776268/639650" } ]
[ { "body": "<p>First of all, to validate that the function is working,\nit's good to use <code>assert</code> statements:</p>\n\n<pre><code>assert [0, 1, 2, 3, 4] == [x for x in irange(5)]\nassert [2, 3, 4] == [x for x in irange(2, 5)]\nassert [2, 1, 0, -1, -2] == [x for x in irange(2, -3, -1)]\n</code></pre>\n\n<p>With these statements covering my back,\nI refactored your <code>irange</code> method to this:</p>\n\n<pre><code>def irange(*args):\n len_args = len(args)\n\n if len_args &gt; 3:\n raise TypeError('irange() expected at most 3 arguments, got %s' % len_args)\n\n if len_args &lt; 1:\n raise TypeError('irange() expected at least 1 arguments, got %s' % len_args)\n\n sanitized_args = [int(x) for x in args]\n\n if len_args == 1:\n start_element = 0\n end_element = sanitized_args[0]\n step = 1\n else:\n start_element = sanitized_args[0]\n end_element = sanitized_args[1]\n step = 1 if len_args == 2 else sanitized_args[2]\n\n current = start_element\n\n if step &gt; 0:\n def should_continue():\n return current &lt; end_element\n else:\n def should_continue():\n return current &gt; end_element\n\n while should_continue():\n yield current\n current += step\n</code></pre>\n\n<p>Points of improvement:</p>\n\n<ul>\n<li>Since <code>len(args)</code> is used repeatedly, I cache it in <code>len_args</code></li>\n<li>Added <code>len(args) &lt; 1</code> check too, in the same fashion as <code>len(args) &gt; 3</code></li>\n<li>Simplified the type checking of args:\n<ul>\n<li>Sanitize with a single, simple list comprehension</li>\n<li>If there are any non-integer arguments, a <code>ValueError</code> will be raised with a reasonably understandable error message</li>\n</ul></li>\n<li>Simplified the initialization of <code>start_element</code>, <code>end_element</code> and <code>step</code></li>\n<li>Greatly simplified the stepping logic</li>\n</ul>\n\n<p>As for the iterator version,\nit would be easiest and best to implement that in terms of the generator version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-21T08:12:51.320", "Id": "74378", "ParentId": "17543", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T03:15:57.977", "Id": "17543", "Score": "4", "Tags": [ "python", "reinventing-the-wheel", "iterator", "generator" ], "Title": "Iterator and Generator versions of Python's range()" }
17543
<pre><code>selected_hour=12 dates=[] date1 = datetime.datetime(2012, 9, 10, 11, 46, 45) date2 = datetime.datetime(2012, 9, 10, 12, 46, 45) date3 = datetime.datetime(2012, 9, 10, 13, 47, 45) date4 = datetime.datetime(2012, 9, 10, 13, 06, 45) dates.append(date1) dates.append(date2) dates.append(date3) dates.append(date4) for i in dates: if (i.hour&lt;=selected_hour+1 and i.hour&gt;=selected_hour-1): if not i.hour==selected_hour: if i.hour==selected_hour-1 and i.minute&gt;45: print i if i.hour==selected_hour+1 and i.minute&lt;=15: print i if i.hour==selected_hour: print i </code></pre> <p>Result is :</p> <pre><code> 2012-09-10 11:46:45 2012-09-10 12:46:45 2012-09-10 13:06:45 </code></pre> <p>I want to filter my dates based on <code>selected_hour</code>. The output should be 15 minutes later and before of the <code>selected_hour</code> including all <code>selected_hour</code>'s minutes. This codes does what I want but, i am looking for a nicer way to do that. How to get same results in a shorter and better way ? </p>
[]
[ { "body": "<p>Try something like this:</p>\n\n<pre><code>for i in dates:\n if i.hour == selected_hour:\n print i\n elif i.hour == (selected_hour - 1) % 24 and i.minute &gt; 45:\n print i\n elif i.hour == (selected_hour + 1) % 24 and i.minute &lt;= 15:\n print i\n</code></pre>\n\n<p>The biggest technique I used to condense your code basically was \"Don't repeat yourself\"! You have a lot of redundant <code>if</code> statements in your code which can be simplified.</p>\n\n<p>Another thing that makes my code more understandable is that it's flat, not nested. Ideally, you'd want to minimize the number of logic branches.</p>\n\n<p>Edit: As @Dougal mentioned, my original code wouldn't work on the special case of midnight. I added in a modulus operator on my two <code>elif</code> conditions so that the <code>selected_hour</code> test wraps in a 24 digit circle, just like real time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:09:32.827", "Id": "27947", "Score": "2", "body": "Note that this doesn't wrap around at midnight well (like the OP's)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:12:03.377", "Id": "27948", "Score": "0", "body": "Maybe I'm not seeing that - what's a datetime that I can see the deficiency with?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:13:07.163", "Id": "27949", "Score": "2", "body": "If we're selecting for 11pm (`i.hour == 23`), then it should presumably allow times up through 12:15am, but this would look for `i.hour == 24`, which won't happen." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:02:37.980", "Id": "17565", "ParentId": "17564", "Score": "5" } }, { "body": "<p>I have a question before the answer. I don't know if you want to filter this case, but if you take this datetime:</p>\n\n<pre><code>selected_hour=12\ndate4 = datetime.datetime(2012, 9, 10, 13, 15, 45)\n</code></pre>\n\n<p>you don't filter that result, and being strict, that datetime is over 15 minutes your selected_hour.</p>\n\n<p>Anyway, if you have the year, month and day too, you can use <code>datetime</code> data type and <code>timedelta</code> to solve this problem.</p>\n\n<pre><code>import datetime\nfrom datetime import timedelta\n\nselected_hour=12\ndates=[]\ndate1 = datetime.datetime(2012, 9, 10, 11, 44, 59)\ndate2 = datetime.datetime(2012, 9, 10, 11, 45, 00)\ndate3 = datetime.datetime(2012, 9, 10, 13, 15, 00)\ndate4 = datetime.datetime(2012, 9, 10, 13, 15, 01)\ndate5 = datetime.datetime(2011, 5, 11, 13, 15, 00)\ndate6 = datetime.datetime(2011, 5, 11, 13, 15, 01)\ndates.append(date1)\ndates.append(date2)\ndates.append(date3)\ndates.append(date4)\ndates.append(date5)\ndates.append(date6)\n\nfor i in dates:\n ref_date = datetime.datetime(i.year, i.month, i.day, selected_hour, 0, 0)\n time_difference = abs( (i-ref_date).total_seconds() )\n if (i &lt; ref_date):\n if time_difference &lt;= 15 * 60:\n print i\n else:\n if time_difference &lt;= 75 * 60:\n print i\n</code></pre>\n\n<p>Result is:</p>\n\n<pre><code>2012-09-10 11:45:00\n2012-09-10 13:15:00\n2011-05-11 13:15:00\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:43:44.733", "Id": "27951", "Score": "1", "body": "I read the question as selecting on the hour without depending on the date itself. It's unfortunate that all the examples used the same date." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:52:24.383", "Id": "27952", "Score": "0", "body": "Yes, you're possibly right. I understood it the other way because of the data. It would be nice if John Smith clarified it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T13:58:18.760", "Id": "27953", "Score": "0", "body": "@MarkRansom I made a change and now it works in the way you mentioned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T14:32:33.700", "Id": "27954", "Score": "0", "body": "Yes, that's much better. It still has a problem around midnight though - test with `selected_hour=0` and `23:59`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:37:10.797", "Id": "17566", "ParentId": "17564", "Score": "0" } }, { "body": "<p>If you want to ignore the date, then you could use <code>combine</code> to shift every date to some arbitrary base date. Then you can still use datetime inequalities to compare the times:</p>\n\n<pre><code>import datetime as dt\nselected_hour=12\ndate1 = dt.datetime(2011, 9, 10, 11, 46, 45)\ndate2 = dt.datetime(2012, 8, 10, 12, 46, 45)\ndate3 = dt.datetime(2012, 9, 11, 13, 47, 45)\ndate4 = dt.datetime(2012, 10, 10, 13, 06, 45)\ndates=[date1, date2, date3, date4]\n\nbase_date = dt.date(2000,1,1)\nbase_time = dt.time(selected_hour,0,0)\nbase = dt.datetime.combine(base_date, base_time)\nmin15 = dt.timedelta(minutes = 15)\nstart = base - min15\nend = base + 5*min15\n\nfor d in dates:\n if start &lt;= dt.datetime.combine(base_date, d.time()) &lt;= end:\n print(d)\n</code></pre>\n\n<p>yields</p>\n\n<pre><code>2011-09-10 11:46:45\n2012-08-10 12:46:45\n2012-10-10 13:06:45\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T04:23:14.333", "Id": "17567", "ParentId": "17564", "Score": "0" } } ]
{ "AcceptedAnswerId": "17565", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T01:37:45.080", "Id": "17564", "Score": "3", "Tags": [ "python" ], "Title": "filter date for a specific hour and minute" }
17564
<p>The following code is a simple random password generator that spits out a randomized password based on some input flags.</p> <pre><code>import string import random import argparse def gen_char(lower, upper, digit, special): _lower_letters = string.ascii_lowercase _upper_letters = string.ascii_uppercase _digits = string.digits _special = "!@#$%^&amp;*()" _rand = random.SystemRandom() _case = "" if lower: _case += _lower_letters if upper: _case += _upper_letters if digit: _case += _digits if special: _case += _special if _case: return _rand.choice(_case) else: return _rand.choice(_lower_letters+_upper_letters+_digits+_special) def main(): """ The following lines of code setup the command line flags that the program can accept. """ parser = argparse.ArgumentParser() parser.add_argument("length", type=int, help="length of password") parser.add_argument("--lower", "-l", help="Generates passwords with lower case letters", action="store_true") parser.add_argument("--upper", "-u", help="Generates passwords with upper case letters", action="store_true") parser.add_argument("--digit", "-d", help="Generates passwords with digits", action="store_true") parser.add_argument("--special", "-s", help="Generates passwords with special characters", action="store_true") args = parser.parse_args() """ The following lines of code calls upon the gen_char() function to generate the password. """ _pass = "" for x in range(args.length): _pass += gen_char(args.lower, args.upper, args.digit, args.special) print _pass main() </code></pre> <p>The code is in working condition. I'm looking for tips in terms of coding styles, readability and perhaps optimizations if any.</p> <p>If anyone is interested, the code can be found on <a href="https://github.com/Ayrx/Password_Generator" rel="noreferrer">github</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T17:44:35.063", "Id": "28035", "Score": "0", "body": "I don't think `_case` is a particularly good name here. Consider `alphabet` instead." } ]
[ { "body": "<p>Re-assembling the _case character list for each character is rather wasteful. I would get rid of the gen_char function.</p>\n\n<pre><code>import string\nimport random\nimport argparse\n\ndef main():\n\n \"\"\"\n\n The following lines of code setup the command line flags that the\n program can accept.\n\n \"\"\"\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"length\", type=int, help=\"length of password\")\n parser.add_argument(\"--lower\", \"-l\", \n help=\"Generates passwords with lower case letters\",\n action=\"store_true\")\n parser.add_argument(\"--upper\", \"-u\",\n help=\"Generates passwords with upper case letters\",\n action=\"store_true\")\n parser.add_argument(\"--digit\", \"-d\",\n help=\"Generates passwords with digits\",\n action=\"store_true\")\n parser.add_argument(\"--special\", \"-s\",\n help=\"Generates passwords with special characters\",\n action=\"store_true\")\n\n args = parser.parse_args()\n\n\n \"\"\"\n\n The following lines of code generate the password.\n\n \"\"\"\n\n _lower_letters = string.ascii_lowercase\n _upper_letters = string.ascii_uppercase\n _digits = string.digits\n _special = \"!@#$%^&amp;*()\"\n\n _case = \"\"\n\n if lower:\n _case += _lower_letters\n\n if upper:\n _case += _upper_letters\n\n if digit:\n _case += _digits\n\n if special:\n _case += _special\n\n if !_case:\n _lower_letters+_upper_letters+_digits+_special\n\n _rand = random.SystemRandom()\n\n _pass = \"\"\n\n for x in range(args.length):\n\n _pass += _rand.choice(_case)\n\n print _pass\n\nmain()\n</code></pre>\n\n<p>You could, perhaps, use a function to make the list the one time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:54:26.340", "Id": "28005", "Score": "0", "body": "Ahhh! Good point." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:49:43.193", "Id": "17595", "ParentId": "17594", "Score": "5" } }, { "body": "<p>In addition to what has been said about not calling <code>gen_char()</code> every iteration, you are prefixing your variable names with an underscore, which is the python standard for private variables - the issue here is that you are doing this inside a function definition - as these are local variables that will go out of scope and get garbage collected when the function ends, there really isn't much point. I would recommend just using normal variable names.</p>\n\n<p>I would also argue <code>gen_char()</code> could be improved by using default values:</p>\n\n<pre><code>def gen_char(lower=string.ascii_lowercase, upper=string.ascii_upercase,\n digit=string.digits, special=\"!@#$%^&amp;*()\"):\n rand = random.SystemRandom()\n return rand.choice(\"\".join(\n group for group in (lower, upper, digit, special) if group)\n</code></pre>\n\n<p>This makes it clear what the default is, makes it possible to change the character range used, and makes it easy to disable certain parts.</p>\n\n<p>It's noted that <code>str.join()</code> is preferable over repeated concatenation, and using it allows us to stop repeating ourself and say that if we get a value, use it.</p>\n\n<p>This would require changing your use of <code>argparse</code>, prehaps like so:</p>\n\n<pre><code>kwargs = {}\nif not args.lower:\n kwargs[\"lower\"] = False\n...\ngen_char(**kwargs)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T13:20:57.757", "Id": "17598", "ParentId": "17594", "Score": "5" } } ]
{ "AcceptedAnswerId": "17607", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:43:36.570", "Id": "17594", "Score": "5", "Tags": [ "python" ], "Title": "Code review for python password generator" }
17594
<p>Here is some code I wrote in Python / Numpy that I pretty much directly translated from MATLAB code. When I run the code in MATLAB on my machine, it takes roughly 17 seconds. When I run the code in Python / Numpy on my machine, it takes roughly 233 seconds. Am I not using Numpy effectively? Please look over my Python code to see if I'm using Numpy in a non effective manner. All this code is doing is fitting the parameter D (diffusion coefficient) in the heat equation to some synthetically generated data using MCMC method. </p> <pre><code>import numpy as np from numpy import * import pylab as py from pylab import * import math import time def heat(D,u0,q,tdim): xdim = np.size(u0) Z = np.zeros([xdim,tdim]) Z[:,0]=u0; for i in range(1,tdim): for j in range (1,xdim-1): Z[j,i]=Z[j,i-1]+ D*q*(Z[j-1,i-1]-2*Z[j,i-1]+Z[j+1,i-1]) return Z start_time = time.clock() L = 10 D = 0.5 s = 0.03 # magnitude of noise Tmax = 0.2 xdim = 25 tdim = 75 x = np.linspace(0,L,xdim) t = np.linspace(0,Tmax,tdim) dt = t[1]-t[0] dx = x[1]-x[0] q = dt/(dx**2) r1 = 0.75*L r2 = 0.8*L ################################################ ## check the stability criterion dt/(dx^2)&lt;.5 ## ################################################ # Define the actual initial temperature distribution u0 = np.zeros(xdim) for i in range(0,xdim): if(x[i]&gt;=r1 and x[i]&lt;=r2): u0[i] = 1 xDat = range(1,xdim-1) tDat = np.array([tdim]) nxDat = len(xDat) ntDat = 1 tfinal = tdim-1 # synthesize data Z = heat(D,u0,q,tdim) u = Z[xDat,tfinal] # matrix uDat = u + s*randn(nxDat) # MATLAB PLOTTING #figure(1);surf(x,t,Z); hold on; #if ntDat&gt;1, mesh(x(xDat),t(tDat),uDat); #else set(plot3(x(xDat),t(tDat)*ones(1,nxDat),uDat,'r-o'),'LineWidth',3); #end; hold off; drawnow #MCMC run N = 10000 m = 100 XD = 1.0 X = np.zeros(N) X[0] = XD Z = heat(XD,u0,q,tdim) u = Z[xDat,tfinal] oLLkd = sum(sum(-(u-uDat)**2))/(2*s**2) LL = np.zeros(N) LL[0] = oLLkd # random walk step size w = 0.1 for n in range (1,N): XDp = XD+w*(2*rand(1)-1) if XDp &gt; 0: Z = heat(XDp,u0,q,tdim) u = Z[xDat,tfinal] nLLkd = sum(sum( -(u-uDat)**2))/(2*s**2) alpha = exp((nLLkd-oLLkd)) if random() &lt; alpha: XD = XDp oLLkd = nLLkd CZ = Z X[n] = XD; LL[n] = oLLkd; print time.clock() - start_time, "seconds" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T13:52:34.893", "Id": "33900", "Score": "0", "body": "Not sure how this works in python, but could you run a kind of profile on the code to see which lines use most computation time?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T05:37:15.730", "Id": "47820", "Score": "1", "body": "I translated this back to Matlab, and ran it on Octave. With that double loop it was very slow, slower than numpy. My guess is that Matlab (probably a newer version) is compiling the loops. The kind of vectorization that classic Matlab required is no longer essential to fast code. Numpy and Octave still require thinking in terms of vector and matrix operations." } ]
[ { "body": "<p>In the <code>heat</code> function, simply vectorizing the inner loop, drops the time from 340 sec to 56 sec, a <strong>6x improvement</strong>. It starts by defining the first column of <code>Z</code>, and calculates the next column from that (modeling heat diffusion). </p>\n\n<pre><code>def heat(D,u0,q,tdim):\n xdim = np.size(u0)\n Z = np.zeros([xdim,tdim])\n Z[:,0]=u0;\n for i in range(1,tdim):\n #for j in range (1,xdim-1):\n # Z[j,i]=Z[j,i-1]+ D*q*(Z[j-1,i-1]-2*Z[j,i-1]+Z[j+1,i-1])\n J = np.arange(1, xdim-1)\n Z[J,i] = Z[J,i-1] + D*q*( Z[J-1,i-1] - 2*Z[J,i-1] + Z[J+1,i-1] )\n return Z\n</code></pre>\n\n<p>some added improvement (<strong>10x speedup</strong>) by streamlining the indexing</p>\n\n<pre><code> Z1 = Z[:,i-1]\n Z[j,i] = Z1[1:-1] + D*q* (Z1[:-2] - 2 * Z1[1:-1] + Z1[2:])\n</code></pre>\n\n<p>Better yet. This drops time to 7sec, a <strong>45x improvement</strong>. It constructs a matrix with 3 diagonals, and applies that repeatedly to the <code>u</code> vector (with a dot product). </p>\n\n<pre><code>def heat(D,u0,q,tdim):\n # drops time to 7sec\n N = np.size(u0)\n dq = D*q\n A = np.eye(N,N,0)+ dq*(np.eye(N,N,-1)+np.eye(N,N,1)-2*np.eye(N,N,0))\n Z = np.zeros([N,tdim])\n Z[:,0] = u0;\n # print u0.shape, A.shape, (A*u0).shape, np.dot(A,u0).shape\n for i in range(1,tdim):\n u0 = np.dot(A,u0)\n Z[:,i] = u0\n return Z\n</code></pre>\n\n<p>Based on further testing and reading, I think <code>np.dot(A,u0)</code> is using the fast <code>BLAS</code> code.</p>\n\n<p>For larger dimensions (here xdim is only 25), <code>scipy.sparse</code> can be used to make a more compact <code>A</code> matrix. For example, a sparse version of <code>A</code> can be produced with</p>\n\n<pre><code>sp.eye(N,N,0) + D * q * sp.diags([1, -2, 1], [-1, 0, 1], shape=(N, N))\n</code></pre>\n\n<p>But there isn't a speed advantage at this small size.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T20:13:19.037", "Id": "30101", "ParentId": "17702", "Score": "15" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T04:40:44.927", "Id": "17702", "Score": "6", "Tags": [ "python", "matlab", "numpy" ], "Title": "Python / Numpy running 15x slower than MATLAB - am I using Numpy effeciently?" }
17702
<p>I'm learning python and I want to model a <a href="http://en.wikipedia.org/wiki/Single-elimination_tournament" rel="noreferrer">single elimination tournament</a> like they use in athletic events like tennis, basketball, etc. The idea would be to insert some meaningful metrics to determine the winner. I've already got a database that I plan to connect to to get the metrics, but I am hoping to find a better way to "process" games in the tournament to move the winner to the next round, and eventually find the tournament winner.</p> <p><img src="https://i.stack.imgur.com/UOMVI.png" alt="16 team tournament"></p> <p>So far this is the best I have come up with, but it doesn't scale (at all easily) to 32, 64, 128 entries &amp; so-on. The "primary key" that I need to retain is the "seed id" (1-16, in this case), which matches the unique identifier in the database, so that I can pull the correct metrics for deciding which entry will win a matchup. Suggestions?</p> <pre><code>## this list represents the round 1 seeding order on the tournament sheet ## this doesnt easily scale to 32, 64, 128 entries teamlist = [1,16,8,9,5,12,4,13,6,11,3,14,7,10,2,15] #In a single elim tournament with a full field, # of games is # of teams-1 totalgames = len(teamlist) - 1 #Set defaults gameid = 0 roundid = 0 nextround = [] #simulate all of the games while gameid &lt; totalgames: if gameid in [8,12,14]: ##this is a manual decision tree, doesn't scale at all #if a new round begins, reset the list of the next round print "--- starting a new round of games ---" teamlist = nextround nextround = [] roundid = 0 #compare the 1st entry in the list to the 2nd entry in the list homeid = teamlist[roundid] awayid = teamlist[roundid + 1] #the winner of the match become the next entry in the nextround list #more realistic metrics could be substituted here, but ID can be used for this example if homeid &lt; awayid: nextround.append(homeid) print str(homeid) + " vs " + str(awayid) + ": The winner is " + str(homeid) else: nextround.append(awayid) print str(homeid) + " vs " + str(awayid) + ": The winner is " + str(awayid) #increase the gameid and roundid gameid += 1 roundid += 2 print "next round matchup list: " + str(nextround) print nextround </code></pre>
[]
[ { "body": "<p>You have two lines marked as \"doesn't scale\".</p>\n\n<p>The initial team list can be obtained from your database table of available teams (select of team details).</p>\n\n<p>The other \"problem line\", is</p>\n\n<pre><code> if gameid in [8,12,14]: ##this is a manual decision tree, doesn't scale at all\n</code></pre>\n\n<p>But that's easily avoided by noticing that the games in a round are always half the previous round, and the initial round is half the number of teams!</p>\n\n<p>In other words, you can do something like (if you include the initial round):</p>\n\n<pre><code>def NewRoundIds( teams_in_tournament ):\n round_ids = []\n game_id = 0\n games_in_next_round = len(teams_in_tournament)/2 #need to count the number of teams_in_tournament list\n while games_in_next_round &gt; 0:\n round_ids += [game_id]\n game_id += games_in_next_round\n games_in_next_round /= 2\n return round_ids\n\nnew_round_game_ids = NewRoundIds( teamlist )\n...\nif gameid in new_round_game_ids:\n # etc\n</code></pre>\n\n<p>== edit ==</p>\n\n<p>This puts it <em>well</em> outside the brief of the site, but it was interesting. The following I think does what you want, <code>generate_tournament(16)</code>. It could do with a bit of tidying up, and it's the sort of thing that will certainly benefit from docstrings and doctests, which I shall leave as a exercise.</p>\n\n<pre><code>import math\n\ndef tournament_round( no_of_teams , matchlist ):\n new_matches = []\n for team_or_match in matchlist:\n if type(team_or_match) == type([]):\n new_matches += [ tournament_round( no_of_teams, team_or_match ) ]\n else:\n new_matches += [ [ team_or_match, no_of_teams + 1 - team_or_match ] ]\n return new_matches\n\ndef flatten_list( matches ):\n teamlist = []\n for team_or_match in matches:\n if type(team_or_match) == type([]):\n teamlist += flatten_list( team_or_match )\n else:\n teamlist += [team_or_match]\n return teamlist\n\ndef generate_tournament( num ):\n num_rounds = math.log( num, 2 )\n if num_rounds != math.trunc( num_rounds ):\n raise ValueError( \"Number of teams must be a power of 2\" )\n teams = 1\n result = [1]\n while teams != num:\n teams *= 2\n result = tournament_round( teams, result )\n return flatten_list( result )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T14:39:34.257", "Id": "28227", "Score": "0", "body": "Thanks Glenn, excellent suggestions. I will give them a try. Do you have any good suggeestions on how to create the initial \"team list\" without typing it all out? Is there some kind of algorithm that we could identify that would follow the structure of a tourney so I could just insert the team ids? Notice they are not just numbered 1-16 down the lefthand side of the diagram." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T16:28:51.980", "Id": "28235", "Score": "0", "body": "That rather depends on what you meant by \"I've already got a database that I plan to connect to to get the metrics\" - it sounded like you have everything like that in your database. If you want a list of random numbers `teamlist = [i + 1 for i in range( teams_in_tournament )`, `random.shuffle( teamlist )`. Not sure what you mean by the algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T17:08:38.030", "Id": "28241", "Score": "0", "body": "So, the \"seed id\" (1 through 16) is the \"primary key\" referenced in the database, but not the \"structure\" of the tournament (in regards to 'who plays who'). I do not want a randlom list, either, as in the first round team 1 plays 16, 9v8, etc. In the second round, the winner of team 1/16 needs to play the winner of 9/8, and so on... Make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T22:36:05.667", "Id": "28259", "Score": "0", "body": "It does. Answer edited." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T03:04:57.457", "Id": "28265", "Score": "1", "body": "Wow...That's amazing! I knew there had to be a better way, and you found it. I really appreciate you putting so much thought into your answer. I definitely learned a lot!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T09:34:22.337", "Id": "17713", "ParentId": "17703", "Score": "3" } } ]
{ "AcceptedAnswerId": "17713", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T04:42:51.203", "Id": "17703", "Score": "7", "Tags": [ "python" ], "Title": "Using Python to model a single elimination tournament" }
17703
<p>I have a string containing around 1 million sets of float/int coords, i.e.:</p> <pre><code> '5.06433685685, 0.32574574576, 2.3467345584, 1,,,' </code></pre> <p>They are all in one large string and only the first 3 values are used. The are separated by 3 commas. The code i'm using right now to read through them and assign them to a list is below:</p> <pre><code> def getValues(s): output = [] while s: v1, v2, v3, _, _, _, s = s.split(',', 6) output.append("%s %s %s" % (v1.strip(), v2.strip(), v3.strip())) return output coords = getValues(tempString) </code></pre> <p>The end results need to be a list of the three floats in each set separated by a space, i.e.: </p> <pre><code> ['5.06433685685 0.32574574576 2.3467345584'] </code></pre> <p>The code I defined above does work for what I want, it just takes much longer than I would like. Does anyone have any opinions or ways I could speed it up? I would like to stay away from external modules/modules i have to download.</p> <p>Btw I don't think it's my computer slowing it down, 32gb ram and 350mb/s write speed, the program that creates the original string does it in about 20 secs, while my code above gets that same string, extracts the 3 values in around 30mins to an hour.</p> <p>P.s. Using python 2.6 if it matters</p> <p><strong>EDIT:</strong> Tried replacing the while loop with a for loop as I did some reading and it stated for loops were faster, it might have shaved off an extra minute but still slow, new code:</p> <pre><code> def getValues(s, ids): output = [] for x in range(len(ids)): v1, v2, v3, _, _, _, s = s.split(',', 6) output.append("%s %s %s" % (v1.strip(), v2.strip(), v3.strip())) return output </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T02:48:05.637", "Id": "28294", "Score": "0", "body": "Could a map perform faster then a for loop? What about multiprocessing.pool.map? Could anyone provide an example that I could apply the above too?" } ]
[ { "body": "<p>How about this?</p>\n\n<pre><code>import random\n\ndef build_string(n):\n s = []\n for i in range(n):\n for j in range(3):\n s.append(random.random())\n for j in range(3):\n s.append(random.randint(0, 10))\n s = ','.join(map(str, s))+','\n return s\n\ndef old_getvalues(s):\n output = []\n while s:\n v1, v2, v3, _, _, _, s = s.split(',', 6)\n output.append(\"%s %s %s\" % (v1.strip(), v2.strip(), v3.strip())) \n return output\n\ndef new_getvalues(s):\n split = s.split(\",\")\n while not split[-1].strip():\n del split[-1]\n outputs = [' '.join(split[6*i:6*i+3]) for i in range(len(split)//6)]\n return outputs\n</code></pre>\n\n<p>I get (using 2.7 here, but I get similar times on 2.6):</p>\n\n<pre><code>In [13]: s = build_string(3)\n\nIn [14]: s\nOut[14]: '0.872836834427,0.151510882542,0.746899728365,1,5,2,0.908901266489,0.92617820935,0.686859068595,1,0,1,0.0773422174111,0.874219587245,0.473976008481,7,9,2,'\n\nIn [15]: old_getvalues(s)\nOut[15]: \n['0.872836834427 0.151510882542 0.746899728365',\n '0.908901266489 0.92617820935 0.686859068595',\n '0.0773422174111 0.874219587245 0.473976008481']\n\nIn [16]: new_getvalues(s)\nOut[16]: \n['0.872836834427 0.151510882542 0.746899728365',\n '0.908901266489 0.92617820935 0.686859068595',\n '0.0773422174111 0.874219587245 0.473976008481']\n\nIn [17]: s = build_string(10001)\n\nIn [18]: old_getvalues(s) == new_getvalues(s)\nOut[18]: True\n</code></pre>\n\n<p>and times of</p>\n\n<pre><code>1000 old 0.00571918487549 new 0.00116586685181\n2000 old 0.0169730186462 new 0.00192594528198\n4000 old 0.0541620254517 new 0.00387787818909\n8000 old 0.240834951401 new 0.00893807411194\n16000 old 3.2578599453 new 0.0209548473358\n32000 old 16.0219330788 new 0.0443530082703\n</code></pre>\n\n<p>at which point I got bored waiting for the original code to finish. And it seems to work nicely on your full case, taking about 2s on my notebook:</p>\n\n<pre><code>In [32]: time s = build_string(10**6)\nCPU times: user 13.05 s, sys: 0.43 s, total: 13.48 s\nWall time: 13.66 s\n\nIn [33]: len(s), s.count(',')\nOut[33]: (51271534, 6000000)\n\nIn [34]: s[:200]\nOut[34]: '0.442266619899,0.54340551778,0.0973845441797,6,9,9,0.849183222984,0.557159614938,0.95352706538,10,7,2,0.658923388772,0.148814178924,0.553198811754,1,0,8,0.662939105945,0.343116945991,0.384742018719,9,'\n\nIn [35]: time z = new_getvalues(s)\nCPU times: user 1.14 s, sys: 0.75 s, total: 1.89 s\nWall time: 1.89 s\n\nIn [36]: len(z)\nOut[36]: 1000000\n\nIn [37]: z[:3]\nOut[37]: \n['0.442266619899 0.54340551778 0.0973845441797',\n '0.849183222984 0.557159614938 0.95352706538',\n '0.658923388772 0.148814178924 0.553198811754']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T03:55:17.757", "Id": "28295", "Score": "0", "body": "Hm This looks very promising thanks for the respongs, I am having one thing that is a bit odd, every once in a while i get a result like this: '-5.46000003815 \\n\\t\\t\\t\\t\\t\\t\\t\\t6.95499992371 -0.194999933243'\nWhich is why i originally had the strip command in my above code, i see you have it in this too, any idea why it's not stripping?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T03:58:59.930", "Id": "28296", "Score": "1", "body": "`.strip()` only affects the start and the end of a line, not anything in the middle. I only put the `.strip()` in as a safety measure. If you want to get rid of that whitespace (I'm assuming you've read an entire file in), then either `.split()` the string or `.strip()` the individual elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T04:06:59.487", "Id": "28297", "Score": "0", "body": "ah ok I'm pretty new to python and wasn't aware of that for the .strip(), they are apparently already in my string, possibly that way from the source, any ideas on how to include a way to remove the newlines and tabs from within the script you provided, i.e without creating to much more inefficiency?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T04:14:03.893", "Id": "28298", "Score": "1", "body": "Probably the fastest would be to add `s = ''.join(s.split())` at the start of `new_getvalues()` -- that will split the string by whitespace and then join it back together. That might seem like it's doing more work, but it's actually faster than `.strip()`-ping each of the elements, because there's only one call to a builtin function. The secret to writing fast Python code is to push as much of the work into the library C code as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T04:40:16.467", "Id": "28299", "Score": "0", "body": "You sir are truly a gentlemen and a scholar, I can't even believe how much faster it is, seriously (Its a sequence of frames, the last frame = the most data) before i was attempting at half way in the sequence, about 50,000 coords and it was taking 20-30mins, now i did the last frame, 1.5 million coords and it took barely 30 secs! I never realized how much more efficient C code is, very eye opening thank you so much for the time and help, you sir have given me hope for this world :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T04:42:59.850", "Id": "28300", "Score": "0", "body": "Just to clarify, I think the bottleneck in your original code was actually the recreation of the string `s` each time through the loop, which is why it showed such superlinear growth with n. But I'm glad to have helped." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T03:39:35.980", "Id": "17774", "ParentId": "17768", "Score": "1" } } ]
{ "AcceptedAnswerId": "17774", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T22:54:22.760", "Id": "17768", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "Python Optimizing/Speeding up the retrieval of values in a large string" }
17768
<p>I have a list of dictionaries, with keys 'a', 'n', 'o', 'u'. Is there a way to speed up this calculation, for instance with <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a>? There are tens of thousands of items in the list.</p> <p>The data is drawn from a database, so I must live with that it's in the form of a list of dictionaries originally.</p> <pre><code>x = n = o = u = 0 for entry in indata: x += (entry['a']) * entry['n'] # n - number of data points n += entry['n'] o += entry['o'] u += entry['u'] loops += 1 average = int(round(x / n)), n, o, u </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:40:02.320", "Id": "28349", "Score": "0", "body": "what are you trying to calculate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:44:34.283", "Id": "28350", "Score": "0", "body": "@OvedD, an average of all 'a' values and a bunch of sums for the others." } ]
[ { "body": "<p>I'm not sure if there really is a better way to do this. The best I could come up with is:</p>\n\n<pre><code>import itertools\nfrom collections import Counter\n\ndef convDict(inDict):\n inDict['a'] = inDict['a'] * inDict['n']\n return Counter(inDict)\n\naverage = sum(itertools.imap(convDict, inData), Counter())\naverage['a'] = average['a'] / average['n']\n</code></pre>\n\n<p>But I'm still not sure if that is better than what you originally had.</p>\n\n<p><code>Counter</code> is a subclass of <code>dict</code>. You can get items from them the same way you get items from a normal dict. One of the most important differences is that the <code>Counter</code> will not raise an Exception if you try to select a non-existant item, it will instead return 0.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:02:51.863", "Id": "28351", "Score": "0", "body": "Interesting but I don't see how I can replace my code with that. +1 though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:06:28.850", "Id": "28352", "Score": "0", "body": "I realized after posting this that you wanted to do some multiplication before summing. Ill look into that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:16:33.677", "Id": "28353", "Score": "0", "body": "Wouldn't that require to access the full list twice instead of once? In that case, it must be slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:17:39.730", "Id": "28354", "Score": "0", "body": "@AmigableClarkKant Yeah, I just got done editing the question to state that. It is probably slower than what you already have. I'm not sure how much better Counter is (if any) than manually summing." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:59:24.223", "Id": "17811", "ParentId": "17810", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:13:17.540", "Id": "17810", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "Optimization of average calculation" }
17810
<p>Title: Identifying equivalent lists</p> <p>I am using lists as keys, and therefore want to identify equivalent ones.</p> <p>For example,</p> <pre><code>[0, 2, 2, 1, 1, 2] [4, 0, 0, 1, 1, 0] </code></pre> <p>are 'equivalent' in my book. I 'equivalify' the list by checking the list value with the highest count, and set that to 0, then the next highest count to 1, and so on and so forth. It's done with this code below, which does the job properly but is fairly slow - and I am wondering if there is a way of doing the same job yet I haven't seen it yet.</p> <pre><code>for key in preliminary_key_list: key = list(key) # convert from immutable tuple to mutable list i = 0 translation = {} counts = [[j, key.count(j)] for j in set(key)] counts_right = [j[1] for j in counts] for count in set(key): translation[counts[counts_right.index(max(counts_right))][0]] = i counts_right[counts_right.index(max(counts_right))] = 0 i += 1 for i in range(len(key)): key[i] = translation[key[i]] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T14:51:48.873", "Id": "28469", "Score": "0", "body": "Could it be the case that there are multiple values with the same count? E.g. `[0, 1, 1, 2, 2, 3, 3, 3]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T07:21:13.493", "Id": "28509", "Score": "0", "body": "@DSM Yes it happens. However, to optimise that would be a smaller optimisation than what I'm currently looking for, which is 'how to speed up all key translations'. I will come back to this one after I've optimised the main process" } ]
[ { "body": "<p>You can do things slightly differently - instead of manually sorting, you can use the standard library sort() function. Below I've modified things slightly for convenience, but using it, <code>timeit</code> originally gave 16.3 seconds for 10^6 iterations and now gives 10.8 seconds.</p>\n\n<pre><code>def equivalify( preliminary_key_list ):\n ret = []\n for key in preliminary_key_list:\n key = list(key) # convert from immutable tuple to mutable list\n\n translation = {}\n counts = [[key.count(j), j] for j in set(key)]\n counts.sort( reverse = True )\n for idx, ( cnt, val ) in enumerate( counts ):\n translation[ val ] = idx\n for i,k in enumerate( key ):\n key[i] = translation[ k ]\n ret += [key]\n return ret\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T08:38:59.313", "Id": "17867", "ParentId": "17859", "Score": "0" } }, { "body": "<pre><code>for key in preliminary_key_list:\n key = list(key) # convert from immutable tuple to mutable list\n</code></pre>\n\n<p>You don't need to do this. Rather then creating a modifiable list, just use the tuple and construct a new tuple at the end</p>\n\n<pre><code> i = 0\n translation = {}\n counts = [[j, key.count(j)] for j in set(key)]\n</code></pre>\n\n<p>This should be a list of tuples, not a list of lists. </p>\n\n<pre><code> counts_right = [j[1] for j in counts]\n\n for count in set(key): \n</code></pre>\n\n<p>Use <code>for i, count in enumerate(set(key)):</code> to avoid having to manage i yourself.</p>\n\n<p>You use <code>set(key)</code> twice, which will force python to do work twice. Also, there is no guarantee you'll get the same order both times. </p>\n\n<pre><code> translation[counts[counts_right.index(max(counts_right))][0]] = i\n counts_right[counts_right.index(max(counts_right))] = 0\n</code></pre>\n\n<p>These lines are really expensive. <code>max</code> will scan the whole list checking for the highest value. <code>.index</code> will then rescan the list to find the index for the value. \nThen you do the whole thing over again on the next line!</p>\n\n<p>You'd do far better as @GlenRogers suggests to sort by the counts. </p>\n\n<pre><code> i += 1\n\n for i in range(len(key)):\n key[i] = translation[key[i]]\n</code></pre>\n\n<p>Here using a comprehension would be better (I think):</p>\n\n<pre><code> key = tuple(translation[item] for item in key)\n</code></pre>\n\n<p>Here is how I'd write the code:</p>\n\n<pre><code>ret = []\nfor key in preliminary_key_list:\n counts = sorted(set(key), key = lambda k: -key.count(k) )\n translation = { val: idx for idx, val in enumerate(counts) }\n ret.append([translation[k] for k in key])\nreturn ret\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T11:31:47.447", "Id": "28519", "Score": "0", "body": "It's certainly a lot faster and it's concise as well. Makes me wonder how you get to that level where you know how to do it. Your explanation was good too. Thanks Winston" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T12:24:54.287", "Id": "17880", "ParentId": "17859", "Score": "3" } } ]
{ "AcceptedAnswerId": "17880", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T02:28:51.793", "Id": "17859", "Score": "2", "Tags": [ "python" ], "Title": "Identifying equivalent lists" }
17859
<p>I know there are other Python wiki API classes out there. I'm writing this one because I don't need all the bells and whistles, no edits, no talks, etc. I just need to be able to search for titles and get the wiki markup.</p> <p>Any advice or suggestions or comments or a review or anything really.</p> <pre><code># -*- coding: utf-8 -*- import urllib2 import re import time import sys from urllib import quote_plus, _is_unicode try: import json except: import simplejson as json def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) class Wiki: def __init__(self, api=None): if api == None: self.api = "http://en.wikipedia.org/w/api.php" else: self.api = api return """A HTTP Request""" def downloadFile(self, URL=None): """ URL - The URL to fetch """ opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] responce = opener.open(URL) data = responce.read() responce.close() return data.decode(encoding='UTF-8',errors='strict') """Search the wiki for titles""" def search(self, searchString): results = [] if (searchString != u""): encoded_searchString = searchString if isinstance(encoded_searchString, unicode): encoded_searchString = searchString.encode('utf-8') url = self.api + "?action=query&amp;list=search&amp;format=json&amp;srlimit=10&amp;srsearch=" + urllib2.quote(encoded_searchString) rawData = self.downloadFile(url) object = json.loads(rawData) if object: if 'query' in object: for item in object['query']['search']: wikiTitle = item['title'] if isinstance(wikiTitle, str): wikiTitle = wikiTitle.decode(encoding='UTF-8',errors='strict') results.append(wikiTitle) return results """Search for the top wiki title""" def searchTop(self, searchString): results = self.search(searchString) if len(results) &gt; 0: return results[0] else: return u"" """Get the raw markup for a title""" def getPage(self, title): # Do the best we can to get a valid wiki title wikiTitle = self.searchTop(title) if (wikiTitle != u""): encoded_title = wikiTitle if isinstance(encoded_title, unicode): encoded_title = title.encode('utf-8') url = self.api + "?action=query&amp;prop=revisions&amp;format=json&amp;rvprop=content&amp;rvlimit=1&amp;titles=" + urllib2.quote(encoded_title) rawData = self.downloadFile(url) object = json.loads(rawData) for k, v in object['query']['pages'].items(): if 'revisions' in v: return v['revisions'][0]['*'] return u"" </code></pre>
[]
[ { "body": "<p>An obvious one that jumps out at me is this:</p>\n\n<pre><code>class Wiki:\n def __init__(self, api=None):\n if api == None:\n self.api = \"http://en.wikipedia.org/w/api.php\"\n else:\n self.api = api\n return\n</code></pre>\n\n<p>Can be simplified to this:</p>\n\n<pre><code>class Wiki:\n def __init__(self, api=\"http://en.wikipedia.org/w/api.php\"):\n self.api = api\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T10:23:57.390", "Id": "17872", "ParentId": "17861", "Score": "3" } } ]
{ "AcceptedAnswerId": "17961", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T04:15:46.467", "Id": "17861", "Score": "2", "Tags": [ "python", "beginner", "classes" ], "Title": "Wiki API getter" }
17861
<p>I wrote this function to read Las file and save a shapefile. The function creates a shapefile with 8 fields. What I wish insert a parse element in the function in order to select the fields I wish to save <code>LAS2SHP(inFile, outFile=None, parse=None)</code>. If <code>parse=None</code> all fields are saved. If <code>parse="irn"</code> the fields <code>intensity</code>, <code>return_number</code>, and <code>number_of_returns</code> are saved, following the legend:</p> <pre><code>"i": p.intensity, "r": p.return_number, "n": p.number_of_returns, "s": p.scan_direction, "e": p.flightline_edge, "c": p.classification, "a": p.scan_angle, </code></pre> <p>I wrote a solution <code>if....ifelse....else</code> really code consuming (and not elegant). Thanks for all helps and suggestions for saving code.</p> <p>Here is the original function in Python:</p> <pre><code>import shapefile from liblas import file as lasfile def LAS2SHP(inFile,outFile=None): w = shapefile.Writer(shapefile.POINT) w.field('Z','C','10') w.field('Intensity','C','10') w.field('Return','C','10') w.field('NumberRet','C','10') w.field('ScanDir','C','10') w.field('FlightEdge','C','10') w.field('Class','C','10') w.field('ScanAngle','C','10') for p in lasfile.File(inFile,None,'r'): w.point(p.x,p.y) w.record(float(p.z),float(p.intensity),float(p.return_number),float(p.number_of_returns),float(p.scan_direction),float(p.flightline_edge),float(p.classification),float(p.scan_angle)) if outFile == None: inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile)) inFile_name = os.path.splitext(inFile_name_ext)[0] w.save("{0}\\{1}.shp".format(inFile_path,inFile_name)) else: w.save(outFile) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T18:33:03.240", "Id": "28546", "Score": "0", "body": "If you'd post the code of the function, I could help you convert the if/elifs/else to a dictionary." } ]
[ { "body": "<p>A possible dictionary based solution:</p>\n\n<pre><code>import os.path\n\nimport shapefile\nfrom liblas import file as lasfile\n\n\n# map fields representing characters to field name and attribute\nFIELDS = {\n 'i': ('Intensity', 'intensity'),\n 'r': ('Return', 'return_number'),\n 'n': ('NumberRet', 'number_of_returns'),\n 's': ('ScanDir', 'scan_direction'),\n 'e': ('FlightEdge', 'flightline_edge'),\n 'c': ('Class', 'classification'),\n 'a': ('ScanAngle', 'scan_angle'),\n}\n\n# assuming that field order is important define it explicitly, otherwise it\n# could simply be DEFAULT_PARSE = FIELDS.keys()\nDEFAULT_PARSE = 'irnseca'\n\n\ndef enhanced_LAS2SHP(inFile, outFile=None, parse=DEFAULT_PARSE):\n w = shapefile.Writer(shapefile.POINT)\n # add 'Z' field not present in fields map\n w.field('Z', 'C', '10')\n # initialise list of desired record attributes\n attributes = []\n # add mapped 'shapefile' fields and desired attributes to list\n for f in parse:\n field, attr = FIELDS[f]\n w.field(field_name, 'C', '10')\n attributes.append(attr)\n # create record from attributes in list of desired attributes\n for p in lasfile.File(inFile, None, 'r'):\n w.point(p.x, p.y)\n record_args = [float(p.z)]\n record_args += (float(getattr(p, attr)) for attr in attributes)\n w.record(*record_args)\n # if not output filename was supplied derive one from input filename\n if outFile is None:\n inFile_path, inFile_name_ext = os.path.split(os.path.abspath(inFile))\n inFile_name, _ = os.path.splitext(inFile_name_ext)\n outFile = os.path.join(inFile_path, '{}.shp'.format(inFile_name))\n # save records to 'shapefile'\n w.save(outFile)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T20:38:26.960", "Id": "17933", "ParentId": "17924", "Score": "1" } } ]
{ "AcceptedAnswerId": "17933", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T17:17:39.417", "Id": "17924", "Score": "2", "Tags": [ "python", "optimization" ], "Title": "Python: improve in elegant way (code saving) a function in order to avoid several statements" }
17924
<p>What can I do to improve performance of this function? So far I've changed stuff as local as possible and made a <code>break</code> if all possible surrounding tiles have been found. Also I use a separate variable to track the length of a list instead of <code>len()</code>.</p> <p>The usage of this is to find surrounding tiles for all tiles.</p> <pre><code>def getsurroundings(tiles): for t in tiles: currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2) check = currentrect.colliderect surroundings = t.surroundings append = t.surroundings.append surroundingscount = t.surroundingscount for t2 in tiles: if check(t2.rect) and not t == t2 and not t2 in surroundings: append(t2) t2.surroundings.append(t) surroundingscount+=1 t2.surroundingscount+=1 if surroundingscount == 8: break return tiles </code></pre> <p>Here's the code without localisations which might be easier to read:</p> <pre><code>def getsurroundings(tiles): for t in tiles: currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2) for t2 in tiles: if currentrect.colliderect(t2.rect) and not t == t2 and not t2 in t.surroundings: t.surroundings.append(t2) t2.surroundings.append(t) t.surroundingscount+=1 t2.surroundingscount+=1 if t.surroundingscount == 8: break return tiles </code></pre>
[]
[ { "body": "<p>What about this?<br>\nI added a second list, so you only iterate over combinations you didn't already check.</p>\n\n<p>By the way, you should code with spaces, not with tabs.</p>\n\n<pre><code>def getsurroundings(tiles):\n tiles2 = tiles[:]\n for t in tiles:\n currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)\n check = currentrect.colliderect\n surroundings = t.surroundings\n append = t.surroundings.append\n surroundingscount = t.surroundingscount\n tiles2.pop(0)\n for t2 in tiles2:\n if check(t2.rect) and not t == t2 and not t2 in surroundings:\n append(t2)\n t2.surroundings.append(t)\n surroundingscount+=1\n t2.surroundingscount+=1\n if surroundingscount == 8:\n break\n return tiles\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T08:08:30.600", "Id": "28562", "Score": "0", "body": "But I like tabs D:" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T18:24:11.767", "Id": "17927", "ParentId": "17925", "Score": "0" } } ]
{ "AcceptedAnswerId": "17946", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T17:58:58.923", "Id": "17925", "Score": "2", "Tags": [ "python", "performance" ], "Title": "Finding surrounding tiles for all tiles" }
17925
<p>I am using the Python module <code>urllib3</code>. It occurs to me that there is a better way to design a good class when I rebuild my last site crawler.</p> <pre><code>class Global: host = 'http://xxx.org/' proxy=True proxyHost='http://127.0.0.1:8087/' opts=AttrDict( method='GET', headers={'Host':'xxxx.org', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language':'en-us;q=0.5,en;q=0.3', 'Accept-Encoding':'gzip, deflate', 'Connection':'keep-alive', 'Cookie':'xxxxxxx', 'Cache-Control':'max-age=0' }, assert_same_host=False ) def getPool(self,proxy=None): if proxy is None: proxy = self.proxy if(self.proxy): http_pool = urllib3.proxy_from_url(self.proxyHost) else: http_pool = urllib3.connection_from_url(self.host) return http_pool class Conn: def __init__(self, proxy): self.proxy= proxy self.pool = Global().getPool(self.proxy) def swith(self): self.pool = Global().getPool(not self.proxy) def get(url, opts=Global.opts): try: self.pool.urlopen( method=opts.method, url= url, headers= opts.headers, assert_same_host=opts.assert_same_host ) except TimeoutError, e: print() except MaxRetryError, e: # .. </code></pre> <p>I try to make class contains all global configs and data for others to call, just like I do in JavaScript. But, are these classes too tightly coupled? Should I just merge them together?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T05:28:23.103", "Id": "28686", "Score": "0", "body": "I think that those two are really parts of the same class. And should be combined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T05:32:31.560", "Id": "28687", "Score": "0", "body": "Does anyone need access to this stuff besides `Conn`? If not, it probably belongs in `Conn`. If you're worried about creating a separate copy of all of these constants in every `Conn` instance, you can make them class variables instance of instance variables. (And you may want to make `getPool` a `@classmethod`, too.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T06:00:29.350", "Id": "28688", "Score": "0", "body": "Actually I just need change configs and grab rules for every specifical site, merge the two class together means I should create a lot of different Conns and make code lager.I just wonder is it deserved?" } ]
[ { "body": "<h3>Class design</h3>\n\n<p>A good class in general is one that corresponds to an <em>Abstract Data Type</em>,\nwhich is a collection of data and operations that work on that data.\nA good ADT should have a single, clear responsibility.</p>\n\n<p>The <code>Global</code> class is not a good ADT:</p>\n\n<ul>\n<li>It does two unrelated things:\n<ul>\n<li>Contain configuration information</li>\n<li>Manage a proxy pool</li>\n</ul></li>\n<li>Possibly as a consequence of the previous point, it is poorly named</li>\n</ul>\n\n<p>It would be better to split this class into two:</p>\n\n<ul>\n<li><code>Configuration</code> or <code>Config</code>: contain configuration information</li>\n<li><code>ProxyPoolManager</code>: manage a proxy pool</li>\n</ul>\n\n<p>Note that <code>ProxyPoolManager</code> should not reference <code>Configuration</code> directly:\nit will be best to pass to it the <code>proxyHost</code> and <code>proxy</code> as constructor parameters.</p>\n\n<p>As the poorly named <code>Conn</code> class already does half of the proxy pool management,\nit would be better to rename it to <code>ProxyPoolManager</code> and move <code>getPool</code> method into it and rename <code>Global</code> to <code>Configuration</code>.</p>\n\n<h3>Coding style</h3>\n\n<p>You have several coding style violations, not conforming to <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>:</p>\n\n<ul>\n<li>Use spaces around <code>=</code> in variable assignments, for example:\n<ul>\n<li><code>proxy = True</code> instead of <code>proxy=True</code></li>\n<li><code>opts = AttrDict(...)</code> instead of <code>opts=AttrDict(...)</code></li>\n</ul></li>\n<li>No need to put parentheses in <code>if(self.proxy):</code></li>\n<li>There should be one blank line in front of method definitions of a class: put a blank line in front of <code>get</code> and <code>switch</code> methods in the <code>Conn</code> class</li>\n<li>You mistyped <code>switch</code> as <code>swith</code></li>\n</ul>\n\n<h3>Other issues</h3>\n\n<p>This code doesn't compile:</p>\n\n<blockquote>\n<pre><code>class Conn:\n def get(url, opts=Global.opts):\n try:\n self.pool.urlopen(...)\n</code></pre>\n</blockquote>\n\n<p>Because it makes a reference to <code>self</code> which was not passed in as method parameter.</p>\n\n<hr>\n\n<p>This is a bit hard to understand,\nbecause of reusing the name \"proxy\" both as method parameter and as attribute:</p>\n\n<blockquote>\n<pre><code>def getPool(self,proxy=None):\n if proxy is None:\n proxy = self.proxy\n if(self.proxy):\n http_pool = urllib3.proxy_from_url(self.proxyHost)\n else:\n http_pool = urllib3.connection_from_url(self.host)\n return http_pool\n</code></pre>\n</blockquote>\n\n<p>The purpose of this method would be more clear if you used a different name for the method parameter.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T09:50:13.377", "Id": "74256", "ParentId": "17993", "Score": "6" } } ]
{ "AcceptedAnswerId": "74256", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T04:57:12.143", "Id": "17993", "Score": "2", "Tags": [ "python", "object-oriented", "http" ], "Title": "Two Python classes for a web crawler" }
17993
<p>How could I improve this code to make it shorter and more functional?</p> <pre><code>#!usr/bin/python import time integer = 0 print("The current integer is set at " + str(integer) + ".") print("\n") time.sleep(2) prompt = raw_input("Would you like to change the integer? (Y/N) ") print("\n") if prompt == 'y': integer = int(raw_input("Insert the new integer here: ")) print("\n") print("You have changed the integer to " + str(integer) + ".") print("\n") print("\n") time.sleep(1) print("1. Add / 2. Subtract / 3. Multiply / 4. Divide") print("\n") new_int = raw_input("What would you like to do with your new integer? (Choose a number) ") print("\n") if new_int == '1': added_int = int(raw_input("What number would you like to add to your integer (" + str(integer) + ") by?")) outcome1 = integer + added_int print("\n") print("The sum of " + str(integer) + " + " + str(added_int) + " is " + str(outcome1)) if new_int == '2': subtracted_int = int(raw_input("What number would you like to subtract your integer (" + str(integer) + ") by?")) outcome2 = integer - subtracted_int print("\n") print("The difference of " + str(integer) + " - " + str(subtracted_int) + " is " + str(outcome2)) if new_int == '3': multiplied_int = int(raw_input("What number would you like to multiply your integer (" + str(integer) + ") by?")) outcome3 = integer * multiplied_int print("\n") print("The product of " + str(integer) + " x " + str(multiplied_int) + " is " + str(outcome3)) if new_int == '4': divided_int = int(raw_input("What number would you like to divide your integer (" + str(integer) + ") by?")) outcome4 = integer / divided_int print("\n") print("The quotient of " + str(integer) + " / " + str(divided_int) + " is " + str(outcome4)) elif prompt == "n": print("The integer will stay the same.") time.sleep(2) print("Press any key to exit...") else: print("Invalid input.") raw_input() </code></pre>
[]
[ { "body": "<p>How about something like this?</p>\n\n<pre><code>import time\n\ndef add_num(x):\n added_int = int(raw_input(\"What number would you like to add to your integer (%s) by?\" % x))\n outcome = x + added_int\n print(\"\\nThe sum of %s + %s is %s\" % (x, added_int, outcome))\n return outcome\n\ndef sub_num(x):\n sub_int = int(raw_input(\"What number would you like to subtract to your integer (%s) by?\" % x))\n outcome = x - sub_int\n print(\"\\nThe subtract of %s - %s is %s\" % (x, added_int, outcome))\n return outcome\n\ndef mul_num(x):\n mul_int = int(raw_input(\"What number would you like to multiply your integer (%s) by?\" % x))\n outcome = x * mul_int\n print(\"\\nThe multiplication of %s * %s is %s\" % (x, added_int, outcome))\n return outcome\n\ndef div_num(x):\n div_num = int(raw_input(\"What number would you like to divide your integer (%s) by?\" % x))\n outcome = x / float(div_num)\n print(\"\\nThe divider of %s / %s is %s\" % (x, added_int, outcome))\n return outcome\n\ndef main():\n op_map = {\"1\":add_num, \"2\":sub_num, \"3\":mul_num, \"4\":div_num}\n number = 0\n print(\"The current integer is set at %s .\" % number)\n while True:\n prompt = raw_input(\"Would you like to change the number? (Y/N)\").lower()\n if prompt == \"y\":\n number = int(raw_input(\"Insert the new integer here: \"))\n print(\"\\nYou have changed the integer to %s .\\n\\n\" % number)\n time.sleep(1)\n print(\"1. Add / 2. Subtract / 3. Multiply / 4. Divide\\n\")\n\n op = raw_input(\"What would you like to do with your new integer? (Choose a number) \\n\")\n if op is not None:\n operation = op_map.get(op)\n number = operation(number)\n\n elif prompt == \"n\":\n print(\"The integer will stay the same.\")\n time.sleep(2)\n raw_input(\"Press enter key to exit...\")\n break\n else:\n print(\"Invalid response\")\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-29T12:37:20.373", "Id": "28741", "Score": "0", "body": "You shouldn't define a function `div_num()` and then inside it use a variable also called `div_num`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-29T20:24:42.240", "Id": "28775", "Score": "0", "body": "@Matt eh good spot but really? function local namespace rarely matters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-29T22:28:29.303", "Id": "28783", "Score": "3", "body": "It makes the code harder to understand if you use the same name for two different things like that. In general it is bad practice." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T18:48:17.997", "Id": "17998", "ParentId": "17996", "Score": "1" } }, { "body": "<p>@Jackob wrote a better solution, but I can still see much duplication, here you can see a DRY version using higher order functions:</p>\n\n<pre><code>def user_interface_operation(start, operation):\n b = int(raw_input(\"What is x in {} {} x ?\".format(start, operation.__name__)))\n outcome = operation(start, b)\n print(\"The result is {}\".format(outcome))\n return outcome\n\nadd_num = lambda start: user_interface_operation(start, op.add)\nsub_num = lambda start: user_interface_operation(start, op.sub)\nmul_num = lambda start: user_interface_operation(start, op.mul)\ndiv_num = lambda start: user_interface_operation(start, op.div)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-24T13:06:13.313", "Id": "87846", "ParentId": "17996", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T18:12:31.087", "Id": "17996", "Score": "4", "Tags": [ "python", "calculator" ], "Title": "Performing calculations with updated integer" }
17996
<p>The basic idea here is that I want to measure the number of seconds between two python datetime objects. However, I only want to count hours between 8:00 and 17:00, as well as skipping weekends (saturday and sunday). This works, but I wondered if anyone had clever ideas to make it cleaner.</p> <pre><code>START_HOUR = 8 STOP_HOUR = 17 KEEP = (STOP_HOUR - START_HOUR)/24.0 def seconds_between(a, b): weekend_seconds = 0 current = a while current &lt; b: current += timedelta(days = 1) if current.weekday() in (5,6): weekend_seconds += 24*60*60*KEEP a_stop_hour = datetime(a.year, a.month, a.day, STOP_HOUR) seconds = max(0, (a_stop_hour - a).total_seconds()) b_stop_hour = datetime(b.year, b.month, b.day, STOP_HOUR) if b_stop_hour &gt; b: b_stop_hour = datetime(b.year, b.month, b.day-1, STOP_HOUR) seconds += (b - b_stop_hour).total_seconds() return (b_stop_hour - a_stop_hour).total_seconds() * KEEP + seconds - weekend_seconds </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T01:04:19.407", "Id": "461344", "Score": "0", "body": "What about other holidays? It sounds as if by excluding weekends you mean to exclude all free days. Note that in Arabic countries, Friday is not a work day, but sunday is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T01:38:14.433", "Id": "461346", "Score": "0", "body": "@RolandIllig, good points, although my use case from 7 years ago wouldn't have been concerned about other possible holidays." } ]
[ { "body": "<p>I think the initial calculation between the two dates looks cleaner using a generator expression + sum. The posterior correction is easier to understand if you do the intersection of hours by thinking in seconds of the day</p>\n\n<pre><code>from datetime import datetime\nfrom datetime import timedelta\n\nSTART_HOUR = 8 * 60 * 60\nSTOP_HOUR = 17 * 60 * 60\nKEEP = STOP_HOUR - START_HOUR\n\ndef seconds_between(a, b):\n days = (a + timedelta(x + 1) for x in xrange((b - a).days))\n total = sum(KEEP for day in days if day.weekday() &lt; 5)\n\n aseconds = (a - a.replace(hour=0, minute=0, second=0)).seconds\n bseconds = (b - b.replace(hour=0, minute=0, second=0)).seconds\n\n if aseconds &gt; START_HOUR:\n total -= min(KEEP, aseconds - START_HOUR)\n\n if bseconds &lt; STOP_HOUR:\n total -= min(KEEP, STOP_HOUR - bseconds)\n\n return total\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-21T22:53:51.810", "Id": "18899", "ParentId": "18053", "Score": "8" } }, { "body": "<h3>1. Issues</h3>\n\n<p>Your code fails in the following corner cases:</p>\n\n<ol>\n<li><p><code>a</code> and <code>b</code> on the same day, for example:</p>\n\n<pre><code>&gt;&gt;&gt; a = datetime(2012, 11, 22, 8)\n&gt;&gt;&gt; a.weekday()\n3 # Thursday\n&gt;&gt;&gt; seconds_between(a, a + timedelta(seconds = 100))\n54100.0 # Expected 100\n</code></pre></li>\n<li><p><code>a</code> or <code>b</code> at the weekend, for example:</p>\n\n<pre><code>&gt;&gt;&gt; a = datetime(2012, 11, 17, 8)\n&gt;&gt;&gt; a.weekday()\n5 # Saturday\n&gt;&gt;&gt; seconds_between(a, a + timedelta(seconds = 100))\n21700.0 # Expected 0\n</code></pre></li>\n<li><p><code>a</code> after <code>STOP_HOUR</code> or <code>b</code> before <code>START_HOUR</code>, for example:</p>\n\n<pre><code>&gt;&gt;&gt; a = datetime(2012, 11, 19, 23)\n&gt;&gt;&gt; a.weekday()\n0 # Monday\n&gt;&gt;&gt; seconds_between(a, a + timedelta(hours = 2))\n28800.0 # Expected 0\n</code></pre></li>\n</ol>\n\n<p>Also, you count the weekdays by looping over all the days between the start and end of the interval. That means that the computation time is proportional to the size of the interval:</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; a = datetime(1, 1, 1)\n&gt;&gt;&gt; timeit(lambda:seconds_between(a, a + timedelta(days=999999)), number=1)\n1.7254137992858887\n</code></pre>\n\n<p>For comparison, in this extreme case the revised code below is about 100,000 times faster:</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:office_time_between(a, a + timedelta(days=999999)), number=100000)\n1.6366889476776123\n</code></pre>\n\n<p>The break even point is about 4 days:</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:seconds_between(a, a + timedelta(days=4)), number=100000)\n1.5806620121002197\n&gt;&gt;&gt; timeit(lambda:office_time_between(a, a + timedelta(days=4)), number=100000)\n1.5950188636779785\n</code></pre>\n\n<h3>2. Improvements</h3>\n\n<p><a href=\"https://codereview.stackexchange.com/a/18899/11728\">barracel's answer</a> has two very good ideas, which I adopted:</p>\n\n<ol>\n<li><p>compute the sum in seconds rather than days;</p></li>\n<li><p>add up whole days and subtract part days if necessary.</p></li>\n</ol>\n\n<p>and I made the following additional improvements:</p>\n\n<ol>\n<li><p>handle corner cases correctly;</p></li>\n<li><p>run in constant time regardless of how far apart <code>a</code> and <code>b</code> are;</p></li>\n<li><p>compute the sum as a <code>timedelta</code> object rather than an integer;</p></li>\n<li><p>move common code out into functions for clarity;</p></li>\n<li><p>docstrings!</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<pre><code>from datetime import datetime, timedelta\n\ndef clamp(t, start, end):\n \"Return `t` clamped to the range [`start`, `end`].\"\n return max(start, min(end, t))\n\ndef day_part(t):\n \"Return timedelta between midnight and `t`.\"\n return t - t.replace(hour = 0, minute = 0, second = 0)\n\ndef office_time_between(a, b, start = timedelta(hours = 8),\n stop = timedelta(hours = 17)):\n \"\"\"\n Return the total office time between `a` and `b` as a timedelta\n object. Office time consists of weekdays from `start` to `stop`\n (default: 08:00 to 17:00).\n \"\"\"\n zero = timedelta(0)\n assert(zero &lt;= start &lt;= stop &lt;= timedelta(1))\n office_day = stop - start\n days = (b - a).days + 1\n weeks = days // 7\n extra = (max(0, 5 - a.weekday()) + min(5, 1 + b.weekday())) % 5\n weekdays = weeks * 5 + extra\n total = office_day * weekdays\n if a.weekday() &lt; 5:\n total -= clamp(day_part(a) - start, zero, office_day)\n if b.weekday() &lt; 5:\n total -= clamp(stop - day_part(b), zero, office_day)\n return total\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-16T06:22:34.960", "Id": "298867", "Score": "3", "body": "This code is broken for a couple of cases, for instance if you give it a Monday and Friday in the same week it gives a negative timedelta. The issue is with the calculation of extra but I don't have a solution yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T00:52:42.630", "Id": "461365", "Score": "0", "body": "@radman's comment on the error of Gareth Rees' is caused by 'extra' value.\nwhen the first day starts on Monday and ends on Friday or Saturday, this issue happens so need to adjust accordingly. so change `extra = (max(0, 5 - a.weekday()) + min(5, 1 + b.weekday())) % 5` to `if a.weekday()==0 and (b.weekday()==4 or b.weekday()==5): extra = 5 else: extra = (max(0, 5 - a.weekday()) + min(5, 1 + b.weekday())) % 5`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-22T13:53:05.113", "Id": "18912", "ParentId": "18053", "Score": "15" } }, { "body": "<p>The code below is a bit of a hybrid between the two approaches mentioned. I think it should work for all scenarios. No work done outside working hours is counted.</p>\n\n<pre><code>from datetime import datetime\nfrom datetime import timedelta\n\ndef adjust_hour_delta(t, start, stop):\n\n start_hour = start.seconds//3600\n end_hour = stop.seconds//3600\n zero = timedelta(0)\n\n if t - t.replace(hour = start_hour, minute = 0, second = 0) &lt; zero:\n t = t.replace(hour = start_hour, minute = 0, second = 0)\n elif t - t.replace(hour = end_hour, minute = 0, second = 0) &gt; zero:\n t = t.replace(hour = end_hour, minute = 0, second = 0)\n # Now get the delta\n delta = timedelta(hours=t.hour, minutes=t.minute, seconds = t.second)\n\n return delta \n\ndef full_in_between_working_days(a, b):\n working = 0\n b = b - timedelta(days=1)\n while b.date() &gt; a.date():\n if b.weekday() &lt; 5:\n working += 1\n b = b - timedelta(days=1)\n return working\n\ndef office_time_between(a, b, start = timedelta(hours = 8),\n stop = timedelta(hours = 17)):\n \"\"\"\n Return the total office time between `a` and `b` as a timedelta\n object. Office time consists of weekdays from `start` to `stop`\n (default: 08:00 to 17:00).\n \"\"\"\n zero = timedelta(0)\n assert(zero &lt;= start &lt;= stop &lt;= timedelta(1))\n office_day = stop - start\n working_days = full_in_between_working_days(a, b)\n\n total = office_day * working_days\n # Calculate the time adusted deltas for the the start and end days\n a_delta = adjust_hour_delta(a, start, stop)\n b_delta = adjust_hour_delta(b, start, stop)\n\n\n if a.date() == b.date():\n # If this was a weekend, ignore\n if a.weekday() &lt; 5:\n total = total + b_delta - a_delta\n else:\n # We now consider if the start day was a weekend\n if a.weekday() &gt; 4:\n a_worked = zero\n else:\n a_worked = stop - a_delta\n # And if the end day was a weekend\n if b.weekday() &gt; 4:\n b_worked = zero\n else:\n b_worked = b_delta - start\n total = total + a_worked + b_worked\n\n return total\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-06T18:52:58.090", "Id": "361239", "Score": "0", "body": "Testing this for these two dates, I get 1 working day when it should be 4: `2018-02-26 18:07:17` and\n`2018-03-04 14:41:04`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-15T08:10:32.243", "Id": "461363", "Score": "0", "body": "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": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-11-03T18:40:15.220", "Id": "179542", "ParentId": "18053", "Score": "2" } } ]
{ "AcceptedAnswerId": "18912", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-29T15:43:41.037", "Id": "18053", "Score": "22", "Tags": [ "python", "datetime" ], "Title": "Seconds between datestimes excluding weekends and evenings" }
18053
<p>I was surprised that I didn't find this approach to logging anywhere while reading up on the subject. So, naturally, I think I may be doing something wrong. I set up some simple tests, and this seems to work:</p> <p>First, the source: <code>log.py</code></p> <pre><code>import datetime import logging import os import config #this is very straightforward, nothing special here. log = config.Parser('log') def setup(stream_level=logging.INFO): """shared log named {log.name + log.format}.log call this logging setup method once, in the main function always refer to the config file when referring to the logger in modules other than the main file, call a reference to the already created logger in memory via log.hook(module_name) as long as this setup() was ran in the main method, the logfile should already exist in the proper place, with streams created for use, according to the config file entry for 'log'. `stream_level` indicates what level of detail should be printed to the terminal """ log.level = log.level.upper() logger = logging.getLogger(log.name) logger.setLevel(log.level) formatter = logging.Formatter(log.format) formatter.datefmt = log.datefmt pretty_date = datetime.date.strftime(datetime.datetime.now(), log.datefmt) date_ext = filter(lambda x: x.isdigit(), pretty_date) #terminal logging if stream_level: ch = logging.StreamHandler() ch.setLevel(stream_level) ch.setFormatter(formatter) #file logging logname = ''.join([log.name, date_ext, '.log']) fh = logging.FileHandler(os.path.join(log.dir, logname)) fh.setLevel(log.level) fh.setFormatter(formatter) logger.addHandler(fh) if stream_level: logger.addHandler(ch) return logger def hook(module_name): """pass in the special method __name__ for best results don't call this until you've setup() the logger in your main function """ return logging.getLogger('.'.join([log.name, module_name])) </code></pre> <p>And the <code>main.py</code></p> <pre><code>import util import log logger = log.setup() logger.info('starting now') util.p() logger.critical('quitting!') </code></pre> <p><code>util.py</code></p> <pre><code>import log def p(): logger = log.hook(__name__) for x in range(10): logger.warn('.') </code></pre>
[]
[ { "body": "<p>You can find approach you are looking for in the <a href=\"http://docs.python.org/2/howto/logging-cookbook.html\" rel=\"nofollow\">logging cookbook</a> and <a href=\"http://docs.python.org/2/howto/logging.html\" rel=\"nofollow\">logging howto</a>: Default logging module provides nice configuration feature. </p>\n\n<p>So your code will be like this: </p>\n\n<p>simpleExample.py (main):</p>\n\n<pre><code>import os\nimport logging\nimport logging.config\nlogging.config.fileConfig(os.path.join(os.path.dirname(__file__),\n 'logging.conf') \nimport util\n\n# create logger\nlogger = logging.getLogger(\"simpleExample\") \n\n# 'application' code\nlogger.info('starting now')\n\nutil.p()\n\nlogger.critical('quitting!')\n</code></pre>\n\n<p>util.py</p>\n\n<pre><code>import logging\nlogger = logging.getLogger(\"simpleExample.Utils\")\n\ndef p():\n for x in range(10):\n logger.warn('.')\n</code></pre>\n\n<p>And all the magic of logging configuration will be avalible in config file:\nlogging.cfg: </p>\n\n<pre><code>[loggers]\nkeys=root,simpleExample\n\n[handlers]\nkeys=consoleHandler\n\n[formatters]\nkeys=simpleFormatter\n\n[logger_root]\nlevel=DEBUG\nhandlers=consoleHandler\n\n[logger_simpleExample]\nlevel=DEBUG\nhandlers=consoleHandler\nqualname=simpleExample\npropagate=0\n\n[handler_consoleHandler]\nclass=StreamHandler\nlevel=DEBUG\nformatter=simpleFormatter\nargs=(sys.stdout,)\n\n[formatter_simpleFormatter]\nformat=%(asctime)s - %(name)s - %(levelname)s - %(message)s\ndatefmt=`\n</code></pre>\n\n<p>You can use any handlers you want, and you can change levels, formats etc and you don't have to change your code. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T20:40:58.343", "Id": "18562", "ParentId": "18132", "Score": "4" } } ]
{ "AcceptedAnswerId": "18562", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-01T13:42:33.667", "Id": "18132", "Score": "4", "Tags": [ "python", "logging" ], "Title": "How's my approach to logging?" }
18132
<p>I'm implementing a version of the mean shift image processing algorithm for color segmentation in Python/NumPy.</p> <p>I've written a pure NumPy version of the actual mean shifting per pixel (which I imagine is where the majority of time is taking). It slices an array of RGB values to work on out of the parent image, then creates lower bound and higher bound RGB reference arrays and generates a boolean masking array for the pixels to use for averaging then averages.</p> <p>Any further optimizations? I suspect vectorizing the x/y for loops might give a speed up but for the life of me, but I haven't figured out how. (Some how generating an array of each pixel grid to work on and then generalizing the mean shift to take array input?) gL is grid length. gS is gL squared - the number of pixels in grid.</p> <pre><code>for itr in xrange(itrs): if itr != 0: img = imgNew for x in xrange(gL,height-gL): for y in xrange(gL,width-gL): cGrid = img[x-gSmp:(x+gSmp+1),y-gSmp:(y+gSmp+1)] cLow,cUp = np.empty((gL,gL,3)),np.empty((gL,gL,3)) cLow[:] = [img[x,y][0]-tol,img[x,y][1]-tol,img[x,y][2]-tol] cUp[:] = [img[x,y][0]+tol,img[x,y][1]+tol,img[x,y][2]+tol] cBool = np.any(((cLow &lt; cGrid) &amp; (cUp &gt; cGrid)),axis=2) imgNew[x,y] = np.sum(cGrid[cBool],axis=0)/cBool.sum() </code></pre>
[]
[ { "body": "<p>The following code is a first shot and it is still not vectorized. The major points here are the extraction of the creation of cLow and cUp (don't create arrays in loops, always 'preallocate' memory), the calculation of the tolerance levels can be done in one operation (under the assumption that broadcasting is possible at this point) and at last I removed the conditional case for copying the imgNew to img (I also doubt that you do not want to copy the last iteration back into img. If so you have to remove the copy line before the loop and move the copy at the beginning of the loop to its end.).</p>\n\n<pre><code>diff_height_gL = height - gL\ndiff_width_gL = width - gL\nsum_gSmp_one = gSmp + 1\n\ncLow, cUp = np.empty((gL, gL, 3)), np.empty((gL, gL, 3))\n\nimgNew = img.copy()\n\nfor itr in xrange(itrs):\n\n img[:] = imgNew\n\n for x in xrange(gL, diff_height_gL):\n for y in xrange(gL, diff_width_gL):\n\n cGrid = img[x-gSmp:(x + sum_gSmp_one), y-gSmp:(y + sum_gSmp_one)]\n\n cLow[:] = img[x, y, :] - tol\n cUp[:] = img[x, y, :] + tol\n\n cBool = np.any(((cLow &lt; cGrid) &amp; (cUp &gt; cGrid)), axis=2)\n\n imgNew[x, y] = np.sum(cGrid[cBool], axis=0) / cBool.sum()\n</code></pre>\n\n<p>This problems seems to be perfectly shaped to do multiprocessing. This could be an alternative/extension to vectorization. If I have time I will try the vectorization...</p>\n\n<p>Kind regeards</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-22T13:25:27.737", "Id": "18911", "ParentId": "18149", "Score": "1" } } ]
{ "AcceptedAnswerId": "18911", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-02T08:14:44.973", "Id": "18149", "Score": "4", "Tags": [ "python", "optimization", "image", "numpy" ], "Title": "Mean shift image processing algorithm for color segmentation" }
18149
<p>I was trying, just for fun, to solve <a href="http://code.google.com/codejam/contest/dashboard?c=2075486#s=p4" rel="nofollow">http://code.google.com/codejam/contest/dashboard?c=2075486#s=p4</a> </p> <p>I can easily solve the small set, but I struggle to solve the big one (my implementation would use approx. 30GB or RAM, which is a bit too much. Any hint or direction is appreciated!</p> <pre><code>def solve_maze(case_no): case = cases[case_no] case_no += 1 edges = case['edges'] #quick and dirty check. Can we reach the goal? if case['goal'] not in sum([i.values() for i in edges.values()],[]): return "Case #%s: Infinity" % case_no last_position = 1 l = 0 states = set() memory = [1 for i in range(1,1+case['goal'])] while not last_position==case['goal']: direction = memory[last_position] memory[last_position] *= -1 move = edges[last_position][direction] states.add(hash((move,tuple(memory)))) l+=1 if len(states) != l: return "Case #%s: Infinity" % case_no last_position = move else: return "Case #%s: %d" % (case_no,len(states)) with open("/xxx/test-small.in","rb") as f: inp = f.read()[:-1].split("\n") N = int(inp[0]) cases = [] it = 0 for line in inp[1:]: if line.find(" ") == -1: #print int(line) cases.append({"goal":int(line),"edges":{}}) it = 0 else: it+=1 cases[-1]['edges'][it] = dict(zip([1,-1],map(int,line.split()))) for i in range(len(cases)): print solve_maze(i) </code></pre>
[]
[ { "body": "<pre><code>def solve_maze(case_no):\n case = cases[case_no]\n</code></pre>\n\n<p>It'd make more sense to pass the case here, and operate on that rather then passing in the case number</p>\n\n<pre><code> case_no += 1\n edges = case['edges']\n #quick and dirty check. Can we reach the goal?\n if case['goal'] not in sum([i.values() for i in edges.values()],[]):\n return \"Case #%s: Infinity\" % case_no\n</code></pre>\n\n<p>I avoid such quick and dirty checks. The problem is that they are easily defeated by a crafted problem. Not enough cases are really eliminated here to make it work.</p>\n\n<pre><code> last_position = 1\n l = 0\n states = set()\n memory = [1 for i in range(1,1+case['goal'])]\n</code></pre>\n\n<p>It's a little odd to add one to both parameters to range and then ignore the count</p>\n\n<pre><code> while not last_position==case['goal']:\n</code></pre>\n\n<p>Use != </p>\n\n<pre><code> direction = memory[last_position]\n memory[last_position] *= -1\n move = edges[last_position][direction]\n states.add(hash((move,tuple(memory))))\n</code></pre>\n\n<p>You aren't guaranteed to have distinct hashes for unequal objects so this must fail. You should really add the whole tuple to the state. Actually, you don't even need to track the states. There are are only so many possible states, and you can simply count the number of transitions, if this gets above the number of possible states, you're in an infinite loop.</p>\n\n<pre><code> l+=1\n if len(states) != l:\n return \"Case #%s: Infinity\" % case_no\n last_position = move\n else:\n return \"Case #%s: %d\" % (case_no,len(states))\n\n\n\nwith open(\"/xxx/test-small.in\",\"rb\") as f:\n inp = f.read()[:-1].split(\"\\n\")\n</code></pre>\n\n<p>This really isn't a good way to read your input. Use <code>f.readline()</code> to fetch a line at a time. It'll be much easier to parse the input that way.</p>\n\n<pre><code> N = int(inp[0])\n cases = []\n it = 0\n for line in inp[1:]:\n</code></pre>\n\n<p>Wrong choice of loop. You really want to repeat the process of reading a single case N times, not do something on each line of the file.</p>\n\n<pre><code> if line.find(\" \") == -1:\n #print int(line)\n cases.append({\"goal\":int(line),\"edges\":{}})\n</code></pre>\n\n<p>Don't treat dictionaries like objects. It'd make more sense to pass goal and edges as parameters rather them stick in a dictionary. At least, you should prefer an object.</p>\n\n<pre><code> it = 0\n else:\n it+=1\n cases[-1]['edges'][it] = dict(zip([1,-1],map(int,line.split())))\n for i in range(len(cases)):\n print solve_maze(i)\n</code></pre>\n\n<p>As for your algorithm. You can't get away with simulating all of the clearings. One can design a test case that takes over 2**39 steps to complete. So you can't simulate the straightforward process of moving one clearing at a time. But any given forest will have patterns in how the states change. You need to find a way to characterize the patterns so that you can simulate the process more quickly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-04T11:52:11.410", "Id": "29041", "Score": "0", "body": "Thanks for the coding review. I was particularly interested in a comment on the algo but I was happy to see how I could have written a cleaner code. As for the infinite loop, now I am doing it by checking if the node I go to is somehow, optimally connected to the goal. If it's not, then I have an infinite loop. The hash was used in a test version to reduce the amount of memory used by the list, but I was aware of the high chance of collisions. I am now following the suggestion of a friend, i.e. trying to implement some DP on half of the set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-04T12:44:49.903", "Id": "29043", "Score": "0", "body": "@luke14free, I believe that checking for connection to the goal won't be sufficient for infinite loops. I'm pretty sure I found cases where I was connected, but still in an infinite loop. The half-set DP solution should work, although its not the same solution I implemented." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-04T13:08:50.780", "Id": "29044", "Score": "0", "body": "Now I am tempted about asking for your idea.. :) But I won't! I'll delve a bit deeper and try to figure out other solution schemas" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-04T03:28:41.680", "Id": "18201", "ParentId": "18154", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-02T13:14:44.727", "Id": "18154", "Score": "2", "Tags": [ "python", "search" ], "Title": "Shifting Paths problem (Code Jam)" }
18154
<p>Below is my written code to determine if, based on the hypotenuse, a Pythagorean triple is possible, and what are the lengths. I was wondering if there is a more efficient way of doing so.</p> <pre><code>#Victor C #Determines if a right triangle with user inputted hypotenuse is capable of being a Pythagorean Triple import math triplecheck = True while True: hypotenuse = int(input("Please enter the hypotentuse:")) #Smallest hypotenuse which results in a pythagorean triple is 5. if hypotenuse &gt; 4: break c = csqr = hypotenuse**2 #sets two variables to be equivalent to c^^2. c is to be modified to shorten factoring, csqr as a reference to set a value if c % 2 != 0: #even, odd check of value c, to create an integer when dividing by half. c = (c+1)//2 else: c = c//2 for b in range(1,c+1): #let b^^2 = b || b is equal to each iteration of factors of c^^2, a is set to be remainder of c^^2 minus length b. a = csqr-b if (math.sqrt(a))%1 == 0 and (math.sqrt(b))%1 == 0: #if squareroots of a and b are both equal to 0, they are integers, therefore fulfilling conditions tripleprompt = "You have a Pythagorean Triple, with the lengths of "+str(int(math.sqrt(b)))+", "+str(int(math.sqrt(a)))+" and "+str(hypotenuse) print(tripleprompt) triplecheck = False if triplecheck == True: print("Sorry, your hypotenuse does not make a Pythagorean Triple.") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-03T01:13:01.627", "Id": "28988", "Score": "0", "body": "please format your code in a readable format" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-03T01:24:04.630", "Id": "28989", "Score": "0", "body": "(`) Change `if math.sqrt(a)%1 == 0` to `if not math.sqrt(a)%1`. (2) Put everything inside `while True` in a function and call that function inside `while True`. Otherwise, this is a better fit for codereview.SE" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-03T02:25:39.657", "Id": "62805", "Score": "0", "body": "There is a significantly more mathematically advanced method called the Hermite-Serret method; you can find details at http://math.stackexchange.com/questions/5877/efficiently-finding-two-squares-which-sum-to-a-prime" } ]
[ { "body": "<p>First, let's write this with a little style, and go from there:</p>\n\n<pre><code>import math\n\ndef is_triple(hypotenuse):\n \"\"\"return (a, b, c) if Pythagrean Triple, else None\"\"\"\n if hypotenuse &lt; 4:\n return None\n\n c = hypotenuse ** 2\n\n for a in xrange(3, hypotenuse):\n b = math.sqrt(c - (a ** 2)) \n if b == int(b):\n return a, int(b), hypotenuse\n\n return None\n</code></pre>\n\n<p>Now, I'll walk you through it, line by line, and show you how I got this.</p>\n\n<p>I have no idea if this is more efficient, but it is written in better style, which is an important thing to consider.</p>\n\n<pre><code>import math\n</code></pre>\n\n<p>Always put your imports at the top of the module.</p>\n\n<pre><code>def is_triple(hypotenuse):\n</code></pre>\n\n<p>Here is say 'let's <strong>def</strong><em>ine</em> some functionality, and encase a repeatable, reusable pattern of logic within it. The rest of my answer revolves around this, and is a major first step to programming in Python.</p>\n\n<pre><code>def is_triple(hypotenuse):\n \"\"\"return (a, b, c) if Pythagrean Triple, else None\"\"\"\n</code></pre>\n\n<p>Note the <code>\"\"\"</code> triple quotes. That's your <a href=\"http://www.python.org/dev/peps/pep-0257/#one-line-docstrings\">docstring</a>, something that reminds you later what you were thinking when you wrote something. Try to keep it under 65 characters or so.</p>\n\n<pre><code>if hypotenuse &lt; 4:\n return None\n</code></pre>\n\n<p>In the first line, <code>def is_triple(hypotenuse):</code>, I ask the user to give me something; a variable that I can use later. If I later <em>call</em> this function in the manner <code>is_triple(5)</code>, I am basically telling the function that my hypotenuse is 5, and for the rest of the time here, we'll call it <code>hypotenuse</code>. </p>\n\n<pre><code>c = hypotenuse ** 2\n</code></pre>\n\n<p>That's really all you need for this calculation right now.</p>\n\n<pre><code>for a in xrange(3, hypotenuse):\n b = math.sqrt(c - (a ** 2)) \n if b == int(b):\n return a, int(b), hypotenuse\n</code></pre>\n\n<p><code>for a in xrange(3, hypotenuse)</code> basically says <em>for each whole number between 3 and the hypotenuse, do the stuff I'm about to write</em>.</p>\n\n<p>Following the previous example,</p>\n\n<pre><code>&gt;&gt;&gt; range(3, hypotenuse) #hypotenuse is == 5\n[3, 4]\n</code></pre>\n\n<p>Nevermind that I call <code>xrange()</code>, it functions the same as far as we're concerned here, and importantly, is more efficient.</p>\n\n<p>So now that we've made a <strong>loop</strong>, <code>a</code> will act as though it is <em>each number in [3, 4]</em>, so first, it's 3:</p>\n\n<pre><code>b = math.sqrt(c - (a ** 2))\nb = math.sqrt(25 - (3 ** 2))\nb = math.sqrt(25 - (9))\nb = math.sqrt(16)\nb = 4.0\n</code></pre>\n\n<p>Just like you would on pencil and paper. Notice I put a <code>.0</code> after, the four. That's important here:</p>\n\n<pre><code>if b == int(b):\n</code></pre>\n\n<p>Basically, <code>int</code> puts the number <code>b</code> from a decimal to a whole number. We just check if they're the same.</p>\n\n<pre><code>&gt;&gt;&gt; int(4.0)\n4\n&gt;&gt;&gt; int(4.0) == 4\nTrue\n</code></pre>\n\n<p>So, if the number we got for <code>b</code> is the same as the whole number representation of <code>b</code>, do the next part:</p>\n\n<pre><code>return a, int(b), hypotenuse\n</code></pre>\n\n<p>Which maps a value back to whatever you called as an assignment for the function call.</p>\n\n<pre><code>&gt;&gt;&gt; values = is_triple(5)\n&gt;&gt;&gt; values\n(3, 4, 5)\n&gt;&gt;&gt; wrong = is_triple(7)\n&gt;&gt;&gt; wrong\n&gt;&gt;&gt; #it didn't print anything, because it gave me back None\n</code></pre>\n\n<p>Finally, at the bottom:</p>\n\n<pre><code>return None\n</code></pre>\n\n<p>That's the last thing to catch, in case nothing else happens. Obviously, if you've gone through this loop and you haven't gotten an answer? Well, looks like you don't have a match. Give back a <code>None</code> to denote this.</p>\n\n<p>To see this work in action, try this:</p>\n\n<pre><code>&gt;&gt;&gt; import pprint\n&gt;&gt;&gt; pprint.pprint([{x: is_triple(x)} for x in xrange(101)])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T01:52:40.290", "Id": "29424", "Score": "0", "body": "Thank you to everybody that replied with an answer. I am in grade 11, and have been getting into coding from september. I appreciate all the feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-03T02:21:22.607", "Id": "18172", "ParentId": "18171", "Score": "9" } }, { "body": "<p>I'm going to point to one thing that is a potential big source of confusion. Imagine you come back to this a year from now, and you've seen some error on one line of this code. You want to fix that line of code, and you're in a rush. You're not going to read the whole function if you can get away with it. Quick - what do <code>a</code>, <code>b,</code> and<code>c</code> mean?</p>\n\n<p>Usually <code>a</code>, <code>b</code>, and <code>c</code> are the lengths of the sides. Here you've got them as the square of the lengths of the sides. That's going to confuse you when you try to revisit this code.</p>\n\n<p>You've even got some of that confusion going on already - you've set </p>\n\n<p><code>c=csqr</code></p>\n\n<p>So you're thinking of <code>c</code> as something, and at the same time you're thinking of that same thing as being csquared. You've got two different concepts of <code>c</code>. Similarly, your comment <code>#let b^^2 = b</code>. That's just asking for trouble. In your comments you clearly think of <code>b</code> as something different from what the code thinks of it as. So somewhere else where your comments might refer to <code>b</code> - is that the same <code>b</code> you meant in your comment earlier, or is it the version of <code>b</code> now in the code? (and note it's really <code>b**2</code>, not <code>b^^2</code>). You don't get any bonus for just having 3 one letter variable names.</p>\n\n<p>If you want to do your calculations in the squared variable, use <code>asq</code>, <code>bsq</code>, and <code>csq</code>. (and consider writing out <code>aSquared</code> etc to make it clear).</p>\n\n<p>I wrote my own version without looking at the other solution, but in Python there should be one and only one obvious way to do things (though you may have to be Dutch to see it). The solutions are almost identical:</p>\n\n<pre><code>def test(hypotenuse):\n factor = 1\n while hypotenuse %2 == 0:\n factor *=2\n hypotenuse/= 2\n\n hsq = hypotenuse**2\n\n success = False\n for b in xrange(1,hypotenuse):\n a = math.sqrt(hsq-b**2)\n if a == int(a):\n return sorted([factor*int(a), factor*b, factor*hypotenuse])\n return (None,None,None)\n\n\n\nhypotenuse = int(input(\"Please enter the hypotentuse:\"))\n\n(a,b,c) = test(hypotenuse)\n\nif a is None:\n print \"failure, utter, utter failure\"\nelse:\n print a, b, c\n</code></pre>\n\n<p>The only real difference is that I took advantage of the fact that one can prove it we have a pythagorean triple with an even hypotenuse, then dividing by 2 yields a new pythagorean triple.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-21T16:21:02.307", "Id": "135292", "Score": "0", "body": "\"Quick - what do a, b, and c mean?\" +50" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-16T02:10:41.947", "Id": "73791", "ParentId": "18171", "Score": "3" } } ]
{ "AcceptedAnswerId": "18172", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-03T01:09:31.610", "Id": "18171", "Score": "11", "Tags": [ "python", "performance", "mathematics" ], "Title": "Determining Pythagorean triples based on the hypotenuse" }
18171
<p>I'm new to Python, just attempted the task <a href="https://www.cs.duke.edu/courses/cps100/fall03/assign/extra/treesum.html" rel="nofollow">here</a>.</p> <p>The part I found hardest was parsing the expression into the tree structure. I was originally trying to build a regular tree structure (i.e. a Node object with left and right nodes), but without any logic for the insertion (i.e. newNode &lt; node then insert left, newNode > node then insert right) I couldn't find a way.</p> <p>In the end I've used Python's lists to kind of replicate the expression structure, and walk the paths as they're created. Each time I find a leaf, I calculate the cumulative sum, pop the last added node, and carry on.</p> <p>The one part of the code I really don't like is the way I'm finding leafs:</p> <pre><code>if tree and expression[i-1:i+3] == ['(',')','(',')']: </code></pre> <p>and I don't like that I've done:</p> <pre><code>pair[1].replace('(', ' ( ').replace(')', ' ) ').split() </code></pre> <p>twice.</p> <p>Any guidance on any part of this - style or just general approach and logic would be great.</p> <pre><code>def pairs(value): """ Yields pairs (target, expression) """ nest_level = 0 expr = "" target = 0 value = value.replace('(', ' ( ').replace(')', ' ) ').split() for x in value: if x.isdigit() and not expr: target = x else: expr += x if x is '(': nest_level += 1 elif x is ')': nest_level -= 1 if nest_level is 0: yield target, expr expr = '' target = 0 def main(): with open('input') as f: expr_input = f.read() level = 0 current_target = 0 for pair in pairs(expr_input): current_target = pair[0] # stack representing the 'current path' tree = list() # store the cumulative total of each path for this expression cumulative_totals = list() running_total = 0 expression = pair[1].replace('(', ' ( ').replace(')', ' ) ').split() for i, s in enumerate(expression): if s is '(': level += 1 elif s == ')': level -= 1 # "is leaf?" ugh. if tree and expression[i-1:i+3] == ['(',')','(',')']: cumulative_totals.append(running_total) # remove the node and carry on down the next path node = tree.pop() running_total = running_total - int(node) if level is 0: if int(current_target) in cumulative_totals: print "yes" else: print "no" else: running_total += int(s) tree.append(s) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>This is not per-ce what you asked, but code can be split into two distinct steps:</p>\n\n<ol>\n<li>Parse the given string to some data structure.</li>\n<li>Execute algorithm on that structure.</li>\n</ol>\n\n<p>Step [1] can be done in 3 lines, as the string is almost a python syntax as is:</p>\n\n<pre><code>s = '(5 (4 (11 (7 () ()) (2 () ()) ) ()) (8 (13 () ()) (4 () (1 () ()) ) ) )'\ns = s.replace('(',',[')\ns = s.replace(')',']')\ns = s[1:]\n</code></pre>\n\n<p>Now <code>s</code> is a valid python list:</p>\n\n<pre><code>'[5 ,[4 ,[11 ,[7 ,[] ,[]] ,[2 ,[] ,[]] ] ,[]] ,[8 ,[13 ,[] ,[]] ,[4 ,[] ,[1 ,[] ,[]] ] ] ]'\n</code></pre>\n\n<p>Let's put it into a variable:</p>\n\n<pre><code>ltree = eval(s)\n</code></pre>\n\n<p>Now <code>ltree</code> is a good tree representation - it is in fact a DFS walk on the tree.</p>\n\n<p><code>ltree[0]</code> is the root value, <code>ltree[1]</code> is the left subtree, and <code>ltree[2]</code> is the right subtree - and so on.</p>\n\n<p>And the code to test the walk becomes simple:</p>\n\n<pre><code>def is_sum(tree, num):\n if (len(tree) == 0): # 'in' a leaf\n return False\n if (len(tree[1]) == 0 &amp; len(tree[2]) == 0): # leaf\n return num == tree[0]\n return (is_sum(tree[1], num-tree[0]) | is_sum(tree[2], num-tree[0]))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T18:23:52.963", "Id": "18358", "ParentId": "18342", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T09:48:31.203", "Id": "18342", "Score": "5", "Tags": [ "python", "beginner" ], "Title": "Parsing s-expression structure into tree and summing the paths" }
18342
<p>I have two sieves that I wrote in python and would like help optimizing them if at all possible. The divisorSieve calculates the divisors of all numbers up to <code>n</code>. Each index of the list contains a list of its divisors. The numDivisorSieve just counts the number of divisors each index has but doesn't store the divisors themselves. These sieves work in a similar way as you would do a Sieve of Eratosthenes to calculate all prime numbers up to <code>n</code>.</p> <p><em>Note: <code>divs[i * j].append(i)</code> changed from <code>divs[i * j] += [i]</code> with speed increase thanks to a member over at stackoverflow. I updated the table below with the new times for divisorSieve. It was suggested to use this board instead so I look forward to your input.</em></p> <pre><code>def divisorSieve(n): divs = [[1] for x in xrange(0, n + 1)] divs[0] = [0] for i in xrange(2, n + 1): for j in xrange(1, n / i + 1): divs[i * j].append(i) #changed from += [i] with speed increase. return divs def numDivisorSieve(n): divs = [1] * (n + 1) divs[0] = 0 for i in xrange(2, n + 1): for j in xrange(1, n / i + 1): divs[i * j] += 1 return divs #Timer test for function if __name__=='__main__': from timeit import Timer n = ... t1 = Timer(lambda: divisorSieve(n)) print n, t1.timeit(number=1) </code></pre> <p>Results:</p> <pre><code> -----n-----|--time(divSieve)--|--time(numDivSieve)-- 100,000 | 0.333831560615 | 0.187762331281 200,000 | 0.71700566026 | 0.362314797537 300,000 | 1.1643773714 | 0.55124339118 400,000 | 1.63861821235 | 0.748340797412 500,000 | 2.06917832929 | 0.959312993718 600,000 | 2.52753840891 | 1.17777010636 700,000 | 3.01465945139 | 1.38268800149 800,000 | 3.49267338434 | 1.62560614543 900,000 | 3.98145114138 | 1.83002270324 1,000,000 | 4.4809342539 | 2.10247496423 2,000,000 | 9.80035361075 | 4.59150618897 3,000,000 | 15.465184114 | 7.24799900479 4,000,000 | 21.2197508864 | 10.1484527586 5,000,000 | 27.1910144928 | 12.7670585308 6,000,000 | 33.6597508864 | 15.4226118057 7,000,000 | 39.7509513591 | 18.2902677738 8,000,000 | 46.5065447534 | 21.1247001928 9,000,000 | 53.2574136966 | 23.8988925173 10,000,000 | 60.0628718044 | 26.8588813211 11,000,000 | 66.0121182435 | 29.4509693973 12,000,000 | MemoryError | 32.3228102258 20,000,000 | MemoryError | 56.2527237669 30,000,000 | MemoryError | 86.8917332214 40,000,000 | MemoryError | 118.457179822 50,000,000 | MemoryError | 149.526622815 60,000,000 | MemoryError | 181.627320396 70,000,000 | MemoryError | 214.17467749 80,000,000 | MemoryError | 246.23677614 90,000,000 | MemoryError | 279.53308422 100,000,000 | MemoryError | 314.813166014 </code></pre> <p>Results are pretty good and I'm happy I was able to get it this far, but I'm looking to get it even faster. If at all possible, I'd like to get <em><strong>100,000,000</strong></em> at a reasonable speed with the divisorSieve. Although this also brings into the issue that anything over <em><strong>12,000,000+</strong></em> throws a <code>MemoryError</code> at <code>divs = [[1] for x in xrange(0, n + 1)]</code>) in divisorSieve. numDivisorSieve does allow the full <em><strong>100,000,000</strong></em> to run. If you could also help get past the memory error, that would be great.</p> <p>I've tried replacing numDivisorSieve's <code>divs = [1] * (n + 1)</code> with both <code>divs = array.array('i', [1] * (n + 1))</code> and <code>divs = numpy.ones((n + 1), dtype='int')</code> but both resulted in a loss of speed (slight difference for array, much larger difference for numpy). I expect that since numDivisorSieve had a loss in efficiency, then so would divisorSieve. Of course there's always the chance I'm using one or both of these incorrectly since I'm not used to either of them.</p> <p>I would appreciate any help you can give me. I hope I have provided enough details. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:04:30.323", "Id": "29298", "Score": "0", "body": "What are you doing with the result?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T02:31:49.577", "Id": "29301", "Score": "0", "body": "If storing only prime factors counts as 'optimization', we can do ~3-4 times faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T10:48:20.477", "Id": "29335", "Score": "0", "body": "Have you tested the application using Python 64bit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T22:29:14.767", "Id": "29377", "Score": "0", "body": "Thanks for the suggestion about Python 64bit. It's looking like it solves the memory issues. Will update once I've run all the tests" } ]
[ { "body": "<p>You can use <code>xrange</code>'s third param to do the stepping for you to shave off a little bit of time (not huge).</p>\n\n<p>Changing:</p>\n\n<pre><code>for j in xrange(1, n / i + 1):\n divs[i * j].append(i)\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>for j in xrange(i, n + 1, i):\n divs[j].append(i)\n</code></pre>\n\n<p>For <code>n=100000</code>, I go from <code>0.522774934769</code> to <code>0.47496509552</code>. This difference is bigger when made to <code>numDivisorSieve</code>, but as I understand, you're looking for speedups in <code>divisorSieve</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:52:07.010", "Id": "29374", "Score": "0", "body": "This was a great optimization! for `n = 10,000,000` divisorSieve's time is down to _**9.56704298066**_ and for `n = 100,000,000` numDivisorSieve's time is down to _**67.1441108416**_ which are both great optimizations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T22:07:14.110", "Id": "29376", "Score": "0", "body": "Wow... that's better than I expected! Glad I could help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T04:14:31.580", "Id": "29425", "Score": "0", "body": "Well...apparently the reason it did so well is I had the range messed up. So while it's still an improvement, it's not quite as good as I thought. Doesn't make me appreciate your help any less, just makes me feel a little stupid. Guess that's what I get for not testing the output well enough. Will update the original post when I get a chance to recompute all the results" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T04:28:39.427", "Id": "29426", "Score": "0", "body": "@JeremyK That's fine. At least I know I'm not crazy now. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:03:58.300", "Id": "31317", "Score": "0", "body": "@JeremyK I was commenting on your OP about the erratic range before reading this. You should update the post - atleast change the code and say that the results are incorrect for now." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T17:57:52.603", "Id": "18411", "ParentId": "18346", "Score": "2" } }, { "body": "<p><strong>EDIT</strong>: <code>map(lambda s: s.append(i) , [divs[ind] for ind in xrange(i, n + 1, i)])</code>\nSeems to be <del>~0.2% faster</del> <strong>~2 times slower</strong> than Adam Wagner's (for <code>n=1000000</code>)</p>\n\n<p>The infamous 'test the unit test' problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T21:52:52.147", "Id": "29375", "Score": "0", "body": "Maybe I'm doing something incorrectly, but when I put this in there I get `TypeError: list indices must be integers, not xrange`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:55:26.067", "Id": "31320", "Score": "0", "body": "**~2 times slower** Must be due to function call overhead for calling the lambda function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T19:57:05.510", "Id": "18416", "ParentId": "18346", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T13:16:23.207", "Id": "18346", "Score": "4", "Tags": [ "python", "optimization" ], "Title": "Optimizing Divisor Sieve" }
18346
<p>I wrote a simple class implementing the <code>collections.Sequence</code> interface, that forwards calls to its items to member functions of its items.</p> <p>I'm requesting a review of the following code snippet.</p> <pre><code>import collections class ForwardSequence(collections.Sequence): def __init__(self, *args, **kw): super(ForwardSequence, self).__init__() self._sequence = tuple(*args) self._get = kw.pop('get', None) self._set = kw.pop('set', None) def __len__(self): return len(self._sequence) def __getitem__(self, item): if isinstance(item, slice): indices = item.indices(len(self)) return [self[i] for i in range(*indices)] return self._get(self._sequence[item]) def __setitem__(self, item, value): items = self._sequence[item] if not isinstance(items, collections.Sequence): items = (items,) for i in items: self._set(i, value) </code></pre> <p>E.g.</p> <pre><code>class Command(object): def query(self): # send and return query string. def write(self, value): #send write string. class Controller(object): '''A simple temperature controller.''' def __init__(self): self.temperature = ForwardSequence( (Command() for _ in range(10)), get=lambda x: x.query(), set=lambda x, v: x.write(v) ) ctrl = Controller() # calls the query method of the first 5 Commands and returns it's results print ctrl.temperature[0:5] </code></pre>
[]
[ { "body": "<pre><code>import collections\n\nclass ForwardSequence(collections.Sequence):\n def __init__(self, *args, **kw):\n super(ForwardSequence, self).__init__()\n self._sequence = tuple(*args)\n</code></pre>\n\n<p>A tuple only takes on argument, why are you passing a variable number of arguments?</p>\n\n<pre><code> self._get = kw.pop('get', None)\n self._set = kw.pop('set', None)\n</code></pre>\n\n<p>Why don't you use keyword arguments instead of <code>**kw</code>? As it stands you are asking for trouble by ignoring any arguments that aren't there. Also, do you really want to allow the user to avoid specifying <code>get</code> and <code>set</code>. It seems to me those will always need to be defined.</p>\n\n<pre><code> def __len__(self):\n return len(self._sequence)\n\n def __getitem__(self, item):\n if isinstance(item, slice):\n indices = item.indices(len(self))\n return [self[i] for i in range(*indices)]\n</code></pre>\n\n<p>I'd suggest </p>\n\n<pre><code>return map(self._get, self_sequence[item])\n</code></pre>\n\n<p>That should offload some of the work onto the underlying sequence. </p>\n\n<pre><code> return self._get(self._sequence[item])\n\n def __setitem__(self, item, value):\n items = self._sequence[item]\n if not isinstance(items, collections.Sequence):\n items = (items,)\n</code></pre>\n\n<p>I suggest checking <code>isinstance(item, slice)</code> instead of this. As it stands, it has confusing behaviour of sequence contains sequences. I'd also just call <code>self._set(item, value)</code>, as you aren't saving anything by storing the item in a one-length tuple</p>\n\n<pre><code> for i in items:\n self._set(i, value)\n</code></pre>\n\n<p>I'm not sure I like the class's interface. It seems to be doing something more complex while masquerading as a list. This seems problematic to me. But I'd have to see more about how you use to know for certain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T16:35:31.787", "Id": "18408", "ParentId": "18399", "Score": "1" } } ]
{ "AcceptedAnswerId": "18408", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T13:13:08.203", "Id": "18399", "Score": "3", "Tags": [ "python" ], "Title": "Forwarding sequence" }
18399
<p>I wrote some code in Flask for site menu:</p> <pre><code>def menu(parent_id=0, menutree=None): menutree = menutree or [] cur = g.db.execute('select id, parent, alias, title, ord from static where parent="'+ str(parent_id) +'" and ord&gt;0 order by ord') fetch = cur.fetchall() if not fetch: return None return [{'id':raw[0], 'parent':raw[1], 'alias':raw[2], 'title':raw[3], 'sub':menu(raw[0])} for raw in fetch] </code></pre> <p>The data is taken from the sqlite3 table:</p> <pre><code>create table static ( id integer primary key autoincrement, parent integer, alias string not null, title string not null, text string not null, ord integer ); </code></pre> <p>Variable (menu_list) is transmitted to template in each route:</p> <pre><code>@app.route('/') def index(): menu_list = menu() [...] return render_template('index.tpl', **locals()) </code></pre> <p>Despite the fact that the code is more or less normal (except for prepared statements in a query to the database), the template is not very good:</p> <pre><code>&lt;nav role="navigation"&gt; {% for menu in menu_list %} &lt;li&gt; &lt;a{% if page_id == menu.id %} class="active"{% endif %} href="/{{ menu.alias }}"&gt;{{ menu.title }}&lt;/a&gt; {% if menu.sub %} &lt;ul&gt; {% for sub in menu.sub %} &lt;li&gt;&lt;a href="/{{ menu.alias }}/{{ sub.alias }}"&gt;{{ sub.title }}&lt;/a&gt; {% if sub.sub %} &lt;ul&gt; {% for subsub in sub.sub %} &lt;li&gt;&lt;a href="/{{ menu.alias }}/{{ sub.alias }}/{{ subsub.alias }}"&gt;{{ subsub.title }}&lt;/a&gt; {% endfor %} &lt;/ul&gt; {% endif %} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} &lt;/li&gt; {% endfor %} &lt;/nav&gt; </code></pre> <p>Is it possible to improve the existing code / output / logic?</p>
[]
[ { "body": "<p>In this code, at first I didn't see the \"danger\" until I scrolled to the right by accident:</p>\n\n<blockquote>\n<pre><code>def menu(parent_id=0, menutree=None):\n menutree = menutree or []\n cur = g.db.execute('select id, parent, alias, title, ord from static where parent=\"'+ str(parent_id) +'\" and ord&gt;0 order by ord')\n fetch = cur.fetchall()\n\n if not fetch:\n return None\n\n return [{'id':raw[0], 'parent':raw[1], 'alias':raw[2], 'title':raw[3], 'sub':menu(raw[0])} for raw in fetch]\n</code></pre>\n</blockquote>\n\n<p>In the <code>g.db.execute</code> statement you're embedding a parameter and we cannot know where the parameter comes from and if it was properly validated to prevent SQL injection. Two things to do here:</p>\n\n<ol>\n<li>Make the line shorter, especially when it contains potentially dangerous stuff in the far right</li>\n<li>Use prepared statements with <code>?</code> placeholder</li>\n</ol>\n\n<p>It's not clear what kind of database you're using, so you might need to edit, but it should be something like this, shorter and without embedded parameters:</p>\n\n<pre><code>cur = g.db.execute('select id, parent, alias, title, ord '\n 'from static where parent = ? and ord &gt; 0 '\n 'order by ord', parent_id)\n</code></pre>\n\n<p>Another small tip here, if you reverse the checking logic of <code>if not fetch</code> to <code>if fetch</code> at the end, you don't need to <code>return None</code>, as that's the default anyway, and the method will be a bit shorter:</p>\n\n<pre><code>def menu(parent_id=0, menutree=None):\n menutree = menutree or []\n cur = g.db.execute('select id, parent, alias, title, ord '\n 'from static where parent = ? and ord &gt; 0 '\n 'order by ord', parent_id)\n fetch = cur.fetchall()\n\n if fetch:\n return [{'id': raw[0], 'parent': raw[1], 'alias': raw[2],\n 'title': raw[3], 'sub': menu(raw[0])} for raw in fetch]\n</code></pre>\n\n<p>And a tiny thing, <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> dictates to put a space after the <code>:</code> in a <code>key:value</code> pair, like so: <code>key: value</code>.</p>\n\n<hr>\n\n<p>In this code:</p>\n\n<blockquote>\n<pre><code>@app.route('/')\ndef index():\n menu_list = menu()\n [...]\n return render_template('index.tpl', **locals())\n</code></pre>\n</blockquote>\n\n<p>I recommend to NOT include all <code>**locals()</code>, but use the list of variables you want to pass explicitly. We're all humans, one day you might accidentally expose something.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-19T20:04:51.980", "Id": "60509", "ParentId": "18614", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:12:00.830", "Id": "18614", "Score": "4", "Tags": [ "python", "flask" ], "Title": "Website menu with Flask" }
18614
<p>I have a string, where I am only interested in getting the numbers encapsulated in single quotes. </p> <p>For instance if I have the string "hsa456456 ['1', '2', ...]</p> <p>I only want the 1 and the 2 and whatever numbers follow</p> <p>To do this, I have the following code:</p> <pre><code>import re #pattern = re.compile("dog") #l = re.findall(pattern, "dog dog dog") #valuepattern=re.compile('\'\d{1,6}\'') valuepattern = re.compile('\'\d+\'') li = [] s = "hsa04012 [[['7039', '1956', '1398', '25'], ['7039', '1956', '1399', '25']], [['1839', '1956', '1398', '25'], ['1839', '1956', '1399', '25']], [['1399', '25']], [['1398', '25']], [['727738', '1956', '1398', '25'], ['727738', '1956', '1399', '25']], [['1956', '1398', '25'], ['1956', '1399', '25']], [['1950', '1956', '1398', '25'], ['1950', '1956', '1399', '25']], [['374', '1956', '1398', '25'], ['374', '1956', '1399', '25']], [['2069', '1956', '1398', '25'], ['2069', '1956', '1399', '25']], [['685', '1956', '1398', '25'], ['685', '1956', '1399', '25']]]" #if match: # print match.group() #else: # print "no match" l = re.findall(valuepattern, s) #print l for item in l: li.append(item.strip("'")) #print item for item in li: print item </code></pre> <p>My areas of interest is to minimize the number of lists. Right now, I use two l and li. I take the item from l and append it to li after stripping. I was curious if there was a way to accomplish this operation all within one list... without the need for li and then appending.</p>
[]
[ { "body": "<h3>New regex</h3>\n\n<p>If you change your regular expression to the following you won't need to even do <code>str.strip()</code></p>\n\n<pre><code>valuepattern = re.compile(\"'(\\d+)'\")\n</code></pre>\n\n<h3>List Comprehension</h3>\n\n<p>Alternatively if you don't want to do that, you could do the following. Currently you have:</p>\n\n<pre><code>for item in l:\n li.append(item.strip(\"'\"))\n</code></pre>\n\n<p>This can be replaced with a <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehension</a>:</p>\n\n<pre><code>l = [x.strip(\"'\") for x in l]\n</code></pre>\n\n<h3>Final Note</h3>\n\n<p>As you compile your regular expression, you can replace</p>\n\n<pre><code>re.findall(valuepattern, s)\n</code></pre>\n\n<p>with</p>\n\n<pre><code>valuepattern.findall(s)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:00:59.257", "Id": "18628", "ParentId": "18626", "Score": "2" } }, { "body": "<p>Well this is not the best, but kind of 'short and works'.</p>\n\n<pre><code>def try_parse(s):\n try: return int(s)\n except: return None\n\nls = [try_parse(x) for x in your_string.split(\"'\")]\nls = filter(lambda s: s is not None, ls)\n</code></pre>\n\n<p>Alternative, given your input is representative:</p>\n\n<pre><code>ls = eval(ls[find(\"[\"):]) # now fold into recursive list flattening...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:18:09.707", "Id": "29657", "Score": "0", "body": "I guess this works, but it doesn't feel like the best way to do it. It could also have problems if there are numeric values not in quotes, or if there is a stray quote somewhere. (i don't know how likely either of those scenarios are though...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:24:12.667", "Id": "29658", "Score": "0", "body": "I totally agree, but given the unknown input any method is likely to fail." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T20:13:12.663", "Id": "18630", "ParentId": "18626", "Score": "0" } } ]
{ "AcceptedAnswerId": "18628", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T19:39:43.483", "Id": "18626", "Score": "1", "Tags": [ "python", "regex" ], "Title": "Minimize Number of Lists" }
18626
<p>I have the following concise-ish (and working) approach to getting all the forward permutations of a list of string. So with the list: </p> <blockquote> <p>w = ["Vehicula", "Sem", "Risus", "Tortor"]</p> </blockquote> <p>the results should be:</p> <blockquote> <p>['Vehicula', 'Vehicula Sem', 'Vehicula Sem Risus', 'Vehicula Sem Risus Tortor', 'Sem', 'Sem Risus', 'Sem Risus Tortor', 'Risus', 'Risus Tortor', 'Tortor']</p> </blockquote> <p>To do this, we loop through each element, and perform an inner loop that looks ahead and saves slices of the remaining elements to a result array. </p> <pre><code>w = ["Vehicula", "Sem", "Risus", "Tortor"] results = [] i = 0 l = len(w) while i &lt; l: j, k = i, i + 1 while k &lt;= l: results.append(" ".join(w[j:k])) k = k + 1 i = i + 1 print results </code></pre> <p>With Python, I always feel like I'm missing a trick, so I'm curios to see if there are any native Python functions that will make this more efficient? </p> <p><strong>Edit</strong></p> <p>I tested all three with <code>timeit</code> and mine is definitely the slowest. I've got to get to grips with <code>itertools</code> - it is very powerful. </p> <pre><code>Verbose (Mine): 3.61756896973 Comprehensions: 3.02565908432 Itertools: 2.83112883568 </code></pre>
[]
[ { "body": "<p>This should work. I don't know if it is more readable than your approach though.</p>\n\n<pre><code>w = [\"Vehicula\", \"Sem\", \"Risus\", \"Tortor\"]\nresults = [' '.join(w[i:i+j+1]) for i in range(len(w)) for j in range(len(w)-i)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T13:04:19.827", "Id": "18658", "ParentId": "18656", "Score": "1" } }, { "body": "<p>Here's an alternative approach using <a href=\"http://docs.python.org/2/library/itertools.html#itertools.combinations\"><code>itertools.combinations</code></a> to generate the (start, end) pairs:</p>\n\n<pre><code>from itertools import combinations\nw = \"Vehicula Sem Risus Tortor\".split()\nresults = [' '.join(w[i:j]) for i, j in combinations(range(len(w) + 1), 2)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T13:18:20.143", "Id": "18659", "ParentId": "18656", "Score": "5" } } ]
{ "AcceptedAnswerId": "18659", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T12:50:35.500", "Id": "18656", "Score": "3", "Tags": [ "python", "algorithm", "combinatorics" ], "Title": "Getting all (forward) permutations of a list of strings" }
18656
<p>This does the job, but is not especially elegant.</p> <p>What is the preferred Pythonic idiom to my childish nests?</p> <pre><code>def bytexor(a, b): res = "" for x, y in zip(a, b): if (x == "1" and y == "0") or (y =="1" and x == "0"): res += "1" else: res += "0" return res def get_all(): res = [] bit = ["0","1"] for i in bit: for j in bit: for k in bit: for l in bit: res.append(i+j+k+l) return res if __name__=="__main__": for k0 in get_all(): for k1 in get_all(): for k2 in get_all(): for k3 in get_all(): for k4 in get_all(): if bytexor(bytexor(k0, k2), k3) == "0011": if bytexor(bytexor(k0, k2), k4) == "1010": if bytexor(bytexor(bytexor(k0,k1),k2),k3) == "0110": print k0, k1, k2, k3, k4 print bytexor(bytexor(bytexor(k0, k1),k2),k4) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T07:52:44.243", "Id": "30024", "Score": "0", "body": "What is the code supposed to be doing? You're apparently trying to get all combinations of 4-bit binary numbers... but what are you trying to get from that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T10:31:20.897", "Id": "30030", "Score": "0", "body": "@JeffMercado the problem was homework. There was an encryption algorithm given and some sample cyphertext - this code does an exhaustive search for keys that fit with the ciphertext, and encrypts a message using the same algorithm for each valid key." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-27T14:00:45.253", "Id": "30560", "Score": "0", "body": "I know this is not really what you were looking for, but you could leave the loops and optimize their runtime using *cython* or *numba*." } ]
[ { "body": "<p>Depending on what you are ultimately doing, probably the neatest way is to use a standard module, <code>itertools</code>. Using <code>get_all</code> as an example:</p>\n\n<pre><code>import itertools\n\ndef get_all_bitpatterns():\n res = []\n bit = [ \"0\", \"1\" ]\n for z in itertools.product( bit, bit, bit, bit ):\n res.append( \"\".join(z) )\n return res\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T12:06:00.437", "Id": "30034", "Score": "2", "body": "`product` takes a `repeat` argument, which would be useful here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T12:14:00.510", "Id": "30036", "Score": "2", "body": "You could also use `bit = '01'` as string is iterable in Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T13:30:34.943", "Id": "30038", "Score": "4", "body": "`return [\"\".join(z) for z in itertools.product(bit, repeat=4)]`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T09:07:33.487", "Id": "18829", "ParentId": "18828", "Score": "6" } }, { "body": "<p>To convert an integer to a bit string with a particular number of digits, use <a href=\"http://docs.python.org/2/library/stdtypes.html#str.format\"><code>string.format</code></a> with the <a href=\"http://docs.python.org/2/library/string.html#format-specification-mini-language\"><code>b</code> format type</a>. For example:</p>\n\n<pre><code>&gt;&gt;&gt; ['{0:04b}'.format(i) for i in range(16)]\n['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',\n '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']\n</code></pre>\n\n<p>But really it looks to me as though you don't want to be working with bit strings at all. You just want to be working with integers.</p>\n\n<p>So instead of <code>get_all</code>, just write <code>range(16)</code> and instead of <code>bytexor</code>, write <code>^</code>. Your entire program can be written like this:</p>\n\n<pre><code>from itertools import product\nfor a, b, c, d, e in product(range(16), repeat=5):\n if a ^ c ^ d == 3 and a ^ c ^ e == 10 and a ^ b ^ c ^ d == 6:\n print a, b, c, d, e, a ^ b ^ c ^ e\n</code></pre>\n\n<p>(This will also run a lot faster without all that fiddling about with strings.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T16:11:51.460", "Id": "30057", "Score": "0", "body": "Thanks.. I can't believe it took me all that to write what could be done with five lines :s" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T12:02:08.500", "Id": "18835", "ParentId": "18828", "Score": "29" } }, { "body": "<p>This is <strong><em>just</em></strong> a little bit improved edition of '<strong>Glenn Rogers</strong>' answer ;)\nSimply work around <code>bit</code>, say <code>bit='abcd'</code> and number <code>n</code>.</p>\n\n<pre><code>from itertools import product\n\ndef AllBitPatterns(bit='01',n=2):\n out = []\n for z in product(bit,repeat=n*len(bit)): #thanks to a comment\n out.append(''.join(z))\n return out\n\nprint AllBitPatterns()\nprint AllBitPatterns(n=3)\nprint AllBitPatterns(bit='-~')\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>&gt;&gt;&gt; \n['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']\n['000000', '000001', '000010', '000011', '000100', '000101', '000110', '000111', '001000', '001001', '001010', '001011', '001100', '001101', '001110', '001111', '010000', '010001', '010010', '010011', '010100', '010101', '010110', '010111', '011000', '011001', '011010', '011011', '011100', '011101', '011110', '011111', '100000', '100001', '100010', '100011', '100100', '100101', '100110', '100111', '101000', '101001', '101010', '101011', '101100', '101101', '101110', '101111', '110000', '110001', '110010', '110011', '110100', '110101', '110110', '110111', '111000', '111001', '111010', '111011', '111100', '111101', '111110', '111111']\n['----', '---~', '--~-', '--~~', '-~--', '-~-~', '-~~-', '-~~~', '~---', '~--~', '~-~-', '~-~~', '~~--', '~~-~', '~~~-', '~~~~']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-31T07:49:28.897", "Id": "302048", "Score": "0", "body": "This answer is not mine, please remove it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T12:19:19.730", "Id": "18836", "ParentId": "18828", "Score": "0" } }, { "body": "<p><a href=\"https://stackoverflow.com/a/12403964/1273830\">I have answered awhile ago to this very type of question</a>. This is a very simple problem. You should not complicate it at all with iterators.</p>\n\n<p>The trick is that the bit pattern you are seeking for is actually the bits of numbers incremented by 1!</p>\n\n<p>Something like:</p>\n\n<pre><code>def get_all():\n res = []\n for i in range(16):\n # get the last four bits of binary form i which is an int\n bin(i) # a string like '0b0000' - strip '0b', 0 pad it to 4 length\n</code></pre>\n\n<p>I am not really the python guy, but I hope the idea is clear. Equivalent Java code:</p>\n\n<pre><code>int len = 3; // your number of for loops\nint num = (int)Math.pow(2, len);\nfor(int i=0; i&lt;num; i++){\n // https://stackoverflow.com/a/4421438/1273830\n System.out.println(String.format(\"%\"+len+\"s\", Integer.toBinaryString(i)).replace(' ', '0'));\n}\n</code></pre>\n\n<p>Happy coding.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T13:18:26.130", "Id": "18839", "ParentId": "18828", "Score": "-1" } } ]
{ "AcceptedAnswerId": "18835", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T07:17:35.717", "Id": "18828", "Score": "14", "Tags": [ "python", "combinatorics", "bitwise" ], "Title": "Exhaustive search for encryption keys" }
18828
<p>Ok, so given the string:</p> <pre><code>s = "Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School" </code></pre> <p>I want to retrieve:</p> <pre><code>[ ["Born"], ["Honolulu", "Hawaii", "Obama"], ["Columbia", "University"] ...] </code></pre> <p>Assuming that we have successfully tokenised the original string, my first psuedocodish attempt was: </p> <pre><code>def retrieve(tokens): results = [] i = 0 while i &lt; len(tokens): if tokens[i][0].isupper(): group = [tokens[i]] j = i + 1 while i + j &lt; len(tokens): if tokens[i + j][0].isupper(): group.append(tokens[i + j]) j += 1 else: break i += 1 return results </code></pre> <p>This is actually quite fast (well compared to some of my trying-to-be-pythonic attempts):</p> <blockquote> <p>Timeit: 0.0160551071167 (1000 cycles)</p> </blockquote> <p>Playing around with it, the quickest I can get is:</p> <pre><code>def retrive(tokens): results = [] group = [] for i in xrange(len(tokens)): if tokens[i][0].isupper(): group.append(tokens[i]) else: results.append(group) group = [] results.append(group) return filter(None, results) </code></pre> <blockquote> <p>Timeit 0.0116229057312</p> </blockquote> <p>Are there any more concise, pythonic ways to go about this (with similar execution times)?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T18:47:53.930", "Id": "30257", "Score": "0", "body": "What is your question exactly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T18:53:24.190", "Id": "30258", "Score": "0", "body": "Yea, I forgot the last line ;) Are there any more concise, pythonic ways to go about this (with similar execution times)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-25T23:12:12.580", "Id": "30333", "Score": "0", "body": "Your optimized retrive() function doesn't seem to work as expected. I get: ``[['B'], ['H'], ['H'], ['O'], ['C'], ['U'], ['H'], ['L'], ['S']]`` when I run it verbatim." } ]
[ { "body": "<p>Here is a solution using regular expressions</p>\n\n<pre><code>import re\n\ndef reMethod(pat, s):\n return [m.group().split() for m in re.finditer(pat, s)]\n\nif __name__=='__main__':\n from timeit import Timer\n s = \"Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School\"\n pat = re.compile(r\"([A-Z][a-z]*)(\\s[A-Z][a-z]*)*\")\n t1 = Timer(lambda: reMethod(pat, s))\n print \"time:\", t1.timeit(number=1000)\n print \"returns:\", reMethod(pat, s)\n</code></pre>\n\n<p>Ouptut:</p>\n\n<pre><code>time: 0.0183469604187\nreturns: [['Born'], ['Honolulu', 'Hawaii', 'Obama'], ['Columbia', 'University'], ['Harvard', 'Law', 'School']]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T19:31:37.290", "Id": "30263", "Score": "0", "body": "I never thought about using regexs actually, this is a good alternative and the performance is around the same" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T19:55:47.747", "Id": "30266", "Score": "0", "body": "Yeah, it didn't turn out to be quite as fast, but it felt a waste not to post it once I had it coded up." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T19:16:15.740", "Id": "18968", "ParentId": "18965", "Score": "3" } }, { "body": "<p>A trivial optimisation that iterates on the tokens instead of by index (remember that in Python lists are iterables, it's unPythonic to iterate a list by index):</p>\n\n<pre><code>def retrieve(tokens):\n results = []\n group = []\n for token in tokens:\n if token[0].isupper():\n group.append(token)\n else:\n if group: # group is not empty\n results.append(group)\n group = [] # reset group\n return results\n</code></pre>\n\n<p>A solution like @JeremyK's with a list comprehension and regular expressions is always going to be more compact. I am only giving this answer to point out how lists should be iterated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T19:27:43.923", "Id": "30262", "Score": "0", "body": "Thanks - this is an improvement alright. I thought that using `xrange` would be faster as it doesn't return items, just index values, but thinking about it if you are using the values of what's being iterated it's faster" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T19:18:27.160", "Id": "18969", "ParentId": "18965", "Score": "4" } }, { "body": "<p>If you asked me, a pythonic solution would be the most readable solution. However in general, readable solutions are not always going to be the fastest. You can't have both, these are conflicting goals.</p>\n\n<p>Pedro has covered what changes you can do to make it bit more pythonic so I won't repeat that. I can't think of anything else you can do to optimize that any further. However if you want a more purely pythonic solution (IMO), you can do this.</p>\n\n<p>Use <a href=\"http://docs.python.org/2/library/itertools.html#itertools.groupby\" rel=\"nofollow\"><code>itertools.groupby</code></a>. It groups consecutive items together with a common key into groups. Group them by whether they are capitalized and filter out the non-capitalized words.</p>\n\n<p>This could be done as a one-liner but for readability, I'd write it like this:</p>\n\n<pre><code>from itertools import groupby\n\ninput_str = 'Born in Honolulu Hawaii Obama is a graduate of ' +\n 'Columbia University and Harvard Law School'\nwords = input_str.split()\ndef is_capitalized(word):\n return bool(word) and word[0].isupper()\nquery = groupby(words, key=is_capitalized)\nresult = [list(g) for k, g in query if k]\n</code></pre>\n\n<p>This would run roughly twice as slow as your implementation, based on my tests on 1000 iterations.</p>\n\n<pre>\n0.0130150737235 # my implementation\n0.0052368790507 # your implementation\n</pre>\n\n<p>You decide what your goals are.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-25T03:57:27.140", "Id": "30295", "Score": "0", "body": "I think `isCapitalized` could be written more simply as `word[:1].isupper()`. (Although I think `is_capitalized` would be a more standard name.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-25T04:54:33.437", "Id": "30297", "Score": "0", "body": "Ah you're right about the name, I've been doing too much Java work lately. ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T22:25:07.473", "Id": "18972", "ParentId": "18965", "Score": "3" } }, { "body": "<p>I get a slight improvement by tweaking your <code>retrive()</code> function:</p>\n\n<pre><code>def retrieve1(tokens):\n results = []\n group = []\n for i in xrange(len(tokens)):\n if tokens[i][0].isupper():\n group.append(tokens[i])\n else:\n results.append(group)\n group = []\n results.append(group)\n return filter(None, results)\n\ndef retrieve2(tokens):\n results = []\n group = []\n for token in tokens:\n if token[0].isupper():\n group.append(token)\n elif group:\n results.append(group)\n group = []\n if group:\n results.append(group)\n return results\n\ns = \"Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School\"\n\nif __name__ == \"__main__\":\n import timeit\n print timeit.timeit('retrieve1(s.split(\" \"))', setup=\"from __main__ import (retrieve1, s)\", number=100000)\n print timeit.timeit('retrieve2(s.split(\" \"))', setup=\"from __main__ import (retrieve2, s)\", number=100000)\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>1.00138902664 (retrieve1)\n0.744722127914 (retrieve2)\n</code></pre>\n\n<p>It's not necessary to iterate via <code>xrange()</code> as you can iterate <code>tokens</code> directly, and you need only append <code>group</code> to <code>results</code> if <code>group</code> is not an empty list -- no need to <code>filter()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-26T00:15:22.910", "Id": "19006", "ParentId": "18965", "Score": "1" } } ]
{ "AcceptedAnswerId": "18969", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T17:34:43.633", "Id": "18965", "Score": "3", "Tags": [ "python", "algorithm" ], "Title": "Retrieving lists of consecutive capitalised words from a list" }
18965
<p>I have written a Python function which matches all files in the current directory with a list of extension names. It is working correctly.</p> <pre><code>import os, sys, time, re, stat def matchextname(extnames, filename): # Need to build the regular expression from the list myregstring = "" for index in range(len(extnames)): # r1 union r2 and so on operator is pipe(|) # $ is to match from the end if index &lt; len(extnames) - 1: myregstring = myregstring + extnames[index] + '$' + '|' else: myregstring = myregstring + extnames[index] + '$' # getting regexobject myregexobj = re.compile(myregstring) # Now search searchstat = myregexobj.search(filename) if searchstat: print 'Regex', filename </code></pre> <p>It is called like this:</p> <pre><code>if __name__ == '__main__': fileextensions = ['\.doc', '\.o', '\.out', '\.c', '\.h'] try: currentdir = os.getcwd() except OSError: print 'Error occured while getting current directory' sys.exit(1) for myfiles in os.listdir(currentdir): matchextname(fileextensions, myfiles) </code></pre> <p>Could you please review the code and suggest if there is any better way of doing this, or share any other comments related to errors/exception handling which are missing - or anything else in terms of logic?</p>
[]
[ { "body": "<p><a href=\"http://docs.python.org/2/library/stdtypes.html#str.endswith\"><code>.endswith()</code></a> accepts a tuple:</p>\n\n<pre><code>#!usr/bin/env python\nimport os\n\nfileextensions = ('.doc', '.o', '.out', '.c', '.h')\nfor filename in os.listdir(os.curdir):\n if filename.endswith(fileextensions):\n print(filename)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T18:15:32.110", "Id": "30551", "Score": "0", "body": "Sebastian. Thanks a lot for your help. This is quite a nice approach, which you have shown" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T11:29:36.507", "Id": "19106", "ParentId": "19103", "Score": "7" } }, { "body": "<p>I think the way to code this, that most clearly indicates what you are doing, is to use <a href=\"http://docs.python.org/2/library/os.path.html#os.path.splitext\" rel=\"nofollow\"><code>os.path.splitext</code></a> to get the extension, and then look it up in a <a href=\"http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset\" rel=\"nofollow\">set</a> of extensions:</p>\n\n<pre><code>import os.path\nextensions = set('.doc .o .out .c .h'.split())\n_, ext = os.path.splitext(filename)\nif ext in extensions:\n print(filename)\n</code></pre>\n\n<p>A couple of other comments on your code:</p>\n\n<ol>\n<li><p>There's no need to catch the <code>OSError</code> if all you're going to do is print a message and exit. (This will happen in any case if the exception is uncaught, so why go to the extra trouble?)</p></li>\n<li><p>If you actually want to build up a regular expression, then do it using <a href=\"http://docs.python.org/2/library/stdtypes.html#str.join\" rel=\"nofollow\"><code>str.join</code></a>. This avoids the need to have a special case at the end:</p>\n\n<pre><code>extensions = r'\\.doc \\.o \\.out \\.c \\.h'.split()\nmyregexobj = re.compile('(?:{})$'.format('|'.join(extensions)))\n</code></pre>\n\n<p>(Whenever you find yourself writing a loop over the <em>indexes</em> to a sequence, then you should think about rewriting it to loop over the <em>elements</em> of the sequence instead: this nearly always results in clearer and shorter code.)</p></li>\n<li><p>If you want to build a regular expression that exactly matches a string literal, you should use <a href=\"http://docs.python.org/2/library/re.html#re.escape\" rel=\"nofollow\"><code>re.escape</code></a> to escape the special characters, instead of escaping each one by hand. For example:</p>\n\n<pre><code>extensions = '.doc .o .out .c .h'.split()\nmyregexobj = re.compile('(?:{})$'.format('|'.join(map(re.escape, extensions))))\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T18:18:51.373", "Id": "30552", "Score": "0", "body": "Thanks Gareth. Your explanation and all the methods that you have shared are excellent for learning. These really helped me to understand many new and better techniques. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T12:39:57.533", "Id": "19108", "ParentId": "19103", "Score": "3" } } ]
{ "AcceptedAnswerId": "19108", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-28T11:20:29.880", "Id": "19103", "Score": "3", "Tags": [ "python", "regex" ], "Title": "Python function to match filenames with extension names" }
19103
<p>I have verified that both of my following functions successfully find prime numbers. I was pretty sure the function called <code>is_prime_new</code> would be faster than <code>is_prime_old</code>; however, after benchmarking (mainly consisting of generating huge lists of primes), I found this to be significantly false and I'm wondering why this may be.</p> <p>I had two main reasons for thinking that <code>is_prime_new</code> would be a better algorithm than its counterpart:</p> <ul> <li><p><code>is_prime_new</code> does more checks for non-primailty early, thus eliminating numbers before iteration</p></li> <li><p>It iterates in steps of 6, whereas its counterpart iterates in steps of 2, both to the same value <code>sqrt(n)+1</code></p></li> </ul> <p>Could anyone explain to me why the newer function is less optimized, and possibly debunk my above assumptions? Thank you.</p> <pre><code>def is_prime_new(n): if n &lt; 2: return False if n == 2 or n == 3: return True if n%2 == 0 or n%3 == 0: return False sqr = math.sqrt(n) if sqr == int(sqr): return False i = 1 while i*6 &lt; sqr+1: if n % (i*6-1) == 0 or n % (i*6+1) == 0: return False i += 1 return True def is_prime_old(n): if n &lt; 2: return False if n == 2: return True if n%2 == 0: return False for i in xrange(3, int(math.sqrt(n)+1), 2): if not n%i: return False return True </code></pre>
[]
[ { "body": "<p>can you test the following (slightly optimized) version?</p>\n\n<pre><code>def is_prime_new(n):\n if n &lt; 2: return False\n if n == 2 or n == 3: return True\n if n%2 == 0 or n%3 == 0: return False\n sqr = math.sqrt(n)\n if sqr == int(sqr): return False\n sqr = int(sqr) + 1\n\n i = 6\n while i &lt; sqr:\n if n % (i-1) == 0 or n % (i+1) == 0: return False\n i += 6\n\n return True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T19:15:11.310", "Id": "30971", "Score": "0", "body": "@almaz, Thank you. These suggestions did speed up my new function, but the old one is still faster! And my question (in its two parts) was \"why is the old one faster?\", \"and are my 2 assumptions invalid?\" Do you have anything to say about either of these questions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T19:27:25.943", "Id": "30974", "Score": "0", "body": "Please post the test code you're running" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T21:32:44.107", "Id": "30988", "Score": "0", "body": "You didn't post how you measure performance, so the first thing I assumed was that you introduced unnecessary calculations, so I suggested you the variant where these calculations were stripped" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T08:53:57.803", "Id": "19280", "ParentId": "19278", "Score": "2" } } ]
{ "AcceptedAnswerId": "19557", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T05:23:42.470", "Id": "19278", "Score": "3", "Tags": [ "python", "optimization", "algorithm", "primes" ], "Title": "Naive prime finder, unexpected behavior in Python" }
19278
<p>I have been reading some NumPy guides but can't seem to figure it out. My TA told me I should be able to speed up my code by using a NumPy array instead of a <code>for</code> loop in the following segment of code.</p> <pre><code>for neighbor in get_neighbors(estimates,i,j): pXgivenX_ *= edge_model(True,neighbor)*observation_model(obs,True) pX_givenX_ *= edge_model(False,neighbor)*observation_model(obs,False) </code></pre> <p>Here is the entire code of the method it is in:</p> <pre><code>def gibbs_segmentation(image, burnin, collect_frequency, n_samples): """ Uses Gibbs sampling to segment an image into foreground and background. Inputs ------ image : a numpy array with the image. Should be Nx x Ny x 3 burnin : Number of iterations to run as 'burn-in' before collecting data collect_frequency : How many samples in between collected samples n_samples : how many samples to collect in total Returns ------- A distribution of the collected samples: a numpy array with a value between 0 and 1 (inclusive) at every pixel. """ (Nx, Ny, _) = image.shape total_iterations = burnin + (collect_frequency * (n_samples - 1)) pixel_indices = list(itertools.product(xrange(Nx),xrange(Ny))) # The distribution that you will return distribution = np.zeros( (Nx, Ny) ) # Initialize binary estimates at every pixel randomly. Your code should # update this array pixel by pixel at each iteration. estimates = np.random.random( (Nx, Ny) ) &gt; .5 # PreProcessing preProObs = {} for (i,j) in pixel_indices: preProObs[(i,j)] = [] preProObs[(i,j)].append(observation_model(image[i][j],False)) preProObs[(i,j)].append(observation_model(image[i][j],True)) for iteration in xrange(total_iterations): # Loop over entire grid, using a random order for faster convergence random.shuffle(pixel_indices) for (i,j) in pixel_indices: pXgivenX_ = 1 pX_givenX_ = 1 for neighbor in get_neighbors(estimates,i,j): pXgivenX_ *= edge_model(True,neighbor)*preProObs[(i,j)][1] pX_givenX_ *= edge_model(False,neighbor)*preProObs[(i,j)][0] estimates[i][j] = np.random.random() &gt; pXgivenX_/(pXgivenX_+pX_givenX_) if iteration &gt; burnin and (iteration-burnin)%collect_frequency == 0: distribution += estimates return distribution / n_samples def edge_model(label1, label2): """ Given the values at two pixels, returns the edge potential between those two pixels. Hint: there might be a more efficient way to compute this for an array of values using numpy! """ if label1 == label2: return ALPHA else: return 1-ALPHA </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:22:04.067", "Id": "30932", "Score": "1", "body": "What is `neighbor`? What does `observation_model(obs,True)` return?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:29:42.743", "Id": "30933", "Score": "0", "body": "neighbor is a boolean corresponding to whether the pixel is currently believed to be in the foreground or background.\nobservation_model(obs,True) returns a number corresponding to the probability of observing True given that you are at obs (where True corresponds to the pixel being in the foreground)." } ]
[ { "body": "<p>Since this is homework, I won't give you the exact answer, but here are some hints. </p>\n\n<ol>\n<li><p><code>==</code> is overloaded in numpy to return an array when you pass in an array. So you can do things like this: </p>\n\n<pre><code>&gt;&gt;&gt; numpy.arange(5) == 3\narray([False, False, False, True, False], dtype=bool)\n&gt;&gt;&gt; (numpy.arange(5) == 3) == False\narray([ True, True, True, False, True], dtype=bool)\n</code></pre></li>\n<li><p>You can use boolean arrays to assign to specific locations in an array. For example:</p>\n\n<pre><code>&gt;&gt;&gt; mostly_true = (numpy.arange(5) == 3) == False\n&gt;&gt;&gt; empty = numpy.zeros(5)\n&gt;&gt;&gt; empty[mostly_true] = 5\n&gt;&gt;&gt; empty\narray([ 5., 5., 5., 0., 5.])\n</code></pre></li>\n<li><p>You can also negate boolean arrays; together, these facts allow you to conditionally assign values to an array. (<a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\"><code>numpy.where</code></a> can be used to do something similar.):</p>\n\n<pre><code>&gt;&gt;&gt; empty[~mostly_true] = 1\n&gt;&gt;&gt; empty\narray([ 5., 5., 5., 1., 5.])\n</code></pre></li>\n<li><p>You can then multiply those values by other values:</p>\n\n<pre><code>&gt;&gt;&gt; empty * numpy.arange(5)\narray([ 0., 5., 10., 3., 20.])\n</code></pre></li>\n<li><p>And many different numpy functions (really <a href=\"http://docs.scipy.org/doc/numpy/reference/ufuncs.html\">ufuncs</a>) provide a <code>reduce</code> method that applies the function along the entire array:</p>\n\n<pre><code>&gt;&gt;&gt; results = empty * numpy.arange(5)\n&gt;&gt;&gt; numpy.multiply.reduce(results)\n0.0\n</code></pre></li>\n</ol>\n\n<p>You should be able to completely eliminate that <code>for</code> loop using only the above techniques. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:53:26.353", "Id": "30934", "Score": "0", "body": "If it is True then I want to multiply by ALPHA and if it is false I multiply by 1-ALPHA but how can I do this in one line?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:54:01.970", "Id": "30935", "Score": "0", "body": "Nevermind I looked at np.where" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:40:59.840", "Id": "19330", "ParentId": "19329", "Score": "6" } } ]
{ "AcceptedAnswerId": "19330", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T02:31:53.703", "Id": "19329", "Score": "3", "Tags": [ "python", "image", "numpy", "vectorization" ], "Title": "Using Gibbs sampling to segment an image" }
19329
<pre><code>def dec_to_bin(ip): ip_array = ip.split(".") ip_array = filter(None, ip_array) if len(ip_array) != 4: return "Invalid IP Address format" else: ip_bin = [] for x in range(len(ip_array)): # Formatting example referenced from: # http://stackoverflow.com/a/10411108/1170681 ip_bin.append('{0:08b}'.format(int(ip_array[x]))) ip_bin.append(".") ip_bin.pop() return ''.join(ip_bin) </code></pre> <p>This is a simple parser that will take a IP address in decimal form and convert it into its binary representation.</p> <p>I'm looking for any tips on coding styles and improving the efficiency of the code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T19:16:57.090", "Id": "31096", "Score": "0", "body": "Beware: This will not work for IPv6." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T11:44:23.653", "Id": "54808", "Score": "0", "body": "@luiscubal: [this solution supports both ipv4 and ipv6 addresses](http://codereview.stackexchange.com/a/34093/6143)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T14:54:26.677", "Id": "54811", "Score": "0", "body": "How does `split('.')` and `append(\".\")` for addresses that use `:` instead of `.`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T16:54:53.887", "Id": "54812", "Score": "0", "body": "@luiscubal: click the link" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T22:28:25.513", "Id": "56815", "Score": "0", "body": "@J.F.Sebastian I've read that answer and I still don't understand how. If nothing else, because your answer is very different from the code in the question. `::1`.split('.') (a valid IPv6 address) returns `['::1']`. The len is 1, not 4, so it returns \"Invalid IP Address format\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T22:33:35.973", "Id": "56816", "Score": "0", "body": "@luiscubal: there is no `.split()` in my code. \"this solution\" refers to [my answer](http://codereview.stackexchange.com/a/34093/6143)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T22:38:36.383", "Id": "56817", "Score": "0", "body": "@J.F.Sebastian Ah, sorry. I misinterpreted your comment." } ]
[ { "body": "<pre><code>def dec_to_bin(ip):\n\n ip_array = ip.split(\".\")\n ip_array = filter(None, ip_array)\n</code></pre>\n\n<p>Why do you need to filter it?</p>\n\n<pre><code> if len(ip_array) != 4:\n return \"Invalid IP Address format\"\n</code></pre>\n\n<p>Never return strings to indicate errors, raise an exception</p>\n\n<pre><code> else:\n ip_bin = []\n\n for x in range(len(ip_array)):\n</code></pre>\n\n<p>Use <code>for ip_element in ip_array:</code>, you should almost never have to iterate over <code>range(len(...))</code>.</p>\n\n<pre><code> # Formatting example referenced from: \n # http://stackoverflow.com/a/10411108/1170681\n\n ip_bin.append('{0:08b}'.format(int(ip_array[x])))\n</code></pre>\n\n<p>What happens if the user put something else besides numbers in there? I'd suggest matching the ip address against a regular expression to make it more robust.</p>\n\n<pre><code> ip_bin.append(\".\")\n\n ip_bin.pop()\n return ''.join(ip_bin)\n</code></pre>\n\n<p>Instead use <code>'.'join(ip_bin)</code> and don't try putting the '.' in the list. It'll be simpler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:25:38.947", "Id": "19391", "ParentId": "19388", "Score": "3" } }, { "body": "<p><strong>Code simplification and related:</strong></p>\n\n<p>Line 4: remove line 3 and replace line 4 with</p>\n\n<pre><code>ip_array = filter(None, ip.split('.'))\n</code></pre>\n\n<p>Line 7:\nCreate an exception, to prevent that a caller gets a string of error instead of the actual result.</p>\n\n<p>Line 12: assuming this is not python3, it's better if you use xrange() instead of range(), because range would create an actual list listing all the items in specified range. xrange(), instead, returns the next item in the sequence without creating the list. This behaviour is the same as the range() function in python3.\nAnyway, for your purposes changing it with:</p>\n\n<pre><code>for el in ip_array:\n ip_bin.append('{0:08b}'.format(int(el)))\n</code></pre>\n\n<p>or, even better:</p>\n\n<pre><code>ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]\n</code></pre>\n\n<p>Last line:\ninstead of appending the \".\" after each element, join over the dot:</p>\n\n<pre><code>return '.'.join(ip_bin)\n</code></pre>\n\n<p><strong>Style:</strong>\nPursue consistency in all the code: if you use double-quotes for defining strings, use them everywhere, same thing with single-quotes (which i personally prefer for strings, reserving double ones for docstrings).</p>\n\n<p>Reassuming:</p>\n\n<pre><code>def dec_to_bin(ip):\n\n ip_array = filter(None, ip.split('.'))\n\n if len(ip_array) != 4:\n raise NotValidIPException('Invalid IP Address format.')\n else:\n ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]\n return '.'.join(ip_bin)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:38:38.313", "Id": "19392", "ParentId": "19388", "Score": "5" } }, { "body": "<p>In Python 3.3:</p>\n\n<pre><code>import ipaddress\n\ndec_to_bin = lambda ip: bin(int(ipaddress.ip_address(ip)))\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/4017219/4279\">It supports both ip4 and ip6</a>.</p>\n\n<p>On older Python versions, you could use <code>socket</code> and <code>struct</code> modules. <a href=\"https://stackoverflow.com/a/9539079/4279\">To convert ipv4 address</a>:</p>\n\n<pre><code>import socket\nimport struct\n\ndec_to_bin = lambda ip4: bin(struct.unpack('!I', socket.inet_pton(socket.AF_INET, ip4))[0])\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt;&gt;&gt; dec_to_bin('192.168.1.1')\n'0b11000000101010000000000100000001'\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/11895244/4279\">To convert ipv6 address</a>:</p>\n\n<pre><code>import socket\nimport struct\n\ndef int_from_ipv6(addr):\n hi, lo = struct.unpack('!QQ', socket.inet_pton(socket.AF_INET6, addr))\n return (hi &lt;&lt; 64) | lo\n\ndec_to_bin = lambda ip6: bin(int_from_ipv6(ip6))\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt;&gt;&gt; dec_to_bin(\"2002:c0a8:0101::\").rstrip('0')\n'0b1000000000001011000000101010000000000100000001'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T01:19:54.793", "Id": "57095", "Score": "1", "body": "Why are you defining it as a `lambda` instead of using `def`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T01:51:46.210", "Id": "57096", "Score": "0", "body": "no reason. It is slightly more convenient to work with in a plain REPL." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T11:43:47.620", "Id": "34093", "ParentId": "19388", "Score": "1" } } ]
{ "AcceptedAnswerId": "19392", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T14:50:41.837", "Id": "19388", "Score": "5", "Tags": [ "python", "converting", "ip-address" ], "Title": "Decimal-to-binary converter for IP addresses" }
19388
<p>Here is Python code written to perform the following operations:</p> <ol> <li>Find each occurrence of a three-letter sequence in a character array (e.g. a sequence such as <code>('a','b','c')</code>), including overlapping sequences of up to 2 shared characters.</li> <li>Count the characters between the start of each sequence and the start of all identical sequences following it.</li> <li>Every time the same number of characters results from #2, increment a counter for that specific number of characters (regardless of which character sequence caused it).</li> <li>Return a dictionary containing all accumulated counters for character distances.</li> </ol> <p></p> <pre><code>counts = {} # repeating groups of three identical chars in a row for i in range(len(array)-2): for j in range(i+1,len(array)-2): if ((array[i] == array[j]) &amp; (array[i+1] == array[j+1]) &amp; (array[i+2] == array[j+2])): if counts.has_key(j-i) == False: counts[j-i] = 1 else: counts[j-i] += 1 </code></pre> <p>This code was originally written in another programming language, but I would like to apply any optimizations or improvements available in Python.</p>
[]
[ { "body": "<p>Instead of taking three elements at a time and comparing them to every other three elements, which takes O(n<sup>2</sup>) comparisons, you can use the following, which only requires traversing the array once:</p>\n\n<pre><code>from collections import defaultdict\n\ncounts = defaultdict(int)\nfor i in xrange(len(string) - 2):\n counts[tuple(string[i:i+3])] += 1\n</code></pre>\n\n<p>Using <a href=\"https://stackoverflow.com/questions/5878403/python-equivalent-to-rubys-each-cons\">this answer</a> about a Python equivalent to Ruby's <a href=\"http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_cons\" rel=\"nofollow noreferrer\">each_cons</a>, you can make this even nicer, though I don't know about the performance.</p>\n\n<p>As the array contains characters, you may as well call it a string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T12:57:33.280", "Id": "31155", "Score": "0", "body": "This doesn't do the same thing as the OP's code: in his `counts` dictionary the keys are the distance between the repetitions, whereas in yours the keys are the repeated triples." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:30:49.377", "Id": "19436", "ParentId": "19409", "Score": "0" } }, { "body": "<p>You can use simple python dictionary and list comprehensions to achieve your goal:</p>\n\n<pre><code>import re\nstring = \"test test test test test\"\naTuplePositions = {string[y:y+3]:[m.start() for m in re.finditer(''.join([string[y],'(?=',string[y+1:y+3],')']), string)] for y in range(len(string)-2) }\naTupleDistances = [t-u for z in aTuplePositions for a,u in enumerate(aTuplePositions[z]) for t in aTuplePositions[z][a+1:]]\ncounts = {y:aTupleDistances.count(y) for y in aTupleDistances if y &gt;= 0}\ncounts # returns {10: 12, 20: 2, 5: 17, 15: 7}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T12:58:12.237", "Id": "31156", "Score": "0", "body": "This doesn't do the same thing as the OP's code: in his `counts` dictionary the keys are the distance between the repetitions, whereas in yours the keys are the repeated triples." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T03:14:25.893", "Id": "31178", "Score": "0", "body": "The OP failed to phrase the question correctly, so downvote the question rather than my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T05:09:36.630", "Id": "31179", "Score": "0", "body": "@GarethRees I fixed the difference between my answer and the answer the OP wanted (but failed to correctly request)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T19:46:43.097", "Id": "31341", "Score": "0", "body": "@Barbarrosa sorry for misunderstanding, now I know that I have to formulate the questions more clearly, so I hope there will be no such problems. your answer is also very interesting, and I take valuable information from both of you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T05:20:23.183", "Id": "19446", "ParentId": "19409", "Score": "0" } }, { "body": "<h3>1. Improving the code</h3>\n\n<p>Here are some ways in which you could improve your code, while leaving the algorithm unchanged:</p>\n\n<ol>\n<li><p>You can avoid the need to check <code>counts.has_key(j-i)</code> if you use <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a>.</p></li>\n<li><p>You are looping over <em>all pairs of distinct indexes</em> between <code>0</code> and <code>len(array)-2</code>. The function <a href=\"http://docs.python.org/2/library/itertools.html#itertools.combinations\" rel=\"nofollow\"><code>itertools.combinations</code></a> provides a way to cleanly express your intention.</p></li>\n<li><p>Instead of comparing three pairs of array elements, you can compare one pair of array <em>slices</em>.</p></li>\n<li><p>Organize the code into a function with a <a href=\"http://docs.python.org/2/tutorial/controlflow.html#documentation-strings\" rel=\"nofollow\">docstring</a>.</p></li>\n<li><p>Generalize it from 3 to \\$k\\$.</p></li>\n<li><p>Python doesn't have an \"array\" type, but it does have <a href=\"http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange\" rel=\"nofollow\">sequences</a>. So your variables could be better named.</p></li>\n</ol>\n\n<p>Here's the revised code after making the above improvements:</p>\n\n<pre><code>from collections import Counter\nfrom itertools import combinations\n\ndef subseq_distance_counts(seq, k=3):\n \"\"\"Return a dictionary whose keys are distances and whose values\n are the number of identical pairs of `k`-length subsequences\n of `seq` separated by that distance. `k` defaults to 3.\n\n \"\"\"\n counts = Counter()\n for i, j in combinations(range(len(seq) - k + 1), 2):\n if seq[i:i + k] == seq[j:j + k]:\n counts[j - i] += 1\n return counts\n</code></pre>\n\n<p>It's possible to rewrite the body of this function as a single expression:</p>\n\n<pre><code> return Counter(j - i\n for i, j in combinations(range(len(seq) - k + 1), 2)\n if seq[i:i + k] == seq[j:j + k])\n</code></pre>\n\n<p>Some people prefer this style of coding, and others prefer the explicitness of the first version. It doesn't make much difference to the performance, so comes down to personal taste.</p>\n\n<h3>2. Improving the algorithm</h3>\n\n<p>Here's an alternative approach (that you could use if the subsequences are hashable). Your original algorithm is \\$ O(n^2) \\$, where \\$n\\$ is the length of the sequence. The algorithm below is \\$O(n + m)\\$, where \\$m\\$ is the number of repeated triples. This won't make any different in the worst case, where \\$m = Θ(n^2)\\$, but in cases where \\$m = ο(n^2)\\$ it should be an improvement.</p>\n\n<pre><code>def subseq_distance_counts(seq, k=3):\n \"\"\"Return a dictionary whose keys are distances and whose values\n are the number of identical pairs of `k`-length subsequences\n of `seq` separated by that distance. `k` defaults to 3.\n\n &gt;&gt;&gt; subseq_distance_counts('abcabcabc')\n Counter({3: 4, 6: 1})\n &gt;&gt;&gt; subseq_distance_counts('aaaaaa', 1)\n Counter({1: 5, 2: 4, 3: 3, 4: 2, 5: 1})\n\n \"\"\"\n positions = defaultdict(list) # List of positions where each subsequence appears.\n for i in range(len(seq) - k + 1):\n positions[seq[i:i + k]].append(i)\n return Counter(j - i\n for p in positions.itervalues()\n for i, j in combinations(p, 2))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T13:32:01.877", "Id": "19457", "ParentId": "19409", "Score": "4" } } ]
{ "AcceptedAnswerId": "19457", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T21:12:55.967", "Id": "19409", "Score": "3", "Tags": [ "python", "array", "search" ], "Title": "Array-search algorithm for identical sequences and character distances" }
19409
<p>Imagine a website that publishes the number of daily commuters in only a graphical form each day using a bar chart. I want to determine the number by reading the bar chart after saving the graphic as an image (the image stuff is not important here). The way I want to read the bar chart is by going to a pixel number (the #of commuters axis) and asking the question, "Is the pixel 'on' or 'off'?" (On means that the bar is present and off means that this guess too high) Note: that there is a lower bound of 0 and, technically, an infinite upper bound. But, in reality, 10000 may be the realistic upper bound. Also note, No Change from yesterday is a frequent finding.</p> <p><strong>Given a starting number from yesterday to guess, what's the most efficient way to find the number? Does my function provide the most efficient method?</strong> Efficient means fewest number of queries to ask if a pixel is on or off. There will be multiple bars to measure and keeping track of the iteration number might add unwanted complexity if it's not truly needed.</p> <p>My algorithm follows as a function. Any advice is most welcome. (brought to CR from SE, <a href="https://stackoverflow.com/questions/13782587/edge-finding-binary-search">https://stackoverflow.com/questions/13782587/edge-finding-binary-search</a> )</p> <pre><code>def EdgeFind(BlackOrWhite,oldtrial,high,low): # BlackOrWhite is a 0 or 1 depending on if the bar is present or not. A 1 indicates that you are below or equal to the true number. A 0 indicates that you are above the true number # the initial values for oldtrial, high, and low all equal yesterday's value factorIncrease = 4 #5 finished = 0 if BlackOrWhite == 1 and oldtrial==high: newtrial = oldtrial+factorIncrease*(high-low)+1 high = newtrial low = oldtrial elif BlackOrWhite == 1 and high-oldtrial==1: finished = 1 newtrial = oldtrial elif BlackOrWhite == 1: newtrial = oldtrial+(high-oldtrial)/2 low = oldtrial if BlackOrWhite == 0 and oldtrial==low: newtrial = (oldtrial)/2 high = oldtrial low = newtrial elif BlackOrWhite == 0 and oldtrial-low==1: finished = 1 newtrial = oldtrial-1 elif BlackOrWhite == 0: newtrial = oldtrial-(oldtrial-low+1)/2 high = oldtrial if (oldtrial==1) and low!=1: finished = 1 return finished,newtrial,high,low </code></pre>
[]
[ { "body": "<p>How about</p>\n\n<pre><code>if BlackOrWhite == 1:\n if oldtrial == high:\n newtrial = oldtrial+factorIncrease*(high-low)+1\n high = newtrial\n low = oldtrial\n elif high-oldtrial==1:\n finished = 1\n newtrial = oldtrial\n else:\n newtrial = oldtrial+(high-oldtrial)/2\n low = oldtrial\n</code></pre>\n\n<p>For simplifying your ifs?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T09:02:54.173", "Id": "19606", "ParentId": "19413", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T23:26:39.413", "Id": "19413", "Score": "4", "Tags": [ "python", "algorithm", "performance" ], "Title": "Edge finding binary search" }
19413
<p>I found a code on my computer that i wrote a while ago. It is based on an exercise from O'Reilly book <em><a href="http://shop.oreilly.com/product/9780596153823.do" rel="noreferrer">Programming the Semantic Web</a></em>. There is a class, that stores <a href="http://en.wikipedia.org/wiki/Resource_Description_Framework" rel="noreferrer">RDF triples</a>, that is data in the form subject-predicate-object:</p> <pre><code>class SimpleGraph: def __init__(self): self._spo = {} self._pos = {} self._osp = {} def add(self, (s, p, o)): # implementation details pass def remove(self, (s, p, o)): # implementation details pass </code></pre> <p>Variables <code>_spo</code>, <code>_pos</code>, <code>_osp</code> are different permutations of subject, predicate, object for performance reasons, and the underlying data structure is dictionary of dictionaries of sets like <code>{'subject': {'predicate': set([object])}}</code> or <code>{'object': {'subject': set([predicate])}}</code>. The class also has a method to yield triples that match the query in a form of a tuple. If one element of a tuple is None, it acts as a wildcard.</p> <pre><code>def triples(self, (s, p, o)): # check which terms are present try: if s != None: if p != None: # s p o if o != None: if o in self._spo[s][p]: yield (s, p, o) # s p _ else: for ro in self._spo[s][p]: yield (s, p, ro) else: # s _ o if o != None: for rp in self._osp[o][s]: yield (s, rp, o) # s _ _ else: for rp, oset in self._spo[s].items(): for ro in oset: yield (s, rp, ro) else: if p != None: # _ p o if o != None: for rs in self._pos[p][o]: yield (rs, p, o) # _ p _ else: for ro, sset in self._pos[p].items(): for rs in sset: yield (rs, p, ro) else: # _ _ o if o != None: for rs, pset in self._osp[o].items(): for rp in pset: yield (rs, rp, o) # _ _ _ else: for rs, pset in self._spo.items(): for rp, oset in pset.items(): for ro in oset: yield (rs, rp, ro) except KeyError: pass </code></pre> <p>You see, this code is huge, and i feel it could be more terse and elegant. I suspect the possible use of dicts here, where tuple (s, p, o) is matched with a certain key in this dict, and then the yield is done. But i have no idea how to implement it.</p> <p>How can i simplify this huge if-else structure?</p>
[]
[ { "body": "<p>You could gain some simplicity by breaking the task into two parts.</p>\n\n<p>Firstly, inspect the <code>None</code>ness of the parameters to figure out which dictionary to look into. Store the results in local variables. So something like:</p>\n\n<pre><code>if (should use _spo):\n data = self._spo\n order = [0,1,2]\nelif (should use _pos):\n data = self._pos\n order = [1,2,0]\nelse:\n ...\n</code></pre>\n\n<p>Secondly, use <code>order</code> and <code>data</code> to actually lookup the data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T17:46:08.033", "Id": "19498", "ParentId": "19470", "Score": "3" } } ]
{ "AcceptedAnswerId": "19527", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T19:00:27.527", "Id": "19470", "Score": "6", "Tags": [ "python", "hash-map" ], "Title": "Refactor deeply nested if-else" }
19470
<p>I've written a Time class that records the time of day and performs simple timing operations (add 2 times, convert a time object to an integer and back again,etc.) following the prompts in How to Think Like a Computer Scientist: Learning with Python. </p> <pre><code>class Time(object): """Attributes: hours, minutes, seconds""" def __init__(self,hours,minutes,seconds): self.hours =hours self.minutes=minutes self.seconds=seconds def print_time(self): """prints time object as a string""" print "%.2d:%.2d:%.2d" % (self.hours, self.minutes, self.seconds) def _str_(self): """returns time object as a string""" return "%.2d:%.2d:%.2d" % (self.hours, self.minutes, self.seconds) def name(self,name): """names an instance""" self.name=name return self.name def after(t1,t2): """checks to see which of two time objects is later""" if t1.convert_to_seconds()&lt;t2.convert_to_seconds(): return "%s is later" %(t2.name) elif t1.convert_to_seconds&gt;t2.convert_to_seconds: return "%s is later" %(t1.name) else: return "these events occur simultaneously" def convert_to_seconds(self): """converts Time object to an integer(# of seconds)""" minutes=self.hours*60+self.minutes seconds=minutes*60+self.seconds return seconds def make_time(self,seconds): """converts from an integer to a Time object""" self.hours=seconds/3600 seconds=seconds-self.hours*3600 self.minutes=seconds/60 seconds=seconds-self.minutes*60 self.seconds=seconds def increment_time(self, seconds): """Modifier adding a given # of seconds to a time object which has been converted to an integer(seconds); permanently alters object""" sum=self.convert_to_seconds()+seconds self.make_time(sum) return self._str_() def add_time(self, addedTime): """adds 2 Time objects represented as seconds; does not permanently modify either object""" import copy end_time=copy.deepcopy(self) seconds=self.convert_to_seconds()+addedTime.convert_to_seconds() end_time.make_time(seconds) return end_time._str_() </code></pre> <p>Usage examples:</p> <pre><code>breakfast=Time(8,30,7) dinner=Time(19,0,0) smokebreak=Time(19,0,0) interval=(4,30,0) print dinner.after(smokebreak) print breakfast.add_time(interval) print breakfast.increment_time(3600) </code></pre> <p>The Time Class example in the text I'm following does not use an <strong>init</strong> method, but passes straight into creating a time object and assigning attributes. Is there any advantage to including an <strong>init</strong> function, as I have done? Removing the <strong>init</strong> method seems to make it easier to adopt a terser and more functional style. Is including a method to name instances bad form, as I suspect? Would it be better write a functional-style version of add_time without importing deepcopy? I would appreciate any advice on best practices in Python 2.x OOP.</p>
[]
[ { "body": "<p>It is perfectly fine to implement an <code>__init__</code> method in this case. I think the only thing you should note is, by the way it's defined, the <code>Time</code> class forces the programmer to give values for <code>hours</code>, <code>minutes</code> and <code>seconds</code> to define a <code>Time</code> object. So, with that constraint in mind, it's really up to you as to whether this is an advantage or disadvantage. Do you want to force the programmer (most likely yourself) to enter these values here? Or should you allow him to first construct an object and then define them later? This is your decision; I don't think Pythoneers will try to sway you one way or another.</p>\n\n<p>Alternatives are (1) as you've already implied: removal or (2) giving these variables default values.</p>\n\n<p>For example:</p>\n\n<pre><code>def __init__(self,hours=None,minutes=None,seconds=None):\n self.hours =hours\n self.minutes=minutes\n self.seconds=seconds\n</code></pre>\n\n<p>With the above you are giving the user the option to define these later or now with no penalty either way. Just keep the following simple philosophy of Python in mind:</p>\n\n<blockquote>\n <p>Easier to ask for forgiveness than permission</p>\n</blockquote>\n\n<p>(From the <a href=\"http://docs.python.org/2/glossary.html\" rel=\"nofollow\">Python Glossary</a>)</p>\n\n<p>I don't really see a point in naming instances. Do you have a rationale for that? Also, if you choose to name them, I think that returning said name after setting is an unexpected behavior and gives the <code>name</code> function more responsibility than it needs.</p>\n\n<p>In your <code>add_time</code> method, I would suggest constructing a new <code>Time</code> object using the values of the <code>self</code> object and then returning that with the incrementation. And, in general, <code>import</code> statements occur at the top of the Python module, unless it is a really special case.</p>\n\n<p>Overall, everything looks pretty good. I hope this was somewhat helpful, if you have any questions be sure to comment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:26:56.947", "Id": "31506", "Score": "0", "body": "Thanks for your comments. The `name` method is of little utility - I thought that naming instances might be useful in print debugging (tracking objects passed between methods), and I also used the `name` method in the `after` method. Perhaps using `_str_` would be a better choice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T05:01:25.423", "Id": "19520", "ParentId": "19502", "Score": "3" } }, { "body": "<p>mjgpy3's answer is very good, though here are a few nit-picks of my own:</p>\n\n<p>1) Conventions are a good thing to adhere to, and the best guide I have found for python is <a href=\"http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html/\" rel=\"nofollow noreferrer\">here</a>. It is far more important to learn the concepts of a language, however, so if you feel this is too much at once, focus on learning the hard stuff before you get to the syntactical sugar.</p>\n\n<p>2) your <code>print_time</code> and <code>_str_</code> functions do nearly the same thing: perhapes it would be better to combine them together? Perhaps like this:</p>\n\n<pre><code>def _str_(self):\n \"\"\"Returns the object as a string\"\"\"\n return '{}:{}:{}'.format(self.hours, self.minutes, self.seconds)\n</code></pre>\n\n<p>2a) As well, the % formatter is commonly used less compared to the .format() option. You could use either, but be sure of the <a href=\"https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format/\">limitations</a> of both.</p>\n\n<p>Apart from those small nit-picks, your code seems fine to me</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T19:34:32.930", "Id": "19637", "ParentId": "19502", "Score": "1" } } ]
{ "AcceptedAnswerId": "19520", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T21:02:52.100", "Id": "19502", "Score": "3", "Tags": [ "python", "object-oriented" ], "Title": "Python Time Class definition and methods, use of __init__" }
19502