body
stringlengths
144
5.58k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm trying to write efficient code for calculating the chain-length of each number.</p> <p>For example, <code>13 -&gt; 40 -&gt; 20 -&gt; 10 -&gt; 5 -&gt; 16 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1</code>. It took 13 iterations to get 13 down to 1, so <code>collatz(13)</code> = <code>10</code>.</p> <p>Here is my implementation:</p> <pre><code>def collatz(n, d={1:1}): if not n in d: d[n] = collatz(n * 3 + 1 if n &amp; 1 else n/2) + 1 return d[n] </code></pre> <p>It's quite efficient, but I'd like to know whether the same efficiency (or better) can be achieved by an iterative one.</p>
[]
[ { "body": "<p>Using the Python call stack to remember your state is very convenient and often results in shorter code, but it has a disadvantage:</p>\n\n<pre><code>&gt;&gt;&gt; collatz(5**38)\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"cr24195.py\", line 3, in collatz\n d[n] = collatz(n * 3 + 1 if n &amp; 1 else n/2) + 1\n [... many lines omitted ...]\n File \"cr24195.py\", line 3, in collatz\n d[n] = collatz(n * 3 + 1 if n &amp; 1 else n/2) + 1\nRuntimeError: maximum recursion depth exceeded\n</code></pre>\n\n<p>You need to remember all the numbers you've visited along the way to your cache hit <em>somehow</em>. In your recursive implementation you remember them on the call stack. In an iterative implementation one would have to remember this stack of numbers in a list, perhaps like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def collatz2(n, d = {1: 1}):\n \"\"\"Return one more than the number of steps that it takes to reach 1\n starting from `n` by following the Collatz procedure.\n\n \"\"\"\n stack = []\n while n not in d:\n stack.append(n)\n n = n * 3 + 1 if n &amp; 1 else n // 2\n c = d[n]\n while stack:\n c += 1\n d[stack.pop()] = c\n return c\n</code></pre>\n\n<p>This is a bit verbose, and it's slower than your recursive version:</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit(lambda:map(collatz, xrange(1, 10**6)), number=1)\n2.7360708713531494\n&gt;&gt;&gt; timeit(lambda:map(collatz2, xrange(1, 10**6)), number=1)\n3.7696099281311035\n</code></pre>\n\n<p>But it's more robust:</p>\n\n<pre><code>&gt;&gt;&gt; collatz2(5**38)\n1002\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T11:40:33.847", "Id": "24198", "ParentId": "24195", "Score": "4" } } ]
{ "AcceptedAnswerId": "24198", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T09:14:06.903", "Id": "24195", "Score": "5", "Tags": [ "python", "optimization", "algorithm", "recursion", "memoization" ], "Title": "Iterative Collatz with memoization" }
24195
<p>I am currently trying to teach myself some programming. I have started to work with Python by doing <a href="https://www.hackerrank.com/challenges/string-similarity" rel="nofollow">this challenge</a>.</p> <p>For each test case, I need to find the sum of the self-similarities of a string with each of its suffixes. For example, given the string <code>ababaa</code>, the self-similarity scores are</p> <ul> <li>6 (because <code>ababaa</code> = <code>ababaa</code>)</li> <li>0 (because <code>ababaa</code> ≠ <code>babaa</code>)</li> <li>3 (because <code>ababaa</code> and <code>abaa</code> share three initial characters)</li> <li>0 (because <code>ababaa</code> ≠ <code>baa</code>)</li> <li>1 (because <code>ababaa</code> and <code>aa</code> share one initial character)</li> <li>1 (because <code>ababaa</code> and <code>a</code> share one initial character)</li> </ul> <p>… for a total score of 11.</p> <p>When I test run it works out fine, however when I run this code with longer strings it takes too long time to run, so the site shuts down the program. Each input string consists of up to 100000 lowercase characters.</p> <p>Is this because this code make unnecessary loops? Or what else might the problem be here? </p> <pre><code># Solution.py for https://www.hackerrank.com/challenges/string-similarity import sys for line in sys.stdin: if line.islower(): line = line[:-1] # line will be compared to suffix line_length = len(line) points = 0 for s in xrange(0,line_length): suffix = line[s:] suffix_length = len(suffix) count = 1 while count &lt; suffix_length+1: if line.startswith(suffix[:1]): # if line and first character of suffix mach if line.startswith(suffix[:suffix_length]): points += len(suffix[:suffix_length]) break else: if line.startswith(suffix[:count+1]): count += 1 elif line.startswith(suffix[:count]): points += len(suffix[:count]) break else: break print points </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T15:05:08.987", "Id": "49229", "Score": "2", "body": "Try studying z-algorithm. This question is a very very simple modification of the z-array you get as part of the z-algorithm. See this <http://codeforces.com/blog/entry/3107> for the tutorial or youtube video tutorials <http://www.youtube.com/watch?v=MFK0WYeVEag>" } ]
[ { "body": "<p>As @Janne-Karila has said there are too many <code>startswith</code>s. Your <code>suffix[:1]</code> could be replaced by <code>suffix[0]</code> and <code>suffix[:suffix_length]</code> is simply the same as <code>suffix</code>.</p>\n\n<p>If you design the loops right you only need to compare one character at a time, and there is no call to use <code>startswith</code> at all. This also greatly simplifies the code.</p>\n\n<pre><code>def string_sim():\n n = int(sys.stdin.readline())\n for _ in range(n):\n line = sys.stdin.readline().strip()\n points = len(line)\n for s in xrange(1, len(line)):\n for count in xrange(len(line) - s):\n if line[count] != line[s + count]:\n break\n points += 1\n print points\nstring_sim()\n</code></pre>\n\n<p>This will give a slight speed boost, but as others have pointed out, you need a wholly better algorithm to pass all the tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T20:14:59.303", "Id": "30930", "ParentId": "24246", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T11:33:51.017", "Id": "24246", "Score": "6", "Tags": [ "python", "algorithm", "strings", "time-limit-exceeded" ], "Title": "Hackers Ranking String Similarity" }
24246
<p>I read about how markov-chains were handy at creating text-generators and wanted to give it a try in python. </p> <p>I'm not sure if this is the proper way to make a markov-chain. I've left comments in the code. Any feedback would be appreciated.</p> <pre><code>import random def Markov(text_file): with open(text_file) as f: # provide a text-file to parse data = f.read() data = [i for i in data.split(' ') if i != ''] # create a list of all words data = [i.lower() for i in data if i.isalpha()] # i've been removing punctuation markov = {i:[] for i in data} # i create a dict with the words as keys and empty lists as values pos = 0 while pos &lt; len(data) - 1: # add a word to the word-key's list if it immediately follows that word markov[data[pos]].append(data[pos+1]) pos += 1 new = {k:v for k,v in zip(range(len(markov)), [i for i in markov])} # create another dict for the seed to match up with length_sentence = random.randint(15, 20) # create a random length for a sentence stopping point seed = random.randint(0, len(new) - 1) # randomly pick a starting point sentence_data = [new[start_index]] # use that word as the first word and starting point current_word = new[start_index] while len(sentence_data) &lt; length_sentence: next_index = random.randint(0, len(markov[current_word]) - 1) # randomly pick a word from the last words list. next_word = markov[current_word][next_index] sentence_data.append(next_word) current_word = next_word return ' '.join([i for i in sentence_data]) </code></pre>
[]
[ { "body": "<pre><code>import random\n\ndef Markov(text_file):\n</code></pre>\n\n<p>Python convention is to name function lowercase_with_underscores. I'd also probably have this function take a string as input rather then a filename. That way this function doesn't make assumptions about where the data is coming from</p>\n\n<pre><code> with open(text_file) as f: # provide a text-file to parse\n data = f.read()\n</code></pre>\n\n<p>data is a bit too generic. I'd call it text.</p>\n\n<pre><code> data = [i for i in data.split(' ') if i != ''] # create a list of all words \n data = [i.lower() for i in data if i.isalpha()] # i've been removing punctuation\n</code></pre>\n\n<p>Since ''.isalpha() == False, you could easily combine these two lines</p>\n\n<pre><code> markov = {i:[] for i in data} # i create a dict with the words as keys and empty lists as values\n\n pos = 0\n while pos &lt; len(data) - 1: # add a word to the word-key's list if it immediately follows that word\n markov[data[pos]].append(data[pos+1])\n pos += 1\n</code></pre>\n\n<p>Whenever possible, avoid iterating over indexes. In this case I'd use</p>\n\n<pre><code> for before, after in zip(data, data[1:]):\n markov[before] += after\n</code></pre>\n\n<p>I think that's much clearer.</p>\n\n<pre><code> new = {k:v for k,v in zip(range(len(markov)), [i for i in markov])} # create another dict for the seed to match up with \n</code></pre>\n\n<p><code>[i for i in markov]</code> can be written <code>list(markov)</code> and it produces a copy of the markov list. But there is no reason to making a copy here, so just pass markov directly.</p>\n\n<p><code>zip(range(len(x)), x)</code> can be written as <code>enumerate(x)</code> </p>\n\n<p><code>{k:v for k,v in x}</code> is the same as <code>dict(x)</code> </p>\n\n<p>So that whole line can be written as</p>\n\n<pre><code> new = dict(enumerate(markov))\n</code></pre>\n\n<p>But that's a strange construct to build. Since you are indexing with numbers, it'd make more sense to have a list. An equivalent list would be</p>\n\n<pre><code> new = markov.keys()\n</code></pre>\n\n<p>Which gives you a list of the keys</p>\n\n<pre><code> length_sentence = random.randint(15, 20) # create a random length for a sentence stopping point\n\n seed = random.randint(0, len(new) - 1) # randomly pick a starting point\n</code></pre>\n\n<p>Python has a function random.randrange such that random.randrange(x) = random.randint(0, x -1) It good to use that when selecting from a range of indexes like this</p>\n\n<pre><code> sentence_data = [new[start_index]] # use that word as the first word and starting point\n current_word = new[start_index]\n</code></pre>\n\n<p>To select a random item from a list, use <code>random.choice</code>, so in this case I'd use</p>\n\n<pre><code> current_word = random.choice(markov.keys())\n\n\n\n while len(sentence_data) &lt; length_sentence:\n</code></pre>\n\n<p>Since you know how many iterations you'll need I'd use a for loop here.</p>\n\n<pre><code> next_index = random.randint(0, len(markov[current_word]) - 1) # randomly pick a word from the last words list.\n next_word = markov[current_word][next_index]\n</code></pre>\n\n<p>Instead do <code>next_word = random.choice(markov[current_word])</code></p>\n\n<pre><code> sentence_data.append(next_word)\n current_word = next_word\n\n return ' '.join([i for i in sentence_data])\n</code></pre>\n\n<p>Again, no reason to be doing this <code>i for i</code> dance. Just use <code>' '.join(sentence_data)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T18:02:20.130", "Id": "37448", "Score": "0", "body": "thanks for taking the time to respond. Your markups will be very helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-02T11:59:47.910", "Id": "167891", "Score": "0", "body": "It's a bit difficult to figure out which comment belongs to which code snippet (above or below?). Also sometimes I think you wanted to have two separate code snippets, but they were merged because there was no text in between." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T17:08:12.697", "Id": "24284", "ParentId": "24276", "Score": "7" } } ]
{ "AcceptedAnswerId": "24284", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-23T11:57:42.617", "Id": "24276", "Score": "11", "Tags": [ "python", "algorithm", "markov-chain" ], "Title": "Implementation of a Markov Chain" }
24276
<p>I am making a Python program with what I learned so far where the user enters two IPs that represents the start and end of the range of IPs to be scanned, then saves the wanted IP in a text file.</p> <pre><code> #ip range and scanning import socket import sys ok=[] def ipscan(start2,port): s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) try: s.connect((start2,port)) print start2 ,'--&gt;port %s is Open'%port ok.append(start2) except: print start2 ,'--&gt;port %s is Closed ! '%port def iprange(start,end): while end&gt;start: start[3]+=1 ipscan('.'.join(map(str,start)),p) for i in (3,2,1,0): if start[i]==255: start[i-1]+=1 start[i]=0 #--------------------------------------------# sta=map(int,raw_input('From : ').split('.')) fin=map(int,raw_input('to : ').split('.')) p=input('Port to scan : ') iprange(sta,fin) print '-----------end--------------' of=open('Output.txt','w') for ip in ok: of.writelines(ip+'\n') of.close() </code></pre> <p>It seems to be working but I need to be sure, and wanted to know if I can make it any faster, or if there is a better way.</p>
[]
[ { "body": "<p>Your naming convention doesnt aid legability. e.g, rename <code>p</code> to <code>port</code>.</p>\n\n<p>Don't do carte blanche exception handling. Be more specific, e.g.:</p>\n\n<pre><code>try:\n ...\nexcept (ValueError, KeyError)\n ...\n</code></pre>\n\n<p>You are also a miser with your spaces. White space is important for legibility.</p>\n\n<p>explicit is better than implicit so replace <code>ipscan('.'.join(map(str,start)),p)</code> with <code>ipscan(start2='.'.join(map(str,start)), port=p)</code></p>\n\n<p>Consider replacing <code>while end&gt;start</code> with <code>while end &gt;= start</code> as it allows scanning of a single IP address..</p>\n\n<p>I cans see how the ordering of 3,2,1,0 is important so replace</p>\n\n<pre><code>for i in (3,2,1,0):\n if start[i]==255:\n start[i-1]+=1 #what if \n start[i]=0\n</code></pre>\n\n<p>with</p>\n\n<pre><code>for i, val in enumerate(start):\n if val == 255:\n start[i] = 0\n start[i-1] += 1\n</code></pre>\n\n<p>Also, what if item at index 0 == 255? that will cause <code>start[i-1] += 1</code> to raise an Index Error.</p>\n\n<p>Also, it is not clear why that transformation is being done, so some documentation will be great. Future you will thank present you for it too. Just simply <code>#this does x because of y</code> can suffice.</p>\n\n<p>replace</p>\n\n<pre><code>of=open('Output.txt','w')\nfor ip in ok:\n of.writelines(ip+'\\n')\nof.close()\n</code></pre>\n\n<p>with context and join</p>\n\n<pre><code>with open('Output.txt','w') as of:\n of.write('\\n'.join(ok))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T13:06:56.117", "Id": "24337", "ParentId": "24302", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T10:47:24.030", "Id": "24302", "Score": "2", "Tags": [ "python", "socket" ], "Title": "Port-scanning with two IPs" }
24302
<p>I wrote a python module that needs to load a file parser to work. Initially it was just one text parsing module but I need to add more parsers for different cases.</p> <pre><code>parser_class1.py parser_class2.py parser_class3.py </code></pre> <p>Only one is required for every running instance. I'm thinking load it by command line:</p> <pre><code>mmain.py -p parser_class1 </code></pre> <p>I wrote this code in order to select the parser to load when the main module is called:</p> <pre><code>#!/usr/bin/env python import argparse aparser = argparse.ArgumentParser() aparser.add_argument('-p', action='store', dest='module', help='-i module to import') results = aparser.parse_args() if not results.module: aparser.error('Error! no module') try: exec("import %s" %(results.module)) print '%s imported done!'%(results.module) except ImportError, e: print e </code></pre> <p>But, I was reading that this way is dangerous, maybe not standard.</p> <p>Then is this approach ok? </p> <p>Or must I find another way to do it?</p> <p>Why?</p>
[]
[ { "body": "<h3>Sanitising your inputs with argparse</h3>\n\n<p>As has already been mentioned in comments and @eikonomega’s answer, running arbitrary code from the user is generally dangerous. Using <code>__import__</code> or <code>importlib</code> restricts their ability somewhat.</p>\n\n<p>You can make it even safer by restricting the set of available modules, by passing a <code>choices</code> flag to <code>add_argument</code>. Like so:</p>\n\n<pre><code>aparser.add_argument('-p',\n action='store',\n dest='module',\n help='-i module to import',\n choices=['parser1', 'parser2', 'parser3'])\n</code></pre>\n\n<p></p></p>\n\n<p>argparse will now enforce that only the values \"parser1\", \"parser2\" or \"parser3\" can be entered here – anything else will cause it to exit and print a usage message, e.g.:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ python conditional_imports.py -p foo\nusage: conditional_imports.py [-h] [-p {parser1,parser2,parser3}]\nconditional_imports.py: error: argument -p: invalid choice: 'foo' (choose from 'parser1', 'parser2', 'parser3')\n</code></pre>\n\n<p></p></p>\n\n<p>It’s also better for the end-user, because the help/usage message will tell them the available options, rather than leaving them to guess.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-19T10:27:30.817", "Id": "155759", "ParentId": "24349", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T16:02:11.530", "Id": "24349", "Score": "7", "Tags": [ "python", "dynamic-loading" ], "Title": "Load modules conditionally Python" }
24349
<p>I was working through another question <a href="https://stackoverflow.com/questions/15632476/">here</a> and have hacked up an answer:</p> <pre><code>def get_rows(): """ Get height of triangle from user""" while True: rows = input('Enter the number of rows: ') if 3 &lt;= rows &lt;= 33: return rows def triangle(rows, invert=True): """ Print the outline of a triangle, of variable size. Print out a regular or inverted version of the triangle as necessary """ if invert: height = -1 * rows else: height = 0 # inner padding for min height (3) inner_buffer = [0, 1, 3] while len(inner_buffer) &lt;= rows: inner_buffer.append(inner_buffer[-1]+2) level = 0 while level &lt;= rows: outer_padding = ' '*(rows - abs(height)) if height == 0: print(outer_padding + '*') else: inner_padding = ' '*( inner_buffer[ abs(height) ] ) print(outer_padding + '*' + inner_padding + '*') height += 1 level += 1 </code></pre> <p>At this stage I am working to re-implement this two ways using: recursion and <code>itertools</code>.</p> <p>But I am looking at this and wonder if it would be a good place to use decorators. If someone is happy to implement one triangle (either regular or inverted, I don't mind) I would love to see the difference in the 3 implementations.</p>
[]
[ { "body": "<p>Decorators are a tool that you use when you have many functions that share a behaviour, for example a particular calling convention or treatment of results. See the <a href=\"http://wiki.python.org/moin/PythonDecoratorLibrary\" rel=\"nofollow noreferrer\">Python Decorator Library</a> on the Python wiki for some examples, and <a href=\"https://stackoverflow.com/a/1594484/68063\">this answer</a> on Stack Overflow for a tutorial.</p>\n\n<p>Here you only have two functions, so it doesn't seem likely that decorators will be helpful. Use the right tool for the job!</p>\n\n<p>Anyway, comments on your code.</p>\n\n<ol>\n<li><p>No docstrings! What do these functions do and how do you call them?</p></li>\n<li><p>The <code>else: continue</code> in <code>get_rows()</code> is unnecessary.</p></li>\n<li><p>The <code>regular</code> keyword argument to <code>triangle</code> is ignored.</p></li>\n<li><p>Your function <code>triangle</code> seems very long for what it's doing. Why not use Python's <a href=\"http://docs.python.org/2/library/string.html#formatspec\" rel=\"nofollow noreferrer\"><code>format</code></a> language to do the padding? Like this:</p>\n\n<pre><code>def triangle(n, invert=True):\n \"\"\"Print inverted triangle of asterisks (with `n`+1 rows) to standard output.\n Print it the right way up if keyword argument `invert=False` is given.\n \"\"\"\n for i in reversed(xrange(n + 1)) if invert else xrange(n + 1):\n print('{:&gt;{}}{:&gt;{}}'.format('*', n - i + 1, '*' if i else '', 2 * i))\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:20:11.580", "Id": "37623", "Score": "1", "body": "+1 + two comments: 1) I'd put some parens on the thing being iterated (or separate it in a variable). 2) That string being formatted is really complicated: I'd probably write a simple string concatenation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T19:07:54.240", "Id": "37657", "Score": "0", "body": "Hi Gareth, thank you for your answer. Will re-edit according to first 3 points. Lol, I will have to wrap my head around your formatting - thank you very much for that! Appreciate your thoughts on decorators and using the right tools. Many thanks!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T11:44:27.397", "Id": "24373", "ParentId": "24372", "Score": "4" } }, { "body": "<p>I would suggest that you read PEP8. Also, you can reduce code size by using certain coding styles:</p>\n\n<pre><code>height = -1 * rows if rows else 0\n</code></pre>\n\n<p>It should look more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T07:13:18.423", "Id": "37736", "Score": "0", "body": "Thanks for the reference to PEP8 - have certainly learned and tidied up many things through reading that. After a cursory look, it seems PEP8 discourages putting multi-line stmts on the same line, BUT... in simple cases (and I agree that the case you've given above is straight forward) it may be ok. Seems there is some lee-way on this.\nnb: the stmt above, does not test `if invert` so does not quite accomplish the intended task.\nWill edit above with a more tidy solution (using recursion, string formatting (as suggested by Gareth) and tidier logic.\nThanks for your comments people!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T08:26:33.957", "Id": "37738", "Score": "0", "body": "hmm, I think there is a typo error, there will be `if invert`. Also, you can have any number of condition in a if statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T09:54:50.070", "Id": "37743", "Score": "0", "body": "I do see your point here, the statement could be written `height = -1 * rows if invert else 0` and still achieve the desired end. PEP8 includes, \"While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements.\" This is not definitive, what is the general concensus re. compacting code in this sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T10:59:41.910", "Id": "37744", "Score": "0", "body": "Hmm, but you see its not a typical `if/else` compound statement where you have two clauses (header and suite). Its a simple expression, and its perfectly fine to use it like this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T11:06:12.833", "Id": "37745", "Score": "0", "body": "Oh right! That makes sense to me now. thanks!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T04:05:10.850", "Id": "24455", "ParentId": "24372", "Score": "0" } } ]
{ "AcceptedAnswerId": "24373", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T11:13:37.633", "Id": "24372", "Score": "3", "Tags": [ "python" ], "Title": "Drawing inverted triangles" }
24372
<p>I created a <em>class EmailParser</em> and check if a supplied string is an email or not with the help of the standard librarie's email module. If the supplied string is not an email I raise an exception. </p> <ul> <li><strong>Is this a pythonic way to deal with inappropiate input values an assertation error?</strong></li> <li><strong>How do you generally check input values and report inappropiate states and values?</strong></li> </ul> <p>code:</p> <pre><code>class EmailParser(object): def __init__(self, message): assert isinstance(message, basestring) parsed_message = email.message_from_string(message) if self._is_email(parsed_message): self.email_obj = parsed_message else: assert False, 'The supplied string is no email: %s' % parsed_message def __str__(self, *args, **kwargs): return self.email_obj.__str__() def _is_email(self, possible_email_obj): is_email = False if isinstance(possible_email_obj, basestring): is_email = False # I struggled a lot with this part - however, I came to the conclusion # to ask for forgiveness than for permission, see Zen of Python and # http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610923#610923 try: if '@' in possible_email_obj['To']: is_email = True except TypeError, e: is_email = False return is_email </code></pre>
[]
[ { "body": "<pre><code>class EmailParser(object):\n\n def __init__(self, message):\n assert isinstance(message, basestring)\n</code></pre>\n\n<p>In python, we typically don't check types. Basically, we prefer duck typing. Let the user pass whatever they want.</p>\n\n<pre><code> parsed_message = email.message_from_string(message)\n\n if self._is_email(parsed_message):\n self.email_obj = parsed_message \n else:\n assert False, 'The supplied string is no email: %s' % parsed_message\n</code></pre>\n\n<p>As Janne mentioned, this is not a good use of an assertion.</p>\n\n<pre><code> def __str__(self, *args, **kwargs):\n return self.email_obj.__str__()\n</code></pre>\n\n<p>You shouldn't call <code>__str__</code> methods directly. Use the <code>str()</code> function.</p>\n\n<pre><code> def _is_email(self, possible_email_obj):\n is_email = False\n\n if isinstance(possible_email_obj, basestring):\n is_email = False\n</code></pre>\n\n<p>This is useless, because the only possible outcome is to set is_email to False which it already is. Furthermore, you know this has to be a Message object since it was returned from <code>message_from_string</code> so why are you checking whether it's a string? You know its not.</p>\n\n<pre><code> # I struggled a lot with this part - however, I came to the conclusion\n # to ask for forgiveness than for permission, see Zen of Python and\n # http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610923#610923 \n try:\n if '@' in possible_email_obj['To']:\n is_email = True \n\n except TypeError, e:\n is_email = False\n</code></pre>\n\n<p>In what circumstances can this possibly happen?</p>\n\n<pre><code> return is_email\n</code></pre>\n\n<p>Don't needlessly set boolean flags. Just return True or False directly.</p>\n\n<p>Better yet, raise an exception with details on what exactly is wrong rather than returning false and raising a generic exception later.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T14:50:03.357", "Id": "24426", "ParentId": "24419", "Score": "5" } } ]
{ "AcceptedAnswerId": "24426", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T13:23:24.860", "Id": "24419", "Score": "3", "Tags": [ "python", "exception" ], "Title": "Raising an assertation error if string is not an email" }
24419
<p>I am writing an email parser and cannot decide how much logic should be included in the <code>__init__</code> function. I know that a constructor should make the object ready for use, but are there best practices?</p> <p>I've added several statements to my constructor:</p> <pre><code>def __init__(self, message): assert isinstance(message, basestring) parsed_message = email.message_from_string(message) if self._is_email(parsed_message): self.email_obj = parsed_message email_payload = parsed_message.get_payload() self.valid_urls = self._find_valid_urls(email_payload) # ... some other stuff like looking for keywords etc. </code></pre> <p>What do you consider the most pythonic way:</p> <ul> <li>Should I create a simple email object which possesses several methods that extract and return keywords, included URLs etc?</li> <li>Do you consider it better to process all this information in the <code>__init__</code> method and putting all results in object variables?</li> </ul>
[]
[ { "body": "<p>Actually, I think you should do something like</p>\n\n<pre><code>@classmethod\ndef parse(cls, message): \n parsed_message = email.message_from_string(message)\n\n cls._verify_email(parsed_message) # throws if something is wrong\n\n message = cls() # make an e-mail message object \n email_payload = parsed_message.get_payload()\n message.valid_urls = self._find_valid_urls(email_payload)\n # ... some other stuff like looking for keywords etc.\n\n return message\n</code></pre>\n\n<p>Which you would then use like</p>\n\n<pre><code> my_message = Message.parse(message_text)\n</code></pre>\n\n<p>I prefer to leave the constructor for just basic object construction. It shouldn't parse things or do complex logic. It gives you flexibility because it is now possible to construct an e-mail object that isn't just a parsed version of the message text. I often find that useful for testing, and it reduces the dependance on a particular source for e-mails.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T21:53:25.940", "Id": "24442", "ParentId": "24425", "Score": "3" } }, { "body": "<p>I think you should keep in mind these two principles in mind:</p>\n\n<ol>\n<li>DRY (Don't Repeat Yourself)</li>\n<li>SRP (Single Responsibility Principle)</li>\n</ol>\n\n<p>According to SRP, your init function should be just initializing your object. All other stuff should go into their respective functions and called as needed.</p>\n\n<pre><code>email = Email(message)\n\nif not email.is_valid: # Do some stuff\n\nurls = email._valid_urls # use property here\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T05:49:55.400", "Id": "24457", "ParentId": "24425", "Score": "1" } } ]
{ "AcceptedAnswerId": "24442", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T14:44:43.513", "Id": "24425", "Score": "3", "Tags": [ "python", "parsing", "constructor", "email" ], "Title": "Logic for an init function in email parser" }
24425
<p><strong>Requirements</strong>:</p> <blockquote> <p>Given a long section of text, where the only indication that a paragraph has ended is a shorter line, make a guess about the first paragraph. The lines are hardwrapped, and the wrapping is consistent for the entire text.</p> </blockquote> <p>The code below assumes that a paragraph ends with a line that is shorter than the average of all of the other lines. It also checks to see whether the line is shorter merely because of word wrapping by looking at the word in the next line and seeing whether that would have made the line extend beyond the "maximum" width for the paragraph.</p> <pre><code>def get_first_paragraph(source_text): lines = source_text.splitlines() lens = [len(line) for line in lines] avglen = sum(lens)/len(lens) maxlen = max(lens) newlines = [] for line_idx, line in enumerate(lines): newlines.append(line) try: word_in_next_line = lines[line_idx+1].split()[0] except IndexError: break # we've reached the last line if len(line) &lt; avglen and len(line) + 1 + len(word_in_next_line) &lt; maxlen: # 1 is for space between words break return '\n'.join(newlines) </code></pre> <h2>Sample #1</h2> <p><strong>Input:</strong></p> <blockquote> <pre class="lang-none prettyprint-override"><code>This is a sample paragaraph. It goes on and on for several sentences. Many OF These Remarkable Sentences are Considerable in Length. It has a variety of words with different lengths, and there is not a consistent line length, although it appears to hover supercalifragilisticexpialidociously around the 70 character mark. Ideally the code should recognize that one line is much shorter than the rest, and is shorter not because of a much longer word following it which has wrapped the line, but because we have reached the end of a paragraph. This is the next paragraph, and continues onwards for more and more sentences. </code></pre> </blockquote> <p><strong>Output:</strong></p> <blockquote> <pre class="lang-none prettyprint-override"><code>This is a sample paragaraph. It goes on and on for several sentences. Many OF These Remarkable Sentences are Considerable in Length. It has a variety of words with different lengths, and there is not a consistent line length, although it appears to hover supercalifragilisticexpialidociously around the 70 character mark. Ideally the code should recognize that one line is much shorter than the rest, and is shorter not because of a much longer word following it which has wrapped the line, but because we have reached the end of a paragraph. </code></pre> </blockquote> <p>Using other sample inputs I see there are a few issues, particularly if the text features a short paragraph or if there is more than one paragraph in the source text (leading to the trailing shorter lines reducing the overall average).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T16:46:31.510", "Id": "37702", "Score": "0", "body": "Can you post example inputs and expected outputs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T08:31:51.227", "Id": "37739", "Score": "0", "body": "Why do you consider the average length at all? `if len(line) + len(word_in_next_line) < maxlen:` would seem better to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-15T20:44:00.083", "Id": "191715", "Score": "0", "body": "I've updated the example to make it clearer. The inputs are originally text from PDFs, and the fonts used are proportional. As a result, the number of characters per line is not constant but rather based on the number of narrow vs wide characters. The sentence `Many OF These Remarkable Sentences are Considerable in Length.` is just 63 characters even though it takes up the whole width. Without the check for average length, it would be falsely identified as a new paragraph." } ]
[ { "body": "<p>Below is a small hash-up for this problem. I have modified the assumptions slightly, in that:</p>\n\n<ul>\n<li><p>Considering the MODE of the line lengths (i.e. taken the most common\nline length as the 'average' length)</p></li>\n<li><p>Tested the length of each line + the next word against the MODE (this is loose, I am assuming that the end of paragraph line is\nSIGNIFICANTLY shorter than the MODE - but I think you could refine\nthis :) )</p></li>\n</ul>\n\n<p>So here we go:</p>\n\n<pre><code>source_lines = source_text.split('\\n')\n\n# add the length of each line to a dictionary, incrementing common lengths\nline_lengths = {}\nfor each_line in source_lines:\n line_size = len(each_line)\n\n # increment a common line length:\n if line_size in line_lengths:\n line_lengths[line_size] += 1\n\n # or add a new line length to dictionary\n else:\n line_lengths[line_size] = 1\n\n# find the most common length (mode)\nmode_length = max(line_lengths, key=line_lengths.get)\n\n# loop through all lines, and test length against MODE\nfor index in range(0, len(source_lines) -1):\n try:\n # length = this line + next word\n length = len( source_lines[index] + source_lines[index + 1].split()[0] )\n except IndexError:\n # ie. end of file\n length - len( source_lines[index] )\n\n # test length against MODE\n if length &lt; mode_length:\n # is end of paragraph\n print('\\n'.join( source_lines[:index + 1] ) )\n # break loop once first paragraph identified\n break\n</code></pre>\n\n<p>There is more than likely a more elegant way to implement this using list comprehension. But conceptually, does this work for your needs?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T22:16:27.507", "Id": "37723", "Score": "0", "body": "Revised: the mode_length is not actually the mode here! `max(line_lengths)` is actually the longest line. Still think this is appropriate however. I will revise and calculate the mode correctly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T23:02:59.457", "Id": "37728", "Score": "0", "body": "Will use `mode_length = max(line_lengths, key=line_lengths.get)` to get an accurate value for MODE (c.f. just the longest line)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T22:09:18.093", "Id": "24443", "ParentId": "24431", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T16:10:13.113", "Id": "24431", "Score": "4", "Tags": [ "python", "strings" ], "Title": "Given a random section of text delimited by line breaks, get the first paragraph" }
24431
<p>After watching Raymond Hettinger, I decided to go through my code and make it faster and more beautiful. The example given on the slides is, unfortunately, not good enough to get me going (ref. <a href="https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger" rel="nofollow noreferrer">https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger</a>)</p> <p>Here's my code. Do you know how I can make it faster? It's from my django code that inserts data from a list.</p> <pre><code>FiveMin(timestamp=datetime.strptime(s[0], "%m/%d/%Y %H:%M:%S"), station=stat, district=s[2], fwy=s[3], fdir=s[4], ftype=s[5], length=float_or_zero(s[6]), samples=int_or_zero(s[7]), p_observed=float_or_zero(s[8]), total_flow=int_or_zero(s[9]), avg_occupancy=float_or_zero(s[10]), avg_speed=float_or_zero(s[11])).save() </code></pre> <p>If not, are there any significant speed losses?</p> <blockquote> <p><em>Note:</em> originally hosted in <a href="https://stackoverflow.com/questions/15665364/unpacking-sequences-for-functions">https://stackoverflow.com/questions/15665364/unpacking-sequences-for-functions</a> </p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:34:52.260", "Id": "37704", "Score": "1", "body": "Insufficient context: what is s? where did come from?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:40:47.120", "Id": "37705", "Score": "0", "body": "data is downloaded and parsed from a text file (not shown). Code above shows data insertion in django. Is there a faster/more beautiful way to do this using python's sequence unpacking?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:43:44.833", "Id": "37707", "Score": "1", "body": "If it is already parsed, why are you doing conversions there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:47:28.840", "Id": "37710", "Score": "1", "body": "Show us the download and parse steps. Then we'll have a better idea of what options are available. Making code beautiful requires looking at more then just one line at a time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:48:09.697", "Id": "37711", "Score": "0", "body": "@codesparkle sorry, by parsed, I meant broken down using a delimiter. Now to save, the db expects a certain format hence the conversions" } ]
[ { "body": "<p>You can use sequence unpacking instead of numeric indexing:</p>\n\n<pre><code>(timestamp, dummy, district, fwy, fdir, ftype, length, samples, \n p_observed, total_flow, avg_occupancy, avg_speed) = s\n\nFiveMin(timestamp=datetime.strptime(timestamp, \"%m/%d/%Y %H:%M:%S\"),\n station=stat,\n district=district,\n fwy=fwy,\n fdir=fdir,\n ftype=ftype,\n length=float_or_zero(length),\n samples=int_or_zero(samples),\n p_observed=float_or_zero(p_observed),\n total_flow=int_or_zero(total_flow),\n avg_occupancy=float_or_zero(avg_occupancy),\n avg_speed=float_or_zero(avg_speed)).save()\n</code></pre>\n\n<p>This avoids a couple of problems of the indexing approach:</p>\n\n<ol>\n<li>It is easy to make the mistake of using a wrong number </li>\n<li>If you need to add or remove a variable in the middle, you would need to update many numbers, possibly making a mistake.</li>\n</ol>\n\n<p>Unpacking may also be <em>slightly</em> faster, but the difference is rather negligible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T08:18:41.660", "Id": "24465", "ParentId": "24437", "Score": "1" } } ]
{ "AcceptedAnswerId": "24465", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:31:26.097", "Id": "24437", "Score": "-1", "Tags": [ "python", "django" ], "Title": "Unpacking sequences for functions" }
24437
<p>I'm trying to merge counts for items (URLs) in the list:</p> <pre><code>[['foo',1], ['bar',3],['foo',4]] </code></pre> <p>I came up with a function, but it's slow when I run it with 50k entries. I'd appreciate if somebody could please review and suggest improvements.</p> <pre><code>def dedupe(data): ''' Finds duplicates in data and merges the counts ''' result = [] for row in data: url, count = row url_already_in_result = filter(lambda res_row: res_row[0] == url, result) if url_already_in_result: url_already_in_result[0][1] += count else: result.append(row) return result def test_dedupe(): data = [['foo',1], ['bar',3],['foo',4]] assert dedupe(data) == [['foo',5], ['bar',3]] </code></pre>
[]
[ { "body": "<p>It looks like you could use <a href=\"http://docs.python.org/2/library/collections.html#counter-objects\"><code>collections.Counter</code></a>. Although you may want to use it earlier in your code, when you create the list of pairs you pass to <code>dedupe</code>. As is, you could use the following in your code:</p>\n\n<pre><code>from collections import Counter\n\ndef dedupe(data):\n result = Counter()\n for row in data:\n result.update(dict([row]))\n return result.items()\n\n&gt;&gt;&gt; data = [['foo',1], ['bar',3],['foo',4]]\n&gt;&gt;&gt; dedupe(data)\n[('foo', 5), ('bar', 3)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T06:54:28.910", "Id": "24460", "ParentId": "24458", "Score": "6" } }, { "body": "<p>Let's assume your list of lists is like this : </p>\n\n<pre><code>a = [[1,1], [2,2], [1,4], [2,3], [1,4]]\nimport itertools\n#you can loop through all the lists and count as :\nb = a\nb.sort()\nb = list(b for b,_ in itertools.groupby(b)) #removing duplicates\ntotal = len(b) #counting total unique elements\nfor i in range(total):\n b[i].insert(3, a.count(b[i])) #count repetitions and inserting in list\n</code></pre>\n\n<p>The counts of elements would be inserted in the index 3 of respective lists.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-28T07:00:04.113", "Id": "136150", "ParentId": "24458", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T06:10:21.250", "Id": "24458", "Score": "5", "Tags": [ "python", "performance", "array" ], "Title": "Find and process duplicates in list of lists" }
24458
<p>How could I possibly shorten / clean this up? I suppose mainly clean up the loop at the start asking whether they would like to scramble the code.</p> <pre><code>def userAnswer(letters): print("Can you make a word from these letters? "+str(letters)+" :") x = input("Would you like to scrample the letters? Enter 1 to scramble or enter to guess :") while x == '1': print(''.join(random.sample(letters,len(letters)))) x = input("Would you like to scrample the letters? Enter 1 to scramble or enter to guess :") word = input("What is your guess? :") word = word.lower() if checkSubset(word, letters) == True and checkWord(word) == True: print("Yes! You can make a word from those letters!") else: print("Sorry, you cannot make that word from those letters") userAnswer("agrsuteod") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T18:21:56.353", "Id": "37824", "Score": "0", "body": "What version of python are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-26T17:58:57.653", "Id": "89467", "Score": "0", "body": "Some of your print statements have typos: \"scrample\" should be \"scramble\"." } ]
[ { "body": "<p>Don't repeat yourself, like I have assigned the message to a variable <code>msg</code> so that if you need to change the message in future then, you don't have to edit at more than one place. Also, you don't need to compare for boolean values as <code>if</code> statement takes care of that.</p>\n\n<pre><code>def userAnswer(letters):\n print(\"Can you make a word from these letters? \"+str(letters)+\" :\")\n msg = \"Would you like to scrample the letters? Enter 1 to scramble or enter to guess :\"\n x = input(msg)\n while x == '1':\n print(''.join(random.sample(letters,len(letters))))\n x = input(msg)\n word = input(\"What is your guess? :\").lower()\n if checkSubset(word, letters) and checkWord(word):\n print(\"Yes! You can make a word from those letters!\")\n else:\n print(\"Sorry, you cannot make that word from those letters\")\n\nuserAnswer(\"agrsuteod\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T18:54:23.957", "Id": "24511", "ParentId": "24508", "Score": "2" } }, { "body": "<p>Before presenting my version, I would like to make a couple of comments:</p>\n\n<ul>\n<li>Use descriptive names. The name <code>userAnswer</code> gives me an impression of just getting the user's answer, nothing else. I like to suggest using names such as <code>startScrambleGame</code>, <code>runScrambleGame</code> or the like. </li>\n<li>Avoid 1-letter names such as <code>x</code> -- it does not tell you much.</li>\n<li>I don't know which version of Python you are using, but mine is 2.7 and <code>input()</code> gave me troubles: it thinks my answer is the name of a Python variable or command. I suggest using <code>raw_input()</code> instead.</li>\n<li>Your code calls <code>input()</code> 3 times. I suggest calling <code>raw_input()</code> only once in a loop. See code below.</li>\n<li>The <code>if checkSubset()...</code> logic should be the same, even if you drop <code>== True</code>.</li>\n</ul>\n\n<p>Here is my version of <code>userAnswer</code>, which I call <code>startScrambleGame</code>:</p>\n\n<pre><code>def startScrambleGame(letters):\n print(\"Can you make a word from these letters: {}?\".format(letters))\n while True:\n answer = raw_input('Enter 1 to scramble, or type a word to guess: ')\n if answer != '1':\n break\n print(''.join(random.sample(letters, len(letters))))\n\n word = answer.lower() \n if checkSubset(word, letters) and checkWord(word):\n print(\"Yes! You can make a word from those letters!\")\n else:\n print(\"Sorry, you cannot make that word from those letters\")\n\nstartScrambleGame(\"agrsuteod\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:11:53.973", "Id": "37840", "Score": "3", "body": "In Python 3, `raw_input()` has been replaced with `input()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:17:07.003", "Id": "37841", "Score": "2", "body": "OK. Sorry for living in stone age :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-26T18:09:07.693", "Id": "89468", "Score": "1", "body": "and the code uses `print()` as a function; the OP is almost certainly using Python 3." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:02:30.590", "Id": "24518", "ParentId": "24508", "Score": "6" } }, { "body": "<p>In Python there is an agreed-upon standard on how the code should look: <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8 -- Style Guide for Python Code</a>. The standard is to use lowercase names with underscores.</p>\n\n<p>For shuffling a list, there is a function in <code>random</code> aptly called <code>random.shuffle</code>. Use <code>.format</code> to interpolate values in string. Do not repeat yourself and just ask the thing once; one can combine these inputs together.</p>\n\n<p>Do not needlessly compare against <code>True</code> using <code>==</code>; just use the implied boolean value of the expression (and if you need to be explicit then use <code>is</code> instead of <code>==</code>). Store the letters in a list for easier modification. Also there is no need to write <code>check_subset</code> as a function, if you really want a set operation (that is, the same letter can occur multiple times in the word, even if only once in the original).</p>\n\n<p>Thus we get:</p>\n\n<pre><code>def ask_user(letter_word):\n letters = list(letter_word)\n while True:\n print(\"Can you make a word from these letters: {}?\"\n .format(''.join(letters)))\n\n choice = input(\"Enter your guess or 1 to scramble: \")\n\n if choice == '1':\n random.shuffle(letters)\n else:\n break # break out of the while loop, a guess was entered\n\n word = choice.lower() \n if set(word).issubset(letters) and check_word(word):\n print(\"Yes! You can make a word from those letters!\")\n else:\n print(\"Sorry, you cannot make that word from those letters\")\n\nask_user(\"agrsuteod\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-26T18:26:10.827", "Id": "89474", "Score": "0", "body": "The `Can you make a word ...` introduction is displayed only once in the OP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-26T18:27:53.383", "Id": "89475", "Score": "0", "body": "Yes, I did coalesce them together here, also I did change the input handling." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-26T18:08:36.740", "Id": "51774", "ParentId": "24508", "Score": "6" } } ]
{ "AcceptedAnswerId": "24518", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T18:17:16.813", "Id": "24508", "Score": "5", "Tags": [ "python", "beginner", "game", "python-3.x" ], "Title": "Guessing words from scrambled letters" }
24508
<p>Basically I have created a function which takes two lists of dicts, for example: </p> <pre><code>oldList = [{'a':2}, {'v':2}] newList = [{'a':4},{'c':4},{'e':5}] </code></pre> <p>My aim is to check for each dictionary key in the oldList and if it has the same dictionary key as in the newList update the dictionary, else append to the oldList. So in this case the key 'a' from oldList will get updated with the value 4, also since the keys b and e from the newList don't exist in the oldList append the dictionary to the oldList. Therefore you get <code>[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]</code>. </p> <p>Is there a better way to do this?</p> <pre><code>def sortList(oldList, newList): for new in newList: #{'a':4},{'c':4},{'e':5} isAdd = True for old in oldList: #{'a':2}, {'v':2} if new.keys()[0] == old.keys()[0]: #a == a isAdd = False old.update(new) # update dict if isAdd: oldList.append(new) #if value not in oldList append to it return oldList sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) print sortedDict [{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T22:34:04.337", "Id": "37835", "Score": "4", "body": "Why in the world do you have a list of single element dictionaries?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:33:20.897", "Id": "37844", "Score": "0", "body": "Please make an effort to name and structure questions appropriately. Because your code has nothing to do with sorting, I tried to find a better title—feel free to improve it further." } ]
[ { "body": "<p>You don't need the <code>isAdd</code> flag, instead you can structure your for loops like this:</p>\n\n<pre><code>for new, old in newList, oldList:\n if new.keys()[0] == old.keys()[0]:\n old.update(new)\n else:\n oldList.append(new)\nreturn oldList\n</code></pre>\n\n<p>As well, you might want to look at <a href=\"http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html\" rel=\"nofollow\">PEP</a> documents for coding style</p>\n\n<p>For reference, here is the rest of your code with those standards in place:</p>\n\n<pre><code> def sort_list(old_list, new_list):\n for new, old in new_list, old_list: \n if new.keys()[0] == old.keys()[0]:\n old.update(new)\n else:\n old_list.append(new)\n return old_list \n\nsorted_dict = sort_list([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}])\nprint sorted_dict\n\n[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]\n</code></pre>\n\n<p>Oh, and I'm assuming you are doing this for practice/homework, but the <a href=\"http://docs.python.org/2/library/stdtypes.html#dict.update\" rel=\"nofollow\">dict.update(iterable)</a> method does this exact thing far, far faster than you ever could.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T22:56:46.497", "Id": "37837", "Score": "1", "body": "Yeah, I'm pretty sure that code doesn't do the same thing. His code only adds to the list if none of the keys match, yours will it for every non-matching key. Furthermore, `for new, old in new_list, old_list`? I'm pretty sure that's not what you meant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T22:59:59.183", "Id": "37838", "Score": "0", "body": "Using his check (and multiple others) I got the code to produce the same output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:03:30.483", "Id": "37839", "Score": "1", "body": "Really? I get `ValueError: too many values to unpack` if I copy and paste your code from above. (After correcting a spacing error)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T22:50:51.687", "Id": "24516", "ParentId": "24514", "Score": "0" } }, { "body": "<pre><code>def sortList(oldList, newList):\n</code></pre>\n\n<p>Python convention is to lowercase_with_underscores for pretty much everything besides class names</p>\n\n<pre><code> for new in newList: #{'a':4},{'c':4},{'e':5}\n isAdd = True \n</code></pre>\n\n<p>Avoid boolean flags. They are delayed gotos and make it harder to follow your code. In this case, I'd suggest using an else: block on the for loop.</p>\n\n<pre><code> for old in oldList: #{'a':2}, {'v':2} \n if new.keys()[0] == old.keys()[0]: #a == a\n isAdd = False\n old.update(new) # update dict\n if isAdd:\n oldList.append(new) #if value not in oldList append to it\n return oldList \n\nsortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}])\nprint sortedDict\n</code></pre>\n\n<p>Why are you calling it sortList? You are merging lists, not sorting anything...</p>\n\n<p>Your whole piece of code would be quicker if implemented using dicts:</p>\n\n<pre><code># convert the lists into dictionaries\nold_list = dict(item.items()[0] for item in oldList)\nnew_list = dict(item.items()[0] for item in newList)\n# actually do the work (python already has a function that does it)\nold_list.update(new_list)\n# covert back to the list format\nreturn [{key:value} for key, value in old_list.items()]\n</code></pre>\n\n<p>All of which raises the question: why aren't these dicts already? What are you trying to do with this list of dicts stuff?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:24:31.817", "Id": "37842", "Score": "0", "body": "1) Your right about the lowercase_with_underscores and the name of the function.\n2) Your code snippet doesn't take order into account and will return `[{'a': 4}, {'b': 4}, {'e': 5}, {'v': 2}]` instead of `[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]`. I guess ordereddict should be used instead" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:28:14.920", "Id": "37843", "Score": "0", "body": "@user1741339, or you could sort the result, if what you really want is for the keys to be in sorted order. Regardless, its still bizarre to have a list of single-element dicts like this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:01:29.710", "Id": "24517", "ParentId": "24514", "Score": "1" } }, { "body": "<p>A list of 1-pair dictionaries makes no sense as data structure. You should join them to create a single dictionary. This way all your code reduces to:</p>\n\n<pre><code>d1 = {'a': 2, 'b': 2}\nd2 = {'a': 4, 'c': 4, 'e': 5}\nd3 = dict(d1, **d2)\n# {'a': 4, 'b': 2, 'c': 4, 'e': 5}\n</code></pre>\n\n<p>If you are going to union/merge dicts a lot, you can create a handy abstraction, more general than <code>dict(d1, **d2)</code>:</p>\n\n<pre><code>def merge_dicts(d1, d2):\n return dict(itertools.chain(d1.items(), d2.items()))\n</code></pre>\n\n<p>To convert list of dictionaries to a dictionary is simple:</p>\n\n<pre><code>d2 = dict(list(d.items())[0] for d in new_list)\n# {'a': 4, 'c': 4, 'e': 5}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-10T18:31:01.260", "Id": "373423", "Score": "0", "body": "`d3 = dict(d1, **d2)`\n I didn't know about this behaviour; super useful. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:39:24.300", "Id": "24519", "ParentId": "24514", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T22:08:41.477", "Id": "24514", "Score": "1", "Tags": [ "python", "hash-map" ], "Title": "Updating list of Dictionaries from other such list" }
24514
<p>Here is a problem I am trying to solve: trying to find missing photographs from a sequence of filenames. The problem boils down to: given an unsorted list of integers, return a sorted list of missing numbers. Below is my code.</p> <p>What I am looking for are:</p> <ul> <li>Are there more efficient algorithms?</li> <li>Is there any performance problem if the list is large (tens of thousands)</li> <li><p>Corner cases which does not work?</p> <pre><code>def find_missing_items(int_list): ''' Finds missing integer within an unsorted list and return a list of missing items &gt;&gt;&gt; find_missing_items([1, 2, 5, 6, 7, 10]) [3, 4, 8, 9] &gt;&gt;&gt; find_missing_items([3, 1, 2]) [] ''' # Put the list in a set, find smallest and largest items original_set = set(int_list) smallest_item = min(original_set) largest_item = max(original_set) # Create a super set of all items from smallest to largest full_set = set(xrange(smallest_item, largest_item + 1)) # Missing items are the ones that are in the full_set, but not in # the original_set return sorted(list(full_set - original_set)) if __name__ == '__main__': import doctest doctest.testmod() </code></pre></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:56:18.607", "Id": "37847", "Score": "0", "body": "Looks fine to me. `find_missing_items([-20000,0,20000])` returned correctly all 39998 items in less than 2s running on a old dual-core." } ]
[ { "body": "<p>For this</p>\n\n<pre><code>full_set = set(xrange(smallest_item, largest_item + 1))\n</code></pre>\n\n<p>I'd suggest inlining the min and max:</p>\n\n<pre><code>full_set = set(xrange(min(original), max(original) + 1))\n</code></pre>\n\n<p>You don't need to convert to a list before using sorted so:</p>\n\n<pre><code>sorted(list(full_set - original_set))\n</code></pre>\n\n<p>Can be written as:</p>\n\n<pre><code>sorted(full_set - original_set)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T00:00:30.003", "Id": "37849", "Score": "0", "body": "Beautiful. I especially like the last one: sorted() without list()." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:57:36.223", "Id": "24523", "ParentId": "24520", "Score": "6" } } ]
{ "AcceptedAnswerId": "24523", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:39:45.547", "Id": "24520", "Score": "5", "Tags": [ "python", "algorithm", "performance" ], "Title": "Finding missing items in an int list" }
24520
<p>Number can be very big.Script is taking number as a "number" list and crossing from 10-decimal based system to n-based system until list equals "5".I don't use letters like in 16-base system(hex).Example if result will be AB5 in hex list will be [10,11,5]. Some ideas how to optimize or/and change this to recursion?Any other hints/ideas for optimizing this code?</p> <pre><code>r=-1 number = [9,7,1,3,3,6,4,6,5,8,5,3,1] l=len(number) p=11 while (number[-1]!=5): i=1 while(i&lt;=l): #for x in reversed(xrange(1,i)): for x in xrange(i-1,0,-1): number[x]+=(number[x-1]*r) while(number[x]&lt;0): number[x]+=p number[x-1]-=1 if number[0]==0: #number.pop(0) del number[0] i-=1 l-=1 i+=1 #print p p+=2 r=-2 print p-2 </code></pre> <p>Algorithm in theory: From start we have some decimal number: 2507 . Base of decimal as everyone know is 10. list=[2, 5, 0, 7] :</p> <pre><code> [2, 5, 0, 7] # 2507 decimal(base 10) 1. l[1]=l[1]+(diff_between_earlier_and_current_base*l[1-1] 2. 1.l[2]=l[2]+(diff_between_earlier_and_current_base*l[2-1] 1.l[1]=l[1]+(diff_between_earlier_and_current_base*l[1-1] 3. 1.l[3]=l[3]+(diff_between_earlier_and_current_base*l[3-1] 1.l[2]=l[2]+(diff_between_earlier_and_current_base*l[2-1] 1.l[1]=l[1]+(diff_between_earlier_and_current_base*l[1-1] </code></pre> <p><strong>if some element (while doing this) will be &lt;0 we need to borrow from l[curent-1] until element&lt;0</strong> (if we doing subtraction below the line we are borrowing 10 but when we converting to 11 base we are borrowing 11 so when we have [2,-2] >> [1,9])</p> <pre><code> Result in 11 base: [1, 9, 7, 10] </code></pre> <p><strong>I think any way to optimize this is to write my code as recurrent function but i don't know how to do this.Anyone?</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:48:17.783", "Id": "37845", "Score": "2", "body": "Welcome to Code Review! Please add an explanation of what the purpose of this code is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:49:51.663", "Id": "37846", "Score": "1", "body": "What does it matter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:57:08.863", "Id": "37848", "Score": "2", "body": "Because it is hard to write good answers without this information. Take a look at the [about page](http://codereview.stackexchange.com/about): *\"Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.\"* I strongly recommend you follow these guidelines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T08:44:57.590", "Id": "37862", "Score": "3", "body": "Can you please update your question to add a precise description of what you are trying to achieve because I'm not quite sure this is very clear now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T18:03:51.013", "Id": "37898", "Score": "1", "body": "`p` seems the base of the numbers. But the base then changes? That's just odd... Can you give us an idea of the motivation here? Right now it just seems a bunch of pointless calculation and its hard to see how to convey its intent better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T18:22:29.300", "Id": "37901", "Score": "0", "body": "This site is for help optimizing code or just asking what is the code for? Yes p=11 because on start we have decimal number.Next will be in 11-base.The question is how to write this more optimal rather than what it is for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T00:34:26.940", "Id": "37916", "Score": "4", "body": "Here's your optimised version of the code : `print 17`.\nPlease keep in mind that people who have commented here are people who would have been willing to help you if they could understand what you are trying to achieve." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T16:57:25.283", "Id": "37941", "Score": "0", "body": "Very funny.Number can be different." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T14:29:30.550", "Id": "38044", "Score": "3", "body": "Actually the site is for improving your code both with performance and style. The biggest problem with your code as it stands is that its inscrutable. It would help us suggest way to make it faster and easier to follow if you'd let us know what the fried monkey it's trying to accomplish. You don't have to tell us what the code is for, but you are much more likely to get help if you do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T14:36:33.210", "Id": "38045", "Score": "2", "body": "The operations that you do are strange and difficult to optimize. This suggests that either you are attempting to optimize silly code (which isn't likely to get much help) or you've taken a strange tact to solve a bigger problem and if we knew that bigger problem we could provide better help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T22:07:29.980", "Id": "38062", "Score": "0", "body": "Assuming my understanding is ok, I've answered your solution. Had you accepted to give more information in the first place, you'd probably had a better solution in a smaller time." } ]
[ { "body": "<p>I can't do much to help optimize this code as I don't know what its trying to do.</p>\n\n<pre><code>r=-1\nnumber = [9,7,1,3,3,6,4,6,5,8,5,3,1]\n</code></pre>\n\n<p>I suggest presenting this as a function which takes number as a parameter. Code also runs faster in functions.</p>\n\n<pre><code>l=len(number)\np=11\n</code></pre>\n\n<p>Use names that mean things. Single letter variables names make your code hard to read</p>\n\n<pre><code>while (number[-1]!=5):\n</code></pre>\n\n<p>You don't need the parens.</p>\n\n<pre><code> i=1\n while(i&lt;=l):\n #for x in reversed(xrange(1,i)):\n</code></pre>\n\n<p>Delete dead code, don't comment it out</p>\n\n<pre><code> for x in xrange(i-1,0,-1):\n number[x]+=(number[x-1]*r)\n</code></pre>\n\n<p>No need for parens, let your binary operates breath with some spaces</p>\n\n<pre><code> while(number[x]&lt;0):\n number[x]+=p\n number[x-1]-=1\n\n\n\n if number[0]==0:\n #number.pop(0)\n del number[0]\n i-=1\n l-=1\n</code></pre>\n\n<p>You don't actually gain much by deleting the empty places in the number. Your code will operate just the same if leave them with zeros. It'll simplify your code if you do that.</p>\n\n<pre><code> i+=1\n#print p\n p+=2\n r=-2\n</code></pre>\n\n<p>Rather then this, add a line</p>\n\n<pre><code> r = 1 if p == 11 else 2\n</code></pre>\n\n<p>to the beginning of the loop. That way r is set in only one place</p>\n\n<pre><code>print p-2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T21:12:07.917", "Id": "38061", "Score": "0", "body": "Thanks for suggestions.but my script is slower with they." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T14:42:12.600", "Id": "24636", "ParentId": "24521", "Score": "2" } }, { "body": "<p>From the explanation you provided, I think this does what you want to do :</p>\n\n<pre><code>def listToNumber(l,b):\n n=0\n for i in l:\n n = i+b*n\n return n\n\ndef numberToList(n,b):\n l=[]\n while n&gt;0:\n l.append(n%b)\n n/=b\n return l[::-1]\n\nl=[9,7,1,3,3,6,4,6,5,8,5,3,1]\nbase=10\nn=listToNumber(l,base)\nwhile numberToList(n,base)[-1] != 5:\n base+=1\nprint base\n</code></pre>\n\n<p>Tested on both <code>[9,7,1,3,3,6,4,6,5,8,5,3,1]</code> and <code>[9,7,1,3,3,6,4,6,5,8,5,3,1]*10</code> , it seems like it returns the same thing but my implementation is much faster and much easier to understand.</p>\n\n<p>A possible improvement would be :</p>\n\n<pre><code>def lastDigitInBase(n,b):\n return n%b\n\nl=[9,7,1,3,3,6,4,6,5,8,5,3,1]*10\nbase=10\nn=listToNumber(l,base)\nwhile lastDigitInBase(n,base) != 5:\n base+=1\nprint base\n</code></pre>\n\n<p>On that final version and working with <code>[9,7,1,3,3,6,4,6,5,8,5,3,1]*30</code>, my code returns 13259 in 0.2 seconds while your implementation return the same result in more than 3 minutes and 16 seconds which is roughly 1000 times slower.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T22:15:21.117", "Id": "38063", "Score": "0", "body": "Ok, but what happened to the stuff he was doing with `r`? That's the part that still confuses me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T22:25:29.270", "Id": "38064", "Score": "0", "body": "I have no idea. My feeling is that the code was way too complicated for what it was trying to achieve. Once I understood the problem, I wrote this simple solution and it seems like it returns the same thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T00:40:45.763", "Id": "38067", "Score": "0", "body": "Nice.For different number with pypy: my: Initial run time: 1.15500020981 ,\nyours: Initial run time: 0.999000072479 ,but can you write as recursive function without using \">>\" , \"/\" or \"%\" ? That's the point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T07:31:50.673", "Id": "38072", "Score": "0", "body": "r = previous_base - current_base. The initial step is base-10 -> base-11, hence -1; then base-11 to base-13 (11+2), hence -2. Why he's jumping by 2, I don't know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T11:06:46.383", "Id": "38087", "Score": "0", "body": "Do not think about it, it is intentionally.Base 10 > 11 > 13 > 15 > 17 > 19 > 21.Only odd." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T15:02:30.600", "Id": "38100", "Score": "0", "body": "@prosze_wyjsc_z_kosmosu, why do you want recursion? Why do you want to avoid \">>\", \"/\", and \"%\"? That's rather like trying to build a house with using wood." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T17:07:31.783", "Id": "38111", "Score": "0", "body": "I want to check something,that can't be checked if I will use(sorry for grammar) \">>\" , \"/\" or \"%\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-06T17:19:35.033", "Id": "38317", "Score": "0", "body": "@prosze_wyjsc_z_kosmosu, what do you want to check?" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-02T22:04:46.063", "Id": "24653", "ParentId": "24521", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-29T23:42:34.243", "Id": "24521", "Score": "-3", "Tags": [ "python", "optimization" ], "Title": "Any way to change optimize this or/and change to recursion?" }
24521
<p>Basically I have a 2d list containing movies. Movies are specified by name, version and description. For example</p> <p><code>['Jaws', 1, 'Movie about sharks']</code> - where <code>Jaws</code> = name, <code>1</code> = version and <code>Movie about sharks</code> = description.</p> <p>My result is a dictionary which contains a map between name and description. But name should be updated to contain the version for e.g </p> <p><code>['Jaws', 2, 'Movie about more sharks']</code> - should now be : </p> <p><code>{'JawsV2': 'Movie about more sharks'}</code></p> <p>Is there a more pythonic way to do this?</p> <pre><code>def movie_version_map(): movies = [['Jaws', 1, 'Movie about sharks'], ['Jaws', 2, 'Movie about more sharks'], ['HarryPotter', 1, 'Movie about magic'], ['HarryPotter', 4, 'Movie about more magic']] for movie in movies: if movie[1] != 1: movie[0] = ''.join([movie[0], 'V',str(movie[1])]) newversion = dict([(movie[0],movie[2]) for movie in movies]) return newversion </code></pre> <p>Output</p> <pre><code>{'Jaws': 'Movie about sharks', 'HarryPotter': 'Movie about magic', 'HarryPotterV4': 'Movie about more magic', 'JawsV2': 'Movie about more sharks'} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T13:33:52.420", "Id": "37876", "Score": "1", "body": "What if a movie was to be called 'somethingV1' ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T13:53:57.153", "Id": "37880", "Score": "0", "body": "this is a case where if version is 1 leave the name as it is" } ]
[ { "body": "<p>A simple <a href=\"http://www.youtube.com/watch?v=pShL9DCSIUw\">dict comprehension</a> and use of <a href=\"http://docs.python.org/3.3/library/stdtypes.html#str.format\"><code>str.format()</code></a> will do the job here:</p>\n\n<pre><code>&gt;&gt;&gt; {\"{}V{}\".format(name, version): description \n for name, version, description in movies}\n{'HarryPotterV1': 'Movie about magic', \n 'HarryPotterV4': 'Movie about more magic', \n 'JawsV1': 'Movie about sharks', \n 'JawsV2': 'Movie about more sharks'}\n</code></pre>\n\n<p>Or, in very old versions of Python where dict comprehensions don't exist, simple replace with <code>dict()</code> and a generator expression - e.g: <code>dict(... for ... in moves)</code>.</p>\n\n<p>Note that if this is just because you want to have the data as keys, you don't need to turn them into a string, a tuple can be a key too:</p>\n\n<pre><code>&gt;&gt;&gt; {(name, version): description \n for name, version, description in movies}\n{('Jaws', 1): 'Movie about sharks', \n ('HarryPotter', 4): 'Movie about more magic', \n ('Jaws', 2): 'Movie about more sharks', \n ('HarryPotter', 1): 'Movie about magic'}\n</code></pre>\n\n<p>This would be more appropriate where you don't need the strings, as it means you don't have to parse stuff out or create strings for keys, and makes the data easier to manipulate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T13:42:31.103", "Id": "24537", "ParentId": "24534", "Score": "8" } }, { "body": "<p>I included the case in which version is 1</p>\n\n<pre><code>{'{}{}'.format(name, version &gt; 1 and 'V'+str(version) or ''):\\ \ndescription for name,version,description in movies}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T16:54:10.317", "Id": "24543", "ParentId": "24534", "Score": "1" } }, { "body": "<p>I suggest to use list comprehension as others did. However, to simplify <em>reading</em>, I am creating a separate function called <em>make_title</em> to deal with combining title and version.</p>\n\n<pre><code>def make_title(title, version):\n if version != 1:\n title = '{}V{}'.format(title, version)\n return title\n\ndef movie_version_map():\n movies = [['Jaws', 1, 'Movie about sharks'], \n ['Jaws', 2, 'Movie about more sharks'], \n ['HarryPotter', 1, 'Movie about magic'], \n ['HarryPotter', 4, 'Movie about more magic']]\n\n new_version = dict((make_title(title, version), description) for title, version, description in movies)\n return new_version\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T17:59:42.570", "Id": "24545", "ParentId": "24534", "Score": "1" } } ]
{ "AcceptedAnswerId": "24543", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T12:45:29.473", "Id": "24534", "Score": "1", "Tags": [ "python", "hash-map" ], "Title": "update list based on other values" }
24534
<p>There have been many posts here about enums in python, but none seem to be both type safe and simple. Here is my attempt at it. Please let me know if you see anything obviously wrong with it. </p> <pre><code>def typeSafeEnum(enumName, *sequential): topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential)))) vals = map(lambda x: type(x,(topLevel,),{}), sequential) for k, v in zip(sequential, vals): setattr(topLevel, k, v()) return topLevel </code></pre> <p>Then to test it:</p> <pre><code>Colors = typeSafeEnum('Colors', 'RED', 'GREEN', 'BLUE') if __name__ == '__main__': x = Colors.RED assert isinstance(x, Colors) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T11:46:54.223", "Id": "37877", "Score": "1", "body": "What do you mean by \"type safe\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T11:51:10.883", "Id": "37878", "Score": "0", "body": "Good point. It should not be comparable to other types. E.g., you should not be able to accidentally use an int instead of Colors.RED" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-16T19:57:36.567", "Id": "177725", "Score": "0", "body": "Note for posterity: as of Python 3.4, there is a standard [`enum`](https://docs.python.org/3/library/enum.html) module and it's available via `pip install enum34` for older versions." } ]
[ { "body": "<pre><code>def typeSafeEnum(enumName, *sequential):\n</code></pre>\n\n<p>Python convention is <code>lowercase_with_underscores</code> for functions and parameters. Although since this is a type factory its not totally clear what convention should appply. I also wonder if passing the enum values as a list might be better.</p>\n\n<pre><code> topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))\n</code></pre>\n\n<p>There is no point in the dict you are passing since you just setattr all the enums in place already. Here you set all the enum values up with None initially and then fill them in. Why? I can also see why you call this topLevel but its not an immeadiately obvious name</p>\n\n<pre><code> vals = map(lambda x: type(x,(topLevel,),{}), sequential)\n</code></pre>\n\n<p>List comprehensions are generally preffered to calling map with a lambda. But also, why? Just do this in the for loop. You don't gain anything by having it done in a map and then zipping over it.</p>\n\n<pre><code> for k, v in zip(sequential, vals):\n</code></pre>\n\n<p>I suggest longer less abbreviated names</p>\n\n<pre><code> setattr(topLevel, k, v())\n return topLevel\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T15:14:36.633", "Id": "37977", "Score": "0", "body": "Thanks, Winston! I will do some revisions and post a new version. Besides the style and code cleanliness, does the approach seem correct to you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T15:30:47.353", "Id": "37978", "Score": "0", "body": "@user1094206, I avoid enums generally in favor of actually defining classes for what would be an enum value. That way I can take advantage of polymorphism and such. So stylistically, I wouldn't use this approach at all." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T15:17:27.880", "Id": "24541", "ParentId": "24536", "Score": "3" } }, { "body": "<p>I'm not sure why you would want to use a Java idiom in Python. The problems TypeSafe Enums fix in Java are not really issues in Python as far as I can tell.</p>\n\n<p>If you can use a regular enumeration you can use <a href=\"http://docs.python.org/2/library/collections.html#collections.namedtuple\" rel=\"nofollow\"><code>collections.namedtuple</code></a>.</p>\n\n<pre><code>from collections import namedtuple\nColors = namedtuple('Colors', ['RED', 'GREEN', 'BLUE'])._make(xrange(3))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-08T02:13:13.613", "Id": "24838", "ParentId": "24536", "Score": "1" } } ]
{ "AcceptedAnswerId": "24541", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T11:38:52.837", "Id": "24536", "Score": "3", "Tags": [ "python", "enum", "type-safety" ], "Title": "An attempt at a simple type safe python enum" }
24536
<p>I have a function that I need to optimize:</p> <pre><code>def search(graph, node, maxdepth = 10, depth = 0): nodes = [] for neighbor in graph.neighbors_iter(node): if graph.node[neighbor].get('station', False): return neighbor nodes.append(neighbor) for i in nodes: if depth+1 &gt; maxdepth: return False if search(graph, i, maxdepth, depth+1): return i return False </code></pre> <p><code>graph</code> should be a networkx graph object. How can I optimize this? This should find the closest node in the network with <code>'station'</code> attribute to <code>True</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T01:17:28.670", "Id": "37924", "Score": "0", "body": "You might have a bug: `if search(graph, i, ...): return i` ==> the search() function might return something other than i, yet you are returning i." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T01:18:19.243", "Id": "37925", "Score": "0", "body": "Not a bug, this should return the first step to the station." } ]
[ { "body": "<pre><code>def search(graph, node, maxdepth = 10, depth = 0):\n nodes = []\n for neighbor in graph.neighbors_iter(node):\n if graph.node[neighbor].get('station', False):\n return neighbor\n nodes.append(neighbor)\n</code></pre>\n\n<p>Why store the neighbor in the list? Instead of putting it in a list, just combine your two loops.</p>\n\n<pre><code>for i in nodes:\n</code></pre>\n\n<p><code>i</code> typically stands for index. I suggest using neighbor to make your code easier to follow</p>\n\n<pre><code> if depth+1 &gt; maxdepth:\n return False\n</code></pre>\n\n<p>This doesn't relate to this individual node. What is it doing inside this loop?</p>\n\n<pre><code> if search(graph, i, maxdepth, depth+1):\n return i\n return False\n</code></pre>\n\n<p>Failure to find is better reported using <code>None</code> rather than <code>False</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T19:01:46.470", "Id": "37903", "Score": "0", "body": "The first loop needs to be run on all litems and if none are station, it should search recursively" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T19:32:01.407", "Id": "37904", "Score": "2", "body": "@fread2281, my bad... I didn't think of that. Actually, I think that makes your code wrong. Its implementing a DFS, so it wasn't neccesairlly find the closest \"station\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T18:56:45.480", "Id": "24549", "ParentId": "24546", "Score": "4" } }, { "body": "<p>Is there any reason that you are shy from using networkx's functions such as breadth-first search <code>bfs_tree()</code> or depth-first search <code>dfs_tree()</code>? Here is an example of breadth-first search:</p>\n\n<pre><code>import networkx as nx\n...\nfor visiting_node in nx.bfs_tree(graph, node):\n if graph.node[visiting_node].get('station', False):\n print 'Found it' # Do something with visiting_node\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T01:06:00.263", "Id": "37920", "Score": "0", "body": "Good point, although it seems he couldn't do the max_depth with it..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T01:12:48.663", "Id": "37921", "Score": "0", "body": "I think max_depth is to prevent circular links in a graph. the `bfs_tree()` function ensures no circular references." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T01:14:35.230", "Id": "37922", "Score": "0", "body": "Ah, you may well be right." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T01:17:05.533", "Id": "37923", "Score": "0", "body": "`max_depth` is to limit time. I need speed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T16:54:00.280", "Id": "37940", "Score": "0", "body": "I reimplemented it using a custom BFS and thanks for the indirect pointer!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T00:58:41.020", "Id": "24557", "ParentId": "24546", "Score": "4" } } ]
{ "AcceptedAnswerId": "24549", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T18:18:15.363", "Id": "24546", "Score": "3", "Tags": [ "python", "performance", "recursion", "graph" ], "Title": "Finding the closest node" }
24546
<p>I have a weighted BFS search in python for networkx that I want to optimize:</p> <pre><code>def bfs(graph, node, attribute, max = 10000): # cProfile shows this taking up the most time. Maybe I could use heapq directly? Or maybe I would get more of a benefit making it multithreaded? queue = Queue.PriorityQueue() num = 0 done = set() for neighbor, attrs in graph[node].iteritems(): # The third element is needed because we want to return the ajacent node towards the target, not the target itself. queue.put((attrs['weight'], neighbor, neighbor)) while num &lt;= max and not queue.empty(): num += 1 item = queue.get() if graph.node[item[1]].get(attribute, False): return item[2] for neighbor, attrs in graph[item[1]].iteritems(): if neighbor not in done: queue.put((item[0] + attrs['weight'], neighbor, item[2])) done.add(neighbor) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T17:20:41.260", "Id": "37942", "Score": "0", "body": "Definitely use `heapq` directly when you don't need the thread synchronization that `Queue.PriorityQueue` provides." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T17:32:00.813", "Id": "37946", "Score": "0", "body": "Right, but should I go threading or heapq?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T18:40:54.187", "Id": "37951", "Score": "0", "body": "@fread2281, no reason to use threading here" } ]
[ { "body": "<p>I understand the reason for you to implement your own search routine instead of using what is readily available is because you want to return the node that is the <em>first step toward the target</em> instead of the target itself. Before presenting my code, I would like to raise a couple of suggestions:</p>\n\n<h3>Use better descriptive names</h3>\n\n<p>Names like <em>max</em>, <em>num</em> are not meaningful. I suggest to use names such as <em>max_visiting_nodes</em>, <em>visit_count</em> instead.</p>\n\n<p>Similarly, item[1], item[2], ... do not mean much. Instead of <code>item = queue.get()</code>, how about something like <code>weigh, target_node, first_step_node = queue.get()</code></p>\n\n<h3>Correctness.</h3>\n\n<p>If you have a graph like this:</p>\n\n<p><img src=\"https://www.evernote.com/shard/s1/sh/00639fa5-e44f-4066-a92c-8b72ad3ec972/c3ec750738639d87052c8cca7bfc8f2f/res/8ff8459a-3e10-4762-8522-a6183e746cf3/skitch.png\" alt=\"graph1\"></p>\n\n<p>The red colors are the weight. If search starts with node 1 and node 2 has the attribute you want, the <em>first step toward the target</em> would be node 5, since the path 1-5-4-3-2 is shorter (weight = 4), instead of 1-2 (weight = 10). Your algorithm returns 2, not 5.</p>\n\n<h3>Propose solution</h3>\n\n<p>I propose using what <em>networkx</em> offering, meaning <code>bfs_tree()</code> to find a list of nodes, then <code>shortest_path()</code>:</p>\n\n<pre><code>def bfs_find_first_step(graph, node, attribute, max_visiting_nodes = 10000):\n for visit_count, visiting_node in enumerate(nx.bfs_tree(graph, node)):\n if visit_count == max_visiting_nodes: break\n if graph.node[visiting_node].get(attribute):\n shortest_path = nx.shortest_path(graph, node, visiting_node, 'weight')\n if len(shortest_path) == 1:\n return node # Only current node qualifies\n else:\n return shortest_path[1] # First step toward the target\n return None\n</code></pre>\n\n<p>A few notes:</p>\n\n<ul>\n<li>In my solution, I use the visit_count (AKA <code>num</code>) to limit the search time, the same way you would like to.</li>\n<li>the <code>nx.shortest_path()</code> function takes in as the fourth parameter, the string name of the edge attribute which used for calculating the weight. I think this is what you have in mind.</li>\n<li>If you start search from node 1, and only node 1 has the attribute your want, your function returns 5, whereas mine returns 1. I think mine is more correct, but I am not sure--it might not be what you want. This case is when <code>len(shortest_path) == 1</code> in my code.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T04:49:24.737", "Id": "37956", "Score": "0", "body": "Wow. A few things: `bfs_tree` is slow compared to my method for large networks and small `max_visiting_nodes` (and maybe also my optimized version from the other answer for all networks). Also your version iterates at least twice (at least once in `bfs_tree`) and that is unnecessary. When I get some time, I may go into netowrkx and make a version of A* for search. Also `bfs_search` is not what I am doing, highlighted my the other answer, so `bfs_tree` is not correct here. Your answer is BFS and does not really use `shortest_path` for deciding what node to return (it gets first instead)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T04:51:40.683", "Id": "37957", "Score": "0", "body": "Also your solution will give 1 by 1->2 (it does not matter here, but for more complex networks it will)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T16:45:45.473", "Id": "37983", "Score": "0", "body": "I just found out that `bfs_tree()` does not seem to return the correct sequence. I am doing some tests at this moment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T23:47:54.793", "Id": "38008", "Score": "0", "body": "BFS is breadth-first-search, so it returns based on depth, not weight. http://en.wikipedia.org/wiki/Breadth-first_search" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T03:53:29.833", "Id": "24584", "ParentId": "24572", "Score": "1" } } ]
{ "AcceptedAnswerId": "24574", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T17:06:50.900", "Id": "24572", "Score": "2", "Tags": [ "python", "queue" ], "Title": "Optimize BFS weighted search in python" }
24572
<p>My implemented regex pattern contains two repeating symbols: <code>\d{2}\.</code> and <code>&lt;p&gt;(.*)&lt;/p&gt;</code>. I want to get rid of this repetition and asked myself if there is a way to loop in Python's regular expression implementation.</p> <p><strong>Note</strong>: I do <strong>not</strong> ask for help to parse a XML file. There are many great tutorials, howtos and libraries. <strong>I am looking for means to implement repetition in regex patterns.</strong> </p> <p>My code:</p> <pre><code>import re pattern = ''' &lt;menu&gt; &lt;day&gt;\w{2} (\d{2}\.\d{2})\.&lt;/day&gt; &lt;description&gt; &lt;p&gt;(.*)&lt;/p&gt; &lt;p&gt;(.*)&lt;/p&gt; &lt;p&gt;(.*)&lt;/p&gt; &lt;/description&gt; ''' my_example_string = ''' &lt;menu&gt; &lt;day&gt;Mi 03.04.&lt;/day&gt; &lt;description&gt; &lt;p&gt;Knoblauchcremesuppe&lt;/p&gt; &lt;p&gt;Rindsbraten "Esterhazy" (Gem&amp;uuml;serahmsauce)&lt;/p&gt; &lt;p&gt;mit H&amp;ouml;rnchen und Salat&lt;/p&gt; &lt;/description&gt; &lt;/menu&gt; ''' re.findall(pattern, my_example_string, re.MULTILINE) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T14:30:35.247", "Id": "37974", "Score": "1", "body": "Parsing XML with regex is usually wrong, what are you really trying to accomplish?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T14:37:01.643", "Id": "37975", "Score": "0", "body": "The XML is malformed what prevents a usage of LXML and Xpath. I easily can retrieve the deserved data, but I want to find a way to avoid these repetitions in any regex patterns." } ]
[ { "body": "<p>Firstly, just for anyone who might read this: DO NOT take this as an excuse to parse your XML with regular expressions. It generally a really really bad idea! In this case the XML is malformed, so its the best we can do.</p>\n\n<p>The regular expressions looping constructs are <code>*</code> and <code>{4}</code> which you already using. But this is python, so you can construct your regular expression using python:</p>\n\n<pre><code>expression = \"\"\"\n&lt;menu&gt;\n&lt;day&gt;\\w{2} (\\d{2}\\.\\d{2})\\.&lt;/day&gt;\n&lt;description&gt;\n\"\"\"\n\nfor x in xrange(3):\n expression += \"&lt;p&gt;(.*)&lt;/p&gt;\"\n\nexpression += \"\"\"\n&lt;/description&gt;\n&lt;/menu&gt;\n\"\"\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T18:40:05.540", "Id": "37990", "Score": "0", "body": "What about `expression += \"<p>(.*)</p>\\n\" * 3` ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T17:45:04.230", "Id": "24599", "ParentId": "24594", "Score": "1" } } ]
{ "AcceptedAnswerId": "24599", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T13:38:29.410", "Id": "24594", "Score": "1", "Tags": [ "python", "regex" ], "Title": "Improvment of and looping in a regular expression pattern" }
24594
<p>I'm working on a project where I need to solve for one of the roots of a quartic polymonial many, many times. Is there a better, i.e., faster way to do this? Should I write my own C-library? The example code is below.</p> <pre><code># this code calculates the pH of a solution as it is # titrated with base and then plots it. import numpy.polynomial.polynomial as poly import numpy as np import matplotlib.pyplot as plt # my pH calculation function # assume two distinct pKa's solution is a quartic equation def pH(base, Facid1, Facid2): ka1 = 2.479496e-6 ka2 = 1.87438e-9 kw = 1.019230e-14 a = 1 b = ka1+ka2+base c = base*(ka1+ka2)-(ka1*Facid1+ka2*Facid2)+ka1*ka2-kw d = ka1*ka2*(base-Facid1-Facid2)-kw*(ka1+ka2) e = -kw*ka1*ka2 p = poly.Polynomial((e,d,c,b,a)) return -np.log10(p.roots()[3]) #only need the 4th root here # Define the concentration parameters Facid1 = 0.002 Facid2 = 0.001 Fbase = 0.005 #the maximum base addition # Generate my vectors x = np.linspace(0., Fbase, 200) y = [pH(base, Facid1, Facid2) for base in x] # Make the plot frame fig = plt.figure() ax = fig.add_subplot(111) # Set the limits ax.set_ylim(1, 14) ax.set_xlim(np.min(x), np.max(x)) # Add my data ax.plot(x, y, "r-") # Plot of the data use lines #add title, axis titles, and legend ax.set_title("Acid titration") ax.set_xlabel("Moles NaOH") ax.set_ylabel("pH") #ax.legend(("y data"), loc='upper left') plt.show() </code></pre> <p>Based on the answer, here is what I came up with. Any other suggestions?</p> <pre><code># my pH calculation class # assume two distinct pKa's solution is a quartic equation class pH: #things that don't change ka1 = 2.479496e-6 ka2 = 1.87438e-9 kw = 1.019230e-14 kSum = ka1+ka2 kProd = ka1*ka2 e = -kw*kProd #things that only depend on Facid1 and Facid2 def __init__(self, Facid1, Facid2): self.c = -(self.ka1*Facid1+self.ka2*Facid2)+self.kProd-self.kw self.d = self.kProd*(Facid1+Facid2)+self.kw*(self.kSum) #only calculate things that depend on base def pHCalc(self, base): pMatrix = [[0, 0, 0, -self.e], #construct the companion matrix [1, 0, 0, self.d-base*self.kProd], [0, 1, 0, -(self.c+self.kSum*base)], [0, 0, 1, -(self.kSum+base)]] myVals = la.eigvals(pMatrix) return -np.log10(np.max(myVals)) #need the one positive root </code></pre>
[]
[ { "body": "<p>NumPy computes the roots of a polynomial by first constructing the companion matrix in Python and then solving the eigenvalues with LAPACK. The companion matrix case looks like this using your variables (as <code>a</code>==1):</p>\n\n<pre><code>[0 0 0 -e\n 1 0 0 -d\n 0 1 0 -c\n 0 0 1 -b]\n</code></pre>\n\n<p>You should be able to save some time by updating a matrix like this directly on each iteration of <code>base</code>. Then use <code>numpy.linalg.eigvals(m).max()</code> to obtain the largest eigenvalue. See <a href=\"https://github.com/numpy/numpy/blob/master/numpy/polynomial/polynomial.py#L1390\" rel=\"nofollow\">the sources</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T20:22:31.837", "Id": "38140", "Score": "0", "body": "Yes, this works. I had already caught the need for a max(). I'm also thinking I could use a class construction to initialize some invariants, so I don't have to recalculate them each time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T21:33:50.927", "Id": "38151", "Score": "1", "body": "Did some timing work with the full problem. Original code (using polynomial module) 5.48 sec, first step (using eigenvalue approach) 2.76 sec, final step (using eigenvalues and class as shown above) 2.68 sec." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T18:05:21.813", "Id": "24676", "ParentId": "24671", "Score": "3" } } ]
{ "AcceptedAnswerId": "24676", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T16:26:46.280", "Id": "24671", "Score": "2", "Tags": [ "python", "numpy" ], "Title": "Using numpy polynomial module - is there a better way?" }
24671
<p>Think of the numpad number layout.</p> <p><code>hvd = horizontal, vertical or diagonal</code></p> <p><code>coord = 1,2 or 3</code> if horizontal or vertical and 1 or 2 if diagonal (1 is up, 2 is down)...</p> <p><code>hello('v', 2)</code> - Asking for the second vertical column etc</p> <pre><code>def hello(hvd, coord): if hvd == 'h': print "horizontal it is" if coord == 1: print "789" elif coord == 2: print "456" elif coord == 3: print "789" else: print "coord is wrong" elif hvd == 'v': print "vertical it is" if coord == 1: print "741" elif coord == 2: print "852" elif coord == 3: print "963" else: print "coord is wrong" elif hvd == 'd': print "diagonal it is" if coord == 1: print "159" elif coord == 2: print "753" else: print "coord is wrong" else: print "hvd is wrong" </code></pre> <p>I just want a critique on this function. I am interested in knowing if there is a nicer way to do what I am doing and if there is anything wrong with my code.</p> <p>It seems quite hard to look at especially since it contains place holder statements and the actual statements I want might be 10 lines long each... Would be unwieldy surely?</p>
[]
[ { "body": "<p>A nicer way to do the same would be to use a dictionary:</p>\n\n<pre><code>def hello(hvd, coord): \n d = {'h': [\"789\", \"456\", \"123\"],\n 'v': [\"741\", \"852\", \"963\"], \n 'd': [\"159\", \"753\"]}\n try:\n print d[hvd][coord-1]\n except IndexError:\n print \"coord is wrong\"\n except KeyError:\n print \"hvd is wrong\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-29T13:06:52.497", "Id": "207124", "Score": "1", "body": "Are you sure you want to print from inside the function? Isn't returning a value more reusable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-30T06:45:15.567", "Id": "207277", "Score": "1", "body": "@Caridorc Yes, that would be a further improvement. alexwlchan has that angle covered now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-04T13:47:51.037", "Id": "24710", "ParentId": "24703", "Score": "6" } }, { "body": "<p>A few suggestions:</p>\n\n<ul>\n<li><p><strong>A function should either do some work, or return a value – not both.</strong> Your function is (1) deciding which set of digits to return, and (2) printing them to stdout. It should just return the set of digits, and let the caller decide how to use them.</p></li>\n<li><p><strong>Don’t use print statements for errors.</strong> Raise exceptions instead – that allows callers to handle problems gracefully with <code>try … except</code>, rather than having to parse what just got sent to stdout.</p>\n\n<p>As a corollary, it would be good for your error messages to include the invalid value. This can be useful for debugging – if your function is several layers deep and throws an exception, it may not be obvious to the end user what the bad value was.</p>\n\n<p>You may also want to specify valid values.</p></li>\n<li><p><strong>Use a dictionary for the values, not multiple if branches.</strong> This is a more concise and readable way to express the information.</p></li>\n<li><p><strong>You can be more defensive to user input.</strong> If the user enters 'H', 'V' or 'D', their intention is unambiguous – but your code will reject it. Perhaps lowercase their input first?</p></li>\n<li><p><strong>I have no idea why the function is called hello().</strong> It doesn’t tell me anything about what the function does. There’s not a docstring either. A better name and documentation would tell me:</p>\n\n<ul>\n<li>What the function is supposed to do</li>\n<li>What arguments I’m supposed to supply</li>\n</ul>\n\n<p></p></p>\n\n<p>You’ve already written most of this in the question – just put it in the code!</p>\n\n<p></p></p></li>\n</ul>\n\n<p></p></p>\n\n<p>Here’s a partially revised version:</p>\n\n<pre><code>def numpad_digits(hvd, coord):\n digits = {\n \"h\": [\"123\", \"456\", \"789\"],\n \"v\": [\"741\", \"852\", \"963\"], \n \"d\": [\"159\", \"753\"]\n }\n try:\n # Offset by one - the user will be thinking of a 1-indexed list\n return digits[hvd.lower()][coord-1]\n except IndexError:\n raise ValueError(\"Invalid value for coord: %s\" % coord)\n except KeyError:\n raise ValueError(\"Invalid value for hvd: %s\" % hvd)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-29T16:42:43.233", "Id": "112233", "ParentId": "24703", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-04T11:51:31.947", "Id": "24703", "Score": "3", "Tags": [ "python" ], "Title": "Numpad number layout" }
24703
<p>I have written a small snippet to validate a substring in a string in O(n). I have tested the code using some combinations. I require your help to let me know if there are any bugs in my code with respect to any other cases that I might have missed out:-</p> <pre><code>class StringClass( object ): def __init__( self, s ): self._s = s def __contains__( self, s ): ind = 0 for ch in self._s: if ind &lt; len( s ) and ch == s[ind]: ind += 1 elif ind &gt;= len( s ): return True elif ch == s[0]: ind = 1 elif ch != s[ind]: ind = 0 if ind &gt;= len( s ): return True if __name__ == '__main__': s = StringClass( 'I llove bangaolove' ) print 'love' in s </code></pre> <p>PS: Here, Instead of trying to find the string 'love' in 'I llove bangalove', I'm using the other method: i.e. to find if the string 'I llove bangalove' contains 'love'. </p> <p>Please let me know if there are any corrections to be made here.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-04T18:20:19.363", "Id": "38191", "Score": "0", "body": "this is O(n), but incorrect (as @Poik pointed out). There are no O(n) algorithms for string matching, maybe O(n+m), using Rabin-Karp or Knuth-Morris-Pratt (n=length of string, m=length of string to match). Look them up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-06T15:12:27.397", "Id": "38315", "Score": "1", "body": "@Gabi Purcaru: if you need to check multiple substrings in the same string then there are better than `O(n+m)` algorithms if you preprocess the string first e.g., a [suffix array + LCP](http://en.wikipedia.org/wiki/Suffix_array) can give you `O(m + log n)` and suffix trees can give you O(m) substring search." } ]
[ { "body": "<p>One case that you missed is replication in the search string.</p>\n\n<pre><code>&gt;&gt;&gt; '1213' in StringClass('121213')\nFalse\n&gt;&gt;&gt; '1213' in '121213'\nTrue\n</code></pre>\n\n<p>This is because your class is already past the second one before it sees a difference and has to start completely over.</p>\n\n<p>Asides from that, the empty string and None cases are problems, as is mentioned in other answers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-04T17:25:36.260", "Id": "24719", "ParentId": "24717", "Score": "5" } } ]
{ "AcceptedAnswerId": "24719", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-04T16:50:08.520", "Id": "24717", "Score": "0", "Tags": [ "python" ], "Title": "Possible Bugs in substring program" }
24717
<p>I am writing Python code for a Tic Tac Toe game. I need to write a function that takes in three inputs: board, x, and y. Board being the current display of the board and then x and y being values of 0, 1, or 2. The game is set up to ask the user for coordinates.</p> <pre><code>def CheckVictory(board, x, y): #check if previous move was on vertical line and caused a win if board[0][y] == ('X') and board[1][y] == ('X') and board [2][y] == ('X'): return True if board[0][y] == ('O') and board[1][y] == ('O') and board [2][y] == ('O'): return True #check if previous move was on horizontal line and caused a win if board[x][0] == ('X') and board[x][1] == ('X') and board [x][2] == ('X'): return True if board[x][0] == ('O') and board[x][1] == ('O') and board [x][2] == ('O'): return True #check if previous move was on the main diagonal and caused a win if board[0][0] == ('X') and board[1][1] == ('X') and board [2][2] == ('X'): return True if board[0][0] == ('O') and board[1][1] == ('O') and board [2][2] == ('O'): return True #check if previous move was on the secondary diagonal and caused a win if board[0][2] == ('X') and board[1][1] == ('X') and board [2][0] == ('X'): return True if board[0][2] == ('O') and board[1][1] == ('O') and board [2][0] == ('O'): return True return False #end of CheckVictory function </code></pre> <p>The function is called in the game loop like so:</p> <pre><code>p_x, p_y = playerTurn(board) #let player take turn displayBoard(board) #show board after move has been made if CheckVictory(board, p_x, p_y): #see if user has won print("CONGRATULATIONS, you win!") newGame(board) #game over start new one continue </code></pre> <p>and it's similar for the computer turn.</p> <p>I feel like there is a better way to write this function. I feel like I should be using x and y more or there is a better way to check rather than writing all the possibilities. What's a better way to write this to make it short and concise?</p>
[]
[ { "body": "<p>I would start by removing duplication. If you pass in the mark that the player being checked is using, then you can eliminate 1/2 your code.</p>\n\n<pre><code>def CheckVictory(board, x, y, mark):\n\n if board[x][0] == (mark) and board[x][1] == (mark) and board [x][2] == (mark):\n return True\n\n if board[0][y] == (mark) and board[1][y] == (mark) and board [2][y] == (mark):\n return True\n\n #check if previous move was on the main diagonal and caused a win\n if board[0][0] == (mark) and board[1][1] == (mark) and board [2][2] == (mark):\n return True\n\n #check if previous move was on the secondary diagonal and caused a win\n if board[0][2] == (mark) and board[1][1] == (mark) and board [2][0] == (mark):\n return True \n\n return False \n\n#end of CheckVictory function\n</code></pre>\n\n<p>Please excuse me if I have syntax wrong, I've never used python before.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T07:08:10.583", "Id": "38459", "Score": "0", "body": "...or set `mark = board[x][y]` inside the function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-05T17:33:29.717", "Id": "24768", "ParentId": "24764", "Score": "2" } }, { "body": "<p>For a start you could make your code twice smaller by removing the logic common to 'X' and to 'O'.\nThen, you can perform all the comparisons in one go.</p>\n\n<pre><code>def CheckVictory(board, x, y):\n playerSymbols=['X','O']\n\n #check if previous move was on vertical line and caused a win\n if (board[0][y] in playerSymbols) and board[0][y] == board[1][y] == board[2][y]:\n\n #check if previous move was on horizontal line and caused a win\n if (board[x][0] in playerSymbols) and board[x][0] == board[x][1] == board [x][2]:\n return True\n\n #check if previous move was on the main diagonal and caused a win\n if (board[0][0] in playerSymbols) and board[0][0] == board[1][1] == board [2][2]:\n\n #check if previous move was on the secondary diagonal and caused a win\n if (board[0][2] in playerSymbols) and board[0][2] == board[1][1] == board [2][0]:\n return True\n\n return False \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-05T17:43:37.657", "Id": "24770", "ParentId": "24764", "Score": "0" } }, { "body": "<p>Notes:</p>\n\n<ul>\n<li><p><code>CheckVictory</code>: Idiomatic in Python is <code>check_victory</code>.</p></li>\n<li><p><code>CheckVictory(board, x, y)</code>: I think you are mixing two things here, putting a value in the board and checking if someone won. Your function should be doing only one thing, checking if someone won on a given <code>board</code>. </p></li>\n<li><p>A standard approach is to prepare all the data you need (here, the positions/coordinates to check) and leave the code as simple as possible. </p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>positions_groups = (\n [[(x, y) for y in range(3)] for x in range(3)] + # horizontals\n [[(x, y) for x in range(3)] for y in range(3)] + # verticals\n [[(d, d) for d in range(3)]] + # diagonal from top-left to bottom-right\n [[(2-d, d) for d in range(3)]] # diagonal from top-right to bottom-left\n)\n\ndef get_winner(board):\n \"\"\"Return winner piece in board (None if no winner).\"\"\"\n for positions in positions_groups:\n values = [board[x][y] for (x, y) in positions]\n if len(set(values)) == 1 and values[0]:\n return values[0]\n\nboard = [\n [\"X\", \"X\", \"O\"],\n [\"O\", \"X\", \"X\"],\n [\"O\", \"X\", \"O\"],\n]\n\nprint(get_winner(board)) # \"X\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-16T19:35:47.273", "Id": "115214", "Score": "0", "body": "\"I think you are mixing two things here\" - no, it's just using the location of the last move (which must be part of any newly-created victory) to narrow down the scope of the search." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-05T20:37:28.810", "Id": "24775", "ParentId": "24764", "Score": "0" } }, { "body": "<p>You know that a mark has been placed at <code>board[x][y]</code>. Then you only need this to check for a win on vertical line <code>y</code>:</p>\n\n<pre><code>if board[0][y] == board[1][y] == board [2][y]\n</code></pre>\n\n<p>Your comments state \"check if previous move was on the main/secondary diagonal\", but you don't actually check. You can use the expressions <code>x == y</code> and <code>x + y == 2</code> to check that.</p>\n\n<p>Simplified code:</p>\n\n<pre><code>def CheckVictory(board, x, y):\n\n #check if previous move caused a win on vertical line \n if board[0][y] == board[1][y] == board [2][y]:\n return True\n\n #check if previous move caused a win on horizontal line \n if board[x][0] == board[x][1] == board [x][2]:\n return True\n\n #check if previous move was on the main diagonal and caused a win\n if x == y and board[0][0] == board[1][1] == board [2][2]:\n return True\n\n #check if previous move was on the secondary diagonal and caused a win\n if x + y == 2 and board[0][2] == board[1][1] == board [2][0]:\n return True\n\n return False \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T07:24:36.103", "Id": "24890", "ParentId": "24764", "Score": "5" } }, { "body": "<p>This solution will check horizontal lines, vertical lines and diagonal lines for a winner and return the player number. I just used player numbers 1, 2 instead of 'x', 'o' to avoid numpy array conversions.</p>\n\n<pre><code>board = np.empty((BOARD_SIZE,BOARD_SIZE))\nwinner_line = [\n np.array([1, 1, 1]),\n np.array([2, 2, 2])\n]\n\ndef CheckVictory(board):\n for idx in range(BOARD_SIZE):\n row = board[idx, :]\n col = board[:, idx]\n diagonal_1 = np.diagonal(board)\n diagonal_2 = np.diagonal(np.fliplr(board))\n\n # Check for each player\n for player in range(1,3):\n if np.all(row == winner_line[player-1]) \\\n or np.all(col == winner_line[player-1]) \\\n or np.all(diagonal_1 == winner_line[player-1]) \\\n or np.all(diagonal_2 == winner_line[player-1]):\n return player # There is a winner\n return False # No winner\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-11-08T11:10:10.873", "Id": "179899", "ParentId": "24764", "Score": "1" } } ]
{ "AcceptedAnswerId": "24890", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-05T16:58:50.477", "Id": "24764", "Score": "4", "Tags": [ "python", "tic-tac-toe" ], "Title": "Tic Tac Toe victory check" }
24764
<p>I'm trying to get the most out of this code, so I would understand what should I look for in the future. The code below, works fine, I just want to make it more efficient. </p> <p>Any suggestions?</p> <pre><code>from mrjob.job import MRJob import operator import re # append result from each reducer output_words = [] class MRSudo(MRJob): def init_mapper(self): # move list of tuples across mapper self.words = [] def mapper(self, _, line): command = line.split()[-1] self.words.append((command, 1)) def final_mapper(self): for word_pair in self.words: yield word_pair def reducer(self, command, count): # append tuples to the list output_words.append((command, sum(count))) def final_reducer(self): # Sort tuples in the list by occurence map(operator.itemgetter(1), output_words) sorted_words = sorted(output_words, key=operator.itemgetter(1), reverse=True) for result in sorted_words: yield result def steps(self): return [self.mr(mapper_init=self.init_mapper, mapper=self.mapper, mapper_final=self.final_mapper, reducer=self.reducer, reducer_final=self.final_reducer)] if __name__ == '__main__': MRSudo.run() </code></pre>
[]
[ { "body": "<p>Since the reduce function in this case is commutative and associative you can use a combiner to pre-aggregate values.</p>\n\n<pre><code>def combiner_count_words(self, word, counts):\n # sum the words we've seen so far\n yield (word, sum(counts))\n\ndef steps(self):\n return [self.mr(mapper_init=self.init_mapper,\n mapper=self.mapper,\n mapper_final=self.final_mapper,\n combiner= self.combiner_count_words,\n reducer=self.reducer,\n reducer_final=self.final_reducer)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-19T09:31:24.787", "Id": "101347", "ParentId": "24776", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-05T20:40:26.903", "Id": "24776", "Score": "3", "Tags": [ "python" ], "Title": "How to improve performace of this Map Reduce function, Python mrjob" }
24776
<p>I have to run a python script that enters data into MySQL database table.</p> <p>My below query runs and inserts data into MySQL database. But I want to optimize it and I have 2 requests:</p> <ol> <li><p>I want to use try except error handling inside the for loop. Probably before insertstmt or where it would be more efficient. If there is bug while executing nSql, program should not terminate, rather continue in other nSql tests. nSql has complex SQL queries with multiple joins, below shown is for simplicity. If any one of the nSql fails during quering, I want the error message to be displayed. </p></li> <li><p>If the data already exists for yesterday, I want to be deleted it as well. As the loop iterates, I want data to be deleted if it exists for yesterday as loop iterates through the nSql.</p></li> </ol> <p>I have: </p> <pre><code>#! /usr/bin/env python import mysql.connector con=mysql.connector.connect(user='root', password ='root', database='test') cur=con.cursor() sel=("select id, custName, nSql from TBLA") cur.execute(sel) res1=cur.fetchall() for outrow in res1: print 'Customer ID : ', outrow[0], ': ', outrow[1] nSql = outrow[2] cur.execute(nSql) res2=cur.fetchall() for inrow in res2: dateK =inrow[0] id= inrow[1] name= inrow[2] city=inrow[3] insertstmt=("insert into TBLB (dateK, id, name, city) values ('%s', '%s', '%s', '%s')" % (dateK, id, name, city)) cur.execute(insertstmt) con.commit() con.close() </code></pre> <p>Database schema is:</p> <pre><code>create table TBLA (id int, custName varchar(20), nSql text); insert into TBLA values ( 101, 'cust1', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t1"), ( 102, 'cust2', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t2"), ( 103, 'cust3', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t3"); create table t1 (id int, name varchar(20), city varchar(20)); create table t2 (id int, name varchar(20), city varchar(20)); create table t3 (id int, name varchar(20), city varchar(20)); insert into t1 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas'); insert into t2 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas'); insert into t3 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas'); create table TBLB (dateK date, id int, name varchar(20), city varchar (20)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T21:13:02.947", "Id": "38377", "Score": "0", "body": "You seem to know what you want and how to do it, so... where's the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T21:15:33.127", "Id": "38378", "Score": "0", "body": "I want to use try except inside the code and would like to delete data if exists as said in 1 in 2. Btw, I am a new to Python World !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T21:16:22.840", "Id": "38379", "Score": "0", "body": "I know what you want, but where's the problem? You know how to use `try:except:` right? You know how to make delete query, right? So where's the problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T21:18:22.703", "Id": "38380", "Score": "0", "body": "I am sorry, but I am stuck in using try except and delete." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T21:34:17.113", "Id": "38381", "Score": "1", "body": "just one tip: it's never a good idea to create sql statements like you do. mysql.connector supports python format style parameter expansion, so if you change your query to `cur.execute(\"insert into TBLB (dateK, id, name, city) values (%s, %s, %s, %s)\", (dateK, id, name, city))` you won't have to worry about sql injection. It's best to get used to this as early as possible." } ]
[ { "body": "<p>OK, here's the simpliest version of <code>try:except:</code> block for your case:</p>\n\n<pre><code># some code\nfor inrow in res2:\n # some code\n try:\n cur.execute(insertstmt)\n except MySQLdb.ProgrammingError:\n pass\n</code></pre>\n\n<p>That's pretty much it. You probably want to know which queries failed, so you should use for example that version:</p>\n\n<pre><code> try:\n cur.execute(insertstmt)\n except MySQLdb.ProgrammingError:\n print \"The following query failed:\"\n print insertstmt\n</code></pre>\n\n<p>Now as for the other question. You have to use a delete query. For example:</p>\n\n<pre><code>DELETE FROM TBLB WHERE dateK &lt; CURDATE();\n</code></pre>\n\n<p>or something like that (note that <code>CURDATE</code> is a built-in MySQL function). Read more about delete queries here:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/delete.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.0/en/delete.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T22:18:32.057", "Id": "38382", "Score": "0", "body": "@ freakish thank you for the response. During the nSql execution, if one of the SQL execution fails, how can I continue with other SQL execution without getting interrupted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-08T12:00:07.893", "Id": "38384", "Score": "1", "body": "I would suggest writing `except MySQLdb.ProgrammingError:` and not `except Exception:`. You should always catch the most specific error class that makes sense. See [PEP 249](http://www.python.org/dev/peps/pep-0249/#exceptions) for the exceptions that can be generated by DB-API methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-08T23:13:20.850", "Id": "38442", "Score": "0", "body": "`ProgrammingError` might not be the right one (or the only one) you need to catch here: it all depends on the OP's purpose in catching these errors." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T21:24:48.040", "Id": "24854", "ParentId": "24853", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T21:07:54.810", "Id": "24853", "Score": "4", "Tags": [ "python", "mysql" ], "Title": "Inserting data into database by Python" }
24853
<p>I have a few Python codes like this:</p> <pre><code> workflow = [] conf = {} result = [] prepare_A(workflow, conf) prepare_B(workflow, conf) prepare_C(workflow, conf) result.append(prepare_D_result(workflow, conf)) prepare_E(workflow, conf) #.... about 100 prepare functions has the same parameter list </code></pre> <p>I was wondering that whether I need to rewrite like this:</p> <pre><code> workflow = [] conf = {} result = [] def prepare_wrapper(prepare_function): return prepare_function(workflow, conf) prepare_wrapper(prepare_A) prepare_wrapper(prepare_B) prepare_wrapper(prepare_C) result.append(prepare_wrapper(prepare_D_result)) prepare_wrapper(prepare_E) #.... about 100 prepare functions has the same parameter list </code></pre> <p>Though it might reduce the burden of passing 2 parameters into the function each time, it might bring difficulties for those who read codes. Is there better ways to ameliorate the code quality in such situation?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T14:47:09.967", "Id": "38489", "Score": "0", "body": "Your question isn't following the FAQ in that your don't appear to be presenting real code. It would be better if you could show us an actual example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T14:58:30.003", "Id": "38491", "Score": "0", "body": "Are you sure about this style of programming? all your \"functions\" work by performing side-effects, so your application will be a gigantic state container where any data structure can be modified anywhere else. Have you considered a more functional approach? (where functions that take values and return another values, no side-effects). It requires some more thought at first, but it pays off later." } ]
[ { "body": "<p>Here's an idea, assuming your logic is really that straightforward:</p>\n\n<pre><code>workflow = [] \nconf = {}\nresult = []\n\nsteps = ((prepare_A, False),\n (prepare_B, False),\n (prepare_C, False),\n (prepare_D, True),\n (prepare_E, False))\n\nfor func, need_results in steps:\n res = func(workflow, conf)\n if need_results:\n result.append(res)\n</code></pre>\n\n<p>If you don't find that approach suitable, I'd suggest making your wrapper a class that encapsulates <code>workflow</code> and <code>conf</code>, and possibly <code>results</code> too.</p>\n\n<pre><code>class PrepareWrapper(object):\n def __init__(self):\n self.workflow = [] \n self.conf = {}\n\n def __call__(self, prepare_function):\n return prepare_function(self.workflow, self.conf) \n\nprepare_wrapper = PrepareWrapper() \nprepare_wrapper(prepare_A) \nprepare_wrapper(prepare_B) \n</code></pre>\n\n<p>Or, why not make all the prepare functions methods of this class? </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T07:39:25.857", "Id": "24892", "ParentId": "24889", "Score": "2" } } ]
{ "AcceptedAnswerId": "24892", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T07:23:59.597", "Id": "24889", "Score": "0", "Tags": [ "python" ], "Title": "Is it worthy to create a wrapper function like this?" }
24889
<p>I have the following dataset in numpy</p> <pre><code>indices | real data (X) |targets (y) | | 0 0 | 43.25 665.32 ... |2.4 } 1st block 0 0 | 11.234 |-4.5 } 0 1 ... ... } 2nd block 0 1 } 0 2 } 3rd block 0 2 } 1 0 } 4th block 1 0 } 1 0 } 1 1 ... 1 1 1 2 1 2 2 0 2 0 2 1 2 1 2 1 ... </code></pre> <p>Theses are my variables</p> <pre><code>idx1 = data[:,0] idx2 = data[:,1] X = data[:,2:-1] y = data[:,-1] </code></pre> <p>I also have a variable <code>W</code> which is a 3D array.</p> <p>What I need to do in the code is loop through all the blocks in the dataset and return a scalar number for each block after some computation, then sum up all the scalars, and store it in a variable called <code>cost</code>. Problem is that the looping implementation is very slow, so I'm trying to do it vectorized if possible. This is my current code. Is it possible to do this without for loops in numpy?</p> <pre><code>IDX1 = 0 IDX2 = 1 # get unique indices idx1s = np.arange(len(np.unique(data[:,IDX1]))) idx2s = np.arange(len(np.unique(data[:,IDX2]))) # initialize global sum variable to 0 cost = 0 for i1 in idx1s: for i2 in idx2: # for each block in the dataset mask = np.nonzero((data[:,IDX1] == i1) &amp; (data[:,IDX2] == i2)) # get variables for that block curr_X = X[mask,:] curr_y = y[mask] curr_W = W[:,i2,i1] # calculate a scalar pred = np.dot(curr_X,curr_W) sigm = 1.0 / (1.0 + np.exp(-pred)) loss = np.sum((sigm- (0.5)) * curr_y) # add result to global cost cost += loss </code></pre> <p>Here is some sample data</p> <pre><code>data = np.array([[0,0,5,5,7], [0,0,5,5,7], [0,1,5,5,7], [0,1,5,5,7], [1,0,5,5,7], [1,1,5,5,7]]) W = np.zeros((2,2,2)) idx1 = data[:,0] idx2 = data[:,1] X = data[:,2:-1] y = data[:,-1] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-23T00:48:33.853", "Id": "354174", "Score": "0", "body": "Could you please edit the title of your question to be less generic?" } ]
[ { "body": "<p>That <code>W</code> was tricky... Actually, your blocks are pretty irrelevant, apart from getting the right slice of <code>W</code> to do the <code>np.dot</code> with the corresponding <code>X</code>, so I went the easy route of creating an <code>aligned_W</code> array as follows:</p>\n\n<pre><code>aligned_W = W[:, idx2, idx1]\n</code></pre>\n\n<p>This is an array of shape <code>(2, rows)</code> where <code>rows</code> is the number of rows of your data set. You can now proceed to do your whole calculation without any for loops as:</p>\n\n<pre><code>from numpy.core.umath_tests import inner1d\npred = inner1d(X, aligned_W.T)\nsigm = 1.0 / (1.0 + np.exp(-pred))\nloss = (sigm - 0.5) * curr_y\ncost = np.sum(loss)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T15:55:12.177", "Id": "24909", "ParentId": "24905", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T15:00:43.700", "Id": "24905", "Score": "4", "Tags": [ "python", "optimization", "numpy" ], "Title": "Eliminate for loops in numpy implementation" }
24905
<p>I've got a string that consists of an arbitrary combination of text and <code>{}</code> delimited python code, for instance, <code>A plus b is {a + b}</code>. However, braces are used for dictionary and set literals in python, so <code>You chose the {{1:"first", 2:"second"}[choice]} option</code> should also be interpretted correctly. It's also valid to have more than one python expression in the input, so <code>You picked {choice1} and {choice2}</code> is valid.</p> <p>Here's my current code:</p> <pre><code>protected String ParseStringForVariable([NotNull] String str) { PythonEngine.PythonEngine pythonEngine = GetCurrentCore().PythonEngine; for (int i = 0; i &lt; str.Length; i++) { if (str[i] != '{') { continue; } int opening = i; foreach (var expression in from closing in str.IndexesWhere('}'.Equals) where closing &gt; opening select new { Template = str.Substring(opening, closing - opening + 1), Code = str.Substring(opening + 1, closing - opening - 1) }) { PythonByteCode compiled; try { compiled = pythonEngine.Compile(expression.Code, PythonByteCode.SourceCodeType.Expression); } catch (PythonParseException) { // not valid python, try next expression continue; } String result = pythonEngine.Evaluate(compiled).ToString(); str = str.Replace(expression.Template, result); break; } } return str; } </code></pre> <p>It works by looking at progressively longer strings, attempting to parse them, and ignoring them if it's not valid python. This is done with the <code>PythonEngine</code> class, which is a wrapper around the IronPython interpretter, and has an extensive test suite, so can assumed to be correct.</p> <ol> <li><p>It appears to burp slightly if the value of the first of multiple python expression contains an opening brace: <code>{"{"} {"}"}</code>, what's the best way to prevent that?</p></li> <li><p>Resharper is complaining about access to modified closures, can you provide a test case that exposes why that is an issue?</p></li> <li><p>It works under all inputs I've tested it with, but what edge cases should be included in the test suite? (It's intended behaviour that invalid python code is left as-is). Current thoughts include:</p> <ul> <li>Empty string</li> <li>without braces</li> <li>empty braces</li> <li>valid python in braces</li> <li>invalid python</li> <li>both valid and invalid</li> <li>both valid and empty</li> <li>both invalid and empty</li> <li>valid, nested braces</li> <li>invalid, nested braces</li> <li>valid, evaluated to contain open brace</li> <li>valid, evaluated to contain close brace - irrelevant, as parsing is LTR?</li> <li>valid, evaluated to contain open brace followed by further invalid</li> <li>valid, evaluated to contain open brace followed by further empty</li> <li>unmatched open brace</li> <li>unmatched close brace</li> </ul></li> <li><p>Are there any improvements that jump out? Clarity, performance, style?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-10T18:35:42.293", "Id": "38593", "Score": "0", "body": "What are you using to execute the Python code? I can't seem to find types like `PythonByteCode` anywhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T08:04:39.003", "Id": "38650", "Score": "0", "body": "@svick Post edited to clarify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T09:31:50.490", "Id": "38654", "Score": "0", "body": "reg 3.) Could you please add your test cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T10:27:20.170", "Id": "38659", "Score": "0", "body": "@mnhg clarified slightly, but added." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T15:01:19.287", "Id": "38671", "Score": "0", "body": "Regarding #2: http://stackoverflow.com/q/8898925/298754" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T15:25:23.430", "Id": "38674", "Score": "0", "body": "@Bobson perhaps I'm just being dense, but I still don't get how that applies in this case. Hence asking for a test case: it works as expected in every situation I've tried. Or is it just Resharper being over-cautious?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T14:58:31.230", "Id": "38723", "Score": "0", "body": "Where is it complaining?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T18:12:37.763", "Id": "38738", "Score": "0", "body": "`str.Substring()` in the anonymous object constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T06:09:16.830", "Id": "38931", "Score": "0", "body": "This bit is troubling to me: `str = str.Replace(expression.Template, result);` You may want to push the result of the replacement on a stack instead of overwriting the `str`. What does the `i` mean in the outer loop after you replace an expression with its value, which usually is of a different length? I will have to come up with some test cases on weekend to definitely say that this is a bug, but I can at least say it is definitely confusing to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T13:36:56.370", "Id": "38960", "Score": "0", "body": "@abuzittingillifirca That's the reason I'm using `i` rather than a foreach: After the replacement, `i` is the index of the first character of the result. I was tempted to add a line like `i += result.Length`... I can't remember the reasoning on why I didn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T13:39:29.300", "Id": "38961", "Score": "0", "body": "Also, I'm replacing in place so that open braces in the code don't get parsed again: `this is a set: {{1,2}}` `{1,2}` is a valid set literal, `1,2` is a valid tuple literal." } ]
[ { "body": "<p>I see an extra unnecessary variable that you can get rid of, or change another variable so that it makes more sense.</p>\n\n<pre><code>int opening = i;\n</code></pre>\n\n<p>you use this inside of a for loop. You can do 2 things with this.</p>\n\n<ol>\n<li>Just use the variable <code>i</code> where ever you had the variable <code>opening</code></li>\n<li><p>change the <code>i</code> variable to <code>opening</code> in the for loop like </p>\n\n<pre><code>for (int opening = 0; opening &lt; str.Length; opening++)\n</code></pre></li>\n</ol>\n\n<p>hopefully this shows you how unnecessary that extra variable is, it isn't used anywhere else for anything other than the loops. </p>\n\n<hr>\n\n<p>Other than that I would need to play with it and spend some time with it to see if it plays well with others.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-04T18:44:39.230", "Id": "61964", "ParentId": "24969", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-10T16:29:01.217", "Id": "24969", "Score": "3", "Tags": [ "c#", "python", "parsing" ], "Title": "Interpolating code delimited with character that can appear in code" }
24969
<p>Before I try to make this work, I wondered if anyone had tried this, whether it was a good idea or not, etc.</p> <p>I find myself doing this a lot:</p> <pre><code>if some_result is None: try: raise ResultException except ResultException: logger.exception(error_msg) raise ResultException(error_msg) </code></pre> <p>I would rather try this:</p> <pre><code>if some_result is None: with ResultException: logger.exception(error_msg) </code></pre> <p>Where the <code>__exit__()</code> statement would always raise the exception in the context.</p> <p>Would this be clearer? Is this possible?</p> <p>I only ask because I imagine someone else has tried this, or at least attempted it. But I don't seem to find any common patterns for accomplishing this after doing a couple of Google searches.</p> <h2>UPDATE</h2> <p>Here's some more information on this particular issue.</p> <p>I have a method that goes to a database and determines what the user's id is via their email. The problem is that if the user isn't found, it'll return <code>None</code>. This is okay for most calls, but when it's incorporated in higher-level methods, this can happen:</p> <pre><code>def change_some_setting(setting, email): user_id = user_id_by_email(email) # None _change_some_setting(setting, id) </code></pre> <p>Now when <code>_change_some_setting</code> attempts to change the setting for a user who's id is <code>None</code>, we get a very vague <code>ProgrammingException</code> from the database library.</p> <p>This helps prevent that. Is there a better way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T19:56:36.767", "Id": "38685", "Score": "0", "body": "Why not log the exception when you actually handle it? The traceback will show where it's from." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T20:09:35.363", "Id": "38686", "Score": "0", "body": "As far as this example is concerned, this is handling it. It catches result sets that are empty, logs the complaint, and then bails out of execution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T20:56:17.967", "Id": "38689", "Score": "0", "body": "Can you show the code that catches the exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T07:13:58.283", "Id": "39854", "Score": "0", "body": "The fix is that `user_id_by_email` should raise an exception, as @JanneKarila said in his answer (however creating a wrapper is only acceptable if you really can't change `user_id_by_email`)." } ]
[ { "body": "<p>This:</p>\n\n<pre><code>if some_result is None:\n with ResultException:\n logger.exception(error_msg)\n</code></pre>\n\n<p>would seem to be equivalent (for most cases) to:</p>\n\n<pre><code>if some_result is None:\n logger.exception(error_msg)\n raise ResultException\n</code></pre>\n\n<p>And so using a context manager as you describe it would not seem to be helpful. That's probably why you can't find any instances of it. But this would not actually work because when you call <code>logger.exception</code>, you need to be in an exception handler. </p>\n\n<p>You could do:</p>\n\n<pre><code>def raise_logged(exception):\n try:\n raise exception\n except: \n logging.exception(str(exception))\n raise exception\n</code></pre>\n\n<p>Then use it like</p>\n\n<pre><code> if some_result is None:\n raise_logged( ResultException(\"not so good\") )\n</code></pre>\n\n<p>However, throwing the exception just to catch it and log it is a bit yucky. Do you really need to log the exception as this point? Usually, we log exceptions when they are caught. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T20:52:02.153", "Id": "38688", "Score": "0", "body": "I updated my question with more specific information about my problem." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T20:14:58.360", "Id": "25008", "ParentId": "25004", "Score": "2" } }, { "body": "<p>Your issue is that a function returns <code>None</code> when raising an exception would be more useful to you. I would create a wrapper for the function for the sole purpose of raising the exception. Then catch the exception normally where it makes sense to you, and log it from there.</p>\n\n<pre><code>def checked_user_id_by_email(email):\n result = user_id_by_email(email) \n if result is None:\n raise LookupError(\"User not found by email '%s'\" % email)\n return result\n</code></pre>\n\n<p>You might use a decorator to wrap your functions like this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T05:49:42.460", "Id": "25018", "ParentId": "25004", "Score": "2" } } ]
{ "AcceptedAnswerId": "25008", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-11T18:48:47.783", "Id": "25004", "Score": "2", "Tags": [ "python", "exception-handling", "logging" ], "Title": "Wrapping an Exception with context-management, using the with statement" }
25004
<p>I have to create a modularized program that can find out the diameter, circumference, and area of a circle's radius. I'm sure many of you can notice I kind of winged this from a example given from my teacher. Instead of people pointing out the fact that I coded this wrong, could you please give me reasons for what I should do so I can better understand this concept?</p> <pre><code>import math def main(): Radius = 0 Diameter = 0 Circumference = 0 Area = 0 Radius = GetRadius(Radius) Diameter = SetDiameter(Radius, Diameter) Circumference = SetCircumference(Radius, Circumference) Area = SetArea(Radius, Area) ShowResults(Radius, Diameter, Circumference, Area) def GetRadius(myradius): myradius = float(str(input("Enter your radius: "))) return myradius def SetDiameter(myradius, mydiameter): mydiameter = myradius * 2 return mydiameter def SetCircumference(myradius, mycircumference): PIE = 3.14159 mycircumference = 2 * PIE * myradius return mycircumference def SetArea(myradius, myarea): PIE = 3.14159 myarea = PIE * myradius * myradius return myarea def ShowResults(Radius, Diameter, Circumference, Area): print("The Diameter is",mydiameter) print("The Circumference is",mycircumference) print("The Area is",myarea) main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T12:02:30.047", "Id": "38945", "Score": "0", "body": "Have you learned about Classes? This would be a great example in using one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T07:51:11.587", "Id": "39104", "Score": "0", "body": "Those \"setters\" make no sense: you pass a variable, set it inside the function and return it? that's not gonna work." } ]
[ { "body": "<p>Many little comments here to make things simpler,shorter,more pythonic :</p>\n\n<ul>\n<li><p><a href=\"http://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables\" rel=\"nofollow\">PEP 0008</a> gives some coding guidelines for python. Among other things, it gives a naming convention. Also, you don't need the \"my\" prefix everywhere.</p></li>\n<li><p>You can use <code>math.pi</code> instead of repeating our own definition of pi everywhere. (Isn't it the reason why your import math in the first place)</p></li>\n<li><p>Most of your function just need to return a value and updating the parameter probably shouldn't be their responsability.</p></li>\n<li><p>Most of the variables are not really required.</p></li>\n<li><p>there's no point to define a main function in your case.</p></li>\n</ul>\n\n<p>After taking these comments into accounts, your code looks like this :</p>\n\n<pre><code>import math\n\ndef get_radius_from_user():\n return float(input(\"Enter your radius: \"))\n\ndef get_diameter(radius):\n return radius * 2\n\ndef get_circumference(radius):\n return 2 * math.pi * radius\n\ndef get_area(radius):\n return math.pi * radius * radius\n\ndef show_results(radius):\n print(\"The Diameter is\",get_diameter(radius))\n print(\"The Circumference is\",get_circumference(radius))\n print(\"The Area is\",get_area(radius))\n\nshow_results(get_radius_from_user())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T13:27:21.190", "Id": "38958", "Score": "1", "body": "Thanks for your review! In `get_radius_from_user()`, is there any reason you're converting a string to a string before converting it to a `float`? Also, you could write `radius ** 2` instead of `radius * radius` but that's subjective." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T15:09:53.910", "Id": "38964", "Score": "0", "body": "For the conversion, I just reused the original code without thinking too much about it as I'm not too sure to understand what was intended.\nYour comment about `radius**2` is valid too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T16:42:26.853", "Id": "38969", "Score": "1", "body": "`float(str(input(...)))` → `float(raw_input(...))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T16:54:14.533", "Id": "38973", "Score": "0", "body": "I've edited my answer. Thanks guys for the comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-07T05:33:11.953", "Id": "92377", "Score": "0", "body": "A comma should be followed by a space, according to PEP8." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T12:31:45.423", "Id": "25171", "ParentId": "25166", "Score": "6" } }, { "body": "<p>Once you've learned about classes you could create a <code>Circle</code> object which when initiated performs all possible conversions, so that its properties - diameter, radius, area and circumference - can all be accessed without having to write anything else.</p>\n\n<p>The conversion functions can be stored as a dictionary of <code>lambda</code>s.</p>\n\n<pre><code>import math\nclass Circle:\n conversions = {\n ('diameter', 'radius'): lambda d: d / 2.0,\n ('radius', 'area'): lambda r: math.pi * r ** 2,\n ('radius', 'diameter'): lambda r: r * 2.0,\n ('radius', 'circumference'): lambda r: math.pi * r * 2,\n ('area', 'radius'): lambda a: (a / math.pi) ** .5,\n ('circumference', 'radius'): lambda c: c / (math.pi * 2)\n }\n\n def _set(self, property, value):\n \"\"\" Set a property and recursively make all possible \n conversions based on that property \"\"\" \n setattr(self, property, value)\n for (fro, to), conversion in self.conversions.items():\n if fro == property and getattr(self, to, None) is None:\n self._set(to, conversion(getattr(self, fro)))\n\n def __init__(self, **kwargs):\n self._set(*kwargs.items()[0])\n\nmy_circle = Circle(radius = 5)\nprint my_circle.area\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-07T20:09:09.133", "Id": "52720", "ParentId": "25166", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T09:30:14.287", "Id": "25166", "Score": "2", "Tags": [ "python" ], "Title": "Modularized program to find circumference, diameter, and area from a circle's radius" }
25166
<p>This is my first attempt with a basic text adventure game, and I was wondering if there was a way to make it more efficient (or any other things I could add to make the game better). It isn't totally finished yet, but if there is a way to make it better, please post in the comments.</p> <pre><code>#lets me use the exit function import sys #Lets me use the time function import time #Want to play loop #asks for name name = raw_input('What is your name, adventurer? ') print 'Nice to meet you, '+name+'. Are you ready for your adventure?' while True: ready = raw_input('y/n ') if ready == 'y': print 'Good, let us start our great adventure!' break elif ready == 'n': print 'That is a real shame...' time.sleep(1) print 'Exiting program in 5 seconds:' time.sleep(1) print '5' time.sleep(1) print '4' time.sleep(1) print '3' time.sleep(1) print '2' time.sleep(1) print '1' time.sleep(1) sys.exit('Exiting Game...') break else: print 'That is not a valid answer... Try again' time.sleep(2) #First level loop while True: print 'You awaken on the ground of a great forest. You can see two possible things to do, enter the cabin to your left, or wander through the woods.' print ' ' print 'Where do you want to go?' FirstDecision = raw_input('cabin/woods ') #Cabin option if FirstDecision == 'cabin': print 'You approach the door to the cabin, luckily it is unlocked.' Cnt = raw_input('Enter &lt; to continue') print 'You open the door and walk through, only to hear a dry and shaky voice say:' print '\"Get out.\"' Cnt = raw_input('Enter &lt; to continue') print 'What do you do?' FirstCabin = raw_input('leave/fight ') if FirstCabin == 'leave': print 'As you run out the door, the voice shoots and kills you.' Cnt = raw_input('Enter &lt; to continue') print ' ' FirstRetry = raw_input('Try again? (y/n)') if FirstRetry == 'y': print 'Restarting back at checkpoint...' time.sleep(2) elif FirstRetry == 'n': print 'That\'s a shame...' time.sleep(1) print 'Exiting program in 5 seconds:' time.sleep(1) print '5' time.sleep(1) print '4' time.sleep(1) print '3' time.sleep(1) print '2' time.sleep(1) print '1' time.sleep(1) sys.exit('Exiting Game...') break elif FirstCabin == 'fight': print 'You turn to where the voice came from and you bluntly say \"No.\"`` </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T22:07:47.220", "Id": "39003", "Score": "0", "body": "`while True: ready = raw_input('y/n ')` : if I'm not wrong and if the indentation is not wrong, this would loop forever." } ]
[ { "body": "<p>A couple things. First of all, you should abstract the function that exits the game:</p>\n\n<pre><code>def exitGame():\n print 'That\\'s a shame...'\n print 'Exiting program in 5 seconds:'\n for i in range(5):\n time.sleep(1)\n print(i+1)\n sys.exit('Exiting Game...')\n</code></pre>\n\n<p>Second, I would probably push Cabins, retries, etc. into arrays.</p>\n\n<pre><code>DECISIONS = []\nCABINS = []\nCONTINUES = []\n</code></pre>\n\n<p>Third, I would define the first level as a function so you can do the gracefully exit:</p>\n\n<pre><code>EXIT_MESSAGE = 'Exiting Game...'\n#First level loop\nwhile True:\n try: firstLevel()\n except SystemExit as e:\n print(str(e))\n break\n</code></pre>\n\n<p>One last thing. Use print as a function and not a statement. And maybe it's personal preference, but I find string formatting strongly preferable:</p>\n\n<pre><code>print('Nice to meet you, %s. Are you ready for your adventure?' % name)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T01:14:24.243", "Id": "39007", "Score": "2", "body": "nitpick: those are lists not arrays" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:22:34.753", "Id": "39047", "Score": "0", "body": "Array is a general term for the type of data structure. I used lists above but you could use many other types of array depending on your needs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:31:04.290", "Id": "39050", "Score": "1", "body": "You could argue that, and that's why its just a nitpick. Typically in python arrays refer to fixed-size arrays from either the `array` module or numpy." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T00:02:12.777", "Id": "25206", "ParentId": "25194", "Score": "3" } }, { "body": "<p>One thing that stuck out to me is line 38 of your code is 158 characters long:</p>\n\n<pre><code>print 'You awaken on the ground of a great forest. You can see two possible things to do, enter the cabin to your left, or wander through the woods.'\n</code></pre>\n\n<p>Below are the first two sentences of the \"Maximum Line Length\" section in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>:</p>\n\n<blockquote>\n <p>Limit all lines to a maximum of 79 characters.</p>\n \n <p>For flowing long blocks of text with fewer structural restrictions\n (docstrings or comments), the line length should be limited to 72\n characters.</p>\n</blockquote>\n\n<p>To break line 38 into shorter lines in your source, you can store it in a variable inside parenthesis:</p>\n\n<pre><code>s1 = ('You awaken on the ground of a great forest. '\n 'You can see two possible things to do, enter '\n 'the cabin to your left, or wander through the woods.')\n</code></pre>\n\n<p>Note that with the above, the output will still be one continuous line of text without line breaks. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T00:32:33.610", "Id": "30471", "ParentId": "25194", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:46:55.353", "Id": "25194", "Score": "3", "Tags": [ "python" ], "Title": "Is there a better way to code this text adventure game?" }
25194
<p>I am trying to get a tuple of <code>date</code> (or <code>datetime</code>) objects over the last <code>N</code> months.</p> <p>My thought was to use the <code>dateutil</code> package with something like this:</p> <pre><code>def last_n_months(n=12, ending=None): """Return a list of tuples of the first/last day of the month for the last N months """ from datetime import date from dateutil.rrule import rrule, MONTHLY from dateutil.relativedelta import relativedelta if not ending: ending = date.today() # set the ending date to the last day of the month ending = ending + relativedelta(months=+1, days=-ending.day) # starting is the first day of the month N months ago starting = ending - relativedelta(months=n, day=1) months = list(rrule(MONTHLY, bymonthday=(1, -1), dtstart=starting, until=ending)) # we return pairs of dates like this: (1st day of month, last day of month) months = zip(months[::2], months[1::2]) return months </code></pre> <p>Example usage:</p> <pre><code> &gt;&gt;&gt; from datetime import date, timedelta # get last two months as a degenerate example &gt;&gt;&gt; l2n = last_n_months(2, ending=date(2012, 01, 01)) &gt;&gt;&gt; map(lambda x: [x[0].year, x[0].month, x[0].day], l2n) [[2011, 11, 1], [2011, 12, 1], [2012, 1, 1]] &gt;&gt;&gt; map(lambda x: [x[1].year, x[1].month, x[1].day], l2n) [[2011, 11, 30], [2011, 12, 31], [2012, 1, 31]] &gt;&gt;&gt; l24n = last_n_months(24, ending=date(2012,03,16)) &gt;&gt;&gt; len(l24n) # inclusive of current month 25 # every tuple starts with the first day of the month &gt;&gt;&gt; all(x[0].day == 1 for x in l24n) True # every tuple ends with the last day of the month &gt;&gt;&gt; all((x[1] +timedelta(days=1)).month != x[1].month for x in l24n) True # every tuple is the same month &gt;&gt;&gt; all(x[0].month == x[1].month for x in l24n) True </code></pre> <p>I am posting it here to see if anyone has a better solution than this (and perhaps see if this yields some off-by-one sort of error that I haven't thought of).</p> <p>Is there a simpler or faster solution than this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-20T01:50:57.113", "Id": "119705", "Score": "0", "body": "Unless I'm missing something, you can probably adapt the itermonthdates() function from the calendar module in the python standard library:\nhttps://docs.python.org/2/library/calendar.html\nNo?" } ]
[ { "body": "<pre><code>def last_n_months(n=12, ending=None):\n \"\"\"Return a list of tuples of the first/last day of the month\n for the last N months \n \"\"\"\n from datetime import date\n from dateutil.rrule import rrule, MONTHLY\n from dateutil.relativedelta import relativedelta\n</code></pre>\n\n<p>It is better to import outside of the function. Typically imports go at the top of the file.</p>\n\n<pre><code> if not ending:\n</code></pre>\n\n<p>You should check for none like: <code>if ending is not None:</code> just to be explicit about what you are checking for.</p>\n\n<pre><code> ending = date.today()\n\n # set the ending date to the last day of the month\n ending = ending + relativedelta(months=+1, days=-ending.day)\n</code></pre>\n\n<p>Modifying <code>ending</code> rubs me the wrong way. </p>\n\n<pre><code> # starting is the first day of the month N months ago\n starting = ending - relativedelta(months=n, day=1)\n\n months = list(rrule(MONTHLY, bymonthday=(1, -1), dtstart=starting,\n until=ending))\n\n # we return pairs of dates like this: (1st day of month, last day of month)\n months = zip(months[::2], months[1::2])\n\n return months\n</code></pre>\n\n<p>You can combine these two lines</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T20:26:09.450", "Id": "39068", "Score": "0", "body": "Thanks Winston, much appreciated. Quick question with respect to the imports, is the preference to import outside the function a preference or functional? From a PEP? Always preferable where there are no circular dependencies? Or is there a concern about cluttering the namespace? Just curious - I'd be very grateful if anyone were to post a link to a discussion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T21:17:18.657", "Id": "39070", "Score": "1", "body": "@BrianM.Hunt, PEP 8 says to put all imports at the top. See here for some discussion of it: http://stackoverflow.com/questions/477096/python-import-coding-style" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:08:40.913", "Id": "39074", "Score": "0", "body": "Thanks for the discussion thread. A quote I thought interesting in one of the upvoted answers \"As you can see, it can be more efficient to import the module in the function\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:45:59.150", "Id": "39076", "Score": "0", "body": "@BrianM.Hunt, yes but that only applies if you are calling the function a lot. In your case it doesn't, because you only use any of those imports a few times." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T20:11:26.720", "Id": "25239", "ParentId": "25233", "Score": "2" } } ]
{ "AcceptedAnswerId": "25239", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T15:09:12.853", "Id": "25233", "Score": "2", "Tags": [ "python", "datetime" ], "Title": "Get tuple of the first and last days of the last N months" }
25233
<p>I am using a recursive algorithm to find all of the file-paths in a given directory: it returns a dictionary like this: <code>{'Tkinter.py': 'C:\Python27\Lib\lib-tk\Tkinter.py', ...}</code>.</p> <p>I am using this in a script to open modules by solely given the name. Currently, the whole process (for everything in <code>sys.path</code>) takes about 9 seconds. To avoid doing this every time, I have it save to a <code>.pkl</code> file and then just load this in my module-opener program.</p> <p>The original recursive method took too long and sometimes gave me a <code>MemoryError</code>, so what I did was create a helper method to iterate through the subfolders (using <code>os.listdir</code>), and then call the recursive method.</p> <p>Here is my code:</p> <pre><code>import os, os.path def getDirs(path): sub = os.listdir(path) paths = {} for p in sub: print p pDir = '{}\{}'.format(path, p) if os.path.isdir(pDir): paths.update(getAllDirs(pDir, paths)) else: paths[p] = pDir return paths def getAllDirs(mainPath, paths = {}): subPaths = os.listdir(mainPath) for path in subPaths: pathDir = '{}\{}'.format(mainPath, path) if os.path.isdir(pathDir): paths.update(getAllDirs(pathDir, paths)) else: paths[path] = pathDir return paths </code></pre> <p>Is there any way to make this faster? Thanks! </p>
[]
[ { "body": "<pre><code>import os, os.path\ndef getDirs(path):\n</code></pre>\n\n<p>Python convention is to use <code>lowercase_with_underscores</code> for function names</p>\n\n<pre><code> sub = os.listdir(path)\n</code></pre>\n\n<p>Don't needlessly abbreviate, and at least have it be a plural name.</p>\n\n<pre><code> paths = {}\n for p in sub:\n</code></pre>\n\n<p>You don't need to store things in a temporary variable to loop over them</p>\n\n<pre><code> print p\n</code></pre>\n\n<p>Do you really want this function printing?</p>\n\n<pre><code> pDir = '{}\\{}'.format(path, p)\n</code></pre>\n\n<p>Use os.path.join to join paths. That'll make sure it works regardless of your platform.</p>\n\n<pre><code> if os.path.isdir(pDir): \n paths.update(getAllDirs(pDir, paths))\n</code></pre>\n\n<p>You shouldn't both pass it and update it afterwords. That's redundant.</p>\n\n<pre><code> else:\n paths[p] = pDir\n return paths\n\ndef getAllDirs(mainPath, paths = {}):\n</code></pre>\n\n<p>Don't use mutable objects as default values, they have unexpected behavior.</p>\n\n<pre><code> subPaths = os.listdir(mainPath)\n for path in subPaths:\n pathDir = '{}\\{}'.format(mainPath, path)\n if os.path.isdir(pathDir):\n paths.update(getAllDirs(pathDir, paths))\n else:\n paths[path] = pathDir\n return paths\n</code></pre>\n\n<p>This whole section is repeated from the previous function. You should combine them.</p>\n\n<p>Take a look at the <code>os.walk</code> function. It does most of the work you're doing here and you could use to simplify your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T21:06:58.440", "Id": "25273", "ParentId": "25272", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T20:52:06.053", "Id": "25272", "Score": "1", "Tags": [ "python", "optimization", "recursion" ], "Title": "Improve file-path finding method" }
25272
<p>I wrote this code for <a href="http://projecteuler.net/index.php?section=problems&amp;id=75" rel="noreferrer">Project Euler problem 75</a>, which asks how many integers ≤ 1500000 exist, where the integer is a perimeter length that can be divided into three integer-length sides of a right triangle in one unique way.</p> <p>I was curious if anyone knew how to improve its speed. It runs fine, but I'm just looking to improve my own coding know-how.</p> <pre><code>from functools import reduce import math primes=set([2,3,5,7,11,13,17,19,23]) def isPrime(n): n=abs(n) if n in primes: return True if n&lt;2: return False if n==2: return True if n%2==0: return False for x in range(3, int(n**0.5)+1, 2): if n % x == 0: return False primes.add(n) return True def aFactors(n): if isPrime(n): return [1,n] return set(reduce(list.__add__,([i,n//i] for i in range(1,int(math.sqrt(n))+1) if n%i==0))) count=0 number=12 while number&lt;=1500000: p=number/2 f=aFactors(p) triangles=[] pairs=[(i, int(p/i)) for i in f] add=triangles.append for i in pairs: mList=aFactors(i[0]) pairsOfmc=[(k,int(i[0]/k)) for k in mList] for j in pairsOfmc: add((2*i[1]*i[0]-i[1]*i[1]*j[0],2*i[0]*i[1]-2*i[0]*j[1],2*i[0]*j[1]+i[1]*i[1]*j[0]-2*i[0]*i[1])) r=0 while r&lt;len(triangles): if any(triangles[r][i]&lt;=0 for i in range(len(triangles[r]))): del triangles[r] else: l=list(triangles[r]) l.sort() triangles[r]=tuple(l) r+=1 trianglesFinal=list(set(triangles)) for i in trianglesFinal: print(number, i) if len(trianglesFinal)==1: count+=1 number+=2 print(count) </code></pre> <p>Please note that I am not looking for a different calculating method (I am sure there is one, but, for me, Project Euler is about finding your own methods. Using yours would, to me, be cheating). However, any faster functions, ways to combine blocks of code, simplified tests, or the like (such as not checking ever other number, but every xth number, etc) would be greatly appreciated!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T20:06:05.227", "Id": "39364", "Score": "0", "body": "Probably not what you are looking for but in my opinion if you are worried about run time, then python is not the right language to use. It is hard to fine tune and optimize in general. It is design for rapid prototyping more then for efficient code." } ]
[ { "body": "<p>It is not necessary to construct all the triangles to find out if there is exactly one: you can stop when you've found two.</p>\n\n<p>Some little things to clean up the code that should give a minor speedup too:</p>\n\n<p>Instead of indexing <code>(triangles[r][i]&lt;=0 for i in range(len(triangles[r])))</code>, iterate directly:</p>\n\n<pre><code>(x &lt;= 0 for x in triangles[r])\n</code></pre>\n\n<hr>\n\n<p><code>reduce(list.__add__, ...</code> looks ugly to me and creates some intermediate lists you can avoid by:</p>\n\n<pre><code>(j for i in range(1,int(math.sqrt(n))+1) if n%i==0 for j in (i,n//i))\n</code></pre>\n\n<hr>\n\n<p>Instead of the outer <code>while</code> loop you can use:</p>\n\n<pre><code>for number in range(12, 1500001, 2): \n</code></pre>\n\n<p>(This is for Python 3, in Python 2 <code>xrange</code> should be used)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T08:36:49.867", "Id": "39392", "Score": "0", "body": "I tried out the \"stop when you've found two triangles\" approach, but found that it actually made things slower. (The test doesn't succeed often enough to pay for its own cost.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T09:27:16.790", "Id": "39397", "Score": "0", "body": "@GarethRees Is this in reference to your best effort? I get almost 40 % time reduction using this trick, when my starting point is the OP's code plus an optimization similar to your number 6." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T06:50:15.760", "Id": "25407", "ParentId": "25388", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T18:12:36.453", "Id": "25388", "Score": "25", "Tags": [ "python", "performance", "programming-challenge", "computational-geometry" ], "Title": "Speed up solution to Project Euler problem 75" }
25388
<p>I got a piece of code I'm not pleased with; Does anyone would have a better idea?</p> <pre><code>def myFunc(verbose=True): if not verbose: print = functools.partial(globals()['print'], file=open(os.devnull, 'w')) else: # Required, othewise I got the error 'local print variable was referenced before being declared' a few lines below… print = globals()['print'] # Bunch of code with tons of print calls […] </code></pre> <p>I also tried the classical <code>sys.stdout = open(os.devnull, 'w')</code> but it can't work with my code because my print function is defined as such at the beginning of the code:</p> <pre><code>print = functools.partial(print, file=codecs.getwriter('utf8')(sys.stdout.buffer)) # Make sure the output is in utf-8 </code></pre> <p>But I'm not really fan about having to use globals twice.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T09:57:35.307", "Id": "39409", "Score": "2", "body": "It might be worth having a look at the logging facilities offered by Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T01:25:19.057", "Id": "39479", "Score": "0", "body": "@Josay Are you talking about the `logging` module? I shall have a look. Last time I tried I couldn't make it work with `cgitb` but I'm not using `cgitb` here so may be it could work. I would still prefer to have a solution which would always work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T01:27:06.783", "Id": "39480", "Score": "0", "body": "@Josay Would it also mean that I would have to change my code anyway? (I mean replacing every print in my function or could I just put something on top just like I did here (I thought about implementing this as a decorator))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T10:29:40.147", "Id": "39508", "Score": "0", "body": "@JeromeJ: why are you clobbering a global function? that looks like a no-no, can't you name `log` or something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T08:08:24.827", "Id": "39559", "Score": "0", "body": "@tokland The one at the beginning seems legit to me, everything else is only local (I think I could/should use `locals()` instead of `globals()`). About `log` maybe I could do something like `print = someKindOfLogModified`? (I don't want to rewrite the code of the functions, some aren't mine) But then, if I use `log`, some old probs will come back in some of my other codes (that's why I stopped using `log`, I couldn't make it work everywhere)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T09:18:11.750", "Id": "39561", "Score": "0", "body": "@JeromeJ: fair enough, it's a local clobbering, it's acceptable. If you are going to do this more than once, by all means, abstract it: `print = get_my_print(verbose)`. Btw, the error you get is normal, Python sees `print =` in the first branch so it decides that it's a local variable in this scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T06:59:14.443", "Id": "39852", "Score": "0", "body": "@tokland Isn't this a valid use case for the `global` keyword? (By the way, in a Unix world, deciding where the output goes is not decided in the code, except to separate standard output and standard error.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T07:07:48.610", "Id": "39853", "Score": "0", "body": "Also, deciding on the output encoding is decided using the locale in Python, explicitely encoding everything in UTF-8 is asking for trouble IMHO, and is probably not the best place to fix a problem you're having." } ]
[ { "body": "<p>It depends on what you are looking to do. For localized 'quiet' code, I use this:</p>\n\n<pre><code>class NoStdStreams(object):\n def __init__(self,stdout = None, stderr = None):\n self.devnull = open(os.devnull,'w')\n self._stdout = stdout or self.devnull or sys.stdout\n self._stderr = stderr or self.devnull or sys.stderr\n\n def __enter__(self):\n self.old_stdout, self.old_stderr = sys.stdout, sys.stderr\n self.old_stdout.flush(); self.old_stderr.flush()\n sys.stdout, sys.stderr = self._stdout, self._stderr\n\n def __exit__(self, exc_type, exc_value, traceback):\n self._stdout.flush(); self._stderr.flush()\n sys.stdout = self.old_stdout\n sys.stderr = self.old_stderr\n self.devnull.close()\n</code></pre>\n\n<p>then it is as easy as:</p>\n\n<pre><code>with NoStdStreams():\n print('you will never see this')\n</code></pre>\n\n<p>You could easily adapt it to:</p>\n\n<pre><code>with NoStdStreams(verbose):\n print('you may see this')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T08:14:49.640", "Id": "39560", "Score": "0", "body": "I like your idea but I gotta modify my code (and yours) if I want to use it (because of my way of overwriting `print` so that it doesn't even call `sys.stdout`)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T06:32:20.040", "Id": "25471", "ParentId": "25417", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T08:13:16.783", "Id": "25417", "Score": "2", "Tags": [ "python" ], "Title": "Is there a better way to make a function silent on need?" }
25417
<p>Let's say I have a key 'messages' that is usually a list, but might be None, or might not be present. So these are all valid inputs:</p> <pre><code>{ 'date': 'tuesday', 'messages': None, } { 'date': 'tuesday', 'messages': ['a', 'b'], } { 'date': 'tuesday', } </code></pre> <p>If I want to retrieve 'messages' from the input, and iterate over them, I need to do something like this:</p> <pre><code>messages = d.get('messages', []) # Check for key existence if messages is None: # Check if key is there, but None messages = [] for message in messages: do_something() </code></pre> <p>That seems a little verbose for Python - is there a simpler way to write that?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T08:32:02.767", "Id": "39495", "Score": "1", "body": "Consider using a `collections.defaultdict`." } ]
[ { "body": "<p>You have to check for the existence of 'messages' AND the content of 'messages'. It's the same thing you have, but I would write it as:</p>\n\n<pre><code>if 'messages' in d and d['messages'] is not None:\n for m in d['messages']:\n do_something(m)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T06:15:21.057", "Id": "25469", "ParentId": "25465", "Score": "2" } }, { "body": "<pre><code>for message in d.get('messages') or ():\n do_something()\n</code></pre>\n\n<ul>\n<li><code>get</code> returns <code>None</code> by default for missing keys.</li>\n<li><code>a or b</code> evaluates to <code>b</code> when <code>bool(a) == False</code>. An empty list and <code>None</code> are examples of values that are false in a boolean context.</li>\n<li>Note that you cannot use this trick if you intend to modify the possibly empty list that is already in the dict. I'm using <code>()</code> instead of <code>[]</code> to guard against such mistakes. Also, CPython caches the empty tuple, so using it is slightly faster than constructing an empty list.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-23T06:50:07.027", "Id": "53029", "Score": "4", "body": "Rollback: someone edited this to `for message in d.get('messages', ()):`. That would not, however, work when the value is `None`, like in the first example." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T06:28:23.827", "Id": "25470", "ParentId": "25465", "Score": "15" } } ]
{ "AcceptedAnswerId": "25470", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T02:54:02.610", "Id": "25465", "Score": "15", "Tags": [ "python", "hash-map" ], "Title": "Set a default if key not in a dictionary, *or* value is None" }
25465
<p>This is a function I just wrote that tries to condense a set of strings into grouped lines. It actually works, but looks ugly. Is there a better way to achieve the same thing?</p> <p><strong>Take 4</strong> <em>filtering empty strings first and dropping the <code>if line</code> on the final <code>yield</code></em></p> <pre><code>def mergeToLines(strings, length=40, sep=" "): strs = (st for st in sorted(strings, key=len, reverse=True) if st) line = strs.next() for s in strs: if (len(line) + len(s) + len(sep)) &gt;= length: yield line line = s else: line += sep + s yield line </code></pre> <p>The idea is that it takes a bunch of strings, and combines them into lines about as long as <code>lineLength</code>. Each line has one or more of the original strings in it, but how many isn't clear until I actually get to slotting them in. Also, note that if a single entry in the list is longer than <code>lineLength</code>, it's still added as its own line (dropping elements is not an option here).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T06:36:57.987", "Id": "39557", "Score": "1", "body": "In take 3, `if line:` is redundant unless you have empty strings in `strings`. If you do have empty strings, you probably should filter out all of them earlier on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T13:46:25.347", "Id": "39576", "Score": "0", "body": "@JanneKarila - good point." } ]
[ { "body": "<p><strong>RECURSIVE SOLUTION:</strong>\n<em>NOTE: it assumes that the input <code>strings</code> is already sorted. You could sort this at every call of the function, but this seems like unnecessary overhead.</em></p>\n\n<pre><code>def recursiveMerge(strings=[], current_line='', line_length=40, result=[]):\n \"\"\" Gather groups of strings into a line length of approx. 40 \"\"\"\n\n # base case\n if not strings:\n result.append(current_line)\n return result\n\n else:\n next_line = strings.pop(0)\n\n # if current_line + next_line &lt; line_length, add them\n # otherwise append current_line to result\n if len(current_line + next_line) &lt; line_length:\n current_line = ' '.join([current_line, next_line]).lstrip(' ') \n else:\n result.append(current_line)\n current_line = next_line\n\n # recursively call function\n return recursiveMerge(strings, current_line = current_line, result=result)\n</code></pre>\n\n<p><strong>ITERATIVE SOLUTION:</strong></p>\n\n<pre><code>def myMerge(strings, line_length=40, res=[]):\n \"\"\" Gather groups of strings into a line length of approx. 40 \"\"\"\n\n # sort the list of string by len\n strings = sorted(strings, key=len, reverse=True)\n\n # loop through the group of strings, until all have been used\n current_line = strings.pop(0)\n while strings:\n next_line = strings.pop(0)\n\n # if current_line + next_line shorter than line_length, add them\n # otherwise, append current_line to the result\n\n if len(current_line + next_line) &lt; line_length:\n current_line = ' '.join([current_line, next_line])\n else:\n res.append(current_line)\n current_line = next_line\n\n # add any remaining lines to result \n res.append(current_line)\n\n return res\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T00:59:42.410", "Id": "39551", "Score": "1", "body": "l_len should be line_length, no?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T23:04:40.167", "Id": "25512", "ParentId": "25508", "Score": "3" } }, { "body": "<p>Your code isn't so ugly, guys :) But I can write it better</p>\n\n<pre><code>def cool_merger(strings, line_len=40, sep=\" \"):\n ss = list(sorted(strings, key=len, reverse=True))\n return [line for line in [(lambda n, s: s if n+1 &lt; len(ss) and (len(s) + len(ss[n+1]) &gt;= line_len) else (ss.__setitem__(n+1, sep.join((str(ss[n]), str(ss[n+1]))))) if len(ss) &gt; n+1 else ss[n] )(n, s) if len(s) &lt; line_len else s for n, s in enumerate(ss)] if line != None]\n</code></pre>\n\n<p>(<em>joke</em>)</p>\n\n<p>By the way, works fast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T00:19:54.530", "Id": "39549", "Score": "2", "body": "+1 for it being crazy short! Very nice. Wouldn't want to be your team-mate who had to maintain it though :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T06:53:28.653", "Id": "39558", "Score": "0", "body": "@NickBurns Thanks :) Surely it's written not for production but just for fun. Maintainability should be on the first place." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T23:49:33.950", "Id": "25515", "ParentId": "25508", "Score": "2" } } ]
{ "AcceptedAnswerId": "25512", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T20:54:11.293", "Id": "25508", "Score": "4", "Tags": [ "python", "iteration" ], "Title": "Python line condenser function" }
25508
<p>I have often read about how important clear and efficient code is. Also often people talk and write about 'beautiful' code. Some hints and critic from experienced developers for the following code would be extremely helpful to me. Another question that I often ask myself is about list comprehensions: I feel that in the first specific code (about prime palindromes), especially the second function that verifies palindrome characteristics could be expressed on one line in a list comprehension - how would that work, and would it even be an advantage of some sort?</p> <p>The code calculates all the prime palindromes from 0 to 1000 and prints the largest.</p> <pre><code>#My solution to codeval challenge Prime Palindrome. AUTHOR: S.Spiess #initial count counting_list = [x for x in range(0,1001)] #prime number check. make list prime_list containing only primes from 0 to 1000 def prime_check(a_list): prime_list = [] for k in a_list: count = 2.0 d_test = 0 while count &lt; k: if k % count == 0: d_test += 1 count += 1 else: count += 1 if d_test &lt; 1 and k &gt; 1: prime_list.append(k) return prime_list #check prime numbers from previous function for palindrome characteristic. append in new list. def palindrome_check(num_list): palindrome_list = [] for i in num_list: temp = str(i) if temp == temp[::-1]: palindrome_list.append(i) return palindrome_list #print biggest palindrome prime from 0 to 1000 print max(palindrome_check(prime_check(counting_list))) </code></pre> <p>Here is another sample of code I wrote. It contains two functions that can change the base of a number.</p> <pre><code>def to_mod20(any_num): a_list = [] if any_num &lt; 20 and any_num &gt;= 1: a_list.append(int(any_num)) while any_num &gt;= 20: a_list.append(any_num % 20) if any_num / 20 &lt; 20: a_list.append(any_num / 20) any_num = any_num / 20 #invert list for proper output return a_list[::-1] def decimal_mod20(any_dec): count = 0 a_list = [] while any_dec &lt; 1 and count &lt; 4: a_list.append(int(any_dec * 17.0)) any_dec = any_dec * 17.0 - int(any_dec * 17.0) count += 1 #print any_dec return a_list </code></pre>
[]
[ { "body": "<ul>\n<li>The list comprehension <code>[x for x in range(0,1001)]</code> is redundant, as <code>range</code> already returns a list in Python 2. In Python 3 one can use <code>list(range(1001))</code></li>\n<li>Write a <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstring</a> instead of a comment to describe a function.</li>\n<li>Why is <code>count</code> a <code>float</code> (2.0) in <code>prime_check</code>? Should be an <code>int</code>.</li>\n<li>Prefer <code>for</code> loops to <code>while</code> loops when they do the same thing. Eg. use <code>for count in xrange(2, k)</code> in <code>prime_check</code>.</li>\n<li><code>if any_num &lt; 20 and any_num &gt;= 1:</code> can be written as <code>if 1 &lt;= any_num &lt; 20:</code></li>\n<li>You may want to look for more efficient algorithms for generating primes.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-29T09:55:58.990", "Id": "39652", "Score": "0", "body": "Good to know.. very helpful points! Unfortunately I cannot vote up yet due to missing reputation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T17:01:51.923", "Id": "25537", "ParentId": "25521", "Score": "5" } } ]
{ "AcceptedAnswerId": "25537", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T10:18:21.683", "Id": "25521", "Score": "5", "Tags": [ "python", "primes", "palindrome" ], "Title": "Calculating all prime palindromes from 0 to 1000 and printing the largest" }
25521
<p>I am trying to code <a href="http://en.wikipedia.org/wiki/Battleship_%28game%29" rel="nofollow">Battleship</a>. It should be a text one-player game against computer where computer and human player take turns in shooting at opponent's ships. I decided to start implementation with this part: <em>A human types target coordinates and computer answers if a ship has been hit or even if it has been sunk. Ship positions are fixed (predefined in the program).</em> For some time I wondered how to represent game plan and ships to get this working as smoothly as possible. This is what I have put together:</p> <pre><code>class GamePlan: DIMX = 10 DIMY = 10 SHIP_MISS = 0 SHIP_HIT = 1 SHIP_DEAD = 2 SHIP_COUNTS = { 2: 1, 3: 1, } def __init__(self): self.ships = [ [(1,1), (1,2)], [(5,6), (5,7), (5,8)], ] def hit(self, target): hit_ship = None hit_ship_index = None for i, ship in enumerate(self.ships): if target in ship: ship.pop(ship.index(target)) hit_ship = ship hit_ship_index = i if hit_ship == []: self.ships.pop(hit_ship_index) return self.SHIP_DEAD if hit_ship: return self.SHIP_HIT return self.SHIP_MISS def main(): game_plan = GamePlan() while True: raw_coords = raw_input('Enter coords: ') str_coords = raw_coords.split() coords = tuple([int(c) for c in str_coords]) if len(coords) != 2: print 'Bad input' continue result = game_plan.hit(coords) if result == GamePlan.SHIP_DEAD: print 'Ship dead' if result == GamePlan.SHIP_HIT: print 'Ship hit' if result == GamePlan.SHIP_MISS: print 'Missed' if __name__ == "__main__": main() </code></pre> <p><strong>EDIT:</strong> <code>GamePlan</code> should be probably called <code>Board</code> as answer of Janne Karila suggests. Just to clarify what I meant by that name with my flawed English.</p> <p>There are a few things I am unsure about:</p> <ol> <li><p>Is it correct that <code>GamePlan</code> processes shooting (in the method <code>hit</code>)? </p></li> <li><p>Is <code>hit</code> a good name for that method or should it be something like <code>process_hit</code>? Because <code>GamePlan</code> is being hit, it is not hitting anything. Is <code>hit</code> still good in such case? This is probably my biggest concern.</p></li> <li><p>Should ships be represented as objects of a class <code>Ship</code> instead?</p></li> <li><p>Is <code>GamePlan</code> a good thing to have or is it useless? I mean I could make class AI that directly owns <code>ships</code> but I am not sure where stuff like <code>SHIP_COUNTS</code> would go then. I have also planned that I will use <code>GamePlan</code> to generate ship positions (hence <code>SHIP_COUNTS</code> and <code>DIMX</code>, <code>DIMY</code> which are unused atm) but plan generation could also easily go to AI, I guess.</p></li> <li><p>Is there anything else that is wrong?</p></li> </ol>
[]
[ { "body": "<ol>\n<li><p>I think it is good idea to have method hit inside GamePlan because you don't plan to use it in other place then GamePlan I assume.</p></li>\n<li><p>You have chosen good name for method hit. 'Simple is better then complex'.</p></li>\n<li><p>If you plan continue develop game you suppose to put ship into separated class it will be easier to operate when code will grow.</p></li>\n<li><p>PlanGame is good idea to have. It helps separate game code from future Menu for example.\nWhat you can do change PlanGame to GameController. The GameController could manage all objects and get orders to do such as .hit(), .create_ship(), .restart() etc. Also this will let you create Plan or Map which will be managed by GameController also.</p></li>\n<li><p>I cannot see any docstrings. Remember that we read code more often then write.</p></li>\n</ol>\n\n<p>Your result codes are good but you can enhance them:</p>\n\n<pre><code>SHIP_MISS = 0\nSHIP_HIT = 1\nSHIP_DEAD = 2\n\nRESULTS = {SHIP_MISS: 'Missed',\n SHIP_HIT: 'Hit',\n SHIP_DEAD: 'Dead'}\n</code></pre>\n\n<p>And now you can do:</p>\n\n<pre><code>if result == GamePlan.SHIP_DEAD:\n print GamePlan.RESULTS[SHIP_DEAD]\nif result == GamePlan.SHIP_HIT:\n print GamePlan.RESULTS[SHIP_HIT]\nif result == GamePlan.SHIP_MISS:\n print GamePlan.RESULTS[SHIP_MISS]\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>print GamePlan.RESULTS[result]\n</code></pre>\n\n<p>This is closing for changes and opening for improvements try do that as much as possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T20:27:47.327", "Id": "39588", "Score": "0", "body": "Thank you. That dictionary in 5. is cool. And GameController is very interesting idea in 4." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T20:17:33.573", "Id": "25549", "ParentId": "25541", "Score": "2" } } ]
{ "AcceptedAnswerId": "25547", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T18:28:20.937", "Id": "25541", "Score": "6", "Tags": [ "python", "battleship" ], "Title": "Designing a simple Battleship game in Python" }
25541
<p>I want to retrieve id and name per skill. It works but is it well done? I would like to stay with minidom but all advices will be appreciated.</p> <pre><code># This is only part of XML that interesting me: # &lt;skill&gt; # &lt;id&gt;14&lt;/id&gt; # &lt;skill&gt; # &lt;name&gt;C++&lt;/name&gt; # &lt;/skill&gt; # &lt;/skill&gt; # &lt;skill&gt; # &lt;id&gt;15&lt;/id&gt; # &lt;skill&gt; # &lt;name&gt;Java&lt;/name&gt; # &lt;/skill&gt; # &lt;/skill&gt; skills = document.getElementsByTagName('skill') for skill in skills: try: id_ = skill.getElementsByTagName('id')[0].firstChild.nodeValue name = skill.getElementsByTagName('name')[0].firstChild.nodeValue my_object.create(name=name.strip(), id=id_.strip()) except IndexError: pass </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T21:27:55.170", "Id": "39591", "Score": "0", "body": "Your xml doesn't seem to match your code (and is also not well formed)." } ]
[ { "body": "<p>This is probably as good as you can get with minidom.</p>\n<p>However, consider ditching minidom--it's really only there when you <em>absolutely, postively</em> need some kind of DOM api and only have the standard library. Note the <a href=\"http://docs.python.org/2/library/xml.dom.minidom.html\" rel=\"nofollow noreferrer\">documentation for minidom</a>.</p>\n<blockquote>\n<p>Users who are not already proficient with the DOM should consider using the xml.etree.ElementTree module for their XML processing instead</p>\n<p>Warning: The xml.dom.minidom module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.</p>\n</blockquote>\n<p>XML in Python is almost always processed with the <a href=\"http://docs.python.org/2/library/xml.etree.elementtree.html\" rel=\"nofollow noreferrer\">ElementTree</a> interface, not a DOM interface. There are many implementations of ElementTree including xml.etree.ElementTree (pure Python, in stdlib) and xml.etree.cElementTree (CPython, in stdlib), and lxml (third-party all-singing, all-dancing xml processing library that uses libxml2).</p>\n<p>Here is how I would do this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n # On Python 2.x, use the faster C implementation if available\n from xml.etree import cElementTree as ET\nexcept ImportError:\n # pure-python fallback\n # In Python3 just use this, not the one above:\n # Python3 will automatically choose the fastest implementation available.\n from xml.etree import ElementTree as ET\n\nxmlstr = &quot;&quot;&quot;&lt;root&gt;\n&lt;skill&gt;\n &lt;id&gt;14&lt;/id&gt;\n &lt;name&gt;C++&lt;/name&gt;\n &lt;/skill&gt;\n &lt;skill&gt;\n &lt;id&gt;15&lt;/id&gt;\n &lt;name&gt;Java&lt;/name&gt;\n &lt;/skill&gt;\n&lt;/root&gt;&quot;&quot;&quot;\n\nroot = ET.fromstring(xmlstr)\n\ndef get_subelem_texts(elem, subelems):\n &quot;&quot;&quot;Return {subelem: textval,...} or None if any subelems are missing (present but empty is ok)&quot;&quot;&quot;\n attrs = {}\n for sa in skillattrs:\n textval = skill.findtext(sa)\n if textval is None:\n return None\n attrs[sa] = textval.strip()\n return attrs\n\n\nskillattrs = 'id name'.split()\n\nfor skill in root.find('skill'):\n args = get_subelem_texts(skill, skillattrs)\n if args is not None:\n my_object.create(**args)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T21:54:14.563", "Id": "25553", "ParentId": "25544", "Score": "2" } }, { "body": "<p>In the sample code you provided, there are skill outer and inner tag names. The way you loop over them triggers to <code>IndexError</code> exceptions that you simply ignore.</p>\n\n<p>Usually we handle exceptions in order to do something meaningful and concrete, not to ignore them. A way to avoid this dilemma is to simply avoid triggering those exceptions (especially that in practice you may have more elements than what you provided). So this is the way you could improve the code on this point:</p>\n\n<pre><code>&gt;&gt;&gt; from xml.dom import minidom\n&gt;&gt;&gt; xml_string = '&lt;top&gt;&lt;skill&gt;&lt;id&gt;14&lt;/id&gt;&lt;skill&gt;&lt;name&gt;C++&lt;/name&gt;&lt;/skill&gt;&lt;/skill&gt;&lt;skill&gt;&lt;id&gt;15&lt;/id&gt;&lt;skill&gt;&lt;name&gt;Java&lt;/name&gt;&lt;/skill&gt;&lt;/skill&gt;&lt;/top&gt;'\n&gt;&gt;&gt; xml_dom = minidom.parseString(xml_string)\n&gt;&gt;&gt; ids = xml_dom.getElementsByTagName('id')\n&gt;&gt;&gt; names = xml_dom.getElementsByTagName('name')\n&gt;&gt;&gt; language_ids = [ids[i].firstChild.data for i in range(len(ids))]\n&gt;&gt;&gt; language_names = [names[i].firstChild.data for i in range(len(names))]\n&gt;&gt;&gt; language_ids_with_names = dict(zip(language_ids, language_names))\n&gt;&gt;&gt; language_ids_with_names\n{u'15': u'Java', u'14': u'C++'}\n</code></pre>\n\n<p>Note that I added a root element called <code>top</code> for the XML string you provided, otherwise I can not parse it.</p>\n\n<p>I do not see a reason why to change the library for this code. Many people ask to use <code>minidom</code> alternatives but there are many situations where <code>minidom</code> is effective and useful and I used it many times professionally.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-25T09:31:14.773", "Id": "192897", "ParentId": "25544", "Score": "0" } } ]
{ "AcceptedAnswerId": "25553", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T18:59:07.863", "Id": "25544", "Score": "2", "Tags": [ "python", "xml" ], "Title": "Parsing XML with double nested tags using mindom" }
25544
<p>The code checks many more conditions like the one below. I was thinking to memoize it, but I can't think about how (writers block). How else could I optimize this? I know it seems silly, but my code is spending the majority of the time in the function.</p> <pre><code>def has_three(p, board): """Checks if player p has three in a row""" # For every position on the board for i in xrange(6): for j in xrange(7): if board[i][j] == p: if i&lt;=2 and board[i+1][j]==p and board[i+2][j]==p and board[i+3][j]==0: return True if i&gt;=3 and board[i-1][j]==p and board[i-2][j]==p and board[i-3][j]==0: return True if j&lt;=3 and board[i][j+1]==p and board[i][j+2]==p and board[i][j+3]==0: return True if j&gt;=3 and board[i][j-1]==p and board[i][j-2]==p and board[i][j-3]==0: return True if i&lt;=2 and j&lt;=3 and board[i+1][j+1]==p and board[i+2][j+2]==p and board[i+3][j+3]==0: return True if i&lt;=2 and j&gt;=3 and board[i+1][j-1]==p and board[i+2][j-2]==p and board[i+3][j-3]==0: return True if i&gt;=3 and j&lt;=3 and board[i-1][j+1]==p and board[i-2][j+2]==p and board[i-3][j+3]==0: return True if i&gt;=3 and j&gt;=3 and board[i-1][j-1]==p and board[i-2][j-2]==p and board[i-3][j-3]==0: return True return False </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T21:13:37.580", "Id": "39589", "Score": "4", "body": "Can you post the entire function and some input and expected output? Also, what the function is supposed to do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T22:23:15.770", "Id": "39592", "Score": "0", "body": "Can there be more than two players?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T22:32:40.573", "Id": "39593", "Score": "0", "body": "nope, only two. and i'll call them 1 and 2" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-27T08:46:34.553", "Id": "39596", "Score": "2", "body": "A board of 7x6 looks like \"Connect Four\", except that you check not 4 but 3 connected cells (\"Connect Three\"?). Is that what you are trying to do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-28T09:25:49.897", "Id": "39627", "Score": "0", "body": "Even not knowing the game, I wonder if the checks for `==0` are correct here." } ]
[ { "body": "<p>We really need to know more about the game to help you properly. Also, why is your program spending so much time in this function? (Are you doing some kind of lookahead, with this function being part of the evaluation?)</p>\n\n<p>If this is a game like <a href=\"http://en.wikipedia.org/wiki/Gomoku\" rel=\"nofollow\">gomoku</a>, where players take turns, and in each turn a player places one piece on the board, and the first player to get <em>n</em> in a line wins, then the only way that the board can have a winning line is if that line includes the piece that was just played. Hence there's no point looking at other points in the board.</p>\n\n<p>So in this case you'd write something like this:</p>\n\n<pre><code>DIRECTIONS = [(1,0),(1,1),(0,1),(-1,1)]\n\ndef legal_position(i, j, board):\n \"\"\"Return True if position (i, j) is a legal position on 'board'.\"\"\"\n return 0 &lt;= i &lt; len(board) and 0 &lt;= j &lt; len(board[0])\n\ndef winning_move(player, move, board, n = 3):\n \"\"\"Return True if 'move' is part of a line of length 'n' or longer for 'player'.\"\"\"\n for di, dj in DIRECTIONS:\n line = 0\n for sign in (-1, 1):\n i, j = move\n while legal_position(i, j, board) and board[i][j] == player:\n i += sign * di\n j += sign * dj\n line += 1\n if line &gt; n: # move was counted twice\n return True\n return False\n</code></pre>\n\n<p>But without understanding the rules of your game, it's impossible for me to know if this approach makes any sense.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T23:04:36.970", "Id": "25554", "ParentId": "25550", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T21:10:59.193", "Id": "25550", "Score": "2", "Tags": [ "python", "performance" ], "Title": "Checking a board to see if a player has three in a row" }
25550
<p>There is a lib code, trying to parse an Element Tree object. If exception happens, it either returns an empty dict of dict or a partially constructed object of such type. In this case, caller needs to parse the results to see if parsing is correctly handled or not. Or in other words, the returned dict is not deterministic. How to solve this issue? Or if this is an issue?</p> <pre><code>def parse_ET(self, ETObj): if ETObj == None: return None dict_of_dict = collections.defaultdict(dict) try: for doc in ETObj.iter("result"): id = doc.attrib.get("id") for elem in doc.iter("attrib"): dict_of_dict[id].setdefault(elem.attrib.get("name"), elem.text) except Exception, ex: logging.exception("%s:%s" % (self.__class__, str(ex))) finally: return dict_of_docs </code></pre>
[]
[ { "body": "<pre><code>def parse_ET(self, ETObj):\n</code></pre>\n\n<p>Python style guide recommends lowercase_with_underscores for both function and parameter names</p>\n\n<pre><code> if ETObj == None: return None\n</code></pre>\n\n<p>Use <code>is None</code> to check for None. However, consider whether you really want to support None as a parameter. Why would someone pass None to this function? Do they really want a None in return?</p>\n\n<pre><code> dict_of_dict = collections.defaultdict(dict)\n</code></pre>\n\n<p>Avoid names that describe the datastructure. Choose names that describe what you are putting in it.</p>\n\n<pre><code> try:\n for doc in ETObj.iter(\"result\"):\n id = doc.attrib.get(\"id\")\n for elem in doc.iter(\"attrib\"):\n dict_of_dict[id].setdefault(elem.attrib.get(\"name\"), elem.text)\n</code></pre>\n\n<p>Can there be duplicate \"id\" and \"name\"? If not you don't need to use defaultdict or setdefault</p>\n\n<pre><code> except Exception, ex:\n</code></pre>\n\n<p>You should almost never catch generic exceptions. Only catch the actual exceptions you want. </p>\n\n<pre><code> logging.exception(\"%s:%s\" % (self.__class__, str(ex)))\n</code></pre>\n\n<p>Don't log errors and try to continue on as if nothing has happened. If your function fails, it should raise an exception. In this case, you probably shouldn't even catch the exception. </p>\n\n<pre><code> finally:\n return dict_of_docs\n</code></pre>\n\n<p><code>finally</code> is for cleanup tasks. Under no circumstances should you putting a return in it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T18:04:25.137", "Id": "39796", "Score": "0", "body": "Thanks Winston. If I don't want to catch the exception, the best way is to remove try...except? or just raise?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T18:04:25.443", "Id": "39797", "Score": "0", "body": "What's the best way to force argument not None? <br>>>> def func(a):\n... print a" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T18:14:14.200", "Id": "39798", "Score": "0", "body": "@user24622, if the caller caused the error, then you should raise a new error which tells the caller what they did wrong. If its a bug in your code, just don't catch it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T18:15:08.720", "Id": "39799", "Score": "0", "body": "@user24622, as for forcing not None, don't bother. You'll get an fairly obvious error in any case, so you don't gain anything by checking. You can't assume that its safe to pass None into things, and so you don't need to let your callers assume that." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T14:09:42.063", "Id": "25686", "ParentId": "25672", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T01:14:45.523", "Id": "25672", "Score": "1", "Tags": [ "python", "exception" ], "Title": "How to handle returned value if an exception happens in a library code" }
25672
<p>Inspired by a recent question that caught my interest (now <a href="https://codereview.stackexchange.com/questions/25642/re-arrange-letters-to-produce-a-palindrome">deleted</a>), I wrote a function in Python 3 to rearrange the letters of a given string to create a (any!) palindrome:</p> <ol> <li>Count the occurrences of each letter in the input</li> <li>Iterate over the resulting <code>(letter, occurrences)</code> tuples only once: <ul> <li>If the occurences are even, we remember them to add them around the center later</li> <li>A valid palindrome can contain only <strong>0 or 1 letter(s) with an odd number of occurrences</strong>, so if we've already found the center, we raise an exception. Otherwise, we save the new-found center for later</li> </ul></li> <li>Finally, we add the sides around the center and join it to create the resulting palindrome string.</li> </ol> <p>I'm looking for feedback on every aspect you can think of, including </p> <ul> <li>readability (including docstrings),</li> <li>how appropriate the data structures are,</li> <li>if the algorithm can be expressed in simpler terms (or replaced altogether) and </li> <li>the quality of my tests.</li> </ul> <hr> <h2>Implementation: <code>palindromes.py</code></h2> <pre><code>from collections import deque, Counter def palindrome_from(letters): """ Forms a palindrome by rearranging :letters: if possible, throwing a :ValueError: otherwise. :param letters: a suitable iterable, usually a string :return: a string containing a palindrome """ counter = Counter(letters) sides = [] center = deque() for letter, occurrences in counter.items(): repetitions, odd_count = divmod(occurrences, 2) if not odd_count: sides.append(letter * repetitions) continue if center: raise ValueError("no palindrome exists for '{}'".format(letters)) center.append(letter * occurrences) center.extendleft(sides) center.extend(sides) return ''.join(center) </code></pre> <hr> <h2>Unit tests: <code>test_palindromes.py</code> (using <em>py.test</em>)</h2> <pre><code>def test_empty_string_is_palindrome(): assert palindrome_from('') == '' def test_whitespace_string_is_palindrome(): whitespace = ' ' * 5 assert palindrome_from(whitespace) == whitespace def test_rearranges_letters_to_palindrome(): assert palindrome_from('aabbb') == 'abbba' def test_raises_exception_for_incompatible_input(): with pytest.raises(ValueError) as error: palindrome_from('asdf') assert "no palindrome exists for 'asdf'" in error.value.args </code></pre> <hr> <h2>Manual testing in the console</h2> <pre><code>while True: try: word = input('Enter a word: ') print(palindrome_from(word)) except ValueError as e: print(*e.args) except EOFError: break </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-14T17:26:20.193", "Id": "184519", "Score": "0", "body": "Rather than checking if you already have a letter with odd frequency, you can just count how many you have total, and if it is not equal to mod2 of the length of the string, it can't be a palindrome. In other words, if(number_of_odd_frequencies == len(word) % 2): it is a palindrome" } ]
[ { "body": "<pre><code>from collections import deque, Counter\n\n\ndef palindrome_from(letters):\n \"\"\"\n Forms a palindrome by rearranging :letters: if possible,\n throwing a :ValueError: otherwise.\n :param letters: a suitable iterable, usually a string\n :return: a string containing a palindrome\n \"\"\"\n counter = Counter(letters)\n sides = []\n center = deque()\n for letter, occurrences in counter.items():\n repetitions, odd_count = divmod(occurrences, 2)\n</code></pre>\n\n<p>odd_count is a bit of a strange name, because its just whether its odd or even, not really an odd_count</p>\n\n<pre><code> if not odd_count:\n sides.append(letter * repetitions)\n continue\n</code></pre>\n\n<p>avoid using continue, favor putting the rest of the loop in an else block. Its easier to follow that way</p>\n\n<pre><code> if center:\n raise ValueError(\"no palindrome exists for '{}'\".format(letters))\n center.append(letter * occurrences)\n center.extendleft(sides)\n center.extend(sides)\n</code></pre>\n\n<p>Avoid reusing variables for something different. Changing center to be the whole phrase isn't all that good an idea. I suggest using <code>itertools.chain(sides, center, reversed(sides))</code> and then joining that.</p>\n\n<pre><code> return ''.join(center)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T13:13:15.043", "Id": "39766", "Score": "0", "body": "Interesting! Using `itertools.chain` eliminates the need to use a `deque` I guess. You need to do `reversed(sides)` for the last argument though (the deque used to do that by itself for some reason)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T13:19:50.703", "Id": "39768", "Score": "0", "body": "@codesparkle, ah I suppose extendleft probably extends in the backwards order." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T13:10:01.467", "Id": "25680", "ParentId": "25679", "Score": "2" } } ]
{ "AcceptedAnswerId": "25680", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T12:39:17.153", "Id": "25679", "Score": "4", "Tags": [ "python", "algorithm", "palindrome" ], "Title": "Create palindrome by rearranging letters of a word" }
25679
<p>I created a reusable function for changing block name in Djago templates. I want to know if the code is good or is there any probable issues in it. I developed the function as a hack for the following <a href="https://stackoverflow.com/questions/16320010/is-there-a-way-to-set-name-of-a-block-using-variables-in-django-templates/">issue</a>.</p> <p>Template Code</p> <pre><code>{% extends base_name %} {% block main-contents %} &lt;h2&gt;{{ message_heading }}&lt;/h2&gt; &lt;div class="alert alert-{{ box_color|default:"info" }}"&gt; {{ message }} {% if btn_1_text and btn_1_url %} &lt;a href="{{ btn_1_url }}" class="btn btn-{{ btn_1_color }}"&gt;{{ btn_1_text }}&lt;/a&gt; {% endif %} {% if btn_2_text and btn_2_url %} &lt;a href="{{ btn_2_url }}" class="btn btn-{{ btn_2_color }}"&gt;{{ btn_2_text }}&lt;/a&gt; {% endif %} &lt;/div&gt; {% endblock %} </code></pre> <p>Function to change block name</p> <pre><code>def change_block_names(template, change_dict): """ This function will rename the blocks in the template from the dictionary. The keys in th change dict will be replaced with the corresponding values. This will rename the blocks in the extended templates only. """ extend_nodes = template.nodelist.get_nodes_by_type(ExtendsNode) if len(extend_nodes) == 0: return extend_node = extend_nodes[0] blocks = extend_node.blocks for name, new_name in change_dict.items(): if blocks.has_key(name): block_node = blocks[name] block_node.name = new_name blocks[new_name] = block_node del blocks[name] tmpl_name = 'django-helpers/twitter-bootstrap/message.html' tmpl1 = loader.get_template(tmpl_name) change_block_names(tmpl1, {'main-contents': 'new-main-contents'}) return HttpResponse(tmpl.render(Context())) </code></pre> <p>This function seems to work for my issue. But I don't know if this breaks any of the Django's functionality. Can anyone verify this and give me some advice?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:17:09.053", "Id": "44851", "Score": "0", "body": "have you tried running django's unit tests? is there a unit test for templates for dealing with similar issues and can you write your own? That's the only thing I can think of judging from this code,." } ]
[ { "body": "<p>This seems valid, and I don't think it should mess up Django's functionality.\nSome improvements are possible.</p>\n\n<hr>\n\n<p>This is not <em>Pythonic</em>:</p>\n\n<blockquote>\n<pre><code>if len(extend_nodes) == 0:\n return\n</code></pre>\n</blockquote>\n\n<p>Write like this:</p>\n\n<pre><code>if not extend_nodes:\n return\n</code></pre>\n\n<hr>\n\n<p>This is not Pythonic:</p>\n\n<blockquote>\n<pre><code> if blocks.has_key(name):\n # ...\n</code></pre>\n</blockquote>\n\n<p>Write like this:</p>\n\n<pre><code> if name in blocks:\n # ...\n</code></pre>\n\n<h3>But...</h3>\n\n<p>You're not supposed to do this.\nYou haven't explained why you want to change template block names on the fly.\nAnd I cannot think of a legitimate use case.\nIt's inefficient to do this operation on the fly,\nfor every page load.\nWhat you should really do instead is update the template files in your project,\ndo the necessary renames once and save it,\nso that you don't need this unnecessary extra operation.\nThe end result will be more efficient, and more robust.\nUpdating all files in your project is possible with a little scripting.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-17T18:57:16.040", "Id": "73968", "ParentId": "25700", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T19:21:36.310", "Id": "25700", "Score": "4", "Tags": [ "python", "django" ], "Title": "Django template block name changing function" }
25700
<p>I have some code for a calculator, and I was wondering what I could look at to make the code smaller, easier to read or better in any way. I'm particularly looking at my global variable <code>x</code>. Is there any way to change the code to completely remove that? Someone mentioned a <code>getTwoInputs()</code> function, but with multiple different questions (<code>powers()</code> input and <code>addition()</code> input) I assume it would take up the same space.</p> <pre><code>def Addition(): print('Addition: What are your numbers?') a = float(input('First Number:')) b = float(input('Second Number:')) print('Your Answer is:', a + b) def Subtraction(): print('Subtraction: What are your numbers?') c = float(input('First Number:')) d = float(input('Second Number:')) print('Your Answer is:', c - d) def Multiplication(): print('Multiplication: What are your numbers?') e = float(input('First Number:')) f = float(input('Second Number:')) print('Your Answer is:', e * f) def Division(): print('Division: What are your numbers?') g = float(input('First Number:')) h = float(input('Second Number:')) print('Your Answer is:', g / h) def Roots(): print('Roots: What do you want to Root?') i = float(input('Number:')) print('Roots: By what root?') j = float(input('Number:')) k = ( 1 / j ) print('Your Answer is:',i**k) def Powers(): print('Powers: What number would you like to multiply by itself?') l = float(input('Number:')) print('Powers: How many times would you like to multiply by itself?') m = float(input('Number:')) print('Your Answer is:',l**m) x = 'test' def Question(): print('What would you like to do?') x = input('(Add, Subtract, Divide, Multiply, Powers, Roots or Quit)') if x.lower().startswith('a'): x = 'test123' print(Addition()) x = 'test' elif x.lower().startswith('d'): x = 'test123' print(Division()) x = 'test' elif x.lower().startswith('m'): x = 'test123' print(Multiplication()) x = 'test' elif x.lower().startswith('s'): x = 'test123' print(Subtraction()) x = 'test' elif x.lower().startswith('r'): x = 'test123' print(Roots()) x = 'test' elif x.lower().startswith('p'): x = 'test123' print(Powers()) x = 'test' elif x.lower().startswith('e'): x = 'test' print(exit()) elif x.lower().startswith('q'): x = 'test' print(exit()) else: print(""" Please type the first letter of what you want to do. """) print(Question()) while x == 'test': Question() </code></pre>
[]
[ { "body": "<p>I am not sure it is very clear to you what your different functions are returning as you seem to be trying to print their return value even though they do not return anything special.</p>\n\n<p>You do not need to change your variable names in each function without special reason. <code>a</code> and <code>b</code> are decent names in your case, you don't need to use <code>c</code> and <code>d</code> later and then <code>e</code> and <code>f</code> as there is no way to get confused anyway.</p>\n\n<p>The way you use your <code>x</code> variable is pretty cryptic to me. I guess this is just some testing/debugging but it would help if you could submit a clean version of your code for reviewing.</p>\n\n<p>Most of what happens in your function is (pretty much) the same from one to another. A good thing to do is to try to avoid repetition whenever you can and to abstract common behaviors. The quick and dirty way I've used to avoid such a repetition was to notice that you ask the user for 2 numbers anyway so it doesn't really matter which operator we will use them for. My minimalist solution stores things in a dictionary (you could improve the content of the dictionary if you wanted to have more things changing from one operator to another such as user prompts).</p>\n\n<pre><code>#!/usr/bin/python\nimport operator\n\noperations={\n 'a':('Addition', operator.add),\n 's':('Substraction', operator.sub),\n 'm':('Multiplication',operator.mul),\n 'd':('Division', operator.truediv),\n 'p':('Power', operator.pow),\n 'r':('Root', lambda x, y:x**(1/y)),\n}\n\nwhile True:\n # TODO : Next line could be generated from the list if it keeps growing\n x = input('(Add, Subtract, Divide, Multiply, Powers, Roots or Quit)').lower()\n if x in operations:\n operation_name,operator=operations[x]\n print(operation_name)\n a = float(input('First Number:'))\n b = float(input('Second Number:'))\n print(\"Your answer is \",operator(a,b))\n elif x.startswith('q'):\n break\n else:\n print(\"Please type the first letter of what you want to do.\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T08:18:31.233", "Id": "39856", "Score": "0", "body": "Comment taken into account :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T08:48:58.417", "Id": "39857", "Score": "0", "body": "One of the most important improvements here is that the real work (the operation dictionary) is separated from the interface/controller (the while loop). Just pointing it out for @Rinslep." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T22:23:10.147", "Id": "25710", "ParentId": "25701", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T19:42:42.393", "Id": "25701", "Score": "5", "Tags": [ "python", "python-3.x", "calculator" ], "Title": "Four-function calculator with roots and powers" }
25701
<p>I'm extracting 4 columns from an imported CSV file (~500MB) to be used for fitting a <code>scikit-learn</code> regression model.</p> <p>It seems that this function used to do the extraction is extremely slow. I just learnt python today, any suggestions on how the function can be sped up?</p> <p>Can multithreading/core be used? My system has 4 cores.</p> <pre><code>def splitData(jobs): salaries = [jobs[i]['salaryNormalized'] for i, v in enumerate(jobs)] descriptions = [jobs[i]['description'] + jobs[i]['normalizedLocation'] + jobs[i]['category'] for i, v in enumerate(jobs)] titles = [jobs[i]['title'] for i, v in enumerate(jobs)] return salaries, descriptions, titles </code></pre> <hr> <h2>Full Code</h2> <pre><code>def loadData(filePath): reader = csv.reader( open(filePath) ) rows = [] for i, row in enumerate(reader): categories = ["id", "title", "description", "rawLocation", "normalizedLocation", "contractType", "contractTime", "company", "category", "salaryRaw", "salaryNormalized","sourceName"] # Skip header row if i != 0: rows.append( dict(zip(categories, row)) ) return rows def splitData(jobs): salaries = [] descriptions = [] titles = [] for i in xrange(len(jobs)): salaries.append( jobs[i]['salaryNormalized'] ) descriptions.append( jobs[i]['description'] + jobs[i]['normalizedLocation'] + jobs[i]['category'] ) titles.append( jobs[i]['title'] ) return salaries, descriptions, titles def fit(salaries, descriptions, titles): #Vectorize vect = TfidfVectorizer() vect2 = TfidfVectorizer() descriptions = vect.fit_transform(descriptions) titles = vect2.fit_transform(titles) #Fit X = hstack((descriptions, titles)) y = [ np.log(float(salaries[i])) for i, v in enumerate(salaries) ] rr = Ridge(alpha=0.035) rr.fit(X, y) return vect, vect2, rr, X, y jobs = loadData( paths['train_data_path'] ) salaries, descriptions, titles = splitData(jobs) vect, vect2, rr, X_train, y_train = fit(salaries, descriptions, titles) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T22:55:18.333", "Id": "39821", "Score": "0", "body": "Can you provide a sample of the `train_data_path`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T02:06:29.573", "Id": "39840", "Score": "0", "body": "@WinstonEwert Sure: `http://www.mediafire.com/?4d3j8g88d6j2h0x`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T06:49:31.953", "Id": "39850", "Score": "0", "body": "Could you post a few lines of the data file directly in the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-16T14:05:36.473", "Id": "164869", "Score": "0", "body": "Please only state the code purpose in the title" } ]
[ { "body": "<p><code>titles = [jobs[i]['title'] for i, v in enumerate(jobs)]</code> can (should?) be rewritten :</p>\n\n<p><code>titles = [j['title'] for j in jobs.items()]</code> \nbecause we just want to access the value at position i (<a href=\"https://stackoverflow.com/questions/10498132/how-to-iterate-over-values-in-dictionary-python\">More details</a>)</p>\n\n<p>Thus, the whole code would be :</p>\n\n<pre><code>def splitData(jobs):\n salaries = [j['salaryNormalized'] for j in jobs.items)]\n descriptions = [j['description'] + j['normalizedLocation'] + j['category'] for j in jobs.items)]\n titles = [j['title'] for j in jobs.items)]\n\n return salaries, descriptions, titles\n</code></pre>\n\n<p>Not quite sure how much it helps from a performance point of view.</p>\n\n<p>Edit : Otherwise, another option might be to write a generator which returns <code>j['salaryNormalized'], j['description'] + j['normalizedLocation'] + j['category'], j['title']</code> as you need it. It depends how you use your function really.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T22:30:47.567", "Id": "39816", "Score": "0", "body": "I have updated the question with more code, that may help! How can I write the generator?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T21:23:49.623", "Id": "25705", "ParentId": "25702", "Score": "1" } }, { "body": "<p>It seems that you are looping through the entire job data set 3 times (once each for salaries, descriptions and titles). You will be able to speed this up three-fold, if you extract all the info in one pass:</p>\n\n<pre><code>def split_data(jobs):\n for job, info in jobs.items():\n salaries.append(info['salaryNormalized'])\n descriptions.append([info['description'], \n info['normalizedLocation'], \n info['category']])\n titles.append(info['title'])\n</code></pre>\n\n<p><strong>EDIT</strong> Added loadData(); slight tweak to return a dictionary of dictionaries, instead of a list of dictionaries:</p>\n\n<pre><code>def load_data(filepath):\n reader = csv.reader(open(filepath))\n jobs = {}\n\n for i, row in enumerate(reader):\n categories = [\"id\", \"title\", \"description\", \"rawLocation\", \"normalizedLocation\",\n \"contractType\", \"contractTime\", \"company\", \"category\",\n \"salaryRaw\", \"salaryNormalized\",\"sourceName\"]\n\n if i != 0:\n jobs[i] = dict(zip(categories, row))\n\n return jobs\n</code></pre>\n\n<p>An example:</p>\n\n<pre><code>jobs = {0 : {'salaryNormalized' : 10000, 'description' : 'myKob',\n 'normalizedLocation': 'Hawaii', 'category': 'categ1',\n 'title' : 'tourist'},\n 1 : {'salaryNormalized' : 15000, 'description' : 'myKob',\n 'normalizedLocation': 'Hawaii', 'category': 'categ2',\n 'title' : 'tourist'},\n 2 : {'salaryNormalized' : 50000, 'description' : 'myKob',\n 'normalizedLocation': 'Hawaii', 'category': 'categ10',\n 'title' : 'resort_manager'}}\n\nsalaries, descriptions, titles = [], [], []\nsplit_data(jobs)\n\nprint(salaries)\n--&gt; [10000, 15000, 50000]\n\nprint(descriptions)\n--&gt; [['myKob', 'Hawaii', 'categ1'], ['myKob', 'Hawaii', 'categ2'], ['myKob', 'Hawaii', 'categ10']]\n\nprint(titles)\n--&gt; ['tourist', 'tourist', 'resort_manager']\n</code></pre>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T22:34:13.837", "Id": "39817", "Score": "0", "body": "What makes you think that will speed it up three fold?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T22:40:22.583", "Id": "39818", "Score": "0", "body": "I am not suggesting that it will be exact, there will be some margin in that. Deductively, the original runs a loop through the data (~500MB) 3 times, that's expensive and dominates the time taken to run. This one only loops once. We have reduced the dominant factor by 3. \nMy algorithm theory isn't perfect though - have I missed the mark on this one? Appreciate your thoughts" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T22:48:17.640", "Id": "39820", "Score": "0", "body": "The problem is that your new loop does three times as much per iteration. It appends to a list three times, instead of 1. That means each iteration will take 3x the cost and your saving cancel completely out. Margins made it difficult to say which version will end up being faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T22:57:39.657", "Id": "39823", "Score": "0", "body": "That is a good point. However, original uses list comprehension to build the list one item at a time (though more efficiently than append) (total 3 'additions to list', for each entry in 500 MB). This version appends 3 times for one iteration (also therefore 3 calls to append for each entry in 500 MB). To me, that is the same number of append operations. Also kinda feel that the cost of appending is nominal compared the cost of looping over 500 MB. What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T23:29:17.363", "Id": "39824", "Score": "0", "body": "Looping is actually fairly cheap. Its the appending which is expensive. That's why I'd expect both versions to have very similar speeds. Combining the loops reduces the looping overhead. Using a comprehension will be faster to append. Who wins out? I don't know. But I'm pretty sure there isn't a 3X difference." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T22:22:43.310", "Id": "25709", "ParentId": "25702", "Score": "1" } }, { "body": "<pre><code>def loadData(filePath):\n reader = csv.reader( open(filePath) )\n rows = []\n\n for i, row in enumerate(reader):\n categories = [\"id\", \"title\", \"description\", \"rawLocation\", \"normalizedLocation\",\n \"contractType\", \"contractTime\", \"company\", \"category\",\n \"salaryRaw\", \"salaryNormalized\",\"sourceName\"]\n</code></pre>\n\n<p>A list like this should really be a global variable to avoid the expense of recreating it constantly. But you'd do better not store your stuff in a dictionary. Instead do this:</p>\n\n<pre><code> for (id, title, description, raw_location, normalized_location, contract_type,\n contractTime, company, category, salary_raw, salary_normalized, source_name) in reader:\n\n yield salary_normalized, ''.join((description, normalized_location, category)), title\n</code></pre>\n\n<p>All the stuff is then stored in python local variables (fairly efficient). Then yield produces the three elements you are actually wanting. Just use</p>\n\n<pre><code> salaries, descriptions, titles = zip(*loadData(...))\n</code></pre>\n\n<p>to get your three lists again</p>\n\n<pre><code> # Skip header row\n if i != 0: \n rows.append( dict(zip(categories, row)) )\n</code></pre>\n\n<p>Rather than this, call reader.next() before the loop to take out the header</p>\n\n<pre><code> return rows\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T01:56:05.563", "Id": "39837", "Score": "0", "body": "`loadtxt()` gives me the error `ValueError: cannot set an array element with a sequence` on line `X = np.array(X, dtype)`. Currently trying to upload the CSV somewhere" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T02:06:14.023", "Id": "39839", "Score": "0", "body": "Here's the CSV: `http://www.mediafire.com/?4d3j8g88d6j2h0x`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T02:57:05.333", "Id": "39843", "Score": "0", "body": "@Nyxynyx, my bad. numpy doesn't handled quoted fields. Replaced my answer with a better one. My code processes the file in 8 seconds (does everything before the `fit` function)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T03:09:59.713", "Id": "39844", "Score": "0", "body": "It appears that I need to do `rows = zip( load_data(...) )` instead of `salaries, descriptions, titles = zip(loadData(...))`. Is this correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T03:11:29.563", "Id": "39845", "Score": "0", "body": "@Nyxynyx, typo. Should be `salaries, description, titles = zip(*loadData(...)))`. `zip(*...)` does the opposite of `zip(...)`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T01:04:30.200", "Id": "25715", "ParentId": "25702", "Score": "2" } } ]
{ "AcceptedAnswerId": "25715", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T19:55:07.530", "Id": "25702", "Score": "1", "Tags": [ "python" ], "Title": "Speed up simple Python function that uses list comprehension" }
25702
<p>I realize this won't stop people who know what they're doing, just a project I decided to undertake while I'm trying to learn Python and Tkinter. Would love some input!</p> <pre><code>import Tkinter import base64 class crypt_mod(Tkinter.Tk): def __init__(self, parent): Tkinter.Tk.__init__(self, parent) self.parent = parent self.initialize() def initialize(self): self.grid() plain_label = Tkinter.Label(text='Plain Text:') plain_label.grid(column=0, row=0, sticky='E') self.ptxt = Tkinter.StringVar() self.plain_text = Tkinter.Entry(self, textvariable=self.ptxt, width=50) self.plain_text.grid(column=1, row=0, padx=5, pady=5) self.plain_text.bind("&lt;Return&gt;", self.encrypt) self.enc_button = Tkinter.Button(self, text='Encrypt', command=self.encrypt, relief='groove') self.enc_button.grid(column=2, row=0, padx=5, pady=5) self.dec_button = Tkinter.Button(self, text='Decrypt', command=self.decrypt, relief='groove') self.dec_button.grid(column=2, row=1, padx=5, pady=5) plain_label = Tkinter.Label(text='Base64:') plain_label.grid(column=0, row=1, sticky='E') self.etxt = Tkinter.StringVar() self.e_text = Tkinter.Entry(self, textvariable=self.etxt, width=50) self.e_text.grid(column=1, row=1, padx=5, pady=5) self.clear_button = Tkinter.Button(self, text='Clear Both', command=self.clear_both, relief='groove') self.clear_button.grid(column=1, row=2, padx=5, pady=5) self.htxt = Tkinter.StringVar() self.history = Tkinter.Text(width=50, height=10, wrap='word', spacing1=2, font=('courier',8), state='disabled') self.history.grid(column=0, row=3, columnspan=3, padx=5, pady=5) self.clear_history_button = Tkinter.Button(self, text='Clear History', command=self.clear_history, relief='groove') self.clear_history_button.grid(column=1, row=4, padx=5, pady=5) def encrypt(self): self.etxt.set(base64.b64encode(str(self.ptxt.get()))) self.history.config(state='normal') self.history.insert(Tkinter.END, 'encrypt:\n' + base64.b64encode(str(self.ptxt.get())) + '\n') self.history.config(state='disabled') self.history.see(Tkinter.END) #print "encrypt click!" def decrypt(self): self.ptxt.set(base64.b64decode(str(self.etxt.get()))) self.history.config(state='normal') self.history.insert(Tkinter.END, 'decrypt:\n' + base64.b64decode(str(self.etxt.get())) + '\n') self.history.config(state='disabled') self.history.see(Tkinter.END) #print "decrypt click!" def clear_both(self): self.etxt.set('') self.ptxt.set('') def clear_history(self): self.history.config(state='normal') self.history.delete(0.0, Tkinter.END) self.history.config(state='disabled') pass if __name__ == "__main__": app = crypt_mod(None) app.title('Base64 Crypto') app.mainloop() </code></pre>
[]
[ { "body": "<pre><code>import Tkinter\nimport base64\n\nclass crypt_mod(Tkinter.Tk):\n</code></pre>\n\n<p>Do you know about <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>? It's a style guide for Python that lots of Python developers follow. One of the things it says is that class names should use the CapWords convention, eg. CryptMod. Note that Tkinter doesn't necessary follow those rules, as it's a really old module.</p>\n\n<pre><code> def __init__(self, parent):\n Tkinter.Tk.__init__(self, parent)\n self.parent = parent\n self.initialize()\n</code></pre>\n\n<p><code>self.parent</code> seems to be unused.</p>\n\n<pre><code> def initialize(self):\n self.grid()\n ....\n</code></pre>\n\n<p>Not much to say here: the usual GUI building code.</p>\n\n<pre><code> def encrypt(self):\n self.etxt.set(base64.b64encode(str(self.ptxt.get())))\n self.history.config(state='normal')\n self.history.insert(Tkinter.END, 'encrypt:\\n' + base64.b64encode(str(self.ptxt.get())) + '\\n')\n self.history.config(state='disabled')\n self.history.see(Tkinter.END)\n #print \"encrypt click!\"\n</code></pre>\n\n<p>Avoid creating twice your encrypted text: your code would be clearer if you had a <code>encrypted</code> variable. It's not terribly important here, but could be in future projects where you will have more lines of code. Consider using <code>format()</code> (recommended in Python 3) instead of building your strings by concatenation: <code>\"decrypt:\\n {} \\n\".format(encrypted)</code>. (Those comments also apply to <code>decrypt</code>.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T02:11:27.177", "Id": "40431", "Score": "0", "body": "No, I was unaware of PEP8, but now I have a new obsession. :P Seems like the best time to learn to be Pythonic is at the start! Thanks for all the tips, will apply PEP8 to all future projects." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-07T11:23:43.270", "Id": "25898", "ParentId": "25773", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-03T16:59:49.900", "Id": "25773", "Score": "3", "Tags": [ "python" ], "Title": "Made a simple gui string encrypter, just to obfuscate plaintext" }
25773
<p>I'm writing a script to archive email messages from one IMAP folder to another. It looks, more or less, like the following. I've obfuscated about 30 lines unrelated to this question:</p> <pre><code>import imaplib import getpass def main(): user = getpass.getuser() + '@mymailbox.com' mailbox = imaplib.IMAP4_SSL('mymailbox.com', 993) try: mailbox.login(user, getpass.getpass()) except imaplib.IMAP4.error: raise RuntimeError('Credential error.') mailbox.select('my_mailbox') # Here lies some 30 lines not relevant to the question, but which # find mailbox messages, copies them to another folder, and # sets the delete flag in 'my_mailbox'. try: mailbox.close() # which also expunges the mailbox except: pass mailbox.logout() </code></pre> <p>After working with my IMAP server for a while, I've discovered a fair amount of unexpected error conditions arising from its implementation of <a href="https://www.rfc-editor.org/rfc/rfc3501" rel="nofollow noreferrer">RFC 3501</a>. No matter what, however, I always want to attempt <code>mailbox.close()</code> and <code>mailbox.logout()</code>.</p> <p>It sounds like a good occasion for a <a href="http://docs.python.org/2/reference/compound_stmts.html#try" rel="nofollow noreferrer"><code>try / finally</code> block</a>, and that usage is supported by <a href="http://pymotw.com/2/imaplib/#deleting-messages" rel="nofollow noreferrer">other examples</a>. All the same, it feels unnatural to wrap some 40 lines of <code>main()</code> execution in a try-block:</p> <pre><code>def main(): user = getpass.getuser() + '@mymailbox.com' mailbox = imaplib.IMAP4_SSL('mymailbox.com', 993) try: try: mailbox.login(user, getpass.getpass()) except imaplib.IMAP4.error: raise RuntimeError('Credential error.') mailbox.select('my_mailbox') # Here lies some 30 lines not relevant to the question, but which # find mailbox messages, copy them to another folder, and # set delete flags in 'my_mailbox'. finally: try: mailbox.close() # which also expunges the mailbox except: pass mailbox.logout() </code></pre> <p>Is that a common pattern? I could also write my own <a href="http://docs.python.org/2/reference/compound_stmts.html#with" rel="nofollow noreferrer">context manager</a>; perhaps that's the better way to go. What's the best practice for long-running connections like this?</p>
[]
[ { "body": "<p>Move the working logic into its own function</p>\n\n<pre><code>def process_mailbox(mailbox):\n user = getpass.getuser() + '@mymailbox.com'\n try:\n mailbox.login(user, getpass.getpass())\n except imaplib.IMAP4.error:\n raise RuntimeError('Credential error.')\n mailbox.select('my_mailbox')\n #whatever else\n\ndef main():\n mailbox = imaplib.IMAP4_SSL('mymailbox.com', 993)\n try:\n process_mailbox(mailbox)\n finally:\n try:\n mailbox.close() # which also expunges the mailbox\n except:\n pass\n mailbox.logout()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-06T02:49:48.453", "Id": "40023", "Score": "0", "body": "Stunningly obvious, in retrospect. Any thoughts on `with` vs. `try / finally` here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-06T02:59:18.330", "Id": "40024", "Score": "0", "body": "@Christopher, the `with` gets really helpful if you need to do this a lot. If this is the only function where you do it, it wouldn't seem all that people." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-06T02:05:53.310", "Id": "25854", "ParentId": "25853", "Score": "2" } } ]
{ "AcceptedAnswerId": "25854", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-06T01:14:56.270", "Id": "25853", "Score": "1", "Tags": [ "python", "exception-handling" ], "Title": "Is 'try / finally' the best way for me to handle (and close) this long-running IMAP4 connection?" }
25853
<p>I'm working on a web application using Bottle, and it is, at this point, functional. </p> <p>The gist of it is that I have a database of drinks, with associated IDs, and associated sets of ingredients. the name and ID of the drink are passed to the client, which displays them.</p> <p>Currently, when the program loads up, all drinks and their associated ingredient amounts are loaded into a list of dictionaries, like so:</p> <pre><code>SampleDrinkDict = {'name': 'Screwdriver', 'id': 4, 'vodka':2, 'orange juice':6} DrinkDictList = [] DrinkDictList.append(SampleDrinkDict) </code></pre> <p>Once the <code>DrinkDictList</code> is fully populated, I pass the names and IDs of every one to the client, which populates those in a list. When a drink is selected, it makes a callback to scan the <code>DrinkDictList</code> and find the matching 'id' field. Once it finds it in the list, the ingredient amounts and details are populated on the page.</p> <p>Would it be faster/better/more proper for me to only query ingredients from the DB once a drink is selected? </p> <p>For example, would it be faster/more pythonic/better to do this?</p> <pre><code>SampleDrinkDict = {'name': 'Screwdriver', 'id': 4,} DrinkDictList = [] DrinkDictList.append(SampleDrinkDict) @bottle.route('/drinkSelected/:id'): def getIng(id,db): sqlString = '''SELECT ingredients WHERE Drink_id = ?''' argString = (id,) ingredientList = db.execute(SqlString, argString).fetchall() </code></pre> <p>This is all running on a Raspberry Pi, and I'm worried about taxing the RAM once the drink list becomes huge. Is there any reason to go with one approach over the other?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T07:57:53.827", "Id": "40445", "Score": "0", "body": "You should use `lower_case_with_underscores` for variable names like `SampleDrinkDict` - see the [style guide](http://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables)." } ]
[ { "body": "<p>Whether you need to store data in the DB is really gonna depend on your testing, but here are a few thoughts about how to reduce memory usage while still building the entire drink table at startup:</p>\n\n<ul>\n<li>While they're convenient, you don't necessarily need to use dictionaries for this. You could replace each dictionary with a tuple where the first item is the drink name, the second item is the drink id, and the rest of the items are tuples of size 2 with the ingredient name and the ratio for that ingredient. This would change your example to <code>('Screwdriver', '4', ('vodka', 2), ('orange juice', 6))</code>. <code>sys.getsizeof</code> gives 280 for the dictionary and only 88 for the tuple, a significant reduction.</li>\n<li>If you're still pressed for space, you can take advantage of the fact that you probably have a lot of overlap in terms of your ingredients. Build a list with a string for each ingredient that one of your drinks uses. Then each tuple can simply have an <code>int</code> referring to the index of the ingredient in your ingredient list. This prevents you from storing a string like 'vodka' 20 different times. Once again using <code>sys.getsizeof</code> gives a value of 42 for the string 'vodka' and a value of 24 for the number 100. This will of course only work if you have enough overlap in your ingredients.</li>\n</ul>\n\n<p>If those ideas aren't enough to reduce your memory usage to an acceptable amount, you're probably going to need to go with your second solution(unless some other folks have some better ideas!). I don't really see one of your solutions as more pythonic than the other, so I wouldn't worry about that.</p>\n\n<p>And enjoy the raspberry pi!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T06:25:45.470", "Id": "40434", "Score": "3", "body": "One can [`intern`](http://docs.python.org/2/library/functions.html#intern) strings instead of your second bullet point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T06:34:28.023", "Id": "40435", "Score": "1", "body": "@JanneKarila good point, that's a much nicer way of solving the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T07:59:38.820", "Id": "40446", "Score": "2", "body": "Don't forget that changing from a dictionary (~O(1) lookups) to a list of tuples (O(n) lookups) will slow searches down considerably." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T12:27:51.730", "Id": "40468", "Score": "1", "body": "@AlexL but he isn't really using a dictionary, he's using a list of dictionaries. Searching through that list is still O(n)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T13:42:04.087", "Id": "40474", "Score": "0", "body": "I don't think I'll be swapping to tuples, as currently all of my logic and the bottle templates operate based on them. And i've already got a list of ingredients, but i havent yet used their indices to access the information, thats a good idea. I'll try out the string intern() too. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T17:54:53.787", "Id": "40499", "Score": "1", "body": "@Nolen Good point, perhaps he could improve performance by using drink ID as the key to his drinks dict? `drinks = {1: {name: screwdriver, ...}, 2: {...}, ...}`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T04:52:40.233", "Id": "26132", "ParentId": "26127", "Score": "3" } } ]
{ "AcceptedAnswerId": "26132", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-13T21:47:14.203", "Id": "26127", "Score": "6", "Tags": [ "python", "performance", "sql", "hash-map", "bottle" ], "Title": "Load drinks and their ingredients into dictionaries" }
26127
<p>I know that this is a complete mess and does not even come close to fitting PEP8. That's why I'm posting it here. I need help making it better.</p> <pre><code>bookName = None authorName = None bookStartLine = None bookEndLine = None def New_book(object): def __init__(self, currentBookName, currentAuthorName, currentBookStartLine, currentBookEndLine): self.currentBookName = currentBookName self.currentAuthorName = currentAuthorName self.currentBookStartLine = currentBookStartLine self.currentBookEndLine = currentBookEndLine import urllib.request def parser(currentUrl): #parses texts to extract their title, author, begginning line and end line global bookName global authorName global bookStartLine global bookEndLine global url url = 'http://www.gutenberg.org/cache/epub/1232/pg1232.txt' #machiaveli url = currentUrl book = urllib.request.urlopen(url) lines = book.readlines() book.close() finalLines = [line.decode()[:-2] for line in lines] for line in finalLines: if "Title" in line: currentBookName = line[7:len(line)] break for line in finalLines: if "Author" in line: currentAuthorName = line[8:len(line)] break currentBookStartLine,currentBookEndLine = False,False for index,line in enumerate(line,start=1): if "*** START OF THE PROJECT" in line: currentBookStartLine = index if "*** END OF THE PROJECT" in line: currentBookEndLine = index url = currentUrl bookName = currentBookName authorName = currentAuthorName bookStartLine = currentBookStartLine bookEndLine = currentBookEndLine parser('http://www.gutenberg.org/cache/epub/768/pg768.txt') #wuthering heights print(url) print(bookName) print(authorName) print(bookStartLine) print(bookEndLine) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T16:02:09.083", "Id": "40490", "Score": "0", "body": "`I know that this is a complete mess`. If you know something is a complete mess I'm sure you have a reason to think so. Focus on the why and try to change it." } ]
[ { "body": "<ul>\n<li>No need for a New_Book class with something so simple – I recommend a <a href=\"http://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow\">named tuple</a> instead.</li>\n<li>HTTPResponse objects don't seem to have a readlines() method (in Python 3) – this forces you to explicitly split the response data with '\\r\\n'.</li>\n<li>It's best to use the with-statement for file/resource operations. This is a CYA in case you forget to include resource.close() in your code.</li>\n</ul>\n\n<p>Here's my refactor:</p>\n\n<pre><code>from urllib.request import urlopen\nimport collections\n\ndef parser(url): \n '''parses texts to extract their title, author, begginning line and end line'''\n\n with urlopen(url) as res:\n lines = res.read().decode('utf-8').split('\\r\\n')\n\n title = next(line[7:] for line in lines if line.startswith(\"Title: \"))\n author = next(line[8:] for line in lines if line.startswith(\"Author: \"))\n start,end = False,False\n\n for index,line in enumerate(lines,start=1):\n if line.startswith(\"*** START OF THIS PROJECT\"):\n start = index\n\n if line.startswith(\"*** END OF THIS PROJECT\"):\n end = index - 1\n\n content = \"\".join(lines[start:end])\n\n return collections.namedtuple('Book', ['title', 'author', 'content', 'start', 'end'])(title, author, content, start, end)\n\nbook = parser('http://www.gutenberg.org/cache/epub/1232/pg1232.txt' ) #machiaveli &lt;3\nprint(\"{} by {}. {} lines\".format(book.title,book.author,book.end-book.start))\n#print(book.content)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-15T07:10:25.377", "Id": "26197", "ParentId": "26155", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T14:27:03.410", "Id": "26155", "Score": "2", "Tags": [ "python", "beginner", "parsing" ], "Title": "New book parser" }
26155
<p>A common idiom that I use for Python2-Python3 compatibility is:</p> <pre><code>try: from itertools import izip except ImportError: #python3.x izip = zip </code></pre> <p>However, a <a href="https://stackoverflow.com/questions/16598244/zip-and-groupby-curiosity-in-python-2-7/16598378?noredirect=1#comment23859060_16598378">comment</a> on one of my Stack Overflow answers implies that there may be a better way. Is there a more clean way to accomplish this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-16T23:10:11.107", "Id": "40683", "Score": "0", "body": "Perhaps the commenter meant to use the import to shadow `zip`? I.e., `try: from itertools import izip as zip; except ImportError: pass`. (Please excuse the lack of newlines.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-16T23:14:21.350", "Id": "40684", "Score": "0", "body": "Perhaps -- (I knew about that one). I was just wondering if there was some magic with `__import__` that I didn't know about or something." } ]
[ { "body": "<p>Not sure this is really an answer, or I should elaborate on my comment, and in hindsight probably not even a very good comment anyway, but:</p>\n\n<p>Firstly, you can just simplify it to:</p>\n\n<pre><code>try:\n from itertools import izip as zip\nexcept ImportError: # will be 3.x series\n pass\n</code></pre>\n\n<p>What I was thinking about was:</p>\n\n<p>From 2.6 you can use <a href=\"http://docs.python.org/2/library/future_builtins.html\">as per the docs</a>:</p>\n\n<pre><code>from future_builtins import map # or zip or filter\n</code></pre>\n\n<p>You do however then have the same problem of <code>ImportError</code> - so:</p>\n\n<pre><code>try:\n from future_builtins import zip\nexcept ImportError: # not 2.6+ or is 3.x\n try:\n from itertools import izip as zip # &lt; 2.5 or 3.x\n except ImportError:\n pass\n</code></pre>\n\n<p>The advantage of using <code>future_builtin</code> is that it's in effect a bit more \"explicit\" as to intended behaviour of the module, supported by the language syntax, and possibly recognised by tools. <strike>For instance, I'm not 100% sure, but believe that the 2to3 tool will re-write <code>zip</code> correctly as <code>list(zip(...</code> in this case, while a plain <code>zip = izip</code> may not be... But that's something that needs looking in to.</strike></p>\n\n<p>Updated - also in the docs:</p>\n\n<blockquote>\n <p>The 2to3 tool that ports Python 2 code to Python 3 will recognize this usage and leave the new builtins alone.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-17T01:16:34.380", "Id": "40692", "Score": "1", "body": "Ahh ... I didn't actually know about `future_builtins`. It seems a little silly that they don't have that in python3 though. I don't know why they didn't do something like `from __future__ import zip` instead. That would have made sense to me. Anyway, thanks for the explanation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-25T19:19:53.957", "Id": "43280", "Score": "0", "body": "I also think it's silly that 2to3 recognizes the usage of `future_builtins` yet leaves the `from future_builtins import whatever` statement(s) in the output." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-17T00:05:37.547", "Id": "26273", "ParentId": "26271", "Score": "14" } }, { "body": "<p>This is roughly twice as fast as using a try/except:</p>\n\n<pre><code>import itertools\nzip = getattr(itertools, 'izip', zip)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-21T03:28:01.590", "Id": "316548", "Score": "0", "body": "I find this claim hard to believe ... [`getattr`](https://github.com/python/cpython/blob/96c7c0685045b739fdc5145018cddfd252155713/Python/bltinmodule.c#L993) works by catching the `AttributeError` and substituting the default value. Admittedly, that's implemented in C so it might be slightly faster, but I find it hard to believe that there's a factor of 2. I also find it hard to believe that the time would matter in the real world if you have this at the top-level of your module... Finally, this _is_ possibly the cleanest way to write it that I've seen. Kudos for that :-)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-22T11:38:52.837", "Id": "316781", "Score": "0", "body": "@mgilson: Use `timeit` and test it yourself. I thought it might be faster, but I didn't think ~2x." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-20T17:48:13.763", "Id": "166265", "ParentId": "26271", "Score": "3" } } ]
{ "AcceptedAnswerId": "26273", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-16T22:53:34.787", "Id": "26271", "Score": "12", "Tags": [ "python", "dynamic-loading" ], "Title": "Import \"izip\" for different versions of Python" }
26271
<p>I have the following function:</p> <pre><code>def item_by_index(iterable, index, default=Ellipsis): """Return the item of &lt;iterable&gt; with the given index. Can be used even if &lt;iterable&gt; is not indexable. If &lt;default&gt; is given, it is returned if the iterator is exhausted before the given index is reached.""" iterable_slice = itertools.islice(iterable, index, None) if default is Ellipsis: return next(iterable_slice) return next(iterable_slice, default) </code></pre> <p>It should (and does) throw an exception if the <code>default</code> is not given and the iterator is exhausted too soon. This is very similar to what the built-in function <a href="http://docs.python.org/2/library/functions.html#next"><code>next</code></a> does.</p> <p>Usually, one would probably use <code>None</code> as default value to make an argument optional. In this case, however, <code>None</code> is a valid value for <code>default</code> and should be treated differently from no argument. This is why I used <code>Ellipsis</code> as a default value. It sort of feels like an abuse of the <code>Ellipsis</code> object, though.</p> <p>Is there a better way of doing this or is <code>Ellipsis</code> a good tool for the job? </p>
[]
[ { "body": "<p>I would argue the best option is to make an explicit sentinel value for this task. The best option in a case like this is a simple <code>object()</code> - it will only compare equal to itself (aka, <code>x == y</code> only when <code>x is y</code>).</p>\n\n<pre><code>NO_DEFAULT = object()\n\ndef item_by_index(iterable, index, default=NO_DEFAULT):\n ...\n</code></pre>\n\n<p>This has some semantic meaning, and means there is no potential overlap between a value a user wants to give and the default (I imagine it's highly unlikely they'd want to use Ellipses, but it's better to make as few assumptions as possible about use cases when writing functions). I'd recommend documenting it as such as well, as it allows the user to give a default/not using a variable, rather than having to change the call.</p>\n\n<pre><code>try:\n default = get_some_value()\nexcept SomeException:\n default = yourmodule.NO_DEFAULT\n\nitem_by_index(some_iterable, index, default)\n</code></pre>\n\n<p>As opposed to having to do:</p>\n\n<pre><code>try:\n default = get_some_value()\nexcept SomeException:\n item_by_index(some_iterable, index)\nelse:\n item_by_index(some_iterable, index, default)\n</code></pre>\n\n<p>The only downside it's not particularly clear what it is if you are looking at the object itself. You could create a custom class with a suitable <code>__repr__()</code>/<code>__str__()</code> and use an instance of it here.</p>\n\n<p>As of Python 3 <a href=\"http://www.python.org/dev/peps/pep-0435/\">enums have been added</a> - the default type of enum only compares equal on identity, so a simple one with only the one value would also be appropriate (and is essentially just an easy way to do the above):</p>\n\n<pre><code>from enum import Enum\nclass Default(Enum):\n no_default = 0\n</code></pre>\n\n<p>Thanks to metaclass magic, <code>Default.no_default</code> is now an instance of a <code>Default</code>, which will only compare equal with itself (not <code>0</code>, by default, enums are pure).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T23:29:20.767", "Id": "26500", "ParentId": "26499", "Score": "6" } } ]
{ "AcceptedAnswerId": "26500", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T22:56:50.490", "Id": "26499", "Score": "6", "Tags": [ "python" ], "Title": "Optional argument for which None is a valid value" }
26499
<pre><code>def stopWatchSeconds(secondCnt) : """ counts second for secondCnt seconds """ # is there a better way to do this? startTime = time.clock() ellapsed = 0 for x in range(0, secondCnt, 1) : print "loop cycle time: %f, seconds cnt: %02d" % (ellapsed , x) ellapsed = 1 - (time.clock() - startTime) time.sleep(ellapsed) startTime = time.clock() </code></pre> <p>I'm reviewing some source code for a buddy of mine and came across this function. I am very new to Python so it is more of a learning experience for me. I see that he put in a comment about is there a better way to do this. I started thinking about it, and I know how I would do it in C#, but since python is so much more laxed it does seem like this function could be improved. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T06:54:17.250", "Id": "41142", "Score": "1", "body": "Could you give a little bit more info about the goal of this function? Is it for benchmarking, a timer, etc? Different goals might make different methods more appropriate. Also, time.clock() behaves differently on *nix systems vs Windows systems. What is the target platform?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T13:55:34.210", "Id": "41167", "Score": "0", "body": "Well the the program is to test a port by sending data for x amount of seconds on a Android device." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T00:04:42.677", "Id": "41261", "Score": "1", "body": "This seems like a reasonable approach to me (as a nitpick, elapsed should only have one 'l'). You might also be able to use the Python timeit module which has a default_timer that tracks wall clock time." } ]
[ { "body": "<p>I'm not sure this code does what you think it does, at least on a *nix OS. <a href=\"http://docs.python.org/2.7/library/time.html#time.clock\" rel=\"noreferrer\">According to the documentation</a>, <code>time.clock()</code> returns <em>processor time</em>, which basically means that any time spent in <code>time.sleep()</code> is not counted. However, on Windows, <code>time.clock()</code> returns the actual time since it was first called. </p>\n\n<p>A better way to determine the time since the function was first called is to use <code>time.time()</code>, which returns the number of seconds since the <em>epoch</em>. We can still use <code>time.clock()</code> to determine the process time if we are using a *nix OS. (If you are using Windows, you may want to upgrade to Python 3.3 which introduces the platform independent function <code>time.process_time()</code>. (There may be another way to do it if you are using 2.x, but I don't know what it is.)</p>\n\n<pre><code>#!/usr/bin/python\nimport time\n\ndef stopwatch(seconds):\n start = time.time()\n # time.time() returns the number of seconds since the unix epoch.\n # To find the time since the start of the function, we get the start\n # value, then subtract the start from all following values.\n time.clock() \n # When you first call time.clock(), it just starts measuring\n # process time. There is no point assigning it to a variable, or\n # subtracting the first value of time.clock() from anything.\n # Read the documentation for more details.\n elapsed = 0\n while elapsed &lt; seconds:\n elapsed = time.time() - start\n print \"loop cycle time: %f, seconds count: %02d\" % (time.clock() , elapsed) \n time.sleep(1) \n # You were sleeping in your original code, so I've stuck this in here...\n # You'll notice that the process time is almost nothing.\n # This is because we are spending most of the time sleeping,\n # which doesn't count as process time.\n # For funsies, try removing \"time.sleep()\", and see what happens.\n # It should still run for the correct number of seconds,\n # but it will run a lot more times, and the process time will\n # ultimately be a lot more. \n # On my machine, it ran the loop 2605326 times in 20 seconds.\n # Obviously it won't run it more than 20 times if you use time.sleep(1)\n\nstopwatch(20)\n</code></pre>\n\n<p>If you find the comments more confusing than helpful, here's a non-commented version...</p>\n\n<pre><code>#!/usr/bin/python\nimport time\n\ndef stopwatch(seconds):\n start = time.time()\n time.clock() \n elapsed = 0\n while elapsed &lt; seconds:\n elapsed = time.time() - start\n print \"loop cycle time: %f, seconds count: %02d\" % (time.clock() , elapsed) \n time.sleep(1) \n\nstopwatch(20)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-14T22:47:58.410", "Id": "298670", "Score": "0", "body": "Thanks for pointing out the \"processor time\" distinction! I was wondering why time.clock() was reporting sub-second times around a 15-second HTTP request." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:15:08.913", "Id": "26669", "ParentId": "26534", "Score": "9" } } ]
{ "AcceptedAnswerId": "26669", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-23T14:42:04.043", "Id": "26534", "Score": "6", "Tags": [ "python" ], "Title": "Is there a better way to count seconds in python" }
26534
<p>I've written this snippet to extract a review request status from review-board in python. It works well but i'm very new to python and i would like to know if i could write this any better.<br> Should i put <code>conn.close</code> in it's own try statement ?</p> <p>This script is supposed to run as part of a post-commit hook in mercurial. If the review-board server is not responding i still want to be able to commit without any issues. If the commit is non existent then an empty string is ok.</p> <pre><code>import httplib import json def getReviewStatus(reviewboardUrl, id): try: conn = httplib.HTTPConnection(reviewboardUrl, 80) headers = { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=UTF-8' } conn.request("GET", "/api/review-requests/%s/" % id, headers=headers) return json.loads(conn.getresponse().read())['review_request']['status'] except: return "" finally: conn.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:45:54.560", "Id": "41520", "Score": "1", "body": "is this a standalone script? if so I'd let it blow on errors, don't catch any exceptions (specially don't *silently* catch *all* exceptions)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:52:39.370", "Id": "41522", "Score": "0", "body": "i amended my question" } ]
[ { "body": "<p>Looks pretty good to me. Regarding <code>conn.close()</code>, definitely don't put this in its own <code>try</code> statement, because if there's a problem with the earlier code, the connection might not get closed. I know you're not using Python 3, but ss an alternative, you might consider using the <code>with</code> statement and let Python handle the closing for you. See <a href=\"http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects\" rel=\"nofollow\">http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects</a> (end of section) and <a href=\"http://docs.python.org/2/library/contextlib.html#contextlib.closing\" rel=\"nofollow\">http://docs.python.org/2/library/contextlib.html#contextlib.closing</a></p>\n\n<p>Your code might look like this:</p>\n\n<pre><code>import httplib\nimport json\nfrom contextlib import closing\n\ndef getReviewStatus(reviewboardUrl, id):\n try:\n with closing(httplib.HTTPConnection(reviewboardUrl, 80)) as conn:\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json; charset=UTF-8'\n }\n conn.request(\"GET\", \"/api/review-requests/%s/\" % id, headers=headers)\n return json.loads(conn.getresponse().read())['review_request']['status']\n except:\n return \"\"\n</code></pre>\n\n<p>I find it's good to get into the habit of using <code>with</code> to open resources so don't have to worry about forgetting to close the connection.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T17:35:01.893", "Id": "41548", "Score": "0", "body": "Wow, this is exactly what i had in mind ! Thanks a bunch !! i knew about `with` but i didn't knew about `from contextlib import closing`, absolutely brilliant !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T17:39:55.947", "Id": "41550", "Score": "1", "body": "Out of interest, what would happen with this code if the `requests` throws an exception and the implicit `close` call throws an exception as well ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T18:01:16.837", "Id": "41552", "Score": "0", "body": "That's a good question! This would be difficult to test. Maybe ask on Stack Overflow? I personally have never seen an exception thrown while trying to close a file/socket. Are you getting one, or just trying to code defensively?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T22:47:55.630", "Id": "41560", "Score": "0", "body": "just trying to be defensive :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T16:55:30.843", "Id": "26814", "ParentId": "26762", "Score": "1" } } ]
{ "AcceptedAnswerId": "26814", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T18:04:10.567", "Id": "26762", "Score": "2", "Tags": [ "python" ], "Title": "python httplib snippet" }
26762
<p>It's a (simple) guesser for game where you need to find words of a given length only using given letters. I'd like to know if there's a more pythonic way to do things here.</p> <pre><code>#!/usr/bin/env python3 import sys if len(sys.argv) &lt; 3: sys.exit("Usage: " + sys.argv[0] + " letters number_of_letters [dictionnaryfile]") letters = sys.argv[1].upper() wordsize = int(sys.argv[2]) dictionnary_name = "dict.txt" if len(sys.argv) &lt; 4 else sys.argv[3] try: wordlist = open(dictionnary_name).read().split('\n') except FileNotFoundError: sys.exit("Couldn't find dictionnary file \"" + dictionnary_name + "\"") good = [] for w in wordlist: if len(w) == wordsize: up = w.upper() ok = True for c in up: if not c in letters: ok = False break if ok: good.append(w) print("Found " + str(len(good)) + " results:") print(good) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T10:08:26.137", "Id": "41988", "Score": "1", "body": "checkout [argparse](http://docs.python.org/3.3/library/argparse.html). It's awesome! Also, it's worth avoiding making the wordlist upfront and instead iterating over the file object so the whole dictionary isn't read into memory, and is read from line by line instead." } ]
[ { "body": "<p>The following code shows I would have done what you asked in Python 2.7. Other readers will tell you the ways in which it is a) not Pythonic and b) wrong.</p>\n\n<ul>\n<li><p>Start with a module comment describing what the code is intended to do. (This is available to the code as <code>__doc__</code>.)</p></li>\n<li><p>Use the various Python string delimiters to avoid escaping.</p></li>\n<li><p>Name variables consistently.</p></li>\n<li><p>strip() text strings read from a text file.</p></li>\n<li><p>Make letters a set to reflect its usage.</p></li>\n<li><p>Create the list of matching words with a list comprehension.</p></li>\n</ul>\n\n<p>Here is the code.</p>\n\n<pre><code>\"\"\"\n Find all the words in a reference dictionary with a specified number of letters\n that contain all the letters in a specified list of letters.\n\n The number of letters and the list of letters must be specified on the command line.\n\n The reference dictionary may be specified on the command line. If is not then \n dict.txt is used.\n\n The matching of letters is case-insensitive. \n\"\"\"\nimport sys\n\nif len(sys.argv) &lt; 3:\n print &gt;&gt; sys.stderr, __doc__\n sys.exit('Usage: %s letters number_of_letters [dictionary_file]' % sys.argv[0])\n\nletters = set(sys.argv[1].upper())\nwordsize = int(sys.argv[2])\ndictname = 'dict.txt' if len(sys.argv) &lt;= 3 else sys.argv[3]\n\ntry:\n wordlist = [w.strip() for w in open(dictname).readlines()]\nexcept IOError:\n sys.exit('''Couldn't find dictionary file \"%s\"''' % dictname)\n\nmatches = [w for w in wordlist \n if len(w) == wordsize \n and all(c in letters for c in w.upper())]\n\nprint 'Found %d results:' % len(matches) \nprint matches\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T15:53:56.093", "Id": "41623", "Score": "0", "body": "BTW, any reason to remove the shebang?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T04:34:46.660", "Id": "41650", "Score": "0", "body": "I forgot to add it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T00:19:59.580", "Id": "26864", "ParentId": "26857", "Score": "8" } }, { "body": "<p>One thing others have missed is the style of opening files. Use the <code>with</code> statement to have it automatically closed once it's no longer needed.</p>\n\n<pre><code>try:\n with open(dictname) as f:\n wordlist = [w.strip() for w in f]\nexcept IOError as e:\n sys.exit('Error opening file \"{0}\", errno {1}'.format(e.filename, e.errno))\n</code></pre>\n\n<p>You can't assume it's because the file doesn't exist. Other errors result in an <code>IOError</code> as well. You'd need to check its <code>errno</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T09:37:43.380", "Id": "27187", "ParentId": "26857", "Score": "2" } } ]
{ "AcceptedAnswerId": "26864", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T20:54:36.020", "Id": "26857", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Finding words of a given length only using given letters" }
26857
<p>I am trying to learn how to animate with tkinter. The code below is an example I was able to build. It creates a small 5x5 map of cubes, then one of them randomly moves around the screen (preferably on the map, but it can wander off).</p> <p>Is this a good way to do it? Is there a more pythonic, or more efficient way of doing it?</p> <pre><code>from tkinter import * from time import sleep from random import randrange class alien(object): def __init__(self): self.root = Tk() self.canvas = Canvas(self.root, width=400, height=400) self.canvas.pack() self.map = [[1, 0, 0, 1, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [1, 0, 0, 1, 0]] self.x = 0 self.y = 0 for row in range(len(self.map)): for column in range(len(self.map[row])): color = "green" if self.map[row][column] == 1: color = "black" #print(50 * row + 50, 50 * column + 50) self.canvas.create_rectangle(50 * row , 50 * column , 50 * row + 50, 50 * column + 50, outline=color, fill=color) self.creature = self.canvas.create_rectangle(50 * self.x, 50 * self.y, 50 * self.x + 50, 50 * self.y + 50, outline="red", fill="red") self.canvas.pack(fill=BOTH, expand=1) self.root.after(0, self.animation) self.root.mainloop() def animation(self): while True: i = randrange(1, 5) print(i) if i == 1: y = -1 elif i == 2: y = 1 elif i == 3: x = -1 elif i == 4: x = 1 sleep(0.025) print(self.x, self.y) self.canvas.move(self.creature, self.x, self.y) self.canvas.update() alien() </code></pre>
[]
[ { "body": "<ul>\n<li>Whenever you do <code>range(len(self.map))</code> in Python, you are most probably doing something wrong. The pythonic way to do this is to use <code>enumerate</code>.</li>\n</ul>\n\n<p>If you also use the ternary operator, remove the useless '== 1', store magic numbers in a unique place and factorize the mathematical expressions, you can transform this :</p>\n\n<pre><code> for row in range(len(self.map)):\n for column in range(len(self.map[row])):\n color = \"green\"\n if self.map[row][column] == 1:\n color = \"black\" \n #print(50 * row + 50, 50 * column + 50)\n self.canvas.create_rectangle(50 * row , 50 * column , 50 * row + 50, 50 * column + 50,\n outline=color, fill=color) \n self.creature = self.canvas.create_rectangle(50 * self.x, 50 * self.y, 50 * self.x + 50, 50 * self.y + 50,\n outline=\"red\", fill=\"red\")\n</code></pre>\n\n<p>Into this</p>\n\n<pre><code> r = 50\n for i,row in enumerate(self.map):\n for j,cell in enumerate(row)):\n color = \"black\" if cell else \"green\"\n self.canvas.create_rectangle(r*i, r*j , r*(i+1), r*(j+1),\n outline=color, fill=color)\n self.creature = self.canvas.create_rectangle(r*self.x, r*self.y, r*(self.x+1), r*(self.y+1),\n outline=\"red\", fill=\"red\")\n</code></pre>\n\n<ul>\n<li><p>Does <code>map</code> need to be an object member or could it be a variable local to <code>__init__</code> ?</p></li>\n<li><p>Is <code>animation()</code> working properly or should it update <code>self.x</code> and <code>self.y</code> ?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T22:17:15.317", "Id": "41689", "Score": "0", "body": "What do you mean by your question about map? Is it does it need the self. designation? Then yes. Animation does work, it's messy but really it's a place holder." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T05:42:24.893", "Id": "41709", "Score": "0", "body": "If you are not using map outside the unit method, you could get rid of the self designation. As for animation, I guessed I misunderstood how it was supposed to work." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T21:14:11.730", "Id": "26899", "ParentId": "26885", "Score": "0" } } ]
{ "AcceptedAnswerId": "26893", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T04:47:23.233", "Id": "26885", "Score": "2", "Tags": [ "python", "optimization", "animation", "tkinter", "tk" ], "Title": "Animation with 5x5 map of cubes" }
26885
<p>The purpose is just to create a dictionary with a path name, along with the file's SHA-256 hash.</p> <p>I'm very new to Python, and have a feeling that there's a much better way to implement the following code. It works, I'd just like to clean it up a bit. fnamelst = [r'C:\file1.txt', r'C:\file2.txt']</p> <pre><code>[fname.replace('\\', '\\\\') for fname in fnamelst] diction = [{fname: hashlib.sha256(open(fname, 'rb').read()).digest()} for fname in fnamelst] for iter in range(0,len(fnamelst)): dic2 = {fnamelst[iter]: hashlib.sha256(open(fnamelst[iter], 'rb').read()).digest()} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T14:20:10.763", "Id": "41735", "Score": "1", "body": "Why are you replacing slashes??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T14:20:58.690", "Id": "41736", "Score": "1", "body": "Well, you've created the dictionary twice. What's the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T14:24:24.227", "Id": "41737", "Score": "2", "body": "Note that the `for` loop will overwrite `dic2` each time, instead of extending it." } ]
[ { "body": "<p>In python, <code>for iter in range(0,len(container)):</code> is pretty much always a bad pattern.</p>\n\n<p>Here, you can rewrite :</p>\n\n<pre><code>for f in fnamelst:\n dic2 = {f: hashlib.sha256(open(f, 'rb').read()).digest()}\n</code></pre>\n\n<p>As @tobias_k pointed out, this doesn't do much at the moment as <code>dict2</code> gets overriden.\nIn Python 2.7+ or 3, you can just use the <a href=\"http://www.python.org/dev/peps/pep-0274/\" rel=\"nofollow\">dict comprehension</a> directly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T14:30:47.510", "Id": "26934", "ParentId": "26931", "Score": "2" } }, { "body": "<p>In your code, you show two ways to create your dictionary, but both are somewhat flawed:</p>\n\n<ul>\n<li><code>diction</code> will be a list of dictionaries, each holding just one entry</li>\n<li><code>dic2</code> will get overwritten in each iteration of the loop, and will finally hold only one dictionary, again with only one element.</li>\n</ul>\n\n<p>Instead, try this:</p>\n\n<pre><code>diction = dict([ (fname, hashlib.sha256(open(fname, 'rb').read()).digest())\n for fname in fnamelst ])\n</code></pre>\n\n<p>Or shorter, for Python 2.7 or later:</p>\n\n<pre><code>diction = { fname: hashlib.sha256(open(fname, 'rb').read()).digest()\n for fname in fnamelst }\n</code></pre>\n\n<p>The first one uses a list comprehension to create a list of key-value tuples, and then uses the <code>dict</code> function to create a single dictionary from that list. The second one does the same, using a dict comprehension.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T14:38:12.107", "Id": "26935", "ParentId": "26931", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T14:18:40.437", "Id": "26931", "Score": "1", "Tags": [ "python", "hash-map" ], "Title": "Creating a dictionary with a path name and SHA-256 hash" }
26931
<p>I'm taking a text file that looks like this:</p> <blockquote> <pre><code>77, 66, 80, 81 40, 5, 35, -1 51, 58, 62, 34 0, -1, 21, 18 61, 69, 58, 49 81, 82, 90, 76 44, 51, 60, -1 64, 63, 60, 66 -1, 38, 41, 50 69, 80, 72, 75 </code></pre> </blockquote> <p>and I'm counting which numbers fall in a certain bracket:</p> <pre><code>f = open("//path to file", "r") text = f.read() split = text.split() greater70=0 sixtys=0 fiftys=0 fortys=0 nomarks=0 for word in split: temp = word.replace(',', '') number = int(temp) if number &gt; 70: greater70+=1 if number &gt;= 60 and number &lt;= 69: sixtys+=1 if number &gt;= 50 and number &lt;= 59: fiftys+=1 if number &gt;= 40 and number &lt;= 49: fortys+=1 if number == -1: nomarks+=1 print greater70 print sixtys print fiftys print fortys print nomarks </code></pre> <p>Have I done it in an efficient way sensible way or do experienced Python users think it looks a little convoluted?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T09:32:47.040", "Id": "42109", "Score": "2", "body": "Is 70 meant to be ignored or is that a mistake?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-24T06:18:46.120", "Id": "278206", "Score": "0", "body": "I'd be tempted to divide by 10 and use counter." } ]
[ { "body": "<p>Looks good, but there are a few things I've noticed that could be better:</p>\n\n<ul>\n<li>You should use the <code>with</code> statement when working with files. This ensures that the file will be closed properly in any case.</li>\n<li><p>I would split the input string on <code>','</code> instead of replacing the comma with a space. This way, something like <code>'-7,67,34,80'</code> will be handled correctly. (It's a bit tricky because you want to split on newlines too, though. I did it using a <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehension</a>.)</p>\n\n<p><code>int()</code> will ignore any whitespace before or after the number, so <code>int(' 50')</code> works just fine.</p></li>\n<li>You can write those conditions as <code>60 &lt;= number &lt;= 69</code>.</li>\n<li>Since the numbers can only fall into one of the five categories, it's clearer (and more efficient) to use <code>elif</code> instead of <code>if</code>.</li>\n<li>Assignments with <code>=</code> or <code>+=</code> should have spaces around them in Python. (See <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> for a Python style guide.)</li>\n</ul>\n\n<p>This is how the changes would look:</p>\n\n<pre><code>with open(\"//path to file\", \"r\") as f:\n split = [word for line in f for word in line.split(',')]\n\ngreater70 = 0\nsixties = 0\nfifties = 0\nforties = 0\nnomarks = 0\n\nfor word in split:\n number = int(word)\n if number &gt; 70:\n greater70 += 1\n elif 60 &lt;= number &lt;= 69:\n sixties += 1 \n elif 50 &lt;= number &lt;= 59:\n fifties += 1\n elif 40 &lt;= number &lt;= 49:\n forties += 1 \n elif number == -1:\n nomarks += 1 \n\nprint greater70 \nprint sixties\nprint fifties\nprint forties\nprint nomarks\n</code></pre>\n\n<p>You might also want to think about how to avoid the repetition of code when you're calculating and printing the 40s, 50s and 60s (which, by the way, are spelt <code>forties, fifties, sixties</code>).</p>\n\n<p>I also noticed that 70 falls into none of the categories, is that the way it's supposed to be?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T02:17:45.307", "Id": "26959", "ParentId": "26958", "Score": "1" } }, { "body": "<p>Few points i have noticed in your code, that i hope, will help you.</p>\n\n<p>1) Try changing your conditions like this: (no need to check two conditions)</p>\n\n<pre><code>if number &gt; 69:\n greater70+=1\nelif number &gt; 59:\n sixtys+=1 \nelif number &gt; 49:\n fiftys+=1\nelif number &gt; 40:\n fortys+=1 \nelif number == -1:\n nomarks+=1 \n</code></pre>\n\n<p>2) Always take care of closing file handler, or better to use <code>with</code> statements as other expert suggested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T06:09:35.167", "Id": "26969", "ParentId": "26958", "Score": "0" } }, { "body": "<p>Notes:</p>\n\n<ul>\n<li><p>Creating so many variables is a warning sign that they should be grouped somehow (an object, a dictionary, ...). I'd use a dictionary here.</p></li>\n<li><p>Consider learning some <a href=\"http://docs.python.org/2/howto/functional.html\" rel=\"nofollow\">functional programming</a> (as opposed to imperative programming) to apply it when it improves the code (IMO: most of the time). Here it means basically using <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\">collections.counter</a> and <a href=\"http://www.python.org/dev/peps/pep-0289/\" rel=\"nofollow\">generator expressions</a>.</p></li>\n<li><p>Don't read whole files, read them line by line: <code>for line in file_descriptor</code>.</p></li>\n<li><p>There are programmatic ways of detecting intervals of numbers (simple loop, binary search). However, since you have here only 5 intervals it's probably fine just to write a conditional as you did. If you had, let's say 20 intervals, a conditional branch would be a very sad thing to see.</p></li>\n<li><p>Conditional branches are more clear when you use non-overlapping conditions with <code>if</code>/<code>elif</code>/<code>else</code> (effectively working as expressions instead of statements).</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>from collections import Counter\n\ndef get_interval(x):\n if x &gt; 70:\n return \"greater70\"\n elif 60 &lt;= x &lt; 70:\n return \"sixtys\" \n elif x &gt;= 50:\n return \"fiftys\"\n elif x &gt;= 40:\n return \"fortys\" \n elif x == -1:\n return \"nomarks\" \n\nwith open(\"inputfile.txt\") as file:\n counter = Counter(get_interval(int(n)) for line in file for n in line.split(\",\"))\n# Counter({'sixtys': 10, 'greater70': 10, None: 7, ..., 'fortys': 4})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-23T23:42:24.983", "Id": "43169", "Score": "0", "body": "Aren't those `for` clauses the wrong way around? I.e. shouldn't it be `Counter(get_interval(int(n)) for n in line.split(\",\") for line in file)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-24T08:17:37.003", "Id": "43187", "Score": "0", "body": "@user9876: no, I am pretty sure it's correct (the output is real, I run that code). A list-comprehension is written in the same order you'd write a normal for-loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T22:04:22.630", "Id": "27010", "ParentId": "26958", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T01:04:11.230", "Id": "26958", "Score": "6", "Tags": [ "python", "interval" ], "Title": "Counting which numbers fall in a certain bracket" }
26958
<p>I wrote this code to solve a problem from a John Vuttag book:</p> <blockquote> <p>Ask the user to input 10 integers, and then print the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.</p> </blockquote> <p>Can my code be optimized or made more concise? Any tips or errors found?</p> <pre><code>{ a = int (raw_input("enter num: ")) b = int (raw_input("enter num: ")) c = int (raw_input("enter num: ")) d = int (raw_input("enter num: ")) e = int (raw_input("enter num: ")) f = int (raw_input("enter num: ")) g = int (raw_input("enter num: ")) h = int (raw_input("enter num: ")) i = int (raw_input("enter num: ")) j = int (raw_input("enter num: ")) num_List = {a,b,c,d,e,f,g,h,i,j } mylist=[] ## Use for loop to search for odd numbers for i in num_List: if i&amp;1 : mylist.insert(0,i) pass elif i&amp;1 is not True: continue if not mylist: print 'no odd integers were entered' else: print max (mylist) } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T19:04:50.700", "Id": "41836", "Score": "0", "body": "Here's my response to a suspiciously similar question: http://codereview.stackexchange.com/questions/26187/i-need-my-code-to-be-more-consise-and-i-dont-know-what-is-wrong-with-it-its/26191#26191" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T19:12:33.970", "Id": "41838", "Score": "0", "body": "this question is a \"finger exercise\" in John Vuttag book, introduction to programming. Sorry if it was posted before" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T20:09:49.907", "Id": "41842", "Score": "0", "body": "Oh no problem, I was just trying to help :)" } ]
[ { "body": "<p>Your main loop can just be:</p>\n\n<pre><code>for i in num_list:\n if i &amp; 1:\n mylist.append(i)\n</code></pre>\n\n<p>There is no need for the else at all since you don't do anything if <code>i</code> is not odd.</p>\n\n<p>Also, there is no need at all for two lists. Just one is enough:</p>\n\n<pre><code>NUM_ENTRIES = 10\n\nfor dummy in range(NUM_ENTRIES):\n i = int(raw_input(\"enter num: \"))\n if i &amp; 1:\n mylist.append(i)\n</code></pre>\n\n<p>Then the rest of the program is as you wrote it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T18:56:23.207", "Id": "41833", "Score": "0", "body": "Thanks! it looks cleaner. I am working on using one raw_input instead of 10" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T19:04:09.980", "Id": "41835", "Score": "0", "body": "No problem! I am no Python specialist though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T20:03:10.350", "Id": "41839", "Score": "0", "body": "@fge one small thing, wouldn't a `for j in range(10)` be better than incrementing in a `while` loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T21:08:00.250", "Id": "41853", "Score": "0", "body": "tijko: yup... I didn't know of `range` :p" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T18:48:14.310", "Id": "26993", "ParentId": "26992", "Score": "4" } }, { "body": "<p>One other minor change you could make, would be to just loop over a range how many times you want to prompt the user for data:</p>\n\n<pre><code>mylist = list()\nfor _ in range(10):\n while True:\n try:\n i = int(raw_input(\"enter num: \"))\n if i &amp; 1:\n mylist.append(i)\n break\n except ValueError:\n print \"Enter only numbers!\"\n</code></pre>\n\n<p>No need to create an extra variable and increment it here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-18T00:56:32.527", "Id": "66257", "Score": "1", "body": "Since you don't care about the value of `j`, it's customary to write `for _ in range(10)` instead." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T20:09:18.560", "Id": "26997", "ParentId": "26992", "Score": "4" } }, { "body": "<p>I'd write:</p>\n\n<pre><code>numbers = [int(raw_input(\"enter num: \")) for _ in range(10)]\nodd_numbers = [n for n in numbers if n % 2 == 1]\nmessage = (str(max(odd_numbers)) if odd_numbers else \"no odd integers were entered\")\nprint(message)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-05T14:00:43.563", "Id": "27035", "ParentId": "26992", "Score": "1" } }, { "body": "<p>This is a solution that doesn't use lists, and only goes through the input once.</p>\n\n<pre><code>maxOdd = None\n\nfor _ in range(10):\n num = int (raw_input(\"enter num: \"))\n if num &amp; 1:\n if maxOdd is None or maxOdd &lt; num:\n maxOdd = num\n\nif maxOdd:\n print \"The max odd number is\", maxOdd \nelse:\n print \"There were no odd numbers entered\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T23:55:39.783", "Id": "44628", "ParentId": "26992", "Score": "5" } } ]
{ "AcceptedAnswerId": "26993", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T18:35:39.707", "Id": "26992", "Score": "4", "Tags": [ "python", "beginner" ], "Title": "Print the largest odd number entered" }
26992
<p>This reads in data from a .csv file and generates an .xml file with respect to the .csv data. Can you spot any parts where re-factoring can make this code more efficient?</p> <pre><code>import csv from xml.etree.ElementTree import Element, SubElement, Comment, tostring from xml.etree.ElementTree import ElementTree import xml.etree.ElementTree as etree def main(): reader = read_csv() generate_xml(reader) def read_csv(): with open ('1250_12.csv', 'r') as data: return list(csv.reader(data)) def generate_xml(reader): root = Element('Solution') root.set('version','1.0') tree = ElementTree(root) head = SubElement(root, 'DrillHoles') head.set('total_holes', '238') description = SubElement(head,'description') current_group = None i = 0 for row in reader: if i &gt; 0: x1,y1,z1,x2,y2,z2,cost = row if current_group is None or i != current_group.text: current_group = SubElement(description, 'hole',{'hole_id':"%s"%i}) collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}), toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))}) cost = SubElement(current_group, 'cost',{'':cost}) i+=1 def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i indent(root) tree.write(open('holes1.xml','w')) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T13:29:56.623", "Id": "42008", "Score": "1", "body": "one note : you have a `for elem in elem` that reassigns elem to the last element of elem, and then you access elem again. Not sure if that's what you want to do or not, but anyway that's confusing." } ]
[ { "body": "<p>Don't use something like <code>for elem in elem</code> at some point with larger for loops you will miss that elem is different variable before and in/after the for loop:</p>\n\n<pre><code>for subelem in elem:\n indent(subelem, level+1)\n\nif not subelem.tail or not elem.tail.strip():\n subelem.tail = i\n</code></pre>\n\n<p>Since indent(subelem...) already sets the tail, you probably do not need to do that again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T04:30:52.473", "Id": "27290", "ParentId": "27037", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-05T14:35:37.980", "Id": "27037", "Score": "3", "Tags": [ "python", "xml", "csv" ], "Title": "Generating .xml files based on .csv files" }
27037
<p>I am writing web application using flask framework + mongodb. I have an issue, should I use classes for my mongo entities or just use dictionaries for them.</p> <pre><code>class School: def __init__(self, num, addr, s_type): self.num = num self.addr = addr self.s_type = s_type </code></pre> <p>or just create dictionary for any entity like:</p> <pre><code>school = { "number" : request['number'] , "address": request['address'], "type" : request['type'] } </code></pre>
[]
[ { "body": "<p>I'm not familiar with that framework, but if there is more than one school and you are going to use Python to access those values (such as the school's address), I'd use a class. Think of it this way: Classes are usually meant to be instantiated, or at least to be a group of functions for a specific purpose.</p>\n\n<p>Instead of creating a dict for each school you simply instantiate the class:</p>\n\n<pre><code>MIT=School(1,'Cambridge','university')\nHarvard=School(2,'Cambridge','university')\n&gt;&gt;&gt; MIT.address\n'Cambridge'\n&gt;&gt;&gt; Harvard.s_type\n'university'\n</code></pre>\n\n<p>Or whatever pattern you are using.</p>\n\n<p>This way you can also add functions to it:</p>\n\n<pre><code>class School:\n def __init__(self, name, num, addr, s_type):\n self.num = num\n self.name = name\n self.addr = addr\n self.s_type = s_type\n def describe(self):\n print \"%s is a %s located at %s.\" % (self.name, self.s_type, self.address)\n def request(self,arg):\n request[arg] # I'm not sure if that's what you want, I copied it from the dict you had there\n\n&gt;&gt;&gt; MIT.describe()\nMIT is a university located at Cambridge.\n&gt;&gt;&gt; MIT.request('name')\n# Whatever that thing does\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T21:20:55.610", "Id": "42055", "Score": "1", "body": "I understand your point. Also I can perform some functions like `def asDictionary():` or `def save():` to save it in mongo or than write function for saving in SQL database. Thank you :D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T21:08:03.797", "Id": "27116", "ParentId": "27105", "Score": "2" } } ]
{ "AcceptedAnswerId": "27116", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T18:09:24.143", "Id": "27105", "Score": "2", "Tags": [ "python", "mongodb", "flask" ], "Title": "Python flask web app, simplification" }
27105
<p>I am building a 2d dictionary with an altered list at the end Afterwords I want to find the min of each list. Is there a better way to do it? Better being faster or at least less of an eyesore.</p> <pre><code>#dummy function, will be replaced later so don't worry about it. def alter(x, y, z,): a = list(x) for i, val in enumerate(x): a[i] = val + y + z return a masterStats = {} askStats = [0, 1, 2] for numberServed in range(3): masterStats[numberServed] = {} for timeToServe in range(3): masterStats[numberServed][timeToServe] = alter(askStats, numberServed, timeToServe) for numberServed in masterStats.keys(): for timeToServe in masterStats[numberServed].keys(): print(min(masterStats[numberServed][timeToServe])) for numberServed in masterStats.keys(): print(numberServed) for timeToServe in masterStats[numberServed].keys(): print(" " + str(timeToServe)) print(" " + str(masterStats[numberServed][timeToServe])) </code></pre>
[]
[ { "body": "<p>Python's variable names are conventionally named lowercase_width_underscores.</p>\n\n<p>Loop using .items() not .keys() if you will need the values, so your final loop can be:</p>\n\n<pre><code>for numberServed, numberServedStats in masterStats.items():\n print(numberServed)\n for timeToServe, timeToServeStats in numberServedStats,items():\n print(\" \" + str(timeToServe))\n print(\" \" + str(timeToServeStats))\n</code></pre>\n\n<p>The whole thing can be made more efficient by using numpy:</p>\n\n<pre><code>askStats = numpy.array([0, 1, 2])\n\nx = askStats[None,None,:] # put askStats in the third dimension\ny = numpy.arange(3)[:, None, None] # put number served in the first dimension\nz = numpy.arange(3)[None, :, None] # put time to serve in the second dimension\n\nstats = x + y + z # same as in alter\n</code></pre>\n\n<p>We create a new array by adding together three existing arrays. The <code>[:,None, None]</code> parts control how they are added. Essentially, the colon indicates the column the data will be spread across. The None indicates where the data will be duplicated. So <code>numpy.arange(3)[:,None]</code> gets treated like</p>\n\n<pre><code>[ \n [0, 0, 0],\n [1, 1, 1],\n [2, 2, 2]\n]\n</code></pre>\n\n<p>Whereas <code>numpy.arange(3)[None, :]</code> gets treated like</p>\n\n<pre><code>[\n [0, 1, 2],\n [0, 1, 2],\n [0, 1, 2]\n]\n</code></pre>\n\n<p>This lets us do the complete loop and adjust function in just that one expression.</p>\n\n<pre><code>for line in stats.min(axis=2).flatten():\n print(line)\n</code></pre>\n\n<p>The min method reduces the 3 dimensional array to 2d array by minimizing along dimension 2. Flatten() converts that 2d array into one long one dimensional array.</p>\n\n<pre><code>for row_index, row in enumerate(stats):\n print(row_index)\n for col_index, col in enumerate(row):\n print(\" \", col_index)\n print(\" \", col)\n</code></pre>\n\n<p>It probably won't help much here, but for bigger cases using numpy will be more efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T00:09:39.923", "Id": "42071", "Score": "0", "body": "You lost me on that second part, can you explain a bit of what you're doing with numpy and flatten?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T00:24:32.783", "Id": "42075", "Score": "0", "body": "@EasilyBaffled, I've added some explanation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T01:12:33.487", "Id": "42084", "Score": "0", "body": "So to alter it to accept larger data sets, I replace 3 with x in numpy.arange(x) but how do I alter the [None,:,None] to take any amount?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T01:20:09.057", "Id": "42085", "Score": "0", "body": "And how is the alter function run in it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T03:43:34.543", "Id": "42089", "Score": "0", "body": "@EasilyBaffled, edited to hopefully clarify things a bit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T03:43:53.317", "Id": "42090", "Score": "0", "body": "@EasilyBaffled, alter function isn't run, its logic is replaced, (edit should make this a bit clearer)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T03:44:36.240", "Id": "42091", "Score": "0", "body": "@EasilyBaffled, you don't need to change the `[None,:,None]`, that just means to put the array into the second dimension. As long as you still want to do that you don't need to change it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T16:15:22.007", "Id": "42188", "Score": "0", "body": "The edits are helping a lot thanks, but just one more question where in this, would I put the alter function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T17:31:23.567", "Id": "42189", "Score": "0", "body": "@EasilyBaffled, the get the full advantage, you need to rewrite the alter function to use numpy. The `stats = x + y + z` does the same thing your alter function does, but faster. Your real function is more complicated I guess, but without knowing more I can't really provide much hints as to how." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T01:35:42.543", "Id": "42199", "Score": "0", "body": "The function I'm using runs x*y times and uses all of the variables from list z along with a lot of randomization to produce a new number so sorta like for i in range(x*y): z[i] = (askStats[0] + randomInt(askStats[1], askStats[2]))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T02:52:44.293", "Id": "42202", "Score": "0", "body": "See http://docs.scipy.org/doc/numpy/reference/routines.random.html, for the random functions that numpy supports. I'm not sure what range your example is suppose to produce but I think you'll find one of the options there to be what you want." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T23:28:24.307", "Id": "27124", "ParentId": "27120", "Score": "1" } }, { "body": "<p><code>alter</code> is equivalent to a list comprehension:</p>\n\n<pre><code>def alter(x, y, z):\n return [val + y + z for val in x]\n</code></pre>\n\n<p><code>collections.defaultdict(dict)</code> is a convenient 2-level dictionary. You could also make use of <code>itertools.product</code> for 2D looping:</p>\n\n<pre><code>masterStats = collections.defaultdict(dict)\naskStats = [0, 1, 2]\nfor numberServed, timeToServe in itertools.product(range(3), range(3)):\n masterStats[numberServed][timeToServe] = alter(askStats, numberServed, timeToServe)\n</code></pre>\n\n<p>Iterate over <code>values()</code>:</p>\n\n<pre><code>for subdict in masterStats.values():\n for lst in subdict.values():\n print(min(lst))\n</code></pre>\n\n<p>Iterate over <code>items()</code>, like Winston already mentioned:</p>\n\n<pre><code>for numberServed, subdict in masterStats.items():\n print(numberServed)\n for timeToServe, lst in subdict.items():\n print(\" \" + str(timeToServe))\n print(\" \" + str(lst))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T06:13:24.373", "Id": "27131", "ParentId": "27120", "Score": "0" } } ]
{ "AcceptedAnswerId": "27124", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T23:04:09.643", "Id": "27120", "Score": "1", "Tags": [ "python", "hash-map" ], "Title": "Making a 2D dict readable" }
27120
<p>I think I'd like to learn Clojure eventually, but at the moment am having fun with <a href="http://docs.hylang.org/en/latest/" rel="nofollow">Hy</a>, a "dialect of Lisp that's embedded in Python." </p> <pre><code>(import socket) (defn echo-upper (sock) (.send c (.upper (.recv c 10000))) (.close c) ) (def s socket.socket) (.bind s (tuple ["" 8000])) (.listen s 5) (while True (echo-upper (.__getitem__ (s.accept) 0)) ) </code></pre> <p>Python generated from ABS with <a href="https://pypi.python.org/pypi/astor/0.2.1" rel="nofollow">astor</a>:</p> <pre><code>import socket def echo_upper(sock): c.send(c.recv(10000).upper()) return c.close() s = socket.socket s.bind(tuple([u'', 8000])) s.listen(5) while True: echo_upper(s.accept().__getitem__(0)) </code></pre> <p>I'm not worried about not dealing with connections properly etc, I'd just like feedback on using lispy syntax. I'm tempted to do things like <code>((getattr s "bind") (tuple ["" 8000]))</code> because it looks more like simple Scheme, the only lisp I have a little experience with.</p> <p>Any thoughts on syntax and style? Any guidelines for dealing with Python APIs in a lispy way, something that apparently happens a lot in Clojure with Java?</p>
[]
[ { "body": "<p>algernon in freenode/#hy says:</p>\n\n<blockquote>\n <p>Looks lispy enough to me, except for the <code>__getitem__</code> line.</p>\n \n <p>...and the closing braces.</p>\n</blockquote>\n\n<p>I'm think this is fix for the braces and using <code>get</code> instead of <code>__getitem__</code>:</p>\n\n<pre><code>(import socket)\n\n(defn echo-upper (sock)\n (.send c (.upper (.recv c 10000)))\n (.close c))\n\n(def s socket.socket)\n(.bind s (tuple [\"\" 8000]))\n(.listen s 5)\n(while True\n (echo-upper (get (s.accept) 0)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T19:41:50.500", "Id": "27180", "ParentId": "27179", "Score": "0" } }, { "body": "<p>As suggested by the Hy docs, I'm trying the threading macro here:</p>\n\n<pre><code>(.send c (.upper (.recv c 10000)))\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>(-&gt; (.recv c 10000) (.upper) (c.send))\n</code></pre>\n\n<p>I'm not sure I like it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T19:55:54.813", "Id": "27181", "ParentId": "27179", "Score": "0" } }, { "body": "<p>I wouldn't use the threading macro here. That's most useful when you want to see the data flow, but you're using <code>c</code> two times in this expression, there's no clear flow that <code>-&gt;</code> could make easier to untangle. It makes it more complicated in this case...</p>\n\n<p>If you'd decouple the receive and the send part, then it'd be different, but then the expression becomes so simple you don't even need the macro:</p>\n\n<pre><code>(let [[received (.recv c 10000)]]\n (.send c (.upper received)))\n</code></pre>\n\n<p>With the threading macro, the inner part would become <code>(-&gt; received (.upper) (.send c))</code> - doesn't make it much clearer, either.</p>\n\n<p>What you could do, however, is abstract away the accept -> do something -> close thing into a macro:</p>\n\n<pre><code>(defmacro with-accepted-connection [listening-socket &amp; rest]\n (quasiquote (let [[*sock* (get (.accept (unquote listening-socket)) 0)]]\n (unquote-splice rest)\n (.close *sock*))))\n\n(with-accepted-connection s (.send *sock* (upper (.recv *sock* 10000))))\n</code></pre>\n\n<p>The above may or may not work out of the box, I just conjured it up. But something similar may make the code lispier and easier to understand the intent later.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T23:09:33.750", "Id": "27378", "ParentId": "27179", "Score": "1" } }, { "body": "<p>So, yeah, the threading macro is a great way of writing it - using it is a borrowed bit of syntax from Clojure :)</p>\n\n<p>FYI, using a tupple in Hy is:</p>\n\n<pre><code>(, 1 2 3)\n; (1, 2, 3)\n</code></pre>\n\n<p>If you'd like, I can help you through another version of this in a more \"Hythonic\" way (like Algernon's!)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T02:24:07.703", "Id": "27384", "ParentId": "27179", "Score": "1" } } ]
{ "AcceptedAnswerId": "27378", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T19:25:32.130", "Id": "27179", "Score": "1", "Tags": [ "python", "lisp", "socket", "hy" ], "Title": "Echoing back input in uppercase over a socket with Hy, a Python Lisp dialect" }
27179
<p>I am trying to start learning Python using <a href="http://learnpythonthehardway.org" rel="nofollow"><em>Learn Python the Hard Way</em></a>. I wrote my first game that works as far as tested. It was done as an exercise for <a href="http://learnpythonthehardway.org/book/ex45.html" rel="nofollow">this</a>.</p> <p>Please give me some constructive criticism on this program on sections and areas where I can improve. I realise that my object-oriented programming specifically, and my programming in general, still needs lots of work:</p> <pre><code>""" MathChallenge: A game randomly creating and testing math sums with 4 operators: addition, subtraction, multiplication and division. Difficulty levels are incremented after each correct answer. No more than 3 incorrect answers are accepted. """ from random import randint, choice class Math(object): """Class to generate different math sums based on operator and difficulty levels""" def __init__(self): """To initialise difficulty on each run""" self.difficulty = 1 def addition(self, a, b): """To return 'addition', '+' sign , and answer of operation""" return ('addition', '+', a+b) def subtraction(self, a, b): """To return 'subtraction', '-' sign , and answer of operation""" return ('subtraction', '-', a-b) def multiplication(self, a, b): """To return 'multiplication', '*' sign , and answer of operation""" return ('multiplication', '*', a*b) def division(self, a, b): """To return 'division', '/' sign , and answer of operation""" return ('division', '/', a/b) def mathsum(self, difficulty): """Function that generates random operator and math sum checks against your answer""" print "Difficulty level %d." % difficulty #let's initialize some random digits for the sum a = randint(1,5)*difficulty b = randint(1,5)*difficulty #Now let's choose a random operator op = choice(self.operator)(a, b) print "Now lets do a %s calculation and see how clever you are." % op[0] print "So what is %d %s %d?" % (a, op[1], b) correct = False incorrect_count = 0 #No more than 3 incorrect answers while not correct and incorrect_count&lt;3: ans = int(raw_input("&gt;")) if ans == op[2]: correct = True print "Correct!" self.difficulty += 1 self.mathsum(self.difficulty) #Restart the function with higher difficulty else: incorrect_count += 1 if incorrect_count == 3: print "That's 3 incorrect answers. The end." else: print "That's not right. Try again." class Engine(Math): """Game engine""" def __init__(self): """To initialise certain variables and function-lists""" #Initialise list of math functions inherited to randomly call from list self.operator = [ self.addition, self.subtraction, self.multiplication, self.division ] #Initialise difficulty level self.difficulty = 1 print "Welcome to the MathChallenge game. I hope you enjoy!" def play(self): """To start game""" #start game self.mathsum(self.difficulty) #print returned difficulty level achieved print "Difficulty level achieved: ", self.difficulty # Start game game = Engine() game.play() </code></pre>
[]
[ { "body": "<p>Try to conform to the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8 style guide</a>, there is a pep8 package in GNU / Linux repos for easy local checking, or try the <a href=\"http://pep8online.com/\" rel=\"nofollow\">online checker</a></p>\n\n<pre><code>Check results\n=============\n\nE501:3:80:line too long (116 &gt; 79 characters)\nE302:10:1:expected 2 blank lines, found 1\nE501:11:80:line too long (87 &gt; 79 characters)\nW291:21:33:trailing whitespace\nW291:25:36:trailing whitespace\nW291:30:71:trailing whitespace\nE501:34:80:line too long (93 &gt; 79 characters)\nE231:39:22:missing whitespace after ','\nE231:40:22:missing whitespace after ','\nE501:45:80:line too long (80 &gt; 79 characters)\nE262:49:53:inline comment should start with '# '\nE501:49:80:line too long (85 &gt; 79 characters)\nE225:50:46:missing whitespace around operator\nW291:53:29:trailing whitespace\nE262:57:53:inline comment should start with '# '\nE501:57:80:line too long (96 &gt; 79 characters)\nE701:61:40:multiple statements on one line (colon)\nE501:61:80:line too long (86 &gt; 79 characters)\nE701:62:21:multiple statements on one line (colon)\nE303:66:1:too many blank lines (3)\nW291:72:80:trailing whitespace\nE123:78:13:closing bracket does not match indentation of opening bracket's line\nW291:95:13:trailing whitespace\nW292:97:12:no newline at end of file\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T13:42:14.640", "Id": "27305", "ParentId": "27203", "Score": "1" } } ]
{ "AcceptedAnswerId": "27210", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T19:13:56.720", "Id": "27203", "Score": "8", "Tags": [ "python", "game", "quiz" ], "Title": "\"MathChallenge\" game for sums with 4 operators" }
27203
<p>I'm going to be working on a much larger version of this program and I just wanted to see if there was anything I should change in my style of coding before I made anything larger.</p> <p>If it wasn't obvious, this code goes through each comic on <a href="http://asofterworld.com/" rel="nofollow">A Softer World</a> and downloads each comic.</p> <p>Oh and with larger projects, should I try and fit my <code>main()</code> function into a class or is having a large <code>main()</code> function normal with programs?</p> <pre><code>from BeautifulSoup import BeautifulSoup as bs from urllib import urlretrieve from urllib2 import urlopen from os import path, mkdir from threading import Thread from Queue import Queue class Worker(Thread): def __init__(self, queue): self.queue = queue self.url = 'http://asofterworld.com/index.php?id=' Thread.__init__(self) def run(self): while 'running': number = self.queue.get() soup = bs(urlopen(self.url + number)) match = soup.find('p', {'id' : 'thecomic'}).find('img') filename = match['src'].split('/')[-1] urlretrieve(match['src'], 'Comic/' + filename) self.queue.task_done() def main(): queue = Queue() if not path.isdir('Comic'): mkdir('Comic') for number in xrange(1, 977): queue.put(str(number)) for threads in xrange(20): thread = Worker(queue) thread.setDaemon(True) thread.start() queue.join() main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-10T06:27:56.390", "Id": "42249", "Score": "0", "body": "Can you tell us something about the much larger version, to give more context to this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-10T06:38:16.717", "Id": "42250", "Score": "0", "body": "I'm hoping to have it go through multiple sites and follow links from there to download random images. Like a web crawler, but instead of indexing things, it will just randomly download images it finds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T07:56:18.083", "Id": "42396", "Score": "0", "body": "One thing that can be improved is the title of your question. Since all questions here ask for code review, instead try describing what your code does. I've changed it for you, but feel free to improve it further. (We also use proper English here, so please do capitalize correctly: `i-->I`)" } ]
[ { "body": "<ul>\n<li><p>The observation made by @l0b0 regarding main is correct. But Ionly makes sense when the module can be imported without executing main. For that use the following pattern:</p>\n\n<pre><code>def main():\n # your actual 'standalone' invocation steps\n\nif __name__ == '__main__':\n main()\n</code></pre></li>\n<li><p>importing BeautifulSoup seems to imply you are still using version 3, which has been replaced with version 4 over a year ago and only receives bugfixes. You should switch to <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow\">bs4</a> before expanding the program.</p></li>\n<li><p>you should put the actual url retrieval code in separate class. At some point (for this or other similar sites), the calls to urllib should be done with mechanize (e.g. keeping login state) or even selenium (if you need to have working javascript support to get to your target on your site).</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T04:11:05.907", "Id": "27288", "ParentId": "27217", "Score": "1" } } ]
{ "AcceptedAnswerId": "27239", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-10T04:15:11.483", "Id": "27217", "Score": "2", "Tags": [ "python", "multithreading" ], "Title": "Criticize my threaded image downloader" }
27217
<p>In my current project, I am working with a lot of JSON objects that contain arrays, er.. <code>lists</code> so I setup a decorator for convienece when the list is one item or multiple. Even though this is convienent in the current project, is it reusable code?</p> <pre><code>def collapse(function): @functools.wraps(function) def func(*args, **kwargs): call = function(*args, **kwargs) if isinstance(call, (list, tuple)) and (len(call) == 1): return call[0] return call return func @collapse def get_results(query, wrapper=None): # get json object. result = result.json() # using the requests library. if wrapper: return result[wrapper] return result </code></pre> <p>So, <code>get_results()</code> has the potential of returning either a <code>list</code> or a <code>dict</code>. In most cases, the code knows when what type is returned, so using the <code>@collapse</code> decorator changes <code>[result_dict]</code> to just <code>result_dict</code></p> <p>Is this a good practice, or should I write a decorator that takes a <code>limit</code> parameter</p> <pre><code>@limit(1) # def limit(items=None): ... return data[0:items] if items else data def get_results(query, wrapper=None): </code></pre> <p>Just wrote out the limit decorator...</p> <pre><code>def limit(items=None, start=0, collapse=False): if items and (start &gt; 0): items += start def wrapper(function): @functools.wraps(function) def func(*args, **kwargs): call = function(*args, **kwargs) if isinstance(call, (list, tuple)): results = call[start:items] if items else call if collapse and (len(results) == 1): return results[0] else: return results return call return func return wrapper </code></pre>
[]
[ { "body": "<p>If you expect a list of length 1, raise an exception when that is not the case:</p>\n\n<pre><code>if isinstance(call, (list, tuple)) and (len(call) == 1):\n return call[0]\nelse:\n raise ValueError(\"List of length 1 expected\")\n</code></pre>\n\n<p>A function that may return either a list or an element is hard to use. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-11T20:44:58.920", "Id": "44516", "Score": "0", "body": "To reinforce this, think of how you would use a function that sometimes returns an object and sometimes returns a list. That would be really messy!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-11T08:50:50.113", "Id": "27258", "ParentId": "27255", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-11T07:42:03.317", "Id": "27255", "Score": "-1", "Tags": [ "python" ], "Title": "Proper use or convenience, or both?" }
27255
<p>I have crated the following small script. I just need to improve this complicated code if possible.</p> <pre><code>def convUnixTime(t): expr_date = int(t) * 86400 fmt = '%Y-%m-%d %H:%M:%S' d1 = datetime.date.today().strftime('%Y-%m-%d %H:%M:%S') d2 = datetime.datetime.fromtimestamp(int(expr_date)).strftime('%Y-%m-%d %H:%M:%S') d1 = datetime.datetime.strptime(d1, fmt) d2 = datetime.datetime.strptime(d2, fmt) return (d2-d1).days </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T09:54:00.197", "Id": "42410", "Score": "1", "body": "What is your reason to do `strftime` followed by `strptime`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T09:56:05.450", "Id": "42411", "Score": "0", "body": "new to python.. don't know much.. just created from googling.. :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T18:41:27.767", "Id": "42460", "Score": "1", "body": "What does this function even do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T02:20:50.683", "Id": "42488", "Score": "0", "body": "On *nix Server it's required to Convert Unix timestamp to Readable Date/time, I used this function to check User account expiry date.." } ]
[ { "body": "<p>I think the main issue here is that you are trying to reuse snippets from Google without trying to understand what is doing what.</p>\n\n<p><strong>Magic numbers</strong></p>\n\n<p>This might be purely personal but I find <code>60*60*24</code> much easier to understand than <code>86400</code>.</p>\n\n<p><strong>Do not repeat yourself</strong></p>\n\n<p>What is the point of having <code>fmt = '%Y-%m-%d %H:%M:%S'</code> if later on you rewrite <code>strftime('%Y-%m-%d %H:%M:%S')</code> ? You could write it : <code>d1 = datetime.date.today().strftime(fmt)</code> making obvious to everyone that the same format is used.</p>\n\n<p><strong>Useless conversion between strings and dates</strong></p>\n\n<p>You are converting dates to string and string to date in a convoluted and probably not required way.</p>\n\n<p><strong>Usess conversion to int</strong></p>\n\n<p>You are using <code>int(expr_date))</code> but <code>expr_date</code> is defined as <code>int(t) * 86400</code> which is an integer anyway. Also, I am not sure you would need the conversion of <code>t</code> as an int.</p>\n\n<p>Taking into account the different comments, my resulting not-tested code looks like :</p>\n\n<pre><code>def convUnixTime(t):\n return (datetime.datetime.fromtimestamp(t*60*60*24)\n - datetime.datetime.today()).days\n</code></pre>\n\n<p><strong>Edit</strong> : I was using <code>datetime.date.today()</code> instead of <code>datetime.datetime.today()</code>. Also fixed the sign issue.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T13:03:17.097", "Id": "42421", "Score": "0", "body": "I have tested it is giving error: `TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T14:02:01.677", "Id": "42433", "Score": "0", "body": "Arg! I'll try and think about a proper working solution then :-P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T22:08:33.287", "Id": "42479", "Score": "0", "body": "If `t` is already in seconds, then that is what `datetime.datetime.fromtimestamp` is expecting, you don't want to do any arithmetic with it. Also, the returned `datetime.datetime` object has no `days` member. If you meant the `day` member, it is the day of the month, not the number of days." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T22:19:55.283", "Id": "42480", "Score": "0", "body": "I've fixed the code and it seems to be behaving just like yours (not sure if good thing or bad thing)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T02:27:49.713", "Id": "42489", "Score": "0", "body": "Thanks Josay for your help.. I saw.. my lazyness in small mistakes.. I will not repeat that again.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T02:50:55.810", "Id": "42490", "Score": "0", "body": "not it's working but, it -1 one day, why ? means today date is 13 Jun and act will expr on 15 Jun , so days should be 2 but it's showing 1, why ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T07:44:27.520", "Id": "42495", "Score": "0", "body": "What value of t are you testing with?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T12:50:40.963", "Id": "27303", "ParentId": "27295", "Score": "5" } } ]
{ "AcceptedAnswerId": "27303", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T09:49:25.310", "Id": "27295", "Score": "1", "Tags": [ "python", "beginner", "datetime" ], "Title": "Converting UNIX time" }
27295
<p>I have a method that takes a generator, converts it into a tuple to sort it, then into a list. It works perfectly, but being as I am fairly new to the Python world, I keep asking myself if it is worth doing or not...</p> <pre><code>@property def tracks(self): if 'tracks' not in self.cache: s = Search(Track) q = {'query': self.name} if self.artists[0]['name'] != 'Various Artists': q.update({'artist': self.artists[0]['name']}) _, tracks = s.search(**q) tracks = sorted(((int(i.track_number), i) for i in tracks)) self.cache['tracks'] = [t for n, t in tracks] return self.cache['tracks'] </code></pre> <p>I could care less about <code>track_number</code> as the <code>track[i]</code> already has that information, I'm just using it to sort the track list. <code>s.search(**q)</code> generates a generator of <code>Track</code> instances from a <code>json</code> object, I sort the track list, then I turn it back to a generator for an output.</p> <p>Is there a better way? Should I just deal with the track number being there?</p> <pre><code>for _, track for Album.tracks: # work with track </code></pre> <p><strong>Update</strong>:</p> <p>The way the backend API works it only requires the first artist in the search, on a collaborated album of various artists, it just gives <code>Various Artists</code>, hence the <code>self.artists[0]['name']</code> which is usually the only item in the list anyways.</p> <p>And I know <code>q['key'] = value</code> is better practice than <code>q.update({key: value})</code>, originally it was taking more than a few items, hence the use of <code>.update()</code>, I just never changed that part.</p> <p>The method is being called in <code>Album.tracks</code> where <code>s = Search(Track)</code> tells the <code>Search</code> class to use the <code>Track</code> class.</p> <pre><code>## models.py class Album: @property def tracks(self): s = Search(Track) ## search.py class Search(Service): def __init__(self, model): self.model = model </code></pre> <p>Instead of:</p> <pre><code>## models.py class Album: @property def tracks(self): s = Search('track') ## search.py from models import * MODELS = { 'album': Album, 'artist': Artist, 'track': Track } class Search(Service): def __init__(self, model): self.model = MODELS[model] </code></pre> <p><code>Search</code> calls a backend api service that returns queries in <code>JSON objects</code> which then generates instances based on what <code>self.model</code> is set to. <code>s = Search(Tracks)</code> tells <code>Search</code> to call the <code>track</code> api and iterate through the results and return <code>Track</code> instances.</p> <p>The main question here is, the current method that I have, is it doing too much? It generates the <code>Track</code> instances from the <code>Search.search()</code> generator, which is a somewhat abstract method for calling the api service for <code>Album</code>, <code>Artist</code>, and <code>Track</code> so it does nothing but generating instances based on what model it is given. Which is why I then have <code>Album.tracks</code> create a tuple so that I can sort the tracks base on track number, and then return a list of the tracks, nice and sorted.</p> <p><strong>Main point:</strong> Should I be worried about getting rid of the track numbers and just return the tuple, or is it fine to return the list?</p> <p><strong>Update 2:</strong></p> <pre><code>class Album: @property def tracks(self): if 'tracks' not in self.cache: s = Search(Track) q = {'query': '', 'album': self.name} if self.artists[0]['name'] != 'Various Artists': q['artist'] = self.artists[0]['name'] _, tracks = s.search(**q) self.cache['tracks'] = sorted(tracks, key = lambda track: int(track.track_number)) return self.cache['tracks'] class Track(BaseModel): def __repr__(self): artist = ', '.join([i['name'].encode('utf-8') for i in self.artists]) track = self.name.encode('utf-8') return '&lt;Track - {artist}: {track}&gt;'.format(artist=artist, track=track) </code></pre> <p>Calling it:</p> <pre><code>album_meta = Search(Album) results = album_meta.search('making mirrors', artist='gotye') for album results: print album.tracks ''' Output [&lt;Track - Gotye: Making Mirrors&gt;, &lt;Track - Gotye: Easy Way Out&gt;, &lt;Track - Gotye, Kimbra: Somebody That I Used To Know&gt;, &lt;Track - Gotye: Eyes Wide Open&gt;, &lt;Track - Gotye: Smoke And Mirrors&gt;, &lt;Track - Gotye: I Feel Better&gt;, &lt;Track - Gotye: In Your Light&gt;, &lt;Track - Gotye: State Of The Art&gt;, &lt;Track - Gotye: Don’t Worry, We’ll Be Watching You&gt;, &lt;Track - Gotye: Giving Me A Chance&gt;, &lt;Track - Gotye: Save Me&gt;, &lt;Track - Gotye: Bronte&gt;] ''' </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-15T16:40:34.707", "Id": "42658", "Score": "0", "body": "This function would be easier to review if you told us a bit more about the Album class that it is defined on, what is it used for, what the performance considerations are, etc." } ]
[ { "body": "<p>You create intermediate list for sorting:</p>\n\n<pre><code>tracks = sorted(((int(i.track_number), i) for i in tracks))\n</code></pre>\n\n<p>and then chose only one column:</p>\n\n<pre><code>self.cache['tracks'] = [t for n, t in tracks]\n</code></pre>\n\n<p>I think this would be better to replace two statements above:</p>\n\n<pre><code>self.cache['tracks'] = sorted(tracks, key = lambda track: int(track.track_number))\n</code></pre>\n\n<p>Also, <code>q.update({'artist': self.artists[0]['name']})</code> doesn't look good. It can easily be replaced with <code>q['artist'] = self.artists[0]['name']</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-15T17:38:50.060", "Id": "42662", "Score": "0", "body": "This is exactly what I was looking to hear. A way to reduce/combine it all. I felt like it was doing too much repetitive work generating a list to sort, then generate another list." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-15T17:16:31.830", "Id": "27437", "ParentId": "27431", "Score": "2" } } ]
{ "AcceptedAnswerId": "27437", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-15T15:21:55.950", "Id": "27431", "Score": "0", "Tags": [ "python", "generator" ], "Title": "Generator to Tuple to List?" }
27431
<p>When I wrote this it just felt messy due to the null checks. Any good ideas on how to clean it up would be most appreciated.</p> <pre><code> def getItemsInStock(self): itemsInStock = [] items = self.soup.find_all("ul", {'class':re.compile('results.*')}) getItems = [x for x in items if x.find("div", class_="quantity")] if getItems: itemsInStock += getItems pages = self.combThroughPages() if pages: for each in pages: self.uri = each soup = self.createSoup() items = soup.find_all("ul", {'class':re.compile('results.*')}) if items: inStock = [x for x in items if x.find("div", class_="quantity")] if inStock: itemsInStock += inStock if itemsInStock: return self.__returnItemDetailAsDictionary(itemsInStock) else: return None </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-22T07:39:25.587", "Id": "379609", "Score": "0", "body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about [what your code does](//codereview.meta.codereview.stackexchange.com/q/1226) and what the purpose of doing that is, the easier it will be for reviewers to help you. The current title states your concerns about the code; it needs an [edit] to simply *state the task*; see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>As an example,</p>\n\n<pre><code> getItems = [x for x in items if x.find(\"div\", class_=\"quantity\")]\n if getItems:\n itemsInStock += getItems\n</code></pre>\n\n<p>can be written</p>\n\n<pre><code> itemsInStock.extend(x for x in items if x.find(\"div\", class_=\"quantity\")]\n</code></pre>\n\n<p><code>extend</code> (and for that matter, <code>+=</code>) are no-ops on empty lists.</p>\n\n<p>Now, I'm not sure what some of the function you call return, but I don't like that <code>getItemsInStock</code> returns <code>None</code> if no items are in stock -- it makes more sense to return an empty list in that case. If your other functions did the same, you wouldn't need any of your <code>if</code> guards. Another example:</p>\n\n<pre><code> pages = self.combThroughPages()\n if pages:\n for each in pages:\n ...\n</code></pre>\n\n<p>can be written</p>\n\n<pre><code> for page in self.combThroughPages():\n ...\n</code></pre>\n\n<p>but only if <code>combThroughPages</code> returns an empty list when there are no, um, pages, I guess? (It's not clear from your function name.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-17T00:48:56.523", "Id": "42715", "Score": "2", "body": "And finally, change `__returnItemDetailAsDictionary` to accept an empty list for which it returns an empty dictionary. Now you can drop the `if itemsInStock` block and simply return `self.__returnItemDetailAsDictionary(itemsInStock)` in all cases." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-16T22:40:25.837", "Id": "27463", "ParentId": "27461", "Score": "4" } }, { "body": "<p>If a function like <code>self.combThroughPages()</code> returns None or a list of items you can wrap such a call in a function <code>listify()</code> that makes None into an empty list:</p>\n\n<pre><code>def listify(l):\n if l is None:\n return []\n</code></pre>\n\n<p>and make the call like:</p>\n\n<pre><code>...\nfor each in listify(self.combThroughPages())\n self.uri = each\n...\n</code></pre>\n\n<p>This works even if you don't have control over the definition of <code>combThroughPages()</code>. </p>\n\n<p>Sometimes you have functions that return None, or a single item or a list.\nI use a slightly more elaborate version of listify() myself to handle that:</p>\n\n<pre><code>def listify(val, none=None):\n \"\"\"return a list if val is only an element.\n if val is None, normally it is returned as is, however if none is set \n and True then [None] is returned as a list, if none is set but not \n True ( listify(val, False) ), then the empty list is returned.\n\n listify(None) == None\n listify(None, 1) == [1]\n listify(None, [2]) == [[2]]\n listify(None, False) == []\n listify(3) == [3]\n listify([4]) == [4]\n listify(5, 6) == [5]\n \"\"\"\n if val is None:\n if none is None:\n return None\n elif none:\n return [None]\n else:\n return []\n if isinstance(val, list):\n return val\n return [val]\n</code></pre>\n\n<p>In your case that version would be called like:</p>\n\n<pre><code>...\nfor each in listify(self.combThroughPages(), False)\n self.uri = each\n...\n</code></pre>\n\n<hr>\n\n<p>Since you are not further using the temporary lists getItems or inStock you can get rid of them and directly append items found to itemsInStock. This would get you (assuming you have the extended version of listify in your scope)</p>\n\n<pre><code>def getItemsInStock(self):\n itemsInStock = []\n for item in self.soup.find_all(\"ul\", {'class':re.compile('results.*')}):\n if item.find(\"div\", class_=\"quantity\"):\n itemsInStock.append(item)\n for self.uri in listify(self.combThroughPages(), False):\n soup = self.createSoup()\n for item in listify(soup.find_all(\"ul\", {'class':re.compile('results.*')}), False):\n if item.find(\"div\", class_=\"quantity\"):\n itemsInStock.append(item)\n if itemsInStock:\n return self.__returnItemDetailAsDictionary(itemsInStock)\n else:\n return None\n</code></pre>\n\n<p>It is of course impossible to test without context, but this should work.</p>\n\n<p>I also removed the variable <code>each</code> directly setting <code>self.uri</code>. I can only assume that self.createSoup is dependent on the value of self.uri, otherwise I am not sure why you would have differences in calling createSoup.</p>\n\n<hr>\n\n<p>Of course you don't need <code>listify()</code> around <code>self.combThroughPages()</code> if you change the latter to return an empty list as @ruds already proposed that would work as well. In that case I would probably also have <code>getItemsInStock()</code> return an empty dictionary ( <code>return {}</code> ) depending on how that function itself is called:</p>\n\n<pre><code> iis = self.getItemsInStock()\n if iis:\n for key, value in iis.iteritems()\n</code></pre>\n\n<p>could then be changed to:</p>\n\n<pre><code> for key, value in iis.iteritems():\n</code></pre>\n\n<p>(or you can write a <code>dictify()</code> function).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-17T09:34:22.990", "Id": "27471", "ParentId": "27461", "Score": "1" } }, { "body": "<p>One of my favourite Python shorthands is the <code>or</code> operator being used to provide a default value:</p>\n\n<pre><code>x = y or 42\n</code></pre>\n\n<p>This will assign the value of <code>y</code> to <code>x</code>, if <code>y</code> evaluates to <code>True</code> when interpreted as a boolean, or <code>42</code> otherwise. While this may seem odd at first, it is perfectly normal if you consider short-circuit evaluation and how Python can interpret nearly everything as a boolean: If the first operand evaluates to <code>True</code> (e.g., it is not <code>None</code>), return the first operand, otherwise return the second.</p>\n\n<p>In other words, <code>A or B</code> is equivalent to <code>A if A else B</code>, and conversely (but not quite as intuitive, I guess), <code>A and B</code> is equivalent to <code>B if A else A</code>.</p>\n\n<p>This is not only handy for assigning default values to variables, as in the above example, but can also be used to get rid of some of your <code>if</code> checks. For example, instead of </p>\n\n<pre><code>pages = self.combThroughPages()\nif pages:\n for each in pages:\n # do stuff\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>pages = self.combThroughPages() or []\nfor each in pages:\n # do stuff\n</code></pre>\n\n<p>or even shorter, since now you need <code>pages</code> only once:</p>\n\n<pre><code>for each in self.combThroughPages() or []:\n # do stuff\n</code></pre>\n\n<p>Now, if <code>combThroughPages()</code> returns <code>None</code> (which is <code>False</code> when interpreted as a boolean), the <code>or</code> operator will return the second operand: <code>[]</code>.</p>\n\n<p>(Of course, if <code>combThroughPages()</code> returns an empty list instead of <code>None</code>, you don't have to check at all, as pointed out by @ruds; same for your list comprehensions.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T04:31:10.817", "Id": "43723", "Score": "0", "body": "I'm a big fan of None or [] as a way of unifying return values - in the Maya api, which is extremely inconsistent about returning None, single items, or lists it's a lifesaver" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-06T11:35:24.697", "Id": "351457", "Score": "0", "body": "`y = 0` will evaluate in `x = y or 42` to `x = 42`. Is this ok?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-06T16:37:56.780", "Id": "351515", "Score": "0", "body": "@Elmex80s What do you mean with \"is this okay\"? If a function returns `None` or numeric values, including `0`, then yes, that's a very good point where using `or` can lead to unexpected behavior. But in OP's case, that should not be a problem." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:48:43.147", "Id": "28002", "ParentId": "27461", "Score": "4" } } ]
{ "AcceptedAnswerId": "27471", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-16T21:55:30.730", "Id": "27461", "Score": "5", "Tags": [ "python" ], "Title": "refactor Python code with lots of None type checks" }
27461
<blockquote> <p>A company sells iPods online. There are 100 stocks maintained at Argentina and Brazil. A single iPod costs $100 in Brazil and $50 in Argentina. The cost of exporting stocks from one country to the other will cost $400 per 10 blocks. The transportation is always done in the multiples of 10. Calculate the minimum cost for purchasing the given no of units. Assume that for each transaction, the available stock in each country is maintained to be 100.</p> <p>Input and output format:</p> <ul> <li>The country from which the order is being placed: No of units</li> <li>Minimum costs:No of stock left in Brazil: No of stock left at Argentina</li> </ul> <p>Sample input and output:</p> <pre class="lang-none prettyprint-override"><code>Brazil:5 500:95:100 Brazil:50 4500:100:50 </code></pre> </blockquote> <pre class="lang-python prettyprint-override"><code>class Country: shp=40 def country_details(self,numberofitems,sellingprice): self.sp=sellingprice self.no=numberofitems def display(self): print self.sp print self.no print self.shp Brazil=Country() Brazil.country_details(100,100) Brazil.display() Argentina=Country() Argentina.country_details(100,50) Argentina.display() print "Enter the country from which you order from" x=raw_input() if x=="Brazil": c=1 else: c=2 print "Enter the amount of products needed" y=raw_input() y=int(y) def profit(y): if c==1: if y%10==0: P=orderfromArgentinafb(y); else: P=orderfromBrazil(y); if c==2: P=orderfromArgentina(y); return P def calculate(y): if (y&lt;101): Pr=profit(y) return Pr else: Pr=profit(y-(y%100))+orderfromBrazil(y-100) return Pr def orderfromBrazil(y): Cost=y*Brazil.sp if c==2: Cost=Cost+y*Brazil.shp Brazil.no=Brazil.no-y return Cost def orderfromArgentina(y): Cost=y*Argentina.sp Argentina.no=Argentina.no-y return Cost def orderfromArgentinafb(y): Cost=y*Argentina.sp+(y*Argentina.shp) Argentina.no=Argentina.no-y if Argentina.no &lt;0: Argentina.no=0 return Cost Pr=calculate(y) print Pr print "%d:%d:%d" %(Pr,Brazil.no,Argentina.no) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-20T06:37:17.327", "Id": "122618", "Score": "1", "body": "[Apparent source of the challenge](http://permalink.gmane.org/gmane.comp.programming.algogeeks/18046)" } ]
[ { "body": "<p>You can write</p>\n\n<pre><code>if raw_input(\"Enter the country from which you order from\") == \"Brazil\":\n c = 1\nelse:\n c = 2\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>print \"Enter the country from which you order from\"\nx=raw_input()\nif x==\"Brazil\":\n c=1\nelse:\n c=2\n</code></pre>\n\n<p>as you are not using x anywhere. I less variable and raw_input has optional string so why not use that?</p>\n\n<p>In function profit instead of using</p>\n\n<pre><code>if y%10==0:\n P=orderfromArgentinafb(y);\nelse:\n P=orderfromBrazil(y);\n</code></pre>\n\n<p>you can use</p>\n\n<pre><code>if y % 10:\n return orderfromBrazil(y)\nelse:\n return orderfromArgentinafb(y)\n</code></pre>\n\n<ul>\n<li>You don't need the variable P when you are just returning it. </li>\n<li>Why are there semicolons at the end? This isn't C</li>\n<li>Notice the changing the order of return. It gives the same result but with one less comparison.</li>\n</ul>\n\n<p>Same thing can be done in function calculate. </p>\n\n<p>Use if...elif... in case you are just doing one of the things. Using as it is leads to more comparisons than are needed. </p>\n\n<p>In both the functions orderfromArgentina and orderfromArgentinafb a simple reordering of statements can lead to removal of additional variable Cost.</p>\n\n<p>You need to read a style guide. Check for official tutorials of Python. They contain brief style guide. That is also an optimization. It doesn't effect memory or time complexity but it leads to better maintenance</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-21T18:57:28.843", "Id": "27645", "ParentId": "27642", "Score": "1" } } ]
{ "AcceptedAnswerId": "27645", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-21T17:23:18.953", "Id": "27642", "Score": "1", "Tags": [ "python", "programming-challenge" ], "Title": "Stocks of iPods for various countries" }
27642
<pre><code>def alist(x): if x == 1: return 1 return [alist(x - 1), x, alist(x - 1)] l = '%r' % alist(int(raw_input('Maximum Number Of Asterisks: '))) f = l.replace("[", "").replace("]", "").replace(",", "").replace(" ", "") for i in f: print "*" * int(i) </code></pre> <p>So, basically, I just formatted the list into a string, removed all unwanted characters (left bracket, right brakcer, comma, and space), and for every number in that string, printed the appropriate amount of asterisks. If there is anything you don't understand, sorry because I had to type this up in under 2 minutes, so please just post a comment and I'll try to answer as soon as I can.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-24T20:14:03.873", "Id": "43232", "Score": "0", "body": "You should clarify what exactly you want.Give us an example of the multidimensional list." } ]
[ { "body": "<p>Without many details, maybe the following can help you:</p>\n\n<pre><code>&gt;&gt;&gt; import itertools\n&gt;&gt;&gt; list_of_lists = [['item_1'], ['item_2', 'item_3'], ['item_4', 'item_5', 'item_6']]\n&gt;&gt;&gt; chain = list(itertools.chain(*list_of_lists))\n&gt;&gt;&gt; print chain\n['item_1', 'item_2', 'item_3', 'item_4', 'item_5', 'item_6']\n</code></pre>\n\n<p>Take a look at this <a href=\"https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python\">question</a>, there are some answers that might help you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-24T22:04:25.190", "Id": "43233", "Score": "0", "body": "Thanks for the effort, evil_inside, but that would only flatten out a 2-dimensional list, not anything higher. In my solution, I could easily use the split() method and not remove the spaces in the string to separate the string by the spaces (that sounds confusing) and make a 1-dimensional list from any multidimensional list." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-24T20:33:14.030", "Id": "27746", "ParentId": "27740", "Score": "1" } }, { "body": "<p>Instead of replacing stuff in the <code>repr(li)</code>, flatten the list with a recursive function..</p>\n\n<pre><code>def alist(x):\n if x in (0,1): return x\n return [alist(x - 1), x, alist(x - 1)]\n\n# the magic function\ndef flatten(list_to_flatten):\n for elem in list_to_flatten:\n if isinstance(elem,(list, tuple)):\n for x in flatten(elem):\n yield x\n else:\n yield elem\n\nl = alist(int(raw_input('Maximum Number Of Asterisks: ')))\nf = flatten(l)\n\nfor i in f:\n print \"*\" * int(i)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-29T07:56:01.133", "Id": "27944", "ParentId": "27740", "Score": "1" } } ]
{ "AcceptedAnswerId": "27944", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-24T19:08:02.273", "Id": "27740", "Score": "1", "Tags": [ "python" ], "Title": "Is there a better way to flatten out a multidimensional list?" }
27740
<p>I am trying to turn this function:</p> <pre><code>collection = ['hey', 5, 'd'] for x in collection: print(x) </code></pre> <p>Into this one:</p> <pre><code>def printElement(inputlist): newlist=inputlist if len(newlist)==0: Element=newlist[:] return Element else: removedElement=newlist[len(inputlist)-1] newlist=newlist[:len(inputlist)-1] Element=printElement(newlist) print(removedElement) collection = ['hey', 5, 'd'] printElement(collection) </code></pre> <p>It works, but I wonder if it's okay there's no "return" line under "else:" Is this as "clean" as I can make it? Is it better code with or without the newlist?</p>
[]
[ { "body": "<blockquote>\n <p>but I wonder if it's okay there's no \"return\" line under \"else:\"</p>\n</blockquote>\n\n<p>Yes, that's OK. You don't need to return anything from your function if you don't want to. In fact, in the interest of consistency, you may as well remove the thing returned in the if block too:</p>\n\n<pre><code>def printElement(inputlist):\n newlist=inputlist\n if len(newlist)==0:\n return\n else:\n removedElement=newlist[len(inputlist)-1]\n newlist=newlist[:len(inputlist)-1]\n Element=printElement(newlist)\n print(removedElement)\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<blockquote>\n <p>Is it better code with or without the newlist?</p>\n</blockquote>\n\n<p>Assigning new things to <code>inputlist</code> won't modify it outside of the function, so there's no harm in doing so. May as well get rid of newlist.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n else:\n removedElement=inputlist[len(inputlist)-1]\n inputlist=inputlist[:len(inputlist)-1]\n Element=printElement(inputlist)\n print(removedElement)\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>you don't use <code>Element</code> after assigning it, so you may as well not assign it at all.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n else:\n removedElement=inputlist[len(inputlist)-1]\n inputlist=inputlist[:len(inputlist)-1]\n printElement(inputlist)\n print(removedElement)\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>You don't really need to modify <code>inputlist</code>, since you only use it once after modifying it. Just stick that expression straight into the <code>printElement</code> call. And now that <code>inputlist</code> is never modified, you can get rid of <code>removedElement</code> too, and just inline its expression in the <code>print</code> function.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n else:\n printElement(inputlist[:len(inputlist)-1])\n print(inputlist[len(inputlist)-1])\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>Fun fact: for any list <code>x</code>, <code>x[len(x)-1]</code> can be shortened to <code>x[-1]</code>. Same with <code>x[:len(x)-1]</code> to <code>x[:-1]</code>.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n else:\n printElement(inputlist[:-1])\n print(inputlist[-1])\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>Since the first block unconditionally returns, you could remove the <code>else</code> and just put that code at the function level, without changing the code's behavior. Some people find this less easy to read. Personally, I like my code to have the least amount of indentation possible.</p>\n\n<pre><code>def printElement(inputlist):\n if len(inputlist)==0:\n return\n printElement(inputlist[:-1])\n print(inputlist[-1])\n\n\ncollection = ['hey', 5, 'd']\n\nprintElement(collection)\n</code></pre>\n\n<p>That's about as compact as you can get, with a recursive solution. You should probably just stick with the iterative version, for a few reasons:</p>\n\n<ul>\n<li>Fewer lines</li>\n<li>More easily understood</li>\n<li>Doesn't raise a \"maximum recursion depth exceeded\" exception on lists with 200+ elements</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-25T19:55:36.597", "Id": "27777", "ParentId": "27773", "Score": "1" } }, { "body": "<p>Your function is needlessly complicated. The return value is never used. You also print from the end of the list, which is a bit odd: tail recursion is a more usual style. For example:</p>\n\n<pre><code>def printCollection(c):\n if c:\n print c[0]\n printCollection(c[1:])\n</code></pre>\n\n<p>This still has the flaw that it copies the list for every element in the list, making it an O(n^2) function. It's also limited to data structures that use slices and indices. Here's a recursive version that prints any iterable:</p>\n\n<pre><code>def printCollection(c):\n it = iter(c)\n try:\n el = it.next()\n print el\n printCollection(it)\n except StopIteration:\n pass\n</code></pre>\n\n<p>It's still a bit odd to recurse here as this is a naturally iterative problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-26T03:03:11.533", "Id": "43310", "Score": "0", "body": "You're right. I was thinking I could get a better grip on recursion by doing some programs that were easier to understand. While that helped a little, I see I need to step it up." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-25T19:55:53.630", "Id": "27778", "ParentId": "27773", "Score": "1" } } ]
{ "AcceptedAnswerId": "27777", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-25T19:27:19.883", "Id": "27773", "Score": "2", "Tags": [ "python", "recursion" ], "Title": "I'm practicing turning for loops into recursive functions. what do you think?" }
27773
<p>I wrote this tiny script to pull the JSON feed from the <a href="http://citibikenyc.com/stations/json" rel="nofollow">CitiBike website</a>:</p> <pre><code>import requests import time def executeCiti(): r = requests.get("http://citibikenyc.com/stations/json") print r.json() time.sleep(62) while True: executeCiti() exit() </code></pre> <p>Then I just run the script in terminal and output it to a .txt file like so: python citi_bike.py > output.txt</p> <p>The end goal of what I would like by the end of this exercise is well formatted JSON data (with only select few of the pairs from each request), separated by each request. I want it to be manageable so I can create visualizations from it.</p> <ol> <li><p>Is this an okay way to start what I'm trying to accomplish?</p></li> <li><p>Is there a better way to begin, so that the data came out like I want it as my end goal? In regards to this question, I feel like I have already started taking a very roundabout way to getting to a cleaned up data set, even though this is only the first step.</p></li> </ol>
[]
[ { "body": "<p>While this is a good start, there are several things that should be noted.</p>\n\n<blockquote>\n <p>r = requests.get(\"<a href=\"http://citibikenyc.com/stations/json\">http://citibikenyc.com/stations/json</a>\")</p>\n</blockquote>\n\n<p>This is code snippet is network-based, and so errors may occur. You will want to handle these errors in some way, with a <code>try-except</code> block like so:</p>\n\n<pre><code>try:\n r = requests.get(\"http://citibikenyc.com/stations/json\")\nexcept ConnectionError:\n pass # handle the error\nexcept TimeoutError:\n pass # handle the error\n</code></pre>\n\n<p>and so on, as per <a href=\"http://docs.python-requests.org/en/latest/user/quickstart/#timeouts\">the requests documentation</a>.</p>\n\n<p>Additionally, do not sleep and do in the same function. These are two responsibilities and so should be separated as per the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a>.</p>\n\n<p>I would suggest adding the <code>sleep(62)</code> to the <code>while True:</code> block.</p>\n\n<p>Also, there is no point to this:</p>\n\n<blockquote>\n <p>exit()</p>\n</blockquote>\n\n<p>as it will never be executed. This leads me to my next point, you should probably do the file writing in Python instead of the command line, so you can open the file, append some data, and then close it to make sure it is safe between network errors and power outages. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-21T21:41:51.647", "Id": "60757", "ParentId": "27774", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-25T19:38:57.170", "Id": "27774", "Score": "8", "Tags": [ "python", "json", "timer" ], "Title": "Timed requests and parsing JSON in Python" }
27774
<p>This little program is self-explanatory. I count letters in a string (can be any string), using a <code>for</code> loop to iterate through each letter. The problem is that this method is very slow and I want to avoid loops.</p> <p>Any ideas? I thought that maybe if I remove checked letters from the string after each loop, then in some cases, where many letters repeat, that would make a difference.</p> <pre><code>def count_dict(mystring): d = {} # count occurances of character for w in mystring: d[w] = mystring.count(w) # print the result for k in sorted(d): print (k + ': ' + str(d[k])) mystring='qwertyqweryyyy' count_dict(mystring) </code></pre> <p>The output:</p> <pre><code>e: 2 q: 2 r: 2 t: 1 w: 2 y: 5 </code></pre>
[]
[ { "body": "<p>Use the built in <code>Counter</code> in the <code>collections</code> module:</p>\n\n<pre><code>&gt;&gt;&gt; from collections import Counter\n&gt;&gt;&gt; Counter('qwertyqweryyyy')\nCounter({'y': 5, 'e': 2, 'q': 2, 'r': 2, 'w': 2, 't': 1})\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-25T22:53:21.943", "Id": "27784", "ParentId": "27781", "Score": "15" } }, { "body": "<p>Counter is definitely the way to go (and I've upvoted Jaime's answer).</p>\n\n<p>If you want to do it yourself and iterate only once, this should work :</p>\n\n<pre><code>d={}\nfor l in s:\n d[l] = d.get(l,0) + 1\n</code></pre>\n\n<p>There might be a short/more pythonic way to do so but it works...</p>\n\n<p><strong>Edit</strong> : \nI must confess that Jaime's comment to this answer surprised me but I've just tested this code :</p>\n\n<pre><code>from profilehooks import profile\n\ns=\"qwertyuiopasdfghjklzxcvbnm\"\n\n@profile\ndef function1(s):\n d={}\n for l in s:\n d[l] = d.get(l,0)+1\n return d\n\n@profile\ndef function2(s):\n return dict((char_, s.count(char_)) for char_ in set(s))\n\nfor i in xrange(0,200):\n function1(s*i)\n function2(s*i)\n</code></pre>\n\n<p>And the results can hardly be contested :</p>\n\n<pre><code>*** PROFILER RESULTS ***\nfunction2 (./fsdhfsdhjk.py:13)\nfunction called 200 times\n\n 10948 function calls in 0.161 seconds\n\n Ordered by: cumulative time, internal time, call count\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 200 0.083 0.000 0.161 0.001 fsdhfsdhjk.py:13(function2)\n 5374 0.033 0.000 0.077 0.000 fsdhfsdhjk.py:15(&lt;genexpr&gt;)\n 5174 0.044 0.000 0.044 0.000 {method 'count' of 'str' objects}\n 200 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 0 0.000 0.000 profile:0(profiler)\n\n\n\n*** PROFILER RESULTS ***\nfunction1 (./fsdhfsdhjk.py:6)\nfunction called 200 times\n\n 517800 function calls in 2.891 seconds\n\n Ordered by: cumulative time, internal time, call count\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 200 1.711 0.009 2.891 0.014 fsdhfsdhjk.py:6(function1)\n 517400 1.179 0.000 1.179 0.000 {method 'get' of 'dict' objects}\n 200 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 0 0.000 0.000 profile:0(profiler)\n</code></pre>\n\n<p><strong>TL;DR</strong>\nJaime's solution (<code>function2</code>) is 18 times faster than mine (<code>function1</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-26T23:12:48.610", "Id": "43383", "Score": "4", "body": "This would be the right way of doing things in a language such as C. Because Python loops have so much overhead, it actually may turn out to be faster to do something like: `char_counts = dict((char_, test_string.count(char_)) for char_ in set(test_string))` It does run multiple times over the string, but because the loops run in C, not in Python, it is faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-26T23:32:28.317", "Id": "43385", "Score": "0", "body": "I am really really impressed. I've updated my answer accordingly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T03:38:15.833", "Id": "43389", "Score": "3", "body": "I tested it on a 10**6 character string and there it was only 4x faster. It's one of the few things I don't like about Python, that sometimes optimizing code is not about writing the most efficient algorithm, but about figuring out which built-in functions run faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T06:31:05.757", "Id": "43393", "Score": "0", "body": "Yes, as function2 loops roughly (x+1) times on the string (x being the number of different characters), I can imagine that the performance gain, compared to function 1 looping only once, gets smaller as x and the string get bigger. Still, this is a damn long string :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T20:37:05.523", "Id": "43537", "Score": "0", "body": "This is my first experience with python profiler. I ran cProfile on several methods and surprisingly, my original method took less function calls than suggested Counter, even though all methods take exactly the same amount of time (I had a relatively short string).\n\nI am running profiler with \n\n`$ python -m cProfile -s time test.py`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-26T21:43:45.900", "Id": "27820", "ParentId": "27781", "Score": "6" } }, { "body": "<p>This is the shortest answer I can think of:</p>\n\n<pre><code>{i:str.count(i) for i in str}\n</code></pre>\n\n<p>This is called Dictionary comprehension, which is an efficient way to get the count of each alphabet in the string as a letter(key):count(value) pair.</p>\n\n<p>Example:</p>\n\n<pre><code>str = \"StackExchange\" \n{i:str.count(i) for i in str} \n{'a': 2, 'c': 2, 'E': 1, 'g': 1, 'h': 1, 'k': 1, 'n': 1, 'S': 1, 't': 1, 'x': 1, 'e': 1}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-29T03:25:17.660", "Id": "85278", "ParentId": "27781", "Score": "1" } } ]
{ "AcceptedAnswerId": "27784", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-06-25T21:43:08.603", "Id": "27781", "Score": "11", "Tags": [ "python", "strings" ], "Title": "Counting letters in a string" }
27781
<p>I applied for a job and they asked me to write code with the following requirements:</p> <blockquote> <p>Get a "toolbar offer" description from http..update.utorrent.com/installoffer.php?offer=conduit. Parse the bencoded (see <a href="http://en.wikipedia.org/wiki/Bencode">http://en.wikipedia.org/wiki/Bencode</a>) response and extract the URL of the binary and its SHA1 hash. The hash is contained in the value of the key 'offer_hash'. The binary is in list for the key 'offer_urls' — please use the one prefixed with "http..download.utorrent.com/".</p> <p>Download the binary and calculate its hash</p> <p>Verify that the calculated SHA1 hash is identical to the one provided in the offer details. It is okay to use existing libraries for bencoding, hashing, etc.</p> </blockquote> <p>What is wrong with my code? The recruiter said it didn't meet their bar.</p> <pre><code># Script that verifies the correctness of a toolbar offers import urllib, bencode , hashlib from hashlib import sha1 url = "http://update.utorrent.com/installoffer.php?offer=conduit" filename = "content.txt" f= urllib.urlretrieve(url, filename) #Bdecoding the response with open (str(filename), 'rb') as myfile: data=myfile.read() decoded = bencode.bdecode(data) # Returning the list for the key 'offer_urls' list = decoded['offer_urls'] #print list # Returning the URL of the binary that is prefixed with "http://download3.utorrent.com/" length = len (list) prefix = "http://download3.utorrent.com/" i= -1 while i &lt; length: i = i + 1 if list[i].startswith(prefix) : break binary= list[i] print "The URL of the the binary is: " , binary # Returning the sha1 hash contained in the value of the key 'offer_hash' encrypted_hash = decoded['offer_hash'] sha1_hash1 = encrypted_hash.encode('hex') print "The sha1 hash contained in the value of the key 'offer_hash' is: " , sha1_hash1 # Downloading the binary and calculating its hash urllib.urlretrieve ( binary , "utct2-en-conduit-20130523.exe") file = "C:\Python27\utct2-en-conduit-20130523.exe" with open (file, 'rb') as myfile: downloaded=myfile.read() k = hashlib.sha1() k.update(downloaded) sha1file = k.hexdigest() print "The sha1 hash of the downloaded binary is: " , sha1file # Verify that the calculated sha1 hash is identical to the one provided in the offer details if (sha1file == sha1_hash1) : print "Test result = Pass" else : print "Test result = Fail" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T17:25:54.403", "Id": "43422", "Score": "58", "body": "A fairly simple problem with your code: Comments should explain why, not how." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T23:44:24.430", "Id": "43441", "Score": "2", "body": "It does show your a pragmatist which is good when your working alone." } ]
[ { "body": "<p>Problems:</p>\n\n<ol>\n<li><p>I would say that <code>import</code> should be an efficient way of reusing the libraries.</p>\n\n<pre><code>import urllib, bencode , hashlib\nfrom hashlib import sha1\n</code></pre>\n\n<p>In the above line of code you have imported <code>hashlib</code> and <code>sha1</code> from <code>hashlib</code> on the second line. There is nothing wrong in that, but when you just want to use only <code>sha1</code>, then no need to import the entire class. </p>\n\n<p>Same with other classes: how many members of the above mentioned libraries have you used in your code?</p></li>\n<li><p>All the constants should be predefined at the beginning of the script, not wherever required.</p></li>\n<li><p>What if the above file failed to open (in case file not present)? How do you deal with this exception?</p>\n\n<pre><code>with open (str(filename), 'rb') as myfile:\n downloaded=myfile.read()\n</code></pre>\n\n<p>Use try-except to catch exceptions.</p></li>\n<li><p>Filename is already a string.</p></li>\n<li><p>No need to use an extra variable to store the length of the list. Also there is a space in between the function <code>len</code> and its arg.</p>\n\n<pre><code>length = len (list)\n</code></pre></li>\n<li><p>Use a <code>for</code> loop for indexing, which is better than using a <code>while</code> loop.</p></li>\n<li><p>Meaningless variable names such as <code>i</code>, <code>f</code>, <code>k</code>.</p></li>\n<li><p>The tasks are not well-divided into different subroutines.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T11:42:33.130", "Id": "60320", "Score": "3", "body": "Problem 8 is the biggest problem. His solution is a typical case of a `transactional script`. I hate transactional scripts, and others do too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T10:06:01.127", "Id": "27887", "ParentId": "27824", "Score": "30" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T03:55:04.517", "Id": "27824", "Score": "213", "Tags": [ "python", "algorithm", "interview-questions" ], "Title": "Calculate SHA1 hash from binary and verify with a provided hash" }
27824
<p>I am reading space separated integers, removing redundant ones and then sorting them. The following code works.</p> <p>I was thinking whether this is the fastest way to do that or can it be optimized more?</p> <pre><code>import sys def p(): #Reads space seperated integers #Removes redundant #Then sorts them nums = set(map(int,next(sys.stdin).split())) nums = [i for i in nums] - nums.sort() print nums </code></pre> <p>EDIT:</p> <p>tobia_k's suggestion is better performance-wise. Just 1 sentence instead of 3 and better in time-efficiency.</p> <pre><code>nums = sorted([int(i) for i in set(next(sys.stdin).split())]) </code></pre>
[]
[ { "body": "<pre><code>inpt = raw_input(\"Enter a string of numbers: \")\nnumbers = sorted(set(map(int, inpt.split())))\nprint numbers\n</code></pre>\n\n<ul>\n<li>I would recommend separating the input-reading from the integer-extraction part.</li>\n<li>Using <code>raw_input</code> (Python 2.x) or <code>input</code> (Python 3) is more usual for reading user inputs.</li>\n<li>You can do it all in one line using <code>sorted</code> instead of <code>sort</code>.</li>\n<li>Performance-wise it <em>might</em> be better to apply <code>set</code> first, and then <code>map</code>, so <code>int</code> has to be applied to fewer elements, but I don't think it makes much of a difference, if at all.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T12:58:33.317", "Id": "43599", "Score": "0", "body": "I am working with online judging so performance matters a lot. I merged the reading and extraction part because they have slight overheads(not much but there are overheads). `raw_input` and `input` are very slow compared to this method. http://stackoverflow.com/questions/17023170/what-are-other-options-for-faster-io-in-python-2-7. Applying set first was better" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T12:32:21.360", "Id": "27963", "ParentId": "27962", "Score": "1" } } ]
{ "AcceptedAnswerId": "27963", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T10:12:25.497", "Id": "27962", "Score": "1", "Tags": [ "python" ], "Title": "Optimizing reading integers directly into a set without a list comprehension in Python" }
27962
<p>I've written the following Python class that fetches <em>iptables</em> rules using basic string processing in Linux. Am I doing this in the correct manner? I've tested the code and it's running fine.</p> <p>I'm ultimately going to use this class in a GUI app that I'm going to write using Python + GObject.</p> <pre><code>#!/usr/bin/python import sys, subprocess class Fwall: currchain="" dichains={'INPUT':[],'OUTPUT':[],'FORWARD':[]} dipolicy=dict(INPUT=True,OUTPUT=True,FORWARD=True) dicolumns={} def __init__(self): self.getrules() self.printrules() print "class initialized." def getrules(self): s = subprocess.check_output("iptables --list --verbose",shell=True,stderr=subprocess.STDOUT)#.split('\n') print s for line in s.splitlines(): if len(line)&gt;0: self.parseline(line) def parseline(self,line): line=line.strip() if line.startswith("Chain"): #this is the primary header line. self.currchain=line.split(' ')[1] allowed=not line.split('policy ')[1].startswith('DROP') self.dipolicy[self.currchain]=allowed #print "curr chain set to " + self.currchain else: items=line.split() if line.strip().startswith('pkts'): #this is the secondary header line, so fetch columns. if len(self.dicolumns)==0: for i,item in enumerate(items): if len(item)&gt;0: self.dicolumns.setdefault(item,i) #print self.dicolumns else: return else: ditemp={} #print line self.dichains[self.currchain].append(ditemp) for k,v in self.dicolumns.iteritems(): #idx= self.dicolumns[item]#,items[item] ditemp.setdefault(k,items[v]) #print line #print k,v #print k,items[v]#,idx def printrules(self): for k,v in self.dichains.iteritems(): print k litemp=self.dichains[k] for item in litemp: print item if __name__=="__main__": f=Fwall() </code></pre>
[]
[ { "body": "<p>There are violations of <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP-8</a> throughout and there are no <a href=\"http://www.python.org/dev/peps/pep-0257/\">PEP-257 docstrings</a>. It sounds petty, but these mean the difference between an easy read and a hard one.</p>\n\n<p>The class name <code>Fwall</code> is terrible, if you mean <code>Firewall</code> call it that. If you mean that it is a container of <code>FirewallRules</code> then say so. Names are extremely important.</p>\n\n<p>If <code>getrules()</code> is not part of the public class interface, convention suggests naming it <code>_getrules</code> which tells the reader that it is expected to be used only by the class itself. Having <code>print</code> statements is fine for debugging, but a well behaved library should assume that there is no stdout and return lists of strings in production code.</p>\n\n<p>Long lines are hard to read, especially on StackExchange. Fortunately, splitting within parenthesis is natural and preferred, thus:</p>\n\n<pre><code>s = subprocess.check_output(\"iptables --list --verbose\",\n shell=True, stderr=subprocess.STDOUT)\n</code></pre>\n\n<p>but sticking a comment marker in code will certainly cause misreadings. Where you have</p>\n\n<pre><code>s = subprocess.check_output(...)#.split('\\n')\n</code></pre>\n\n<p>you should drop the <code>#.split('\\n')</code>. Also, following PEP-8, put spaces after argument separating commas.</p>\n\n<p>You use <code>iteritems()</code> unnecessarily as the standard iteration behavior of a dictionary is now assumed. Where you have <code>for k,v in self.dicolumns.iteritems():</code> the line</p>\n\n<pre><code>for k, v in self.dicolumns:\n</code></pre>\n\n<p>is equivalent. To bang on the \"names are important\" drum, every dictionary has <code>k</code> and <code>v</code>, using more descriptive names would tell me what the meaning of the keys and values are. For that matter I have no idea was a <code>dipolicy</code> or <code>dicolumns</code> are, they might be related or parallel lists but I don't know. You tend to use <code>if len(item)==0</code> when <code>if item</code> means the same thing.</p>\n\n<p>I had to edit your entry because the class methods were not properly indented; this usually means that you are using a mix of tabs and spaces. Tell your editor to forget that the TAB character exists and to use only spaces, there are instructions for most editors on how to make it pretend that the TAB key behaves like you expect without putting literal <code>\\t</code> characters in your source code.</p>\n\n<p>The structure of <code>parseline()</code> is so deeply nested and has so many return points and un-elsed ifs that I really can't follow the logic of it. Read <a href=\"http://www.python.org/dev/peps/pep-0020/\">The Zen of Python</a> and keep it wholly.</p>\n\n<p>Finally, iptables is notoriously hairy. I strongly suggest that you use <a href=\"http://ldx.github.io/python-iptables/\">python-iptables</a> or at least study its class structure. You might also want to look at <a href=\"http://en.wikipedia.org/wiki/Uncomplicated_Firewall\">Uncomplicated Firewall</a> as it is designed to abstract iptables into something most humans can understand. It doesn't handle all possible uses, but it makes the typical cases comprehensible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T20:23:27.163", "Id": "28009", "ParentId": "27987", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T10:59:21.073", "Id": "27987", "Score": "2", "Tags": [ "python", "linux", "iptables" ], "Title": "Python class to abstract the iptables Linux firewall" }
27987
<p><strong>MyText.txt</strong> </p> <pre><code>This is line 1 This is line 2 Time Taken for writing this# 0 days 0 hrs 1 min 5 sec Nothing Important Sample Text </code></pre> <p><strong>Objective</strong></p> <p>To read the text file and find if "Sample Test is present in the file. If present print the time taken to write the file (which is a value already inside the file)"</p> <p><strong>My Code</strong></p> <pre><code>with open('MyText.txt', 'r') as f: f.readline() for line in f: if 'Sample Text' in line: print "I have found it" f.seek(0) f.readline() for line in f: if 'Time Taken' in line: print line print ' '.join(line.split()) f.close() </code></pre> <p>The code is working fine. I want to know if this code can be made even better. Considering I am new to Python, I am sure there would be a better way to code this. Can anyone suggest alternative/faster approaches for this?</p>
[]
[ { "body": "<p>How about this:</p>\n\n<pre><code>with open('MyText.txt', 'r') as f:\n time = None\n for line in f:\n if 'Time Taken' in line:\n time = line[line.find(\"#\") + 1:].strip()\n if 'Sample Text' in line:\n print \"I have found it\"\n if time:\n print \"Time taken:\", time\n</code></pre>\n\n<ul>\n<li>not sure what that first <code>f.readline()</code> was for...</li>\n<li>no need to explicitly invoke <code>f.close()</code> when using <code>with</code></li>\n<li>find time taken in the first pass through the file instead of resetting the pointer and seeking again</li>\n<li>you could use <code>find()</code> to get the substring after the <code>#</code> and <code>strip()</code> to get rid of the extra spaces</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T23:08:57.440", "Id": "43854", "Score": "0", "body": "Point1 ,Point2 and Point3 are very valid. Thanks for pinting those out. Point 4: `print ' '.join(line.split()) print line[line.find(\"#\") + 1:].strip()` give the following output `Time Taken for writing this# 0 days 0 hrs 0 min 14 sec\nTime Taken for writing this# 0 days 0 hrs 0 min 14 sec` I prefer first to the second as it looks better formatted." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T08:58:17.273", "Id": "28070", "ParentId": "28067", "Score": "0" } }, { "body": "<p>as you say, it does look like this code is doing exactly what you want. But it also looks like you are repeating yourself in a couple of places.</p>\n\n<p>If it was me, I would prefer to loop through the file only once and check for both <code>Sample Text</code> and <code>Time Taken</code> at the same time, and then only print out if the sample text is there:</p>\n\n<pre><code>def my_read(my_text):\n time_taken, sample_text = False, False\n with open(my_text) as f:\n for i in f:\n time_taken = ' '.join(i.split()) if 'Time Taken' in i else time_taken\n sample_text = 'I have found it!' if 'Sample Text' in i else sample_text\n\n # now, if sample text was found, print out\n if sample_text:\n print sample_text\n print time_taken\n return\n\nmy_read('MyText.txt')\n</code></pre>\n\n<p>By testing for both, you avoid having to use <code>f.seek(0)</code> and start looping through the file again. Of course, this is based on the sample input above - and assumes that there isn't multiple lines with 'Time taken' or 'Sample Text' in them. </p>\n\n<p>Hope this helps</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T09:14:53.973", "Id": "28071", "ParentId": "28067", "Score": "1" } } ]
{ "AcceptedAnswerId": "28071", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-03T06:10:09.127", "Id": "28067", "Score": "4", "Tags": [ "python", "beginner", "file", "python-2.x" ], "Title": "Text file reading and printing data" }
28067
<p>I was doing a standard problem of DP (dynamic programming) on SPOJ <a href="http://www.spoj.com/problems/EDIST/" rel="nofollow">Edit Distance</a> using Python. </p> <pre><code>t = raw_input() for i in range(int(t)): a,b = raw_input(),raw_input() r = len(a) c = len(b) x = [[0]*(c+1) for j in range(r+1)] for j in range(c+1): x[0][j] = j for j in range(r+1): x[j][0] = j for j in range(1,r+1): for k in range(1,c+1): if(b[k-1]!=a[j-1]): x[j][k] = min(x[j-1][k-1]+1,x[j-1][k]+1,x[j][k-1]+1) else: x[j][k] = min(x[j-1][k-1],x[j-1][k]+1,x[j][k-1]+1) print x[r][c] </code></pre> <p>The solution I have proposed is giving T.L.E (Time Limit Exceeded) even though I am using D.P. Is there any way to optimize it further in terms of time complexity or with respect to any feature of Python 2.7 such as input and output?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T17:09:26.710", "Id": "43986", "Score": "1", "body": "you can group these things into descriptive functions, moving some of the arguments into variables would help because they would give a hint to the intent of them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T22:46:46.090", "Id": "44004", "Score": "0", "body": "this works pretty quickly for me; are you testing it on very long strings?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T06:39:51.390", "Id": "44007", "Score": "0", "body": "@Stuart the max size of strings are 2000 characters....... I don't think we can improve the solution algorithmically but can we improve it with respect to some feature of python like fast input/output,etc.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T09:07:49.540", "Id": "44012", "Score": "0", "body": "ah. because they run it on the slow cluster and presumably use long strings. You could look in to improving the algorithm with something like `collections.deque` - I doubt the input/output methods will make much difference. But I see no one has solved this problem with python yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T09:14:55.397", "Id": "44013", "Score": "0", "body": "@stuart you can go to the best solutions for this problem and see that there are two python solutions..... how can we use **collections.deque** ????" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T09:53:08.647", "Id": "44014", "Score": "0", "body": "Sorry, yes, you're right. I noted with your solution that in each iteration you are only accessing a certain part of `x`, and that this could be done by manipulating a deque instead of a list of lists, and might be faster. I doubt it would bring the speed improvement you need though. The fastest solution is 2.65s which must be using a much better algorithm, probably with more use of special data types and libraries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T12:43:47.547", "Id": "44098", "Score": "0", "body": "Checking the forums, [psyco](http://psyco.sourceforge.net/) was available on spoj in the past but has now been disabled. This may make it hard to achieve times using Python that were possible up until last year." } ]
[ { "body": "<p>I don't think there is much to improve in terms of performance. However, you could make the code a whole lot more self-descriptive, e.g. using better variable names, and moving the actual calculation into a function that can be called with different inputs. Here's my try:</p>\n\n<pre><code>def min_edit_distance(word1, word2, subst=1):\n len1, len2 = len(word1), len(word2)\n med = [[0] * (len2 + 1) for j in range(len1 + 1)]\n for j in xrange(len1 + 1):\n for k in xrange(len2 + 1):\n if min(j, k) == 0:\n med[j][k] = max(j, k) # initialization\n else:\n diag = 0 if word1[j-1] == word2[k-1] else subst\n med[j][k] = min(med[j-1][k-1] + diag, # substite or keep\n med[j-1][k ] + 1, # insert\n med[j ][k-1] + 1) # delete\n return med[len1][len2]\n</code></pre>\n\n<p>Main points:</p>\n\n<ul>\n<li>move the actual calculation into a function, for reusability</li>\n<li>use more descriptive names instead of one-letter variables</li>\n<li>different calculations of minimum edit distance use different costs for substitutions -- sometimes <code>1</code>, sometimes <code>2</code> -- so this could be a parameter</li>\n<li>unless I'm mistaken the <code>min</code> in your <code>else</code> is not necessary; <code>x[j-1][k-1]</code> will always be the best</li>\n<li>the two initialization loops can be incorporated into the main double-loop. (Clearly this is a question of taste. Initialization loops are more typical for DP, while this variant is closer to the <a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance#Definition\" rel=\"nofollow\">definition</a>.)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T10:08:21.643", "Id": "28223", "ParentId": "28167", "Score": "1" } }, { "body": "<p>I've solved that problem in java and c++ (<a href=\"http://www.spoj.com/ranks/EDIST/\" rel=\"nofollow\">2nd and 3th places</a> in best solutions category :) so I can compare the local and the remote execution time in order to see - how much faster should be your solution in order to pass.</p>\n\n<p>So, the local execution time of my java solution is 78 ms for the <a href=\"http://pastebin.com/5Q9h5dRK\" rel=\"nofollow\">such testcase</a> (10 pairs x 2000 chars), the robot's time is 500 ms, so my PC is ~6.5 times faster. Then the following python DP solution takes 3.6 seconds on my PC so, it would take ~23.5 seconds on the remote PC. So if the remote time limit 15 seconds, the following solution <strong>must be minimum ~ 1.56 times faster</strong> in order to pass. Ufff.... </p>\n\n<pre><code>import time\n\ntry:\n # just to see the Python 2.5 + psyco speed - 17 times faster than Python 2.7 !!!\n import psyco\n psyco.full()\nexcept:\n pass\n\ndef editDistance(s1, s2):\n if s1 == s2: return 0 \n if not len(s1):\n return len(s2)\n if not len(s2):\n return len(s1)\n if len(s1) &gt; len(s2):\n s1, s2 = s2, s1\n r1 = range(len(s2) + 1)\n r2 = [0] * len(r1)\n i = 0\n for c1 in s1:\n r2[0] = i + 1\n j = 0\n for c2 in s2:\n if c1 == c2:\n r2[j+1] = r1[j]\n else:\n a1 = r2[j]\n a2 = r1[j]\n a3 = r1[j+1]\n if a1 &gt; a2:\n if a2 &gt; a3:\n r2[j+1] = 1 + a3\n else:\n r2[j+1] = 1 + a2\n else:\n if a1 &gt; a3:\n r2[j+1] = 1 + a3\n else:\n r2[j+1] = 1 + a1\n j += 1\n aux = r1; r1 = r2; r2 = aux\n i += 1\n return r1[-1] \n\nif __name__ == \"__main__\": \n st = time.time()\n t = raw_input() \n for i in range(int(t)): \n a, b = raw_input(), raw_input()\n print editDistance(a, b)\n #print \"Time (s): \", time.time()-st\n</code></pre>\n\n<p>What I can say - It's very very hard or may be impossible to pass that puzzle using Python and DP approach (using java or c++ - peace of cake). Wait, wait - ask you - what about that two guys <a href=\"http://www.spoj.com/ranks/EDIST/lang=PYTH%202.7\" rel=\"nofollow\">that passed using python</a>? Ok, the answer is easy - they use something different. What's exactly? Something that <a href=\"http://google-web-toolkit.googlecode.com/svn-history/r8941/trunk/dev/core/src/com/google/gwt/dev/util/editdistance/MyersBitParallelEditDistance.java\" rel=\"nofollow\">I've used for java solution</a> I think. That stuff just blows away the competitors....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:36:27.337", "Id": "44175", "Score": "0", "body": "Thanks @cat_baxter i am not much familiar with java but i will try and look into the algo part of that java solution and try to implement it in python if possible ...." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T14:05:30.273", "Id": "28253", "ParentId": "28167", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T15:29:13.203", "Id": "28167", "Score": "2", "Tags": [ "python", "algorithm", "python-2.x", "time-limit-exceeded", "edit-distance" ], "Title": "Optimizing SPOJ edit distance solution" }
28167
<p>I'm trying to find the closest point (Euclidean distance) from a user-inputted point to a list of 50,000 points that I have. Note that the list of points changes all the time. and the closest distance depends on when and where the user clicks on the point.</p> <pre><code>#find the nearest point from a given point to a large list of points import numpy as np def distance(pt_1, pt_2): pt_1 = np.array((pt_1[0], pt_1[1])) pt_2 = np.array((pt_2[0], pt_2[1])) return np.linalg.norm(pt_1-pt_2) def closest_node(node, nodes): pt = [] dist = 9999999 for n in nodes: if distance(node, n) &lt;= dist: dist = distance(node, n) pt = n return pt a = [] for x in range(50000): a.append((np.random.randint(0,1000),np.random.randint(0,1000))) some_pt = (1, 2) closest_node(some_pt, a) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T15:56:12.700", "Id": "168904", "Score": "2", "body": "I was working on a similar problem and found [this](http://stackoverflow.com/questions/10818546/finding-index-of-nearest-point-in-numpy-arrays-of-x-and-y-coordinates). Also, [`Scipy.spatial.KDTree`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html) is the way to go for such approaches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-12T06:14:33.830", "Id": "176604", "Score": "0", "body": "The part that says \"the list changes all the time\" can be expanded a bit, which might hint some ideas to increase the code performance maybe. Is the list updated randomly, or some points are added every some-seconds, and some points are lost?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-17T01:19:41.270", "Id": "353293", "Score": "0", "body": "The ball tree method in scikit-learn does this efficiently if the same set of points has to be searched through repeatedly. The points are sorted into a tree structure in a preprocessing step to make finding the closest point quicker. http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.BallTree.html" } ]
[ { "body": "<p>It will certainly be faster if you vectorize the distance calculations:</p>\n\n<pre><code>def closest_node(node, nodes):\n nodes = np.asarray(nodes)\n dist_2 = np.sum((nodes - node)**2, axis=1)\n return np.argmin(dist_2)\n</code></pre>\n\n<p>There may be some speed to gain, and a lot of clarity to lose, by using one of the dot product functions:</p>\n\n<pre><code>def closest_node(node, nodes):\n nodes = np.asarray(nodes)\n deltas = nodes - node\n dist_2 = np.einsum('ij,ij-&gt;i', deltas, deltas)\n return np.argmin(dist_2)\n</code></pre>\n\n<p>Ideally, you would already have your list of point in an array, not a list, which will speed things up a lot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T03:28:57.380", "Id": "44073", "Score": "1", "body": "Thanks for the response, do you mind explaining why the two methods are faster? I'm just curious as I don't come from a CS background" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T03:54:36.320", "Id": "44074", "Score": "6", "body": "Python for loops are very slow. When you run operations using numpy on all items of a vector, there are hidden loops running in C under the hood, which are much, much faster." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T23:25:23.140", "Id": "28210", "ParentId": "28207", "Score": "41" } }, { "body": "<p>All your code could be rewritten as:</p>\n\n<pre><code>from numpy import random\nfrom scipy.spatial import distance\n\ndef closest_node(node, nodes):\n closest_index = distance.cdist([node], nodes).argmin()\n return nodes[closest_index]\n\na = random.randint(1000, size=(50000, 2))\n\nsome_pt = (1, 2)\n\nclosest_node(some_pt, a)\n</code></pre>\n\n<hr>\n\n<p>You can just write <code>randint(1000)</code> instead of <code>randint(0, 1000)</code>, the documentation of <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html\" rel=\"noreferrer\"><code>randint</code></a> says:</p>\n\n<blockquote>\n <p>If <code>high</code> is <code>None</code> (the default), then results are from <code>[0, low)</code>.</p>\n</blockquote>\n\n<p>You can use the <code>size</code> argument to <code>randint</code> instead of the loop and two function calls. So:</p>\n\n<pre><code>a = []\nfor x in range(50000):\n a.append((np.random.randint(0,1000),np.random.randint(0,1000)))\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>a = np.random.randint(1000, size=(50000, 2))\n</code></pre>\n\n<p>It's also much faster (twenty times faster in my tests).</p>\n\n<hr>\n\n<p>More importantly, <code>scipy</code> has the <code>scipy.spatial.distance</code> module that contains the <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist\" rel=\"noreferrer\"><code>cdist</code></a> function:</p>\n\n<blockquote>\n <p><code>cdist(XA, XB, metric='euclidean', p=2, V=None, VI=None, w=None)</code></p>\n \n <p>Computes distance between each pair of the two collections of inputs.</p>\n</blockquote>\n\n<p>So calculating the <code>distance</code> in a loop is no longer needed.</p>\n\n<p>You use the for loop also to find the position of the minimum, but this can be done with the <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.argmin.html\" rel=\"noreferrer\"><code>argmin</code></a> method of the <code>ndarray</code> object.</p>\n\n<p>Therefore, your <code>closest_node</code> function can be defined simply as:</p>\n\n<pre><code>from scipy.spatial.distance import cdist\n\ndef closest_node(node, nodes):\n return nodes[cdist([node], nodes).argmin()]\n</code></pre>\n\n<hr>\n\n<p>I've compared the execution times of all the <code>closest_node</code> functions defined in this question:</p>\n\n<pre><code>Original:\n1 loop, best of 3: 1.01 sec per loop\n\nJaime v1:\n100 loops, best of 3: 3.32 msec per loop\n\nJaime v2:\n1000 loops, best of 3: 1.62 msec per loop\n\nMine:\n100 loops, best of 3: 2.07 msec per loop\n</code></pre>\n\n<p>All vectorized functions perform hundreds of times faster than the original solution.</p>\n\n<p><code>cdist</code> is outperformed only by the second function by Jaime, but only slightly.\nCertainly <code>cdist</code> is the simplest.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-14T22:58:57.373", "Id": "134918", "ParentId": "28207", "Score": "20" } }, { "body": "<p>By using a <a href=\"https://en.wikipedia.org/wiki/K-d_tree\" rel=\"nofollow noreferrer\">kd-tree</a> computing the distance between all points it's not needed for this type of query. It's also <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html\" rel=\"nofollow noreferrer\">built in into scipy</a> and can speed up these types of programs enormously going from O(n^2) to O(log n), if you're doing many queries. If you only make one query, the time constructing the tree will dominate the computation time.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from scipy.spatial import KDTree\nimport numpy as np\nn = 10\nv = np.random.rand(n, 3)\nkdtree = KDTree(v)\nd, i = kdtree.query((0,0,0))\nprint(&quot;closest point:&quot;, v[i])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T13:48:07.273", "Id": "255890", "ParentId": "28207", "Score": "1" } } ]
{ "AcceptedAnswerId": "28210", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T20:19:34.250", "Id": "28207", "Score": "47", "Tags": [ "python", "performance", "numpy", "clustering" ], "Title": "Finding the closest point to a list of points" }
28207
<p>Is there a way to make this more pythonic?</p> <pre><code>def money(): current_salary = float(input("What is your current salary? ")) years = int(input("How many years would you like to look ahead? ")) amount_of_raise = float(input("What is the average percentage raise you think you will get? ")) * 0.01 for years in range(1, years + 1): current_salary += current_salary * amount_of_raise print('Looks like you will be making', current_salary,' in ', years,'years.') money() </code></pre>
[]
[ { "body": "<p>Maybe you could write: </p>\n\n<p>Instead of <code>print('Looks like you will be making', current_salary,' in ', years,'years.')</code> you could write <code>print('Looks like you will be making %d in %d years.') % (current_salary, years)</code></p>\n\n<p>Also, and this one is kind of important, you should check the input before converting it to an <code>int</code> or <code>float</code> (maybe the user goes crazy and throws a string just for the fun of it). You could maybe do that with a <code>try: ... except:</code> block.</p>\n\n<p>And just to be nitpicky, what's your position on quotes? Do you use single or you use double?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T23:09:44.183", "Id": "44061", "Score": "0", "body": "Your first point seems to have missed that he's using the variable years in the output. So your suggestions don't seem to make sense there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T23:18:32.793", "Id": "44062", "Score": "0", "body": "You're right, sorry about that. Edited." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T02:57:00.980", "Id": "44072", "Score": "0", "body": "Hi Paul, I actually do plan to add in a type check as I'm a fan of error checking I just haven't done that yet. I just like to write efficient code and make checks along the way. So regarding the quotes, I don't really have a position. Even though I say that, if I'm right, to quote within there I would have to use double and single quotes so I am probably more likely to use double and then use single as necessary. I'm REALLY new to all of this so I appreciate your input." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T22:59:09.947", "Id": "28209", "ParentId": "28208", "Score": "2" } }, { "body": "<p>Not sure if that it would make things more pythonic but here are 2 comments to make things less awkward.</p>\n\n<p>You might want to rename your variable name in <code>for years in range(1, years + 1):</code> for something like <code>for year in range(1, years + 1):</code>.</p>\n\n<p>It might make sense to use an additional variable to make things slighly clearer in your calculations:</p>\n\n<pre><code>def money():\n # TODO : Add error handling on next 3 lines\n current_salary = float(input(\"What is your current salary? \"))\n years = int(input(\"How many years would you like to look ahead? \"))\n amount_of_raise = float(input(\"What is the average percentage raise you think you will get? \"))\n coeff = 1 + amount_of_raise * 0.01\n\n for year in range(1, years + 1):\n current_salary *= coeff\n print('Looks like you will be making', current_salary,' in ', year,'years.')\nmoney()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T00:56:43.977", "Id": "28211", "ParentId": "28208", "Score": "2" } }, { "body": "<ul>\n<li>As others have noted, you'll probably want to do some error-checking on your inputs, which means writing a helper function to handle your prompts.</li>\n<li>You're writing a program that handles money and using binary floats, which are designed for scientific calculations. You are likely to run into a variety of small calculation errors! Python has a decimal module for calculations involving money. This will also make your input-handling easier.</li>\n<li>Don't reuse \"years\" as the iterator in the for loop when you already have a variable with that name. It works here, but only by luck.</li>\n<li>Prefer the format() method to straight concatenation. In this case it allows you to easily print your numbers with comma separators.</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>from decimal import * \n\ndef get_decimal(prompt):\n while True:\n try:\n answer = Decimal(input(prompt + \" \"))\n return answer\n except InvalidOperation:\n print(\"Please input a number!\")\n\ndef money():\n current_salary = get_decimal(\"What is your current salary?\")\n years = int(get_decimal(\"How many years would you like to look ahead?\"))\n percent_raise = get_decimal(\"What is the average percentage raise you think you will get?\") * Decimal(\"0.01\")\n for year in range(1, years+1):\n current_salary += percent_raise * current_salary\n line = \"Looks like you will be making ${0:,.2f} in {1} years.\".format(current_salary, year)\n print(line)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T16:41:12.663", "Id": "44184", "Score": "0", "body": "`from <module> import *` is discouraged because it can cause namespace collisions and gives static analyzers a hard time determining where a name originates from. `from decimal import Decimal` is better." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T04:35:25.867", "Id": "28220", "ParentId": "28208", "Score": "4" } }, { "body": "<p>I would use a docstring and split the method to even smaller ones</p>\n\n<pre><code>def money():\n \"\"\"Print Expectations on Salary\"\"\"\n salary, delta, perc_raise = get_user_input()\n expectations = calculate_expectations(salary, delta, perc_raise)\n print_expectations(expectations)\n\nmoney()\n</code></pre>\n\n<p>And I would store the expectations in a List</p>\n\n<pre><code>def calculate_expectations(salary, delta_max, perc_raise):\n \"\"\"Calculate Expectations on Salary\"\"\"\n [salary*(1+perc_raise/100)**delta for delta in range(1, delta_max + 1)]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T10:09:46.903", "Id": "44227", "Score": "0", "body": "@codesparcle Thank you for the hint. I've edited my answer and renamed the variable to perc_raise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T16:18:03.637", "Id": "28230", "ParentId": "28208", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T22:09:19.470", "Id": "28208", "Score": "2", "Tags": [ "python" ], "Title": "Calculate cumulative salary including raises" }
28208
<p>I am currently going through Codecademy's Python course (I don't come from a coding background but I'm thoroughly enjoying it) and I got to the end of one of the sections and thought, "Well it worked, but that seemed wildly inefficient." I tried shortening unnecessary parts and came up with this:</p> <pre><code>lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } classlist = [lloyd, alice, tyler] # Add your function below! def get_average(student): average_homework = sum(student["homework"]) / len(student["homework"]) average_quizzes = sum(student["quizzes"]) / len(student["quizzes"]) average_tests = sum(student["tests"]) / len(student["tests"]) average_total = average_homework * 0.1 + average_quizzes * 0.3 + average_tests * 0.6 return average_total def get_letter_grade(score): if score &gt;= 90: return "A" if score &lt; 90 and score &gt;= 80: return "B" if score &lt; 80 and score &gt;= 70: return "C" if score &lt; 70 and score &gt;= 60: return "D" else: return "F" def get_class_average(classlist): a = [] for student in classlist: a.append(get_average(student)) return sum(a) / len(a) get_class_average(classlist) </code></pre> <p>Now this bit works, but I was wondering if there are more places I could trim the code down without losing the functionality (I'm guessing there is in the get_average function but the things I tried came back as errors because of the "name" field in the dictionary). Codecademy seems good for learning the fundamentals, but I wanted to get some insight into the "best" way to do things. Should I not worry about reworking functional code to be more efficient at first and just learn the fundamentals, or should I keep trying to make the "best" code as I learn?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T14:50:32.037", "Id": "44104", "Score": "1", "body": "Can you add information about the problem you are trying to solve ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:06:50.560", "Id": "44106", "Score": "0", "body": "@Josay Actually he isn't trying to solve any problem. This is the part of the python track on codecademy.com. One introducing to dictionary in Python." } ]
[ { "body": "<ul>\n<li>In the function <code>get_letter_grade</code> you were checking more conditions then necessary. Try to follow the logical difference between your function and my code. It is simple math which I used to optimize it. Also structuring it as an if-elif-...-else is better for readability.</li>\n<li>In <code>get_average</code> and <code>get_class_average</code> I use a thing called list comprehension. A simple google search will tell you what it is and why it is better. Google it in python tutorials if you have problem.</li>\n</ul>\n\n<p><strong>Edited Functions</strong></p>\n\n<pre><code>def average(values):\n return sum(values) / len(values)\n\ndef get_average(student):\n keys = ['homework', 'quizzes', 'tests']\n factors = [0.1, 0.3, 0.6]\n return sum([ average(student[key]) * factor for key, factor in zip(keys, factors)])\n\ndef get_letter_grade(score):\n if score &gt;= 90:\n return \"A\"\n elif score &gt;= 80:\n return \"B\"\n elif score &gt;= 70:\n return \"C\"\n elif score &gt;= 60:\n return \"D\"\n else:\n return \"F\"\n\ndef get_class_average(classlist):\n return average([get_average(student) for student in classlist])\n\nget_class_average(classlist)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:21:45.747", "Id": "44109", "Score": "0", "body": "I would vote you up, but I don't have 15 reputation. This is exactly what I was meaning. It works to Codeacademy standards, but could easily be refined. Thanks for the list comprehension pointer as well!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:34:22.833", "Id": "44110", "Score": "0", "body": "@Raynman37 Edited the answer a bit more. Try to figure out how the return statement of `get_average` works. Yeah you cannot vote up but you can [accept an answer](http://codereview.stackexchange.com/help/accepted-answer)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:34:48.043", "Id": "44111", "Score": "3", "body": "Actually you don't need a list-comprehension. A generator expression works too, and avoids the creation of the intermediate `list`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:39:42.170", "Id": "44112", "Score": "0", "body": "@Bakuriu Yeah that would have been better. There are two reasons I didn't do that. FIrstly, the OP is a beginner and I don't think introducing generators to a beginner would be a good idea. Secondly, I am not much experienced in Python either so my explanation might not have been the best. If he is interested here is a [link to a question on stackoverflow](http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:42:08.100", "Id": "44113", "Score": "0", "body": "@AseemBansal I'm not sure I understand the xrange part. Is that just so it loops 3 times? The rest I get after following it through all the steps." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:43:48.013", "Id": "44114", "Score": "0", "body": "@Bakuriu thanks as well! I'll look into that too. This is really what I wanted, to get extra things that I can go read about to expand my understanding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:45:28.740", "Id": "44115", "Score": "0", "body": "Yeah. The value of i goes from 0 upto 3 i.e. 0,1,2. Try to figure out what is keys[0], keys[1] and key[2]. Similarly for factors. The best way to understand is to take pen and paper and write these values. It might be helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:48:47.130", "Id": "44116", "Score": "0", "body": "@Raynman37 If you want to know extra things then I would suggest you to go [here](http://docs.python.org/2/index.html). It has the entire Python. In this the tutorial part is especially useful for beginners. It might be more useful than reading advanced material in the beginning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:50:47.273", "Id": "44117", "Score": "0", "body": "@AseemBansal I will definitely take a look at that. Thanks! I kind of figured the only way to refine it past what you do on code academy would be to start using more advanced things. I'll keep this bit of code for later and come back to it after I learn more techniques." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T03:19:03.903", "Id": "44136", "Score": "1", "body": "I would have used ``zip`` in ``get_average()``: ``return sum([average(student[key]) * factor for key, factor in zip(keys, factors)])``." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T14:57:48.720", "Id": "28227", "ParentId": "28226", "Score": "1" } }, { "body": "<p>Defining an <code>average</code> function (based on <a href=\"https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list\">this</a>), you could have things slightly clearer :</p>\n\n<pre><code>def average_list(l)\n return sum(l) / float(len(l))\n\ndef average_student(student):\n average_homework = average_list(student[\"homework\"])\n average_quizzes = average_list(student[\"quizzes\"])\n average_tests = average_list(student[\"tests\"])\n average_total = average_homework * 0.1 + average_quizzes * 0.3 + average_tests * 0.6\n return average_total\n\ndef class_average(students):\n return average_list([average_student(s) for s in students])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:07:57.283", "Id": "44107", "Score": "0", "body": "You are not using the description in the link that you provided. You just added a function call which can be used in the other function as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:52:27.583", "Id": "44118", "Score": "0", "body": "Actually I was talking about using `reduce` and `lambda`. Anyways you don't need to use `float` in the `average_list` function either. All the values are `float` already so sum would also be. Implicit conversion so explicit isn't needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T17:49:21.100", "Id": "44124", "Score": "1", "body": "@Josay Are we supposed to use `class` in the class_average section because it's already a built in Python term (I don't know what you'd call it officially)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T18:54:44.100", "Id": "44126", "Score": "0", "body": "Raynman37 : As per http://docs.python.org/release/2.5.2/ref/keywords.html this is a valid comment. It completely went out of my mind but I'm going to change this." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T14:58:00.580", "Id": "28228", "ParentId": "28226", "Score": "0" } }, { "body": "<p>In average_student, you're manually iterating over the keys in a dictionary, and you've hardcoded the weights of the various parts. What if you want to add a \"presentation\" component to the grade? You've got a lot of places to touch.</p>\n\n<p>Consider exporting the hardcoded information into its own dictionary, and iterating over the keys in that dictionary:</p>\n\n<pre><code>weights = {\n \"homework\": 0.1,\n \"quizzes\": 0.3,\n \"tests\": 0.6\n}\n\ndef get_average(student):\n return sum(average(student[section]) * weights[section] for section in weights)\n\ndef average(x):\n return sum(x)/len(x)\n</code></pre>\n\n<p>In terms of learning Python, I'd definitely agree with your instinct -- you should keep trying to make your code as clean as possible even while completing exercises. When you're learning fundamentals, it's that much more important to understand good structure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T16:10:53.630", "Id": "44120", "Score": "0", "body": "Is this the `get_average` function? I tried but couldn't run it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T17:40:04.553", "Id": "44122", "Score": "0", "body": "Oops! I had a syntax brainfart. Fixed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T17:45:11.850", "Id": "44123", "Score": "0", "body": "@llb Thanks for this input too! `get_average` was the section I didn't like when I got done with it either. Exactly like you said that whole section was basically hardcoded in there. I'll definitely be playing with this today as well!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T15:45:34.337", "Id": "28229", "ParentId": "28226", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-06T22:32:45.643", "Id": "28226", "Score": "0", "Tags": [ "python" ], "Title": "Calculating student and class averages" }
28226
<p>Say I have <code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code> and I want to spread it across - at most - 4 columns. The end result would be: <code>[[1, 2, 3], [4, 5], [6, 7], [8, 9]]</code>. So I made this:</p> <pre><code>item_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] item_count = len(item_list) column_count = item_count if item_count &lt;= 4 else 4 items_per_column = int(item_count / 4) extra_items = item_count % 4 item_columns = [] for group in range(column_count): count = items_per_column if group &lt; extra_items: count += 1 item_columns.append(item_list[:count]) item_list = item_list[count:] </code></pre> <p>Is there a nicer way of accomplishing this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T09:32:37.943", "Id": "44142", "Score": "0", "body": "What are the constraints ? I assume that : 1) a column cannot be be bigger than a column on its left 2) the maximum size difference between two columns must be 0 or 1 3) the element should stay in the same order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T09:34:49.140", "Id": "44143", "Score": "0", "body": "Also, I guess the list in your question should be [1, 2, 3, 4, 5, 6, 7, 8, 9] and not [1, 2, 3, 4, 5, 7, 8, 9]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T10:18:32.023", "Id": "44145", "Score": "0", "body": "@Josay Correct on all accounts. It should attempt to spread everything evenly, left -> right, maintaining order and I've fixed my list, thanks." } ]
[ { "body": "<p>How about using generators? </p>\n\n<ul>\n<li>It puts the whole thing in a function which in <a href=\"https://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function\">itself is a performance boost</a>. </li>\n<li>List comprehension are better compared to list creation and appending. See the part Loops and avoiding dots.. in <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow noreferrer\">here</a></li>\n<li>An extra variable isn't needed for the length of the list as <a href=\"http://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">it is <code>O(1)</code> operation</a>.</li>\n<li>You don't need to use the <code>int</code> function. It will be an <code>int</code> in this case.</li>\n</ul>\n\n<p><strong>My Suggested Code</strong></p>\n\n<pre><code>def get_part(item_list):\n items_per_column = len(item_list) / 4\n extra_items = len(item_list) % 4\n\n if len(item_list) &lt;= 4:\n column_count = len(item_list)\n else:\n column_count = 4\n\n for i in xrange(column_count):\n if i &lt; extra_items:\n yield item_list[i * (items_per_column + 1) : (i + 1) * (items_per_column + 1)]\n else:\n yield item_list[i * items_per_column : (i + 1) * items_per_column]\n\nitem_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nitem_columns = [i for i in get_part(item_list)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T18:16:08.537", "Id": "28258", "ParentId": "28244", "Score": "0" } }, { "body": "<p>You could do something like this (elegant, but not the fastest approach)</p>\n\n<pre><code>item_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nmin_height = len(item_list) // 4\nmod = len(item_list) % 4\n\nheights = [min_height + 1] * mod + [min_height] * (4 - mod)\nindices = [sum(heights[:i]) for i in range(4)]\ncolumns = [item_list[i:i+h] for i, h in zip(indices, heights)]\n</code></pre>\n\n<p>Or a compressed version:</p>\n\n<pre><code>columns = [item_list[\n min_height * i + (i &gt;= mod) * mod :\n min_height * (i+1) + (i+1 &gt;= mod) * mod]\n for i in range(4)]\n</code></pre>\n\n<p>I guess the fastest way would be similar to what you already have:</p>\n\n<pre><code>index = 0\ncolumns = []\nfor i in xrange(4):\n height = min_height + (i &lt; mod)\n columns.append(item_list[index:index+height])\n index += height\n</code></pre>\n\n<p>(With both of these, if there are less than 4 items you get empty columns at the end.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-10T04:35:45.980", "Id": "44341", "Score": "0", "body": "o.O I didn't know `(1 + True) == 2`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-10T18:04:53.113", "Id": "44381", "Score": "0", "body": "it's hacky but True and False become 1 or 0 when mixed with numbers." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T19:51:04.863", "Id": "28304", "ParentId": "28244", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-08T08:27:11.953", "Id": "28244", "Score": "1", "Tags": [ "python" ], "Title": "Taking a list and using it to build columns" }
28244
<p>I want to abstract away differences between <a href="http://docs.python.org/2/library/zipfile.html" rel="nofollow">zipfile</a> and <a href="https://pypi.python.org/pypi/rarfile/" rel="nofollow">rarfile</a> modules. In my code i want to call <code>ZipFile</code> or <code>RarFile</code> constructors depending on file format. Currently i do it like that.</p> <pre><code>def extract(dir, f, archive_type): ''' archive_type should be 'rar' or 'zip' ''' images = [] if archive_type == 'zip': constructor = zipfile.ZipFile else: constructor = rarfile.RarFile with directory(dir): with constructor(encode(f)) as archive: archive.extractall() os.remove(f) images = glob_recursive('*') return images </code></pre> <p>Is there any more elegant way for dynamic object calling?</p>
[]
[ { "body": "<p>Classes are first-class objects in Python.</p>\n\n<pre><code>amap = {\n 'zip': zipfile.ZipFile,\n 'rar': rarfile.RarFile\n}\n\n ...\n\nwith amap[archive_type](encode(f)) as archive:\n ...\n</code></pre>\n\n<p>or</p>\n\n<pre><code>with amap.get(archive_type, rarfile.RarFile)(encode(f)) as archive:\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T09:19:30.730", "Id": "28277", "ParentId": "28275", "Score": "4" } } ]
{ "AcceptedAnswerId": "28277", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T09:02:56.733", "Id": "28275", "Score": "1", "Tags": [ "python", "constructor" ], "Title": "Dynamic object creation in Python" }
28275
<p>My aim is to sort a list of strings where words have to be sorted alphabetically. Words starting with <code>s</code> should be at the start of the list (they should be sorted as well), followed by the other words.</p> <p>The below function does that for me.</p> <pre><code>def mysort(words): mylist1 = sorted([i for i in words if i[:1] == "s"]) mylist2 = sorted([i for i in words if i[:1] != "s"]) list = mylist1 + mylist2 return list </code></pre> <p>I am looking for better ways to achieve this, or if anyone can find any issues with the code above.</p>
[]
[ { "body": "<p>For this snippet, I would have probably written the more compact:</p>\n\n<pre><code>def mysort(words):\n return (sorted([i for i in words if i[0] == \"s\"]) +\n sorted([i for i in words if i[0] != \"s\"]))\n</code></pre>\n\n<p>(You're not supposed to align code like this in Python, but I tend to do it anyway.) Note that I wrote <code>i[0]</code> and not <code>i[:1]</code> - I think the former is clearer. Using <code>str.startswith()</code> is even better.</p>\n\n<p>Also, it is generally considered bad practice to use <code>list</code> as a variable name.</p>\n\n<p>However, your algorithm iterates the list at least three times: Once to look for the words starting with <code>s</code>, once to look for the words <em>not</em> starting with <code>s</code> and then finally <code>O(n log n)</code> times more to sort the two lists. If necessary, you can improve the algorithm to do just one pass before sorting, by populating both lists simultaneously:</p>\n\n<pre><code>def prefix_priority_sort(words, special_prefix = \"s\"):\n begins_with_special = []\n not_begin_with_special = []\n\n for word in words:\n if word.startswith(special_prefix):\n begins_with_special.append(word)\n else:\n not_begin_with_special.append(word)\n\n return sorted(begins_with_special) + sorted(not_begin_with_special)\n</code></pre>\n\n<p>However, the best way is to define your own comparator and pass it to the sorting function, like <code>mariosangiorgio</code> suggests. In Python 3, you need to pass in a <em>key</em> function, <a href=\"http://docs.python.org/3.1/library/functions.html#sorted\" rel=\"nofollow\">see the docs for details</a>, or <a href=\"http://python3porting.com/preparing.html#keycmp-section\" rel=\"nofollow\">this article</a>.</p>\n\n<p>Depending on execution speed requirements, list sizes, available memory and so on, you <em>might</em> want to pre-allocate memory for the lists using <code>[None] * size</code>. In your case it is probably premature optimization, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:04:16.123", "Id": "44583", "Score": "5", "body": "Note that `i[0]` will fail for empty strings, while `i[:1]` will not. Agreed that `startswith` is best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:48:22.693", "Id": "44587", "Score": "0", "body": "Your `mysort` needs another pair of parentheses, or a backslash before the newline." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T16:48:37.153", "Id": "44591", "Score": "0", "body": "@tobias_k Ah, good point!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:53:50.330", "Id": "44793", "Score": "0", "body": "What makes you say you're not supposed to align code like that? [PEP-8](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) does it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T07:33:03.253", "Id": "28402", "ParentId": "28398", "Score": "4" } }, { "body": "<p>Lastor already said what I was going to point out so I am not going to repeat that. I'll just add some other things.</p>\n\n<p>I tried timing your solution with a bunch of other solutions I came up with. Among these the one with best time-memory combination should be the function <code>mysort3</code> as it gave me best timing in nearly all cases. I am still looking about <a href=\"https://codereview.stackexchange.com/questions/28373/is-this-the-proper-way-of-doing-timing-analysis-of-many-test-cases-in-python-or\">proper timing</a> in Python. You can try putting in different test cases in the function <code>tests</code> to test the timing for yourself. </p>\n\n<pre><code>def mysort(words):\n mylist1 = sorted([i for i in words if i[:1] == \"s\"])\n mylist2 = sorted([i for i in words if i[:1] != \"s\"])\n list = mylist1 + mylist2\n return list\n\ndef mysort3(words):\n ans = []\n p = ans.append\n q = words.remove\n words.sort()\n for i in words[:]:\n if i[0] == 's':\n p(i)\n q(i)\n return ans + words\n\ndef mysort4(words):\n ans1 = []\n ans2 = []\n p = ans1.append\n q = ans2.append\n for i in words:\n if i[0] == 's':\n p(i)\n else:\n q(i)\n ans1.sort()\n ans2.sort()\n return ans1 + ans2\n\ndef mysort6(words):\n return ( sorted([i for i in words if i[:1] == \"s\"]) +\n sorted([i for i in words if i[:1] != \"s\"])\n )\n\nif __name__ == \"__main__\":\n from timeit import Timer\n def test(f):\n f(['a','b','c','abcd','s','se', 'ee', 'as'])\n\n print Timer(lambda: test(mysort)).timeit(number = 10000)\n print Timer(lambda: test(mysort3)).timeit(number = 10000)\n print Timer(lambda: test(mysort4)).timeit(number = 10000)\n print Timer(lambda: test(mysort6)).timeit(number = 10000)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T07:45:58.533", "Id": "28403", "ParentId": "28398", "Score": "1" } }, { "body": "<p>Some notes about your code:</p>\n\n<ul>\n<li><p><code>sorted([i for i in words if i[:1] == \"s\"])</code>: No need to generate an intermediate list, drop those <code>[</code> <code>]</code> and you'll get a lazy generator expression instead.</p></li>\n<li><p><code>mylist1</code>. This <code>my</code> prefix looks pretty bad. Do other languages use them?</p></li>\n<li><p><code>list</code>: Red flag. Don't overshadow a built-in (at least not one so important) with a variable.</p></li>\n<li><p><code>return list</code>. You can directly write <code>return mylist1 + mylist2</code>, no gain in naming the value you're about to return (the name of the function should inform about that).</p></li>\n<li><p><code>i[:1] == \"s\"</code> -> <code>i.startswith(\"s\")</code>.</p></li>\n</ul>\n\n<p>Now what I'd write. Using <a href=\"http://docs.python.org/2/library/functions.html#sorted\" rel=\"nofollow\">sorted</a> with the argument <code>key</code> (<a href=\"http://en.wikipedia.org/wiki/Schwartzian_transform\" rel=\"nofollow\">Schwartzian transform</a>) and taking advantage of the <a href=\"http://en.wikipedia.org/wiki/Lexicographical_order\" rel=\"nofollow\">lexicographical order</a> defined by tuples:</p>\n\n<pre><code>def mysort(words):\n return sorted(words, key=lambda word: (0 if word.startswith(\"s\") else 1, word))\n</code></pre>\n\n<p>If you are familiar with the fact that <code>False &lt; True</code>, it can be simplified a bit more:</p>\n\n<pre><code>sorted(words, key=lambda word: (not word.startswith(\"s\"), word))\n</code></pre>\n\n<p>Here's another way using the abstraction <code>partition</code>:</p>\n\n<pre><code>words_with_s, other_words = partition(words, lambda word: word.startswith(\"s\"))\nsorted(words_with_s) + sorted(other_words)\n</code></pre>\n\n<p>Writing <code>partition</code> is left as an exercise for the reader :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:00:34.030", "Id": "44580", "Score": "0", "body": "Dang, I was just writing up the same thing! +1 :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:01:15.923", "Id": "44581", "Score": "0", "body": "@tobias_k: sorry ;-) I was a bit suprised no one had proposed something similar yet, this is pretty standard stuff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T14:02:16.180", "Id": "44582", "Score": "1", "body": "No problem, but two times the same answer within 2 minutes for a 8 hours old question... how probable is this?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T13:56:20.453", "Id": "28418", "ParentId": "28398", "Score": "7" } } ]
{ "AcceptedAnswerId": "28418", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T05:46:42.197", "Id": "28398", "Score": "2", "Tags": [ "python", "sorting" ], "Title": "Sort a list in Python" }
28398
<p>While working with someone else's code I've isolated a time-killer in the (very large) script. Basically this program runs through a list of thousands and thousands of objects to find matches to an input (or many inputs) object. It works well when the number is below 50 but any input higher than that and it begins to take a looooong time. Is this just an issue with the database I'm running it against (30,000 things)? Or is this code written inefficiently?</p> <pre><code>for i in range(BestX): Tin=model[BestFitsModel[0][i]][2] Tau2=np.append(Tau2,model[BestFitsModel[0][i]][6]) Dir=model[BestFitsModel[0][i]][0] Dir=Dir.replace('inp','out',1) ##open up correct .out file T=open(Dir,"rb") hold='' Tau=[] for line in T: if not line.strip(): continue else: hold=line.split() Tau.append(hold) Tauline=0 Taunumber=0 print 'Loop' for j in range(5,len(Tau)-50): if 'RESULTS:' in Tau[j-5][0]: for k in range(j,j+50): if (Tau[k][1] == model[BestFitsModel[0][i]][6]): Tauline=i #line number of the tau Taunumber=k-(j) #Tau 1, 2, 3, etc. Dir=Dir.replace('out','stb',1)#.stb file Dir2=np.append(Dir2,Dir) F=open(Dir, "rb") hold='' Spectrum=[] for line in F: hold=line.split() Spectrum.append(hold) </code></pre> <p>BestX is a list of 30,000 objects (stars).</p> <p>I'm not looking for an answer to this problem, I'm looking for code-critique...there has to be a way to write this so that it performs faster, right?</p> <p>Thanks.</p> <p><strong>EDIT</strong>: Reading through the <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips" rel="nofollow">Python Performance Tips</a> I've noticed one little snag (so far). Starting with the line <code>Tau=[]</code> and continuing for the next six lines. I can shorten it up by </p> <pre><code>Tau=[line.split() for line in T] </code></pre> <p>I'm gonna keep looking. Hopefully I'm on the right track.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T21:34:43.993", "Id": "44608", "Score": "0", "body": "Can you clarify a bit further what this is supposed to do and what 'number' you are referring to exactly? The number of input objects? Are the stars in BestX the input objects? Also, with >50 objects, does it work slowly but correctly, or does it not work at all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T21:40:23.687", "Id": "44609", "Score": "0", "body": "Yeah, sorry for being 'nebulous' (drumroll). The BestX file is the file I'm matching my input stars to. If I put in a star it might have 5 matches in that file (I called it a database), or it could have 1000+, when it has a high number of matches it begins to get bogged down dramatically. What this does after it finds the matches -moving down the script- is computes some stellar values of some characteristic or another to give me an averaged value over all the matches for whatever property I'm searching for. I ran a lot of checks and isolated it to this exact region of the code. Need more?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T21:48:37.137", "Id": "44610", "Score": "0", "body": "@Stuart (more) these files I'm searching through are easily less than a gigabyte. That's why I think it's the code structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T22:04:38.633", "Id": "44611", "Score": "0", "body": "as a first improvement try to give the variables more descriptive names. This should make it easier to understand what's going on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T22:07:57.820", "Id": "44612", "Score": "0", "body": "Your edit improving the code actually changes what it does. What you need is `Tau = [line.split() for line in T if line.strip()]`, i.e. only include the line if it is contains something other than spaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T22:18:20.487", "Id": "44613", "Score": "0", "body": "I'm doubtful that this code actually works. If there are fewer than 56 lines in `Tau` then the loop `for j...` never actually runs. Is anything done with the variables `Tauline` and `Taunumber`? If so, is that within the `for i...` loop or afterwards? (Also, can you check the indentation as it seems wrong in what you have pasted here). I suspect what is intended is actually to break out of all three loops (i, j, and k) as soon as a match is found; but instead the loops carry on iterating regardless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T22:27:56.370", "Id": "44614", "Score": "0", "body": "Yeah this whole script is wacky. I've been working with it for a while trying to make it better, but I'm not that good so it's really really painful. I timed the script (by importing datetime) and it took roughly 38 seconds to complete and that was only working with 69 matches it found out of the larger file. I ran it with a different parameter (to boost the possible matches) and just shut it down after a few minutes out of frustration." } ]
[ { "body": "<p>Some guesswork here but I think what you want is actually something like this:</p>\n\n<pre><code>def match_something(file, match):\n \"\"\" Finds a line in file starting with 'RESULTS:' then checks the following 50\n lines for match; if it fails returns None, otherwise it returns\n how many lines down from the 'RESULTS:' heading the match is found\n \"\"\"\n in_results_section = False\n results_counter = 0\n for line in file:\n if line.strip():\n if results_header_found:\n if line.split()[1] == match:\n return results_counter # found a match\n else:\n results_counter += 1\n if results_counter &gt; 50:\n return None \n# I'm assuming in the above that there can only be one results section in each file\n\n elif line.startswith('RESULTS:'):\n results_header_found = True\n\nmatched_results = [] \nfor i in range(BestX):\n thing = model[BestFitsModel[0][i]]\n\n # make variables with descriptive names \n directory, input_thing, match = thing[0], thing[2], thing[6]\n list_of_matches = np.append(list_of_matches, match)\n with open(directory.replace('inp', 'out', 1), 'rb') as file:\n m = match_something(file, match)\n if m is not None:\n matched_results.apppend((i, m))\n stb_directory = directory.replace('inp', 'stb', 1), 'rb')\n np.append(directory_list, stb_directory)\n with open(stb_directory, 'rb') as file:\n spectrum = [line.split() for line in file] \n</code></pre>\n\n<p>This uses a function <code>match_something</code> to go through the file. As soon as a result is found, the function exits (<code>return i, results_counter</code>) and then the main loop adds this result to a list of matched results. If no result is found within 50 lines of the line starting 'RESULTS:' then the function returns None, and the loop moves to the next line of <code>BestFitsModel[0]</code>. (If, on the other hand, there can be more than one results section within each file, then you need to alter this accordingly; it should carry on checking the rest of the file rather than returning, which will be slower.) I hope it should be fairly clear what is happening in this code; it should avoid looping through anything unnecessarily (assuming I've guessed correctly what it's supposed to do)</p>\n\n<p>In the original code, it seems that the files are not closed (<code>T.close()</code>), which could cause problems later on in the programme. Using the <code>with</code> notation avoids the need for this in the above code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T23:35:48.180", "Id": "28430", "ParentId": "28428", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-12T21:21:04.760", "Id": "28428", "Score": "0", "Tags": [ "python" ], "Title": "Is there a better, more efficient way to write this loop?" }
28428
<p>It works fine, but it is slow. </p> <p>Could anybody help make this faster?</p> <pre><code>import itertools from decorators import timer from settings import MENU, CASH class Cocktail(object): def __init__(self, group, name, sell, count=0): self.group = group self.name = name self.sell = sell self.count = count class Check(object): def __init__(self, cash, menu=MENU): self.__cash = cash self.__cheapest_cocktail = 10000 self.__menu = self.__read_menu(menu) self.__matrix = self.__create_matrix() self.correct = [] def __read_menu(self, menu): result = [] for group in menu: key = group.keys()[0] for cocktail in group[key]: if self.__cheapest_cocktail &gt; cocktail['sell']: self.__cheapest_cocktail = cocktail['sell'] result.append(Cocktail( key, cocktail['name'], cocktail['sell'], )) return result def __create_matrix(self): result = [] max_count = self.__cash // self.__cheapest_cocktail for cocktail in self.__menu: row = [] for i in range(0, max_count): row.append(Cocktail( cocktail.group, cocktail.name, cocktail.sell, i )) result.append(row) return result def find_combinations(self): for check in itertools.product(*self.__matrix): if sum([(c.sell * c.count) for c in check]) == self.__cash: self.correct.append(check) check = Check(CASH) check.find_combinations() check.__matrix size 80x25 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-14T20:59:32.400", "Id": "44709", "Score": "1", "body": "Hello, could you please add some more information about what you are trying to achieve here? Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-14T21:01:49.020", "Id": "44710", "Score": "0", "body": "I try find all row combinations which sum elements equal any given number." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T06:28:25.067", "Id": "44727", "Score": "0", "body": "What is `check.__matrix size 80x25` after your code? Is it part of the code? Can you give a sample Input and output of your program so it can be easier to understand?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T06:56:50.407", "Id": "44735", "Score": "0", "body": "Probably not worth an answer but I think you should have a look at http://www.youtube.com/watch?v=o9pEzgHorH0 (I have no idea how many times I've posted a link to this video on this SE)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T07:02:26.733", "Id": "53043", "Score": "0", "body": "I believe you are trying to solve the knapsack problem, here is an example: http://rosettacode.org/wiki/Knapsack_Problem/Python" } ]
[ { "body": "<p>Take a look at <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow\">Python Performace Tips</a> and search for list comprehension. As far as I can understand your code you can use it.</p>\n\n<p>An example would be this function.</p>\n\n<pre><code>def __create_matrix(self):\n max_count = self.__cash // self.__cheapest_cocktail\n return [ [Cocktail(cocktail.group,cocktail.name,cocktail.sell,i)\n for i in xrange(0, max_count)] for cocktail in self._menu]\n</code></pre>\n\n<p>You don't need to create a list if you are not using it elsewhere. In the <code>find_combinations</code> function you can avoid the overhead of list creation because you are only interested in the sum of the elements.</p>\n\n<pre><code>def find_combinations(self):\n for check in itertools.product(*self.__matrix):\n if sum((c.sell * c.count) for c in check) == self.__cash:\n self.correct.append(check)\n</code></pre>\n\n<p>I think there is a bug in your code. You are using a class<code>Cocktail</code> but using <code>cocktail</code> in your code. I understand they are different but I think you have messed up <strong>C</strong> with <strong>c</strong> in your code in the <code>__read_menu</code> function. It is confusing whether or not you have messed it up.</p>\n\n<p>That is all I can think of because I don't understand what the code is doing unless. Please edit your question to add sample input and output.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T06:46:47.130", "Id": "28491", "ParentId": "28477", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-14T20:53:31.733", "Id": "28477", "Score": "2", "Tags": [ "python", "algorithm", "combinatorics" ], "Title": "Find all row combinations which sum elements equal to any given number" }
28477
<p>I have a <a href="https://github.com/regebro/svg.path">module in Python for dealing with SVG paths</a>. One of the problems with this is that the <a href="http://www.w3.org/TR/SVG/">SVG spec</a> is obsessed with saving characters to a pointless extent. As such, this path is valid:</p> <pre><code>"M3.4E-34-2.2e56L23-34z" </code></pre> <p>And should be parsed as follows:</p> <pre><code>"M", "3.4E-34", "-2.2e56", "L", "23", "-34", "z" </code></pre> <p>As you see, anything non-ambiguous is allowed, including separating two numbers only by a minus sign, as long as that minus-sign is not preceded by an "E" or an "e", in which case it should be interpreted as an exponent of the first number. Letters are commands (except "E" and "e" of course), and both comma and any sort of whitespace is allowed as separators.</p> <p>My module currently uses a rather ugly way of tokenizing the SVG path by multiple string replacements and then a split:</p> <pre><code>COMMANDS = set('MmZzLlHhVvCcSsQqTtAa') def _tokenize_path_replace(pathdef): # First handle negative exponents: pathdef = pathdef.replace('e-', 'NEGEXP').replace('E-', 'NEGEXP') # Commas and minus-signs are separators, just like spaces. pathdef = pathdef.replace(',', ' ').replace('-', ' -') pathdef = pathdef.replace('NEGEXP', 'e-') # Commands are allowed without spaces around. Let's insert spaces so it's # easier to split later. for c in COMMANDS: pathdef = pathdef.replace(c, ' %s ' % c) # Split the path into elements return pathdef.split() </code></pre> <p>This in fact is doing a total of 23 string replacements on the path, and this is easy, but seems like it should be slow. I tried doing this other ways, but to my surprise they were all slower. I did a character by character tokenizer, which took around 30-40% more time. A user of the module also suggested a regex:</p> <pre><code>import re TOKEN_RE = re.compile("[MmZzLlHhVvCcSsQqTtAa]|[-+]?[0-9]*\.?[0-9]+(?:[eE] [-+]?[0-9]+)?") def _tokenize_path_replace(pathdef): return TOKEN_RE.findall(pathdef) </code></pre> <p>To my surprise this was also slower than doing 23 string replacements, although just 20-30%.</p> <p>One thing that could speed up this is if the two expressions in the regex could be merged to one, but I can't find a way of doing that. If some regex guru can, that would improve things.</p> <p>Any other way of making a speedy parsing of SVG paths that I haven't though about would also be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T10:26:14.583", "Id": "44746", "Score": "1", "body": "It's not just you having trouble with slow parsing of paths: [`svgwrite` has the same problem](https://bitbucket.org/mozman/svgwrite/issue/7/parsing-of-paths-is-very-time-consuming)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T11:55:17.037", "Id": "44751", "Score": "0", "body": "Since you're asking us to try to improve the speed of your code, it's important to have a standard test suite for comparison. Can you post or link to your test suite?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T12:45:34.800", "Id": "44752", "Score": "1", "body": "Maybe `re.split('([MmZzLlHhVvCcSsQqTtAa])', \"M3.4E-34-2.2e56L23-34z\")` and then parsing the coordinates separately (with a smaller regex) would speed things up?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:21:11.677", "Id": "44845", "Score": "0", "body": "@GarethRees: The module includes a full test suite. The test_parsing.py is the testcases for parsing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T16:53:03.263", "Id": "44850", "Score": "0", "body": "@VedranŠego: Well, geez, I was gonna prove to you that it wasn't gonna help because you can't do a smaller regex. It helped anyway. :-)" } ]
[ { "body": "<p>With cred to @VedranŠego for kicking me in the right direction, my current solution is simply to split the two regex-parts into separate parsings, the first one a split (instead of a match) and the second one a findall on the floats (because doing a split is near impossible, as - both should and should not be a separator, depending on context).:</p>\n\n<pre><code>import re\n\nCOMMANDS = set('MmZzLlHhVvCcSsQqTtAa')\nCOMMAND_RE = re.compile(\"([MmZzLlHhVvCcSsQqTtAa])\")\nFLOAT_RE = re.compile(\"[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?\")\n\ndef _tokenize_path(pathdef):\n for x in COMMAND_RE.split(pathdef):\n if x in COMMANDS:\n yield x\n for token in FLOAT_RE.findall(x):\n yield token\n</code></pre>\n\n<p>I times this with:</p>\n\n<pre><code>from timeit import timeit\nnum = 1000000\n\na = timeit(\"_tokenize_path('M-3.4e38 3.4E+38L-3.4E-38,3.4e-38')\", \n \"from svg.path.parser import _tokenize_path\", number=num)\nb = timeit(\"_tokenize_path('M600,350 l 50,-25 a25,25 -30 0,1 50,-25 l 50,-25 a25,50 -30 0,1 50,-25 l 50,-25 a25,75 -30 0,1 50,-25 l 50,-25 a25,100 -30 0,1 50,-25 l 50,-25')\",\n \"from svg.path.parser import _tokenize_path\", number=num)\nc = timeit(\"_tokenize_path('M3.4E-34-2.2e56L23-34z')\",\n \"from svg.path.parser import _tokenize_path\", number=num)\n\nprint a + b + c\n</code></pre>\n\n<p>And it runs an astonishing 23 times faster than the \"replace\" based tokenizer above, and 30 times faster then the regex based tokenizer, even though it essentially does the same thing. :-) I really did not think it would be faster to run this \"dual\" regex in two separate steps, and I have tried other \"two-stage\" variations before that was even slower, but this time I arrived at the right combination.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T18:58:15.647", "Id": "44874", "Score": "0", "body": "I'm glad I've helped. The splitter is a simple regex, by which I mean that there is no quantifiers `*` and `+`, so it runs straightforward. These quantifiers make regexes slow because they often have to try-and-fail before doing a match. With this approach, you've significantly shortened the strings being matched with the more complicated (meaning it has quantifiers) `FLOAT_RE`. Doing one match on a long string often takes much more time than doing n similar matches on strings of approximately 1/n length of a long string. Although, I have to admit I didn't expect this much of a speedup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T14:08:09.260", "Id": "44922", "Score": "2", "body": "FWIW, the regex is slightly wrong. If you look at the definition of `fractional-constant` you'll see that it permits `digit-sequence \".\"` (i.e. `[0-9]+\\.`), which isn't compatible with the regex `[0-9]*\\.?[0-9]+`. That portion should be replaced with e.g. `(?:[0-9]*\\.?[0-9]+|[0-9]+\\.?)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T18:11:04.817", "Id": "44929", "Score": "0", "body": "Also, my reading of the BNF is that the following is a valid path: `M.4.4.4.4z`. The regex-based approach in this answer handles it correctly, but the multiple-replace approach of the question doesn't." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:07:34.677", "Id": "28565", "ParentId": "28502", "Score": "3" } } ]
{ "AcceptedAnswerId": "28565", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-15T09:34:16.747", "Id": "28502", "Score": "6", "Tags": [ "python", "performance", "parsing", "regex", "svg" ], "Title": "SVG path parsing" }
28502
<p>Consider (simplified)</p> <pre><code>low_count = 0 high_count = 0 high = 10 low = 5 value = 2 </code></pre> <p>What is a clean way to check a number <code>value</code> versus a min <code>low</code> and a max <code>high</code>, such that if <code>value</code> is below <code>low</code> <code>low_count</code> increments, and if <code>value</code> is above <code>high</code> <code>high_count</code> increments? Currently I have (code snippet)</p> <pre><code> high_count = 0 low_count = 0 low = spec_df['Lower'][i] high = spec_df['Upper'][i] #Calculate results above/below limit for result in site_results: if result&lt;low: low_count+=1 else: if result&gt;high: high_count+=1 </code></pre> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:39:47.417", "Id": "44789", "Score": "4", "body": "Use `elif` instead of `else:\\nif`." } ]
[ { "body": "<p>The pythonic way would be:</p>\n\n<pre><code> for result in site_results:\n if result&lt;low:\n low_count+=1\n elif result&gt;high:\n high_count+=1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:45:26.283", "Id": "44790", "Score": "5", "body": "Truly pythonic code would follow PEP8, particularly [with regards to spacing](http://www.python.org/dev/peps/pep-0008/#other-recommendations)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:41:00.630", "Id": "28529", "ParentId": "28528", "Score": "0" } }, { "body": "<p>For a more complex case, I'd write a function and use a <code>Counter</code>. For example:</p>\n\n<pre><code>def categorize(low, high):\n def func(i):\n if i &lt; low:\n return 'low'\n elif i &gt; high:\n return 'high'\n else:\n return 'middle'\n return func\n\nsite_results = list(range(20))\n\ncounts = collections.Counter(map(categorize(5, 10), site_results))\nprint(counts['high'], counts['low'])\n</code></pre>\n\n<p>But for a trivial case like this, that would be silly. Other than tenstar's/minitech's suggestions, I wouldn't do anything different.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:53:28.637", "Id": "44792", "Score": "0", "body": "Wow - I was playing with: `print Counter({-1: 'low', 1: 'high'}.get(cmp(result, low), 'eq') for result in site_results)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T01:00:24.297", "Id": "44794", "Score": "0", "body": "@JonClements: If you want to one-liner-ize it, you'd need something like `(cmp(result, low) + cmp(result, high)) // 2`, which I think goes way beyond the bounds of readability…" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:52:32.487", "Id": "28531", "ParentId": "28528", "Score": "0" } }, { "body": "<p>I would write it as</p>\n\n<pre><code>low_count = sum(map(lambda x: x &lt; low, site_results))\nhigh_count = sum(map(lambda x: x &gt; high, site_results))\n</code></pre>\n\n<p>but admit I'm spoiled by Haskell.</p>\n\n<p><strong>Edit</strong>: As suggested by @Nick Burns, using list comprehension will make it even clearer:</p>\n\n<pre><code>low_count = sum(x &lt; low for x in site_results)\nhigh_count = sum(x &gt; high for x in site_results)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T03:54:16.710", "Id": "44796", "Score": "1", "body": "+1 - I agree that this is far more pythonic in this example. However, would probably use a simple generator inside sum: `sum(x for x in site_results if x < low)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:19:15.603", "Id": "44803", "Score": "1", "body": "I agree that the list comprehension is even clearer, but I believe you meant ``len``, not ``sum`` (since the count of low-value elements is needed); it will also require wrapping the comprehension in list, since you can't take ``len`` of a generator. Alternatively, you can write ``sum(x < low for x in site_results)``" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:36:57.300", "Id": "44804", "Score": "0", "body": "sorry -good point. This was a typo, meant to read: `sum(1 for x in site_results if x < low)` . I which case, no need for a list :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T17:28:48.233", "Id": "44853", "Score": "0", "body": "wouldn't this code be poor performing once you get a huge number of items in `site_results`? I'm thinking this is four linear, a.k.a. `O(n)`, operations, since `sum` and `map` are `O(n)`...is this incorrect?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T00:13:18.850", "Id": "44894", "Score": "2", "body": "@omouse: not four, but only two, since ``map`` or list comprehensions return iterators, not lists. Yes, in my solution technically there will be more additions (you will add ``False`` values too), but @Nick's solution does not have this drawback. Finally, it's still O(N), same as the original code, and in the very unlikely event the different coefficient matters, it will be picked up during profiling. I prefer to optimize for humans first." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T01:48:15.120", "Id": "28532", "ParentId": "28528", "Score": "3" } }, { "body": "<p>You can make use of the fact that Python can interpret boolean values as integers:</p>\n\n<pre><code>for result in site_results:\n low_count += result &lt; low\n high_count += result &gt; high\n</code></pre>\n\n<p>If those conditions evaluate to <code>True</code>, this will add <code>1</code> to the counts, otherwise <code>0</code>. This is the same principle as used in the list comprehensions by Bogdan and Nick Burns:</p>\n\n<pre><code>high_count = sum(result &gt; high for result in site_results)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T08:21:48.877", "Id": "28542", "ParentId": "28528", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T00:38:14.367", "Id": "28528", "Score": "2", "Tags": [ "python" ], "Title": "Python Clean way to get whether a number is above/below two values and increment accordingly" }
28528
<p>After considerable effort, I've come up with the following code to generate a list of primes of a given length.</p> <p>I would be very interested to see how an experienced coder would modify my code to make it more readable, more concise, or somehow better. I won't be able to follow fancy-pants coding that doesn't involve basic iterations of the type I have used, so please keep it simple for me. I've been learning the language only a few months.</p> <p>Function returns number of primes indicated in call.</p> <p>Algorithm: Add two to last candidate in list (starting with [2, 3, 5]) and check whether other members divide the new candidate, iterating only up to the square root of the candidate.</p> <pre><code>import math def primeList(listLength): plist = [2, 3] j = 3 while listLength &gt; len(plist): prime = 'true' i = 0 j +=2 plist.append(j) while plist[i] &lt;= math.sqrt(j) and prime == 'true': if j%plist[i] == 0: prime = 'false' i +=1 if prime == 'false': plist.pop(-1) return plist </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:04:10.643", "Id": "44798", "Score": "1", "body": "See http://stackoverflow.com/questions/567222/simple-prime-generator-in-python?rq=1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:07:06.617", "Id": "44799", "Score": "0", "body": "see http://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:08:12.460", "Id": "44801", "Score": "0", "body": "But immediately: use `True` and `False`, not `'true'` and `'false`'. And use `not prime` and `and prime`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T04:11:59.010", "Id": "44802", "Score": "0", "body": "See: http://www.macdevcenter.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2" } ]
[ { "body": "<p>Other than the few things pointed out above, it might be 'cleaner' to use a helper function to test primality. For example:</p>\n\n<pre><code>import math\n\ndef is_prime(x, primes):\n return all(x % i for i in primes if i &lt; math.sqrt(x))\n\ndef first_k_primes(i, k, my_primes):\n if k &lt;= 0:\n return my_primes\n\n if is_prime(i, my_primes):\n my_primes.append(i) \n return first_k_primes(i + 2, k - 1, my_primes)\n\n return first_k_primes(i + 2, k, my_primes)\n\nprint(first_k_primes(5, 10, [2, 3]))\n</code></pre>\n\n<p>Now, I know you didn't want any \"fancy-pants\" coding, but this is actually really really similar to your iterative approach, just using recursion. If we look at each bit we have the following:</p>\n\n<p><code>is_prime(x, primes)</code>: this tests whether the value <code>x</code> is prime or not. Just like in your code, it takes the modulo of <code>x</code> against all of the primes up to the square root of <code>x</code>. This isn't too tricky :) The <code>all()</code> function gathers all of these tests and returns a boolean (True or False). If all of the test (from 2 up to sqrt(x)) are False (i.e., every single test confirms ti is prime) then it returns this finding, and we know x is prime.</p>\n\n<p><code>first_k_primes(i, k, my_primes)</code>: ok, this is recursive, but it isn't too tricky. It takes 3 parameters: </p>\n\n<ul>\n<li>i: the number to test</li>\n<li>k: the number of primes you still need to find until you have the\nnumber you want, e.g. if you want the first 4 primes, and you\nalready know [2, 3, 5], then k will be 1</li>\n<li>my_primes: which is the list of primes so far.</li>\n</ul>\n\n<p>In python, the first thing you need to do with a recursive function, is to figure out a base case. Here, we want to keep going until we have k number of primes (or until k = 0), so that is our base case.</p>\n\n<p>Then we test to see if <code>i</code> is prime or not. If it is, we add it to our growing list of my_primes. Then, we go to the next value to test (<code>i += 2</code>), we can reduce k by one (since we just added a new prime) and we continue to grow our list of my_primes by calling the modified: <code>first_k_primes(i + 2, k - 1, my_primes)</code>.</p>\n\n<p>Finally, if it happens that <code>i</code> is not prime, we don't want to add anything to <code>my_primes</code> and all we want to do is test the next value of <code>i</code>. This is what the last return statement does. It will only get this far if we still want more primes (i.e. k is not 0) or i wasn't prime.</p>\n\n<p>Why do I think this is more readable? The main thing is that I think it is good practice to separate out your logic. <code>is_prime()</code> does one thing and one thing only, and it does the very thing it says it does - it tests a value. Similarly <code>first_k_primes()</code> does exactly what it says it does too, it returns the first k primes. The really nice thing, is that this all boils down to one simple test:</p>\n\n<pre><code>if is_prime(i, my_primes):\n my_primes.append(i)\n</code></pre>\n\n<p>the rest just sets up the boundaries (i.e. the kth limit). So once you have seen a bit of recursion, you intuitively zoom in on the important lines and sort of 'ignore' the rest :)</p>\n\n<p>As a side note, there is a slight gotcha with using recursion in Python: Python has a recursion limit of 1,000 calls. So if you need to recurse on large numbers it will often fail. I love recursion, it is quite an elegant way to do things. But it might also be just as easy to do the <code>first_k_primes()</code> function as an iterative function, or using a generator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T03:54:10.343", "Id": "44900", "Score": "0", "body": "It fails for k = 1001. It isn't really that big a number. So that recursive approach won't work for even moderate numbers. http://ideone.com/k4u9So" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:45:55.300", "Id": "44903", "Score": "0", "body": "You're right - and that is why the caveat is there in the last paragraph and a recommendation to use an iterative approach or a generator expression." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:53:29.467", "Id": "44904", "Score": "0", "body": "I tested this a bit more and it failed for all n > 312. http://ideone.com/jYliuH and http://ideone.com/dDgwiz This was a bit too much. Shouldn't the limit of recursion be more in Python? Your approach would be great in both clarity as well as speed in C as compilers optimize tail-recursive calls. In Python this flaw of tail-recursive calls not being optimized led to this being useless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:58:37.580", "Id": "44905", "Score": "0", "body": "You don't seem to be considering the number of recursive calls necessary to generate 300 primes. It is far more than 300 calls because not all calls will generate a prime number. Again, the limits of recursion in Python have been discussed" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T05:03:38.887", "Id": "44906", "Score": "0", "body": "I understand that there are more than 300 calls. Just saying that I didn't understand why this was so. I found that stack frames are big in Python and guido doesn't like tail-recursion but just... Anyways, me babbling doesn't help anyone so I'll stop with this." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T05:11:25.320", "Id": "28539", "ParentId": "28537", "Score": "0" } }, { "body": "<p>Don't be afraid of typing. Longer names are more readable and should be used except for simple counters. Split out complicated sub-parts where they are separate concepts.</p>\n\n<p>Here is how I would improve it:</p>\n\n<pre><code>import math\n\ndef isPrime (primeList, candidate):\n upperLimit = math.sqrt(candidate)\n for p in primeList:\n if candidate % p == 0:\n return False\n if p &gt;= upperLimit:\n break\n\n return True\n\ndef primeList(listLength):\n if listLength &lt; 1 :\n return []\n primes = [2]\n\n candidate = 3\n while listLength &gt; len(primes):\n if isPrime(primes, candidate):\n primes.append(candidate)\n candidate +=2\n\n return primes\n</code></pre>\n\n<p>To make a faster simple prime algorithm, consider the other naive algorithm in <a href=\"http://en.wikipedia.org/wiki/Primality_test\" rel=\"nofollow\">the primality test wikipedia article</a> where all primes are of the form 6k +- 1.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T05:18:25.023", "Id": "44805", "Score": "0", "body": "+1 for near identical solutions :) Fantastic to see an iterative approach to `primeList` against the similar recursive one in my answer. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T03:47:21.937", "Id": "44899", "Score": "0", "body": "This code **does not run** http://ideone.com/v6cOLI. `j` is not defined in the function `isprime`. Also why are not just returning when it is non-prime. It seems like a waste to use a variable to do essentially the same thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:15:58.643", "Id": "44901", "Score": "0", "body": "Thanks @AseemBansal. I had no idea that a site like ideone.com existed. That will be very useful. Very good point about not just returning, and I got rid of the while loop as well. Also I have no idea why I named the list inside primeList the same as the function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-30T15:12:04.073", "Id": "143259", "Score": "0", "body": "thanx@DominicMcDonnell ,nut I think in primeList function,,, the statement candidate += 2 should be below if statement body ,, because it doesn't include 3 to the prime list." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T05:15:28.870", "Id": "28540", "ParentId": "28537", "Score": "5" } }, { "body": "<p>I'll firstly talk about micro-optimizations then go for major optimizations that can be done in your code.</p>\n\n<p>Don't use the <code>while</code> loop when you can instead use <code>for i in xrange()</code>. It is very slow. Take a look <a href=\"http://mail.python.org/pipermail/tutor/2011-March/082586.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://stackoverflow.com/questions/1377429/what-is-faster-in-python-while-or-for-xrange\">here</a>. There are some limitations but<code>xrange</code> unless you are hitting that limit your code would get faster.</p>\n\n<p>The inner <code>while</code> loop's conditions can be improved. As you have placed calculating <code>math.sqrt()</code> in the conditions it is calculated every time. That makes it very slow because finding square root consumes much time. You should use a variable before the loop to store that value. The second condition is not needed. Instead of checking always for the value of <code>prime</code> you can delete this condition as well as the variable and simply use a <code>break</code> in the <code>if</code> statement.</p>\n\n<p>About using <code>append</code>. You are appending numbers and popping them if they are not primes. Not needed. Just append at the correct condition and use <code>break</code></p>\n\n<p>Also read the Python performance tips link given in Python Tags' wiki on codereview.\nI would have written it like this:</p>\n\n<pre><code>import math\ndef primeList(listLength):\n if listLength &lt; 1:\n return []\n plist = [2]\n j = 3\n sqr_root = math.sqrt\n list_app = plist.append\n while listLength &gt; len(plist):\n temp = sqr_root(j)\n for i in xrange(len(plist)):\n if j % plist[i] == 0:\n break\n if plist[i] &gt; temp:\n list_app(j)\n break\n\n j += 2\n return plist\n</code></pre>\n\n<p>Notice that I defined <code>math.sqrt</code> as something. You'll find that in the Python Performance tips. Also your implementation had a bug. If I entered anything less than 2 it returned <code>[2, 3]</code> which was incorrect result.</p>\n\n<p>This worked in 44 % time that your original function took. Your <a href=\"http://ideone.com/4dhotO\" rel=\"nofollow noreferrer\">code's timing</a> and <a href=\"http://ideone.com/FUI8Nc\" rel=\"nofollow noreferrer\">my code's timing</a>. Note that memory usage is lower in my case. I changed my code a bit. This <a href=\"http://ideone.com/tPuBBf\" rel=\"nofollow noreferrer\">new code uses only 34% time</a> of OP's code.</p>\n\n<p>Now done with micro-optimizations I'll get to major optimizations.</p>\n\n<p>Using this approach to find the list of prime numbers is actually very naive. I also used it in the beginning and after much headache and waiting for outputs to come I found that such approaches can be very slow. Nothing you change in Python's syntax can offset the advantage of using a better algorithm. Check out <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">this</a>. It is not to difficult to implement. You can look at <a href=\"https://github.com/anshbansal/Python\" rel=\"nofollow noreferrer\">my github</a> to get a basic implementation. You'll have to tweak it but you won't have to write it from the beginning.</p>\n\n<p>Hope this helped.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T15:59:08.047", "Id": "28561", "ParentId": "28537", "Score": "1" } }, { "body": "<pre><code>import math\ndef primeList(n):\n plist = [2, 3]\n j = 3\n while len(plist) &lt; n:\n j += 2\n lim = math.sqrt(j)\n for p in plist: # 100k primes: 3.75s vs 5.25 with while loop\n if p &gt; lim: # and the setting of the flag, \n plist.append(j) # on ideone - dNLYD3\n break\n if j % p == 0:\n break\n return plist\nprint primeList(100000)[-1] \n</code></pre>\n\n<p>Don't use long variable names, they hamper readability. Do add comments at first use site of a var to explain what it is (if not self-evident). Move repeated calculations out of the (inner) loop. No need to <em>index</em> into the <code>plist</code> list; just <code>for ... in</code> it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T04:43:16.203", "Id": "44902", "Score": "0", "body": "Avoiding the dots can give better timing.[Your code](http://ideone.com/qYBeUF) timing was 0.25 and by [avoiding dots](http://ideone.com/tPuBBf) it was 0.17." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T06:07:49.963", "Id": "44908", "Score": "0", "body": "@AseemBansal no, your testing is unreliable, because you chose too small a test size so it runs too fast, so you can't be sure whether you observe a real phenomenon or just some fluctuations. I tested this code for 100,000 primes, and [there was no change in timing](http://ideone.com/tbofSs). OTOH even on the same code it was 3.75s usually but there was a one-time outlier of 4.20 (yes I ran it several times, to be sure my observation was repeatable). Another thing, my code performs its steps in correct sequence. It doesn't test any prime above the square root of the candidate. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T07:22:52.797", "Id": "44910", "Score": "0", "body": "I wrote that in that sequence because I thought that would be better as there are more chances of a number being composite. I thought that benefit would build up. About the dots, I don't know why the Python Performance tips say that it helps the performance if they don't. About unreliable timing, noone is answering [this question](http://codereview.stackexchange.com/questions/28373/is-this-the-proper-way-of-doing-timing-analysis-of-many-test-cases-in-python-or) so I am stuck with using ideone for doing the timing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T12:31:33.217", "Id": "44921", "Score": "0", "body": "@AseemBansal Ideone's fine, just short timespans (smaller than half a second, say) are not so reliable, a priori. --- ok, so your ordering saves one comparison for each composite, mine saves one division for each prime." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T19:53:58.740", "Id": "28584", "ParentId": "28537", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T03:58:48.117", "Id": "28537", "Score": "5", "Tags": [ "python", "algorithm", "primes" ], "Title": "Generating a list of primes of a given length" }
28537
<p>I frequently write Python scripts that require three command line arguments:</p> <ol> <li><code>config_file</code> — A CSV configuration file</li> <li><code>input_dir</code> — The directory containing the input files to be processed</li> <li><code>output_dir</code> — The directory where the output files should be stored</li> </ol> <p>I found myself copying/pasting two functions all the time: <code>is_valid_file</code> and <code>is_valid_directory</code>.</p> <h2>Questions</h2> <ol> <li>How can I consolidate the <code>is_valid_file</code> and <code>is_valid_directory</code> functions to eliminate duplicate code?</li> <li>Is there a better way to check that files/directories provided in CLI arguments actually exist?</li> </ol> <h2>Code</h2> <p>Here is the code for <code>process_the_data.py</code>:</p> <pre><code>if __name__ == "__main__": # Process the arguments import argparse import arghelper parser = argparse.ArgumentParser( description='Process the data.') parser.add_argument( 'config_file', help='CSV configuration file.', metavar='FILE', type=lambda x: arghelper.is_valid_file(parser, x)) parser.add_argument( 'input_dir', help='Directory containing the input files.', metavar='DIR', type=lambda x: arghelper.is_valid_directory(parser, x)) parser.add_argument( 'output_dir', help='Directory where the output files should be saved.', metavar='DIR', type=lambda x: arghelper.is_valid_directory(parser, x)) args = parser.parse_args() </code></pre> <p>Here is the code for <code>arghelper.py</code>:</p> <pre><code>import os def is_valid_file(parser, arg): if not os.path.isfile(arg): parser.error('The file {} does not exist!'.format(arg)) else: # File exists so return the filename return arg def is_valid_directory(parser, arg): if not os.path.isdir(arg): parser.error('The directory {} does not exist!'.format(arg)) else: # File exists so return the directory return arg </code></pre>
[]
[ { "body": "<p>You can address some of this by subclassing ArgumentParser. This will allow you hide the lambda calls that may turn off some and leave you scratching your head if you come back to that file later.</p>\n\n<p><strong>Your Script</strong> </p>\n\n<pre><code>if __name__ == \"__main__\":\n # Process the arguments\n #import argparse\n import arghelper\n parser = arghelper.FileArgumentParser(\n description='Process the data.')\n parser.add_argument_with_check(\n 'config_file',\n help='CSV configuration file.',\n metavar='FILE')\n parser.add_argument_with_check(\n 'input_dir',\n help='Directory containing the input files.',\n metavar='DIR')\n parser.add_argument_with_check(\n 'output_dir',\n help='Directory where the output files should be saved.',\n metavar='DIR')\n args = parser.parse_args()\n print args\n</code></pre>\n\n<p><strong>New ArgHelper</strong> </p>\n\n<pre><code>import argparse\nimport os\n\n\nclass FileArgumentParser(argparse.ArgumentParser):\n def __is_valid_file(self, parser, arg):\n if not os.path.isfile(arg):\n parser.error('The file {} does not exist!'.format(arg))\n else:\n # File exists so return the filename\n return arg\n\n def __is_valid_directory(self, parser, arg):\n if not os.path.isdir(arg):\n parser.error('The directory {} does not exist!'.format(arg))\n else:\n # File exists so return the directory\n return arg\n\n def add_argument_with_check(self, *args, **kwargs):\n # Look for your FILE or DIR settings\n if 'metavar' in kwargs and 'type' not in kwargs:\n if kwargs['metavar'] is 'FILE':\n type=lambda x: self.__is_valid_file(self, x)\n kwargs['type'] = type\n elif kwargs['metavar'] is 'DIR':\n type=lambda x: self.__is_valid_directory(self, x)\n kwargs['type'] = type\n self.add_argument(*args, **kwargs)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T15:08:17.283", "Id": "411299", "Score": "0", "body": "At line 8 self.error('The file {} does not exist!'.format(arg)) is enough. Line 9 \"else\" not needed. \"parser\" is same as self." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T19:33:33.983", "Id": "28614", "ParentId": "28608", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T17:06:31.357", "Id": "28608", "Score": "5", "Tags": [ "python" ], "Title": "Checking if CLI arguments are valid files/directories in Python" }
28608
<p>I am porting a linear optimization model for power plants from <a href="http://gams.com/" rel="nofollow">GAMS</a> to <a href="https://software.sandia.gov/trac/coopr/wiki/Pyomo" rel="nofollow">Pyomo</a>. Models in both frameworks are a collection of sets (both elementary or tuple sets), parameters (fixed values, defined over sets), variables (unknowns, defined over sets, value to be determined by optimization) and equations (defining relationships between variables and parameters).</p> <p>In the following example, I am asking for ideas on how to make the following inequality more readable:</p> <pre><code>def res_stock_total_rule(m, co, co_type): if co in m.co_stock: return sum(m.e_pro_in[(tm,)+ p] for tm in m.tm for p in m.pro_tuples if p[1] == co) + \ sum(m.e_pro_out[(tm,)+ p] for tm in m.tm for p in m.pro_tuples if p[2] == co) + \ sum(m.e_sto_out[(tm,)+ s] for tm in m.tm for s in m.sto_tuples if s[1] == co) - \ sum(m.e_sto_in[(tm,)+ s] for tm in m.tm for s in m.sto_tuples if s[1] == co) &lt;= \ m.commodity.loc[co, co_type]['max'] else: return Constraint.Skip </code></pre> <p><strong>Context:</strong></p> <ul> <li><code>m</code> is a model object, which contains all of the above elements (sets, params, variables, equations) as attributes.</li> <li><code>m.e_pro_in</code> for example is a 4-dimensional variable defined over the tuple set <em>(time, process name, input commodity, output commodity)</em>.</li> <li><code>m.tm</code> is a set of timesteps <em>t = {1, 2, ...}</em>, <code>m.co_stock</code> the set of stock commodity, for which this rule will apply only (otherwise, no Constraint is generated via Skip).</li> <li><code>m.pro_tuples</code> is a set of all valid (i.e. realisable) tuples <em>(process name, input commodity, output commodity)</em>.</li> <li><code>m.commodity</code> is a Pandas DataFrame that effectively acts as a model parameter.</li> </ul> <p><strong>My question now is this:</strong></p> <p>Can you give me some hints on how to improve the readability of this fragment? The combination of tuple concatenation, two nested list comprehensions with conditional clause, Pandas DataFrame indexing, and a multiline expression with line breaks all make it less than easy to read for someone who might just be learning Python while using this model.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T11:18:49.763", "Id": "45246", "Score": "0", "body": "Is there any necessity for it to be an expression?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T15:51:30.360", "Id": "45338", "Score": "0", "body": "No, as I found out in the meantime. The revised version is added to the question." } ]
[ { "body": "<p>First of all, use helper functions or explicit for loops.</p>\n\n<p>E.g. you're looping over <code>m.tm</code> four times. This can be done in a single loop. It might need more lines of code, but it will get much more readable.</p>\n\n<p>E.g.</p>\n\n<pre><code>def res_stock_total_rule(m, co, co_type):\n if not co in m.co_stock:\n return Constraint.Skip\n\n val = 0\n for tm in m.tm: # one single loop instead of four\n for p in m.pro_tuples:\n if p[1] == co:\n val += m.e_pro_in[(tm,) + p)]\n if p[2] == co:\n val += m.e_pro_out[(tm,) + p)]\n for s in m.sto_tuples: # one single loop instead of two\n if s[1] == co:\n val += m.e_sto_out[(tm,) + p)] - m.e_sto_in[(tm,) + p)]\n return val &lt;= m.commodity.loc[co, co_type]['max']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T14:47:11.220", "Id": "28649", "ParentId": "28647", "Score": "4" } }, { "body": "<p>Wrapping with parentheses is often preferable to newline escapes:</p>\n\n<pre><code>def res_stock_total_rule(m, co, co_type):\n if co in m.co_stock:\n return (\n sum(m.e_pro_in [(tm,) + p] for tm in m.tm for p in m.pro_tuples if p[1] == co) +\n sum(m.e_pro_out[(tm,) + p] for tm in m.tm for p in m.pro_tuples if p[2] == co) +\n sum(m.e_sto_out[(tm,) + s] for tm in m.tm for s in m.sto_tuples if s[1] == co) -\n sum(m.e_sto_in [(tm,) + s] for tm in m.tm for s in m.sto_tuples if s[1] == co)\n ) &lt;= m.commodity.loc[co, co_type]['max']\n else:\n return Constraint.Skip\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-28T07:21:34.247", "Id": "180099", "Score": "0", "body": "Indeed, but in case of an expression *that* long, omitting the line continuation character `\\` does not help much." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-27T22:01:27.320", "Id": "98268", "ParentId": "28647", "Score": "1" } } ]
{ "AcceptedAnswerId": "28649", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T14:16:10.587", "Id": "28647", "Score": "4", "Tags": [ "python", "matrix", "pandas" ], "Title": "Long expression to sum data in a multi-dimensional model" }
28647
<p>I've written a little function that iterates over two iterables. The first one returns an object which is used to convert an object of the second iterable. I've got a working implementation, but would like to get some feedback.</p> <p>A simple use case would look like this:</p> <pre><code>list(serialize([String(), String()], [1, 2])) # should work list(serialize([String(), String()], range(3))) # should fail, too many values list(serialize([String(), String()], range(1))) # should fail, too few values </code></pre> <p>But sometimes the number of values is not known but the type is the same. Therefore infinite iterators should be allowed as types argument:</p> <pre><code>list(serialize(it.repeat(String()), range(3))) # should work </code></pre> <p>Of course finite iterators are allowed as well:</p> <pre><code>list(serialize(it.repeat(String(), times=3), range(3))) # should work list(serialize(it.repeat(String(), times=4), range(5))) # should fail # should fail, but probably not that easy to do. list(serialize(it.repeat(String(), times=4), range(3))) </code></pre> <p>My working implementation (except for the last case) looks like this:</p> <pre><code>class String(object): def dump(self, value): return str(value) def serialize(types, values): class Stop(object): """Since None can be valid value we use it as fillvalue.""" if isinstance(types, collections.Sized): # Since None is a valid value, use a different fillvalue. tv_pairs = it.izip_longest(types, values, fillvalue=Stop) else: tv_pairs = it.izip(it.chain(types, (Stop,)), values) for type, value in tv_pairs: if type is Stop: raise ValueError('Too many values.') if value is Stop: raise ValueError('Too few values.') yield type.dump(value) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T15:25:27.507", "Id": "44993", "Score": "0", "body": "you could be checking to see if the lengths of the two lists match instead of messing around with `izip`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T15:35:50.723", "Id": "44996", "Score": "0", "body": "@omouse This won't work if a generator is used." } ]
[ { "body": "<p>There is no (general) way of telling the difference between an infinite and a finite iterator.</p>\n\n<p><code>types</code> might be a generator that stops yielding after a million items have been yielded. The only fool-proof way of telling would be to consume the generator up to the point where it stops yielding items. Of course, even if we've consumed a billion items and it hasn't stopped, we can't be sure it wouldn't stop at a later point.</p>\n\n<p>This is why I recommend you change the specification for your function. The new version will yield items until <code>values</code> have been up. If there are too few <code>types</code>, it raises <code>ValueError</code>.</p>\n\n<pre><code>def serialize(types, values):\n types_iter = iter(types)\n for value in values:\n try:\n type = next(types_iter)\n except StopIteration:\n raise ValueError(\"Too few types.\")\n yield type.dump(value)\n</code></pre>\n\n<p>If you really want to, you can check with <code>len()</code> that the lengths of <code>types</code> and <code>values</code> are the same, but as you have said, this will only work for some iterables.</p>\n\n<pre><code>def serialize(types, values):\n try:\n len_types, len_values = len(types), len(values)\n except TypeError:\n pass\n else:\n if len_values &gt; len_types:\n raise ValueError(\"Too many values.\")\n if len_values &lt; len_types:\n raise ValueError('Too few values.')\n\n for type, value in itertools.izip(types, values):\n yield type.dump(value)\n return\n\n types_iter = iter(types)\n for value in values:\n try:\n type = next(types_iter)\n except StopIteration:\n raise ValueError(\"Too many values.\")\n yield type.dump(value)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T17:50:06.220", "Id": "28658", "ParentId": "28648", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T14:30:07.373", "Id": "28648", "Score": "1", "Tags": [ "python", "serialization" ], "Title": "Iterating over two iterables" }
28648
<p>Suppose I need to process a list of list of list of many objects, where the data usually comes from third party APIs.</p> <p>For the sake of an example, lets assume we have many users, and for each user we get many days of data, and for each day you get many events. We want to process all of these objects and store in our database</p> <p>I thought about some differents design patterns I could use, but I'm not sure what is considered to be the best approach, if any.</p> <p>These are my thoughts:</p> <p>1) Nested iterations and do the side-effect (save to database) at the lowest-level loop.</p> <pre><code>for user in users: for day in user.days: for event in day.event: processed_object = process_event(event) save_to_db(processed_object) </code></pre> <p>2) Similar to one, except that each nested iteration is 'hidden' in another method.</p> <pre><code>for user in users: process_user(user) def process_user(user): for day in user.days: process_day(day) def process_day(day): for event in day.events: process_event(event) def process_event(event): save_to_db(event) </code></pre> <p>3) Return everything from deep in the nest and then do the side-effects afterwards.</p> <pre><code>def process_users(users): processed = [] for user in users: processed.append(process_user(user)) return processed def process_user(user): processed = [] for day in user.days: processed.append(process_day(day)) return processed def process_day(day): processed = [] for event in day.events: processed.append(process_event) return processed processed_events = process_users(users) for event in processed_events: save_to_db(event) </code></pre> <p>Is there a general, agreed on approach for these type of programs, where side-effects are involved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T15:54:07.330", "Id": "45166", "Score": "0", "body": "Your third example could be rewritten using generators, avoiding the creation of temporary lists. Also using `itertools.chain.from_iterable` could be useful to flatten the iterations." } ]
[ { "body": "<p>Not sure what is \"generally agreed upon\", if anything, but in my opinion the first variant is by far the easiest to read and understand, let alone most compact.</p>\n\n<p>As @Alex points out, the second and third variant give more flexibility, e.g., you can process the events of just a single user, or a single day, but judging from your question this seems not to be necessary.</p>\n\n<p>Another variant would be: First collect the events in a list, then process them in a separate loop, i.e., a mixture of variant 1 and 3:</p>\n\n<pre><code>all_events = []\nfor user in users:\n for day in user.days:\n all_events.extend(day.event)\n\nfor event in all_events:\n processed_object = process_event(event)\n save_to_db(processed_object)\n</code></pre>\n\n<p>You could also use a list comprehension for the first part...</p>\n\n<pre><code>all_events = [event for user in users for day in user.days for event in day.event]\n</code></pre>\n\n<p>...or even for the whole thing (although I don't think this is very readable).</p>\n\n<pre><code>[save_to_db(process_event(event)) for user in ... ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T11:55:34.347", "Id": "28691", "ParentId": "28674", "Score": "1" } } ]
{ "AcceptedAnswerId": "28691", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T04:20:59.267", "Id": "28674", "Score": "1", "Tags": [ "python", "design-patterns" ], "Title": "Deep iterations with side effects" }
28674
<p>This script creates a hierarchy of directories. Is this a good approach or can it be made better? I am mainly concerned with maintainability here, not efficiency. Suppose I wanted to add more directories to this hierarchy. Would this structure of the script make it easier to do?</p> <p><strong>Hierarchy</strong></p> <pre><code>./project_euler ./001_050 ./051_100 ... ./401_450 ./codechef ./easy ./medium ./hard ./spoj ./functions ./utilities </code></pre> <p><strong>The script</strong></p> <pre><code>import os TOP = ['project_euler', 'codechef', 'spoj', 'functions', 'utilities'] CODECHEF = ['easy', 'medium', 'hard'] def safe_make_folder(i): '''Makes a folder if not present''' try: os.mkdir(i) except: pass def make_top_level(top): for i in top: safe_make_folder(i) def make_euler_folders(highest): def folder_names(): '''Generates strings of the format 001_050 with the 2nd number given by the function argument''' for i in range(1,highest, 50): yield ( 'project_euler' + os.sep + str(i).zfill(3) + '_' + str(i + 49).zfill(3) ) for i in folder_names(): safe_make_folder(i) def make_codechef_folders(codechef): for i in codechef: safe_make_folder('codechef' + os.sep + i) def main(): make_top_level(TOP) make_euler_folders(450) make_codechef_folders(CODECHEF) if __name__ == "__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T19:58:10.533", "Id": "45093", "Score": "1", "body": "PEP 8 advices lower case for local variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:37:10.633", "Id": "45172", "Score": "1", "body": "@Josay HIGHEST is constant, but not defined at the module level. PEP8: `Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:59:02.973", "Id": "45174", "Score": "0", "body": "@Lstor said that global variables are code-smell so I thought to make them local variables(which are constants so I used capital letters). What would be the correct design decision here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:59:34.587", "Id": "45175", "Score": "0", "body": "@Josay Please see the above" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T17:08:55.517", "Id": "45176", "Score": "0", "body": "@Anthon Please see the above comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:08:32.653", "Id": "45188", "Score": "0", "body": "Since Python doesn't have real constants, the convention is to use all uppercase (+underscore) for the variable name, make it global and treat it as read-only. It would be inappropriate to assign a value to the global 'constant' somewhere else. Look e.g. at the os.py module that comes with Python. It has `SEEK_SET = 0` at the module level and no smell is involved because it is used as a constant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:17:21.573", "Id": "45189", "Score": "0", "body": "@Anthon Updated the code. How about now? Is this what you were talking about?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T19:27:28.443", "Id": "45192", "Score": "0", "body": "@AseemBansal Looks good to me, I would leave it like that." } ]
[ { "body": "<p>I'm not quite convinced that a python script is required here as a shell one-liner would probably do the trick (<code>mkdir -p codechef/{easy,medium,hard} spoj utilities</code> would be a good starting point).</p>\n\n<p>Your python code could be improved by using <a href=\"http://www.python.org/dev/peps/pep-0289/\" rel=\"nofollow\">Generator Expressions</a> :</p>\n\n<pre><code>def make_euler_folders(highest):\n def folder_names():\n '''Generates strings of the format 001_050 with\n the 2nd number given by the function argument'''\n for i in range(1,highest, 50):\n yield (\n 'project_euler' + os.sep +\n str(i).zfill(3) + '_' + str(i + 49).zfill(3)\n )\n\n for i in folder_names():\n safe_make_folder(i)\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>def make_euler_folders(highest):\n def folder_names():\n '''Generates strings of the format 001_050 with\n the 2nd number given by the function argument'''\n return ('project_euler' + os.sep + str(i).zfill(3) + '_' + str(i + 49).zfill(3) for i in range(1,highest, 50))\n\n for i in folder_names():\n safe_make_folder(i)\n</code></pre>\n\n<p>which is then nothing but :</p>\n\n<pre><code>def make_euler_folders(highest):\n for i in ('project_euler' + os.sep + str(i).zfill(3) + '_' + str(i + 49).zfill(3) for i in range(1,highest, 50)):\n safe_make_folder(i)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:57:03.443", "Id": "45065", "Score": "0", "body": "I used Python because I am on Windows." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T15:02:36.047", "Id": "45066", "Score": "0", "body": "Anything about use of global variables? Should I pass them or not? Best practice about that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T15:25:07.960", "Id": "45068", "Score": "1", "body": "You should pass them. Global variables is a code smell, and leads to tighter coupling (which is bad)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T15:50:17.833", "Id": "45070", "Score": "1", "body": "Also, you should probably check your usage of literal strings as some of them are defined twice ('project_euler', 'codechef')." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T05:46:00.400", "Id": "45139", "Score": "0", "body": "@Josay Is it better now?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:45:14.807", "Id": "28716", "ParentId": "28715", "Score": "2" } }, { "body": "<p>One of the things I would do is remove the double occurrence of the strings <code>'project_euler'</code> and <code>'codechef'</code>. If you ever have to change one of these in <code>TOP</code>, you are bound to miss the repetition in the functions. </p>\n\n<p>You should at least use <code>TOP[0]</code> in <code>make_euler_folders()</code> and <code>TOP[1]</code> in <code>make_codechef_folders</code>. A better approach however would be to take both definitions out of <code>TOP</code> and change <code>def safe_make_folder()</code>:</p>\n\n<pre><code>TOP = ['spoj', 'functions', 'utilities']\n\ndef safe_make_folder(i):\n '''Makes a folder (and its parents) if not present'''\n try: \n os.makedirs(i)\n except:\n pass\n</code></pre>\n\n<p>The standard function <a href=\"http://docs.python.org/2/library/os.html#os.makedirs\" rel=\"nofollow\"><code>os.makedirs()</code></a> creates the <code>'project_euler'</code> resp. \n'codechef', as the first subdirectory of each is created.</p>\n\n<hr>\n\n<p>The other is that I would create the directory names using <a href=\"http://docs.python.org/2/library/os.path.html#os.path.join\" rel=\"nofollow\"><code>os.path.join()</code></a> (as it prevents e.g. the mistake of providing double path separators), in combination with <a href=\"http://docs.python.org/3/library/string.html#format-specification-mini-language\" rel=\"nofollow\">standard string formatting</a> to get the leading zeros on the subfolder names:</p>\n\n<pre><code>os.path.join('project_euler', '{:03}_{:03}'.format(i, i+49))\n</code></pre>\n\n<p>the <code>{:03}</code> gives a 3 character wide field with leading zeros. @Josay improvemed function would then become:</p>\n\n<pre><code>def make_euler_folders(highest):\n for i in (os.path.join('project_euler', '{:03}_{:03}'.format(i, i+49)) \\\n for i in range(1,highest, 50)):\n safe_make_folder(i)\n</code></pre>\n\n<p>And the other function would become:</p>\n\n<pre><code>def make_codechef_folders(codechef):\n for i in codechef:\n safe_make_folder(os.path.join('codechef', i))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:40:38.997", "Id": "45077", "Score": "0", "body": "Updated the code. Any other suggestions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-20T16:38:27.263", "Id": "45173", "Score": "0", "body": "move the constant `HIGHEST` to the module level and make it a somewhat more descriptive name (HIGHEST_EXERSIZE_NUMBER ?)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T16:04:01.203", "Id": "28719", "ParentId": "28715", "Score": "4" } } ]
{ "AcceptedAnswerId": "28719", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T14:30:32.763", "Id": "28715", "Score": "5", "Tags": [ "python", "directory" ], "Title": "Script for creating a hierarchy of directories" }
28715
<p>I am new to Python and can't quite make my <code>if</code>-cases any shorter. Any ideas on how to do that?</p> <pre><code>import csv fileheader = csv.reader(open("test.csv"), delimiter=",") # Defines the header of the file opened header = fileheader.next() # Loop into the file for fields in fileheader: # For each header of the file, it does the following : # 1/ Detect if the header exists in the file # 2/ If yes and if the cell contains datas, it's added to the payload that will be used for an HTTP POST request. # 3/ If not, it doesn't add the cell to the payload. if 'url_slug' in header: url_slug_index = header.index('url_slug') if fields[url_slug_index] == "": print "url_slug not defined for %s" % fields[url_index] else: payload['seo_page[path]'] = fields[url_slug_index] if 'keyword' in header: keyword_index = header.index('keyword') if fields[keyword_index] == "": print "keyword not defined for %s" % fields[url_index] else: payload['seo_page[keyword]'] = fields[keyword_index] </code></pre>
[]
[ { "body": "<p>I would consider wrapping the conditions up inside a function:</p>\n\n<pre><code>def is_header(pattern):\n if pattern in header:\n pattern_index = header.index(pattern)\n if fields[pattern_index]:\n pattern_key = \"path\" if pattern == \"url_slug\" else \"keyword\"\n payload['seo_page[{}]'.format(pattern_key)] = fields[pattern_index] \n else:\n print(\"{} not defined for {}\".format(pattern, fields[pattern_index])\n</code></pre>\n\n<p>Because the tests are essentially the same, you could create a common function and pass in the pattern to test against (<code>url_slug</code> or <code>keyword</code>). There is some extra hocus pocus to get <code>pattern_key</code> to be the right thing in order to point to the right key in your seo_page dict (I assume it is a dict?).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T20:47:58.213", "Id": "28789", "ParentId": "28788", "Score": "1" } }, { "body": "<p>Instead of <code>fileheader = csv.reader(open(\"test.csv\"), delimiter=\",\")</code> you should do</p>\n\n<pre><code>with open(\"test.csv\") as f:\n fileheader = csv.reader(f, delimiter=\",\")\n</code></pre>\n\n<p>to ensure that the file is property closed at the end of the script.</p>\n\n<p>Also, why is the reader holding the entire CSV file named <code>fileheader</code>? This seems odd.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T14:27:16.257", "Id": "28831", "ParentId": "28788", "Score": "0" } } ]
{ "AcceptedAnswerId": "28789", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T19:01:12.267", "Id": "28788", "Score": "2", "Tags": [ "python", "beginner", "csv" ], "Title": "Loop in a .csv file with IF cases" }
28788
<p>This code works nicely for my purposes, but I would like to improve it exponentially.</p> <p>What are some steps I can take? I'm interested in optimization, refactoring, and clean-code.</p> <pre><code> def do_GET(self): qs = {} path = self.path print path if path.endswith('robots.txt'): self.send_response(500) self.send_header('Connection', 'close') return if '?' in path: path, tmp = path.split('?', 1) qs = urlparse.parse_qs(tmp) print path, qs if 'youtube' in path: ID = qs.get('vID') LTV = qs.get('channelID') EMAIL = qs.get('uEmail') TIME = qs.get('Time') userID = qs.get('uID') URL = qs.get('contentUrl') channelID = str(LTV)[2:-2] print channelID uEmail = str(EMAIL)[2:-2] print uEmail ytID = str(ID)[2:-2] print ytID ytURL = str("https://www.youtube.com/tv#/watch?v=%s" % ytID) print ytURL uTime = str(TIME)[2:-2] print uTime uID = str(userID)[2:-2] print uID contentUrl = str(URL)[2:-2] print contentUrl if sys.platform == "darwin": subprocess.Popen('./killltv', shell=True) sleep(1) subprocess.Popen('./killltv', shell=True) sleep(1) subprocess.Popen('./test.py %s'%ytURL, shell=True) elif sys.platform == "linux2": subprocess.Popen('./killltv', shell=True) sleep(1) subprocess.Popen('./test.py %s'% ytURL, shell=True) #subprocess.Popen('chromium-browser https://www.youtube.com/tv#/watch?v=%s'% ytID, shell=True) sleep(2) #subprocess.Popen("./fullscreen", shell=True) elif sys.platform == "win32": os.system('tskill chrome') browser = webbrowser.open('http://youtube.com/watch?v="%s"'% ytID) log.warn("'%s':,video request:'%s' @ %s"% (channelID, ytID, time)) #playyt = subprocess.Popen("/Users/Shared/ltv.ap </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T05:00:50.163", "Id": "45291", "Score": "1", "body": "Some explanation of its purpose would be helpful. That way we don't accidentally break it. That is the first feedback. Always use [docstring at the beginning of a function explaining its purpose](http://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T02:06:17.753", "Id": "45693", "Score": "0", "body": "Why are you running ./killtv a bunch of times and then running another python script (test.py) from your python script?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T02:25:28.690", "Id": "45695", "Score": "0", "body": "http get request opens a pyside window (test.py), killtv just closes the previous request/window" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-30T13:12:48.913", "Id": "46033", "Score": "0", "body": "About your os specific code why are you only opening the browser when `sys.platform` is `win32`? If you add certain details about what you are trying to do by `test.py` then the os specific code can be converted into loops based on values stored in dictionaries with key being `sys.platform`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-03T01:32:51.813", "Id": "46305", "Score": "0", "body": "@AseemBansal can you elaborate... I think this is something i'm searching for. test.py opens up a pyside window with a url passed in from the get request." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-03T12:47:36.357", "Id": "46330", "Score": "0", "body": "@sirvonandrethomas I updated my answer to add details regarding the os-specific code." } ]
[ { "body": "<p>Some notes about your code:</p>\n\n<ul>\n<li>Use 4 spaces for indentation.</li>\n<li>Local variables should use the underscore style: <code>name_of_variable</code>.</li>\n<li>This function is too long. Split code in functions.</li>\n<li>When writing conditionals, try to keep a <code>if</code>/<code>elif</code>/<code>else</code> layout, without early returns, you'll see that readability is greatly enhanced.</li>\n<li>Use dictionaries to hold multiple named values, not one variable per value, that's too messy.</li>\n<li>Some patterns are repeated all over the place, abstract them.</li>\n<li>Don't update variables in-place unless there is a good reason for it (99% of the time there isn't).</li>\n</ul>\n\n<p>I'd write (<code>show_video</code> has been left out, it's clearly another function's task):</p>\n\n<pre><code>def do_GET(self):\n url = urlparse.urlparse(self.path)\n if 'youtube' not in url.path:\n sys.stderr.write(\"Not a youtube path: {0}\".format(self.path))\n elif url.path == '/robots.txt':\n self.send_response(500)\n self.send_header('Connection', 'close')\n else:\n url_params = urlparse.parse_qs(url.query)\n keys = [\"vID\", \"channelID\", \"uEmail\", \"Time\", \"uID\", \"contentUrl\"]\n params = dict((key, url_params[key][2:-2]) for key in keys)\n yt_url = \"https://www.youtube.com/tv#/watch?v={0}\".format(params[\"vID\"])\n show_video(yt_url)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T14:47:52.830", "Id": "28834", "ParentId": "28799", "Score": "4" } } ]
{ "AcceptedAnswerId": "28803", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T02:45:04.277", "Id": "28799", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "Optimization of \"def do_GET(self)\"" }
28799
<p>I'm looking for a way to make my code more simple. This code takes a list of vectors and returns all subset of that list that sum up to another vector.</p> <p>For example:</p> <blockquote> <p><code>{'a','b','c'}</code> is the subset consisting of: <code>a (1100000)</code>, <code>b (0110000)</code>, and <code>c (0011000)</code>.</p> </blockquote> <pre><code>def AddVectors(A, B): if not A: return B if not B: return A return [A[i] + B[i] for i in range(len(A))] def SumVectorList(lst, SuperSet): result = [] for l in lst: if not result: result = SuperSet[l] else: for j in range(len(l)): result = AddVectors(result, SuperSet[l[j]]) return result def GetPowerSet(lst): result = [[]] for x in lst: result.extend([subset + [x] for subset in result]) return result S = {'a': [one, one, 0, 0, 0, 0, 0], 'b': [0, one, one, 0, 0, 0, 0], 'c': [0, 0, one, one, 0, 0, 0], 'd': [0, 0, 0, one, one, 0, 0], 'e': [0, 0, 0, 0, one, one, 0], 'f': [0, 0, 0, 0, 0, one, one]} P = GetPowerSet(S) u = [0, 0, one, 0, 0, one, 0] v = [0, one, 0, 0, 0, one, 0] u_0010010 = {y for x in P for y in x if SumVectorList(x, S) == u} u_0100010 = {y for x in P for y in x if SumVectorList(x, S) == v} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T19:43:09.140", "Id": "45648", "Score": "0", "body": "What does your code do ? What is it supposed to do ? Does it work ? I've tried replacing `one` by `1` and it is now running fine but it doesn't seem to be doing much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T19:48:30.097", "Id": "45649", "Score": "0", "body": "one should not be replace with 1. The one in this case is 1 in GF2. So one+one=0 where as 1+1 in R = 2" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T19:50:10.557", "Id": "45650", "Score": "0", "body": "@Josay As stated about I'm trying to find subset of S that when summed over GF2 you get the value of u or v respectively. I left out the GF2 portion, sorry. The code works just fine. I just was wondering how I could make it cleaner and with less lines maybe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T20:00:15.253", "Id": "45652", "Score": "0", "body": "Thanks for the clarification. That makes sense now. Can you give the definition of `one` (and any other things we might need for testing purposes) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T20:38:32.557", "Id": "45657", "Score": "0", "body": "@Josay you can go to http://resources.codingthematrix.com and Download GF2.py" } ]
[ { "body": "<p>Please have a look at <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> giving the Style Guide for Python Code.</p>\n\n<p>Now, in <code>AddVectors</code> (or <code>add_vectors</code>), it seems like you assume that A and B have the same size. You could achieve the same result with <code>zip</code>.</p>\n\n<pre><code>def add_vectors(a, b):\n assert(len(a)==len(b))\n return [sum(i) for i in zip(a,b)]\n</code></pre>\n\n<p>I have to go, I'll some more later :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T17:16:37.603", "Id": "28987", "ParentId": "28985", "Score": "1" } } ]
{ "AcceptedAnswerId": "28987", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-25T16:45:53.400", "Id": "28985", "Score": "-1", "Tags": [ "python", "python-3.x", "mathematics" ], "Title": "Find all subsets of a vector that sum up to another vector" }
28985
<p>As a beginner Python programmer, I wrote a simple program that counts how many times each letter appears in a text file. It works fine, but I'd like to know if it's possible to improve it.</p> <pre><code>def count_letters(filename, case_sensitive=False): alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" with open(filename, 'r') as f: text = f.read() if not case_sensitive: alphabet = alphabet[:26] text = text.lower() letter_count = {ltr: 0 for ltr in alphabet} for char in text: if char in alphabet: letter_count[char] += 1 for key in sorted(letter_count): print(key, letter_count[key]) print("total:", sum(letter_count.values())) </code></pre>
[]
[ { "body": "<p>Your coding style is good, especially if you're only starting to program in Python. But to improve your code, you should learn your way around the standard library. In this case, the <a href=\"http://docs.python.org/3/library/string.html\" rel=\"nofollow\"><code>string</code></a> and <a href=\"http://docs.python.org/3/library/collections.html\" rel=\"nofollow\"><code>collections</code></a> modules can make life easier for you.</p>\n\n<pre><code>import collections\nimport string\n\ndef count_letters(filename, case_sensitive=False):\n with open(filename, 'r') as f:\n text = f.read()\n\n if case_sensitive:\n alphabet = string.ascii_letters\n else:\n alphabet = string.ascii_lowercase\n text = text.lower()\n\n letter_count = collections.Counter()\n\n for char in text:\n if char in alphabet:\n letter_count[char] += 1\n\n for letter in alphabet:\n print(letter, letter_count[letter])\n\n print(\"total:\", sum(letter_count.values()))\n</code></pre>\n\n<p><a href=\"http://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a> is, in essence, a dictionary with all values defaulting to <code>0</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-27T12:11:11.783", "Id": "45804", "Score": "1", "body": "Note that `collection.Counter` may take an iterable, so there is no need to add values with a side-effect (`letter_count[char] += 1`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-27T18:27:12.150", "Id": "45825", "Score": "0", "body": "@tokland Good point." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T16:01:47.133", "Id": "29031", "ParentId": "29024", "Score": "4" } }, { "body": "<p>@flornquake points at the good direction (use <code>string</code> and <code>collections.Counter</code>) but I'd still modify some details:</p>\n\n<ul>\n<li><p><code>alphabet = alphabet[:26]</code> and <code>text = text.lower()</code>: My advice is not to override existing variables with new values, it makes code harder to understand. Use different names.</p></li>\n<li><p><code>if char in alphabet</code>: Make sure you perform inclusion predicates with hashes, sets or similar data structures, not lists/arrays. O(1) vs O(n).</p></li>\n<li><p>Functions should return values (hopefully related with their name). Here it makes sense to return the counter.</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>import collections\nimport string\n\ndef count_letters(filename, case_sensitive=False):\n with open(filename, 'r') as f:\n original_text = f.read()\n if case_sensitive:\n alphabet = string.ascii_letters\n text = original_text\n else:\n alphabet = string.ascii_lowercase\n text = original_text.lower()\n alphabet_set = set(alphabet)\n counts = collections.Counter(c for c in text if c in alphabet_set)\n\n for letter in alphabet:\n print(letter, counts[letter])\n print(\"total:\", sum(counts.values()))\n\n return counts\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-27T09:03:02.060", "Id": "45801", "Score": "0", "body": "You didn't explicitly mention it, but one of the best improvements is the initialization of the `Counter` from a generator expression. Nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-27T12:09:20.523", "Id": "45803", "Score": "0", "body": "@codesparkle: I was to, but I realized that would be reviewing flownquake's answer, not OP :-) I'l add a comment to his question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-29T16:33:59.233", "Id": "45944", "Score": "0", "body": "Wouldn't using `original_text = original_text.lower()` be better? Avoids unneeded variable. Also what about non-existent files? That would create an unrecognizable error for user as saying that file doesn't exist in error is quite different from the error that `original_text` undeclared." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-29T16:39:10.743", "Id": "45945", "Score": "0", "body": "@AseemBansal 1) reuse variables: Are you familiar with the functional paradigm? in FP you never ever use the same variable name (or symbol) for two different values (in the same scope, of course), because it's harder to reason about the algorithm. It's like in maths, you don't have x = 1, and just a step later x = 2, that makes no sense; the same when programming. More on this: https://en.wikipedia.org/wiki/Functional_programming 2) \"what about non-existent files\" The OP didn't stated what was to be done, so I did the same he did: nothing. Let the exception blow or be caught by the caller." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-29T17:00:58.690", "Id": "45948", "Score": "0", "body": "@tokland I just know C so not familiar with functional programming. But here it seems to be just procedural code with function call. Is it bad to reuse variables in Python? Noone pointed that out earlier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-29T18:08:33.100", "Id": "45955", "Score": "1", "body": "@AseemBansal: In C is difficult (and usually unrealistic) to apply FP principles, but in Python (like in Ruby, Perl, Lua and other imperative languages), you definitely can (of course an inpure approach to FP, with side-effects). If you give it a try, you'll see that code improves noticiably, it's more much more declarative (describing not *how* but *what* you are doing). Perhaps the starting point would be: http://docs.python.org/3/howto/functional.html. If you happen to know Ruby, I wrote this: https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-29T18:12:02.733", "Id": "45956", "Score": "0", "body": "@tokland This will be really helpful. I found that there is a how-to for fetching web resources using urllib also which I am currently trying to do. I wish you had told me earlier. I might not have needed to ask question on SO. Many thanks." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-07-26T20:46:11.370", "Id": "29043", "ParentId": "29024", "Score": "6" } } ]
{ "AcceptedAnswerId": "29043", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T13:43:09.550", "Id": "29024", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "file" ], "Title": "Counting letters in a text file" }
29024