body
stringlengths
603
27.3k
question_id
stringlengths
4
6
label
stringclasses
5 values
meta_data
dict
answer
dict
<p>I just started playing with Python and was hoping to get some feedback regarding the quality of the following snippet. Does this look like proper Python? What would you change? Is this small script well structured?</p> <p>Quick description of functional goal: reorder list such that each element is followed by the value closest to it, starting from 20 (AKA shortest-seek-first algorithm).</p> <p>example: <code>[15, 24, 12, 13, 48, 56, 2]</code><br> becomes: <code>[24, 15, 13, 12, 2, 48, 56]</code></p> <p>better example: <code>[22, 19, 23, 18, 17, 16]</code><br> becomes: <code>[19, 18, 17, 16, 22, 23]</code></p> <pre><code>fcfs_working = [15, 24, 12, 13, 48, 56, 2] fcfs_track = [] track_number = 20 while len(fcfs_working) &gt; 0: track_number = min(fcfs_working, key=lambda x:abs(x-track_number)) fcfs_working.remove(track_number) fcfs_track.append(track_number) </code></pre>
5548
GOOD_ANSWER
{ "AcceptedAnswerId": "5554", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T05:02:50.907", "Id": "5548", "Score": "10", "Tags": [ "python" ], "Title": "Reorder list such that each element is followed by the value closest to it" }
{ "body": "<pre><code>while len(fcfs_working) &gt; 0:\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>while fcfs_working:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T14:58:03.417", "Id": "30048", "Score": "0", "body": "@GarethRees, you're right. I don't recall what I was thinking at the time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T03:39:44.840", "Id": "5554", "ParentId": "5548", "Score": "4" } }
<p>I just started playing with Python and was hoping to get some feedback regarding the quality of the following snippet. Does this look like proper Python? What would you change? Is this small script well structured?</p> <p>Quick description of functional goal: reorder list such that each element is followed by the value closest to it, starting from 20 (AKA shortest-seek-first algorithm).</p> <p>example: <code>[15, 24, 12, 13, 48, 56, 2]</code><br> becomes: <code>[24, 15, 13, 12, 2, 48, 56]</code></p> <p>better example: <code>[22, 19, 23, 18, 17, 16]</code><br> becomes: <code>[19, 18, 17, 16, 22, 23]</code></p> <pre><code>fcfs_working = [15, 24, 12, 13, 48, 56, 2] fcfs_track = [] track_number = 20 while len(fcfs_working) &gt; 0: track_number = min(fcfs_working, key=lambda x:abs(x-track_number)) fcfs_working.remove(track_number) fcfs_track.append(track_number) </code></pre>
5548
WEIRD
{ "AcceptedAnswerId": "5554", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T05:02:50.907", "Id": "5548", "Score": "10", "Tags": [ "python" ], "Title": "Reorder list such that each element is followed by the value closest to it" }
{ "body": "<p>I'm not familiar with the shortest-seek-first algorithm. However, it may work to calculate the distances of each number in the list from the current position, sort that and then output the results. Consequently:</p>\n\n<pre><code>working = [15, 24, 12, 13, 48, 56, 2]\nposition = 20\ndistances = [(abs(position-x), x) for x in working]\n&gt;&gt; [(5, 15), (4, 24), (8, 12), (7, 13), (28, 48), (36, 56), (18, 2)]\ndistances.sort()\n&gt;&gt; [(4, 24), (5, 15), (7, 13), (8, 12), (18, 2), (28, 48), (36, 56)]\n[x[1] for x in distances]\n&gt;&gt; [24, 15, 13, 12, 2, 48, 56]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-24T16:42:53.053", "Id": "30255", "Score": "0", "body": "not working as expected, for example: `working = [15, 24, 12, 13, 25, 56, 2]` results with `[24, 15, 25, 13, 12, 2, 56]`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-20T21:22:58.190", "Id": "18860", "ParentId": "5548", "Score": "0" } }
<p>I just started playing with Python and was hoping to get some feedback regarding the quality of the following snippet. Does this look like proper Python? What would you change? Is this small script well structured?</p> <p>Quick description of functional goal: reorder list such that each element is followed by the value closest to it, starting from 20 (AKA shortest-seek-first algorithm).</p> <p>example: <code>[15, 24, 12, 13, 48, 56, 2]</code><br> becomes: <code>[24, 15, 13, 12, 2, 48, 56]</code></p> <p>better example: <code>[22, 19, 23, 18, 17, 16]</code><br> becomes: <code>[19, 18, 17, 16, 22, 23]</code></p> <pre><code>fcfs_working = [15, 24, 12, 13, 48, 56, 2] fcfs_track = [] track_number = 20 while len(fcfs_working) &gt; 0: track_number = min(fcfs_working, key=lambda x:abs(x-track_number)) fcfs_working.remove(track_number) fcfs_track.append(track_number) </code></pre>
5548
GOOD_ANSWER
{ "AcceptedAnswerId": "5554", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T05:02:50.907", "Id": "5548", "Score": "10", "Tags": [ "python" ], "Title": "Reorder list such that each element is followed by the value closest to it" }
{ "body": "<p>From the algorithmic perspective, I'd like to suggest another solution (regardless to Python as a language).</p>\n\n<p>Here goes:</p>\n\n<p>let's assume that all items in the given array are different. the other case has a similar solution, so let's focus on the algorithm itself.</p>\n\n<ol>\n<li>Find the nearest number, in terms of distance, from the array to the given external number (20).</li>\n<li>sort the given array.</li>\n<li>find the value in (1) in the array. it can be done using a binary search.</li>\n<li>now, to the main point: the next value would be either to the left of the current value or to the right of the current value, since the distance is now between the next value to the current one, and the array is sorted (!).</li>\n<li>so all you have to do is to hold two additional indexes: inner-left and inner-right. these indexes represent the inner boundaries of the \"hole\" that is being created while constructing the new list.</li>\n</ol>\n\n<p>Demonstration:</p>\n\n<p>original array:</p>\n\n<pre>\n[22, 19, 23, 18, 17, 8]\n</pre>\n\n<p>sorted:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n</pre>\n\n<p>first element is 19, since abs(20-19) = 1 is the nearest distance to 20.<br>\nlet's find 19 in the sorted array:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n ^\n</pre>\n\n<p>now the next element would be either 18 or 22, since the array is already sorted:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n ? ^ ?\n</pre>\n\n<p>so now we have those inner-left and inner-right indexes, let's label them as \"il\" and \"ir\".</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n il ^ ir\n\nresult list: [19]\n</pre>\n\n<p>since 18 is closer to 19 than 22, we take it, and shift il to the left:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n il ^ ir\n\nresult list: [19, 18]\n</pre>\n\n<p>again, now 17 is closer to 18 than 22</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n il ^ ir\n\nresult list: [19, 18, 17]\n</pre>\n\n<p>now 22 is closer to 17 than 8, so we'd shift the right-index:</p>\n\n<pre>\n[8, 17, 18, 19, 22, 23]\n il ^ ir\n\nresult list: [19, 18, 17, 22]\n</pre>\n\n<p>and the rest is obvious.</p>\n\n<p>Again, this has nothing to do with Python in particular. It's purely an algorithm to be implemented in any language.</p>\n\n<p>This algorithm takes O(n log(n)) in time, while the one suggested by the original poster takes O(n^2) in time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-23T09:51:18.787", "Id": "18926", "ParentId": "5548", "Score": "3" } }
<p>I'm working on a feature for the <a href="http://github.com/jessemiller/HamlPy" rel="nofollow">HamlPy (Haml for Django)</a> project:</p> <h2>About Haml</h2> <p>For those who don't know, Haml is an indentation-based markup language which compiles to HTML:</p> <pre><code>%ul#atheletes - for athelete in athelete_list %li.athelete{'id': 'athelete_{{ athelete.pk }}'}= athelete.name </code></pre> <p>compiles to</p> <pre><code>&lt;ul id='atheletes'&gt; {% for athelete in athelete_list %} &lt;li class='athelete' id='athelete_{{ athelete.pk }}'&gt;{{ athelete.name }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <h2>The code</h2> <p><code>{'id': 'athelete_{{ athelete.pk }}'}</code> is referred to as the 'attribute dictionary'. It is an (almost) valid Python dictionary and is currently parsed with some very ugly regular expressions and an <code>eval()</code>. However, I would like to add some features to it that would no longer make it a valid Python dictionary, e.g. using Haml within the attributes:</p> <pre><code>%a.link{ 'class': - if forloop.first link-first - else - if forloop.last link-last 'href': - url some_view } </code></pre> <p>among other things.</p> <p>I began by writing a class which I could swap out for the eval and would pass all of the current tests: </p> <pre><code>import re # Valid characters for dictionary key re_key = re.compile(r'[a-zA-Z0-9-_]+') re_nums = re.compile(r'[0-9\.]+') class AttributeParser: """Parses comma-separated HamlPy attribute values""" def __init__(self, data, terminator): self.terminator=terminator self.s = data.lstrip() # Index of current character being read self.ptr=1 def consume_whitespace(self, include_newlines=False): """Moves the pointer to the next non-whitespace character""" whitespace = (' ', '\t', '\r', '\n') if include_newlines else (' ', '\t') while self.ptr&lt;len(self.s) and self.s[self.ptr] in whitespace: self.ptr+=1 return self.ptr def consume_end_of_value(self): # End of value comma or end of string self.ptr=self.consume_whitespace() if self.s[self.ptr] != self.terminator: if self.s[self.ptr] == ',': self.ptr+=1 else: raise Exception("Expected comma for end of value (after ...%s), but got '%s' instead" % (self.s[max(self.ptr-10,0):self.ptr], self.s[self.ptr])) def read_until_unescaped_character(self, closing, pos=0): """ Moves the dictionary string starting from position *pos* until a *closing* character not preceded by a backslash is found. Returns a tuple containing the string which was read (without any preceding backslashes) and the number of characters which were read. """ initial_pos=pos while pos&lt;len(self.s): if self.s[pos]==closing and (pos==initial_pos or self.s[pos-1]!='\\'): break pos+=1 return (self.s[initial_pos:pos].replace('\\'+closing,closing), pos-initial_pos+1) def parse_value(self): self.ptr=self.consume_whitespace() # Invalid initial value val=False if self.s[self.ptr]==self.terminator: return val # String if self.s[self.ptr] in ("'",'"'): quote=self.s[self.ptr] self.ptr += 1 val,characters_read = self.read_until_unescaped_character(quote, pos=self.ptr) self.ptr += characters_read # Django variable elif self.s[self.ptr:self.ptr+2] == '={': self.ptr+=2 val,characters_read = self.read_until_unescaped_character('}', pos=self.ptr) self.ptr += characters_read val="{{ %s }}" % val # Django tag elif self.s[self.ptr:self.ptr+2] in ['-{', '#{']: self.ptr+=2 val,characters_read = self.read_until_unescaped_character('}', pos=self.ptr) self.ptr += characters_read val=r"{%% %s %%}" % val # Boolean Attributes elif self.s[self.ptr:self.ptr+4] in ['none','None']: val = None self.ptr+=4 # Integers and floats else: match=re_nums.match(self.s[self.ptr:]) if match: val = match.group(0) self.ptr += len(val) if val is False: raise Exception("Failed to parse dictionary value beginning at: %s" % self.s[self.ptr:]) self.consume_end_of_value() return val class AttributeDictParser(AttributeParser): """ Parses a Haml element's attribute dictionary string and provides a Python dictionary of the element attributes """ def __init__(self, s): AttributeParser.__init__(self, s, '}') self.dict={} def parse(self): while self.ptr&lt;len(self.s)-1: key = self.__parse_key() # Tuple/List parsing self.ptr=self.consume_whitespace() if self.s[self.ptr] in ('(', '['): tl_parser = AttributeTupleAndListParser(self.s[self.ptr:]) val = tl_parser.parse() self.ptr += tl_parser.ptr self.consume_end_of_value() else: val = self.parse_value() self.dict[key]=val return self.dict def __parse_key(self): '''Parse key variable and consume up to the colon''' self.ptr=self.consume_whitespace(include_newlines=True) # Consume opening quote quote=None if self.s[self.ptr] in ("'",'"'): quote = self.s[self.ptr] self.ptr += 1 # Extract key if quote: key,characters_read = self.read_until_unescaped_character(quote, pos=self.ptr) self.ptr+=characters_read else: key_match = re_key.match(self.s[self.ptr:]) if key_match is None: raise Exception("Invalid key beginning at: %s" % self.s[self.ptr:]) key = key_match.group(0) self.ptr += len(key) # Consume colon ptr=self.consume_whitespace() if self.s[self.ptr]==':': self.ptr+=1 else: raise Exception("Expected colon for end of key (after ...%s), but got '%s' instead" % (self.s[max(self.ptr-10,0):self.ptr], self.s[self.ptr])) return key def render_attributes(self): attributes=[] for k, v in self.dict.items(): if k != 'id' and k != 'class': # Boolean attributes if v==None: attributes.append( "%s" % (k,)) else: attributes.append( "%s='%s'" % (k,v)) return ' '.join(attributes) class AttributeTupleAndListParser(AttributeParser): def __init__(self, s): if s[0]=='(': terminator = ')' elif s[0]=='[': terminator = ']' AttributeParser.__init__(self, s, terminator) def parse(self): lst=[] # Todo: Must be easier way... val=True while val != False: val = self.parse_value() if val != False: lst.append(val) self.ptr +=1 if self.terminator==')': return tuple(lst) else: return lst </code></pre> <p>The class can be used stand-alone as follows:</p> <pre><code>&gt;&gt;&gt; from attribute_dict_parser import AttributeDictParser &gt;&gt;&gt; a=AttributeDictParser("{'id': 'a', 'class': 'b'}") &gt;&gt;&gt; d=a.parse() &gt;&gt;&gt; d {'id': 'a', 'class': 'b'} &gt;&gt;&gt; type(d) &lt;type 'dict'&gt; </code></pre> <p><code>AttributeDictParser</code> iterates through characters in <code>s</code> (the attribute dictionary) and uses the variable <code>ptr</code> to track its location (to prevent unnecessary string splicing). The function <code>parse_key</code> parses the keys (<code>'id':</code> and <code>'class':</code>), and the function <code>parse_value</code> parses the values (<code>'a'</code> and <code>'b'</code>). parse_value works with data types other than strings. It returns <code>False</code> if it reaches the end of the attribute dictionary, because <code>Null</code> is a valid value to return.</p> <p><code>AttributeTupleAndListParser</code> parses list and tuple values, as these are valid values (e.g. <code>{'id': ['a','b','c']}</code>. </p> <p>Both of these classes inherit from <code>AttributeParser</code> because they share the same way of parsing values.</p> <h2>Questions:</h2> <ol> <li><p>Is this a sensible approach? Am I insane to think that I can move from <code>eval()</code>ing the code as a Python dictionary to a custom parser without causing issues for users, just because it passes the tests?</p></li> <li><p>I'm worried that the performance hit of writing a parser in an interpreted language will be too much compared to doing the <code>eval()</code>. I've written similar things before for parsing JSON expressions, and was dismayed that for all my optimisations, the two-line regular expression won on the benchmarks. I will do some profiling on it once I've tidied up a few things. Are there any notable ineffeciencies in my approach?</p></li> <li><p>There are some things in the old parser that have not been ported to the new one (e.g. supporting the Ruby Haml <code>=&gt;</code> syntax). This feature has never been documented however and I doubt anybody knows it's there. What is a good rule of thumb for breaking an undocumented feature in open source projects?</p></li> <li><p>I would welcome any feedback on my coding style, as I don't get to be around other developers much.</p></li> </ol>
15395
GOOD_ANSWER
{ "AcceptedAnswerId": "15450", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T22:45:31.233", "Id": "15395", "Score": "5", "Tags": [ "python", "parsing", "django", "haml" ], "Title": "Python parser for attributes in a HAML template" }
{ "body": "<h3>1. Answers to your questions</h3>\n<ol>\n<li><p>If the goal of the project is to be able to include Haml in attribute values, then you've got no choice but to switch to your own parser. I haven't looked at the set of test cases, but it does seem plausible that you are going to introduce incompatibilities because of the complexity of Python's own parser. You are going to find that you have users who used the oddities of Python's string syntax (<code>r</code>-strings, <code>\\u</code>-escapes and all).</p>\n<p>The way to manage the transition from the old parser to the new is to start out by shipping both, with the old parser selected by default, but the new parser selectable with an option. This gives your users time to discover the incompatibilities and fix them (or submit bug reports). Then in a later release make the new parser the default, but with the old parser available but deprecated. Finally, remove the old parser.</p>\n</li>\n<li><p>Correctness and simplicity first, speed later. You can always port the parser to C if nothing else will do.</p>\n</li>\n<li><p>My answer to question 1 applies here too.</p>\n</li>\n<li><p>See below.</p>\n</li>\n</ol>\n<h3>2. Designing a parser</h3>\n<p>Now, let's look at the code. I thought about making a series of comments on the various misfeatures, but that seems less than helpful, given that the whole design of the parser isn't quite right:</p>\n<ol>\n<li><p>There's no separation between the lexer and the parser.</p>\n</li>\n<li><p>You have different classes for different productions in your syntax, so that each time you need to parse a tuple/list, you construct a new <code>AttributeTupleAndListParser</code> object, construct a string for it to parse (by copying the tail of the original string), and then throw away the parser object when done.</p>\n</li>\n<li><p>Some of your parsing methods don't seem well-matched to the syntax of the language, making it difficult to understand what they do. <code>consume_end_of_value</code> is a good example: it doesn't seem to correspond to anything natural in the syntax.</p>\n</li>\n</ol>\n<p>Computer science is by no means a discipline with all the answers, but one thing that we know how to do is write a parser! You don't have to have read <a href=\"http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools\" rel=\"noreferrer\">the dragon book</a> from cover to cover to know that it's conventional to develop a <a href=\"http://en.wikipedia.org/wiki/Formal_grammar\" rel=\"noreferrer\"><em>formal grammar</em></a> for your language (often written down in a variation on <a href=\"http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form\" rel=\"noreferrer\">Backus–Naur form</a>), and then split your code into a <a href=\"http://en.wikipedia.org/wiki/Lexical_analysis\" rel=\"noreferrer\"><em>lexical analyzer</em></a> (which transforms source code into <em>tokens</em> using a finite state machine or something similar) and a <a href=\"http://en.wikipedia.org/wiki/Parsing\" rel=\"noreferrer\"><em>parser</em></a> which takes a stream of tokens and constructs a <em>syntax tree</em> or some other form of output based on the syntax of the input.</p>\n<p>Sticking to this convention has a bunch of advantages: the existence of a formal grammar makes it easier to build compatible implementations; you can modify and test the lexical analyzer independently from the parser and vice versa; and other programmers will find it easier to understand and modify your code.</p>\n<h3>3. Rewriting your parser conventionally</h3>\n<p>Here's how I might start rewriting your parser to use the conventional approach. This implements a deliberately incomplete subset of the HamlPy attribute language, in order to keep the code short and to get it finished in a reasonable amount of time.</p>\n<p>First, a class whose instances represent source tokens. The original string and position of each token is recorded in that token so that we can easily produce an error message related to that token. I've used the built-in exception <code>SyntaxError</code> here so that the error messages match those from other Python libraries. (You might later want to extend this so that the class can represent tokens from files as well as tokens from strings.)</p>\n<pre><code>class Token(object):\n &quot;&quot;&quot;\n An object representing a token in a HamlPy document. Construct it\n using `Token(type, value, source, start, end)` where:\n\n `type` is the token type (`Token.DELIMITER`, `Token.STRING`, etc);\n `value` is the token value;\n `source` is the string from which the token was taken;\n `start` is the character position in `source` where the token starts;\n `ends` is the character position in `source` where the token finishes.\n &quot;&quot;&quot;\n\n # Enumeration of token types.\n DELIMITER = 1\n STRING = 2\n END = 3\n ERROR = 4\n\n def __init__(self, type, value, source, start, end):\n self.type = type\n self.value = value\n self.source = source\n self.start = start\n self.end = end\n\n def __repr__(self):\n type_name = 'UNKNOWN'\n for attr in dir(self):\n if getattr(self, attr) == self.type:\n type_name = attr\n break\n return ('Token(Token.{0}, {1}, {2}, {3}, {4})'\n .format(type_name, repr(self.value), repr(self.source),\n self.start, self.end))\n\n def matches(self, type, value):\n &quot;&quot;&quot;\n Return True iff this token matches the given `type` and `value`.\n &quot;&quot;&quot;\n return self.type == type and self.value == value\n\n def error(self, msg):\n &quot;&quot;&quot;\n Return a `SyntaxError` object describing a problem with this\n token. The argument `msg` is the error message; the token's\n line number and position are also reported.\n &quot;&quot;&quot;\n line_start = 1 + self.source.rfind('\\n', 0, self.start)\n line_end = self.source.find('\\n', self.end)\n if line_end == -1: line_end = len(self.source)\n e = SyntaxError(msg)\n e.lineno = 1 + self.source.count('\\n', 0, self.start)\n e.text = self.source[line_start: line_end]\n e.offset = self.start - line_start + 1\n return e\n</code></pre>\n<p>Second, the lexical analyzer, using Python's <a href=\"http://docs.python.org/library/stdtypes.html#iterator-types\" rel=\"noreferrer\">iterator protocol</a>.</p>\n<pre><code>class Tokenizer(object):\n &quot;&quot;&quot;\n Tokenizer for a subset of HamlPy. Instances of this class support\n the iterator protocol, and yield tokens from the string `s` as\n Token object. When the string `s` runs out, yield an END token.\n\n &gt;&gt;&gt; from pprint import pprint\n &gt;&gt;&gt; pprint(list(Tokenizer('{&quot;a&quot;:&quot;b&quot;}')))\n [Token(Token.DELIMITER, '{', '{&quot;a&quot;:&quot;b&quot;}', 0, 1),\n Token(Token.STRING, 'a', '{&quot;a&quot;:&quot;b&quot;}', 2, 3),\n Token(Token.DELIMITER, ':', '{&quot;a&quot;:&quot;b&quot;}', 4, 5),\n Token(Token.STRING, 'b', '{&quot;a&quot;:&quot;b&quot;}', 6, 7),\n Token(Token.DELIMITER, '}', '{&quot;a&quot;:&quot;b&quot;}', 8, 9),\n Token(Token.END, '', '{&quot;a&quot;:&quot;b&quot;}', 9, 9)]\n &quot;&quot;&quot;\n def __init__(self, s):\n self.iter = self.tokenize(s)\n\n def __iter__(self):\n return self\n\n def next(self):\n return next(self.iter)\n\n # Regular expression matching a source token.\n token_re = re.compile(r'''\n \\s* # Ignore initial whitespace\n (?:([][{},:]) # 1. Delimiter\n |'([^\\\\']*(?:\\\\.[^\\\\']*)*)' # 2. Single-quoted string\n |&quot;([^\\\\&quot;]*(?:\\\\.[^\\\\&quot;]*)*)&quot; # 3. Double-quoted string\n |(\\S) # 4. Something else\n )''', re.X)\n\n # Regular expression matching a backslash and following character.\n backslash_re = re.compile(r'\\\\(.)')\n\n def tokenize(self, s):\n for m in self.token_re.finditer(s):\n if m.group(1):\n yield Token(Token.DELIMITER, m.group(1),\n s, m.start(1), m.end(1))\n elif m.group(2):\n yield Token(Token.STRING,\n self.backslash_re.sub(r'\\1', m.group(2)),\n s, m.start(2), m.end(2))\n elif m.group(3):\n yield Token(Token.STRING,\n self.backslash_re.sub(r'\\1', m.group(3)),\n s, m.start(3), m.end(3))\n else:\n t = Token(Token.ERROR, m.group(4), s, m.start(4), m.end(4))\n raise t.error('Unexpected character')\n yield Token(Token.END, '', s, len(s), len(s))\n</code></pre>\n<p>And third, the <a href=\"http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools\" rel=\"noreferrer\">recursive descent</a> parser, with the formal grammar given in the docstring for the class. The parser needs one token of <a href=\"http://en.wikipedia.org/wiki/Parsing#Lookahead\" rel=\"noreferrer\">lookahead</a>.</p>\n<pre><code>class Parser(object):\n &quot;&quot;&quot;\n Parser for the subset of HamlPy with the following grammar:\n\n attribute-dict ::= '{' [attribute-list] '}'\n attribute-list ::= attribute (',' attribute)*\n attribute ::= string ':' value\n value ::= string | '[' [value-list] ']'\n value-list ::= value (',' value)*\n &quot;&quot;&quot;\n\n def __init__(self, s):\n self.tokenizer = Tokenizer(s)\n self.lookahead = None # The lookahead token.\n self.next_token() # Lookahead one token.\n\n def next_token(self):\n &quot;&quot;&quot;\n Return the next token from the lexer and update the lookahead\n token.\n &quot;&quot;&quot;\n t = self.lookahead\n self.lookahead = next(self.tokenizer)\n return t\n\n # Regular expression matching an allowable key.\n key_re = re.compile(r'[a-zA-Z_0-9-]+$')\n\n def parse_value(self):\n t = self.next_token()\n if t.type == Token.STRING:\n return t.value\n elif t.matches(Token.DELIMITER, '['):\n return list(self.parse_value_list())\n else:\n raise t.error('Expected a value')\n\n def parse_value_list(self):\n if self.lookahead.matches(Token.DELIMITER, ']'):\n self.next_token()\n return\n while True:\n yield self.parse_value()\n t = self.next_token()\n if t.matches(Token.DELIMITER, ']'):\n return\n elif not t.matches(Token.DELIMITER, ','):\n raise t.error('Expected &quot;,&quot; or &quot;]&quot;')\n\n def parse_attribute(self):\n t = self.next_token()\n if t.type != Token.STRING:\n raise t.error('Expected a string')\n key = t.value\n if not self.key_re.match(key):\n raise t.error('Invalid key')\n t = self.next_token()\n if not t.matches(Token.DELIMITER, ':'):\n raise t.error('Expected &quot;:&quot;')\n value = self.parse_value()\n return key, value\n\n def parse_attribute_list(self):\n if self.lookahead.matches(Token.DELIMITER, '}'):\n self.next_token()\n return\n while True:\n yield self.parse_attribute()\n t = self.next_token()\n if t.matches(Token.DELIMITER, '}'):\n return\n elif not t.matches(Token.DELIMITER, ','):\n raise t.error('Expected &quot;,&quot; or &quot;}&quot;')\n\n def parse_attribute_dict(self):\n t = self.next_token()\n if not t.matches(Token.DELIMITER, '{'):\n raise t.error('Expected &quot;{&quot;')\n return dict(self.parse_attribute_list())\n</code></pre>\n<p>You'll probably want to know how to handle Haml's significant whitespace. The way to do this is to modify the tokenizer to emit <code>NEWLINE</code>, <code>INDENT</code> and <code>DEDENT</code> tokens, and then modify <code>next_token</code> to take an <code>include_newlines</code> optional parameter, and discard or return these extra tokens as appropriate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-09T17:16:51.363", "Id": "15450", "ParentId": "15395", "Score": "7" } }
<p>I'm trying to learn how to write functional code with Python and have found some tutorials online. Please note that I know Python is not a promoter for functional programming. I just want to try it out. <a href="http://anandology.com/python-practice-book/functional-programming.html">One tutorial</a> in particular gives this as an exercise:</p> <blockquote> <p>Write a function flatten_dict to flatten a nested dictionary by joining the keys with . character.</p> </blockquote> <p>So I decided to give it a try. Here is what I have and it works fine:</p> <pre><code>def flatten_dict(d, result={}, prv_keys=[]): for k, v in d.iteritems(): if isinstance(v, dict): flatten_dict(v, result, prv_keys + [k]) else: result['.'.join(prv_keys + [k])] = v return result </code></pre> <p>I'd like to know whether this is the best way to solve the problem in python. In particular, I really don't like to pass a list of previous keys to the recursive call. </p>
21033
null
{ "AcceptedAnswerId": "21035", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:08:41.920", "Id": "21033", "Score": "14", "Tags": [ "python", "functional-programming" ], "Title": "Flatten dictionary in Python (functional style)" }
{ "body": "<p>Your solution really isn't at all functional. You should return a flattened dict and then merge that into your current dictionary. You should also not modify the dictionary, instead create it with all the values it should have. Here is my approach:</p>\n\n<pre><code>def flatten_dict(d):\n def items():\n for key, value in d.items():\n if isinstance(value, dict):\n for subkey, subvalue in flatten_dict(value).items():\n yield key + \".\" + subkey, subvalue\n else:\n yield key, value\n\n return dict(items())\n</code></pre>\n\n<p>Alternative which avoids yield</p>\n\n<pre><code>def flatten_dict(d):\n def expand(key, value):\n if isinstance(value, dict):\n return [ (key + '.' + k, v) for k, v in flatten_dict(value).items() ]\n else:\n return [ (key, value) ]\n\n items = [ item for k, v in d.items() for item in expand(k, v) ]\n\n return dict(items)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:39:53.393", "Id": "33764", "Score": "0", "body": "Thanks. I was trying to iterate through the result during each recursive step but it returns an error stating the size of the dictionary changed. I'm new to python and I barely understand yield. Is it because yield creates the value on the fly without storing them that the code is not blocked anymore?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:45:27.547", "Id": "33765", "Score": "0", "body": "One thing though. I did return a flattened dict and merged it into a current dictionary, which is the flattened result of the original dictionary. I'd like to know why it was not functional at all..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:05:55.500", "Id": "33767", "Score": "0", "body": "@LimH., if you got that error you were modifying the dictionary you were iterating over. If you are trying to be functional, you shouldn't be modifying dictionaries at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:07:34.050", "Id": "33769", "Score": "0", "body": "No, you did not return a flattened dict and merge it. You ignore the return value of your recursive function call. Your function modifies what is passed to it which is exactly that which you aren't supposed to do in functional style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:08:37.700", "Id": "33771", "Score": "0", "body": "yield does create values on the fly, but that has nothing to do with why this works. It works because it creates new objects and never attempts to modify the existing ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T17:09:11.227", "Id": "33772", "Score": "0", "body": "I see my mistakes now. Thank you very much :) I thought I was passing copies of result to the function. In fact, I think the author of the tutorial I'm following makes the same mistake, at least with the flatten_list function: http://anandology.com/python-practice-book/functional-programming.html#example-flatten-a-list" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:49:06.400", "Id": "33785", "Score": "0", "body": "Unfortunately, both versions are bugged for 3+ levels of recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T21:36:07.440", "Id": "33793", "Score": "2", "body": "@JohnOptionalSmith, I see the problem in the second version, but the first seems to work for me... test case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:17:53.050", "Id": "33807", "Score": "0", "body": "@WinstonEwert Try it with `a = { 'a' : 1, 'b' : { 'leprous' : 'bilateral' }, 'c' : { 'sigh' : 'somniphobia'} }` (actually triggers the bug with 2-level recursion)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:33:31.610", "Id": "33810", "Score": "0", "body": "My bad ! CopyPaste error ! Your first version is fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:01:49.873", "Id": "272490", "Score": "0", "body": "Thanks for this nice code snippet @WinstonEwert! Could you explain why you defined a function in a function here? Is there a benefit to doing this instead of defining the same functions outside of one another?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:20:31.280", "Id": "272493", "Score": "2", "body": "@zelusp, the benefit is organizational, the function inside the function is part of of the implementation of the outer function, and putting the function inside makes it clear and prevents other functions from using it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-24T21:33:43.197", "Id": "272496", "Score": "0", "body": "[This link](https://realpython.com/blog/python/inner-functions-what-are-they-good-for/) helped me understand better" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:20:49.623", "Id": "21035", "ParentId": "21033", "Score": "19" } }
<p>I'm trying to learn how to write functional code with Python and have found some tutorials online. Please note that I know Python is not a promoter for functional programming. I just want to try it out. <a href="http://anandology.com/python-practice-book/functional-programming.html">One tutorial</a> in particular gives this as an exercise:</p> <blockquote> <p>Write a function flatten_dict to flatten a nested dictionary by joining the keys with . character.</p> </blockquote> <p>So I decided to give it a try. Here is what I have and it works fine:</p> <pre><code>def flatten_dict(d, result={}, prv_keys=[]): for k, v in d.iteritems(): if isinstance(v, dict): flatten_dict(v, result, prv_keys + [k]) else: result['.'.join(prv_keys + [k])] = v return result </code></pre> <p>I'd like to know whether this is the best way to solve the problem in python. In particular, I really don't like to pass a list of previous keys to the recursive call. </p>
21033
GOOD_ANSWER
{ "AcceptedAnswerId": "21035", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T16:08:41.920", "Id": "21033", "Score": "14", "Tags": [ "python", "functional-programming" ], "Title": "Flatten dictionary in Python (functional style)" }
{ "body": "<p>Beside avoiding mutations, functional mindset demands to split into elementary functions, along two axes:</p>\n\n<ol>\n<li>Decouple responsibilities.</li>\n<li>By case analysis (eg pattern matching). Here scalar vs dict. </li>\n</ol>\n\n<p>Regarding 1, nested dict traversal has nothing to do with the requirement to create dot separated keys. We've better return a list a keys, and concatenate them afterward. Thus, if you change your mind (using another separator, making abbreviations...), you don't have to dive in the iterator code -and worse, modify it.</p>\n\n<pre><code>def iteritems_nested(d):\n def fetch (suffixes, v0) :\n if isinstance(v0, dict):\n for k, v in v0.items() :\n for i in fetch(suffixes + [k], v): # \"yield from\" in python3.3\n yield i\n else:\n yield (suffixes, v0)\n\n return fetch([], d)\n\ndef flatten_dict(d) :\n return dict( ('.'.join(ks), v) for ks, v in iteritems_nested(d))\n #return { '.'.join(ks) : v for ks,v in iteritems_nested(d) }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T09:27:12.087", "Id": "33806", "Score": "0", "body": "Thank you for your response. Let me see if I get this right. Basically there are two strategies here. One is to recursively construct the dictionary result and one is to construct the suffixes. I used the second approach but my mistake was that I passed a reference of the result down the recursive chains but the key part is correct. Is that right? Winston Etwert used the first approach right? What's wrong with his code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:25:24.513", "Id": "33808", "Score": "0", "body": "The point is to (a) collect keys until deepest level and (b) concatenate them. You indeed did separate the two (although packed in the same function). Winston concatenate on the fly without modifying (mutating) anything, but an issue lies in recursion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T10:34:48.367", "Id": "33811", "Score": "0", "body": "My bad : Winston's implementation with yield is ok !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T11:38:34.250", "Id": "33818", "Score": "0", "body": "Is packing multiple objectives in the same function bad? I.e., is it bad style or is it conceptually incorrect?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-30T21:01:43.017", "Id": "33859", "Score": "0", "body": "@LimH. [Both !](http://www.cs.utexas.edu/~shmat/courses/cs345/whyfp.pdf). It can be necessary for performance reason, since Python won't neither inline nor defer computation (lazy programming). To alleviate this point, you can follow the opposite approach : provide to the iterator the way to collect keys -via a folding function- (strategy pattern, kind of)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-29T20:47:57.963", "Id": "21045", "ParentId": "21033", "Score": "9" } }
<p>I have a grid as </p> <pre><code>&gt;&gt;&gt; data = np.zeros((3, 5)) &gt;&gt;&gt; data array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]] </code></pre> <p>i wrote a function in order to get the ID of each tile.</p> <pre><code>array([[(0,0), (0,1), (0,2), (0,3), (0,4)], [(1,0), (1,1), (1,2), (1,3), (1,4)], [(2,0), (2,1), (2,2), (2,3), (2,4)]] def get_IDgrid(nx,ny): lstx = list() lsty = list() lstgrid = list() for p in xrange(ny): lstx.append([p]*nx) for p in xrange(ny): lsty.append(range(0,nx)) for p in xrange(ny): lstgrid.extend(zip(lstx[p],lsty[p])) return lstgrid </code></pre> <p>where nx is the number of columns and ny the number of rows</p> <pre><code>test = get_IDgrid(5,3) print test [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)] </code></pre> <p>this function will be embed inside a class</p> <pre><code>class Grid(object): __slots__= ("xMin","yMax","nx","ny","xDist","yDist","ncell") def __init__(self,xMin,yMax,nx,ny,xDist,yDist): self.xMin = xMin self.yMax = yMax self.nx = nx self.ny = ny self.xDist = xDist self.yDist= yDist self.ncell = nx*ny </code></pre>
22968
GOOD_ANSWER
{ "AcceptedAnswerId": "22973", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T16:33:57.390", "Id": "22968", "Score": "1", "Tags": [ "python", "optimization", "performance" ], "Title": "python Improve a function in a elegant way" }
{ "body": "<p>Numpy has built in functions for most simple tasks like this one. In your case, <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html\" rel=\"nofollow\"><code>numpy.ndindex</code></a> should do the trick:</p>\n\n<pre><code>&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; [j for j in np.ndindex(3, 5)]\n[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]\n</code></pre>\n\n<p>You can get the same result in a similarly compact way using <a href=\"http://docs.python.org/2/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a> :</p>\n\n<pre><code>&gt;&gt;&gt; import itertools\n&gt;&gt;&gt; [j for j in itertools.product(xrange(3), xrange(5))]\n[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),\n (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]\n</code></pre>\n\n<p><strong>EDIT</strong> Note that the (now corrected) order of the parameters is reversed with respect to the OP's <code>get_IDgrid</code>.</p>\n\n<p>Both expressions above require a list comprehension, because what gets returned is a generator. You may want to consider whether you really need the whole list of index pairs, or if you could consume them one by one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:28:55.673", "Id": "35374", "Score": "0", "body": "Thanks @jaime. Do you think insert the def of [j for j in np.ndindex(5, 3)] in the class can be correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:33:07.450", "Id": "35376", "Score": "0", "body": "@Gianni It is kind of hard to tell without knowing what exactly you are trying to accomplish. I can't think of any situation in which I would want to store a list of all possible indices to a numpy array, but if you really do need it, then I guess it is OK." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:34:34.857", "Id": "35379", "Score": "0", "body": "@jamie with [j for j in np.ndindex(5, 3)] return a different result respect my function and the Grid (see the example). Just invert the example :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:47:24.460", "Id": "35381", "Score": "1", "body": "@Gianni I did notice that, it is now corrected. What `np.ndindex` does is what is known as [row major order](http://en.wikipedia.org/wiki/Row-major_order) arrays, which is the standard in C language, and the default in numpy. What your function is doing is column major order, which is the Fortran and Matlab way. If you are using numpy, it will probably make your life easier if you stick to row major." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T17:27:13.847", "Id": "22973", "ParentId": "22968", "Score": "4" } }
<p>I have been working on a project where I needed to analyze multiple, large datasets contained inside many CSV files at the same time. I am not a programmer but an engineer, so I did a lot of searching and reading. Python's stock CSV module provides the basic functionality, but I had a lot of trouble getting the methods to run quickly on 50k-500k rows since many strategies were simply appending. I had lots of problems getting what I wanted and I saw the same questions asked over and over again. I decided to spend some time and write a class that performed these functions and would be portable. If nothing else, myself and other people I work with could use it.</p> <p>I would like some input on the class and any suggestions you may have. I am not a programmer and don't have any formal background so this has been a good OOP intro for me. The end result is in two lines you can read all CSV files in a folder into memory as either pure Python lists or, as lists of NumPy arrays. I have tested it in many scenarios and hopefully found most of the bugs. I'd like to think this is good enough that other people can just copy and paste into their code and move on to the more important stuff. I am open to all critiques and suggestions. Is this something you could use? If not, why?</p> <p>You can try it with generic CSV data. The standard Python lists are flexible in size and data type. NumPy will only work with numeric (float specifically) data that is rectangular in format:</p> <pre><code>x, y, z, 1, 2, 3, 4, 5, 6, ... import numpy as np import csv import os import sys class EasyCSV(object): """Easily open from and save CSV files using lists or numpy arrays. Initiating and using the class is as easy as CSV = EasyCSV('location'). The class takes the following arguements: EasyCSV(location, width=None, np_array='false', skip_rows=0) location is the only mandatory field and is string of the folder location containing .CSV file(s). width is optional and specifies a constant width. The default value None will return a list of lists with variable width. When used with numpy the array will have the dimensions of the first valid numeric row of data. np_array will create a fixed-width numpy array of only float values. skip_rows will skip the specified rows at the top of the file. """ def __init__(self, location, width=None, np_array='false', skip_rows=0): # Initialize default vairables self.np_array = np_array self.skip_rows = skip_rows self.loc = str(location) os.chdir(self.loc) self.dataFiles = [] self.width = width self.i = 0 #Find all CSV files in chosen directory. for files in os.listdir(loc): if files.endswith('CSV') or files.endswith('csv'): self.dataFiles.append(files) #Preallocate array to hold csv data later self.allData = [0] * len(self.dataFiles) def read(self,): '''Reads all files contained in the folder into memory. ''' self.Dict = {} #Stores names of files for later lookup #Main processig loop for files in self.dataFiles: self.trim = 0 self.j = 0 with open(files,'rb') as self.rawFile: print files #Read in CSV object self.newData = csv.reader(self.rawFile) self.dataList = [] #Extend iterates through CSV object and passes to datalist self.dataList.extend(self.newData) #Trims off pre specified lines at the top if self.skip_rows != 0: self.dataList = self.dataList[self.skip_rows:] #Numpy route, requires all numeric input if self.np_array == 'true': #Finds width if not specified if self.width is None: self.width = len(self.dataList[self.skip_rows]) self.CSVdata = np.zeros((len(self.dataList),self.width)) #Iterate through data and adds it to numpy array self.k = 0 for data in self.dataList: try: self.CSVdata[self.j,:] = data self.j+=1 except ValueError: #non numeric data if self.width &lt; len(data): sys.exit('Numpy array too narrow. Choose another width') self.trim+=1 pass self.k+=1 #trims off excess if not self.trim == 0: self.CSVdata = self.CSVdata[:-self.trim] #Python nested lists route; tolerates multiple data types else: #Declare required empty str arrays self.CSVdata = [0]*len(self.dataList) for rows in self.dataList: self.k = 0 self.rows = rows #Handle no width imput, flexible width if self.width is None: self.numrow = [0]*len(self.rows) else: self.numrow = [0]*self.width #Try to convert to float, fall back on string. for data in self.rows: try: self.numrow[self.k] = float(data) except ValueError: try: self.numrow[self.k] = data except IndexError: pass except IndexError: pass self.k+=1 self.CSVdata[self.j] = self.numrow self.j+=1 #append file to allData which contains all files self.allData[self.i] = self.CSVdata #trim CSV off filename and store in Dict for indexing of allData self.dataFiles[self.i] = self.dataFiles[self.i][:-4] self.Dict[self.dataFiles[self.i]] = self.i self.i+=1 def write(self, array, name, destination=None): '''Writes array in memory to file. EasyCSV.write(array, name, destination=None) array is a pointer to the array you want written to CSV name will be the name of said file destination is optional and will change the directory to the location specified. Leaving it at the default value None will overwrite any CSVs that may have been read in by the class earlier. ''' self.array = array self.name = name self.dest = destination #Optional change directory if self.dest is not None: os.chdir(self.dest) #Dict does not hold CSV, check to see if present and trim if not self.name[-4:] == '.CSV' or self.name[-4:] == '.csv': self.name = name + '.CSV' #Create files and write data, 'wb' binary req'd for Win compatibility with open(self.name,'wb') as self.newCSV: self.CSVwrite = csv.writer(self.newCSV,dialect='excel') for data in self.array: self.CSVwrite.writerow(data) os.chdir(self.loc) #Change back to original __init__.loc def lookup(self, key=None): '''Prints a preview of data to the console window with just a key input ''' self.key = key #Dict does not hold CSV, check to see if present and trim if self.key[-4:] == '.CSV' or self.key[-4:] == '.csv': self.key = key[:-4] #Print None case elif self.key is None: print self.allData[0] print self.allData[0] print '... ' * len(self.allData[0][-2]) print self.allData[0][-2] print self.allData[0] #Print everything else else: self.index = self.Dict[self.key] print self.allData[self.index][0] print self.allData[self.index][1] print '... ' * len(self.allData[self.index][-2]) print self.allData[self.index][-2] print self.allData[self.index][-1] def output(self, key=None): '''Returns the array for assignment to a var with just a key input ''' self.key = key #Dict does not hold CSV, check to see if present and trim if self.key is None: return self.allData[0] elif self.key[-4:] == '.CSV' or self.key[-4:] == '.csv': self.key = key[:-4] #Return file requested self.index = self.Dict[self.key] return self.allData[self.Dict[self.key]] ################################################ loc = 'C:\Users\Me\Desktop' CSV = EasyCSV(loc, np_array='false', width=None, skip_rows=0) CSV.read() target = 'somecsv' #with or without .csv/.CSV CSV.lookup(target) A = CSV.output(target) loc2 = 'C:\Users\Me\Desktop\New folder' for keys in CSV.Dict: print keys CSV.write(CSV.output(keys),keys,destination=loc2) </code></pre>
24836
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T20:15:44.593", "Id": "24836", "Score": "5", "Tags": [ "python", "parsing", "csv", "numpy", "portability" ], "Title": "Portable Python CSV class" }
{ "body": "<p>Some observations:</p>\n\n<ul>\n<li>You expect <code>read</code> to be called exactly once (otherwise it reads the same files again, right?). You might as well call it from <code>__init__</code> directly. Alternatively, <code>read</code> could take <code>location</code> as parameter, so one could read multiple directories into the object.</li>\n<li>You use strings <code>'true', 'false'</code> where you should use actual <code>bool</code> values <code>True, False</code></li>\n<li>You set instance variables such as <code>self.key = key</code> that you use only locally inside the function, where you could simply use the local variable <code>key</code>.</li>\n<li>The <code>read</code> method is very long. Divide the work into smaller functions and call them from <code>read</code>.</li>\n<li>You have docstrings and a fair amount of comments, good. But then you have really cryptic statements such as <code>self.i = 0</code>.</li>\n<li>Some variable names are misleading, such as <code>files</code> which is actually a single filename.</li>\n<li>Don't change the working directory (<code>os.chdir</code>). Use <code>os.path.join(loc, filename)</code> to construct paths. (If you think it's OK to change it, think what happens if you combine this module with some other module that <em>also</em> thinks it's OK)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-08T15:05:13.380", "Id": "38399", "Score": "0", "body": "This was exactly the sort of stuff I was looking for. Thanks for taking the time to look through it. You hit on a lot of the issues that came up during. Allowing for separate read paths would be really helpful. Also I need to research more on the local vars for a function. I was having problems getting them to work and found it easier to declare a self.xyz. Tan" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-08T11:31:51.730", "Id": "24852", "ParentId": "24836", "Score": "6" } }
<p>I have been working on a project where I needed to analyze multiple, large datasets contained inside many CSV files at the same time. I am not a programmer but an engineer, so I did a lot of searching and reading. Python's stock CSV module provides the basic functionality, but I had a lot of trouble getting the methods to run quickly on 50k-500k rows since many strategies were simply appending. I had lots of problems getting what I wanted and I saw the same questions asked over and over again. I decided to spend some time and write a class that performed these functions and would be portable. If nothing else, myself and other people I work with could use it.</p> <p>I would like some input on the class and any suggestions you may have. I am not a programmer and don't have any formal background so this has been a good OOP intro for me. The end result is in two lines you can read all CSV files in a folder into memory as either pure Python lists or, as lists of NumPy arrays. I have tested it in many scenarios and hopefully found most of the bugs. I'd like to think this is good enough that other people can just copy and paste into their code and move on to the more important stuff. I am open to all critiques and suggestions. Is this something you could use? If not, why?</p> <p>You can try it with generic CSV data. The standard Python lists are flexible in size and data type. NumPy will only work with numeric (float specifically) data that is rectangular in format:</p> <pre><code>x, y, z, 1, 2, 3, 4, 5, 6, ... import numpy as np import csv import os import sys class EasyCSV(object): """Easily open from and save CSV files using lists or numpy arrays. Initiating and using the class is as easy as CSV = EasyCSV('location'). The class takes the following arguements: EasyCSV(location, width=None, np_array='false', skip_rows=0) location is the only mandatory field and is string of the folder location containing .CSV file(s). width is optional and specifies a constant width. The default value None will return a list of lists with variable width. When used with numpy the array will have the dimensions of the first valid numeric row of data. np_array will create a fixed-width numpy array of only float values. skip_rows will skip the specified rows at the top of the file. """ def __init__(self, location, width=None, np_array='false', skip_rows=0): # Initialize default vairables self.np_array = np_array self.skip_rows = skip_rows self.loc = str(location) os.chdir(self.loc) self.dataFiles = [] self.width = width self.i = 0 #Find all CSV files in chosen directory. for files in os.listdir(loc): if files.endswith('CSV') or files.endswith('csv'): self.dataFiles.append(files) #Preallocate array to hold csv data later self.allData = [0] * len(self.dataFiles) def read(self,): '''Reads all files contained in the folder into memory. ''' self.Dict = {} #Stores names of files for later lookup #Main processig loop for files in self.dataFiles: self.trim = 0 self.j = 0 with open(files,'rb') as self.rawFile: print files #Read in CSV object self.newData = csv.reader(self.rawFile) self.dataList = [] #Extend iterates through CSV object and passes to datalist self.dataList.extend(self.newData) #Trims off pre specified lines at the top if self.skip_rows != 0: self.dataList = self.dataList[self.skip_rows:] #Numpy route, requires all numeric input if self.np_array == 'true': #Finds width if not specified if self.width is None: self.width = len(self.dataList[self.skip_rows]) self.CSVdata = np.zeros((len(self.dataList),self.width)) #Iterate through data and adds it to numpy array self.k = 0 for data in self.dataList: try: self.CSVdata[self.j,:] = data self.j+=1 except ValueError: #non numeric data if self.width &lt; len(data): sys.exit('Numpy array too narrow. Choose another width') self.trim+=1 pass self.k+=1 #trims off excess if not self.trim == 0: self.CSVdata = self.CSVdata[:-self.trim] #Python nested lists route; tolerates multiple data types else: #Declare required empty str arrays self.CSVdata = [0]*len(self.dataList) for rows in self.dataList: self.k = 0 self.rows = rows #Handle no width imput, flexible width if self.width is None: self.numrow = [0]*len(self.rows) else: self.numrow = [0]*self.width #Try to convert to float, fall back on string. for data in self.rows: try: self.numrow[self.k] = float(data) except ValueError: try: self.numrow[self.k] = data except IndexError: pass except IndexError: pass self.k+=1 self.CSVdata[self.j] = self.numrow self.j+=1 #append file to allData which contains all files self.allData[self.i] = self.CSVdata #trim CSV off filename and store in Dict for indexing of allData self.dataFiles[self.i] = self.dataFiles[self.i][:-4] self.Dict[self.dataFiles[self.i]] = self.i self.i+=1 def write(self, array, name, destination=None): '''Writes array in memory to file. EasyCSV.write(array, name, destination=None) array is a pointer to the array you want written to CSV name will be the name of said file destination is optional and will change the directory to the location specified. Leaving it at the default value None will overwrite any CSVs that may have been read in by the class earlier. ''' self.array = array self.name = name self.dest = destination #Optional change directory if self.dest is not None: os.chdir(self.dest) #Dict does not hold CSV, check to see if present and trim if not self.name[-4:] == '.CSV' or self.name[-4:] == '.csv': self.name = name + '.CSV' #Create files and write data, 'wb' binary req'd for Win compatibility with open(self.name,'wb') as self.newCSV: self.CSVwrite = csv.writer(self.newCSV,dialect='excel') for data in self.array: self.CSVwrite.writerow(data) os.chdir(self.loc) #Change back to original __init__.loc def lookup(self, key=None): '''Prints a preview of data to the console window with just a key input ''' self.key = key #Dict does not hold CSV, check to see if present and trim if self.key[-4:] == '.CSV' or self.key[-4:] == '.csv': self.key = key[:-4] #Print None case elif self.key is None: print self.allData[0] print self.allData[0] print '... ' * len(self.allData[0][-2]) print self.allData[0][-2] print self.allData[0] #Print everything else else: self.index = self.Dict[self.key] print self.allData[self.index][0] print self.allData[self.index][1] print '... ' * len(self.allData[self.index][-2]) print self.allData[self.index][-2] print self.allData[self.index][-1] def output(self, key=None): '''Returns the array for assignment to a var with just a key input ''' self.key = key #Dict does not hold CSV, check to see if present and trim if self.key is None: return self.allData[0] elif self.key[-4:] == '.CSV' or self.key[-4:] == '.csv': self.key = key[:-4] #Return file requested self.index = self.Dict[self.key] return self.allData[self.Dict[self.key]] ################################################ loc = 'C:\Users\Me\Desktop' CSV = EasyCSV(loc, np_array='false', width=None, skip_rows=0) CSV.read() target = 'somecsv' #with or without .csv/.CSV CSV.lookup(target) A = CSV.output(target) loc2 = 'C:\Users\Me\Desktop\New folder' for keys in CSV.Dict: print keys CSV.write(CSV.output(keys),keys,destination=loc2) </code></pre>
24836
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-07T20:15:44.593", "Id": "24836", "Score": "5", "Tags": [ "python", "parsing", "csv", "numpy", "portability" ], "Title": "Portable Python CSV class" }
{ "body": "<p><a href=\"https://codereview.stackexchange.com/a/24852/11728\">Janne's points</a> are good. In addition:</p>\n\n<ol>\n<li><p>When I try running this code, it fails:</p>\n\n<pre><code>&gt;&gt;&gt; e = EasyCSV('.')\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"cr24836.py\", line 37, in __init__\n for files in os.listdir(loc):\nNameError: global name 'loc' is not defined\n</code></pre>\n\n<p>I presume that <code>loc</code> is a typo for <code>self.loc</code>. This makes me suspicious. Have you actually used or tested this code?</p></li>\n<li><p>The <code>width</code> and <code>skip_rows</code> arguments to the constructor apply to <em>all</em> CSV files in the directory. But isn't it likely that different CSV files will have different widths and need different numbers of rows to be skipped?</p></li>\n<li><p>Your class requires NumPy to be installed (otherwise the line <code>import numpy as np</code> will fail). But since it has a mode of operation that doesn't require NumPy (return lists instead), it would be nice if it worked even if NumPy is not installed. Wait until you're just about to call <code>np.zeros</code> before importing NumPy.</p></li>\n<li><p><code>location</code> is supposed to be the name of a directory, so name it <code>directory</code>.</p></li>\n<li><p>You write <code>self.key[-4:] == '.CSV'</code> but why not use <code>.endswith</code> like you did earlier in the program? Or better still, since you are testing this twice, write a function:</p>\n\n<pre><code>def filename_is_csv(filename):\n \"\"\"Return True if filename has the .csv extension.\"\"\"\n _, ext = os.path.splitext(filename)\n return ext.lower() == '.csv'\n</code></pre>\n\n<p>But having said that, do you really want to insist that this can only read CSV files whose names end with <code>.csv</code>? What if someone has CSV stored in a file named <code>foo.data</code>? They'd never be able to read it with your class.</p></li>\n<li><p>There's nothing in the documentation for the class that explains that I am supposed to call the <code>read()</code> method. (If I don't, nothing happens.)</p></li>\n<li><p>There's nothing in the documentation for the class that explains how I am supposed to access the data that has been loaded into memory.</p></li>\n<li><p>If I want to access the data for a filename, I have look up the filename in the <code>Dict</code> attribute to get the index, and then I could look up the index in the <code>allData</code> attribute to get the data. Why this double lookup? Why not have a dictionary that maps filename to data instead of going via an index?</p></li>\n<li><p>There is no need to preallocate arrays in Python. Wait to create the array until you have some data to put in it, and then <code>append</code> each entry to it. Python is not Fortran!</p></li>\n<li><p>In your <code>read()</code> method, you read all the CSV files into memory. This seems wasteful. What if I had hundreds of files but only wanted to read one of them? Why not wait to read a file until the caller needs it?</p></li>\n<li><p>You convert numeric elements to floating-point numbers. This might not be what I want. For example, if I have a file containing:</p>\n\n<pre><code>Apollo,Launch\n7,19681011\n8,19681221\n9,19690303\n10,19690518\n11,19690716\n12,19691114\n13,19700411\n14,19710131\n15,19710726\n16,19720416\n17,19721207\n</code></pre>\n\n<p>and then I try to read it, all the data has been wrongly converted to floating-point:</p>\n\n<pre><code>&gt;&gt;&gt; e = EasyCSV('.')\n&gt;&gt;&gt; e.read()\napollo.csv\n&gt;&gt;&gt; from pprint import pprint\n&gt;&gt;&gt; pprint(e.allData[e.Dict['apollo']])\n[['Apollo', 'Launch'],\n [7.0, 19681011.0],\n [8.0, 19681221.0],\n [9.0, 19690303.0],\n [10.0, 19690518.0],\n [11.0, 19690716.0],\n [12.0, 19691114.0],\n [13.0, 19700411.0],\n [14.0, 19710131.0],\n [15.0, 19710726.0],\n [16.0, 19720416.0],\n [17.0, 19721207.0]]\n</code></pre>\n\n<p>This can go wrong in other ways. For example, suppose I have a CSV file like this:</p>\n\n<pre><code>product code,inventory\n1a0,81\n7b4,61\n9c2,32\n8d3,90\n1e9,95\n2f4,71\n</code></pre>\n\n<p>When I read it with your class, look at what happens to the sixth row:</p>\n\n<pre><code>&gt;&gt;&gt; e = EasyCSV('.')\n&gt;&gt;&gt; e.read()\ninventory.csv\n&gt;&gt;&gt; pprint(e.allData[e.Dict['inventory']])\n[['product code', 'inventory'],\n ['1a0', 81.0],\n ['7b4', 61.0],\n ['9c2', 32.0],\n ['8d3', 90.0],\n [1000000000.0, 95.0],\n ['2f4', 71.0]]\n</code></pre></li>\n<li><p>You suggest that \"other people can just copy and paste into their code\" but this is never a good idea. How would you distribute bug fixes and other improvements? If you plan for other people to use your code, you should aim to make a package that can be distributed through the <a href=\"https://pypi.python.org/pypi\" rel=\"nofollow noreferrer\">Python Package Index</a>.</p></li>\n</ol>\n\n<p>In summary, your class is misnamed: it does not seem to me as if it would be easy to use in practice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-08T15:56:02.063", "Id": "24860", "ParentId": "24836", "Score": "5" } }
<p>As a follow-up to my previous <a href="https://codereview.stackexchange.com/questions/26071/computation-of-prefix-free-codes-with-many-repeated-weight-values-in-reduced-spa">question</a> about prefix free code, I learned about the module unittest and wrote the following set of functions, to be used in order to semi-automatically check the optimality of the output of any new algorithm to compute prefix free code.</p> <p>The code works but I would like it to be as elegant (and compact) as possible in order to potentially include it in a research article, in a more formal and reproducible maneer than the traditional "algorithm". I am proud of how it looks, but I do expect you to still criticize it!!!</p> <pre><code>import unittest, doctest, math def codeIsPrefixFreeCodeMinimal(L,W): """Checks if the prefix free code described by an array $L$ of pairs $(codeLenght_i,nbWeights_i)$ is minimal for weights $W$, by 1) checking if the code respects Kraft's inequality and 2) comparing the lenght of a code encoded with $L$ with the entropy of $W$. """ assert respectsKraftInequality(L) return compressedTextLenght(L,W) &lt;= NTimesEntropy(W)+len(W) def respectsKraftInequality(L): """Checks if the given array $L$ of pairs $(codeLenght_i,nbWeights_i)$ corresponds to a prefix free code by checking Kraft's inequality, i.e. $\sum_i nbWeights_i 2^{-codelenght_i} \leq 1$. """ return KraftSum(L) &lt;= 1 ; def KraftSum(L): """Computes the Kraft sum of the prefix free code described by an array $L$ of pairs $(codeLenght_i,nbWeights_i)$ i.e. $\sum_i nbWeights_i 2^{-codelenght_i}$. """ if len(L)==0: return 0 terms = map( lambda x: x[1] * math.pow(2,-x[0]), L) return sum(terms) class TestKraftSum(unittest.TestCase): def test_empty(self): """Empty input.""" self.assertEqual(KraftSum([]),0) def test_singleton(self): """Singleton with one single symbol.""" self.assertEqual(KraftSum([(0,1)]),1) def test_simpleCode(self): """Simple Code with code lenghts [1,2,2].""" self.assertEqual(KraftSum([(1,1),(2,2)]),1) def test_fourEqual(self): """Four equal weights""" self.assertEqual(KraftSum([(2,4)]),1) def test_HuffmanExample(self): """Example from Huffman's article""" self.assertEqual(KraftSum([(5,6),(4,3),(3,3),(2,1)]),1) def test_MoffatTurpinExample(self): """Example from Moffat and Turpin's article""" self.assertEqual(KraftSum([(5,4),(4,4),(3,3),(2,1)]),1) def NTimesEntropy(W): """Returns N times the entropy, rounded to the next integer, as computed by $\lceil \sum_{i=1}^N W[i]/\sum(W) \log (sum(W) / W[i]) \rceil$. """ if len(W)==0: return 0 assert min(W)&gt;0 sumWeights = sum(W) terms = map( lambda x: x * math.log(x,2), W ) return math.ceil(sumWeights * math.log(sumWeights,2) - sum(terms)) class TestNTimesEntropy(unittest.TestCase): def test_empty(self): """Empty input""" self.assertEqual(NTimesEntropy([]),0) def test_singleton(self): """Singleton""" self.assertEqual(NTimesEntropy([1]),0) def test_pair(self): """Pair""" self.assertEqual(NTimesEntropy([1,1]),2) def test_fourEqual(self): """Four equal weights""" self.assertEqual(NTimesEntropy([1,1,1,1]),8) def test_HuffmanExample(self): """Example from Huffman's article""" self.assertEqual(NTimesEntropy([1,3,4,4,4,4,6,6,10,10,10,18,20]),336) def test_MoffatTurpinExample(self): """Example from Moffat and Turpin's article""" self.assertEqual(NTimesEntropy([1,1,1,1,1,2,2,2,2,3,3,6]),84) def compressedTextLength(L,W): """Computes the lengths of a text which frequencies are given by an array $W$, when it is compressed by a prefix free code described by an array $L$ of pairs $(codeLenght_i,nbWeights_i)$. """ compressedTextLength = 0 Ls = sorted(L, reverse=True) Ws = sorted(W) for (l,n) in Ls: compressedTextLength += l*sum(Ws[0:n]) Ws = Ws[n:] return compressedTextLength class TestcompressedTextLength(unittest.TestCase): def test_empty(self): """Empty input""" self.assertEqual(compressedTextLength([],[]),0) def test_pair(self): """Pair of symbols, arbitrary text""" self.assertEqual(compressedTextLength([(1,2)],[1,1]),2) def test_fourEqual(self): """Four equal weights""" self.assertEqual(compressedTextLength([(2,4)],[1,1,1,1]),8) def test_HuffmanExample(self): """Example from Huffman's article (compares with value compared by hand)""" self.assertEqual(compressedTextLength([(5,6),(4,3),(3,3),(2,1)],[1,3,4,4,4,4,6,6,10,10,10,18,20]),342) def test_MoffatTurpinExample(self): """Example from Moffat and Turpin's article (compares with entropy value)""" self.assertEqual(compressedTextLength([(5,4),(4,4),(3,3),(2,1)],[1,1,1,1,1,2,2,2,2,3,3,6]),84) def main(): unittest.main() if __name__ == '__main__': doctest.testmod() main() </code></pre>
27821
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-26T21:45:48.927", "Id": "27821", "Score": "1", "Tags": [ "python" ], "Title": "Code to check for the optimality of a minimal prefix free code" }
{ "body": "<p>Most Python I read these days prefers list comprehensions over <code>map</code> or <code>filter</code>. For example, I'd change</p>\n\n<pre><code>terms = map( lambda x: x[1] * math.pow(2,-x[0]), L)\nreturn sum(terms)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>return sum(x[1] * math.pow(2, -x[0]) for x in L)\n</code></pre>\n\n<hr>\n\n<p>You consistently misspell \"length\" as \"lenght\".</p>\n\n<hr>\n\n<p>Your formatting is odd. Sometimes you have 3 blank lines between functions, sometimes 0. Likewise, sometimes you write <code>foo &lt;= bar</code> and sometimes <code>foo=bar+baz</code>. Sometimes your functions begin with a lowercase letter (<code>compressedTextLength</code>, <code>respectsKraftInequality</code>) and sometimes with an uppercase (<code>KraftSum</code>). Look over <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> for formatting recommendations.</p>\n\n<hr>\n\n<p>In <code>compressedTextLength</code>, you can rewrite</p>\n\n<pre><code>for (l,n) in Ls:\n compressedTextLength += l*sum(Ws[0:n])\n Ws = Ws[n:]\n</code></pre>\n\n<p>as</p>\n\n<pre><code>for i, (l, n) in enumerate(Ls):\n compressedTextLength += l * sum(Ws[i:i+n])\n</code></pre>\n\n<hr>\n\n<p>You call <code>doctest.testmod()</code> but it doesn't look like you have any doctests.</p>\n\n<hr>\n\n<p>As a generalized note, I would find it difficult to learn anything about this algorithm from reading your code. I also have no idea how to use this module. I would add a docstring to the beginning of the module telling the reader about the functions they should care about, and in each function's docstring I would document what the arguments should be and what the return values are (arrays of ints? floating point numbers? etc).</p>\n\n<p>It looks like this may be a test harness for code that actually computes minimal prefix free codes. If that's a case, document it in the module's docstring.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T05:05:39.987", "Id": "27827", "ParentId": "27821", "Score": "1" } }
<p>I have a file with just 3500 lines like these:</p> <pre><code>filecontent= "13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234" </code></pre> <p>Then I want to grab every line from the <code>filecontent</code> that matches a certain string (with python 2.7):</p> <pre><code>this_item= "IBMlalala123" matchingitems = re.findall(".*?;.*?;.*?;.*?;.*?;.*?;.*?"+this_item,filecontent) </code></pre> <p>It needs 17 seconds for each <code>findall</code>. I need to search 4000 times in these 3500 lines. It takes forever. Any idea how to speed it up?</p>
32449
GOOD_ANSWER
{ "AcceptedAnswerId": "32450", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T07:47:42.643", "Id": "32449", "Score": "22", "Tags": [ "python", "performance", "regex", "csv", "python-2.x" ], "Title": "Regex to parse semicolon-delimited fields is too slow" }
{ "body": "<p><code>.*?;.*?</code> will cause <a href=\"http://www.regular-expressions.info/catastrophic.html\" rel=\"nofollow noreferrer\">catastrophic backtracking</a>.</p>\n<p>To resolve the performance issues, remove <code>.*?;</code> and replace it with <code>[^;]*;</code>, that should be much faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T08:35:18.953", "Id": "51840", "Score": "2", "body": "Thanks alot. I didn't got the fact at first, that I have to replace each old element with your new lement. Worked, when I did it like that :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:11:40.400", "Id": "51860", "Score": "7", "body": "Also, one other thing you should do here, is rather than repeating it, as `[^;]*;[^;]*;[^;]*;[^;]*;[^;]*;[^;]*;[^;]*`, you should shrink it down to something more concise, for instance `[^;]*(?:;[^;]*){6}`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T21:38:07.453", "Id": "530450", "Score": "0", "body": "Another option (a fairly big shift) would be to use a regex engine other than the standard library one, which doesn't backtrack." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-09T07:53:31.477", "Id": "32450", "ParentId": "32449", "Score": "35" } }
<p>I have a file with just 3500 lines like these:</p> <pre><code>filecontent= "13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234" </code></pre> <p>Then I want to grab every line from the <code>filecontent</code> that matches a certain string (with python 2.7):</p> <pre><code>this_item= "IBMlalala123" matchingitems = re.findall(".*?;.*?;.*?;.*?;.*?;.*?;.*?"+this_item,filecontent) </code></pre> <p>It needs 17 seconds for each <code>findall</code>. I need to search 4000 times in these 3500 lines. It takes forever. Any idea how to speed it up?</p>
32449
BAD_ANSWER
{ "AcceptedAnswerId": "32450", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T07:47:42.643", "Id": "32449", "Score": "22", "Tags": [ "python", "performance", "regex", "csv", "python-2.x" ], "Title": "Regex to parse semicolon-delimited fields is too slow" }
{ "body": "<blockquote>\n <p>Some people, when confronted with a problem, think \"I know, I'll use regular expressions.\" Now they have two problems. -- Jamie Zawinski</p>\n</blockquote>\n\n<p>A few things to be commented :</p>\n\n<ol>\n<li><p>Regular expressions might not be the right tool for this.</p></li>\n<li><p><code>.*?;.*?;.*?;.*?;.*?;.*?;.*?\"</code> is potentially very slow and might not do what you want it to do (it could match many more <code>;</code> than what you want). <code>[^;]*;</code> would most probably do what you want.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T08:14:44.210", "Id": "51838", "Score": "0", "body": "The actual expression would be:\n .*?;.*?;.*?;.*?;.*?;.*?;.*?IBMlalala123\n\n Mind being a bit more explicit? I tried some variations to replace my version with yours, but failed... (should return the whole line, [^;]*;IBMlalala123 just returns the id string)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T07:56:29.723", "Id": "32451", "ParentId": "32449", "Score": "17" } }
<p>I have a file with just 3500 lines like these:</p> <pre><code>filecontent= "13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234" </code></pre> <p>Then I want to grab every line from the <code>filecontent</code> that matches a certain string (with python 2.7):</p> <pre><code>this_item= "IBMlalala123" matchingitems = re.findall(".*?;.*?;.*?;.*?;.*?;.*?;.*?"+this_item,filecontent) </code></pre> <p>It needs 17 seconds for each <code>findall</code>. I need to search 4000 times in these 3500 lines. It takes forever. Any idea how to speed it up?</p>
32449
GOOD_ANSWER
{ "AcceptedAnswerId": "32450", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T07:47:42.643", "Id": "32449", "Score": "22", "Tags": [ "python", "performance", "regex", "csv", "python-2.x" ], "Title": "Regex to parse semicolon-delimited fields is too slow" }
{ "body": "<p>Some thoughts:</p>\n\n<p>Do you need a regex? You want a line that contains the string so why not use 'in'?</p>\n\n<p>If you are using the regex to validate the line format, you can do that after the less expensive 'in' finds a candidate line reducing the number of times the regex is used.</p>\n\n<p>If you do need a regex then what about replacing '.<em>?;' with '[^;]</em>;' ?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T13:43:20.077", "Id": "32472", "ParentId": "32449", "Score": "2" } }
<p>I have a file with just 3500 lines like these:</p> <pre><code>filecontent= "13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234" </code></pre> <p>Then I want to grab every line from the <code>filecontent</code> that matches a certain string (with python 2.7):</p> <pre><code>this_item= "IBMlalala123" matchingitems = re.findall(".*?;.*?;.*?;.*?;.*?;.*?;.*?"+this_item,filecontent) </code></pre> <p>It needs 17 seconds for each <code>findall</code>. I need to search 4000 times in these 3500 lines. It takes forever. Any idea how to speed it up?</p>
32449
GOOD_ANSWER
{ "AcceptedAnswerId": "32450", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T07:47:42.643", "Id": "32449", "Score": "22", "Tags": [ "python", "performance", "regex", "csv", "python-2.x" ], "Title": "Regex to parse semicolon-delimited fields is too slow" }
{ "body": "<p>Use split, like so:</p>\n\n<pre><code>&gt;&gt;&gt; filecontent = \"13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234\";\n&gt;&gt;&gt; items = filecontent.split(\";\");\n&gt;&gt;&gt; items;\n['13P397', 'Fotostuff', 't', 'IBM', 'IBM lalala 123|IBM lalala 1234', '28.000 things', '', 'IBMlalala123|IBMlalala1234']\n&gt;&gt;&gt; \n</code></pre>\n\n<p>I'm a bit unsure as what you wanted to do in the last step, but perhaps something like this?</p>\n\n<pre><code>&gt;&gt;&gt; [(i, e) for i,e in enumerate(items) if 'IBMlalala123' in e]\n[(7, 'IBMlalala123|IBMlalala1234')]\n&gt;&gt;&gt; \n</code></pre>\n\n<p>UPDATE: \nIf I get your requirements right on the second attempt: To find all lines in file having 'IBMlalala123' as any one of the semicolon-separated fields, do the following:</p>\n\n<pre><code>&gt;&gt;&gt; with open('big.file', 'r') as f:\n&gt;&gt;&gt; matching_lines = [line for line in f.readlines() if 'IBMlalala123' in line.split(\";\")]\n&gt;&gt;&gt; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T16:17:42.527", "Id": "51880", "Score": "1", "body": "+1: split is usually much faster than regex for these kind of cases. Especially if you need to use the captured field values aftwerward." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T18:36:54.137", "Id": "51889", "Score": "0", "body": "Yup, +1 for split. Regex doesn't appear to be the best tool for this job." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T13:44:37.137", "Id": "57136", "Score": "0", "body": "In my case it was about getting every full line (from some thousand lines) that has a certain string in it. Your solution gives back a part of the line, and would need some enhancements to work with some thousand files. I imagine you would suggest splitting by '\\n' and then checking each line with 'if string in line' and putting that into a list then? Don't know if this would be faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T14:46:42.827", "Id": "57145", "Score": "0", "body": "@Mike: Ok, but in your example I don't see any reference to newlines, did you mean that semicolon should signify newlines? Anyway, there is no \"fast\" way of splitting lines. The OS does not keep track of where newlines are stored, so scanning for newline chars is the way any row-reading lib works AFAIK. But you can of course save a lot of mem by reading line by line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T15:17:33.993", "Id": "57288", "Score": "0", "body": "It wasn't in the example, but in the text before and after it ;) ...file with just 3500 lines... ...want to grab every line from the filecontent that matches a certain string..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T15:30:47.630", "Id": "57293", "Score": "0", "body": "@Mike: So \"filecontent\" actually signifies the content of one line in the file?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T15:54:58.790", "Id": "57301", "Score": "0", "body": "Hallo Alexander, \n...file with just 3500 lines... ...want to grab every line from the filecontent that matches a certain string...\nThis means: the file has 3500 lines in it. I refer to these 3500 lines as filecontent, as it is the content of the file...\nThe phrase 'every line' wouldn't make sense, if we were talking about one-line files." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T16:02:03.143", "Id": "57303", "Score": "0", "body": "Your solution is close, but if you look closer at my first attempt (that awful slow one), you will see, I tried to match the entry in the last field. Your last solution would have to look only for the last filed, e.g. line.split(\";\")[5] (if I counted right). It's a nice solution, thanks!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:56:41.627", "Id": "32477", "ParentId": "32449", "Score": "16" } }
<p>This is a similar question to <a href="https://stackoverflow.com/questions/492716/reversing-a-regular-expression-in-python">this</a>, but I am looking for the set of <strong>all possible values</strong> that will match a regular expression pattern.</p> <p>To avoid an infinite set of possible values, I am willing to restrict the regular expression pattern to a subset of the regular expression language.</p> <p>Here's the approach I took (Python code):</p> <pre><code>def generate_possible_strings(pattern): ''' input: 'K0[2468]' output: ['K02', 'K04', 'K06', 'K08'] generates a list of possible strings that would match pattern ie, any value X such that re.search(pattern, X) is a match ''' query = re.compile(pattern, re.IGNORECASE) fill_in = string.uppercase + string.digits + '_' # Build a re for a language subset that is supported by reverse_search bracket = r'\[[^\]]*\]' #finds [A-Z], [0-5], [02468] symbol = r'\\.' #finds \w, \d expression = '|'.join((bracket,symbol)) #search query tokens = re.split(expression, pattern) for c in product(fill_in, repeat=len(tokens)-1): candidate = ''.join(roundrobin(tokens, c)) #roundrobin recipe from itertools documentation if query.match(candidate): yield candidate </code></pre> <p>Supported subset of regular expressions language</p> <ul> <li>Supports <code>[]</code> set of characters (<code>[A-Z]</code>, <code>[0-5]</code>, etc)</li> <li>Supports escaped special characters (<code>\w</code>, <code>\d</code>, <code>\D</code>, etc)</li> </ul> <p>Basically what this does is locate all parts of a regular expression that could match a single character (<code>[A-Z]</code> or <code>[0-5]</code> or <code>[02468]</code> or <code>\w</code> or <code>\d</code>), then for all of the valid replacement characters <code>A-Z0-9_</code> test to see if the replacement matches the regular expression.</p> <p>This algorithm is slow for regular expressions with many fields or if <code>fill_in</code> is not restricted to just <code>A-Z0-9_</code>, but at least it guarantees finding every possible string that will match a regular expression in finite time (if the solution set is finite).</p> <p>Is there a faster approach to solving this problem, or an approach that supports a larger percentage of the standard regular expression language?</p>
43981
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T17:32:16.360", "Id": "43981", "Score": "3", "Tags": [ "python", "performance", "regex" ], "Title": "All possible values that will match a regular expression" }
{ "body": "<p>A major inefficiency in your solution is that you try every <code>fill_in</code> character as a replacement for any character class in the pattern. Instead, you could use the character class to select matching characters from <code>fill_in</code> and only loop over those. </p>\n\n<pre><code>&gt;&gt;&gt; pattern = 'K0[2468]'\n&gt;&gt;&gt; re.findall(expression, pattern)\n['[2468]']\n&gt;&gt;&gt; re.findall('[2468]', fill_in)\n['2', '4', '6', '8']\n</code></pre>\n\n<p>For a more complete existing solution, you may want to look into these:</p>\n\n<ul>\n<li><a href=\"http://qntm.org/lego\" rel=\"nofollow\">Regular expression parsing in Python</a></li>\n<li>invRegex.py in <a href=\"http://pyparsing.wikispaces.com/Examples\" rel=\"nofollow\">Pyparsing examples</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T16:05:50.130", "Id": "76503", "Score": "0", "body": "Thank you! This helps a lot, particularly for cases like '\\d\\d\\d', where only 1000 of 50653 candidates are matches (given fill_in is [A-Z0-9_])" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T07:33:20.617", "Id": "44129", "ParentId": "43981", "Score": "4" } }
<p>I am trying create an algorithm for finding the zero crossing (check that the signs of all the entries around the entry of interest are not the same) in a two dimensional matrix, as part of implementing the Laplacian of Gaussian edge detection filter for a class, but I feel like I'm fighting against Numpy instead of working with it.</p> <pre><code>import numpy as np range_inc = lambda start, end: range(start, end+1) # Find the zero crossing in the l_o_g image # Done in the most naive way possible def z_c_test(l_o_g_image): print(l_o_g_image) z_c_image = np.zeros(l_o_g_image.shape) for i in range(1, l_o_g_image.shape[0] - 1): for j in range(1, l_o_g_image.shape[1] - 1): neg_count = 0 pos_count = 0 for a in range_inc(-1, 1): for b in range_inc(-1, 1): if a != 0 and b != 0: print("a ", a, " b ", b) if l_o_g_image[i + a, j + b] &lt; 0: neg_count += 1 print("neg") elif l_o_g_image[i + a, j + b] &gt; 0: pos_count += 1 print("pos") else: print("zero") # If all the signs around the pixel are the same # and they're not all zero # then it's not a zero crossing and an edge. # Otherwise, copy it to the edge map. z_c = ((neg_count &gt; 0) and (pos_count &gt; 0)) if z_c: print("True for", i, ",", j) print("pos ", pos_count, " neg ", neg_count) z_c_image[i, j] = 1 return z_c_image </code></pre> <p>Here is the test cases it should pass:</p> <pre><code>test1 = np.array([[0,0,1], [0,0,0], [0,0,0]]) test2 = np.array([[0,0,1], [0,0,0], [0,0,-1]]) test3 = np.array([[0,0,0], [0,0,-1], [0,0,0]]) test4 = np.array([[0,0,0], [0,0,0], [0,0,0]]) true_result = np.array([[0,0,0], [0,1,0], [0,0,0]]) false_result = np.array([[0,0,0], [0,0,0], [0,0,0]]) real_result1 = z_c_test(test1) real_result2 = z_c_test(test2) real_result3 = z_c_test(test3) real_result4 = z_c_test(test4) assert(np.array_equal(real_result1, false_result)) assert(np.array_equal(real_result2, true_result)) assert(np.array_equal(real_result3, false_result)) assert(np.array_equal(real_result4, false_result)) </code></pre> <p>How do I vectorize checking a property in a matrix range? Is there a quick way of accessing all of the entries adjacent to an entry in a matrix?</p>
45458
GOOD_ANSWER
{ "AcceptedAnswerId": "67662", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-27T02:00:06.057", "Id": "45458", "Score": "19", "Tags": [ "python", "matrix", "numpy" ], "Title": "Finding a zero crossing in a matrix" }
{ "body": "<p>One way to get the neighbor coordinates without checking for (a != 0) or (b != 0) on every iteration would be to use a generator. Something like this:</p>\n\n<pre><code>def nborz():\n l = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1),(1,0),(1,1)]\n try:\n while True:\n yield l.pop(0)\n except StopIteration:\n return None\n....\n\nfor i in range(1,l_o_g_image.shape[0]-1):\n for j in range(1,l_o_g_image.shape[1]-1):\n neg_count = 0\n pos_count = 0\n nbrgen = nborz()\n for (a,b) in nbrgen:\n print \"a \" + str(a) + \" b \" + str(b)\n if(l_o_g_image[i+a,j+b] &lt; 0):\n neg_count += 1\n print \"neg\"\n elif(l_o_g_image[i+a,j+b] &gt; 0):\n pos_count += 1\n print \"pos\"\n else:\n print \"zero\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T06:02:03.390", "Id": "83594", "Score": "0", "body": "Would that actually be faster?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T10:43:59.747", "Id": "83616", "Score": "0", "body": "I would think it might, 1) because it avoids a comparison on every iteration of the inner loops, and 2) because it avoids computation of the index values for the inner loops (counting -1, 0, 1 twice in a nested fashion). However, I have not actually tried it so I don't know for sure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-20T03:39:41.580", "Id": "47693", "ParentId": "45458", "Score": "1" } }
<p>I am trying create an algorithm for finding the zero crossing (check that the signs of all the entries around the entry of interest are not the same) in a two dimensional matrix, as part of implementing the Laplacian of Gaussian edge detection filter for a class, but I feel like I'm fighting against Numpy instead of working with it.</p> <pre><code>import numpy as np range_inc = lambda start, end: range(start, end+1) # Find the zero crossing in the l_o_g image # Done in the most naive way possible def z_c_test(l_o_g_image): print(l_o_g_image) z_c_image = np.zeros(l_o_g_image.shape) for i in range(1, l_o_g_image.shape[0] - 1): for j in range(1, l_o_g_image.shape[1] - 1): neg_count = 0 pos_count = 0 for a in range_inc(-1, 1): for b in range_inc(-1, 1): if a != 0 and b != 0: print("a ", a, " b ", b) if l_o_g_image[i + a, j + b] &lt; 0: neg_count += 1 print("neg") elif l_o_g_image[i + a, j + b] &gt; 0: pos_count += 1 print("pos") else: print("zero") # If all the signs around the pixel are the same # and they're not all zero # then it's not a zero crossing and an edge. # Otherwise, copy it to the edge map. z_c = ((neg_count &gt; 0) and (pos_count &gt; 0)) if z_c: print("True for", i, ",", j) print("pos ", pos_count, " neg ", neg_count) z_c_image[i, j] = 1 return z_c_image </code></pre> <p>Here is the test cases it should pass:</p> <pre><code>test1 = np.array([[0,0,1], [0,0,0], [0,0,0]]) test2 = np.array([[0,0,1], [0,0,0], [0,0,-1]]) test3 = np.array([[0,0,0], [0,0,-1], [0,0,0]]) test4 = np.array([[0,0,0], [0,0,0], [0,0,0]]) true_result = np.array([[0,0,0], [0,1,0], [0,0,0]]) false_result = np.array([[0,0,0], [0,0,0], [0,0,0]]) real_result1 = z_c_test(test1) real_result2 = z_c_test(test2) real_result3 = z_c_test(test3) real_result4 = z_c_test(test4) assert(np.array_equal(real_result1, false_result)) assert(np.array_equal(real_result2, true_result)) assert(np.array_equal(real_result3, false_result)) assert(np.array_equal(real_result4, false_result)) </code></pre> <p>How do I vectorize checking a property in a matrix range? Is there a quick way of accessing all of the entries adjacent to an entry in a matrix?</p>
45458
GOOD_ANSWER
{ "AcceptedAnswerId": "67662", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-27T02:00:06.057", "Id": "45458", "Score": "19", "Tags": [ "python", "matrix", "numpy" ], "Title": "Finding a zero crossing in a matrix" }
{ "body": "<p>Here's concise method to get the coordinates of the zero-crossings that seems to work according to my tests :</p>\n\n<pre><code>def zcr(x, y):\n return x[numpy.diff(numpy.sign(y)) != 0]\n</code></pre>\n\n<p>Some simple test case :</p>\n\n<pre><code>&gt;&gt;&gt; zcr(numpy.array([0, 1, 2, 3, 4, 5, 6, 7]), [1, 2, 3, -1, -2, 3, 4, -4])\narray([2, 4, 6])\n</code></pre>\n\n<p>This is 2d only, but I believe it is easy to adapt to more dimensions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-23T08:35:01.540", "Id": "67662", "ParentId": "45458", "Score": "7" } }
<p>I wrote a program that reads a pcap file and parses the HTTP traffic in the pcap to generate a dictionary that contains HTTP headers for each request and response in this pcap.</p> <p>My code does the following:</p> <ol> <li>Uses tcpflow to reassemble the tcp segments</li> <li>Read the files generated by tcpflow and check if it related to HTTP</li> <li>If the file contains HTTP traffic, my code will read the file and generate a corresponding dictionary that contains the HTTP header fields.</li> </ol> <p>I test my code with multiple test cases, but honestly I don't have a good experience in Python, so could anyone check it for me please?</p> <pre><code>import os from os import listdir from os.path import isfile, join from StringIO import StringIO import mimetools def getFields(headers): fields={} i=1 for header in headers: if len(header)==0: continue # if this line is complement for the previous line if header.find(" ")==0 or header.find("\t")==0: continue if len(header.split(":"))&gt;=2: key = header.split(":")[0].strip() # if the key has multiple values such as cookie if fields.has_key(key): fields[key]=fields[key]+" "+header[header.find(":")+1:].strip() else: fields[key]=header[header.find(":")+1:].strip() while headers[i].find(" ")==0 or headers[i].find("\t")==0 : fields[key]=fields[key]+" "+headers[i].strip() i=i+1 # end of the while loop # end of the else else: # else for [if len(header.split(":"))&gt;=2: ] print "ERROR: RFC VIOLATION" # end of the for loop return fields def main(): # you have to write it in the terminal "cd /home/user/Desktop/empty-dir" os.system("tcpflow -r /home/user/Desktop/12.pcap -v") for f in listdir("/home/user/Desktop/empty-dir"): if f.find("80")==19 or f.find("80")==41: with open("/home/user/Desktop/empty-dir"+f) as fh: fields={} content=fh.read() #to test you could replace it with content="any custom http header" if content.find("\r\n\r\n")==-1: print "ERROR: RFC VIOLATION" return headerSection=content.split("\r\n\r\n")[0] headerLines=headerSection.split("\r\n") firstLine=headerLines[0] firstLineFields=firstLine.split(" ") if len(headerLines)&gt;1: fields=getFields(headerLines[1:]) if len(firstLineFields)&gt;=3: if firstLine.find("HTTP")==0: fields["Version"]=firstLineFields[0] fields["Status-code"]=firstLineFields[1] fields["Status-desc"]=" ".join(firstLineFields[2:]) else: fields["Method"]=firstLineFields[0] fields["URL"]=firstLineFields[1] fields["Version"]=firstLineFields[2] else: print "ERROR: RFC VIOLATION" continue print fields print "__________________" return 0 if __name__ == '__main__': main() </code></pre>
57715
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T18:26:02.543", "Id": "57715", "Score": "10", "Tags": [ "python", "http" ], "Title": "Parse HTTP header using Python and tcpflow" }
{ "body": "<p>New Lines and indentations help the interpreter know where the code terminates and blocks end, you have to be super careful with them </p>\n\n<p>Like in your if condition, you can't have a newline in between the conditions.</p>\n\n<pre><code>if header.find(\" \")==0 or \n header.find(\"\\t\")==0:\n continue\n</code></pre>\n\n<p>This code will error out because you can't have a new line in your condition statement.</p>\n\n<p>Python is New Line Terminated. It should read like this</p>\n\n<pre><code>if header.find(\" \")==0 or header.find(\"\\t\")==0\n continue\n</code></pre>\n\n<p>Same with this piece of code</p>\n\n<pre><code>while headers[i].find(\" \")==0 or \n headers[i].find(\"\\t\")==0 :\n fields[key]=fields[key]+\" \"+headers[i].strip()\n i=i+1\n</code></pre>\n\n<p>It should read:</p>\n\n<pre><code>while headers[i].find(\" \")==0 or headers[i].find(\"\\t\")==0 :\n fields[key]=fields[key]+\" \"+headers[i].strip()\n i=i+1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T19:12:24.773", "Id": "103315", "Score": "0", "body": "when I wrote my code in gedit the indentation was correct,but when I copy/past the code here the indentation is changed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T19:14:13.387", "Id": "103316", "Score": "0", "body": "@RaghdaHraiz Edit your question code, but I think you still had issues with Scope of variables" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T19:15:38.797", "Id": "103317", "Score": "0", "body": "regarding the while statement, it should be inside the loop and in the else statement.\n\nthe else which print the error message is related to this if statement \nif len(header.split(\":\"))>=2: @Malachi" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T19:30:40.147", "Id": "103321", "Score": "1", "body": "I edited the code indentation and added comments ..could you check it now @Malachi" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T19:34:47.800", "Id": "103325", "Score": "0", "body": "I saw, and I have changed my review to reflect your edit, thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T19:36:59.400", "Id": "103326", "Score": "1", "body": "@RaghdaHraiz: Please be aware that code edits based on answers are normally disallowed, but this is a somewhat different case. If someone mentions *other* changes that you weren't aware of, then the original code must stay intact." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T18:55:35.333", "Id": "57719", "ParentId": "57715", "Score": "5" } }
<p>I wrote a program that reads a pcap file and parses the HTTP traffic in the pcap to generate a dictionary that contains HTTP headers for each request and response in this pcap.</p> <p>My code does the following:</p> <ol> <li>Uses tcpflow to reassemble the tcp segments</li> <li>Read the files generated by tcpflow and check if it related to HTTP</li> <li>If the file contains HTTP traffic, my code will read the file and generate a corresponding dictionary that contains the HTTP header fields.</li> </ol> <p>I test my code with multiple test cases, but honestly I don't have a good experience in Python, so could anyone check it for me please?</p> <pre><code>import os from os import listdir from os.path import isfile, join from StringIO import StringIO import mimetools def getFields(headers): fields={} i=1 for header in headers: if len(header)==0: continue # if this line is complement for the previous line if header.find(" ")==0 or header.find("\t")==0: continue if len(header.split(":"))&gt;=2: key = header.split(":")[0].strip() # if the key has multiple values such as cookie if fields.has_key(key): fields[key]=fields[key]+" "+header[header.find(":")+1:].strip() else: fields[key]=header[header.find(":")+1:].strip() while headers[i].find(" ")==0 or headers[i].find("\t")==0 : fields[key]=fields[key]+" "+headers[i].strip() i=i+1 # end of the while loop # end of the else else: # else for [if len(header.split(":"))&gt;=2: ] print "ERROR: RFC VIOLATION" # end of the for loop return fields def main(): # you have to write it in the terminal "cd /home/user/Desktop/empty-dir" os.system("tcpflow -r /home/user/Desktop/12.pcap -v") for f in listdir("/home/user/Desktop/empty-dir"): if f.find("80")==19 or f.find("80")==41: with open("/home/user/Desktop/empty-dir"+f) as fh: fields={} content=fh.read() #to test you could replace it with content="any custom http header" if content.find("\r\n\r\n")==-1: print "ERROR: RFC VIOLATION" return headerSection=content.split("\r\n\r\n")[0] headerLines=headerSection.split("\r\n") firstLine=headerLines[0] firstLineFields=firstLine.split(" ") if len(headerLines)&gt;1: fields=getFields(headerLines[1:]) if len(firstLineFields)&gt;=3: if firstLine.find("HTTP")==0: fields["Version"]=firstLineFields[0] fields["Status-code"]=firstLineFields[1] fields["Status-desc"]=" ".join(firstLineFields[2:]) else: fields["Method"]=firstLineFields[0] fields["URL"]=firstLineFields[1] fields["Version"]=firstLineFields[2] else: print "ERROR: RFC VIOLATION" continue print fields print "__________________" return 0 if __name__ == '__main__': main() </code></pre>
57715
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T18:26:02.543", "Id": "57715", "Score": "10", "Tags": [ "python", "http" ], "Title": "Parse HTTP header using Python and tcpflow" }
{ "body": "<p>A few brief comments:</p>\n\n<ul>\n<li>Use four spaces for each indentation level</li>\n<li>Use a space around each operator (<code>==</code>, <code>&gt;=</code>, ...)</li>\n<li>Use the <code>in</code> operator instead of the <code>has_key</code> method</li>\n<li>Use <code>subprocess.Popen</code> instead of <code>os.system</code></li>\n<li>Use <code>x.startswith(y)</code> (returns a boolean directly) instead of <code>x.find(y) == 0</code></li>\n</ul>\n\n<p>A few longer comments:</p>\n\n<ul>\n<li>I'm not sure what is the logic regarding filenames that you need to implement, but I recommend to have a look at the <code>fnmatch</code> module.</li>\n<li>For the parsing of the HTTP fields, you might want to use a regular expression.</li>\n<li>Also, a comment to make clear when a request or a response is being parsed would make the code more readable.</li>\n<li>Rename the <code>i</code> variable to make clear what is being used for (is <code>headers[i]</code> supposed to be the same as <code>header</code>?).</li>\n<li>Do not reinvent the wheel unless you need to. Check if there's an HTTP parsing library around already.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-23T09:22:25.267", "Id": "103431", "Score": "0", "body": "why the in operator is better than has_key and subprocess.Popen is better than os.system @jcollado" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-23T10:38:44.627", "Id": "103440", "Score": "0", "body": "According to the documentation [has_key](https://docs.python.org/2/library/stdtypes.html#dict.has_key) has been deprecated (`in` is more generic and can be used with user defined classes that implement the `__contains__` method) and [os.system](https://docs.python.org/2/library/os.html#os.system) is not as powerful as `subprocess.Popen`. There's a section about how to use `subprocess.Popen` instead of `os.system` [here](https://docs.python.org/2/library/subprocess.html#replacing-os-system)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T22:39:01.000", "Id": "57736", "ParentId": "57715", "Score": "3" } }
<p>The profile tells me it took ~15s to run, but without telling me more.</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Tue Aug 19 20:55:38 2014 Profile.prof 3 function calls in 15.623 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 15.623 15.623 15.623 15.623 {singleLoan.genLoan} 1 0.000 0.000 15.623 15.623 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} </code></pre> </blockquote> <pre class="lang-python prettyprint-override"><code>import numpy as np cimport numpy as np from libc.stdlib cimport malloc, free from libc.stdlib cimport rand, srand, RAND_MAX import cython cimport cython import StringIO cdef extern from "math.h": int floor(double x) double pow(double x, double y) double exp(double x) cdef double[:] zeros = np.zeros(360) cdef double[:] stepCoupons = np.array([2.0,60,3.0,12.0,4.0,12.0,5.0]) cdef double[:,:] zeros2 = np.empty(shape=(999,2)) paraC2P = StringIO.StringIO('''1 10 0 0 (Intercept) 0 -4.981792 1 10 0 0 lv 50 0.55139 1 10 0 0 lv 51 0.53667 1 10 0 0 lv 52 0.52194 1 10 0 0 lv 53 0.50722 1 10 0 0 lv 54 0.49249 1 10 0 0 lv 55 0.47776 1 10 0 0 lv 56 0.46301 1 10 0 0 lv 57 0.44825 1 10 0 0 lv 58 0.43347 1 10 0 0 lv 59 0.41867 1 10 0 0 lv 60 0.40384 1 10 0 0 lv 61 0.38897 1 10 0 0 lv 62 0.37405 1 10 0 0 lv 63 0.35908 1 10 0 0 lv 64 0.34406 1 10 0 0 lv 65 0.32897 1 10 0 0 lv 66 0.31381 1 10 0 0 lv 67 0.29856 1 10 0 0 lv 68 0.28322 1 10 0 0 lv 69 0.26778 1 10 0 0 lv 70 0.25224 1 10 0 0 lv 71 0.23657 1 10 0 0 lv 72 0.22078 1 10 0 0 lv 73 0.20486 1 10 0 0 lv 74 0.18879 1 10 0 0 lv 75 0.17258 1 10 0 0 lv 76 0.1562 1 10 0 0 lv 77 0.13966 1 10 0 0 lv 78 0.12294 1 10 0 0 lv 79 0.10604 1 10 0 0 lv 80 0.08896 1 10 0 0 lv 81 0.07167 1 10 0 0 lv 82 0.05419 1 10 0 0 lv 83 0.0365 1 10 0 0 lv 84 0.0186 1 10 0 0 lv 85 0.00048 1 10 0 0 lv 86 -0.01785 1 10 0 0 lv 87 -0.03641 1 10 0 0 lv 88 -0.0552 1 10 0 0 lv 89 -0.07422 1 10 0 0 lv 90 -0.09347 1 10 0 0 lv 91 -0.11295 1 10 0 0 lv 92 -0.13267 1 10 0 0 lv 93 -0.15263 1 10 0 0 lv 94 -0.17282 1 10 0 0 lv 95 -0.19325 1 10 0 0 lv 96 -0.21392 1 10 0 0 lv 97 -0.23482 1 10 0 0 lv 98 -0.25596 1 10 0 0 lv 99 -0.27734 1 10 0 0 lv 100 -0.29895 1 10 0 0 lv 101 -0.32078 1 10 0 0 lv 102 -0.34285 1 10 0 0 lv 103 -0.36513 1 10 0 0 lv 104 -0.38764 1 10 0 0 lv 105 -0.41037 1 10 0 0 lv 106 -0.43331 1 10 0 0 lv 107 -0.45646 1 10 0 0 lv 108 -0.47982 1 10 0 0 lv 109 -0.50338 1 10 0 0 lv 110 -0.52713 1 10 0 0 lv 111 -0.55107 1 10 0 0 lv 112 -0.5752 1 10 0 0 lv 113 -0.59952 1 10 0 0 lv 114 -0.624 1 10 0 0 lv 115 -0.64866 1 10 0 0 lv 116 -0.67348 1 10 0 0 lv 117 -0.69846 1 10 0 0 lv 118 -0.72359 1 10 0 0 lv 119 -0.74887 1 10 0 0 lv 120 -0.77429 1 10 0 0 lv 121 -0.79985 1 10 0 0 lv 122 -0.82554 1 10 0 0 lv 123 -0.85135 1 10 0 0 lv 124 -0.87728 1 10 0 0 lv 125 -0.90332 1 10 0 0 lv 126 -0.92947 1 10 0 0 lv 127 -0.95572 1 10 0 0 lv 128 -0.98206 1 10 0 0 lv 129 -1.0085 1 10 0 0 lv 130 -1.03502 1 10 0 0 lv 131 -1.06162 1 10 0 0 lv 132 -1.0883 1 10 0 0 lv 133 -1.11504 1 10 0 0 lv 134 -1.14185 1 10 0 0 lv 135 -1.16872 1 10 0 0 lv 136 -1.19565 1 10 0 0 lv 137 -1.22263 1 10 0 0 lv 138 -1.24965 1 10 0 0 lv 139 -1.27672 1 10 0 0 lv 140 -1.30382 1 10 0 0 lv 141 -1.33097 1 10 0 0 lv 142 -1.35814 1 10 0 0 lv 143 -1.38534 1 10 0 0 lv 144 -1.41257 1 10 0 0 lv 145 -1.43982 1 10 0 0 lv 146 -1.46709 1 10 0 0 lv 147 -1.49437 1 10 0 0 lv 148 -1.52167 1 10 0 0 lv 149 -1.54898 1 10 0 0 lv 150 -1.57629 1 10 0 0 dollarSaving -50 -1.10708 1 10 0 0 dollarSaving -48 -1.08948 1 10 0 0 dollarSaving -46 -1.07188 1 10 0 0 dollarSaving -44 -1.05429 1 10 0 0 dollarSaving -42 -1.03669 1 10 0 0 dollarSaving -40 -1.0191 1 10 0 0 dollarSaving -38 -1.0015 1 10 0 0 dollarSaving -36 -0.98391 1 10 0 0 dollarSaving -34 -0.96632 1 10 0 0 dollarSaving -32 -0.94873 1 10 0 0 dollarSaving -30 -0.93115 1 10 0 0 dollarSaving -28 -0.91357 1 10 0 0 dollarSaving -26 -0.896 1 10 0 0 dollarSaving -24 -0.87843 1 10 0 0 dollarSaving -22 -0.86087 1 10 0 0 dollarSaving -20 -0.84331 1 10 0 0 dollarSaving -18 -0.82577 1 10 0 0 dollarSaving -16 -0.80823 1 10 0 0 dollarSaving -14 -0.79071 1 10 0 0 dollarSaving -12 -0.7732 1 10 0 0 dollarSaving -10 -0.7557 1 10 0 0 dollarSaving -8 -0.73821 1 10 0 0 dollarSaving -6 -0.72074 1 10 0 0 dollarSaving -4 -0.70329 1 10 0 0 dollarSaving -2 -0.68586 1 10 0 0 dollarSaving 0 -0.66844 1 10 0 0 dollarSaving 2 -0.65105 1 10 0 0 dollarSaving 4 -0.63368 1 10 0 0 dollarSaving 6 -0.61634 1 10 0 0 dollarSaving 8 -0.59901 1 10 0 0 dollarSaving 10 -0.58172 1 10 0 0 dollarSaving 12 -0.56446 1 10 0 0 dollarSaving 14 -0.54722 1 10 0 0 dollarSaving 16 -0.53002 1 10 0 0 dollarSaving 18 -0.51285 1 10 0 0 dollarSaving 20 -0.49572 1 10 0 0 dollarSaving 22 -0.47862 1 10 0 0 dollarSaving 24 -0.46157 1 10 0 0 dollarSaving 26 -0.44455 1 10 0 0 dollarSaving 28 -0.42757 1 10 0 0 dollarSaving 30 -0.41064 1 10 0 0 dollarSaving 32 -0.39376 1 10 0 0 dollarSaving 34 -0.37692 1 10 0 0 dollarSaving 36 -0.36014 1 10 0 0 dollarSaving 38 -0.3434 1 10 0 0 dollarSaving 40 -0.32672 1 10 0 0 dollarSaving 42 -0.31009 1 10 0 0 dollarSaving 44 -0.29352 1 10 0 0 dollarSaving 46 -0.27701 1 10 0 0 dollarSaving 48 -0.26056 1 10 0 0 dollarSaving 50 -0.24417 1 10 0 0 dollarSaving 52 -0.22785 1 10 0 0 dollarSaving 54 -0.21159 1 10 0 0 dollarSaving 56 -0.1954 1 10 0 0 dollarSaving 58 -0.17928 1 10 0 0 dollarSaving 60 -0.16323 1 10 0 0 dollarSaving 62 -0.14725 1 10 0 0 dollarSaving 64 -0.13135 1 10 0 0 dollarSaving 66 -0.11553 1 10 0 0 dollarSaving 68 -0.09978 1 10 0 0 dollarSaving 70 -0.08411 1 10 0 0 dollarSaving 72 -0.06853 1 10 0 0 dollarSaving 74 -0.05303 1 10 0 0 dollarSaving 76 -0.03761 1 10 0 0 dollarSaving 78 -0.02229 1 10 0 0 dollarSaving 80 -0.00704 1 10 0 0 dollarSaving 82 0.00811 1 10 0 0 dollarSaving 84 0.02317 1 10 0 0 dollarSaving 86 0.03813 1 10 0 0 dollarSaving 88 0.05301 1 10 0 0 dollarSaving 90 0.06778 1 10 0 0 dollarSaving 92 0.08246 1 10 0 0 dollarSaving 94 0.09704 1 10 0 0 dollarSaving 96 0.11152 1 10 0 0 dollarSaving 98 0.1259 1 10 0 0 dollarSaving 100 0.14018 1 10 0 0 dollarSaving 102 0.15435 1 10 0 0 dollarSaving 104 0.16841 1 10 0 0 dollarSaving 106 0.18237 1 10 0 0 dollarSaving 108 0.19623 1 10 0 0 dollarSaving 110 0.20997 1 10 0 0 dollarSaving 112 0.2236 1 10 0 0 dollarSaving 114 0.23712 1 10 0 0 dollarSaving 116 0.25053 1 10 0 0 dollarSaving 118 0.26383 1 10 0 0 dollarSaving 120 0.27701 1 10 0 0 dollarSaving 122 0.29007 1 10 0 0 dollarSaving 124 0.30302 1 10 0 0 dollarSaving 126 0.31585 1 10 0 0 dollarSaving 128 0.32857 1 10 0 0 dollarSaving 130 0.34116 1 10 0 0 dollarSaving 132 0.35364 1 10 0 0 dollarSaving 134 0.36599 1 10 0 0 dollarSaving 136 0.37822 1 10 0 0 dollarSaving 138 0.39034 1 10 0 0 dollarSaving 140 0.40233 1 10 0 0 dollarSaving 142 0.4142 1 10 0 0 dollarSaving 144 0.42594 1 10 0 0 dollarSaving 146 0.43756 1 10 0 0 dollarSaving 148 0.44906 1 10 0 0 dollarSaving 150 0.46043 1 10 0 0 dollarSaving 152 0.47168 1 10 0 0 dollarSaving 154 0.4828 1 10 0 0 dollarSaving 156 0.49379 1 10 0 0 dollarSaving 158 0.50466 1 10 0 0 dollarSaving 160 0.51541 1 10 0 0 dollarSaving 162 0.52602 1 10 0 0 dollarSaving 164 0.53651 1 10 0 0 dollarSaving 166 0.54687 1 10 0 0 dollarSaving 168 0.55711 1 10 0 0 dollarSaving 170 0.56722 1 10 0 0 dollarSaving 172 0.5772 1 10 0 0 dollarSaving 174 0.58705 1 10 0 0 dollarSaving 176 0.59678 1 10 0 0 dollarSaving 178 0.60637 1 10 0 0 dollarSaving 180 0.61584 1 10 0 0 dollarSaving 182 0.62519 1 10 0 0 dollarSaving 184 0.6344 1 10 0 0 dollarSaving 186 0.64349 1 10 0 0 dollarSaving 188 0.65245 1 10 0 0 dollarSaving 190 0.66129 1 10 0 0 dollarSaving 192 0.67 1 10 0 0 dollarSaving 194 0.67858 1 10 0 0 dollarSaving 196 0.68704 1 10 0 0 dollarSaving 198 0.69537 1 10 0 0 dollarSaving 200 0.70358 1 10 0 0 dollarSaving 202 0.71167 1 10 0 0 dollarSaving 204 0.71963 1 10 0 0 dollarSaving 206 0.72746 1 10 0 0 dollarSaving 208 0.73517 1 10 0 0 dollarSaving 210 0.74276 1 10 0 0 dollarSaving 212 0.75023 1 10 0 0 dollarSaving 214 0.75758 1 10 0 0 dollarSaving 216 0.7648 1 10 0 0 dollarSaving 218 0.77191 1 10 0 0 dollarSaving 220 0.77889 1 10 0 0 dollarSaving 222 0.78576 1 10 0 0 dollarSaving 224 0.79251 1 10 0 0 dollarSaving 226 0.79914 1 10 0 0 dollarSaving 228 0.80565 1 10 0 0 dollarSaving 230 0.81205 1 10 0 0 dollarSaving 232 0.81833 1 10 0 0 dollarSaving 234 0.8245 1 10 0 0 dollarSaving 236 0.83055 1 10 0 0 dollarSaving 238 0.8365 1 10 0 0 dollarSaving 240 0.84233 1 10 0 0 dollarSaving 242 0.84805 1 10 0 0 dollarSaving 244 0.85366 1 10 0 0 dollarSaving 246 0.85916 1 10 0 0 dollarSaving 248 0.86455 1 10 0 0 dollarSaving 250 0.86984 1 10 0 0 dollarSaving 252 0.87502 1 10 0 0 dollarSaving 254 0.8801 1 10 0 0 dollarSaving 256 0.88507 1 10 0 0 dollarSaving 258 0.88994 1 10 0 0 dollarSaving 260 0.89471 1 10 0 0 dollarSaving 262 0.89938 1 10 0 0 dollarSaving 264 0.90395 1 10 0 0 dollarSaving 266 0.90843 1 10 0 0 dollarSaving 268 0.91281 1 10 0 0 dollarSaving 270 0.91709 1 10 0 0 dollarSaving 272 0.92128 1 10 0 0 dollarSaving 274 0.92539 1 10 0 0 dollarSaving 276 0.9294 1 10 0 0 dollarSaving 278 0.93332 1 10 0 0 dollarSaving 280 0.93715 1 10 0 0 dollarSaving 282 0.9409 1 10 0 0 dollarSaving 284 0.94457 1 10 0 0 dollarSaving 286 0.94815 1 10 0 0 dollarSaving 288 0.95165 1 10 0 0 dollarSaving 290 0.95507 1 10 0 0 dollarSaving 292 0.95842 1 10 0 0 dollarSaving 294 0.96169 1 10 0 0 dollarSaving 296 0.96488 1 10 0 0 dollarSaving 298 0.96801 1 10 0 0 dollarSaving 300 0.97106 1 10 0 0 dollarSaving 302 0.97404 1 10 0 0 dollarSaving 304 0.97696 1 10 0 0 dollarSaving 306 0.97981 1 10 0 0 dollarSaving 308 0.9826 1 10 0 0 dollarSaving 310 0.98532 1 10 0 0 dollarSaving 312 0.98799 1 10 0 0 dollarSaving 314 0.9906 1 10 0 0 dollarSaving 316 0.99315 1 10 0 0 dollarSaving 318 0.99565 1 10 0 0 dollarSaving 320 0.99809 1 10 0 0 dollarSaving 322 1.00049 1 10 0 0 dollarSaving 324 1.00283 1 10 0 0 dollarSaving 326 1.00513 1 10 0 0 dollarSaving 328 1.00738 1 10 0 0 dollarSaving 330 1.00959 1 10 0 0 dollarSaving 332 1.01176 1 10 0 0 dollarSaving 334 1.01389 1 10 0 0 dollarSaving 336 1.01598 1 10 0 0 dollarSaving 338 1.01803 1 10 0 0 dollarSaving 340 1.02005 1 10 0 0 dollarSaving 342 1.02204 1 10 0 0 dollarSaving 344 1.02399 1 10 0 0 dollarSaving 346 1.02592 1 10 0 0 dollarSaving 348 1.02782 1 10 0 0 dollarSaving 350 1.02969 1 10 0 0 dollarSaving 352 1.03154 1 10 0 0 dollarSaving 354 1.03337 1 10 0 0 dollarSaving 356 1.03518 1 10 0 0 dollarSaving 358 1.03696 1 10 0 0 dollarSaving 360 1.03873 1 10 0 0 dollarSaving 362 1.04049 1 10 0 0 dollarSaving 364 1.04222 1 10 0 0 dollarSaving 366 1.04395 1 10 0 0 dollarSaving 368 1.04566 1 10 0 0 dollarSaving 370 1.04736 1 10 0 0 dollarSaving 372 1.04906 1 10 0 0 dollarSaving 374 1.05074 1 10 0 0 dollarSaving 376 1.05242 1 10 0 0 dollarSaving 378 1.05409 1 10 0 0 dollarSaving 380 1.05576 1 10 0 0 dollarSaving 382 1.05742 1 10 0 0 dollarSaving 384 1.05908 1 10 0 0 dollarSaving 386 1.06073 1 10 0 0 dollarSaving 388 1.06238 1 10 0 0 dollarSaving 390 1.06403 1 10 0 0 dollarSaving 392 1.06568 1 10 0 0 dollarSaving 394 1.06733 1 10 0 0 dollarSaving 396 1.06898 1 10 0 0 dollarSaving 398 1.07063 1 10 0 0 dollarSaving 400 1.07228 1 10 0 0 fo 500 0.58651 1 10 0 0 fo 501 0.58111 1 10 0 0 fo 502 0.57571 1 10 0 0 fo 503 0.57031 1 10 0 0 fo 504 0.56492 1 10 0 0 fo 505 0.55952 1 10 0 0 fo 506 0.55412 1 10 0 0 fo 507 0.54872 1 10 0 0 fo 508 0.54332 1 10 0 0 fo 509 0.53793 1 10 0 0 fo 510 0.53253 1 10 0 0 fo 511 0.52713 1 10 0 0 fo 512 0.52173 1 10 0 0 fo 513 0.51633 1 10 0 0 fo 514 0.51093 1 10 0 0 fo 515 0.50554 1 10 0 0 fo 516 0.50014 1 10 0 0 fo 517 0.49474 1 10 0 0 fo 518 0.48934 1 10 0 0 fo 519 0.48394 1 10 0 0 fo 520 0.47855 1 10 0 0 fo 521 0.47315 1 10 0 0 fo 522 0.46775 1 10 0 0 fo 523 0.46235 1 10 0 0 fo 524 0.45695 1 10 0 0 fo 525 0.45156 1 10 0 0 fo 526 0.44616 1 10 0 0 fo 527 0.44076 1 10 0 0 fo 528 0.43536 1 10 0 0 fo 529 0.42996 1 10 0 0 fo 530 0.42457 1 10 0 0 fo 531 0.41917 1 10 0 0 fo 532 0.41377 1 10 0 0 fo 533 0.40837 1 10 0 0 fo 534 0.40297 1 10 0 0 fo 535 0.39758 1 10 0 0 fo 536 0.39218 1 10 0 0 fo 537 0.38678 1 10 0 0 fo 538 0.38138 1 10 0 0 fo 539 0.37598 1 10 0 0 fo 540 0.37059 1 10 0 0 fo 541 0.36519 1 10 0 0 fo 542 0.35979 1 10 0 0 fo 543 0.35439 1 10 0 0 fo 544 0.34899 1 10 0 0 fo 545 0.34359 1 10 0 0 fo 546 0.3382 1 10 0 0 fo 547 0.3328 1 10 0 0 fo 548 0.3274 1 10 0 0 fo 549 0.322 1 10 0 0 fo 550 0.3166 1 10 0 0 fo 551 0.31121 1 10 0 0 fo 552 0.30581 1 10 0 0 fo 553 0.30041 1 10 0 0 fo 554 0.29501 1 10 0 0 fo 555 0.28961 1 10 0 0 fo 556 0.28422 1 10 0 0 fo 557 0.27882 1 10 0 0 fo 558 0.27342 1 10 0 0 fo 559 0.26802 1 10 0 0 fo 560 0.26262 1 10 0 0 fo 561 0.25723 1 10 0 0 fo 562 0.25183 1 10 0 0 fo 563 0.24643 1 10 0 0 fo 564 0.24103 1 10 0 0 fo 565 0.23563 1 10 0 0 fo 566 0.23024 1 10 0 0 fo 567 0.22484 1 10 0 0 fo 568 0.21944 1 10 0 0 fo 569 0.21404 1 10 0 0 fo 570 0.20864 1 10 0 0 fo 571 0.20325 1 10 0 0 fo 572 0.19785 1 10 0 0 fo 573 0.19245 1 10 0 0 fo 574 0.18705 1 10 0 0 fo 575 0.18165 1 10 0 0 fo 576 0.17625 1 10 0 0 fo 577 0.17086 1 10 0 0 fo 578 0.16546 1 10 0 0 fo 579 0.16006 1 10 0 0 fo 580 0.15466 1 10 0 0 fo 581 0.14926 1 10 0 0 fo 582 0.14387 1 10 0 0 fo 583 0.13847 1 10 0 0 fo 584 0.13307 1 10 0 0 fo 585 0.12767 1 10 0 0 fo 586 0.12227 1 10 0 0 fo 587 0.11688 1 10 0 0 fo 588 0.11148 1 10 0 0 fo 589 0.10608 1 10 0 0 fo 590 0.10068 1 10 0 0 fo 591 0.09528 1 10 0 0 fo 592 0.08989 1 10 0 0 fo 593 0.08449 1 10 0 0 fo 594 0.07909 1 10 0 0 fo 595 0.07369 1 10 0 0 fo 596 0.06829 1 10 0 0 fo 597 0.0629 1 10 0 0 fo 598 0.0575 1 10 0 0 fo 599 0.0521 1 10 0 0 fo 600 0.0467 1 10 0 0 fo 601 0.0413 1 10 0 0 fo 602 0.03591 1 10 0 0 fo 603 0.03051 1 10 0 0 fo 604 0.02511 1 10 0 0 fo 605 0.01972 1 10 0 0 fo 606 0.01433 1 10 0 0 fo 607 0.00895 1 10 0 0 fo 608 0.00357 1 10 0 0 fo 609 -0.0018 1 10 0 0 fo 610 -0.00716 1 10 0 0 fo 611 -0.01251 1 10 0 0 fo 612 -0.01784 1 10 0 0 fo 613 -0.02316 1 10 0 0 fo 614 -0.02846 1 10 0 0 fo 615 -0.03374 1 10 0 0 fo 616 -0.03899 1 10 0 0 fo 617 -0.04422 1 10 0 0 fo 618 -0.04942 1 10 0 0 fo 619 -0.05459 1 10 0 0 fo 620 -0.05972 1 10 0 0 fo 621 -0.06482 1 10 0 0 fo 622 -0.06988 1 10 0 0 fo 623 -0.07489 1 10 0 0 fo 624 -0.07986 1 10 0 0 fo 625 -0.08478 1 10 0 0 fo 626 -0.08964 1 10 0 0 fo 627 -0.09445 1 10 0 0 fo 628 -0.09921 1 10 0 0 fo 629 -0.1039 1 10 0 0 fo 630 -0.10853 1 10 0 0 fo 631 -0.11309 1 10 0 0 fo 632 -0.11758 1 10 0 0 fo 633 -0.122 1 10 0 0 fo 634 -0.12634 1 10 0 0 fo 635 -0.1306 1 10 0 0 fo 636 -0.13478 1 10 0 0 fo 637 -0.13888 1 10 0 0 fo 638 -0.14288 1 10 0 0 fo 639 -0.1468 1 10 0 0 fo 640 -0.15063 1 10 0 0 fo 641 -0.15436 1 10 0 0 fo 642 -0.15799 1 10 0 0 fo 643 -0.16152 1 10 0 0 fo 644 -0.16494 1 10 0 0 fo 645 -0.16826 1 10 0 0 fo 646 -0.17147 1 10 0 0 fo 647 -0.17457 1 10 0 0 fo 648 -0.17756 1 10 0 0 fo 649 -0.18043 1 10 0 0 fo 650 -0.18319 1 10 0 0 fo 651 -0.18582 1 10 0 0 fo 652 -0.18834 1 10 0 0 fo 653 -0.19073 1 10 0 0 fo 654 -0.19299 1 10 0 0 fo 655 -0.19513 1 10 0 0 fo 656 -0.19714 1 10 0 0 fo 657 -0.19901 1 10 0 0 fo 658 -0.20076 1 10 0 0 fo 659 -0.20237 1 10 0 0 fo 660 -0.20385 1 10 0 0 fo 661 -0.20519 1 10 0 0 fo 662 -0.20639 1 10 0 0 fo 663 -0.20746 1 10 0 0 fo 664 -0.20838 1 10 0 0 fo 665 -0.20917 1 10 0 0 fo 666 -0.20981 1 10 0 0 fo 667 -0.21031 1 10 0 0 fo 668 -0.21067 1 10 0 0 fo 669 -0.21088 1 10 0 0 fo 670 -0.21095 1 10 0 0 fo 671 -0.21087 1 10 0 0 fo 672 -0.21065 1 10 0 0 fo 673 -0.21028 1 10 0 0 fo 674 -0.20977 1 10 0 0 fo 675 -0.20911 1 10 0 0 fo 676 -0.20831 1 10 0 0 fo 677 -0.20736 1 10 0 0 fo 678 -0.20626 1 10 0 0 fo 679 -0.20502 1 10 0 0 fo 680 -0.20363 1 10 0 0 fo 681 -0.2021 1 10 0 0 fo 682 -0.20042 1 10 0 0 fo 683 -0.1986 1 10 0 0 fo 684 -0.19664 1 10 0 0 fo 685 -0.19453 1 10 0 0 fo 686 -0.19228 1 10 0 0 fo 687 -0.1899 1 10 0 0 fo 688 -0.18737 1 10 0 0 fo 689 -0.1847 1 10 0 0 fo 690 -0.1819 1 10 0 0 fo 691 -0.17896 1 10 0 0 fo 692 -0.17588 1 10 0 0 fo 693 -0.17267 1 10 0 0 fo 694 -0.16933 1 10 0 0 fo 695 -0.16586 1 10 0 0 fo 696 -0.16226 1 10 0 0 fo 697 -0.15853 1 10 0 0 fo 698 -0.15468 1 10 0 0 fo 699 -0.1507 1 10 0 0 fo 700 -0.1466 1 10 0 0 fo 701 -0.14238 1 10 0 0 fo 702 -0.13805 1 10 0 0 fo 703 -0.1336 1 10 0 0 fo 704 -0.12903 1 10 0 0 fo 705 -0.12436 1 10 0 0 fo 706 -0.11957 1 10 0 0 fo 707 -0.11468 1 10 0 0 fo 708 -0.10969 1 10 0 0 fo 709 -0.1046 1 10 0 0 fo 710 -0.0994 1 10 0 0 fo 711 -0.09412 1 10 0 0 fo 712 -0.08874 1 10 0 0 fo 713 -0.08326 1 10 0 0 fo 714 -0.0777 1 10 0 0 fo 715 -0.07206 1 10 0 0 fo 716 -0.06633 1 10 0 0 fo 717 -0.06053 1 10 0 0 fo 718 -0.05465 1 10 0 0 fo 719 -0.04869 1 10 0 0 fo 720 -0.04267 1 10 0 0 fo 721 -0.03658 1 10 0 0 fo 722 -0.03042 1 10 0 0 fo 723 -0.02421 1 10 0 0 fo 724 -0.01793 1 10 0 0 fo 725 -0.0116 1 10 0 0 fo 726 -0.00522 1 10 0 0 fo 727 0.00121 1 10 0 0 fo 728 0.00769 1 10 0 0 fo 729 0.01421 1 10 0 0 fo 730 0.02077 1 10 0 0 fo 731 0.02737 1 10 0 0 fo 732 0.034 1 10 0 0 fo 733 0.04066 1 10 0 0 fo 734 0.04735 1 10 0 0 fo 735 0.05407 1 10 0 0 fo 736 0.06081 1 10 0 0 fo 737 0.06758 1 10 0 0 fo 738 0.07436 1 10 0 0 fo 739 0.08115 1 10 0 0 fo 740 0.08797 1 10 0 0 fo 741 0.09479 1 10 0 0 fo 742 0.10162 1 10 0 0 fo 743 0.10846 1 10 0 0 fo 744 0.11531 1 10 0 0 fo 745 0.12216 1 10 0 0 fo 746 0.12902 1 10 0 0 fo 747 0.13588 1 10 0 0 fo 748 0.14274 1 10 0 0 fo 749 0.1496 1 10 0 0 fo 750 0.15646 1 10 0 0 xcumC 0 -0.64115 1 10 0 0 xcumC 1 -0.622 1 10 0 0 xcumC 2 -0.60285 1 10 0 0 xcumC 3 -0.5837 1 10 0 0 xcumC 4 -0.56455 1 10 0 0 xcumC 5 -0.54541 1 10 0 0 xcumC 6 -0.52628 1 10 0 0 xcumC 7 -0.50716 1 10 0 0 xcumC 8 -0.48805 1 10 0 0 xcumC 9 -0.46896 1 10 0 0 xcumC 10 -0.4499 1 10 0 0 xcumC 11 -0.43086 1 10 0 0 xcumC 12 -0.41186 1 10 0 0 xcumC 13 -0.39291 1 10 0 0 xcumC 14 -0.374 1 10 0 0 xcumC 15 -0.35515 1 10 0 0 xcumC 16 -0.33636 1 10 0 0 xcumC 17 -0.31764 1 10 0 0 xcumC 18 -0.29899 1 10 0 0 xcumC 19 -0.28044 1 10 0 0 xcumC 20 -0.26197 1 10 0 0 xcumC 21 -0.24361 1 10 0 0 xcumC 22 -0.22536 1 10 0 0 xcumC 23 -0.20722 1 10 0 0 xcumC 24 -0.18921 1 10 0 0 xcumC 25 -0.17133 1 10 0 0 xcumC 26 -0.1536 1 10 0 0 xcumC 27 -0.13602 1 10 0 0 xcumC 28 -0.11859 1 10 0 0 xcumC 29 -0.10134 1 10 0 0 xcumC 30 -0.08426 1 10 0 0 xcumC 31 -0.06736 1 10 0 0 xcumC 32 -0.05066 1 10 0 0 xcumC 33 -0.03416 1 10 0 0 xcumC 34 -0.01786 1 10 0 0 xcumC 35 -0.00179 ''') matParaC2P = np.genfromtxt(paraC2P, names= ['pt1','ct','mods','mbas','para','x','y'], dtype=['&lt;f8','&lt;f8','&lt;f8','&lt;f8','|S30','&lt;f8','&lt;f8'], delimiter='\t') cdef packed struct paraArray: double pt1 double ct double mods double mbas char[30] para double x double y @cython.boundscheck(False) @cython.wraparound(False) @cython.nonecheck(False) @cython.cdivision(True) cpdef genc2p(paraArray [:] mat_p = matParaC2P, double pt_p= 1.0, double ct_p=10.0, double mbas_p =0.0, double mods_p=0.0, double count_c_p=24.0, double lv_p=60.0, double fo_p=740.0, double incentive_p = 200.0): cdef double[:,:] lvsubmat = getSubParaMat(input_s = mat_p, para_s='lv', ct_s = ct_p, pt1_s=pt_p, mbas_s=mbas_p,mods_s=0.0) cdef double lv0 = interp2d(lvsubmat[:,0], lvsubmat[:,1], lv_p) cdef double[:,:] fosubmat = getSubParaMat(input_s = mat_p, para_s='fo', ct_s = ct_p, pt1_s=pt_p, mbas_s=mbas_p,mods_s=0.0) cdef double fo0 = interp2d(fosubmat[:,0], fosubmat[:,1], fo_p) cdef double[:,:] cumCsubmat = getSubParaMat(input_s = mat_p, para_s='xcumC', ct_s = ct_p, pt1_s=pt_p, mbas_s=mbas_p,mods_s=0.0) cdef double cumC0 = interp2d(cumCsubmat[:,0], cumCsubmat[:,1], count_c_p) cdef double[:,:] incsubmat = getSubParaMat(input_s= mat_p, para_s='dollarSaving', ct_s = ct_p, pt1_s=pt_p, mbas_s=mbas_p,mods_s=mods_p) cdef double inc0 = interp2d(incsubmat[:,0], incsubmat[:,1], incentive_p) cdef double[:,:] intercept = getSubParaMat(input_s= mat_p, para_s='(Intercept)', ct_s = ct_p, pt1_s=pt_p, mbas_s=mbas_p,mods_s=0.0) cdef double intercept0 = intercept[0,1] return genLogit(lv0+fo0+cumC0+inc0+intercept0) #return intercept0 cpdef double[:,:] getSubParaMat(paraArray [:] input_s = matParaC2P, double pt1_s =1.0, double ct_s=10.0, double mods_s=0.0, double mbas_s=0.0, char[30] para_s = 'lv'): cdef int start = 0, end =0, k=0 cdef double[:,:] output = zeros2 for i from 0&lt;=i&lt;input_s.size: if input_s[i].pt1 == pt1_s and input_s[i].ct == ct_s and input_s[i].mods==mods_s and input_s[i].mbas==mbas_s and input_s[i].para[:]==para_s[:] and start==0: start = i end = i while end&lt;input_s.size and input_s[end].pt1 == pt1_s and input_s[end].ct == ct_s and input_s[end].mods==mods_s and input_s[end].mbas==mbas_s and input_s[end].para[:]==para_s[:]: (output[k,0], output[k, 1]) = (input_s[end].x, input_s[end].y) end += 1 k+=1 break return output[:k, :] cpdef double interp2d(double[:] x, double[:] y, double new_x, int ex = 0): cdef int nx = x.shape[0]-1 cdef int ny = y.shape[0]-1 cdef double new_y cdef int steps=0 if ex==0 and new_x&lt;x[0]: new_x = x[0] elif ex==0 and new_x&gt;x[nx]: new_x = x[nx] if new_x&lt;=x[0]: new_y = (new_x - x[0])*(y[0]-y[1])/(x[0] - x[1]) + y[0] elif new_x&gt;=x[nx]: new_y = (new_x - x[nx])*(y[ny] - y[ny-1])/(x[nx] - x[nx-1]) + y[ny] else: while new_x&gt;x[steps]: steps +=1 new_y = (new_x - x[steps-1])*(y[steps] - y[steps-1])/(x[steps] - x[steps-1]) + y[steps-1] return new_y cpdef double genLogit(double total): return 1.0/(1.0+exp(-1.0*(total))) cpdef genLoan(): for j from 0&lt;=j&lt;100: for i from 1&lt;=i&lt;240: prob_p = genc2p(mat_p = matParaC2P) </code></pre>
60540
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-20T01:02:35.297", "Id": "60540", "Score": "3", "Tags": [ "python", "performance", "matrix", "numpy", "cython" ], "Title": "Where is the bottleneck in my Cython code?" }
{ "body": "<p>There's a lot of code here, so I'm just going to review <code>interp2d</code>.</p>\n\n<ol>\n<li><p>There's no docstring. What does this function do? How am I supposed to call it? Are there any constraints on the parameters (for example, does the <code>x</code> array need to be sorted)?.</p></li>\n<li><p>The function seems to be misnamed: it interpolates the function that takes <code>x</code> to <code>y</code>, but this is a function of one argument, so surely <code>interp1d</code> or just <code>interp</code> would be better names. (Compare <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html\" rel=\"nofollow\"><code>numpy.interp</code></a>, which does something very similar to your function, but is documentated as \"one-dimensional linear interpolation\".)</p></li>\n<li><p>The parameter <code>ex</code> is opaquely named. What does it mean? Reading the code, it seems that it controls whether or not to <em>extrapolate</em> for values of <em>x</em> outside the given range. So it should be named <code>extrapolate</code> and it should be a Boolean (<code>True</code> or <code>False</code>) not a number.</p></li>\n<li><p>Python allows indexing from the end of an array, so you can write <code>x[-1]</code> for the last element of an array, instead of the clusmy <code>x[x.shape[0] - 1]</code>.</p></li>\n<li><p>You find the interval in which to do the interpolation by a linear search over the array <code>x</code>, which takes time proportional to the size of <code>x</code> and so will be slow when <code>x</code> is large. Since <code>x</code> needs to be sorted in order for this algorithm to make sense, you should use binary search (for example, <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html\" rel=\"nofollow\"><code>numpy.searchsorted</code></a>) so that the time taken is logarithmic in the size of <code>x</code>.</p></li>\n<li><p>You have failed to vectorize this function. The whole point of NumPy is that it provides fast operations on arrays of fixed-size numbers. If you find yourself writing a function that operates on just one value at a time (here, the single value <code>new_x</code>) then you probably aren't getting much, if any, benefit from NumPy.</p></li>\n<li><p>Putting all this together, I'd write something like this:</p>\n\n<pre><code>def interp1d(x, y, a, extrapolate=False):\n \"\"\"Interpolate a 1-D function.\n\n x is a 1-dimensional array sorted into ascending order.\n y is an array whose first axis has the same length as x.\n a is an array of interpolants.\n If extrapolate is False, clamp all interpolants to the range of x.\n\n Let f be the piecewise-linear function such that f(x) = y.\n Then return f(a).\n\n &gt;&gt;&gt; x = np.arange(0, 10, 0.5)\n &gt;&gt;&gt; y = np.sin(x)\n &gt;&gt;&gt; interp1d(x, y, np.pi)\n 0.0018202391415163\n\n \"\"\"\n if not extrapolate:\n a = np.clip(a, x[0], x[-1])\n i = np.clip(np.searchsorted(x, a), 1, len(x) - 1)\n j = i - 1\n xj, yj = x[j], y[j]\n return yj + (a - xj) * (y[i] - yj) / (x[i] - xj)\n</code></pre>\n\n<p>(The rest of the program may need to be reorganized to pass arrays of values instead of one value at a time.)</p></li>\n<li><p>Finally, what was wrong with <a href=\"http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.interp1d.html\" rel=\"nofollow\"><code>scipy.interpolate.interp1d</code></a>? It doesn't provide quite the same handling of points outside the range, but you could call <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html\" rel=\"nofollow\"><code>numpy.clip</code></a> yourself before calling it.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-26T13:05:22.670", "Id": "61075", "ParentId": "60540", "Score": "4" } }
<p>I'm new to Python and I just wrote my first program with OOP. The program works just fine and gives me what I want. Is the code clear? Can you review the style or anything else?</p> <pre><code>import numpy as np import time, os, sys import datetime as dt class TemplateGenerator(object): """This is a general class to generate all of the templates""" def excelWrtGE(self,*typos): for typo in typos: self.excelWriteGE.write(typo) return def create_KeywordsGE(self,list): list1=list.split("/") for x in list1: list1=[list1.strip()for list1 in list1] print list1 keyword1="Patrone, Toner aufladen "+str(list1[0]) keyword2="Patronen, CMYK, Set of, Ein" keyword3="Set, of, Schwarz, Cyan, Magenta, Gelb, Photoblack" keyword4="Remanufactured ink, Druckerpatronen Ersatz " keyword5=str(list1[0]) print keyword5 i=1 while len(keyword5)&lt;50: keyword5_old=keyword5 if i&gt;=len(list1): break if len(list1)==1: break keyword5=keyword5+", "+str(list1[i]) if len(keyword5)&gt;50: keyword5=keyword5_old break i=i+1 keywords=keyword1+"\t"+keyword2+"\t"+keyword3+"\t"+keyword4+"\t"+keyword5 + "\t" return keywords def keyFeaturesGE(self,feat,inkNumber): list1=feat.split(",") for x in list1: list1=[list1.strip()for list1 in list1] if inkNumber==5: feat1="Lieferumfang: : 1 Schwarz, 1 Cyan, 1 Magenta, 1 Gelb , 1 Photoblack" if inkNumber==4: feat1="Lieferumfang: : 1 Schwarz, 1 Cyan, 1 Magenta, 1 Gelb " if inkNumber==1: feat1="Lieferumfang: : 1 Cyan " if inkNumber==2: feat1="Lieferumfang: : 1 Magenta " if inkNumber==3: feat1="Lieferumfang: : 1 Gelb " if inkNumber==0: feat1="Lieferumfang: : 1 Schwarz " if inkNumber==242: feat1="Lieferumfang: : 4 Schwarz, 2 Cyan, 2 Magenta, 2 Gelb " if inkNumber==54: feat1="Lieferumfang: : 5 Schwarz, 5 Cyan, 5 Magenta, 5 Gelb " if inkNumber==11: feat1="Lieferumfang: : 1 Photoblack" if inkNumber==25: feat1="Lieferumfang: : 2 Schwarz, 2 Cyan, 2 Magenta, 2 Gelb, 2 Photoblack " if inkNumber==45: feat1="Lieferumfang: : 4 Schwarz, 4 Cyan, 4 Magenta, 4 Gelb, 4 Photoblack " if inkNumber==24: feat1="Lieferumfang: : 2 Schwarz, 2 Cyan, 2 Magenta, 2 Gelb " feat2="100% Kompatibel" feat3="Bis zu 80% Druckkosten sparen - Premium Qualit\xE4t" feat4="Geeignet f\xFCr Folgende Drucker: "+str(list1[0]) feat5="Inhalt der Druckerpatronen ca. bei 5% Deckung (DIN A4)" print feat1 i=1 while len(feat4)&lt;500: feat4_old=feat4 if i&gt;=len(list1): break if len(list1)==1: break feat4=feat4+", "+str(list1[i]) if len(feat4)&gt;500: feat4=feat4_old break i=i+1 ListOfFeatures=feat1+"\t"+ feat2+"\t"+feat3+"\t"+feat4 + "\t" +feat5+"\t" return ListOfFeatures def ManProNum(self,num): list1=num.split("/") for x in list1: list1=[list1.strip()for list1 in list1] ProdNum=str(list1[0]) i=1 while len(ProdNum)&lt;40: ProdNum_old=ProdNum if i&gt;=len(list1): break if len(list1)==1: break ProdNum=ProdNum+", "+str(list1[i]) if len(ProdNum)&gt;40: ProdNum=ProdNum_old break i=i+1 ProdNum=ProdNum+"\t" return ProdNum def pictureLink(self,amount): if amount==1: linkW="dfghj" elif amount==2: linkW="fgh" elif amount==4: linkW="hj" elif amount==5: linkW="lk" elif amount==6: linkW="erty" return str(linkW) # GERMANY STARTS HERE----------------- def GenerateGETemplatesFor6(self,ElementsOfPrinter): FourSetSalePrice=round((float(ElementsOfPrinter[5])+2.5)*1.26*1.2*1.4*1.2,2) descr="Industriell wiederaufgearbeitete und gepr\xFCfte Druckerpatronen in Premium qualit\xE4t 100% Kompatible, keine Original Geeignet f\xFCr folgende Ger\xE4te: "+ElementsOfPrinter[0]+ ". Hinweis: Die auf unseren Shop aufgef\xFChrten Markennamen und Original Zubeh\xF6rbezeichnungen sind eingetragene Warenzeichen Ihrer jeweiligen Hersteller und dienen nur als Anwenderhilfe f\xFCr die Zubeh\xF6ridentifikation.\t" title0="4 Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4]+" Set mit Chip\t" +str(FourSetSalePrice)+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],4) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" self.excelWrtGE(title0) def GenerateGETemplatesFor7(self,ElementsOfPrinter): FiveSetSalePrice=round((float(ElementsOfPrinter[6])+2.5)*1.26*1.2*1.4*1.2,2) descr="Industriell wiederaufgearbeitete und gepr\xFCfte Druckerpatrone in Premium qualit\xE4t 100% Kompatible, keine Original Geeignet f\xFCr folgende Ger\xE4te: "+ElementsOfPrinter[0]+ ". Hinweis: Die auf unseren Shop aufgef\xFChrten Markennamen und Original Zubeh\xF6rbezeichnungen sind eingetragene Warenzeichen Ihrer jeweiligen Hersteller und dienen nur als Anwenderhilfe f\xFCr die Zubeh\xF6ridentifikation.\t" title0="5 Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4]+" - "+ElementsOfPrinter[5]+" Set mit Chip\t" +str(round(FiveSetSalePrice,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],5) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" self.excelWrtGE(title0) def GenerateGETemplatesFor9(self,ElementsOfPrinter): FourSETBuyingPrice=sum(map(float,ElementsOfPrinter[5::])) FourSetSalePrice=round((FourSETBuyingPrice+2.5)*1.26*1.2*1.4*1.2,2) descr="Industriell wiederaufgearbeitete und gepr\xFCfte Druckerpatrone in Premium qualit\xE4t 100% Kompatible, keine Original Geeignet f\xFCr folgende Ger\xE4te: "+ElementsOfPrinter[0]+ ". Hinweis: Die auf unseren Shop aufgef\xFChrten Markennamen und Original Zubeh\xF6rbezeichnungen sind eingetragene Warenzeichen Ihrer jeweiligen Hersteller und dienen nur als Anwenderhilfe f\xFCr die Zubeh\xF6ridentifikation.\t" title0="4 Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[2]+" - "+ElementsOfPrinter[3]+" - " +ElementsOfPrinter[4]+" - "+ElementsOfPrinter[5]+" Set mit Chip\t" +str(round(FourSetSalePrice-1,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],4) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title1="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[2]+" Schwarz mit Chip\t" +str(round((float(ElementsOfPrinter[5])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],0) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title2="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[3]+" Cyan mit Chip\t" +str(round((float(ElementsOfPrinter[6])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],1) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title3="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[4]+" Magenta mit Chip\t" +str(round((float(ElementsOfPrinter[7])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],2) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title4="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[5]+" Gelb mit Chip\t" +str(round((float(ElementsOfPrinter[8])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],3) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title5="4 Druckerpatronen mit CHIP kompatibel f\xFCr "+ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4] +" Multipack SET f\xFCr" +ElementsOfPrinter[0] +" mit Chip\t" +str(round(FourSetSalePrice,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],4) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title6="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+", "+ElementsOfPrinter[2]+", "+ElementsOfPrinter[3]+", "+ElementsOfPrinter[4]+" SET "+ElementsOfPrinter[0]+"\t" +str(round(FourSetSalePrice,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],4) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title7="20 Patronen MIT CHIP kompatibel zu "+ ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4]+"\t" +str(round((FourSETBuyingPrice*5+2.5)*1.26*1.2*1.4*1.2-5,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],54) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title8="10 Premium Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4]+"f\xFCr"+ElementsOfPrinter[0] +"2 SET + 2 BLACK\t" +str(round(((FourSETBuyingPrice*2+2*float(ElementsOfPrinter[5]))+2.5)*1.26*1.2*1.4*1.2-2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],242) +self.create_KeywordsGE(ElementsOfPrinter[0]) +self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title9="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+ "f\xFCr "+ElementsOfPrinter[2]+" Schwarz\t" +str(round((float(ElementsOfPrinter[5])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],0) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title10="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[2]+ "f\xFCr "+ElementsOfPrinter[3]+" Cyan\t" +str(round((float(ElementsOfPrinter[6])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],1) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title11="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[3]+ "f\xFCr "+ElementsOfPrinter[4]+" Magenta\t" +str(round((float(ElementsOfPrinter[7])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],2) +self.create_KeywordsGE(ElementsOfPrinter[0]) +self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title12="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[4]+ "f\xFCr "+ElementsOfPrinter[5]+" Gelb\t"+str(round((float(ElementsOfPrinter[8])+2.5)*1.26*1.2*1.4*1.2,2))+"\t" +self.keyFeaturesGE(ElementsOfPrinter[0],3) +self.create_KeywordsGE(ElementsOfPrinter[0]) +self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" self.excelWrtGE(title0,title1,title2,title3,title4,title5,title6,title7,title8,title9,title10,title11,title12) def GenerateGETemplatesFor11(self,ElementsOfPrinter): # print ElementsOfPrinter[5], ElementsOfPrinter[10] FiveSETBuyingPrice=sum(map(float,ElementsOfPrinter[6::])) FourSETBuyingPrice=sum(map(float,ElementsOfPrinter[7::])) FourSetSalePrice=(FourSETBuyingPrice+2.5)*1.26*1.2*1.4*1.2 FiveSetSalePrice=round((FiveSETBuyingPrice+2.5)*1.26*1.2*1.4*1.2) descr="Industriell wiederaufgearbeitete und gepr\xFCfte Druckerpatrone in Premium qualit\xE4t 100% Kompatible, keine Original Geeignet f\xFCr folgende Ger\xE4te: "+ElementsOfPrinter[0]+ ". Hinweis: Die auf unseren Shop aufgef\xFChrten Markennamen und Original Zubeh\xF6rbezeichnungen sind eingetragene Warenzeichen Ihrer jeweiligen Hersteller und dienen nur als Anwenderhilfe f\xFCr die Zubeh\xF6ridentifikation.\t" title0="4 Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4]+" Set mit Chip\t" +str(round(FourSetSalePrice,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],4) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title1="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[1]+" Photoblack mit Chip\t" +str(round((float(ElementsOfPrinter[6])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],11) +self.create_KeywordsGE(ElementsOfPrinter[0]) +self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title2="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[2]+" Schwarz mit Chip\t" +str(round((float(ElementsOfPrinter[7])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],1) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title3="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[3]+" Cyan mit Chip\t" +str(round((float(ElementsOfPrinter[8])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],1) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title4="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[4]+" Magenta mit Chip\t" +str(round((float(ElementsOfPrinter[9])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[2],2) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title5="Druckerpatrone kompatibel f\xFCr "+ElementsOfPrinter[5]+" Gelb mit Chip\t" +str(round((float(ElementsOfPrinter[10])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],3) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title6="5 Druckerpatronen mit CHIP kompatibel f\xFCr "+ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4] +" - "+ElementsOfPrinter[5]+" Multipack SET f\xFCr " +ElementsOfPrinter[0] +" mit Chip\t" +str(FiveSetSalePrice)+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],5) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title7="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+", "+ElementsOfPrinter[2]+", "+ElementsOfPrinter[3]+", "+ElementsOfPrinter[4]+","+ElementsOfPrinter[5]+" SET "+ElementsOfPrinter[0]+"\t" +str(round(FiveSetSalePrice,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],5) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title8="20 Patronen MIT CHIP kompatibel zu "+ ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4]+" - "+ElementsOfPrinter[5]+"\t" +str(round((FiveSETBuyingPrice*4+2.5)*1.26*1.2*1.4*1.2-4,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],45) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title9="10 Premium Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+" - "+ElementsOfPrinter[2]+" - " +ElementsOfPrinter[3]+" - "+ElementsOfPrinter[4]+" - "+ElementsOfPrinter[5]+" f\xFCr"+ElementsOfPrinter[0] +"2 SET\t" +str(round((FiveSETBuyingPrice*2+2.5)*1.26*1.2*1.4*1.2-2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],25) +self.create_KeywordsGE(ElementsOfPrinter[0]) +self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title10="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[1]+ "f\xFCr "+ElementsOfPrinter[0]+" Photoblack\t"+str(round((float(ElementsOfPrinter[6])+2.5)*1.26*1.2*1.4*1.2,2))+"\t" +self.keyFeaturesGE(ElementsOfPrinter[0],11) +self.create_KeywordsGE(ElementsOfPrinter[0]) +self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title11="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[2]+ "f\xFCr "+ElementsOfPrinter[0]+" Schwarz\t" +str(round((float(ElementsOfPrinter[7])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],0) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title12="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[3]+ "f\xFCr "+ElementsOfPrinter[0]+" Cyan\t" +str(round((float(ElementsOfPrinter[8])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],1) +self.create_KeywordsGE(ElementsOfPrinter[0])+self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title13="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[4]+ "f\xFCr "+ElementsOfPrinter[0]+" Magenta\t" +str(round((float(ElementsOfPrinter[9])+2.5)*1.26*1.2*1.4*1.2,2))+"\t"+self.keyFeaturesGE(ElementsOfPrinter[0],2) +self.create_KeywordsGE(ElementsOfPrinter[0]) +self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" title14="XXL PREMIUM Druckerpatronen kompatibel f\xFCr "+ElementsOfPrinter[5]+ "f\xFCr "+ElementsOfPrinter[0]+" Gelb\t"+str(round((float(ElementsOfPrinter[10])+2.5)*1.26*1.2*1.4*1.2,2))+"\t" +self.keyFeaturesGE(ElementsOfPrinter[0],3) +self.create_KeywordsGE(ElementsOfPrinter[0]) +self.ManProNum(ElementsOfPrinter[0])+descr+self.pictureLink(1)+"\n" self.excelWrtGE(title0,title1,title2,title3,title4,title5,title6,title7,title8,title9,title10,title11,title12,title13,title14) def __init__(self): super(TemplateGenerator, self).__init__() # self.arg = arg now=dt.datetime.now() cur_time=time.mktime(now.timetuple()) path='/Users/dfghj/Desktop/listings/THM/'+str(cur_time) print str(cur_time) os.mkdir(path) excelRead=open('/Users/dfghj/Desktop/listings/dataGA.txt','r') self.excelWriteGE=open(path +'/Them.GE.Sets.txt','w') header="Titles\t"+"Price equal to title:\t"+"Key Features1\t"+"Key Features2\t"+"Key Features3\t"+"Key Features4\t"+"Key Feature5\t"+"keyword1\t"+"keyword2\t"+"keyword3\t"+"keyword4\t"+"keyword5\t"+"Manufacturer Part Number\t"+"Description\t"+"Picture Link\n" self.excelWrtGE(header) data=np.genfromtxt(excelRead, delimiter="\n", dtype=None) for line in data: titles=line.split("+") # print title, len(title) if len(titles)==11: self.GenerateGETemplatesFor11(titles) elif len(titles)==9: self.GenerateGETemplatesFor9(titles) elif len(titles)==7: self.GenerateGETemplatesFor7(titles) elif len(titles)==6: self.GenerateGETemplatesFor6(titles) else: print "Check your names in file once again!!!" excelRead.close() self.excelWriteGE.close() self.excelWriteSP.close() if __name__=='__main__': TemplateGenerator() </code></pre>
70989
GOOD_ANSWER
{ "AcceptedAnswerId": "70994", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-27T11:04:44.870", "Id": "70989", "Score": "4", "Tags": [ "python", "beginner", "parsing", "numpy" ], "Title": "Printer Color Templates" }
{ "body": "<p>I could make out some parts that could be improved.</p>\n\n<ol>\n<li>Good that you have used docstring for the class. You could do the same for the methods. In general, the code could have more comments where things are not obvious. Right now there are hardly any comments.</li>\n<li>Python programmers prefer <code>functions_named_like_this()</code> rather than <code>functionsNamedLikeThis()</code>.</li>\n<li><code>__init__()</code> should preferably be at the start of the class. Those who read the code will want to know how it is initialized before looking at other things.</li>\n<li>Is this really necessary: <code>super(TemplateGenerator, self).__init__()</code> ? I don't know the answer but I believe the base class <code>__init__</code> method either does nothing useful or is invoked by default.</li>\n<li>A better way to open/close files is using the <code>with</code> statement. That way, you never need to worry about files you have forgotten to close.</li>\n<li><code>header=\"Titles\\t\"+\"Price equal to title:\\t\"+\"Key Features1\\t\"+\"Key Features2\\t\"+\"Key Features3\\t\"+\"Key Features4\\t\"+\"Key Feature5\\t\"+\"keyword1\\t\"+\"keyword2\\t\"+\"keyword3\\t\"+\"keyword4\\t\"+\"keyword5\\t\"+\"Manufacturer Part Number\\t\"+\"Description\\t\"+\"Picture Link\\n\"</code>: this is definitely not Pythonic. Use instead a list and then call <code>'\\t'.join()</code> on that list.</li>\n<li><code>(x+2.5)*1.26*1.2*1.4*1.2</code>: since this is used in many places, put it into a method.</li>\n<li><code>ElementsOfPrinter[]</code>: this is really cryptic since it's hard to remember the semantics of each position. It would be better to extract them into named variables. Example: <code>x,y,z = position</code>, assuming position is a list of 3 items.</li>\n<li><code>list1=[list1.strip()for list1 in list1]</code>: nothing wrong here but it is better for readability to use different variable names.</li>\n<li>test0, test1, ...: can be converted to a list instead. Also, Python allows you to have multiline strings. No need to type them out in long lines.</li>\n<li><code>if inkNumber==4:</code> : convert to <code>elif</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-27T15:24:26.833", "Id": "129792", "Score": "0", "body": "Thanks a lot, I really appreciate that, will try to bring some parts of code according to some rules, thanks again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-27T15:41:13.727", "Id": "129799", "Score": "0", "body": "ElementsOfPrinter[] I do remember the order of all variables, but since data which is read from file can be different, I wanted to send all variables to their methods[GenerateGETemplatesFor6] (according to element amount) and then work with elements inside, isn't that bette?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-27T11:55:48.850", "Id": "70994", "ParentId": "70989", "Score": "2" } }
<p>In honor of Star Wars day, I've put together this small Python program I'm calling JediScript. JediScript is essentially a scrapped-down version of BrainFuck without input or looping. Here are the commands in JediScript.</p> <ul> <li><code>SlashWithSaber</code>: Move forward on the tape.</li> <li><code>ParryBladeWithSaber</code>: Move backward on the tape.</li> <li><code>StabWithSaber</code>: Increment a cell.</li> <li><code>BlockBladeWithSaber</code>: Decrement cell.</li> <li><code>UseForceWithHands</code>: Output the current cell.</li> </ul> <p>Each command is semicolon <code>;</code> separated, like so: <code>StabWithSaber;UseForceWithHands</code>. Here's an example input. This will output the character <code>p</code>.</p> <blockquote> <pre><code>StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;StabWithSaber;UseForceWithHands; </code></pre> </blockquote> <p>This is something that I threw together in about 20 minutes, so it's not the greatest, but I'd still appreciate a review.</p> <pre><code>#!/usr/bin/env python """ JediScript, BrainFuck for Star Wars. May the 4th be with you. """ DEFAULT_SPLIT = ";" """ Variables below this are environment variables for the user to modify. """ data_tape = [0 for _ in range(256)] tape_pos = 0 def increment_cell(): global data_tape global tape_pos data_tape[tape_pos] += 1 if data_tape[tape_pos] &lt;= 127 else 0 def decrement_cell(): global data_tape global tape_pos data_tape[tape_pos] -= 1 if data_tape[tape_pos] &gt;= 0 else 0 def move_forward(): global tape_pos tape_pos += 1 if tape_pos &lt;= len(data_tape) - 1 else 0 def move_backward(): global tape_pos tape_pos -= 1 if tape_pos &gt;= 0 else 0 def output_cell(): print chr(data_tape[tape_pos]) """ Dictionary contains tokens that reference their relevant functions. """ TOKENS = { "SlashWithSaber": move_forward, "ParryBladeWithSaber": move_backward, "StabWithSaber": increment_cell, "BlockBladeWithSaber": decrement_cell, "UseForceWithHands": output_cell, } def execute_commands(tokenized_string): """ Executes commands from the tokenized string. tokenized_string - The tokenized string """ for token in tokenized_string: if token in TOKENS: TOKENS[token]() def tokenize_input(string): """ Tokenize a string into it's the form [ token, ... ] string - The string to tokenize. """ string = string.replace(" ", "") string = string.split(DEFAULT_SPLIT) return string def get_user_input(prompt): """ Get input from the user. prompt - The prompt to be used. """ while True: string = raw_input(prompt) string = tokenize_input(string) execute_commands(string) if __name__ == "__main__": get_user_input("JediScript $ ") </code></pre>
88783
WEIRD
{ "AcceptedAnswerId": "88797", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-04T14:07:32.930", "Id": "88783", "Score": "16", "Tags": [ "python", "interpreter", "language-design" ], "Title": "JediScript - May the 4th be with you" }
{ "body": "<ul>\n<li>Why do you allow each cell of the tape to hold numbers from -1 to 128? seems like an odd range.</li>\n<li>in <code>move_backward()</code> why do you allow the tape to reach position -1?</li>\n<li>in <code>move_forward()</code> why do you allow the tape's position to be beyond the end of the tape?</li>\n<li>In general you should be using exclusive comparisons (without the =) as you'll make fewer mistakes.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-04T17:16:54.343", "Id": "161788", "Score": "4", "body": "I don't understand why using exclusive comparisons would make fewer mistakes ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-04T17:33:36.117", "Id": "161790", "Score": "4", "body": "I don't either, but there's actually research on it. Coders who use an exclusive comparison for the top-end of the loop or the range make fewer off-by-one errors than coders who use the \"-or-equal-to\" comparators." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-04T17:36:02.913", "Id": "161792", "Score": "6", "body": "I would be interested in the link to that research!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-04T19:14:45.967", "Id": "161821", "Score": "1", "body": "Searched a while and all I came up with was https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html I'll keep looking" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-04T17:02:51.233", "Id": "88797", "ParentId": "88783", "Score": "11" } }
<h2><strong><a href="https://codegolf.stackexchange.com/questions/50472/check-if-words-are-isomorphs">Are the words isomorphs? (Code-Golf)</a></strong></h2> <p>This is my non-golfed, readable and linear (quasi-linear?) in complexity take of the above problem. For completeness I include the description:</p> <blockquote> <p>Two words are isomorphs if they have the same pattern of letter repetitions. For example, both ESTATE and DUELED have pattern abcdca</p> <pre><code>ESTATE DUELED abcdca </code></pre> <p>because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching <code>E &lt;-&gt; D, S &lt;-&gt; U, T &lt;-&gt; E, A &lt;-&gt; L</code>.</p> <p>Write code that takes two words and checks whether they are isomorphs.</p> </blockquote> <p>As always tests are included for easier understanding and modification.</p> <pre><code>def repetition_pattern(text): """ Same letters get same numbers, small numbers are used first. Note: two-digits or higher numbers may be used if the the text is too long. &gt;&gt;&gt; repetition_pattern('estate') '012320' &gt;&gt;&gt; repetition_pattern('dueled') '012320' &gt;&gt;&gt; repetition_pattern('longer example') '012345647891004' # ^ ^ ^ 4 stands for 'e' because 'e' is at 4-th position. # ^^ Note the use of 10 after 9. """ for index, unique_letter in enumerate(sorted(set(text), key=text.index)): text = text.replace(unique_letter, str(index)) return text def are_isomorph(word_1, word_2): """ Have the words (or string of arbitrary characters) the same the same `repetition_pattern` of letter repetitions? All the words with all different letters are trivially isomorphs to each other. &gt;&gt;&gt; are_isomorph('estate', 'dueled') True &gt;&gt;&gt; are_isomorph('estate'*10**4, 'dueled'*10**4) True &gt;&gt;&gt; are_isomorph('foo', 'bar') False """ return repetition_pattern(word_1) == repetition_pattern(word_2) </code></pre>
94776
GOOD_ANSWER
{ "AcceptedAnswerId": "94810", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-26T13:36:14.983", "Id": "94776", "Score": "3", "Tags": [ "python", "strings", "unit-testing", "rags-to-riches" ], "Title": "Are the words isomorph?" }
{ "body": "<pre><code>for index, unique_letter in enumerate(sorted(set(text), key=text.index)):\n text = text.replace(unique_letter, str(index))\nreturn text\n</code></pre>\n\n<p>You don't need to go through the set and sort, you can do:</p>\n\n<pre><code>for index, letter in enumerate(text):\n text = text.replace(letter, str(index))\nreturn text\n</code></pre>\n\n<p>By the time it gets to the last \"e\" in \"estate\" and tries to replace it with \"5\", it will already have replaced it with \"0\" earlier on, and there won't be any \"e\"s left to replace. And it's not changing something while iterating over it, because strings are immutable.</p>\n\n<p>More golf-ish and less readable is:</p>\n\n<pre><code>return ''.join(str(text.index(letter)) for letter in text)\n</code></pre>\n\n<p><strong>Edit:</strong> Note for posterity: the above two methods have the same bug Gareth Rees identified, comparing 'decarbonist' and 'decarbonized', where one ends by adding number 10 and the other is a character longer and ends by adding numbers 1, 0 and they compare equally.<strong>End Edit</strong></p>\n\n<p>But @jonsharpe's comment asks if you need it to return a string; if you don't, then it could be a list of numbers, which is still very readable:</p>\n\n<pre><code>return [text.index(letter) for letter in text]\n</code></pre>\n\n<p>Minor things:</p>\n\n<ul>\n<li><code>are_isomorph</code> is a mix of plural/singular naming. Maybe <code>isomorphic(a, b)</code>?</li>\n<li>Your code doesn't take uppercase/lowercase into account - should it?</li>\n<li>This approach will break without warning for an input with numbers in it, e.g.\n\n<ul>\n<li><code>repetition_pattern('abcdefghi1')</code> is <code>0923456789</code>. \"b\" changes to 1, then changes to 9 because the \"1\" at the end catches it, then it appears the two were originally the same character. (It might be outside the scope of the question and not a problem).</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-26T19:34:24.933", "Id": "94810", "ParentId": "94776", "Score": "2" } }
<h2><strong><a href="https://codegolf.stackexchange.com/questions/50472/check-if-words-are-isomorphs">Are the words isomorphs? (Code-Golf)</a></strong></h2> <p>This is my non-golfed, readable and linear (quasi-linear?) in complexity take of the above problem. For completeness I include the description:</p> <blockquote> <p>Two words are isomorphs if they have the same pattern of letter repetitions. For example, both ESTATE and DUELED have pattern abcdca</p> <pre><code>ESTATE DUELED abcdca </code></pre> <p>because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching <code>E &lt;-&gt; D, S &lt;-&gt; U, T &lt;-&gt; E, A &lt;-&gt; L</code>.</p> <p>Write code that takes two words and checks whether they are isomorphs.</p> </blockquote> <p>As always tests are included for easier understanding and modification.</p> <pre><code>def repetition_pattern(text): """ Same letters get same numbers, small numbers are used first. Note: two-digits or higher numbers may be used if the the text is too long. &gt;&gt;&gt; repetition_pattern('estate') '012320' &gt;&gt;&gt; repetition_pattern('dueled') '012320' &gt;&gt;&gt; repetition_pattern('longer example') '012345647891004' # ^ ^ ^ 4 stands for 'e' because 'e' is at 4-th position. # ^^ Note the use of 10 after 9. """ for index, unique_letter in enumerate(sorted(set(text), key=text.index)): text = text.replace(unique_letter, str(index)) return text def are_isomorph(word_1, word_2): """ Have the words (or string of arbitrary characters) the same the same `repetition_pattern` of letter repetitions? All the words with all different letters are trivially isomorphs to each other. &gt;&gt;&gt; are_isomorph('estate', 'dueled') True &gt;&gt;&gt; are_isomorph('estate'*10**4, 'dueled'*10**4) True &gt;&gt;&gt; are_isomorph('foo', 'bar') False """ return repetition_pattern(word_1) == repetition_pattern(word_2) </code></pre>
94776
WEIRD
{ "AcceptedAnswerId": "94810", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-26T13:36:14.983", "Id": "94776", "Score": "3", "Tags": [ "python", "strings", "unit-testing", "rags-to-riches" ], "Title": "Are the words isomorph?" }
{ "body": "<p>There is a Python feature that almost directly solves this problem, leading to a simple and fast solution.</p>\n\n<pre><code>from string import maketrans # &lt;-- Python 2, or\nfrom str import maketrans # &lt;-- Python 3\n\ndef are_isomorph(string1, string2):\n return len(string1) == len(string2) and \\\n string1.translate(maketrans(string1, string2)) == string2\n string2.translate(maketrans(string2, string1)) == string1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-26T23:09:47.493", "Id": "172956", "Score": "0", "body": "`are_isomorph('abcdef', 'estate')` returns `true`. This is because the order in which the translation table is made. Maybe instead you could use `are_isomorph(a, b) and are_isomorph(b, a)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-29T14:43:39.380", "Id": "173407", "Score": "0", "body": "I get `ImportError: No module named 'str'` when I run this code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-26T20:55:17.720", "Id": "94817", "ParentId": "94776", "Score": "2" } }
<h2><strong><a href="https://codegolf.stackexchange.com/questions/50472/check-if-words-are-isomorphs">Are the words isomorphs? (Code-Golf)</a></strong></h2> <p>This is my non-golfed, readable and linear (quasi-linear?) in complexity take of the above problem. For completeness I include the description:</p> <blockquote> <p>Two words are isomorphs if they have the same pattern of letter repetitions. For example, both ESTATE and DUELED have pattern abcdca</p> <pre><code>ESTATE DUELED abcdca </code></pre> <p>because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching <code>E &lt;-&gt; D, S &lt;-&gt; U, T &lt;-&gt; E, A &lt;-&gt; L</code>.</p> <p>Write code that takes two words and checks whether they are isomorphs.</p> </blockquote> <p>As always tests are included for easier understanding and modification.</p> <pre><code>def repetition_pattern(text): """ Same letters get same numbers, small numbers are used first. Note: two-digits or higher numbers may be used if the the text is too long. &gt;&gt;&gt; repetition_pattern('estate') '012320' &gt;&gt;&gt; repetition_pattern('dueled') '012320' &gt;&gt;&gt; repetition_pattern('longer example') '012345647891004' # ^ ^ ^ 4 stands for 'e' because 'e' is at 4-th position. # ^^ Note the use of 10 after 9. """ for index, unique_letter in enumerate(sorted(set(text), key=text.index)): text = text.replace(unique_letter, str(index)) return text def are_isomorph(word_1, word_2): """ Have the words (or string of arbitrary characters) the same the same `repetition_pattern` of letter repetitions? All the words with all different letters are trivially isomorphs to each other. &gt;&gt;&gt; are_isomorph('estate', 'dueled') True &gt;&gt;&gt; are_isomorph('estate'*10**4, 'dueled'*10**4) True &gt;&gt;&gt; are_isomorph('foo', 'bar') False """ return repetition_pattern(word_1) == repetition_pattern(word_2) </code></pre>
94776
WEIRD
{ "AcceptedAnswerId": "94810", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-26T13:36:14.983", "Id": "94776", "Score": "3", "Tags": [ "python", "strings", "unit-testing", "rags-to-riches" ], "Title": "Are the words isomorph?" }
{ "body": "<p><code>text.replace()</code> is \\$\\mathcal{O}(n)\\$. Assuming we have a string of \\$n\\$ distinct characters your algorithm could devolve in to \\$\\mathcal{O}(n^2)\\$. Of course your strings are likely never long enough for big O to matter.</p>\n\n<p>In problems like this no matter what language you use it is often useful to build tables of characters.</p>\n\n<pre><code>def base_pattern(text):\n lst=[chr(i) for i in range(256)]\n\n for index, c in enumerate(text):\n lst[ord(c)] = index\n\n return [lst[ord(c)] for c in text]\n\ndef are_isomorph(word1, word2):\n return base_pattern(word1) == base_pattern(word2)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-29T15:06:56.350", "Id": "173414", "Score": "0", "body": "This is brittle: what if `ord(c)` is greater than 255? `ord('\\N{HIRAGANA LETTER KA}')` → 12363." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-30T19:14:09.133", "Id": "173866", "Score": "0", "body": "@GarethRees This code was never meant to support anything other than ASCII. The codegolf even defines the range as `A..Z`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-30T20:00:01.200", "Id": "173872", "Score": "0", "body": "Sure, but a robust implementation would also be shorter: `d={c: i for i, c in enumerate(text)}; return [d[c] for c in text]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-30T20:34:57.877", "Id": "173891", "Score": "0", "body": "And then I would have a hash table which provides an \\$\\mathrm{O}(n^2)\\$ worst case to the entire algorithm and goes against the point of my post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-30T21:02:56.740", "Id": "173904", "Score": "0", "body": "All characters have different hashes, so the worst case is \\$O(n)\\$." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-26T23:30:04.890", "Id": "94836", "ParentId": "94776", "Score": "0" } }
<h2><strong><a href="https://codegolf.stackexchange.com/questions/50472/check-if-words-are-isomorphs">Are the words isomorphs? (Code-Golf)</a></strong></h2> <p>This is my non-golfed, readable and linear (quasi-linear?) in complexity take of the above problem. For completeness I include the description:</p> <blockquote> <p>Two words are isomorphs if they have the same pattern of letter repetitions. For example, both ESTATE and DUELED have pattern abcdca</p> <pre><code>ESTATE DUELED abcdca </code></pre> <p>because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching <code>E &lt;-&gt; D, S &lt;-&gt; U, T &lt;-&gt; E, A &lt;-&gt; L</code>.</p> <p>Write code that takes two words and checks whether they are isomorphs.</p> </blockquote> <p>As always tests are included for easier understanding and modification.</p> <pre><code>def repetition_pattern(text): """ Same letters get same numbers, small numbers are used first. Note: two-digits or higher numbers may be used if the the text is too long. &gt;&gt;&gt; repetition_pattern('estate') '012320' &gt;&gt;&gt; repetition_pattern('dueled') '012320' &gt;&gt;&gt; repetition_pattern('longer example') '012345647891004' # ^ ^ ^ 4 stands for 'e' because 'e' is at 4-th position. # ^^ Note the use of 10 after 9. """ for index, unique_letter in enumerate(sorted(set(text), key=text.index)): text = text.replace(unique_letter, str(index)) return text def are_isomorph(word_1, word_2): """ Have the words (or string of arbitrary characters) the same the same `repetition_pattern` of letter repetitions? All the words with all different letters are trivially isomorphs to each other. &gt;&gt;&gt; are_isomorph('estate', 'dueled') True &gt;&gt;&gt; are_isomorph('estate'*10**4, 'dueled'*10**4) True &gt;&gt;&gt; are_isomorph('foo', 'bar') False """ return repetition_pattern(word_1) == repetition_pattern(word_2) </code></pre>
94776
GOOD_ANSWER
{ "AcceptedAnswerId": "94810", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-26T13:36:14.983", "Id": "94776", "Score": "3", "Tags": [ "python", "strings", "unit-testing", "rags-to-riches" ], "Title": "Are the words isomorph?" }
{ "body": "<p>The code in the post does not work! Here's an example where it fails:</p>\n\n<pre><code>&gt;&gt;&gt; are_isomorph('decarbonist', 'decarbonized')\nTrue\n</code></pre>\n\n<p>The problem is that the eleventh distinct character gets represented by <code>10</code>, but an occurrence of the second distinct character followed by the first distinct character is also represented by <code>10</code>. You could avoid this confusion by representing the pattern as a list instead of a string:</p>\n\n<pre><code>def repetition_pattern(s):\n \"\"\"Return the repetition pattern of the string s as a list of numbers,\n with same/different characters getting same/different numbers.\n\n \"\"\"\n return list(map({c: i for i, c in enumerate(s)}.get, s))\n</code></pre>\n\n<p>or, if you don't care about algorithmic efficiency:</p>\n\n<pre><code> return list(map(s.find, s))\n</code></pre>\n\n<p>but an alternative approach avoids generating a repetition pattern at all, but instead considers the pairs of corresponding characters in the two strings. If we have:</p>\n\n<pre><code>ESTATE\nDUELED\n</code></pre>\n\n<p>then the pairs are E↔D, S↔U, T↔E and A↔L. The two strings are isomorphic if and only if these pairs constitute a bijection: that is, iff the first characters of the pairs are all distinct, and so are the second characters.</p>\n\n<pre><code>def isomorphic(s, t):\n \"\"\"Return True if strings s and t are isomorphic: that is, if they\n have the same pattern of characters.\n\n &gt;&gt;&gt; isomorphic('estate', 'dueled')\n True\n &gt;&gt;&gt; isomorphic('estate'*10**4, 'dueled'*10**4)\n True\n &gt;&gt;&gt; isomorphic('foo', 'bar')\n False\n\n \"\"\"\n if len(s) != len(t):\n return False\n pairs = set(zip(s, t))\n return all(len(pairs) == len(set(c)) for c in zip(*pairs))\n</code></pre>\n\n<p>From a purely code golf point of view, however, the following seems hard to beat (especially in Python 2, where you can drop the <code>list</code> calls):</p>\n\n<pre><code>list(map(s.find, s)) == list(map(t.find, t))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-29T16:22:51.073", "Id": "173431", "Score": "0", "body": "Ooh, I was wondering about where it switched to double digits, but decided that as long as both strings were the same it would work. I should have thought of different length strings. (Sorry, I was trying to edit my post with your correct name, but you got to it first)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-29T16:28:29.787", "Id": "173432", "Score": "1", "body": "@TessellatingHeckler: Even strings of the same length can go wrong. Consider `abcdefgihjkba` versus `abcdefgihjbak`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-29T15:18:18.900", "Id": "95090", "ParentId": "94776", "Score": "2" } }
<p>I am new to programming and I am trying to make a simple unit converter in python. I want to convert units within the metric system and metric to imperial and vice-versa. I have started with this code and I found this method is slow and in-efficient, How can I code this more efficiently?</p> <pre><code>import math import time """Unit Converter""" #Welcome and variable setting print ("Welcome to Sam's Unit Converter") cat = raw_input ("Which category would you like to convert? we support length(l) and Weight(w): ") if cat == ("l"): unit1 = raw_input ("Which unit would you like to convert from: ") unit2 = raw_input ("Which unit would you like to convert to: ") num1 = raw_input ("Enter your value: " ) ##Calculations if unit1 == "cm" and unit2 == "m": ans = float(num1)/100 elif unit1 == "mm" and unit2 == "cm": ans = float(num1)/10 elif unit1 == "m" and unit2 == "cm": ans = float(num1)*100 elif unit1 == "cm" and unit2 == "mm": ans = float(num1)*10 elif unit1 == "mm" and unit2 == "m": ans = float(num1)/1000 elif unit1 == "m" and unit2 == "mm": ans = float(num1)*1000 elif unit1 == "km" and unit2 == "m": ans = float(num1)*1000 elif unit1 == "m" and unit2 == "km": ans = float(num1)/1000 elif unit1 == "mm" and unit2 == "km": ans = float(num1)/1000000 </code></pre>
101348
BAD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2015-08-19T09:35:27.683", "Id": "101348", "Score": "4", "Tags": [ "python", "beginner", "unit-conversion" ], "Title": "Unit converter in Python" }
{ "body": "<p>Instead of converting directly between arbitrary units, choose a standard unit and do the conversion in two steps, to and from the standard unit. That way you only need one conversion factor for each unit. Store the conversion factors in a dictionary keyed by the unit name.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-19T14:56:38.697", "Id": "185356", "Score": "1", "body": "In practice this can cause problems due to issues with floating-point numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-20T06:33:48.053", "Id": "185474", "Score": "1", "body": "@TheBlackCat We're discussing a beginner's programming exercise here. I stand by my straightforward suggestion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-09T15:18:19.017", "Id": "395825", "Score": "0", "body": "@TheBlackCat - the biggest conversion is 1e6. That can be represented exactly, so we're no less accurate than the original (we need to shuffle the arithmetic slightly so that we create the conversion factor from input and output units, and then multiply or divide by that; we might be able to streamline the code by embedding the multiply/divide decision in an integer-rational number)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-19T09:55:58.583", "Id": "101352", "ParentId": "101348", "Score": "3" } }
<p>I am new to programming and I am trying to make a simple unit converter in python. I want to convert units within the metric system and metric to imperial and vice-versa. I have started with this code and I found this method is slow and in-efficient, How can I code this more efficiently?</p> <pre><code>import math import time """Unit Converter""" #Welcome and variable setting print ("Welcome to Sam's Unit Converter") cat = raw_input ("Which category would you like to convert? we support length(l) and Weight(w): ") if cat == ("l"): unit1 = raw_input ("Which unit would you like to convert from: ") unit2 = raw_input ("Which unit would you like to convert to: ") num1 = raw_input ("Enter your value: " ) ##Calculations if unit1 == "cm" and unit2 == "m": ans = float(num1)/100 elif unit1 == "mm" and unit2 == "cm": ans = float(num1)/10 elif unit1 == "m" and unit2 == "cm": ans = float(num1)*100 elif unit1 == "cm" and unit2 == "mm": ans = float(num1)*10 elif unit1 == "mm" and unit2 == "m": ans = float(num1)/1000 elif unit1 == "m" and unit2 == "mm": ans = float(num1)*1000 elif unit1 == "km" and unit2 == "m": ans = float(num1)*1000 elif unit1 == "m" and unit2 == "km": ans = float(num1)/1000 elif unit1 == "mm" and unit2 == "km": ans = float(num1)/1000000 </code></pre>
101348
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2015-08-19T09:35:27.683", "Id": "101348", "Score": "4", "Tags": [ "python", "beginner", "unit-conversion" ], "Title": "Unit converter in Python" }
{ "body": "<p>I recommend nesting dictionaries for your conversions. Usually if you have a long chain of <code>elif</code> comparisons to a string or number, you should use a dictionary.</p>\n\n<p>You can store the first unit as the primary key, and then the second value is the key of the second unit. The values then all need to be a number that you can multiply by in order to perform the conversion. So to divide by 1000, instead the value to multiply by is <code>1/1000</code>. You could technically store functions to call in order to evaluate the conversions but just numbers is simpler.</p>\n\n<pre><code>conversions = {\n \"mm\": {\"mm\": 1, \"cm\": 1/10, \"m\": 1/1000, \"km\": 1/1000000},\n \"cm\": {\"mm\": 10, \"cm\": 1, \"m\": 1/100, \"km\": 1/100000},\n \"m\": {\"mm\": 1000, \"cm\": 100, \"m\": 1, \"km\": 1/1000},\n \"km\": {\"mm\": 100000, \"cm\": 10000, \"m\": 1000, \"km\": 1},\n }\n</code></pre>\n\n<p>This makes it easier to see if all of them are implemented, they're kept in neat rows so you can make sure none of the math seems off. Another advantage is that you can automatically generate a list of values to tell the user about.</p>\n\n<pre><code>unit1 = raw_input (\"Which unit would you like to convert from?\\n\"\n \"We support: \" + \", \".join(conversions.keys()))\nunit2 = raw_input (\"Which unit would you like to convert to?\\n\")\n \"We support: \" + \", \".join(conversions[unit1].keys()))\n</code></pre>\n\n<p>Also you could now make sure that the user is typing in a valid key this way.</p>\n\n<pre><code>while True:\n try:\n unit1 = raw_input (\"Which unit would you like to convert from?\\n\"\n \"We support: \"\n \", \".join(conversions.keys())).lower()\n unit2 = raw_input (\"Which unit would you like to convert to?\\m\")\n \"We support: \"\n \", \".join(conversions[unit1].keys())).lower()\n convert = conversions[unit1][unit2]\n except KeyError:\n print (\"That is not a valid key, please try again\")\n</code></pre>\n\n<p><code>conversions[unit1][unit2]</code> is just called in order to test whether the key exists and will raise an error if it doesn't so that the user will be told to enter new keys. I also added <code>.lower()</code> so that if the user inputs <code>CM</code>, <code>Cm</code> or even <code>cM</code> they'll all be converted to <code>cm</code> to match the key.</p>\n\n<p>I recommend wrapping the number input similarly, as it prevents errors later.</p>\n\n<pre><code>while True:\n try:\n num1 = float(raw_input(\"Enter your value: \" ))\n except ValueError:\n print (\"That is not a valid float, please try again.\")\n</code></pre>\n\n<p>Now when it comes to the actual logic, it's really quite simple since both values are already prepared:</p>\n\n<pre><code>ans = num1 * convert\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-19T13:39:24.093", "Id": "185338", "Score": "0", "body": "Using dictionaries is much better than those ifs. Nice answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-09T15:14:38.410", "Id": "395824", "Score": "1", "body": "This is an improvement, but still suffers from the poor scaling of the original: when you add a new unit, you need to update all the existing units as well as adding conversions for the new unit. Converting to the base unit and then to the result unit (or, equivalently, forming a single conversion from the two base-unit conversions) is easier to maintain." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-19T09:56:29.130", "Id": "101353", "ParentId": "101348", "Score": "4" } }
<p>I am new to programming and I am trying to make a simple unit converter in python. I want to convert units within the metric system and metric to imperial and vice-versa. I have started with this code and I found this method is slow and in-efficient, How can I code this more efficiently?</p> <pre><code>import math import time """Unit Converter""" #Welcome and variable setting print ("Welcome to Sam's Unit Converter") cat = raw_input ("Which category would you like to convert? we support length(l) and Weight(w): ") if cat == ("l"): unit1 = raw_input ("Which unit would you like to convert from: ") unit2 = raw_input ("Which unit would you like to convert to: ") num1 = raw_input ("Enter your value: " ) ##Calculations if unit1 == "cm" and unit2 == "m": ans = float(num1)/100 elif unit1 == "mm" and unit2 == "cm": ans = float(num1)/10 elif unit1 == "m" and unit2 == "cm": ans = float(num1)*100 elif unit1 == "cm" and unit2 == "mm": ans = float(num1)*10 elif unit1 == "mm" and unit2 == "m": ans = float(num1)/1000 elif unit1 == "m" and unit2 == "mm": ans = float(num1)*1000 elif unit1 == "km" and unit2 == "m": ans = float(num1)*1000 elif unit1 == "m" and unit2 == "km": ans = float(num1)/1000 elif unit1 == "mm" and unit2 == "km": ans = float(num1)/1000000 </code></pre>
101348
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2015-08-19T09:35:27.683", "Id": "101348", "Score": "4", "Tags": [ "python", "beginner", "unit-conversion" ], "Title": "Unit converter in Python" }
{ "body": "<p>I must respectfully disagree with SuperBiasedMan's recommendation for using a dictionary: while it is already a much better solution than yours, that solution is still making things too complicated.</p>\n\n<p>Instead, I recommend using this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/itKiV.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/itKiV.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Above is a chart for converting units within the metric system. And, thanks to a quick google search, a good way to remember this would be to remember the phrase:</p>\n\n<blockquote>\n <p><strong>K</strong>ing <strong>H</strong>enry <strong>d</strong>oesn't <strong>u</strong>sually <strong>d</strong>rink <strong>c</strong>hocolate <strong>m</strong>ilk.</p>\n</blockquote>\n\n<p>I have bold-ed the first letter of every word to show the correlation between this and the metric system: the first letter of each word directly corresponds to a metric unit \"type\": <strong>k</strong>ilo*, <strong>h</strong>ecto*, etc.</p>\n\n<p>And, again going back to the chart, we can see that there are numbers associated with each unit \"type\" to show how many of the basic unit is in one of that unit type.</p>\n\n<p>For example, there are 10 basic units in a deka*, and 0.01 basic units in a centi*.</p>\n\n<hr>\n\n<p>Now with that information be said, we can easily create a map/different of the different metric \"types\" and the number of basic units on one of this type.</p>\n\n<p>That would look like this:</p>\n\n<pre><code>types = {\n \"k\": 1000,\n \"h\": 100,\n \"da\": 10,\n \"\": 1,\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>To find out what values the user would like, we simply can use the <code>types</code> dictionary and the user input as an indexer to search the dictionary for what values to add.</p>\n\n<p>That would look like this:</p>\n\n<pre><code>values[input]\n</code></pre>\n\n<hr>\n\n<p>Now, for the converting. This process will be very easy since we already have a handy dandy dictionary that holds all the information we need for converting.</p>\n\n<p>All we need to do is divide the amount of basic units of the first type by the amount of basic units for the second type, and then multiply the input number by that result.</p>\n\n<p>Here is what that would look like:</p>\n\n<pre><code>def convert(from_unit_type, to_unit_type, value):\n from_type_units = types[from_unit_type]\n to_type_units = types[to_unit_type]\n\n new_value = value * (from_type_units / to_type_units)\n\n return str(new_value) + to_unit_type\n</code></pre>\n\n<p>Using this method, we were able to completely reduce all conditionals.</p>\n\n<hr>\n\n<p>Putting it all together:</p>\n\n<pre><code>import math\nimport time\n\"\"\"Unit Converter\"\"\"\n#Welcome and variable setting\n\ntypes = {\n \"k\": 1000,\n \"h\": 100,\n \"da\": 10,\n \"\": 1,\n \"d\": 0.1,\n \"c\": 0.01,\n \"m\": 0.001\n}\n\ndef convert(from_unit_type, to_unit_type, value):\n from_type_units = types[from_unit_type]\n to_type_units = types[to_unit_type]\n\n new_value = value * (from_type_units / to_type_units)\n\n return str(new_value) + to_unit_type\n\nprint (\"Welcome to Sam's Unit Converter\")\ncat = raw_input (\"Which category would you like to convert? [g,l,m]\")\n\nunit1 = raw_input (\"Which unit would you like to convert from: \")\nunit2 = raw_input (\"Which unit would you like to convert to: \")\nnum1 = raw_input (\"Enter your value: \" )\n\nprint(convert(unit1, unit2, float(num1)))\n</code></pre>\n\n<p><em>If you have an issues or questions, please let me know in a comment.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-19T14:40:26.567", "Id": "101375", "ParentId": "101348", "Score": "5" } }
<p>I suspect there might be a much more efficient way to accomplish this task. I would appreciate a more clever hint for performance increase. I am also looking for feedback on style and simplification where appropriate. </p> <p>I assume that the set of what counts as English words is a given and that I don't need to do something clever like an actual dictionary or use Google n-grams. That being said, the results could differ depending on the domain and also what is accepted as a word. </p> <p>The original problem set M=3 (3-gram characters), which makes the results not so interesting (ans=<code>[(u'the', 191279), (u'and', 92292), (u'ing', 57323), (u'her', 44627), (u'hat', 38609)]</code>). </p> <pre><code>#gets the top N most common substrings of M characters in English words from nltk import FreqDist from nltk.corpus import gutenberg def get_words(): for fileid in gutenberg.fileids(): for word in gutenberg.words(fileid): yield word def ngrams(N, which_list, strict=False): list_size = len(which_list) stop = list_size if strict: stop -= (N - 1) for i in xrange(0, stop): element = which_list[i] ngram = [element] j = 1 index = j + i while j &lt; N and index &lt; list_size: ngram.append(which_list[index]) j += 1 index += 1 yield ''.join(ngram) def m_most_common_ngram_chars(M=5, N=3): n_grams = [] for word in get_words(): for ngram in ngrams(N, word, strict=True): n_grams.append(ngram) f = FreqDist(n_grams) return f.most_common(M) l = m_most_common_ngram_chars(M=5, N=3) print l </code></pre>
105883
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-28T04:53:05.160", "Id": "105883", "Score": "2", "Tags": [ "python", "performance", "natural-language-processing" ], "Title": "Finding top most N common character grams in English" }
{ "body": "<p>ngrams seems overly verbose for generating substrings. You are just slicing the word. xrange() has a single parameter usage for starting at 0. I also don't like the identifier which_list, I prefer word or root_word in this context.</p>\n\n<p>Also ignoring the parameter strict which is never false in your usage (and I think would be inconsistent with a normal definition of ngram)</p>\n\n<pre><code>def ngrams(N, word):\n for i in xrange(len(word) - N):\n yield word[i:i+N]\n</code></pre>\n\n<p>I don't know if FreqDist needs a list or just an iterable, the following list comprehension can be a generator if that is allowed.</p>\n\n<pre><code>def m_most_common_ngram_chars(M=5, N=3):\n n_grams = [ngram for ngram in ngrams(N, word) for word in get_words()]\n f = FreqDist(n_grams)\n return f.most_common(M)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-28T12:32:14.333", "Id": "105909", "ParentId": "105883", "Score": "1" } }
<p>I suspect there might be a much more efficient way to accomplish this task. I would appreciate a more clever hint for performance increase. I am also looking for feedback on style and simplification where appropriate. </p> <p>I assume that the set of what counts as English words is a given and that I don't need to do something clever like an actual dictionary or use Google n-grams. That being said, the results could differ depending on the domain and also what is accepted as a word. </p> <p>The original problem set M=3 (3-gram characters), which makes the results not so interesting (ans=<code>[(u'the', 191279), (u'and', 92292), (u'ing', 57323), (u'her', 44627), (u'hat', 38609)]</code>). </p> <pre><code>#gets the top N most common substrings of M characters in English words from nltk import FreqDist from nltk.corpus import gutenberg def get_words(): for fileid in gutenberg.fileids(): for word in gutenberg.words(fileid): yield word def ngrams(N, which_list, strict=False): list_size = len(which_list) stop = list_size if strict: stop -= (N - 1) for i in xrange(0, stop): element = which_list[i] ngram = [element] j = 1 index = j + i while j &lt; N and index &lt; list_size: ngram.append(which_list[index]) j += 1 index += 1 yield ''.join(ngram) def m_most_common_ngram_chars(M=5, N=3): n_grams = [] for word in get_words(): for ngram in ngrams(N, word, strict=True): n_grams.append(ngram) f = FreqDist(n_grams) return f.most_common(M) l = m_most_common_ngram_chars(M=5, N=3) print l </code></pre>
105883
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-28T04:53:05.160", "Id": "105883", "Score": "2", "Tags": [ "python", "performance", "natural-language-processing" ], "Title": "Finding top most N common character grams in English" }
{ "body": "<p>Building up on Caleth's answer:</p>\n\n<ul>\n<li><p>Beware that:</p>\n\n<pre><code>def ngrams(N, word):\n for i in xrange(len(word) - N):\n yield word[i:i+N]\n</code></pre>\n\n<p>will not account for the last character:</p>\n\n<pre><code>for g in ngrams(3, \"small\"):\n print(g)\n</code></pre>\n\n<p>will output</p>\n\n<pre><code>sma\nmal\n</code></pre>\n\n<p>If it was the purpose of the <code>strict</code> parameter to allow to include/skip the last character (and be able to print the missing <code>all</code>), you can use it that way:</p>\n\n<pre><code>def ngrams(N, words, strict=True):\n last = int(strict)\n for i in xrange(len(word) - N + last):\n yield word[i:i+N]\n</code></pre>\n\n<p>If, however, you wanted to allow to generate n_grams whose length is lower than <code>N</code>:</p>\n\n<pre><code>def ngrams(N, words, strict=True):\n last = N - 1 if strict else 0\n for i in xrange(len(word) - last):\n yield word[i:i+N]\n</code></pre></li>\n<li><p>As per the <a href=\"http://www.nltk.org/api/nltk.html#nltk.probability.FreqDist\" rel=\"nofollow\">documentation</a>, <code>FreqDist</code> accepts generators in its constructor. It is thus more memory efficient to turn the <code>n_grams</code> list into a generator:</p>\n\n<pre><code>n_grams = (ngram for ngram in ngrams(N, word) for word in get_words())\n</code></pre></li>\n<li><p>Your top comment would be most suited as a docstring for the <code>m_most_common_ngram_chars</code> function. In fact, each function might need its own docstring.</p></li>\n<li><p>Since almost all your code is functions, you may want to put your last two lines into the module check <code>if __name__ == \"__main__\":</code>. It will allow you to run your code from the command line as usual and it will do exactly the same thing; but also to import it and call the function with other parameters without running anything at import time.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>from nltk import FreqDist\nfrom nltk.corpus import gutenberg\n\n\ndef get_words():\n \"\"\"generate english words from the whole gutemberg corpus\"\"\"\n for fileid in gutenberg.fileids():\n for word in gutenberg.words(fileid):\n yield word\n\ndef ngrams(N, word, strict=True):\n \"\"\"generate a sequence of N-sized substrings of word. \n if strict is False, also account for P-sized substrings\n at the end of the word where P &lt; N\"\"\"\n\n last = N - 1 if strict else 0\n for i in xrange(len(word) - last):\n yield word[i:i+N]\n\ndef m_most_common_ngram_chars(M=5, N=3):\n \"\"\"gets the top M most common substrings of N characters in English words\"\"\"\n f = FreqDist(ngram for ngram in ngrams(N, word) for word in get_words())\n return f.most_common(M)\n\nif __name__ == \"__main__\":\n # Uses the default values M=5, N=3\n print m_most_common_ngram_chars()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-29T09:28:35.693", "Id": "105990", "ParentId": "105883", "Score": "2" } }
<p>Often I need to perform <em>multiple assignment</em> from a sequence (e.g. from the result of a <a href="https://docs.python.org/2/library/string.html#string.split" rel="noreferrer"><code>split()</code></a>) but with some semantics that, AFAIK, are not available in the language:</p> <ol> <li><p>Assign N first elements and silently ignore the rest (like Perl's <a href="http://docstore.mik.ua/orelly/perl4/lperl/ch03_04.htm" rel="noreferrer">list assignment</a>).</p> <pre><code>&gt;&gt;&gt; a, b = 'foo bar is here'.split() &gt;&gt;&gt; a, b ('foo', 'bar') &gt;&gt;&gt; </code></pre></li> <li><p>Assign the remaning items to the last variable in the variable list:</p> <pre><code>&gt;&gt;&gt; a, b, c = 'foo bar is here'.split() &gt;&gt;&gt; a, b, c ('foo', 'bar', ['is', 'here']) &gt;&gt;&gt; </code></pre></li> <li><p>If the sequence doesn't have enough values, set the variables to a default value (<code>None</code> or any other, again similar to <a href="http://docstore.mik.ua/orelly/perl4/lperl/ch03_04.htm" rel="noreferrer">Perl</a>):</p> <pre><code>&gt;&gt;&gt; a, b, c, d, e = 'foo bar is here'.split() &gt;&gt;&gt; a, b, c, d, e ('foo', 'bar', 'is', 'here', None) &gt;&gt;&gt; </code></pre></li> </ol> <p>I have designed an iterator function to help me with this, but I'm concerned about my solution to this problem from the point of view of pythonic adherence:</p> <ul> <li><p>Usefulness: Using an iterator for this kind of job is the right option, or there is something more appropriate? Or even worse: my need to do this kind of assignment in Python is not favoring other language features?</p></li> <li><p>Clearness: The implementation is solid and clear enough? Or is there some other way to implement this that would be cleaner?</p></li> </ul> <p>In other words, this solution is better discarded or can it be improved?</p> <pre class="lang-py prettyprint-override"><code>from itertools import * def iterassign(iterable, *, count, use_default=False, default=None, tail=False): """Iterattor for multiple assignment. :param iterable: The iterable. :param int count: The maximum count of iterations. :param bool use_default: If set, and iterable ends before max_count, continue iteration using :param:`default`. :param default: Default value to use when :param:`use_default` is set to ``True``. """ it = iter(iterable) for idx, element in enumerate(chain(islice(it, 0, count), repeat(default))): if idx &gt;= count: break yield element else: raise StopIteration() if tail: yield list(it) </code></pre> <p>Usage examples:</p> <pre><code>&gt;&gt;&gt; ret = 'foo bar is here'.split() &gt;&gt;&gt; a, b = iterassign(ret, count=2) &gt;&gt;&gt; a, b ('foo', 'bar') &gt;&gt;&gt; a, b, c = iterassign(ret, count=2, tail=True) &gt;&gt;&gt; a, b, c ('foo', 'bar', ['is', 'here']) &gt;&gt;&gt; a, b, c, d, e = iterassign(ret, count=5, use_default=True) ('foo', 'bar', 'is', 'here', None) &gt;&gt;&gt; </code></pre>
110769
GOOD_ANSWER
{ "AcceptedAnswerId": "110778", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-14T18:18:01.493", "Id": "110769", "Score": "7", "Tags": [ "python", "python-3.x", "functional-programming", "iterator" ], "Title": "Improving multiple assignment using an iterator function" }
{ "body": "<p>I'll look at each of your three examples individually.</p>\n\n<ol>\n<li><p>Ignoring remaining values</p>\n\n<p>In Python 2:</p>\n\n<pre><code>&gt;&gt;&gt; a, b = 'foo bar is here'.split()[:2]\n&gt;&gt;&gt; a, b\n('foo', 'bar')\n</code></pre>\n\n<p>In Python 3 (<code>_</code> used by convention, double underscore, <code>__</code>, is\nalso appropriate):</p>\n\n<pre><code>&gt;&gt;&gt; a, b, *_ = 'foo bar is here'.split()\n&gt;&gt;&gt; a, b\n('foo', 'bar')\n</code></pre>\n\n<p>When ignoring remaining values, using the built-in language features would be the most Pythonic approach. I think they're clear enough that they do not need to be re-invented.</p></li>\n<li><p>Capture remaining values</p>\n\n<p>In Python 2:</p>\n\n<pre><code>&gt;&gt;&gt; split_string = 'foo bar is here'.split()\n&gt;&gt;&gt; a, b, c = split_string[2:] + [split_string[2:]]\n&gt;&gt;&gt; a, b, c\n('is', 'here', ['is', 'here'])\n</code></pre>\n\n<p>In Python 3:</p>\n\n<pre><code>&gt;&gt;&gt; a, b, *c = 'foo bar is here'.split()\n&gt;&gt;&gt; a, b, c\n('is', 'here', ['is', 'here'])\n</code></pre>\n\n<p>In Python 3, the <code>*</code> feature is again more Pythonic than your approach. In Python 2, that approach won't work if you're dealing with a non-indexable type.</p></li>\n<li><p>Fill remaining values with <code>None</code>. Here is <a href=\"https://codereview.stackexchange.com/questions/40272/append-nones-to-list-if-is-too-short\">a somewhat similar question</a>. That question and the Python 2 solution only work for lists.</p>\n\n<p>Python 2:</p>\n\n<pre><code>&gt;&gt;&gt; split_string = 'foo bar is here'.split()\n&gt;&gt;&gt; a, b, c, d, e = split_string + [None] * (5-len(split_string))\n&gt;&gt;&gt; a, b, c, d, e\n('foo', 'bar', 'is', 'here', None)\n</code></pre>\n\n<p>Python 3.5 (this is not very clear in my opinion):</p>\n\n<pre><code>&gt;&gt;&gt; a, b, c, d, e, *_ = *'foo bar is here'.split(), *[None]*5\n&gt;&gt;&gt; a, b, c, d, e\n('foo', 'bar', 'is', 'here', None)\n</code></pre>\n\n<p>There isn't really a built-in language construct for this so this case might warrant re-inventing. However, this kind of <code>None</code>-filling seems rare and may not necessarily be clear to other Python programmers.</p></li>\n</ol>\n\n<hr>\n\n<p><strong>A review of your actual implementation</strong></p>\n\n<p>Don't use <code>import *</code> in Python. In Python we value our namespaces highly because namespaces allow us to see what variables came from what modules.</p>\n\n<pre><code>from itertools import *\n</code></pre>\n\n<p>Do this instead:</p>\n\n<pre><code>from itertools import chain, islice, repeat\n</code></pre>\n\n<p>You didn't use <code>use_default</code> in your code at all. It seems like you could use another <code>islice</code> instead of an <code>enumerate</code> to restructure your code like this:</p>\n\n<pre><code>def iterassign(iterable, *, count, default=None, tail=False):\n it = iter(iterable)\n for x in islice(chain(islice(it, 0, count), repeat(default)), 0, count):\n yield x\n if tail:\n yield list(it)\n</code></pre>\n\n<p>Iterators are the right solution to this problem (assuming we've decided it's one that needs solving).</p>\n\n<p>If we want to rewrite this to only handle <em>case 3</em> (because we've already decided we can just use Python's built-in language features for case 1 and 2, we could rewrite like this:</p>\n\n<pre><code>def fill_remaining(iterable, *, length, default=None):\n \"\"\"Return iterable padded to at least ``length`` long.\"\"\"\n return islice(chain(iterable, repeat(default)), 0, length)\n</code></pre>\n\n<p>Which would work like this:</p>\n\n<pre><code>&gt;&gt;&gt; a, b, c, d, e = fill_remaining(ret, length=5)\n&gt;&gt;&gt; a, b, c, d, e\n('foo', 'bar', 'is', 'here', None)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-14T20:03:25.707", "Id": "110778", "ParentId": "110769", "Score": "9" } }
<p>My code implementing rock, paper and scissors in Python, using dicts to hold choices.</p> <pre><code>import random choices = ['rock', 'paper', 'scissors'] def choice(): player_choice = raw_input('Choose rock, paper or scissors: ') if player_choice.lower() in choices: computer_choice = random.choice(choices) play(player_choice, computer_choice) else: choice() def play(p_choice, c_choice): win_table = {'rock' : {'rock':'It was a Tie', 'paper':'You Lose', 'scissors':'You Win'}, 'paper' : {'rock':'You Win', 'paper':'It was a Tie', 'scissors':'You Lose'}, 'scissors' : {'rock':'You Lose', 'paper':'You Win', 'scissors':'It was a Tie'}} print 'Computer chose', c_choice print win_table[p_choice][c_choice] new = raw_input('Play again ? (Y/N): ') if new.lower() == 'y': choice() else: print 'Have a nice day !' choice() </code></pre> <p><code>win_table</code> dictionary names are player choices and dictionary keys are computer choices, seems more efficient to me. I haven't run any memory usage tests, though.</p>
111684
GOOD_ANSWER
{ "AcceptedAnswerId": "111724", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T10:03:02.270", "Id": "111684", "Score": "6", "Tags": [ "python", "python-2.x", "rock-paper-scissors" ], "Title": "Python rock paper scissors" }
{ "body": "<p><strong>Single Responsibility Principle</strong></p>\n\n<p><code>choice()</code> should do one thing: get the player's choice. It does three things: gets the player's choice, picks a choice for the computer, and then plays. </p>\n\n<p>If we just drop the other two, we'd get down to:</p>\n\n<pre><code>def choice():\n player_choice = raw_input('Choose rock, paper or scissors: ')\n if player_choice.lower() in choices:\n return player_choice\n else:\n return choice()\n</code></pre>\n\n<p>However, making this recursive isn't great. We could just run out of stack space. There's no advantage here. Let's just loop until done:</p>\n\n<pre><code>def choice():\n while True:\n player_choice = raw_input('Choose rock, paper or scissors: ')\n if player_choice.lower() in choices:\n return player_choice\n</code></pre>\n\n<p>It would be better to flip the namings here too, and call the function <code>player_choice</code> and the variable <code>choice</code>. </p>\n\n<p>Similarly, <code>play()</code> does too many things. Ideally, you'd want to structure your main like:</p>\n\n<pre><code>while True:\n player = player_choice() ## JUST grab the player's choice\n cpu = computer_choice() ## JUST grab the CPU's choice\n show_results(player, cpu) ## JUST print the outcome\n\n new = raw_input('Play again? (Y/N): ')\n if new.lower() != 'y':\n print 'Have a nice day!'\n break\n</code></pre>\n\n<p><strong>Determining Success</strong></p>\n\n<p>Right now, your <code>win_table</code> is explicitly listing all 9 cases. That's super repetitive. First of all, the message is the same regardless of which win case we're in, so you could simplify the <code>win_table</code> to actually be a table of wins:</p>\n\n<pre><code>win_table = {'rock': ['scissors'],\n 'scissors': ['paper'],\n 'paper': ['rock']}\n\nif cpu in win_table[player]:\n # You win!\n</code></pre>\n\n<p>Or we can do this programmaticly. Rock, Paper, Scissors is a wheel. Rock > Paper > Scissors > Rock. We win if the opponent's choice is the next one along in the wheel. </p>\n\n<p>That is:</p>\n\n<pre><code>if player == cpu:\n # Tie\nelse:\n idx = choices.index(player)\n if cpu == choices[(idx + 1) % len(choices)]:\n # We win\n else:\n # We lose\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-25T08:53:31.753", "Id": "206252", "Score": "0", "body": "Good points, thanks. I'll definitely be looking into it more carefully." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-07T13:54:38.713", "Id": "227488", "Score": "0", "body": "+1 for the mathematical insight. For more weapons: https://en.wikipedia.org/wiki/Rock-paper-scissors#Additional_weapons" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T18:07:23.253", "Id": "111724", "ParentId": "111684", "Score": "4" } }
<p>My code implementing rock, paper and scissors in Python, using dicts to hold choices.</p> <pre><code>import random choices = ['rock', 'paper', 'scissors'] def choice(): player_choice = raw_input('Choose rock, paper or scissors: ') if player_choice.lower() in choices: computer_choice = random.choice(choices) play(player_choice, computer_choice) else: choice() def play(p_choice, c_choice): win_table = {'rock' : {'rock':'It was a Tie', 'paper':'You Lose', 'scissors':'You Win'}, 'paper' : {'rock':'You Win', 'paper':'It was a Tie', 'scissors':'You Lose'}, 'scissors' : {'rock':'You Lose', 'paper':'You Win', 'scissors':'It was a Tie'}} print 'Computer chose', c_choice print win_table[p_choice][c_choice] new = raw_input('Play again ? (Y/N): ') if new.lower() == 'y': choice() else: print 'Have a nice day !' choice() </code></pre> <p><code>win_table</code> dictionary names are player choices and dictionary keys are computer choices, seems more efficient to me. I haven't run any memory usage tests, though.</p>
111684
GOOD_ANSWER
{ "AcceptedAnswerId": "111724", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T10:03:02.270", "Id": "111684", "Score": "6", "Tags": [ "python", "python-2.x", "rock-paper-scissors" ], "Title": "Python rock paper scissors" }
{ "body": "<p>The biggest problem with this code is that you are using functions as glorified GOTO labels, when <code>choice()</code> is called from within <code>choice</code>, when <code>choice()</code> is called from <code>play</code>, and when <code>choice()</code> is called initially. If you hit <kbd>Ctrl</kbd><kbd>C</kbd> after a few rounds, you'll see that the call stack is inappropriately deep. The remedy is to use functions, return values, and loops properly.</p>\n\n<p>The other change I would suggest is removing the redundancy between the <code>choices</code> list and the <code>win_table</code>.</p>\n\n<pre><code>import random\n\nMOVES = {\n 'rock': {'rock':'It was a Tie', 'paper':'You Lose', 'scissors':'You Win'},\n 'paper': {'rock':'You Win', 'paper':'It was a Tie', 'scissors':'You Lose'},\n 'scissors': {'rock':'You Lose', 'paper':'You Win', 'scissors':'It was a Tie'},\n}\n\ndef choices():\n \"\"\"Produce a tuple of the player's choice and the computer's choice.\"\"\"\n while True:\n player_choice = raw_input('Choose rock, paper or scissors: ')\n if player_choice.lower() in MOVES:\n computer_choice = random.choice(MOVES.keys())\n return player_choice, computer_choice\n\ndef reveal(p_choice, c_choice):\n \"\"\"Print both players' choices and the result of the game.\"\"\"\n print 'Computer chose', c_choice\n print MOVES[p_choice][c_choice]\n\ndef play():\n \"\"\"Play a round of rock-paper-scissors, then repeat if desired.\"\"\"\n while True:\n reveal(*choices())\n if raw_input('Play again? (Y/N): ').lower() != 'y':\n break\n print 'Have a nice day!'\n\nplay()\n</code></pre>\n\n<p>There isn't much benefit to having <code>choices()</code> produce both the player's choice and the computer's choice, though. You should break that up into two functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-24T18:13:44.550", "Id": "111725", "ParentId": "111684", "Score": "5" } }
<p>This is the "<a href="https://www.codeeval.com/browse/205/" rel="nofollow noreferrer">Clean up the words</a>" challenge from CodeEval:</p> <blockquote> <h3>Challenge</h3> <p>Given a list of words mixed with extra symbols. Write a program that will clean up the words from extra numbers and symbols.</p> <h3>Specifications</h3> <ol> <li>The first argument is a path to a file. </li> <li>Each line includes a test case.</li> <li>Each test case is a list of words.</li> <li>Letters are both lowercase and uppercase, and mixed with extra symbols.</li> <li>Print the words separated by spaces in lowercase letters.</li> </ol> <h3>Constraints</h3> <ol> <li>The length of a test case together with extra symbols can be in a range from 10 to 100 symbols.</li> <li>The number of test cases is 40.</li> </ol> <p><strong>Input Sample</strong></p> <pre><code>(--9Hello----World...--) Can 0$9 ---you~ 13What213are;11you-123+138doing7 </code></pre> <p><strong>Output Sample</strong></p> <pre><code>hello world can you what are you doing </code></pre> </blockquote> <p>In a <a href="https://codereview.stackexchange.com/questions/131730/no-more-filthy-words?noredirect=1#comment245828_131730">previous question</a> someone joked the program would be much shorter / simpler in Python. I accepted this as a challenge and excuse to practice Python.</p> <p><strong>Solution</strong>:</p> <pre><code>import sys import re def sanitized(line): sanitized_line = re.sub("[^a-zA-Z]+", " ", line) return sanitized_line.lower().strip() def main(file): with open(file, 'r') as input_file: for line in input_file: print(sanitized(line)) if __name__ == "__main__": try: file = sys.argv[1] main(file) except: print("No argument provided.") </code></pre> <p>It's so succinct I'm unsure there's enough for a review, but this site surprised me in the past.</p>
131804
GOOD_ANSWER
{ "AcceptedAnswerId": "131823", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-12T19:40:29.990", "Id": "131804", "Score": "8", "Tags": [ "python", "beginner", "strings", "programming-challenge", "error-handling" ], "Title": "Snakes and Letters" }
{ "body": "<p>The code is pretty clear and clean. I will have to do some nit-picking, but here goes an attempt:</p>\n\n<ul>\n<li><p><code>try</code> - <code>except</code> without the actual exception(s). Here, you print an error when the exception raised is an <code>IndexError</code> (to <code>sys.argv</code>), but consider that you get the same error message if the file can't be properly opened (or is simply non-existent).</p>\n\n<p>Change it to <code>except IndexError</code>, and let any <code>IO/OSError</code> just bubble up, since the corresponding error message is often clear enough (e.g., 'Is a directory', 'File does not exist', etc).</p></li>\n<li><p>You're printing the error message to stdout. You could consider exiting using <code>sys.exit(\"No argument provided.\")</code>, which will exit with an exit code of 1, and print the message to stderr. Or raise an equivalent exception to the one you're catching.</p></li>\n<li><p>'r'ead mode is the default opening mode. While perhaps clearer with the extra argument, <code>with open(file) as ...</code> is more standard.</p></li>\n<li><p>In case of Python 2: don't use <code>file</code> as a variable name, since it shadows the built-in <code>file</code> function. Use e.g. <code>filename</code> instead.</p></li>\n</ul>\n\n<p>Nits:</p>\n\n<ul>\n<li><p>Do you want it to be Python 3 only? Otherwise, include a <code>from __future__ import print_function</code> at the top. <code>print</code> will still work as it is now in Python 2, but once you use more arguments, you're printing a tuple in Python 2, instead of a series of concatenated <code>str</code>-ified elements. (Thanks to JoeWallis in the comments for pointing out the mistake that I was thinking \"tuple\"-wise where it was just a parenthesized string.)</p></li>\n<li><p>doc-strings to the program and functions, if you want to go all-out. (A linter would complain about that, even if it's pretty unnecessary here, and not to the point of the exercise.)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-13T13:22:04.377", "Id": "245971", "Score": "0", "body": "Related to your `try...except` remarks, one should almost never use bare `except:` as per [PEP8](https://www.python.org/dev/peps/pep-0008/#id48): *A bare `except:` clause will catch `SystemExit` and `KeyboardInterrupt` exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use `except Exception:` (bare `except` is equivalent to `except BaseException:`).* It's not a problem here, but one should make it a habit not use bare `except:`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-14T04:24:52.670", "Id": "246111", "Score": "0", "body": "@VedranŠego I state it less general (more specific about catching the proper `IndexError`, since that relates to the error message), but aren't we saying the same thing; or do I miss something? Or is your comment for the question, not my answer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-14T09:37:25.010", "Id": "246172", "Score": "0", "body": "@Evert I was in doubt whether to put it under the question or here. I opted here, as an additional comment to what you wrote, aimed for the OP." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-13T01:45:22.267", "Id": "131823", "ParentId": "131804", "Score": "7" } }
<p>I am working through Automate the Boring Stuff. How can I make this code cleaner/better?</p> <pre><code>#madlibs.py : ABS Chapter 8 Project #Make mad libs using madlibtemplate.txt file that will prompt user for parts of speech #Will return new file with replacements called madlib.txt import re, os #Create template.txt file if doesn't exist print("Let's play MadLibs! \n Note: Your current working directory is ", os.getcwd()) if os.path.exists('madlibtemplate.txt') == False: print("No template file found. Using default 'madlibtemplate.txt'") template = open('madlibtemplate.txt', 'w+') template.write("""The ADJECTIVE girl walked to the NOUN and then VERB. A nearby NOUN was upset by this.""") else: print("Using your 'madlibtemplate.txt' file:") template = open('madlibtemplate.txt', 'r') #Extract text from template file &amp; turn into list of words template.seek(0) #reset pointer to beginning of file text = (template.read()).lower() #make lowercase to match parts of speech wordregex = re.compile(r'\w+|\s|\S') words = re.findall(wordregex, text) #Find and replace parts of speech for i, word in enumerate(words): for part_of_speech in ['adjective', 'noun', 'adverb', 'verb', 'interjection']: if word == part_of_speech: print('Enter a(n) %s ' % part_of_speech) words[i] = input() madlib_text_unformatted = ''.join(words) #Capitalize first letter in each sentence (Function found on stackoverflow) def sentence_case(text): # Split into sentences. Therefore, find all text that ends # with punctuation followed by white space or end of string. sentences = re.findall('[^.!?]+[.!?](?:\s|\Z)', text) # Capitalize the first letter of each sentence sentences = [x[0].upper() + x[1:] for x in sentences] # Combine sentences return ''.join(sentences) madlib_text = sentence_case(madlib_text_unformatted) #Print result and save to a new file print('Here we go... \n') print(madlib_text) madlib = open('madlib.txt', 'w') madlib.write(madlib_text) madlib.close() template.close() print("\n This has been saved to file 'madlib.txt'") </code></pre>
157698
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-14T06:24:40.937", "Id": "157698", "Score": "10", "Tags": [ "python", "beginner", "regex" ], "Title": "Beginner code for MadLibs game" }
{ "body": "<ul>\n<li>You could use a bit less comments, most of the code is self-explnatory</li>\n<li>You could also use a bit more split of the code into functions, e.g. a function to create a default file</li>\n<li>This is a full script, so it's nice to have the <code>if __name__ == \"__main__\":</code> condition to call the main function</li>\n<li>If you use the <code>\"\"\"</code> to have a multi-line string, whatever you put will be there, including newlines and tabs. You probably want to split the string by using <code>\"</code> on separate lines (see later).</li>\n<li>Also, if you concatenate that way, you're losing the <code>\\n</code>, it's better to use <code>format</code></li>\n</ul>\n\n<p>Revised code:</p>\n\n<pre><code>#madlibs.py : ABS Chapter 8 Project\n#Make mad libs using madlibtemplate.txt file that will prompt user for parts of speech\n#Will return new file with replacements called madlib.txt\n\nimport re, os\n\ndef generate_default_template():\n with open('madlibtemplate.txt', 'w+') as template:\n template.write(\"The ADJECTIVE girl walked to the NOUN and then VERB. \"\n \"A nearby NOUN was upset by this.\")\n\ndef capitalize_sentences(text):\n sentences = re.findall('[^.!?]+[.!?](?:\\s|\\Z)', text)\n capitalized_sentences = [sentence.capitalize() for sentence in sentences]\n return ''.join(capitalized_sentences)\n\n\ndef main():\n print(\"Let's play MadLibs!\\nNote: Your current working directory is {0}\".format(os.getcwd()))\n if not os.path.exists('madlibtemplate.txt'):\n print(\"No template file found. Using default 'madlibtemplate.txt'\")\n generate_default_template()\n else:\n print(\"Using your 'madlibtemplate.txt' file:\")\n\n with open('madlibtemplate.txt', 'r') as template:\n template.seek(0)\n text = (template.read()).lower()\n\n wordregex = re.compile(r'\\w+|\\s|\\S')\n words = re.findall(wordregex, text)\n\n for i, word in enumerate(words):\n if word in {'adjective', 'noun', 'adverb', 'verb', 'interjection'}:\n print('Enter a(n) %s ' % word)\n words[i] = input()\n\n madlib_text_unformatted = ''.join(words)\n madlib_text = capitalize_sentences(madlib_text_unformatted)\n\n print('Here we go... \\n')\n print(madlib_text)\n\n with open('madlib.txt', 'w') as madlib:\n madlib.write(madlib_text)\n\n print(\"\\nThis has been saved to file 'madlib.txt'\")\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<ul>\n<li>If you want to capitalize a word, there's the... well, <code>capitalize</code> function for that.</li>\n<li>When opening files it's nice to use the <code>with</code> keyword, so they'll be closed automatically.</li>\n<li>You don't need to do a loop when checking the parts of speech, just use the <code>in</code> operator.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-14T09:50:20.833", "Id": "157708", "ParentId": "157698", "Score": "4" } }
<p>I need to calculate a Bayesian likelihood in its negative logarithmic form:</p> <p>$$-\ln L = N\ln M -\sum\limits_{i=1}^{N} \ln\left\{P_i \sum\limits_{j=1}^M \frac{\exp\left[ -\frac{1}{2}\left(\sum_{k=1}^D \frac{(f_{ik}-g_{jk})^2}{\sigma_{ik}^2 + \rho_{jk}^2}\right) \right]}{\prod_{k=1}^D \sqrt{\sigma_{ik}^2 + \rho_{jk}^2}} \right\}$$</p> <p>where these $$P_i\;\;;\;\; f_{ik} \;\;;\;\; \sigma_{ik}^2\;\;;\;\; g_{jk} \;\;;\;\; \rho_{jk}^2$$ are all known floats. This is my code:</p> <pre><code>import numpy as np # Define random data with correct shapes. N, M = np.random.randint(10, 1000), np.random.randint(10, 1000) D = np.random.randint(2, 5) f_N, g_M = np.random.rand(N, D, 2), np.random.rand(M, D, 2) P_i = np.random.uniform(0., 1., N) # N summatory. # Store here each 'i' element from the M summatory. sum_Mi = [] for f_i in f_N: # M summatory. sum_M_j = 0. for g_j in g_M: # Obtain ijk element inside the M summatory D_sum, sigma_ijk = 0., 1. for k, f_ik in enumerate(f_i): # Where: f_ik[0] = \f_{ik} ; g_j[k][0] = \g_{jk} # and: f_ik[1] = \sigma_{ik}^2 ; g_j[k][1] = \rho_{jk}^2 D_sum += np.square(f_ik[0] - g_j[k][0]) / (f_ik[1] + g_j[k][1]) sigma_ijk = sigma_ijk * (f_ik[1] + g_j[k][1]) sum_M_j += np.exp(-0.5 * D_sum) / np.sqrt(sigma_ijk) sum_Mi.append(sum_M_j) sum_Mi_Pi = P_i * sum_Mi # Remove 0. elements before applying the logarithm below. sum_N = sum_Mi_Pi[sum_Mi_Pi != 0.] # Final negative logarithmic likelihood lik = len(f_N) * np.log(len(g_M)) - sum(np.log(sum_N)) print(lik) </code></pre> <p>I'm after an optimization done at the code level, ie: not using multi-threading.</p> <p>I've tried <code>numpy</code> broadcasting on the inner loop</p> <pre><code># Obtain ijk element inside the M summatory D_sum = sum(np.square((f_i[:, 0] - g_j[:, 0])) / (f_i[:, 1] + g_j[:, 1])) sigma_ijk = np.prod(f_i[:, 1] + g_j[:, 1]) </code></pre> <p>but that actually <em>takes a longer time to complete</em> than using the <code>for</code> loop!</p> <p>I also tried using the <a href="https://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.misc.logsumexp.html" rel="nofollow noreferrer">logsumexp</a> function from <code>scipy</code> combined with the broadcasted arrays:</p> <pre><code># Store here each 'i' element from the M summatory. sum_N = 0. # N summatory. for f_i in f_N: # M summatory. A, B = [], [] for g_j in g_M: # Obtain ijk element inside the M summatory A.append(sum( np.square((f_i[:, 0] - g_j[:, 0])) / (f_i[:, 1] + g_j[:, 1]))) B.append(np.prod(f_i[:, 1] + g_j[:, 1])) sum_N += logsumexp(-.5 * np.array(A), b=1. / np.sqrt(B)) # Final negative logarithmic likelihood lik = len(f_N) * np.log(len(g_M)) - sum(np.log(P_i[P_i != 0.])) - sum_N print(lik) </code></pre> <p>This resulted in a marginal improvement over just using broadcasting, but still slower than the original code.</p>
158049
GOOD_ANSWER
{ "AcceptedAnswerId": "158081", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-17T15:27:43.733", "Id": "158049", "Score": "5", "Tags": [ "python", "performance", "numpy" ], "Title": "Increase performance of Bayesian likelihood equation" }
{ "body": "<p>This is much faster. I added the <code>seed</code> to better compare results across runs.</p>\n\n<pre><code>import numpy as np\n\n# Define random data with correct shapes.\nnp.random.seed(0)\nN, M = np.random.randint(10, 1000), np.random.randint(10, 1000)\nD = np.random.randint(2, 5)\nf_N, g_M = np.random.rand(N, D, 2), np.random.rand(M, D, 2)\nP_i = np.random.uniform(0., 1., N)\n\n# replace loops with broadcasted array operation, followed by sums \nfgsum = f_N[:,None,:,1] + g_M[None,:,:,1]\nfgdif = f_N[:,None,:,0] - g_M[None,:,:,0]\nprint(fgsum.shape) # e.g. (694, 569, 3)\n\nDsum = (fgdif**2 / fgsum).sum(axis=-1)\nsigma_ijk = np.prod(fgsum, axis=-1)\nsum_M_j = np.exp(-0.5 * Dsum) / np.sqrt(sigma_ijk)\nsum_Mi = np.sum(sum_M_j, axis=-1)\n\n# as before\nsum_Mi_Pi = P_i * sum_Mi\n# Remove 0. elements before applying the logarithm below.\nsum_N = sum_Mi_Pi[sum_Mi_Pi != 0.]\n\n# Final negative logarithmic likelihood\nlik = len(f_N) * np.log(len(g_M)) - sum(np.log(sum_N))\nprint(lik)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-17T21:54:01.800", "Id": "299208", "Score": "0", "body": "Excellent! This code is between 80-100 times faster in my machine, thank you very much hpaulj!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-18T09:59:22.053", "Id": "299245", "Score": "1", "body": "You can get another few percent faster by replacing `sum(np.log(sum_N))` with `np.log(sum_N).sum()` or `np.sum(np.log(sum_N))`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-18T16:41:21.683", "Id": "299285", "Score": "1", "body": "okay ... nice that this is faster, but ... WHY???" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-18T16:48:09.313", "Id": "299288", "Score": "0", "body": "Because it replaces Python loops with compiled `numpy` code. Sorry. I normally answer on SO where this kind of `numpy` 'vectorization' is an everyday question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-18T16:50:18.660", "Id": "299289", "Score": "1", "body": "More about increasing performance with `numpy`: http://codereview.stackexchange.com/questions/17702/python-numpy-running-15x-slower-than-matlab-am-i-using-numpy-effeciently" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-18T17:05:22.380", "Id": "299296", "Score": "0", "body": "Here's a [nice tutorial](http://eli.thegreenplace.net/2015/broadcasting-arrays-in-numpy/) on `numpy`'s broadcasting." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-17T21:45:15.790", "Id": "158081", "ParentId": "158049", "Score": "1" } }
<p>Here is the problem I've been trying to tackle:</p> <blockquote> <p>Design a thread-safe image caching server that can keep in memory only the ten most recently used images.</p> </blockquote> <p>I chose to implement an <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29" rel="nofollow noreferrer">LRU cache</a> to solve this as follows:</p> <pre><code>''' This module defines an LRUCache. Constraints: 1. May only hold upto ten items at a time. 2. Must be able to synchronise multiple requests. 3. Must be able to update its cache. ''' import random import threading class LRUCache(object): def __init__(self, cacheSize=10): # this variables maps image names to file locations self.Cache = {} # this variables maps image names to timestamp of last request # filed for them. Is volatile - requires local clock to never change, # or that there is a separate clock service that guarantees global # consistency. self.RequestTimestamps = {} self.CacheSize = cacheSize def insert(self, imageName, imageLocation): ''' Insert a new image into our cache. If inserting would exceed our cache size, then we shall make room for it by removing the least recently used. ''' with threading.Lock(): if len(self.Cache) == self.CacheSize: self.removeLeastRecentlyUsed() self.Cache[imageName] = imageLocation self.RequestTimestamps[imageName] = time.time() def get(self, imageName): ''' Retrieve an image from our cache, keeping note of the time we last retrieved it. ''' with threading.Lock(): if imageName in self.Cache: self.RequestTimestamps[imageName] = time.time() return self.Cache[imageName] else: raise KeyError("Not found!") def removeLeastRecentlyUsed(self): ''' Should only be called in a threadsafe context. ''' if self.RequestTimestamps: # scan through and find the least recently used key by finding # the lowest timestamp among all the keys. leastRecentlyUsedKey = min(self.RequestTimestamps, key=lambda imageName: self.RequestTimestaps[imageName]) # now that the least recently used key has been found, # remove it from the cache and from our list of request timestamps. self.Cache.pop(leastRecentlyUsedKey, None) self.RequestTimestamps.pop(leastRecentlyUsedKey, None) return # only called in the event requestTimestamps does not exist - randomly # pick a key to erase. randomChoice = random.choice(self.Cache.keys()) self.Cache.pop(randomChoice, None) </code></pre> <p>Questions:</p> <ol> <li><p>Is this <em>actually</em> threadsafe? </p> <p>I'm used to implementing locks on single resources, but not class methods - would multiple threads, one accessing <code>insert</code> and the other doing a <code>get</code> be forced to synchronised as well? </p> <p>Or is my strategy of creating different locks in each method only able to prevent concurrent individual <code>insert</code> requests? </p> <p>Ignore the GIL.</p></li> <li><p>What would be a good strategy to test this code? </p> <p>I have thought of the obvious strategy:</p> <p>a) Insert ten items, make nine requests, attempt to insert a tenth and check if the item that was removed was the tenth.</p> <p>but I am not sure if this is the only way or if there is a better way to implement it. </p></li> </ol>
160277
GOOD_ANSWER
{ "AcceptedAnswerId": "175004", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-09T22:05:43.430", "Id": "160277", "Score": "8", "Tags": [ "python", "thread-safety", "cache" ], "Title": "Implementing a thread-safe LRUCache" }
{ "body": "<h2>Thread-safeness</h2>\n\n<p>As others have pointed out in the comments, your implementation is not thread-safe. <code>threading.Lock()</code> returns a new lock each time it is called, so each thread will be locking a different lock. Instead, you should have a single lock as an instance member object:</p>\n\n<pre><code>def __init__(self, cacheSize=10):\n\n # this variables maps image names to file locations\n self.Cache = {}\n\n # this variables maps image names to timestamp of last request\n # filed for them. Is volatile - requires local clock to never change,\n # or that there is a separate clock service that guarantees global\n # consistency. \n self.RequestTimestamps = {}\n\n self.CacheSize = cacheSize\n\n self.lock = threading.Lock()\n</code></pre>\n\n<p>Then, you use it like so:</p>\n\n<pre><code>def insert(self, imageName, imageLocation):\n\n '''\n Insert a new image into our cache. If inserting would exceed our cache size,\n then we shall make room for it by removing the least recently used. \n '''\n\n with self.lock:\n\n if len(self.Cache) == self.CacheSize:\n self.removeLeastRecentlyUsed()\n\n self.Cache[imageName] = imageLocation\n self.RequestTimestamps[imageName] = time.time()\n</code></pre>\n\n<p>Additionally, using <code>time.time()</code> for access orders can cause inconsistent results: it's not guaranteed to have good precision, and is dependent on the system clock steadily increasing. If the system clock is manually set back, you lose your consistent ordering. Instead, a safer way would be to use an <a href=\"https://docs.python.org/2/library/collections.html#collections.OrderedDict\" rel=\"noreferrer\"><code>OrderedDict</code></a>, where you remove and re-insert items as they are accessed, and use <code>OrderedDict.popitem(False)</code> to remove the least-recently inserted item.</p>\n\n<h2>PEP8 compliance</h2>\n\n<p>Your variables and methods are written with a mixture of <code>PascalCase</code> (<code>Cache.RequestTimestamps</code>), which is typically only used for class names, and <code>camelCase</code> (<code>Cache.removeLeastRecentlyUsed</code>, <code>leastRecentlyUsedKey</code>), which is typically not used in Python. You should use <code>snake_case</code> instead for variables and methods, and use it consistently:</p>\n\n<pre><code>def __init__(self, cache_size=10):\n\n # this variables maps image names to file locations\n self.cache = {}\n\n # this variables maps image names to timestamp of last request\n # filed for them. Is volatile - requires local clock to never change,\n # or that there is a separate clock service that guarantees global\n # consistency. \n self.request_timestamps = {}\n\n self.cache_size = cache_size\n</code></pre>\n\n\n\n<pre><code>def remove_least_recently_used(self):\n\n '''\n Should only be called in a threadsafe context.\n '''\n\n if self.request_timestamps:\n\n # scan through and find the least recently used key by finding\n # the lowest timestamp among all the keys.\n\n least_recently_used_key = min(self.request_timestamps, key=lambda image_name: self.request_timestamps[image_name])\n\n # now that the least recently used key has been found, \n # remove it from the cache and from our list of request timestamps.\n\n self.cache.pop(least_recently_used_key, None)\n self.request_timestamps.pop(least_recently_used_key, None)\n return\n\n # only called in the event requestTimestamps does not exist - randomly \n # pick a key to erase.\n\n random_choice = random.choice(self.cache.keys())\n self.cache.pop(random_choice, None)\n</code></pre>\n\n<p>And while we're looking at this method...</p>\n\n<h2>Single exit only</h2>\n\n<p>While there are many arguments against the single-exit-only style, none of them apply here. There's no good reason to have the <code>return</code> inside of the <code>if</code> in <code>Cache.removeLastRecentlyUsed</code>. Instead, wrap the rest in an <code>else</code>:</p>\n\n<pre><code>if self.request_timestamps:\n\n # scan through and find the least recently used key by finding\n # the lowest timestamp among all the keys.\n\n least_recently_used_key = min(self.request_timestamps, key=lambda image_name: self.request_timestamps[image_name])\n\n # now that the least recently used key has been found, \n # remove it from the cache and from our list of request timestamps.\n\n self.cache.pop(least_recently_used_key, None)\n self.request_timestamps.pop(least_recently_used_key, None)\nelse:\n\n # only called in the event requestTimestamps does not exist - randomly \n # pick a key to erase.\n\n random_choice = random.choice(self.cache.keys())\n self.cache.pop(random_choice, None)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T01:26:28.427", "Id": "431122", "Score": "0", "body": "What's the advantage of having a single exit point?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T05:03:56.477", "Id": "431129", "Score": "0", "body": "@HubertGrzeskowiak In this case, structuring the function as an `if`-`else` block makes it clear that there are two cases that define the behavior of the function. It is explicit, and is easier to understand as a reader. Using `return` to break out of a function early without actually returning anything is a code smell, and understanding that there are two branches is made more difficult because it's expressed implicitly as a side effect of the early return. The Zen of Python teaches us that explicit is better than implicit, so the if-else version is preferable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T05:51:54.920", "Id": "431139", "Score": "0", "body": "I agree that it makes the logic most obvious in this particular case because both code paths contain some logic for \"the good path\" (as opposed to error conditions). However, maybe we should clarify the `many arguments against the single-exit-only style` you mentioned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T05:23:17.023", "Id": "431399", "Score": "0", "body": "@HubertGrzeskowiak The common argument against it is that avoiding it can often make code harder to read. However, that's not the case here - following the single-exit-only style makes it easier to read." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-07T02:48:16.900", "Id": "175004", "ParentId": "160277", "Score": "5" } }
<p>Now that <a href="https://codereview.stackexchange.com/q/160958/27623">I have generated training data</a>, I need to classify each example with a label to train a TensorFlow neural net (first <a href="https://github.com/tensorflow/models/blob/master/inception/inception/data/build_image_data.py" rel="noreferrer">building a suitable dataset</a>). To streamline the process, I wrote this little Python script to help me. Any suggestions for improvement?</p> <hr> <p><strong>classify.py:</strong></p> <pre><code># Builtin modules import glob import sys import os import shutil import wave import time import re from threading import Thread # 3rd party modules import scipy.io.wavfile import pyaudio DATA_DIR = 'raw_data' LABELED_DIR = 'labeled_data' answer = None def classify_files(): global answer # instantiate PyAudio p = pyaudio.PyAudio() for filename in glob.glob('{}/*.wav'.format(DATA_DIR)): # define stream chunk chunk = 1024 #open a wav format music wf = wave.open(filename, 'rb') #open stream stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) #read data data = wf.readframes(chunk) #play stream while answer is None: stream.write(data) data = wf.readframes(chunk) if data == b'': # if file is over then rewind wf.rewind() time.sleep(1) data = wf.readframes(chunk) # don't know how to classify, skip sample if answer == '.': answer = None continue # sort spectogram based on input spec_filename = 'spec{}.jpeg'.format(str(re.findall(r'\d+', filename)[0])) os.makedirs('{}/{}'.format(LABELED_DIR, answer), exist_ok=True) shutil.copyfile('{}/{}'.format(DATA_DIR, spec_filename), '{}/{}/{}'.format(LABELED_DIR, answer, spec_filename)) # reset answer field answer = None #stop stream stream.stop_stream() stream.close() #close PyAudio p.terminate() if __name__ == '__main__': try: # exclude file from glob os.remove('{}/ALL.wav'.format(DATA_DIR)) num_files = len(glob.glob('{}/*.wav'.format(DATA_DIR))) Thread(target = classify_files).start() for i in range(0, num_files): answer = input("Enter letter of sound heard: ") except KeyboardInterrupt: sys.exit() </code></pre>
161273
GOOD_ANSWER
{ "AcceptedAnswerId": "161595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-20T00:56:40.443", "Id": "161273", "Score": "6", "Tags": [ "python", "multithreading", "sorting", "file", "audio" ], "Title": "Speech Recognition Part 2: Classifying Data" }
{ "body": "<ul>\n<li>Most of your comments aren't that great. Commenting about PEP8 compliance shouldn't be needed, and saying you're instantiating an object before doing it duplicates the amount we have to read for no actual gain.</li>\n<li><p><code>os.path.join</code> is much better at joining file locations by the OSes separator than <code>'{}/{}'.format</code>. Please use it instead.</p>\n\n<p>An alternate to this in Python 3.4+ could be <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a>, as it allows you to extend the path by <a href=\"https://docs.python.org/3/library/pathlib.html#operators\" rel=\"nofollow noreferrer\">using the <code>/</code> operator</a>. I have however not tested that this works with the functions you're using.</p>\n\n<p>Here's an example of using it: (untested)</p>\n\n<pre><code>DATA_DIR = pathlib.PurePath('raw_data')\n\n...\n\nos.remove(DATA_DIR / 'All.wav')\n</code></pre></li>\n<li>You should move <code>chunk</code> out of the for loop, making it a function argument may be a good idea too.</li>\n<li><p>Making a function to infinitely read your <code>wf</code> may ease reading slightly, and giving it a good name such as <code>cycle_wave</code> would allow people to know what it's doing. As it'd work roughly the same way as <code>itertools.cycle</code>. This could be implemented as:</p>\n\n<pre><code>def cycle_wave(wf):\n while True:\n data = wf.readframes(chunk)\n if data == b'':\n wf.rewind()\n time.sleep(1)\n data = wf.readframes(chunk)\n yield data\n</code></pre></li>\n<li><p>For your <code>spec_filename</code> you can use <code>re.match</code> to get a single match, rather than all numbers in the file name. You also don't need to use <code>str</code> on the object as format will do that by default.</p></li>\n<li><p>Rather than removing a file from your directory, to then search the directory, you can instead remove the file from the resulting list from <code>glob.glob</code>. Since it returns a normal list, you can go about this the same way you would otherwise.</p>\n\n<p>One way you can do this, is as followed:</p>\n\n<pre><code>files = glob.glob('D:/*')\ntry:\n files.remove('D:/$RECYCLE.BIN')\nexcept ValueError:\n pass\n</code></pre>\n\n<p>If you have multiple files you want to remove you could instead use sets, and instead use:</p>\n\n<pre><code>files = set(glob.glob('D:/*')) - {'D:/$RECYCLE.BIN'}\n</code></pre></li>\n</ul>\n\n<p>All of this together can get you:</p>\n\n<pre><code>import glob\nimport sys\nimport os\nimport shutil\nimport wave\nimport time\nimport re\nfrom threading import Thread\n\nimport scipy.io.wavfile\nimport pyaudio\n\nDATA_DIR = 'raw_data'\nLABELED_DIR = 'labeled_data'\nanswer = None\n\ndef cycle_wave(wf):\n while True:\n data = wf.readframes(chunk)\n if data == b'':\n wf.rewind()\n time.sleep(1)\n data = wf.readframes(chunk)\n yield data\n\ndef classify_files(chunk=1024):\n global answer\n join = os.path.join\n\n p = pyaudio.PyAudio()\n files = set(glob.glob(join(DATA_DIR, '*.wav'))) - {join(DATA_DIR, 'ALL.wav')}\n for filename in files:\n wf = wave.open(filename, 'rb')\n stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),\n channels=wf.getnchannels(),\n rate=wf.getframerate(),\n output=True)\n\n for data in cycle_wave(wf):\n if answer is not None:\n break\n stream.write(data)\n\n # don't know how to classify, skip sample\n if answer == '.':\n answer = None\n continue\n\n # sort spectogram based on input\n spec_filename = 'spec{}.jpeg'.format(re.match(r'\\d+', filename)[0])\n os.makedirs(join(LABELED_DIR, answer), exist_ok=True)\n shutil.copyfile(\n join(DATA_DIR, spec_filename),\n join(LABELED_DIR, answer, spec_filename)\n )\n\n # reset answer field\n answer = None\n\n #stop stream\n stream.stop_stream()\n stream.close()\n\n #close PyAudio\n p.terminate()\n\nif __name__ == '__main__':\n join = os.path.join\n try:\n # exclude file from glob\n files = set(glob.glob(join(DATA_DIR, '*.wav'))) - {join(DATA_DIR, 'ALL.wav')}\n num_files = len(files)\n Thread(target = classify_files).start()\n for _ in range(0, num_files):\n answer = input(\"Enter letter of sound heard: \")\n except KeyboardInterrupt:\n sys.exit()\n</code></pre>\n\n<hr>\n\n<p>But I've left out proper handling of streams, in most languages, that I've used streams in, it's recommended to <em>always</em> close the steam. In Python it's the same. You can do this normally in two ways:</p>\n\n<ol>\n<li><p>Use <code>with</code>, this hides a lot of the code, so it makes using streams seamless. It also makes people know the lifetime of the stream, and so people won't try to use it after it's been closed.</p>\n\n<p>Here's an example of using it:</p>\n\n<pre><code>with wave.open('&lt;file location&gt;') as wf:\n print(wf.readframes(1024))\n</code></pre></li>\n<li><p>Use a try-finally. You don't need to add an except clause to this, as if it errors you may not want to handle it here, but the finally is to ensure that the stream is closed.</p>\n\n<p>Here's an example of using it:</p>\n\n<pre><code>p = pyaudio.PyAudio()\ntry:\n stream = p.open(...)\n try:\n # do some stuff\n finally:\n stream.stop_stream()\n stream.close()\nfinally:\n p.terminate()\n</code></pre></li>\n</ol>\n\n<p>I'd personally recommend using one of the above in your code. I'd <em>really</em> recommend using <code>with</code> over a try-finally, but <code>pyaudio</code> doesn't support that interface. And so you'd have to add that interface to their code, if you wanted to go that way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-29T15:03:10.780", "Id": "307787", "Score": "0", "body": "Do you have a less destructive way for excluding a file from the glob?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-29T17:03:58.587", "Id": "307801", "Score": "0", "body": "@syb0rg I didn't change how you're using glob" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-30T19:46:18.557", "Id": "307939", "Score": "1", "body": "For some alternatives related to using glob: http://stackoverflow.com/questions/8931099/quicker-to-os-walk-or-glob" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-23T17:45:35.460", "Id": "161595", "ParentId": "161273", "Score": "5" } }
<p>I made a program that solves KenKen Puzzles using graphics.py, and I was just wondering if my code was reasonably Pythonic.</p> <p>neknek.py</p> <pre><code>import options import copy from graphics import * from random import randint from itertools import product class Cell: def __init__(self, x, y): self.options = [1, 2, 3, 4, 5, 6] self.x = x self.y = y self.answer = 0 self.text = Text(Point(x * 100 + 50, y * 100 + 50), str(self.options)) self.text.setSize(10) self.marker = Circle(Point(self.x * 100 + 50, self.y * 100 + 80), 10) self.marker.setFill(color_rgb(255, 0, 0)) def update(self): if len(self.options) == 1 and self.answer == 0: self.answer = self.options[0] self.text.setText(str(self.answer)) self.marker.setFill(color_rgb(0, 255, 0)) elif self.answer &gt; 0: self.text.setText(str(self.answer)) self.marker.setFill(color_rgb(0, 255, 0)) elif self.answer == 0: self.text.setText(str(self.options)) def remove_options(self, options): if len(list(set(self.options) - set(options))) &gt; 0: self.options = list(set(self.options) - set(options)) class Group: def __init__(self, cells, goal): self.cells = cells self.goal = goal self.options = [] def happy(self): raise NotImplementedError def check_bend(self): x = [] y = [] for cell in self.cells: x.append(cell.x) y.append(cell.y) return not (self._bend_helper(x) or self._bend_helper(y)) def _all_options(self): temp = [] for cell in self.cells: if cell.answer &gt; 0: temp.append([cell.answer]) else: temp.append(cell.options) temp = list(product(*temp)) li = [] for x in temp: li.append(list(x)) return li def _bend_helper(self, li): for i in li: if li.count(i) == len(li): return True return False def _check_group_options(self, cell, i): for option in self.options: if i == option[self.cells.index(cell)]: return True return False def _remove_group_options(self): possible = self._all_options() remove = [] for option in self.options: if option not in possible: remove.append(option) for option in remove: self.options.remove(option) def _remove_cell_options(self): for cell in self.cells: remove = [] for option in cell.options: if not self._check_group_options(cell, option): remove.append(option) cell.remove_options(remove) def solve(self): self._remove_group_options() self._remove_cell_options() for cell in self.cells: cell.update() class AddGroup(Group): def __init__(self, cells, goal): super().__init__(cells, goal) if self.check_bend(): try: self.options = copy.deepcopy(options.add_options[len(self.cells)][goal + '*']) except KeyError: self.options = copy.deepcopy(options.add_options[len(self.cells)][goal]) else: self.options = copy.deepcopy(options.add_options[len(self.cells)][goal]) def happy(self): total = 0 for cell in self.cells: total += cell.answer return total == int(self.goal) class SubGroup(Group): def __init__(self, cells, goal): super().__init__(cells, goal) if self.check_bend(): try: self.options = copy.deepcopy(options.sub_options[len(self.cells)][goal + '*']) except KeyError: self.options = copy.deepcopy(options.sub_options[len(self.cells)][goal]) else: self.options = copy.deepcopy(options.sub_options[len(self.cells)][goal]) def happy(self): return max(self.cells[0].answer, self.cells[1].answer) - min(self.cells[0].answer, self.cells[1].answer) == int(self.goal) class MulGroup(Group): def __init__(self, cells, goal): super().__init__(cells, goal) if self.check_bend(): try: self.options = copy.deepcopy(options.mul_options[len(self.cells)][goal + '*']) except KeyError: self.options = copy.deepcopy(options.mul_options[len(self.cells)][goal]) else: self.options = copy.deepcopy(options.mul_options[len(self.cells)][goal]) def happy(self): total = 1 for cell in self.cells: total *= cell.answer return total == int(self.goal) class DivGroup(Group): def __init__(self, cells, goal): super().__init__(cells, goal) if self.check_bend(): try: self.options = copy.deepcopy(options.div_options[len(self.cells)][goal + '*']) except KeyError: self.options = copy.deepcopy(options.div_options[len(self.cells)][goal]) else: self.options = copy.deepcopy(options.div_options[len(self.cells)][goal]) def happy(self): return max(self.cells[0].answer, self.cells[1].answer) / min(self.cells[0].answer, self.cells[1].answer) == int(self.goal) class RowColGroup(Group): def __init__(self, cells): super().__init__(cells, '21') self.options = options.row_col_options def happy(self): total = 0 for cell in self.cells: total += cell.answer return total == int(self.goal) def _remove_used_answers(self): remove = [] for cell in self.cells: if cell.answer != 0: remove.append(cell.answer) for cell in self.cells: cell.remove_options(remove) def _remove_used_options(self): remove = [] used_options = [] for cell in self.cells: if len(cell.options) == used_options.count(cell.options) + 1: for i in cell.options: remove.append(i) else: used_options.append(cell.options) for cell in self.cells: cell.remove_options(remove) def _count_options(self): options = [0, 0, 0, 0, 0, 0, 0] for cell in self.cells: for option in cell.options: options[option] += 1 for i in range(1, 7): if options[i] == 1: for cell in self.cells: if i in cell.options and cell.answer != i: cell.options = [i] def solve(self): self._remove_used_answers() self._remove_used_options() self._count_options() for cell in self.cells: cell.update() class Puzzle: def __init__(self, cells, groups, rows, cols, win): self.width = 100 * 6 self.height = 100 * 6 self.cells = cells self.win = win self.prompt = Text(Point((self.width + 150) / 3, self.height + 25), '') self.prompt.setSize(10) self.prompt.draw(self.win) self.input = Entry(Point(2 * (self.width + 150) / 3, self.height + 25), 5) self.input.setSize(10) self.input.draw(self.win) self.groups = groups self.rows = rows self.cols = cols @classmethod def from_gui(cls): width = 100 * 6 height = 100 * 6 cells = {} win = GraphWin('KenKen', width + 200, height + 50) prompt = Text(Point((width + 150) / 3, height + 25), 'How many groups are there?') prompt.setSize(10) prompt.draw(win) input = Entry(Point(2 * (width + 150) / 3, height + 25), 5) input.setSize(10) input.draw(win) groups = [] rows = [] cols = [] r = Rectangle(Point(width + 10, 20), Point(width + 190, 50)) r.setFill(color_rgb(255, 0, 0)) r.draw(win) t = Text(Point(width + 100, 35), 'Remove') t.setSize(10) t.draw(win) r = Rectangle(Point(width + 10, 60), Point(width + 190, 90)) r.setFill(color_rgb(0, 255, 0)) r.draw(win) t = Text(Point(width + 100, 75), 'Enter') t.setSize(10) t.draw(win) for i in range(6): l = Line(Point((i + 1) * 100, 0), Point((i + 1) * 100, height)) l.setWidth(4) l.draw(win) l = Line(Point(0, (i + 1) * 100), Point(width, (i + 1) * 100)) l.setWidth(4) l.draw(win) for y in range(6): for x in range(6): c = Cell(x, y) cells[x, y] = c c.text.draw(win) win.getMouse() group_num = int(input.getText()) input.setText('') for i in range(group_num): g = randint(0, 255) r = randint(g, 255) b = randint(g, 255) color = color_rgb(r, g, b) prompt.setText("Enter the goal and operator for group {}, then select the cells.".format(i)) group_cells = [] while True: p = win.getMouse() inp = input.getText().split() op = inp[1] goal = inp[0] x, y = p.getX(), p.getY() if y &gt; height or x &gt; width: if op == '+': g = AddGroup(group_cells, goal) elif op == '-': g = SubGroup(group_cells, goal) elif op == '*': g = MulGroup(group_cells, goal) else: g = DivGroup(group_cells, goal) groups.append(g) g.solve() input.setText('') break else: if cells[x // 100, y // 100] in cells: group_cells.remove(cells[x // 100, y // 100]) cells[x // 100, y // 100].marker.undraw() else: group_cells.append(cells[x // 100, y // 100]) cells[x // 100, y // 100].marker.setFill(color) cells[x // 100, y // 100].marker.draw(win) for y in range(6): group_cells = [] for x in range(6): group_cells.append(cells[x, y]) rows.append(RowColGroup(group_cells)) for x in range(6): group_cells = [] for y in range(6): group_cells.append(cells[x, y]) cols.append(RowColGroup(group_cells)) prompt.setText('') input.setText('') puzzle = cls(cells, groups, rows, cols, win) return puzzle def copy(self): win = GraphWin('KenKen', 100 * 6, 100 * 6 + 50) for i in range(6): l = Line(Point((i + 1) * 100, 0), Point((i + 1) * 100, 600)) l.setWidth(4) l.draw(win) l = Line(Point(0, (i + 1) * 100), Point(600, (i + 1) * 100)) l.setWidth(4) l.draw(win) cells = {} for y in range(6): for x in range(6): c = Cell(x, y) c.options = copy.deepcopy(self.cells[x, y].options) c.answer = self.cells[x, y].answer c.marker.draw(win) c.text.draw(win) if c.answer &gt; 0: c.update() cells[x, y] = c groups = [] for group in self.groups: c = [] for cell in group.cells: c.append(cells[cell.x, cell.y]) if type(group) is AddGroup: g = AddGroup(c, group.goal) elif type(group) is SubGroup: g = SubGroup(c, group.goal) elif type(group) is MulGroup: g = MulGroup(c, group.goal) else: g = DivGroup(c, group.goal) g.options = copy.deepcopy(group.options) groups.append(g) rows = [] for row in self.rows: c = [] for cell in row.cells: c.append(cells[cell.x, cell.y]) r = RowColGroup(c) r.options = copy.deepcopy(row.options) rows.append(r) cols = [] for col in self.cols: c = [] for cell in col.cells: c.append(cells[cell.x, cell.y]) c = RowColGroup(c) c.options = copy.deepcopy(col.options) cols.append(c) return Puzzle(cells, groups, rows, cols, win) def solve(self): tries = 0 while self.total() &lt; 36 and tries &lt; 60: tries += 1 for row in self.rows: row.solve() self.prompt.setText('Solving Rows... Continue.') for col in self.cols: col.solve() self.prompt.setText('Solving Columns... Continue.') for group in self.groups: group.solve() self.prompt.setText('Solving Groups... Continue.') if self.total() &lt; 36: for row in self.rows: for cell in row.cells: if cell.answer == 0: for option in cell.options: result = self.try_solve(cell, option) if result is not None: self.win.close() return result elif self.happy(): return self self.win.close() return None def try_solve(self, cell, option): c = self.copy() c.cells[cell.x, cell.y].answer = option c.cells[cell.x, cell.y].options = [option] result = c.solve() return result # cell.answer = option # return self.solve() def happy(self): all_groups = self.rows + self.cols + self.groups for group in all_groups: if not group.happy(): return False return True def total(self): total = 0 for y in range(6): for x in range(6): if self.cells[x, y].answer &gt; 0: total += 1 return total def get_input(self): p = self.win.getMouse() x, y = p.getX(), p.getY() if x &gt;= self.width: if 20 &lt; y &lt; 50: self.remove_options(self.win.getMouse(), int(self.prompt.getText())) else: self.solve() def remove_options(self, p, i): pass if __name__ == '__main__': p = Puzzle.from_gui() p = p.solve() p.win.getMouse() </code></pre> <p>options.py is just every possible combination for different groups.</p>
163898
GOOD_ANSWER
{ "AcceptedAnswerId": "164150", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-21T19:32:15.450", "Id": "163898", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "recursion" ], "Title": "KenKen puzzle solver" }
{ "body": "<p>There was no real explanation here of what this code does, and frankly there was a lot of it. Also, I had no way to run this code, so I will stick with some more generally pythonic things, which is what you asked for anyways.</p>\n\n<p>In general your code looks pretty good. For code tagged beginner, it is in fact excellent. I will however recommend getting familiar with python comprehensions. You have lots of loops that can be made considerably more pythonic with comprehension. I will show a few examples from your code, but first...</p>\n\n<h2>Pep8:</h2>\n\n<p>Python has a strong idea of how the code should be styled, and it is expressed in <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">pep8</a>. </p>\n\n<p>I suggest you get a style/lint checker. I use the <a href=\"https://www.jetbrains.com/pycharm/\" rel=\"nofollow noreferrer\">pycharm ide</a> which will show you style and compile issues right in the editor.</p>\n\n<p>The primary violation was due to line length issues. Breaking things to 80 columns can seem a bit uncomfortable at first, but it makes the code easier to read. </p>\n\n<h2>Comprehensions</h2>\n\n<p>So, this will go over a few styles of loops in your code and show a comprehension equivalent. I won't spend any time discussing the details, but hopefully the syntax is fairly straightforward, and the compactness and clarity will motivate you you to go study them.</p>\n\n<p>This: </p>\n\n<pre><code>temp = list(product(*temp))\nli = []\nfor x in temp:\n li.append(list(x)) \n</code></pre>\n\n<p>Can be:</p>\n\n<pre><code>li = [list(x) for x in product(*temp)]\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>remove = []\nfor option in self.options:\n if option not in possible:\n remove.append(option)\n\nfor option in remove:\n self.options.remove(option)\n</code></pre>\n\n<p>Can be:</p>\n\n<pre><code>self.options = [o for o in self.options if o in possible]\n</code></pre>\n\n<p>This: </p>\n\n<pre><code>total = 0\nfor cell in self.cells:\n total += cell.answer\n</code></pre>\n\n<p>Can be:</p>\n\n<pre><code>total = sum(cell.answer for cell in self.cells)\n</code></pre>\n\n<p>This: </p>\n\n<pre><code>x = []\ny = []\nfor cell in self.cells:\n x.append(cell.x)\n y.append(cell.y)\n</code></pre>\n\n<p>Can be:</p>\n\n<pre><code>x, y = zip(*((cell.x, cell.y) for cell in a))\n</code></pre>\n\n<h2>Note:</h2>\n\n<p>I didn't actually test any of these, so they may contain silly typos. Have any questions? Hit me up in comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-31T18:00:12.623", "Id": "313043", "Score": "0", "body": "Thank you so much! This is exactly the type of response I was looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-25T03:58:17.540", "Id": "164150", "ParentId": "163898", "Score": "3" } }
<p>I have been working on a 2-player battleship game and have finally got it working, bug free.</p> <p>I'm posting this here to ask you what you think of it. Are there any changes that could be made to improve the performance/general layout of the code?</p> <p>If you come across any issues with the code itself, (maybe a bug yet to be found) then I'd be grateful if you could let me know.</p> <p>The game is a fairly simple console-based battleship game, where the players take it in turns to sink a mutual ship that is defined by an x and y coordinate on a 5x5 game board.</p> <pre><code>from random import randint game_board = [] player_one = { "name": "Player 1", "wins": 0, } player_two = { "name": "Player 2", "wins": 0, } colors = { "reset":"\033[00m", "red":"\033[91m", "blue":"\033[94m", "cyan":"\033[96m", } # Building our 5 x 5 board def build_game_board(board): for item in range(5): board.append(["O"] * 5) def show_board(board): for row in board: print(" ".join(row)) # Defining ships locations def load_game(board): print("WELCOME TO BATTLESHIP!") print("Find and sink the ship!") del board[:] build_game_board(board) print(colors['blue']) show_board(board) print(colors['reset']) ship_col = randint(1, len(board)) ship_row = randint(1, len(board[0])) return { 'ship_col': ship_col, 'ship_row': ship_row, } ship_points = load_game(game_board) # Players will alternate turns. def player_turns(total_turns): if total_turns % 2 == 0: total_turns += 1 return player_one return player_two # Allows new game to start def play_again(): positive = ["yes", "y"] negative = ["no", "n"] global ship_points while True: answer = input("Play again? [Y(es) / N(o)]: ").lower().strip() if answer in positive: ship_points = load_game(game_board) main() break elif answer in negative: print("Thanks for playing!") exit() # What will be done with players guesses def input_check(ship_row, ship_col, player, board): guess_col = 0 guess_row = 0 while True: try: guess_row = int(input("Guess Row:")) - 1 guess_col = int(input("Guess Col:")) - 1 except ValueError: print("Enter a number only: ") continue else: break match = guess_row == ship_row - 1 and guess_col == ship_col - 1 not_on_game_board = (guess_row &lt; 0 or guess_row &gt; 4) or (guess_col &lt; 0 or guess_col &gt; 4) if match: player["wins"] += 1 print("Congratulations! You sunk my battleship!") print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"])) print("Thanks for playing!") play_again() elif not match: if not_on_game_board: print("Oops, that's not even in the ocean.") elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y": print("You guessed that one already.") else: print("You missed my battleship!") if player == player_one: board[guess_row][guess_col] = "X" else: board[guess_row][guess_col] = "Y" print(colors['cyan']) show_board(game_board) print(colors['reset']) else: return 0 begin = input("Type 'start' to begin: ") while (begin != str('start')): begin = input("Type 'start' to begin: ") def main(): for turns in range(6): if player_turns(turns) == player_one: print(ship_points) print("Player One") input_check( ship_points['ship_row'], ship_points['ship_col'], player_one, game_board ) elif player_turns(turns) == player_two: print("Player Two") input_check( ship_points['ship_row'], ship_points['ship_col'], player_two, game_board ) if turns == 5: print("This game is a draw.") print(colors['red']) show_board(game_board) print(colors['reset']) print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"])) play_again() if __name__ == "__main__": main() </code></pre>
164709
GOOD_ANSWER
{ "AcceptedAnswerId": "164712", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-01T19:55:46.217", "Id": "164709", "Score": "3", "Tags": [ "python", "python-3.x", "battleship" ], "Title": "2-player Game of Battleship (Python)" }
{ "body": "<p>This one's common it seems-</p>\n\n<h1>Whitespace</h1>\n\n<p>Python relies on whitespace and proper indentation to be readable; both for the developer(s) and people from all over the world who view the code. You should try to add whitespace to seperate <strong>logical</strong> pieces of code from one another. Especially your <em>load_game()</em> function needs this. I've rewritten it so it's more readable:</p>\n\n<pre><code>def load_game(board):\n del board[:]\n build_game_board(board)\n\n print(colors['blue'])\n show_board(board)\n print(colors['reset'])\n\n ship_col = randint(1, len(board))\n ship_row = randint(1, len(board[0]))\n\n return {\n 'ship_col': ship_col,\n 'ship_row': ship_row,\n }\n</code></pre>\n\n<h1>main() function and input / output</h1>\n\n<p>In the above example code, you may have noticed I got rid of the program's output. The reason I did this is because in general, it's easier to keep most in- / output in <strong>one</strong> part of the code (<em>main()</em>). This way, it's easier to use ~switch-case~ statements and to efficiently evaluate user input.</p>\n\n<p><strong>Bad code:</strong></p>\n\n<pre><code>def some_function():\n some_input = input()\n some_result = evaluate(some_input)\n if some_result:\n some_other_result = do_this()\n if some_other_result:\n do_this_again()\n else:\n do_that()\n</code></pre>\n\n<p><strong>Slightly better code:</strong></p>\n\n<pre><code>def some_function(result):\n\n if evaluate(result):\n do_this()\n\n else:\n do_that()\n\ndef main():\n print(\"Some welcome message.\")\n evaluate_me = input()\n\n some_function(result)\n</code></pre>\n\n<h1>input_check()</h1>\n\n<p>There's a couple of things that are off:</p>\n\n<ul>\n<li><p>The name of the function is <strong>too generic</strong>. Use something more meaningful, so you don't have to explain it with comments.</p></li>\n<li><p>Your code is not seperated into logical parts; whitespace is off:</p>\n\n<pre><code>guess_col = 0\nguess_row = 0\nwhile True:\n\n try:\n guess_row = int(input(\"Guess Row:\")) - 1\n guess_col = int(input(\"Guess Col:\")) - 1\n except ValueError:\n\n print(\"Enter a number only: \")\n continue\n else:\n\n break\n</code></pre></li>\n</ul>\n\n<p>Better code:</p>\n\n<pre><code>guess_col = 0\nguess_row = 0\n\nwhile True:\n try:\n guess_row = int(input(\"Guess Row:\")) - 1\n guess_col = int(input(\"Guess Col:\")) - 1\n break # break will run here if no ValueError gets raised\n except ValueError:\n print(\"Enter a number only.\")\n</code></pre>\n\n<ul>\n<li><p>Your <em>else:</em> statement (see above) will silently let an error escape if it ever gets to run (which, with the current setup, seems unlikely). <strong>Why not get rid of the statement altogether?</strong></p></li>\n<li><p>You don't need to use <em>continue</em>, because the indented code will only run if a ValueError occurs, and if that does happen, the <em>else:</em> statement would not run (else only runs if any other condition is False, not if any condition is True).</p></li>\n<li><p>You made the same mistake of using an <em>else: return 0</em> statement at the end of the function, even though <strong>there is no way this would run.</strong> You could change the if / elif / else to an if / else statement: </p>\n\n<p>if match:\n # do stuff</p>\n\n<p>else:\n # do other stuff</p></li>\n<li><p><em>return 0</em> is confusing. If you need to return none, use <em>return None</em> (wasn't that easy?). <em>return 0</em> may be understood as an exit code, in which case you should use sys.exit(0) (<a href=\"https://stackoverflow.com/questions/23547284/exit-0-vs-return-0-python-preference\">https://stackoverflow.com/questions/23547284/exit-0-vs-return-0-python-preference</a>). You could also just use <em>return</em> or <em>return False</em>, if any.</p></li>\n</ul>\n\n<h1>General</h1>\n\n<p>Just above the line where you declare <em>main()</em>:</p>\n\n<pre><code>begin = input(\"Type 'start' to begin: \")\n\nwhile (begin != str('start')):\n begin = input(\"Type 'start' to begin: \")\n</code></pre>\n\n<p>Simplify this:</p>\n\n<pre><code>while True:\n start_game = input(\"Type 'start' to begin: \")\n if start_game == \"start\": \n # No need for parentheses;\n # \"start\" is already str(). No need to convert.\n break\n</code></pre>\n\n<p>Some of your code is right on the edge of the 79 characters border (one line is 116 characters long). Look into shortening your lines to improve readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-02T11:35:21.623", "Id": "313389", "Score": "1", "body": "Thanks for the help. One question though, my `else: break` statement in my code is needed. If I were to remove that, then the code wouldn't work would it? I tried getting rid of it, and program kept prompting me for an input for the row and column, even though I put a valid value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-02T13:45:48.260", "Id": "313413", "Score": "0", "body": "Changed my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-01T20:17:22.343", "Id": "164712", "ParentId": "164709", "Score": "4" } }
<p>I wrote a country name generator in Python 3.5. My goal was to get randomized names that would look as much like real-world names as possible. Each name needed to have a noun and an adjective form (e.g., <code>Italy</code> and <code>Italian</code>).</p> <p>I started with a list of real countries, regions, and cities, which I stored in a text file. The names are broken up by syllables, with the noun and adjective endings separated (e.g., <code>i-ta-l y/ian</code>). The program splits each name into syllables, and each syllable into three <em>segments</em>: <a href="https://en.wikipedia.org/wiki/Syllable#Typical_model" rel="noreferrer">onset, nucleus, and coda</a> (i.e., the leading consonants, the vowels, and the trailing consonants). It then uses the frequency of these segments in relation to each other to drive a <a href="https://en.wikipedia.org/wiki/Markov_chain" rel="noreferrer">Markov process</a> that generates a name. (It's not a pure Markov process because I wanted to ensure a distribution of syllable counts similar to the input set. I also special-cased the endings.) Several types of undesirable names are rejected.</p> <h3>Main code</h3> <pre><code>#!/usr/bin/python3 import re, random # A regex that matches a syllable, with three groups for the three # segments of the syllable: onset (initial consonants), nucleus (vowels), # and coda (final consonants). # The regex also matches if there is just an onset (even an empty # onset); this case corresponds to the final partial syllable of the # stem, which is usually the consonant before a vowel ending (for # example, the d in "ca-na-d a"). syllableRgx = re.compile(r"(y|[^aeiouy]*)([aeiouy]+|$)([^aeiouy]*)") nameFile = "names.txt" # Dictionary that holds the frequency of each syllable count (note that these # are the syllables *before* the ending, so "al-ba-n ia" only counts two) syllableCounts = {} # List of four dictionaries (for onsets, nuclei, codas, and endings): # Each dictionary's key/value pairs are prevSegment:segmentDict, where # segmentDict is a frequency dictionary of various onsets, nuclei, codas, # or endings, and prevSegment is a segment that can be the last nonempty # segment preceding them. A prevSegment of None marks segments at the # beginnings of names. segmentData = [{}, {}, {}, {}] ONSET = 0 NUCLEUS = 1 CODA = 2 ENDING = 3 # Read names from file and generate the segmentData structure with open(nameFile) as f: for line in f.readlines(): # Strip whitespace, ignore blank lines and comments line = line.strip() if not line: continue if line[0] == "#": continue stem, ending = line.split() # Endings should be of the format noun/adj if "/" not in ending: # The noun ending is given; the adjective ending can be # derived by appending -n ending = "{}/{}n".format(ending, ending) # Syllable count is the number of hyphens syllableCount = stem.count("-") if syllableCount in syllableCounts: syllableCounts[syllableCount] += 1 else: syllableCounts[syllableCount] = 1 # Add the segments in this name to segmentData prevSegment = None for syllable in stem.split("-"): segments = syllableRgx.match(syllable).groups() if segments[NUCLEUS] == segments[CODA] == "": # A syllable with emtpy nucleus and coda comes right before # the ending, so we only process the onset segments = (segments[ONSET],) for segType, segment in enumerate(segments): if prevSegment not in segmentData[segType]: segmentData[segType][prevSegment] = {} segFrequencies = segmentData[segType][prevSegment] if segment in segFrequencies: segFrequencies[segment] += 1 else: segFrequencies[segment] = 1 if segment: prevSegment = segment # Add the ending to segmentData if prevSegment not in segmentData[ENDING]: segmentData[ENDING][prevSegment] = {} endFrequencies = segmentData[ENDING][prevSegment] if ending in endFrequencies: endFrequencies[ending] += 1 else: endFrequencies[ending] = 1 def randFromFrequencies(dictionary): "Returns a random dictionary key, where the values represent frequencies." keys = dictionary.keys() frequencies = dictionary.values() index = random.randrange(sum(dictionary.values())) for key, freq in dictionary.items(): if index &lt; freq: # Select this one return key else: index -= freq # Weird, should have returned something raise ValueError("randFromFrequencies didn't pick a value " "(index remainder is {})".format(index)) def markovName(syllableCount): "Generate a country name using a Markov-chain-like process." prevSegment = None stem = "" for syll in range(syllableCount): for segType in [ONSET, NUCLEUS, CODA]: try: segFrequencies = segmentData[segType][prevSegment] except KeyError: # In the unusual situation that the chain fails to find an # appropriate next segment, it's too complicated to try to # roll back and pick a better prevSegment; so instead, # return None and let the caller generate a new name return None segment = randFromFrequencies(segFrequencies) stem += segment if segment: prevSegment = segment endingOnset = None # Try different onsets for the last syllable till we find one that's # legal before an ending; we also allow empty onsets. Because it's # possible we won't find one, we also limit the number of retries # allowed. retries = 10 while (retries and endingOnset != "" and endingOnset not in segmentData[ENDING]): segFrequencies = segmentData[ONSET][prevSegment] endingOnset = randFromFrequencies(segFrequencies) retries -= 1 stem += endingOnset if endingOnset != "": prevSegment = endingOnset if prevSegment in segmentData[ENDING]: # Pick an ending that goes with the prevSegment endFrequencies = segmentData[ENDING][prevSegment] endings = randFromFrequencies(endFrequencies) else: # It can happen, if we used an empty last-syllable onset, that # the previous segment does not appear before any ending in the # data set. In this case, we'll just use -a(n) for the ending. endings = "a/an" endings = endings.split("/") nounForm = stem + endings[0] # Filter out names that are too short or too long if len(nounForm) &lt; 3: # This would give two-letter names like Mo, which don't appeal # to me return None if len(nounForm) &gt; 11: # This would give very long names like Imbadossorbia that are too # much of a mouthful return None # Filter out names with weird consonant clusters at the end for consonants in ["bl", "tn", "sr", "sn", "sm", "shm"]: if nounForm.endswith(consonants): return None # Filter out names that sound like anatomical references for bannedSubstring in ["vag", "coc", "cok", "kok", "peni"]: if bannedSubstring in stem: return None if nounForm == "ass": # This isn't a problem if it's part of a larger name like Assyria, # so filter it out only if it's the entire name return None return stem, endings </code></pre> <h3>Testing code</h3> <pre><code>def printCountryNames(count): for i in range(count): syllableCount = randFromFrequencies(syllableCounts) nameInfo = markovName(syllableCount) while nameInfo is None: nameInfo = markovName(syllableCount) stem, endings = nameInfo stem = stem.capitalize() noun = stem + endings[0] adjective = stem + endings[1] print("{} ({})".format(noun, adjective)) if __name__ == "__main__": printCountryNames(10) </code></pre> <h3>Example <code>names.txt</code> contents</h3> <pre><code># Comments are ignored i-ta-l y/ian # A suffix can be empty i-ra-q /i # The stem can end with a syllable break ge-no- a/ese # Names whose adjective suffix just adds an -n need only list the noun suffix ar-me-n ia sa-mo- a </code></pre> <p>My full <code>names.txt</code> file can be found, along with the code, in <a href="https://gist.github.com/dloscutoff/d4d79df2ab71411d99d6d646e8f45ee6" rel="noreferrer">this Gist</a>.</p> <h3>Example output</h3> <p>Generated using the full data file:</p> <pre class="lang-none prettyprint-override"><code>Slorujarnia (Slorujarnian) Ashmar (Ashmari) Babya (Babyan) Randorkia (Randorkian) Esanoa (Esanoese) Manglalia (Manglalic) Konara (Konaran) Lilvispia (Lilvispian) Cenia (Cenian) Rafri (Rafrian) </code></pre> <h2>Questions</h2> <ul> <li>Is my code readable? Clear variable and function names? Sufficient comments?</li> <li>Should I restructure anything?</li> <li>Are there any Python 3 features I could use or use better? I'm particularly unused to <code>format</code> and the various approaches for using it.</li> </ul> <p>If you see anything else that can be improved, please let me know. Just one exception: I know the PEP standard is snake_case, but <strong>I want to use camelCase</strong> and I don't intend to change that. Other formatting tips are welcome.</p>
172929
GOOD_ANSWER
{ "AcceptedAnswerId": "172933", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T05:35:05.427", "Id": "172929", "Score": "36", "Tags": [ "python", "python-3.x", "markov-chain" ], "Title": "Markov country name generator" }
{ "body": "<ul>\n<li><p>It is better to follow PEP8 which says that <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"noreferrer\">import statements</a>, such as in your case, should use multiple lines:</p>\n\n<pre><code>import re\nimport random\n</code></pre></li>\n<li>Whatever the programming language you use, it is better to avoid input/output operations whenever you can. So instead of storing the countries' names in a text file, you can choose a suitable Python data structure for the purpose.</li>\n<li>When someone reads your main program, he must straightforwardly knows what it is doing. It is not the case with your <em>main.py</em> file where I see lot of distracting information and noise. For example, you should save all those constants in a separate module you may call <em>configurations.py</em>, <em>cfg.py</em>, <em>settings.py</em> or whatever name you think it fits into the your project's architecture. </li>\n<li>Choose meaningful names: while most of the names you chose are edible, I believe you still can make some improvements for few of them. That is the case, for example, of <code>nameFile</code> which is too vague and does not bring any information apart from the one of the assignment operation itself: <code>nameFile = \"names.txt\"</code>. Sure it is a name of a file, but only after reading your program's statement that one can guess what you would mean by <code>nameFile</code> and start to suggest you right away a more suitable and informative name such as <code>countries_names</code>. Note in my suggestion there is not the container's name. I mean, I am not pushing the reader of your code to know programming details such as whether you stored the information in a file or this or that data structure. Names should be \"high level\" and independent from the data structure they represent. This offers you the advantage not to spot the same name in your program to re-write it just because you changed the store data from a file to an other data structure. This also applies to <code>syllableRgx</code>: for sure when someone reads <code>syllableRgx = re.compile(r\"...\")</code> he understands you are storing the result of a regex expression. But you should change this name to something better for the reasons I explained just before.</li>\n<li>You should follow the standard <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"noreferrer\">naming conventions</a>. For example, <code>syllableCounts</code> and <code>segmentData</code> should be written <code>syllable_counts</code> and <code>segment_data</code> respectively.</li>\n<li><em>I want to use camelCase</em> No. When develop in a given programming language, adopt its spirit and philosophy. It is like when you join a new company's developer team: adapt yourself to themselves, and do not ask them to adapt themselves to your habits and wishes.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T10:19:46.763", "Id": "327936", "Score": "5", "body": "Mmm. Edible names. (Readable?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T10:56:06.597", "Id": "327944", "Score": "3", "body": "By *edible* (rather a French way of expressing myself) I meant \"meaningful names that tell about the variable's, function's or class' purpose*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T15:15:32.837", "Id": "328023", "Score": "0", "body": "Often the information needs to get stored in a language-agnostic way at some point. In such a case, would you keep the structure as-is or first put everything in a variable and print the whole variable in 1 go at the end?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T15:40:41.907", "Id": "328032", "Score": "0", "body": "Naming conventions are different for constants. syllableCounts shoudl be SYLLABLE_COUNTS not syllable_counts, for example. https://www.python.org/dev/peps/pep-0008/#constants" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T15:56:25.633", "Id": "328036", "Score": "3", "body": "You are right, constants should be written in capital letters as you did, and as the OP did , but `syllable_counts` is a dictionary which is, in the beginning inititalized to be empty, later it is filled with data, so it is not a constant @Wyrmwood" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T19:59:49.973", "Id": "328111", "Score": "0", "body": "Good idea storing the names as a Python list and importing them. A few questions: For `syllableRgx`, would `syllablePattern` be a better name? By \"all those constants\" do you mean just `ONSET` etc. or would `configuration.py` also include `syllablePattern` and the new list of `countryNames`? (And should those be capitalized as constants, since they never change?) Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T20:04:00.583", "Id": "328112", "Score": "9", "body": "I think 'digestible' (or better still, 'easy to digest') is better English, while still being faithful to your intention in French." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-15T15:07:57.267", "Id": "328238", "Score": "0", "body": "@BillalBEGUERADJ Pylint will disagree :-)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T06:14:46.707", "Id": "172933", "ParentId": "172929", "Score": "18" } }
<p>I wrote a country name generator in Python 3.5. My goal was to get randomized names that would look as much like real-world names as possible. Each name needed to have a noun and an adjective form (e.g., <code>Italy</code> and <code>Italian</code>).</p> <p>I started with a list of real countries, regions, and cities, which I stored in a text file. The names are broken up by syllables, with the noun and adjective endings separated (e.g., <code>i-ta-l y/ian</code>). The program splits each name into syllables, and each syllable into three <em>segments</em>: <a href="https://en.wikipedia.org/wiki/Syllable#Typical_model" rel="noreferrer">onset, nucleus, and coda</a> (i.e., the leading consonants, the vowels, and the trailing consonants). It then uses the frequency of these segments in relation to each other to drive a <a href="https://en.wikipedia.org/wiki/Markov_chain" rel="noreferrer">Markov process</a> that generates a name. (It's not a pure Markov process because I wanted to ensure a distribution of syllable counts similar to the input set. I also special-cased the endings.) Several types of undesirable names are rejected.</p> <h3>Main code</h3> <pre><code>#!/usr/bin/python3 import re, random # A regex that matches a syllable, with three groups for the three # segments of the syllable: onset (initial consonants), nucleus (vowels), # and coda (final consonants). # The regex also matches if there is just an onset (even an empty # onset); this case corresponds to the final partial syllable of the # stem, which is usually the consonant before a vowel ending (for # example, the d in "ca-na-d a"). syllableRgx = re.compile(r"(y|[^aeiouy]*)([aeiouy]+|$)([^aeiouy]*)") nameFile = "names.txt" # Dictionary that holds the frequency of each syllable count (note that these # are the syllables *before* the ending, so "al-ba-n ia" only counts two) syllableCounts = {} # List of four dictionaries (for onsets, nuclei, codas, and endings): # Each dictionary's key/value pairs are prevSegment:segmentDict, where # segmentDict is a frequency dictionary of various onsets, nuclei, codas, # or endings, and prevSegment is a segment that can be the last nonempty # segment preceding them. A prevSegment of None marks segments at the # beginnings of names. segmentData = [{}, {}, {}, {}] ONSET = 0 NUCLEUS = 1 CODA = 2 ENDING = 3 # Read names from file and generate the segmentData structure with open(nameFile) as f: for line in f.readlines(): # Strip whitespace, ignore blank lines and comments line = line.strip() if not line: continue if line[0] == "#": continue stem, ending = line.split() # Endings should be of the format noun/adj if "/" not in ending: # The noun ending is given; the adjective ending can be # derived by appending -n ending = "{}/{}n".format(ending, ending) # Syllable count is the number of hyphens syllableCount = stem.count("-") if syllableCount in syllableCounts: syllableCounts[syllableCount] += 1 else: syllableCounts[syllableCount] = 1 # Add the segments in this name to segmentData prevSegment = None for syllable in stem.split("-"): segments = syllableRgx.match(syllable).groups() if segments[NUCLEUS] == segments[CODA] == "": # A syllable with emtpy nucleus and coda comes right before # the ending, so we only process the onset segments = (segments[ONSET],) for segType, segment in enumerate(segments): if prevSegment not in segmentData[segType]: segmentData[segType][prevSegment] = {} segFrequencies = segmentData[segType][prevSegment] if segment in segFrequencies: segFrequencies[segment] += 1 else: segFrequencies[segment] = 1 if segment: prevSegment = segment # Add the ending to segmentData if prevSegment not in segmentData[ENDING]: segmentData[ENDING][prevSegment] = {} endFrequencies = segmentData[ENDING][prevSegment] if ending in endFrequencies: endFrequencies[ending] += 1 else: endFrequencies[ending] = 1 def randFromFrequencies(dictionary): "Returns a random dictionary key, where the values represent frequencies." keys = dictionary.keys() frequencies = dictionary.values() index = random.randrange(sum(dictionary.values())) for key, freq in dictionary.items(): if index &lt; freq: # Select this one return key else: index -= freq # Weird, should have returned something raise ValueError("randFromFrequencies didn't pick a value " "(index remainder is {})".format(index)) def markovName(syllableCount): "Generate a country name using a Markov-chain-like process." prevSegment = None stem = "" for syll in range(syllableCount): for segType in [ONSET, NUCLEUS, CODA]: try: segFrequencies = segmentData[segType][prevSegment] except KeyError: # In the unusual situation that the chain fails to find an # appropriate next segment, it's too complicated to try to # roll back and pick a better prevSegment; so instead, # return None and let the caller generate a new name return None segment = randFromFrequencies(segFrequencies) stem += segment if segment: prevSegment = segment endingOnset = None # Try different onsets for the last syllable till we find one that's # legal before an ending; we also allow empty onsets. Because it's # possible we won't find one, we also limit the number of retries # allowed. retries = 10 while (retries and endingOnset != "" and endingOnset not in segmentData[ENDING]): segFrequencies = segmentData[ONSET][prevSegment] endingOnset = randFromFrequencies(segFrequencies) retries -= 1 stem += endingOnset if endingOnset != "": prevSegment = endingOnset if prevSegment in segmentData[ENDING]: # Pick an ending that goes with the prevSegment endFrequencies = segmentData[ENDING][prevSegment] endings = randFromFrequencies(endFrequencies) else: # It can happen, if we used an empty last-syllable onset, that # the previous segment does not appear before any ending in the # data set. In this case, we'll just use -a(n) for the ending. endings = "a/an" endings = endings.split("/") nounForm = stem + endings[0] # Filter out names that are too short or too long if len(nounForm) &lt; 3: # This would give two-letter names like Mo, which don't appeal # to me return None if len(nounForm) &gt; 11: # This would give very long names like Imbadossorbia that are too # much of a mouthful return None # Filter out names with weird consonant clusters at the end for consonants in ["bl", "tn", "sr", "sn", "sm", "shm"]: if nounForm.endswith(consonants): return None # Filter out names that sound like anatomical references for bannedSubstring in ["vag", "coc", "cok", "kok", "peni"]: if bannedSubstring in stem: return None if nounForm == "ass": # This isn't a problem if it's part of a larger name like Assyria, # so filter it out only if it's the entire name return None return stem, endings </code></pre> <h3>Testing code</h3> <pre><code>def printCountryNames(count): for i in range(count): syllableCount = randFromFrequencies(syllableCounts) nameInfo = markovName(syllableCount) while nameInfo is None: nameInfo = markovName(syllableCount) stem, endings = nameInfo stem = stem.capitalize() noun = stem + endings[0] adjective = stem + endings[1] print("{} ({})".format(noun, adjective)) if __name__ == "__main__": printCountryNames(10) </code></pre> <h3>Example <code>names.txt</code> contents</h3> <pre><code># Comments are ignored i-ta-l y/ian # A suffix can be empty i-ra-q /i # The stem can end with a syllable break ge-no- a/ese # Names whose adjective suffix just adds an -n need only list the noun suffix ar-me-n ia sa-mo- a </code></pre> <p>My full <code>names.txt</code> file can be found, along with the code, in <a href="https://gist.github.com/dloscutoff/d4d79df2ab71411d99d6d646e8f45ee6" rel="noreferrer">this Gist</a>.</p> <h3>Example output</h3> <p>Generated using the full data file:</p> <pre class="lang-none prettyprint-override"><code>Slorujarnia (Slorujarnian) Ashmar (Ashmari) Babya (Babyan) Randorkia (Randorkian) Esanoa (Esanoese) Manglalia (Manglalic) Konara (Konaran) Lilvispia (Lilvispian) Cenia (Cenian) Rafri (Rafrian) </code></pre> <h2>Questions</h2> <ul> <li>Is my code readable? Clear variable and function names? Sufficient comments?</li> <li>Should I restructure anything?</li> <li>Are there any Python 3 features I could use or use better? I'm particularly unused to <code>format</code> and the various approaches for using it.</li> </ul> <p>If you see anything else that can be improved, please let me know. Just one exception: I know the PEP standard is snake_case, but <strong>I want to use camelCase</strong> and I don't intend to change that. Other formatting tips are welcome.</p>
172929
GOOD_ANSWER
{ "AcceptedAnswerId": "172933", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T05:35:05.427", "Id": "172929", "Score": "36", "Tags": [ "python", "python-3.x", "markov-chain" ], "Title": "Markov country name generator" }
{ "body": "<h2>Looping over lines of a file</h2>\n\n<p>Probably a minor nitpick, but when using a file object returned by <code>open()</code>, you can just iterate over the object, instead of calling <code>readlines()</code>, like so:</p>\n\n<pre><code># Read names from file and generate the segmentData structure\nwith open(nameFile) as input_names:\n for line in input_names:\n</code></pre>\n\n<p>From <a href=\"https://docs.python.org/3/library/io.html?highlight=readlines#io.IOBase.readlines\" rel=\"noreferrer\">the docs</a>:</p>\n\n<blockquote>\n <h3><code><strong>readlines</strong>(<em>hint=-1</em>)</code></h3>\n \n <p>Read and return a list of lines from the stream. <em>hint</em> can be\n specified to control the number of lines read: no more lines will be\n read if the total size (in bytes/characters) of all lines so far\n exceeds <em>hint</em>.</p>\n \n <p>Note that it’s already possible to iterate on file objects using <code>for line in file: ...</code> without calling <code>file.readlines()</code>.</p>\n</blockquote>\n\n<p>So, if you're not going to limit the data being read, then there's no need to use <code>readlines()</code>.</p>\n\n<h2>Testing if any element matches a condition</h2>\n\n<p>... can be done using <a href=\"https://docs.python.org/3/library/functions.html?highlight=any#any\" rel=\"noreferrer\"><code>any()</code></a>, <code>map()</code>, and an appropriate function, so:</p>\n\n<pre><code># Filter out names with weird consonant clusters at the end\nweird_consonant_clusters = [\"bl\", \"tn\", \"sr\", \"sn\", \"sm\", \"shm\"]\nif any(map(nounForm.endswith, weird_consonant_clusters)):\n return None\n</code></pre>\n\n<p>With the <code>bannedSubstring</code> case, though, there's no direct equivalent of <code>in</code>: you'd have to use <code>count()</code> or write a lambda, so there might not be much to be gained here.</p>\n\n<h2>Increment-or-set</h2>\n\n<p>For the frequencies, where you do <a href=\"https://stackoverflow.com/a/2626102/2072269\">an increment or set</a>, you could use the <code>get</code> method, or a <a href=\"https://docs.python.org/3/library/collections.html?highlight=defaultdict#collections.defaultdict\" rel=\"noreferrer\">defaultdict</a>, so that this:</p>\n\n<pre><code>if ending in endFrequencies:\n endFrequencies[ending] += 1\nelse:\n endFrequencies[ending] = 1\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>endFrequencies[ending] = endFrequencies.get(ending, 0) + 1\n</code></pre>\n\n<p>Or if <code>endFrequencies</code> is a <code>defaultdict(int)</code>, just:</p>\n\n<pre><code>endFrequencies[ending] += 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T12:09:13.627", "Id": "327961", "Score": "7", "body": "There’s a specialized collection class made just for this purpose: [collections.Counter](https://docs.python.org/3/library/collections.html#collections.Counter). Just initialize with `endFrequencies = Counter()` and update with `endFrequencies[ending] += 1`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T20:07:26.457", "Id": "328113", "Score": "0", "body": "[facepalm] Forgot about iterating over the file. Due to another answer's suggestion I won't be reading a file anymore, but thanks. `defaultdict` is another good idea, although it looks like @Chortos-2's `collections.Counter` is exactly what I need." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T10:02:38.553", "Id": "172952", "ParentId": "172929", "Score": "15" } }
<p>I'd like some feedback on the readability, style, and potential problems or issues. In particular I'm not too happy with how I handle ratelimits.</p> <pre><code>import json import requests import pandas as pd import matplotlib.pyplot as plt from dateutil.relativedelta import relativedelta from datetime import date from flatten_json import flatten from tqdm import tnrange as trange from time import sleep class CrimsonHexagonClient(object): """Interacts with the Crimson Hexagon API to retrieve post data (twitter ids etc.) from a configured monitor. Docs: https://apidocs.crimsonhexagon.com/v1.0/reference Args: username (str): Username on website. password (str): Password on website. monitor_id (str): id of crimson monitor. """ def __init__(self, username, password, monitor_id): self.username = username self.password = password self.monitor_id = monitor_id self.base = 'https://api.crimsonhexagon.com/api/monitor' self.session = requests.Session() self.ratelimit_refresh = 60 self._auth() def _auth(self): """Authenticates a user using their username and password through the authenticate endpoint. """ url = 'https://forsight.crimsonhexagon.com/api/authenticate?' payload = { 'username': self.username, 'password': self.password } r = self.session.get(url, params=payload) j_result = r.json() self.auth_token = j_result["auth"] print('-- Authenticated --') return def make_endpoint(self, endpoint): return '{}/{}?'.format(self.base, endpoint) def get_data_from_endpoint(self, from_, to_, endpoint): """Hits the designated endpoint (volume/posts) for a specified time period. The ratelimit is burned through ASAP and then backed off for one minute. """ endpoint = self.make_endpoint(endpoint) from_, to_ = str(from_), str(to_) payload = { 'auth': self.auth_token, 'id': self.monitor_id, 'start': from_, 'end': to_, 'extendLimit': 'true', 'fullContents': 'true' } r = self.session.get(endpoint, params=payload) self.last_response = r ratelimit_remaining = r.headers['X-RateLimit-Remaining'] # If the header is empty or 0 then wait for a ratelimit refresh. if (not ratelimit_remaining) or (float(ratelimit_remaining) &lt; 1): print('Waiting for ratelimit refresh...') sleep(self.ratelimit_refresh) return r def get_dates_from_timespan(self, r_volume, max_documents=10000): """Divides the time period into chunks of less than 10k where possible. """ # If the count is less than max, just return the original time span. if r_volume.json()['numberOfDocuments'] &lt;= max_documents: l_dates = [[pd.to_datetime(r_volume.json()['startDate']).date(), pd.to_datetime(r_volume.json()['endDate']).date()]] return l_dates # Convert json to df for easier subsetting &amp; to calculate cumulative sum. df = pd.DataFrame(r_volume.json()['volume']) df['startDate'] = pd.to_datetime(df['startDate']) df['endDate'] = pd.to_datetime(df['endDate']) l_dates = [] while True: df['cumulative_sum'] = df['numberOfDocuments'].cumsum() # Find the span whose cumulative sum is below the threshold. df_below = df[df['cumulative_sum'] &lt;= max_documents] # If there are 0 rows under threshold. if (df_below.empty): # If there are still rows left, use the first row. if len(df) &gt; 0: # This entry will have over 10k, but we can't go more # granular than one day. df_below = df.iloc[0:1] else: break # Take the first row's start date and last row's end date. from_ = df_below['startDate'].iloc[0].date() to_ = df_below['endDate'].iloc[-1].date() l_dates.append([from_, to_]) # Reassign df to remaining portion. df = df[df['startDate'] &gt;= to_] return l_dates def plot_volume(self, r_volume): """Plots a time-series chart with two axes to show the daily and cumulative document count. """ # Convert r to df, fix datetime, add cumulative sum. df_volume = pd.DataFrame(r_volume.json()['volume']) df_volume['startDate'] = pd.to_datetime(df_volume['startDate']) df_volume['endDate'] = pd.to_datetime(df_volume['endDate']) df_volume['cumulative_sum'] = df_volume['numberOfDocuments'].cumsum() fig, ax1 = plt.subplots() ax2 = ax1.twinx() df_volume['numberOfDocuments'].plot(ax=ax1, style='b-') df_volume['cumulative_sum'].plot(ax=ax2, style='r-') ax1.set_ylabel('Number of Documents') ax2.set_ylabel('Cumulative Sum') h1, l1 = ax1.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() ax1.legend(h1+h2, l1+l2, loc=2) plt.show() return def make_data_pipeline(self, from_, to_): """Combines the functionsin this class to make a robust pipeline, that loops through each day in a time period. Data is returned as a dataframe. """ # Get the volume over time data. r_volume = self.get_data_from_endpoint(from_, to_, 'volume') print('There are approximately {} documents.'.format(r_volume.json()['numberOfDocuments'])) self.plot_volume(r_volume) # Carve up time into buckets of volume &lt;10k. l_dates = self.get_dates_from_timespan(r_volume) data = [] for i in trange(len(l_dates), leave=False): from_, to_ = l_dates[i] # Pull posts. r_posts = self.get_data_from_endpoint(from_, to_, 'posts') if r_posts.ok and (r_posts.json()['status'] != 'error'): j_result = json.loads(r_posts.content.decode('utf8')) data.extend(j_result['posts']) l_flat= [flatten(d) for d in data] df = pd.DataFrame(l_flat) return df if __name__ == "__main__": # Credentials. username = 'xxxxx' password = 'xxxxx' # Monitor id - taken from URL on website. monitor_id = '123' # Instantiate client. crimson_api = CrimsonHexagonClient(username, password, monitor_id) from_ = date(2017, 1, 1) to_ = date(2017, 6, 30) # Combine class functions into a typical workflow. df = crimson_api.make_data_pipeline(from_, to_) </code></pre>
173049
GOOD_ANSWER
{ "AcceptedAnswerId": "173083", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-15T06:04:55.490", "Id": "173049", "Score": "6", "Tags": [ "python", "api", "pandas" ], "Title": "Python API for Crimson Hexagon" }
{ "body": "<h3><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Readability &amp; Style</a></h3>\n<p><strong>Imports</strong></p>\n<p>Remove the modules that you're not using (<code>dateutil</code>).<br />\nImports should be grouped in the following order:</p>\n<ol>\n<li>standard library imports</li>\n<li>related third party imports</li>\n<li>local application/library specific imports</li>\n</ol>\n<p><strong>Code layout</strong></p>\n<p>You should surround top-level function and class definitions with two blank lines.</p>\n<p><em>Whitespace in Expressions and Statements</em></p>\n<p><strong>Avoid</strong> extraneous whitespaces before/after any operator (in your case, <code>=</code>) and between two lines of code.</p>\n<p><strong>Comments</strong></p>\n<p>You have some comments which doesn't add any value to your code. Get rid of them. (E.g: <code># Credentials.</code>, <code># Instantiate client.</code>)</p>\n<hr />\n<h3>Should you use OOP ?</h3>\n<p>You've created all your code by using a class but you didn't actually make use of it. 80% of your methods are <em>static</em> which makes me think you shouldn't need to use a class . Try to reorganise your code by splitting it into smaller functions and create classes only if you need to communicate state between your methods or you need one of the OOP principles (inheritance, polymorphism etc). <em>PS: As a side note, this is entirely subjective</em></p>\n<hr />\n<h3>More on the code</h3>\n<ul>\n<li>You're not using <code>self.last_response</code> anywhere. Remove it.</li>\n<li>In <code>_auth</code> and <code>plot_volume</code> methods, the <code>return</code> statement is redundant. Remove it.</li>\n<li>In <code>make_data_pipeline</code> method, don't create useless variables. Instead, you can directly return <code>pd.DataFrame(l_flat)</code>.</li>\n<li>You don't need parentheses here: <code>if (df_below.empty)</code>.</li>\n<li>You should really add some <code>try/except</code> blocks at least when you're authenticating against the API and let the user know if something went wrong or not.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-15T14:04:12.677", "Id": "173083", "ParentId": "173049", "Score": "5" } }
<p>I have a project and I am trying to do a complex cryptographic method. Is it normal to use nested loops a lot? Or Did I miss something?</p> <p>I intend to create a method which tries all strings to find password. For example, It should create each of these one by one: ('A','A') ('B', 'A') ('A', 'B') ('B', 'B') ('A', 'AA' ) ('A', 'AB') ('B', 'AA') ('B', 'AB') ('A', 'BA') ('B', 'BA') ('A', 'BB') ('B', 'BB') , (triple permutations), (quadruple permutations).. and it goes...</p> <pre><code>def rulefinder(): global externalrul1 global externalrul2 rul2 = uniquestring1[0] rul1 = uniquestring1[0] for n in range (0,3): for m in range (0, len(uniquestring1)): for z in range(0, n+1): for k in range (0,3): for i in range(0, len(uniquestring1)): for o in range(0, k+1): for y in range (0, len(uniquestring1)): rul2 = rul2[:-1] + uniquestring1[y] for x in range (0, len(uniquestring1)): rul1= rul1[:-1] + uniquestring1[x] code="" for cha in Genx1: if cha==uniquestring1[0]: code +=codereplacer(rul1) elif cha==uniquestring1[1]: code +=codereplacer(rul2) print(code) print(uniquestring1[0],rul1) print(uniquestring1[1],rul2) print(LastString) if code == LastString: axiom1=uniquestring1[0] axiom2=uniquestring1[1] externalrul1=rul1 externalrul2=rul2 print('rules are found') print("First RULE:", uniquestring1[0], rul1) print("Second RULE:", uniquestring1[1], rul2) findsubgeneration(code, axiom1, rul1, axiom2, rul2) return rul1 = rul1[:o] + uniquestring1[i] + rul1[(o + 1):] rul1 += codereplacer(uniquestring1[i]) rul2 = rul2[:z] + uniquestring1[m] + rul2[(z + 1):] rul1 ="" rul2 += codereplacer(uniquestring1[m]) </code></pre>
183763
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-28T07:06:57.710", "Id": "183763", "Score": "4", "Tags": [ "python", "cryptography" ], "Title": "Is it proper to use nested loops a lot in python?" }
{ "body": "<p>From what I understand from your comment, using <code>itertools</code> did solve your problems.</p>\n\n<p>Here are a few suggestions anyway (that you may want to take into account before submitting a new question with the updated code):</p>\n\n<ul>\n<li><p>instead of using global variables, you should add parameters to your functions.</p></li>\n<li><p>you could take this chance to add a proper documentation about what your function is supposed to do and what the parameters are.</p></li>\n<li><p>the indentations seem to be of various sizes. <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8, the Style Guide for Python code</a> recommands using 4 spaces. It is probably worth reading the whole document.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-28T22:47:01.880", "Id": "350007", "Score": "0", "body": "Thank you! I am going to add document after the project is done and I will edit spaces as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-28T13:13:12.427", "Id": "183782", "ParentId": "183763", "Score": "2" } }
<p>I'm using some old <a href="http://usaco.org/index.php" rel="nofollow noreferrer">USA Computing Olympiad</a> (USACO) problems to help teach me programming. This is the second one I've posted, I hope that's okay -- let me know if this is considered abusing the system. </p> <p>You can find my first post <a href="https://codereview.stackexchange.com/questions/195463/milking-order-compatible-with-maximum-number-of-observations">here</a>. As noted there, I'm essentially a beginner at programming in general, so any suggestions you have to improve any aspect of the code will be helpful. I tried to implement the suggestions of Gareth and Peter from the last thread as I worked on this problem. </p> <p>This is the <a href="http://usaco.org/index.php?page=viewproblem2&amp;cpid=839" rel="nofollow noreferrer">"Talent Show" problem</a>:</p> <blockquote> <p>Farmer John is bringing his \$N\$ cows, conveniently numbered \$1,\ldots, N\$, to the county fair, to compete in the annual bovine talent show! His \$i\$th cow has a weight \$w_i\$ and talent level \$t_i,\$ both integers. Upon arrival, Farmer John is quite surprised by the new rules for this year's talent show: </p> <ol> <li>A group of cows of total weight at least \$W\$ must be entered into the show(in order to ensure strong teams of cows are competing, not just strong individuals), and </li> <li>The group with the largest ratio of total talent to total weight shall win. </li> </ol> <p>FJ observes that all of his cows together have weight at least \$W,\$ so he should be able to enter a team satisfying (1). Help him determine the optimal ratio of talent to weight he can achieve for any such team. </p> <h3>Input Format</h3> <p>The first line of input contains \$N\$ (\$1 \le N \le 250 \$) and \$W\$ (\$1 \le W \le 1000\$). The next \$N\$ lines describe a cow with two integers \$w_i\$ and \$t_i.\$</p> <h3>Output Format</h3> <p>Output \$\lfloor 1000A\rfloor\$ where \$A\$ is the largest possible talent ratio Farmer John can achieve with cows having weight at least \$W.\$</p> <h3>Sample input</h3> <pre><code>3 15 20 21 10 11 30 31 </code></pre> <h3>Sample Output</h3> <pre><code>1066 </code></pre> </blockquote> <p>The algorithm is a bit hard to follow, so I'm also curious if my code got across what's going on or not. I started the problem by drawing this picture on paper, which hopefully sheds some light on what I'm trying to do with the code. <a href="https://i.stack.imgur.com/vK6c0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vK6c0.jpg" alt="enter image description here"></a></p> <p>(Note that when I actually started coding, I realized it was a lot of work for zero gain to keep track of the second index so I dropped it.)</p> <pre><code>import glob def check_possible(talent_ratio, cow_list, min_weight): """ check if the talent ratio possible with the min weight given the cow list Note that talent_ratio is possible if there is some set of cows with total weight at least min_weight and SUM (talent - talent_ratio*weight) &gt;= 0 We use a knapsack like algorithm to keep track of this ------- Inputs: talent_ratio is an integer expressing the ratio of talent we want to check min_weight is an integer expressing how large we force the weight to be cow_list is the list of cows should be a list of tuples (weight, talent) Return: true if the talent ratio is achievable false otherwise """ #max_talent[total_weight] will keep track of the the maximum value of # SUM (talent - talent_ratio*weight) #among all sets of cows with total weight exactly total_weight # #max_talent[min_weight] represents the maximum value of # SUM (talent - talent_ratio*weight) #among all sets of cows with total weight at least min_weight max_talent = ["no_value" for total_weight in range(min_weight+1)] max_talent[0] = 0 number_cows = len(cow_list) #Knapsack type algorithm to compute max_talent[total_weight] for cow in range(number_cows): talent = cow_list[cow][1] weight = cow_list[cow][0] value = talent - talent_ratio*weight for heaviness in range(min_weight,-1,-1): #loop backwards to avoid using individual cows more than once. #For example, say our max_talent[1] was 10 cow 1. #this would be computed at heaviness=0. #But then at heaviness=1 we add cow 1's max talent again, #giving max_talent[2] = 20, but using cow 1 twice. new_weight = min(heaviness+weight, min_weight) #only update if there's a value already for heaviness if max_talent[heaviness] != "no_value": if max_talent[new_weight] == "no_value": max_talent[new_weight] = max_talent[heaviness]+value elif max_talent[heaviness]+value &gt; max_talent[new_weight]: max_talent[new_weight] = max_talent[heaviness]+value return max_talent[min_weight] &gt;= 0 def process_inputs(data): """ Take the input data from file and turn it into a list of lists of ints, and two ints telling us how many cows we have and the min weight. ------- Inputs: data is a file object. Returns: num_cows -- the number of cows we have in total, an INT min_weight -- the minimum weight our cows must have, an INT cow_list -- A list of tuples representing cows. Each tuple describes a cow by (weight, talent) """ lines = data.readlines() #turn the lines into a list of list ints cow_list=[list(map(int,line.split())) for line in lines] num_cows, min_weight = cow_list[0] cow_list.pop(0) return num_cows, min_weight, cow_list inputs = glob.glob("*.in") for input in inputs: with open(input) as data: num_cows, min_weight, cow_list = process_inputs(data) max_talent = 0 #binary search through possible values of floor(1000*max_talent) top = int(1000*max([cow[1]/cow[0] for cow in cow_list])) bottom = 0 while(top &gt; bottom + 1): middle = int((top + bottom)/2) if check_possible(middle/1000, cow_list, min_weight): bottom = middle else: top = middle max_talent = bottom print(max_talent) </code></pre>
195672
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-02T02:05:09.527", "Id": "195672", "Score": "4", "Tags": [ "python", "programming-challenge", "knapsack-problem" ], "Title": "Find subset with largest talent to weight ratio, subject to minimum weight" }
{ "body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>The code would be easier to test if there were a function with a specification like this:</p>\n\n<pre><code>def max_talent_to_weight_ratio(min_weight, cow_list):\n \"\"\"Return the maximum of int(1000 * sum(talent) / sum(weight)) for a\n subset of cows with total weight at least min_weight, each cow\n being represented as a pair (weight, talent).\n\n \"\"\"\n</code></pre>\n\n<p>Then it would be easy to run test cases:</p>\n\n<pre><code>&gt;&gt;&gt; max_talent_to_weight_ratio(15, [(20, 21), (10, 11), (30, 31)])\n1066\n</code></pre></li>\n<li><p>Instead of looking up the elements of a tuple by number:</p>\n\n<pre><code>talent = cow_list[cow][1]\nweight = cow_list[cow][0]\n</code></pre>\n\n<p>use <em>tuple assignment</em>:</p>\n\n<pre><code>weight, talent = cow_list[cow]\n</code></pre></li>\n<li><p>Instead of iterating over the indexes into a list:</p>\n\n<pre><code>number_cows = len(cow_list)\nfor cow in range(number_cows):\n # code using cow_list[cow]\n</code></pre>\n\n<p>iterate over the elements of the list directly:</p>\n\n<pre><code>for cow in cow_list:\n # code using cow\n</code></pre>\n\n<p>or better still, combine this with tuple assignment:</p>\n\n<pre><code>for weight, talent in cow_list:\n</code></pre></li>\n<li><p>When iterating backwards:</p>\n\n<pre><code>for heaviness in range(min_weight,-1,-1):\n</code></pre>\n\n<p>it's often clearer to use <a href=\"https://docs.python.org/3/library/functions.html#reversed\" rel=\"nofollow noreferrer\"><code>reversed</code></a>:</p>\n\n<pre><code>for heaviness in reversed(range(min_weight + 1)):\n</code></pre></li>\n<li><p>I think a name like <code>old_weight</code> would be clearer than <code>heaviness</code>.</p></li>\n<li><p>Where the code has two conditions but both of the bodies are the same:</p>\n\n<pre><code>if max_talent[new_weight] == \"no_value\":\n max_talent[new_weight] = max_talent[heaviness]+value\nelif max_talent[heaviness]+value &gt; max_talent[new_weight]: \n max_talent[new_weight] = max_talent[heaviness]+value\n</code></pre>\n\n<p>the two conditions can be combined into one, using <code>or</code>:</p>\n\n<pre><code>new_value = max_talent[old_weight] + value\nif (max_talent[new_weight] == \"no_value\"\n or new_value &gt; max_talent[new_weight]):\n max_talent[new_weight] = new_value\n</code></pre></li>\n<li><p>The need for the special case of <code>\"no_value\"</code> can be avoided by representing <code>max_talent</code> as a mapping from total weight to value (instead of a list), like this:</p>\n\n<pre><code># Mapping from total weight to maximum value.\nmax_talent = {0: 0}\n</code></pre>\n\n<p>And then the lack of a value corresponds to the lack of a key in the mapping:</p>\n\n<pre><code>if old_weight in max_talent:\n new_value = max_talent[old_weight] + value\n if (new_weight not in max_talent\n or new_value &gt; max_talent[new_weight]):\n max_talent[new_weight] = new_value\n</code></pre>\n\n<p>But now the need to test <code>new_weight not in max_talent</code> can be avoided by using <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a>:</p>\n\n<pre><code># Mapping from total weight to maximum value.\nmax_talent = defaultdict(lambda:0)\nmax_talent[0] = 0\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>if old_weight in max_talent:\n max_talent[new_weight] = max(max_talent[new_weight], max_talent[old_weight] + value)\n</code></pre></li>\n<li><p>There is nothing about the problem that is specific to cows, so I think it would be less distracting for the reader if the code used abstract terminology. I would use \"item\" instead of \"cow\" and \"score\" instead of \"talent\".</p></li>\n</ol>\n\n<h3>2. Improved algorithm</h3>\n\n<p>Before working on an algorithm like this it's worth doing a bit of analysis to see if there are any properties of the solution that might come in useful.</p>\n\n<p>Let's start with some notation. Suppose that \\$I\\$ is a team (a set of cows). Define \\$W(I) = \\sum_{i∈I} w_i\\$ to be the total weight of the team, \\$T(I) = \\sum_{i∈I} t_i\\$ to be the total talent of the team, and \\$R(I) = {T(I) \\over W(I)}\\$ to be the ratio of total talent to total weight of the team.</p>\n\n<p>Write \\$w\\$ for the minimum total weight needed to win, and say that a team \\$I\\$ is \"winning\" if \\$W(I) ≥ w\\$ and \\$R(I)\\$ is the maximum among all teams meeting the weight requirement. Note that there might be multiple winning teams if several teams have the same ratio.</p>\n\n<p>Let \\$J\\$ be the winning team with the smallest total weight. Consider the weakest cow in the team, that is, the cow \\$j∈J\\$ with the smallest value of \\$R(\\{j\\})\\$, and let \\$J′ = J \\setminus \\{j\\}\\$ be the team with \\$j\\$ removed.</p>\n\n<p>Now either \\$J′\\$ is empty, in which case \\$W(J′) = 0 &lt; w\\$ and so \\$J′\\$ is not a winning team, or else \\$J′\\$ is non-empty, in which case \\$R(J′) ≥ R(J)\\$, since \\$j\\$ was the weakest cow and so removing it improves the overall talent-to-weight ratio. In the latter case it follows that \\$W(J′) &lt; w\\$, otherwise \\$J′\\$ would be a winning team with a smaller total weight, contrary to hypothesis.</p>\n\n<p>What this means is that there exists a winning team with the property that we can't remove the weakest cow from the team without going under the minimum total weight. And this means that if we follow the dynamic programming approach, but taking the cows in descending order of their talent-to-weight ratio, then we can never need to add another cow to a team that is already at or over the minimum weight. (Because such a cow would be the weakest cow in the new team, and so could be removed without hurting the team as explained above.)</p>\n\n<p>This means that we avoid the need for the adjustment of the talent (<code>value = talent - talent_ratio*weight</code>): we can just store the total talent. And more importantly, we avoid the need for a binary search, since just one application of the knapsack algorithm finds the result.</p>\n\n<h3>3. Revised code</h3>\n\n<pre><code>from collections import defaultdict\nfrom fractions import Fraction\nfrom itertools import product\n\ndef max_score_to_weight_ratio(min_weight, items):\n \"\"\"Return the maximum of sum(score) / sum(weight) for a subset of\n items with total weight at least min_weight, each item being\n represented as a pair (weight, score).\n\n \"\"\"\n # Sort items into descending order by score-to-weight ratio.\n items = sorted(items, key=lambda it: Fraction(it[1], it[0]), reverse=True)\n\n # Mapping from total weight to best (maximum) total score for a\n # subset of items with that weight.\n best = defaultdict(lambda:0)\n best[0] = 0\n\n for (w, s), old_w in product(items, reversed(range(min_weight))):\n if old_w in best:\n new_w = old_w + w\n best[new_w] = max(best[new_w], best[old_w] + s)\n\n return max(Fraction(s, w) for w, s in best.items() if w &gt;= min_weight)\n</code></pre>\n\n<p>Notes</p>\n\n<ol>\n<li><p>This implementation returns the best ratio itself, not <code>int(1000 * ratio)</code>. The reason for doing it this way is that the former is easy to explain, and the latter is an artificial condition of the USACO challenge, and not inherent to the problem. It would be easy enough to add a small wrapper function for the actual challenge if you needed to.</p></li>\n<li><p>The ratios are represented as fractions using the <a href=\"https://docs.python.org/3/library/fractions.html#fractions.Fraction\" rel=\"nofollow noreferrer\"><code>fractions.Fraction</code></a> class. This avoids the need to worry about possible loss of precision when doing floating-point division: a fraction object represents an exact ratio of integers.</p></li>\n<li><p>The code uses <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product</code></a> to combine two loops into one. This saves a level of indentation.</p></li>\n<li><p>I've abbreviated variable names within loops in order to keep expressions on one line and to make the structure of the code clear. This kind of abbreviation would be a poor idea in a large block of code, but within a loop of four lines I think it's easy enough to remember that <code>w</code> represents weight and <code>s</code> represents score.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-04T18:50:45.483", "Id": "377085", "Score": "0", "body": "note that `defaultdict(lambda:0)` can be `defaultdict(int)`, or maybe you can use `collections.Counter`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-04T18:56:31.780", "Id": "377088", "Score": "0", "body": "it's just that it's better to avoid `lambda` when a function already does the job." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-04T11:15:19.057", "Id": "195803", "ParentId": "195672", "Score": "4" } }
<p>I have two models in Flask-SQLAlchemy (<strong>Post</strong> and <strong>Comment</strong>) that have many-to-many relationship that is manifested in the third model (<strong>post_mentions</strong>):</p> <pre><code>post_mentions = db.Table( 'post_mentions', db.Column('post_id', db.Integer, db.ForeignKey('posts.id'), primary_key=True), db.Column('comment_id', db.Integer, db.ForeignKey('comments.id'), primary_key=True), ) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True, nullable=False) mentions = db.relationship('Comment', secondary=post_mentions, lazy='dynamic') def __eq__(self, other): return self.name.lower() == other.name.lower() def __hash__(self): return hash(self.name.lower()) class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text, nullable=False) created_at = db.Column(db.Integer, nullable=False) </code></pre> <p>There is also a <strong>/posts</strong> endpoint that triggers the following query:</p> <pre><code># flask and other imports @app.route('/posts') def posts(): page_num = request.args.get('page', 1) posts = models.Post.query.join(models.post_mentions)\ .group_by(models.post_mentions.columns.post_id)\ .order_by(func.count(models.post_mentions.columns.post_id).desc())\ .paginate(page=int(page_num), per_page=25) return render_template('posts.html', posts=posts) </code></pre> <p>There are more than 14k+ posts and 32k+ comments stored in SQLite database. As you can see from the snippet above, when someone hits <strong>/posts</strong> endpoint, SQLAlchemy loads all data at once to the memory and then subsequent queries (e.g. retrieving posts, comments to that posts, etc..) take sub-millisecond time, since data is being served from the memory without hitting the database. Initial load takes 10s+ on my laptop, which is, to put it mildly, suboptimal. </p> <p>So the question is: Considering that users won't view 97+% of posts, how can I both order posts by number of mentions in comments and load them on demand instead of doing it in one swoop? </p>
196034
BAD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-07T13:14:58.373", "Id": "196034", "Score": "3", "Tags": [ "python", "flask", "sqlalchemy" ], "Title": "Slow Flask-SQLAlchemy query using association tables" }
{ "body": "<p>Saw your post on indiehackers. I don't know this orm, but generally speaking, I see you have two options.</p>\n\n<p>Decide to preload/precache the data when your app starts and refresh it occasionally, if you insist on having all records available. </p>\n\n<p>But some good advice I've read is : never do in real time what you can do in advance. So... Why not even build some \"top posts\" table and seed that?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-09T16:05:11.573", "Id": "196165", "ParentId": "196034", "Score": "1" } }
<p>I built a GUI tool that takes excel files and outputs a finished report to help automate a report at work. It was a fantastic learning experienced and I feel much more comfortable with pandas and python, but I am very aware of some bad programming practices I have included.</p> <p>I am self taught, and a little stuck on what I should focus on how to improve my program, I'm just looking to be pointed in the right direction.</p> <p>Most of the program is wrapped into one "Try/Except" block. I'm really not experienced enough to know what else I can do to improve it, aside from implementing some DRY and wrapping part of the program into a function so its not repeated for multiple files.</p> <p>Could a pandas guru or python guru give me a nudge in the right direction? I'm hitting a block on best practices to implement.</p> <pre><code>import Tkinter import pandas as pd import xlsxwriter class simpleapp_tk(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() # Create the grid #Label for entering filename label_one = Tkinter.Label(self, text="Please Enter a Filename:",anchor="w",fg="black", font="Times_New_Roman 10 bold") label_one.grid(column=0,row=1,sticky='W') #Label for entering filename label_one2 = Tkinter.Label(self, text="Please Enter a 2nd Filename:",anchor="w",fg="black", font="Times_New_Roman 10 bold") label_one2.grid(column=0,row=2,sticky='W') #Example label label_two = Tkinter.Label(self, text="RXInfoAug1.xlsx",anchor="center",fg="black", font="Times_New_Roman 10") label_two.grid(column=1,row=3,sticky='EW') #Creating label area for user information. label_three = Tkinter.Label(self, text="Please select User:",anchor='w',fg='black', font="Times_New_Roman 10 bold") label_three.grid(column=0,row=4,sticky='EW') #Label four is for EXAMPLE text label_four = Tkinter.Label(self,text="Example:",anchor='w',fg='black', font="Times_New_Roman 10 bold") label_four.grid(column=0,row=3,sticky='W') #Label five is below Generate RX report, spits out result information. label_five = Tkinter.Label(self,text="----------Result Info----------",anchor='center', fg='black',font="Times_New_Roman 10 bold") label_five.grid(column=0,row=6,sticky='EW',columnspan=2) #Label six is return information after clicking the button self.labelVariable_six = Tkinter.StringVar() #have to create a variable to return label_six = Tkinter.Label(self,text="None",anchor='center',fg='white',bg="blue", font='Times_New_Roman 10 bold', textvariable=self.labelVariable_six) #notice the return variable label_six.grid(column=0,row=8,sticky='EW',columnspan=2) #Label seven is more return information, pertaining to after you click the button. self.labelVariable_seven = Tkinter.StringVar() #creating the return variable label_seven = Tkinter.Label(self,text="None",anchor='center',fg='white',bg='blue', font='Times_New_Roman 10 bold', textvariable=self.labelVariable_seven) label_seven.grid(column=0,row=9,sticky='EW',columnspan=2) #Entry Variable creation and location set. self.entryVariable = Tkinter.StringVar() self.entry = Tkinter.Entry(self,textvariable=self.entryVariable) #NOTICE the entry var name self.entry.grid(column=1,row=1,sticky='EW') #Entry Variable2 creation and location set. self.entryVariable2 = Tkinter.StringVar() self.entry2 = Tkinter.Entry(self,textvariable=self.entryVariable2) #NOTICE the entry var name self.entry2.grid(column=1,row=2,sticky='EW') #Creating the variable of which user used by option menu self.var = Tkinter.StringVar(self) self.var.set("User") #Creating a drop down menu for user selection self.option_menu = Tkinter.OptionMenu(self, self.var, "Corey","Warwick","Jane", "Jacque") self.option_menu.grid(column=1,row=4,sticky='EW') #Button to generate reports - When clicked runs OnButtonClick button = Tkinter.Button(self,text="Generate RX Report", font="Times_New_Roman 12 bold", command=self.OnButtonClick) button.grid(column=0,row=6,sticky="EW",columnspan=2) #Layout management area self.grid_columnconfigure(0,weight=1) self.grid_columnconfigure(1,weight=1) #Layout Manager resizes if you adjust window self.resizable(True,True) self.update() #sets canvas size (Length, depth) self.geometry("320x170+300+300") self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) self.entry2.selection_range(0, Tkinter.END) def OnButtonClick(self): UserName = self.var.get() FileName = self.entryVariable.get() if len(self.entryVariable2.get()) &gt; 0: FileName2 = self.entryVariable2.get() else: FileName2 = self.entryVariable.get() if UserName == "User": self.labelVariable_six.set("Please select a User before Continuing") self.labelVariable_seven.set("") elif UserName == "Corey": FilePath = "\cashley\Desktop\\" self.labelVariable_six.set("Welcome Corey, enjoy the report.") self.labelVariable_seven.set("Output file is located on desktop") writer = pd.ExcelWriter('C:\\Users\\cashley\\Desktop\\RX_STATS.xlsx') elif UserName == "Warwick": FilePath = "\wbarlow.GMSPRIMARY\Desktop\\" self.labelVariable_six.set("Welcome Warwick, always great to see you") self.labelVariable_seven.set("Output file is RX_STATS located on desktop") writer = pd.ExcelWriter('C:\\Users\\wbarlow.GMSPRIMARY\\Desktop\\RX_STATS.xlsx') elif UserName == "Jane": FilePath = "\janen.GMSPRIMARY\Desktop\\" self.labelVariable_six.set("Welcome Jane, enjoy the report") self.labelVariable_seven.set("Output file is RX_STATS located on desktop") writer = pd.ExcelWriter('C:\\Users\\janen.GMSPRIMARY\\Desktop\\RX_STATS.xlsx') elif UserName == "Jacque": FilePath = "\jacquea\Desktop\\" self.labelVariable_six.set("Welcome Jacquea, enjoy the report") self.labelVariable_seven.set("Output file is RX_STATS located on desktop") writer = pd.ExcelWriter('C:\\Users\\jacquea\\Desktop\\RX_STATS.xlsx') try: df = pd.read_excel("C:\Users" + FilePath + FileName) #DF_C Was added in so you can bring two files in to compare the two. df_C = pd.read_excel("C:\Users" + FilePath + FileName2) df.columns = ['GROUP','MEMBER_NAME','DRUG','CLAIM_DATE','SUB_QUANT','DAYS_SUPPLY','COPAY_AMT','TOTAL_COST'] df_C.columns = ['GROUP','MEMBER_NAME','DRUG','CLAIM_DATE','SUB_QUANT','DAYS_SUPPLY','COPAY_AMT','TOTAL_COST'] df['GROUP'] = df['GROUP'].astype(str) df_C['GROUP'] = df_C['GROUP'].astype(str) total_expense = df['TOTAL_COST'].sum() Y = total_expense * .80 df['PERCENT'] = (df['TOTAL_COST'] / total_expense).round(4) #Bad DRY here but metrics for analysis for df_C total_expense_C = df_C['TOTAL_COST'].sum() Y_C = total_expense_C * .80 df_C['PERCENT'] = (df_C['TOTAL_COST'] / total_expense_C).round(4) emp_dict = { 'FAKELASTNAME, FAKEFIRSTNAME': 'REDACTED1', 'BOB, FAKE': 'REDACTED2', 'SARAH, FAKE': 'REDACTED3', } df['MEMBER_NAME'].replace(emp_dict, inplace=True) df.loc[df.DRUG.isin(['LATUDA TAB 20MG', 'LATUDA TAB 60MG','LATUDA TAB 40MG']), 'DRUG'] = 'LATUDA TAB' df.loc[df.DRUG.isin(['HUMIRA START KIT 40MG PEN', 'HUMIRA PEN INJ 40MG/0.8','HUMIRA KIT 40MG SYN']), 'DRUG'] = 'HUMIRA' df.loc[df.DRUG.isin(['ENBREL SCLIK SYR 50MG/ML', 'ENBREL SYR 50MG/ML','ENBREL SYR 25/0.5ML']), 'DRUG'] = 'ENBREL' df.loc[df.DRUG.isin(['TRULICITY(4) PEN 1.5/0.5', 'TRULICITY(4) PEN 0.75/0.5']), 'DRUG'] = 'TRULICITY' df_C['MEMBER_NAME'].replace(emp_dict, inplace=True) df_C.loc[df_C.DRUG.isin(['LATUDA TAB 20MG', 'LATUDA TAB 60MG','LATUDA TAB 40MG']), 'DRUG'] = 'LATUDA TAB' df_C.loc[df_C.DRUG.isin(['HUMIRA START KIT 40MG PEN', 'HUMIRA PEN INJ 40MG/0.8','HUMIRA KIT 40MG SYN']), 'DRUG'] = 'HUMIRA' df_C.loc[df_C.DRUG.isin(['ENBREL SCLIK SYR 50MG/ML', 'ENBREL SYR 50MG/ML','ENBREL SYR 25/0.5ML']), 'DRUG'] = 'ENBREL' df_C.loc[df_C.DRUG.isin(['TRULICITY(4) PEN 1.5/0.5', 'TRULICITY(4) PEN 0.75/0.5']), 'DRUG'] = 'TRULICITY' df2 = df['TOTAL_COST'].groupby(df['MEMBER_NAME']).sum().nlargest(10) df3 = df['TOTAL_COST'].groupby(df['DRUG']).sum().nlargest(20) df4 = df['MEMBER_NAME'].value_counts().nlargest(20) df5 = df['PERCENT'].groupby(df['MEMBER_NAME']).sum().nlargest(20) df7 = df[df['TOTAL_COST'] &gt; 0] df8 = df['TOTAL_COST'].groupby(df['MEMBER_NAME']).sum().nlargest(1000) df13 = df['TOTAL_COST'].groupby(df['GROUP']).sum().nlargest(5) count = 0 total = 0 for row in df8: if total &lt; Y: total = total + row count += 1 WW = count #Count of how many Members are in the file. It combines duplicate individuals with nunique. Ind_count = df['MEMBER_NAME'].nunique() # Count of non zero individuals in the file. Ind_count_nonzero = df7['MEMBER_NAME'].nunique() # Finding what 20 percent of the total is twenty_percent1 = Ind_count_nonzero * .20 twenty_percent = round(twenty_percent1,0) row_count = df.shape[0] df10 = df['PERCENT'].groupby(df['MEMBER_NAME']).sum().nlargest(WW) group_dict = { '2006':'GROUPNAME1', '2033':'GROUPNAME2', '2041':'GROUPNAME3', } df['GROUP'].replace(group_dict, inplace=True) df_C['GROUP'].replace(group_dict, inplace=True) df15 = df_C[~df_C.MEMBER_NAME.isin(df.MEMBER_NAME)] pivot_C = pd.pivot_table(df15, index=['MEMBER_NAME','GROUP'],values=['TOTAL_COST'], aggfunc='sum') pivot_C2 = pivot_C.sort_values(by=['TOTAL_COST'],ascending=False) pv_C = pivot_C2.head(20) pv_C2 = pv_C.reset_index() df13 = df['TOTAL_COST'].groupby(df['GROUP']).sum().nlargest(5) df3 = df3.reset_index() df2 = df2.reset_index() df4 = df4.reset_index() df5 = df5.reset_index() df10 = df10.reset_index() df13 = df13.reset_index() pivot2 = pd.pivot_table(df, index=['MEMBER_NAME','GROUP'],values=['TOTAL_COST'], aggfunc='sum') pivot3 = pivot2.sort_values(by=['TOTAL_COST'],ascending=False) pv3 = pivot3.head(20) pv4 = pv3.reset_index() writer = pd.ExcelWriter('C:\\Users' + FilePath + 'RX_STATS.xlsx') #writer = pd.ExcelWriter('C:\\Users\\wbarlow.GMSPRIMARY\\Desktop\\RX_STATS.xlsx') pv4.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=0,startrow=10) pv_C2.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=0,startrow=35) df3.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=4,startrow=10) df4.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=7,startrow=10) df10.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=10,startrow=10) df13.to_excel(writer, sheet_name='Summary',index=False,header=True,startcol=4,startrow=0) df.to_excel(writer, sheet_name='Raw Data',index=False,header=True) df_C.to_excel(writer, sheet_name='Compare Data',index=False,header=True) worksheet1 = writer.sheets['Summary'] worksheet2 = writer.sheets['Raw Data'] worksheet3 = writer.sheets['Compare Data'] workbook = writer.book format1 = workbook.add_format({'num_format':'$#,###.##'}) format6 = workbook.add_format({'num_format':'$#,###.##','bold':True}) format2 = workbook.add_format({'bold': True}) format5 = workbook.add_format({'bold': True,'border':1,'align':'center'}) format3 = workbook.add_format({'bold': True, 'align': 'center'}) format4 = workbook.add_format({'num_format':'0.00%'}) merge_format = workbook.add_format({ 'bold':1, 'border':1, 'align':'center'}) worksheet1.write('A1', "Caremark File Statistics", format2) worksheet1.write('A6', "Individual Count:", format2) worksheet1.write('A3', "Individual Non-Zero Count:", format2) worksheet1.write('A4', "Twenty percent of all individuals:", format2) worksheet1.write('A5', "Count representing eighty percent:", format2) worksheet1.write('A2', "RX Total Expense:", format2) worksheet1.write('B6', Ind_count, format2) worksheet1.write('B3', Ind_count_nonzero, format2) worksheet1.write('B4', twenty_percent, format2) worksheet1.write('B5', WW, format2) worksheet1.write('B2', total_expense, format6) worksheet1.conditional_format('C12:C31',{'type':'cell', 'criteria':'&gt;=', 'value':1, 'format':format1}) worksheet1.conditional_format('F12:F31',{'type':'cell', 'criteria':'&gt;=', 'value':1, 'format':format1}) worksheet1.conditional_format(11,11,11+WW,11,{'type':'cell', 'criteria':'&gt;=', 'value':0, 'format':format4}) worksheet1.conditional_format('F2:F6',{'type':'cell', 'criteria':'&gt;=', 'value':0, 'format':format1}) worksheet2.conditional_format(1,8,row_count,8,{'type':'cell', 'criteria':'&gt;=', 'value':0, 'format':format4}) worksheet3.conditional_format(1,8,row_count,8,{'type':'cell', 'criteria':'&gt;=', 'value':0, 'format':format4}) worksheet1.conditional_format('C37:C56',{'type':'cell', 'criteria':'&gt;=', 'value':1, 'format':format1}) worksheet1.set_column(0,0,32) worksheet1.set_column(1,1,35) worksheet1.set_column(2,2,12) worksheet1.set_column(3,3,5) worksheet1.set_column(4,4,36) worksheet1.set_column(5,5,12) worksheet1.set_column(6,6,5) worksheet1.set_column(7,7,30) worksheet1.set_column(8,8,12) worksheet1.set_column(9,9,5) worksheet1.set_column(10,10,30) worksheet1.set_column(11,11,12) worksheet2.set_column(0,0,35) worksheet2.set_column(1,1,30) worksheet2.set_column(2,2,35) worksheet2.set_column(3,3,20) worksheet2.set_column(4,4,13) worksheet2.set_column(5,5,13) worksheet2.set_column(6,6,13) worksheet2.set_column(7,7,13) worksheet2.set_column(8,8,9) worksheet3.set_column(0,0,35) worksheet3.set_column(1,1,30) worksheet3.set_column(2,2,35) worksheet3.set_column(3,3,20) worksheet3.set_column(4,4,13) worksheet3.set_column(5,5,13) worksheet3.set_column(6,6,13) worksheet3.set_column(7,7,13) worksheet3.set_column(8,8,9) worksheet1.merge_range('A9:C9','Top Twenty Expense Individuals',merge_format) worksheet1.merge_range('E9:F9','Top Twenty RX Prescriptions', merge_format) worksheet1.merge_range('H9:I9','Top Twenty Prescription Fills Per Person', merge_format) worksheet1.merge_range('K9:L9','Individuals Representing 80% of Total Cost', merge_format) worksheet1.merge_range('A34:C34','New Individuals with Largest RX Totals', merge_format) worksheet1.write('H11', 'MEMBER_NAME', format5) worksheet1.write('I11','COUNT',format5) worksheet1.write('E1','LARGEST RX GROUPS',format5) worksheet1.write('A36','MEMBER NAME', format5) writer.save() self.entry.focus_set() self.entry.selection_range(0, Tkinter.END) except: self.labelVariable_six.set("Confirm User is accurate.") self.labelVariable_seven.set("Confirm your filename.") if __name__ == "__main__": app = simpleapp_tk(None) app.title('WB Caremark Cleaner') app.mainloop() </code></pre>
200425
GOOD_ANSWER
{ "AcceptedAnswerId": "200885", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-27T15:04:35.727", "Id": "200425", "Score": "4", "Tags": [ "python", "beginner", "pandas", "tkinter" ], "Title": "Pandas/Tkinter GUI Excel report generator" }
{ "body": "<p>To get this working for Python 3, I needed to change:</p>\n\n<pre><code>import Tkinter\nclass simpleapp_tk(Tkinter.Tk):\n</code></pre>\n\n<p>to</p>\n\n<pre><code>import tkinter\nclass simpleapp_tk(tkinter.Tk):\n</code></pre>\n\n<p>So just a lower case for tkinter (a global search/replace). Warwick, you have a lot of code in one big class!<br>\nThe creation and formatting of the worksheet can be extracted into another function external to the <code>simpleapp_tk</code> class.</p>\n\n<p>For example, if you were going to do that, the code inside the <code>onButtonClick</code> should look like:</p>\n\n<pre><code> result = make_me_a_spreadsheet(file_name, file_name2)\n if result:\n self.entry.focus_set()\n self.entry.selection_range(0, tkinter.END)\n else:\n self.label_variable_six.set(\"Confirm User is accurate.\")\n self.label_variable_seven.set(\"Confirm your filename.\")\n</code></pre>\n\n<p>With the start of the excel creation function starting like:</p>\n\n<pre><code>def make_me_a_spreadsheet(filename_a, filename_b):\n try:\n df = pd.read_excel(filename_a) # r\"C:\\Users\" + FilePath + file_name)\n # ... etc\n</code></pre>\n\n<p>(I just did a cut/paste myself), and of course, the end of the spreadsheet creation function being like this:</p>\n\n<pre><code> writer.save()\n return True\n\nexcept:\n return None\n</code></pre>\n\n<p>the <code>return None</code> means that if there was an error creating the file inside the large <code>try/except block</code>, it will return an empty value to the GUI class. With <code>result</code> being nothing, the GUI will display the correct message (the same as you currently have it).</p>\n\n<p>Please have a go at making this change, and don't forget to make a backup of your code before changing it.</p>\n\n<p>You should encounter a minor bug or two, such as:</p>\n\n<pre><code>writer = pd.ExcelWriter(r'C:\\Users' + FilePath + 'RX_STATS.xlsx')\n</code></pre>\n\n<p>However I'm confident that you will be able to figure out any bugs. If you make this change, your code will be a smaller step towards being better. You will have separated the creation of the xlsx file from the GUI. In the future, if there is a problem when creating the spreadsheet, you know to look only at the <code>make_me_a_spreadsheet</code> function - and not at the GUI class. Much easier to track down bugs!</p>\n\n<p>You can follow this methodology to improve your code, that is, extracting specific steps/actions into a separate function (with passing values in and passing them out). Please see some of the other Python examples people offer on Code Review to get more ideas.</p>\n\n<p>Good luck, hope this helps a little bit!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-06T12:50:01.050", "Id": "387223", "Score": "0", "body": "Thank you so much for your input, it is a massive help, ill get started on implementing these changes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-03T09:30:47.030", "Id": "200885", "ParentId": "200425", "Score": "1" } }
<p>I'm very new to python (been coding for about two days) and have created a programme that simulates blackjack games so that I can work out optimal strategy over many iterations.</p> <p>The problem is that when I run it, my CPU goes to about 99.8% and it freezes (I run in terminal) - Does anybody have any suggestions on how I can change my code so that it is less CPU intensive? - I'm looking to learn about what I've done wrong, the code is just a bit of fun!</p> <p>As I said I'm new to this and as such the code isn't very elegant, but it works just fine.</p> <pre><code>import random q = 0 #simple counter that will record the score of games over time win_count = 0 draw_count = 0 lose_count = 0 bust_count = 0 #User input for when the game is run, it will allow them to choose the number of games to be played (iterations) and also the score at which the player will hold. iterations = input('Number of iterations: ') hold_score = input('Hold score for the player: ') #defining the card values, suits and decks. for x in range(0, iterations): s2 = 2 s3 = 3 s4 = 4 s5 = 5 s6 = 6 s7 = 7 s8 = 8 s9 = 9 s10 = 10 sj = 10 sq = 10 sk = 10 sa = 11 c2 = 2 c3 = 3 c4 = 4 c5 = 5 c6 = 6 c7 = 7 c8 = 8 c9 = 9 c10 = 10 cj = 10 cq = 10 ck = 10 ca = 11 d2 = 2 d3 = 3 d4 = 4 d5 = 5 d6 = 6 d7 = 7 d8 = 8 d9 = 9 d10 = 10 dj = 10 dq = 10 dk = 10 da = 11 h2 = 2 h3 = 3 h4 = 4 h5 = 5 h6 = 6 h7 = 7 h8 = 8 h9 = 9 h10 = 10 hj = 10 hq = 10 hk = 10 ha = 11 spades = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa] clubs = [c2, c3, c4, c5, c6, c7, c7, c8, c9, c10, cj, cq, ck, ca] diamonds = [d2, d3, d4, d5, d6, d7, d8, d9, d10, dj, dq, dk, da] hearts = [h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] deck = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa, c2, c3, c4, c5, c6, c7, c8, c9, c10, cj, cq, ck, ca, d2, d3, d4, d5, d6, d7, d7, d8, d9, d10, dj, dq, dk, da, h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] deck_standard = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa, c2, c3, c4, c5, c6, c7, c8, c9, c10, cj, cq, ck, ca, d2, d3, d4, d5, d6, d7, d7, d8, d9, d10, dj, dq, dk, da, h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] #List for the cards the dealer and player holds dealer = [] user_1 = [] #Randomly gives the player and dealer two cards each - and then remove these cards from the deck of cards so it cannot be used again. card_1 = random.choice(deck) deck.remove(card_1) user_1.append(card_1) card_2 = random.choice(deck) deck.remove(card_2) dealer.append(card_2) card_3 = random.choice(deck) deck.remove(card_3) user_1.append(card_3) card_4 = random.choice(deck) deck.remove(card_4) dealer.append(card_4) #Calculates the number of cards the player/dealer has - also defines their scores to be zero. dealer_card_count = len(dealer) user_1_card_count = len(user_1) dealer_score = 0 user_1_score = 0 #Looks at the two cards each player has and calculates their score - then adds this score to their score. for x in range(0, dealer_card_count): dealer_score = dealer_score + int(dealer[x]) for x in range(0, user_1_card_count): user_1_score = user_1_score + int(user_1[x]) #code to say that if the user has less cards than the pre-defined hold score - give them another card and add that card to their score. while (int(user_1_score) &lt;= int(hold_score)): if (int(user_1_card_count)&lt;6): card_5 = random.choice(deck) deck.remove(card_5) user_1.append(card_5) user_1_score = 0 user_1_card_count = len(user_1) for x in range(0, user_1_card_count): user_1_score = user_1_score + int(user_1[x]) # sets the hold score for the dealer as that of the user (so that the dealer knows how high he has to aim for) hold_score_dealer = user_1_score # Same as above - but for the dealer. if (int(user_1_score) &lt; int(21)): while (int(dealer_score) &lt;= int(hold_score_dealer)): if (int(dealer_card_count)&lt;6): card_6 = random.choice(deck) deck.remove(card_6) dealer.append(card_6) dealer_score = 0 dealer_card_count = len(dealer) for x in range(0, dealer_card_count): dealer_score = dealer_score + int(dealer[x]) #code so that if the user or the dealer have 5 cards they win automatically (5 card rule) if (int(user_1_card_count) ==5): if (int(dealer_card_count) !=5): if (int(user_1_score)) &lt;22: win_count = win_count + 1 if (int(user_1_card_count) == 5): if (int(dealer_card_count) == 5): if (int(user_1_score) &lt; 22): if (int(dealer_score) &lt;22): draw_count = draw_count + 1 elif (int(user_1_score) &gt; 22): bust_count = bust_count + 1 if (int(dealer_card_count) == 5): if(int(user_1_card_count) != 5): if (int(dealer_score) &lt;22): lose_count = lose_count + 1 #Code to deal with all possible outcomes (assuming they don't have 5 cards) - and add to the counter. if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) &gt; int(dealer_score)): if (int(user_1_score) &lt; int(22)): win_count = win_count + 1 elif (int(user_1_score) &gt; int(21)): if (int(dealer_score) &lt; int(22)): lose_count = lose_count + 1 elif (int(user_1_score) &gt; int(21)): if (int(dealer_score) &gt; int (21)): draw_count = draw_count + 1 bust_count = bust_count + 1 elif (int(user_1_score) &lt; int(dealer_score)): if(int(user_1_score) &gt; 21): draw_count = draw_count + 1 bust_count = bust_count + 1 if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) == int(dealer_score)): if (int(user_1_score)) &lt; int(22): draw_count = draw_count + 1 elif (int(user_1_score) &gt; 21): draw_count = draw_count + 1 bust_count = bust_count + 1 if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) &lt; int(dealer_score)): if (int(dealer_score) &lt; int(22)): lose_count = lose_count + 1 elif (int(dealer_score) &gt; int(21)): if (int(user_1_score) &lt; int(22)): win_count = win_count + 1 #Code to print the progress of the iterations over time if (q == iterations * 0.2): print "20%" if (q == iterations * 0.4): print "40%" if (q == iterations * 0.6): print "60%" if (q == iterations * 0.8): print "80%" if (q == iterations * 1): print "100%" gc.collect() print q q = q + 1 # Code to print the final scores after all iterations are complete. print "Total iterations: " + str(iterations) print "*****" print "Win count : " + str(win_count) +" ("+ str((float(win_count))/float(iterations)*100) +"%)" print "Draw count : " + str(draw_count) +" ("+ str((float(draw_count))/float(iterations)*100) +"%)" print "Lose count : " + str(lose_count) +" ("+ str((float(lose_count))/float(iterations)*100) +"%)" print "Bust count : " + str(bust_count) +" ("+ str((float(bust_count))/float(iterations)*100) +"%)" print "" </code></pre>
201472
WIERD
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T17:01:28.373", "Id": "201472", "Score": "0", "Tags": [ "python", "python-3.x", "time-limit-exceeded", "playing-cards", "simulation" ], "Title": "Blackjack strategy simulation" }
{ "body": "<p>Take a look at these lines:</p>\n\n<pre><code>while (int(user_1_score) &lt;= int(hold_score)):\n if (int(user_1_card_count)&lt;6):\n</code></pre>\n\n<p>what happens if the player draws six cards and their score is still less than or equal to the hold score? For example, suppose the hold score is 15 and they draw 2♣ 2♦ 2♥ 2♠ 3♣ 3♦ so that their score is 14. What happens next?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-14T13:53:09.443", "Id": "201664", "ParentId": "201472", "Score": "1" } }
<p>I'm very new to python (been coding for about two days) and have created a programme that simulates blackjack games so that I can work out optimal strategy over many iterations.</p> <p>The problem is that when I run it, my CPU goes to about 99.8% and it freezes (I run in terminal) - Does anybody have any suggestions on how I can change my code so that it is less CPU intensive? - I'm looking to learn about what I've done wrong, the code is just a bit of fun!</p> <p>As I said I'm new to this and as such the code isn't very elegant, but it works just fine.</p> <pre><code>import random q = 0 #simple counter that will record the score of games over time win_count = 0 draw_count = 0 lose_count = 0 bust_count = 0 #User input for when the game is run, it will allow them to choose the number of games to be played (iterations) and also the score at which the player will hold. iterations = input('Number of iterations: ') hold_score = input('Hold score for the player: ') #defining the card values, suits and decks. for x in range(0, iterations): s2 = 2 s3 = 3 s4 = 4 s5 = 5 s6 = 6 s7 = 7 s8 = 8 s9 = 9 s10 = 10 sj = 10 sq = 10 sk = 10 sa = 11 c2 = 2 c3 = 3 c4 = 4 c5 = 5 c6 = 6 c7 = 7 c8 = 8 c9 = 9 c10 = 10 cj = 10 cq = 10 ck = 10 ca = 11 d2 = 2 d3 = 3 d4 = 4 d5 = 5 d6 = 6 d7 = 7 d8 = 8 d9 = 9 d10 = 10 dj = 10 dq = 10 dk = 10 da = 11 h2 = 2 h3 = 3 h4 = 4 h5 = 5 h6 = 6 h7 = 7 h8 = 8 h9 = 9 h10 = 10 hj = 10 hq = 10 hk = 10 ha = 11 spades = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa] clubs = [c2, c3, c4, c5, c6, c7, c7, c8, c9, c10, cj, cq, ck, ca] diamonds = [d2, d3, d4, d5, d6, d7, d8, d9, d10, dj, dq, dk, da] hearts = [h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] deck = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa, c2, c3, c4, c5, c6, c7, c8, c9, c10, cj, cq, ck, ca, d2, d3, d4, d5, d6, d7, d7, d8, d9, d10, dj, dq, dk, da, h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] deck_standard = [s2, s3, s4, s5, s6, s7, s8, s9, s10, sj, sq, sk, sa, c2, c3, c4, c5, c6, c7, c8, c9, c10, cj, cq, ck, ca, d2, d3, d4, d5, d6, d7, d7, d8, d9, d10, dj, dq, dk, da, h2, h3, h4, h5, h6, h7, h8, h9, h10, hj, hq, hk, ha] #List for the cards the dealer and player holds dealer = [] user_1 = [] #Randomly gives the player and dealer two cards each - and then remove these cards from the deck of cards so it cannot be used again. card_1 = random.choice(deck) deck.remove(card_1) user_1.append(card_1) card_2 = random.choice(deck) deck.remove(card_2) dealer.append(card_2) card_3 = random.choice(deck) deck.remove(card_3) user_1.append(card_3) card_4 = random.choice(deck) deck.remove(card_4) dealer.append(card_4) #Calculates the number of cards the player/dealer has - also defines their scores to be zero. dealer_card_count = len(dealer) user_1_card_count = len(user_1) dealer_score = 0 user_1_score = 0 #Looks at the two cards each player has and calculates their score - then adds this score to their score. for x in range(0, dealer_card_count): dealer_score = dealer_score + int(dealer[x]) for x in range(0, user_1_card_count): user_1_score = user_1_score + int(user_1[x]) #code to say that if the user has less cards than the pre-defined hold score - give them another card and add that card to their score. while (int(user_1_score) &lt;= int(hold_score)): if (int(user_1_card_count)&lt;6): card_5 = random.choice(deck) deck.remove(card_5) user_1.append(card_5) user_1_score = 0 user_1_card_count = len(user_1) for x in range(0, user_1_card_count): user_1_score = user_1_score + int(user_1[x]) # sets the hold score for the dealer as that of the user (so that the dealer knows how high he has to aim for) hold_score_dealer = user_1_score # Same as above - but for the dealer. if (int(user_1_score) &lt; int(21)): while (int(dealer_score) &lt;= int(hold_score_dealer)): if (int(dealer_card_count)&lt;6): card_6 = random.choice(deck) deck.remove(card_6) dealer.append(card_6) dealer_score = 0 dealer_card_count = len(dealer) for x in range(0, dealer_card_count): dealer_score = dealer_score + int(dealer[x]) #code so that if the user or the dealer have 5 cards they win automatically (5 card rule) if (int(user_1_card_count) ==5): if (int(dealer_card_count) !=5): if (int(user_1_score)) &lt;22: win_count = win_count + 1 if (int(user_1_card_count) == 5): if (int(dealer_card_count) == 5): if (int(user_1_score) &lt; 22): if (int(dealer_score) &lt;22): draw_count = draw_count + 1 elif (int(user_1_score) &gt; 22): bust_count = bust_count + 1 if (int(dealer_card_count) == 5): if(int(user_1_card_count) != 5): if (int(dealer_score) &lt;22): lose_count = lose_count + 1 #Code to deal with all possible outcomes (assuming they don't have 5 cards) - and add to the counter. if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) &gt; int(dealer_score)): if (int(user_1_score) &lt; int(22)): win_count = win_count + 1 elif (int(user_1_score) &gt; int(21)): if (int(dealer_score) &lt; int(22)): lose_count = lose_count + 1 elif (int(user_1_score) &gt; int(21)): if (int(dealer_score) &gt; int (21)): draw_count = draw_count + 1 bust_count = bust_count + 1 elif (int(user_1_score) &lt; int(dealer_score)): if(int(user_1_score) &gt; 21): draw_count = draw_count + 1 bust_count = bust_count + 1 if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) == int(dealer_score)): if (int(user_1_score)) &lt; int(22): draw_count = draw_count + 1 elif (int(user_1_score) &gt; 21): draw_count = draw_count + 1 bust_count = bust_count + 1 if (int(user_1_card_count) != 5): if (int(dealer_card_count) != 5): if (int(user_1_score) &lt; int(dealer_score)): if (int(dealer_score) &lt; int(22)): lose_count = lose_count + 1 elif (int(dealer_score) &gt; int(21)): if (int(user_1_score) &lt; int(22)): win_count = win_count + 1 #Code to print the progress of the iterations over time if (q == iterations * 0.2): print "20%" if (q == iterations * 0.4): print "40%" if (q == iterations * 0.6): print "60%" if (q == iterations * 0.8): print "80%" if (q == iterations * 1): print "100%" gc.collect() print q q = q + 1 # Code to print the final scores after all iterations are complete. print "Total iterations: " + str(iterations) print "*****" print "Win count : " + str(win_count) +" ("+ str((float(win_count))/float(iterations)*100) +"%)" print "Draw count : " + str(draw_count) +" ("+ str((float(draw_count))/float(iterations)*100) +"%)" print "Lose count : " + str(lose_count) +" ("+ str((float(lose_count))/float(iterations)*100) +"%)" print "Bust count : " + str(bust_count) +" ("+ str((float(bust_count))/float(iterations)*100) +"%)" print "" </code></pre>
201472
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-11T17:01:28.373", "Id": "201472", "Score": "0", "Tags": [ "python", "python-3.x", "time-limit-exceeded", "playing-cards", "simulation" ], "Title": "Blackjack strategy simulation" }
{ "body": "<p>In both the code listings I see so far, both yours OP, and vash_the_stampede’s code, all I see is an arbitrary card game that looks kinda like blackjack. Neither of which models it the same way. But I guess that’s me being pedantic since I actually dealt the game. </p>\n\n<p>As in vash’s code, it would be advisable to use a generating method to populate the deck. But I would do it a little differently than in their code. First of all, instead of just storing a number for the card in the array, I would at the very least also store a ‘isUsed’ flag that you toggle to take the card out of play, then you can just iterate over the deck setting all the ‘isUsed’ to false. This would save the memory allocation/deallocation every time you create or replenish a deck. </p>\n\n<p>Second, I would take advantage of the fact that you would be storing multiple pieces of information about the cards in the list, and make them into a class so that you can store a few things about the card, like suit, value, used, representation, and any more you can think of that may be of use. This will aid you in developing the program further, like making a graphical version of it for a screensaver ;)</p>\n\n<p>Third, the rules of blackjack:</p>\n\n<p>Each player is dealt 2 cards at the beginning of each hand, one at a time in order around the table starting with the player in the first position, and ending with the dealer. The dealer deals the first card face up, the second face down</p>\n\n<p>The player cards are added together, faces counted as 10, aces counted as either 11, or 1. </p>\n\n<p>When a player has an ace plus a face (counting 10s), they have a blackjack, which is paid 3 to 2. If the player has a blackjack and the dealer has an ace showing, offer insurance which costs the same as their original bet, if they take insurance and the dealer also has a blackjack, they are paid 1 to 1, else they lose the bet and the insurance. The dealer checks for blackjack. in this situation if they have a blackjack it is revealed, insurance pays, and all other hands lose. If they do not have blackjack, the insurance is forfeit, and play continues normally for the rest of the hand.</p>\n\n<p>When the dealer has an ace showing, and no players have a blackjack, they will check the hidden card without showing it, to see if they have a blackjack. If the dealer has a blackjack, all currently active hands lose.</p>\n\n<p>Starting with the first remaining player closest to the player 1 position, play resumes. The values of the players showing cards are added together, and the player is asked to either hit or stand, except in the special case which is below. Each time the player hits, they are given another card, which is added to their total. If the player busts (goes over 21), they lose immediately. If they hit 21, they cannot take any more cards, once they meet one of the preceding conditions, or have 5 cards the action goes to the next player. (Where I dealt, there is no 5 card rule)</p>\n\n<p>If a player has two of the same cards considering their card rank (Kings only count with other Kings, tens only other tens...) they may opt to split the cards by putting up another bet equal to the original bet, each split hand is played as a separate hand, and the player may have up to 4 hands. Any split then busted hands count towards this total.</p>\n\n<p>Once all the players hands have been played, and every player has opted to stand ending their action turn, it is the dealers action. The dealer reveals their face down card and plays according to a specific rule set:</p>\n\n<p>If the dealer shows a hard 17 or above (any hand that uses an ace as 11 is soft, any hand that uses aces only as 1s, or does not include an ace is hard. Aces can be demoted from 11 to 1 mid hand) the dealer will stand. If they show a soft 17 or below they will take another card. Also up to 5 cards total. If the dealer busts at this point, all remaining active hands are paid out 1 to 1. </p>\n\n<p>Once the dealer has reached a stand, their total is compared to each players showing value, in the opposite order of dealing. If the dealers total is higher, the hand loses and the bet is taken. If the dealers and players hands are the same value, the hand pushes, and the player keeps the bet. If the players total is higher, the player wins, and the bet isn’t paid 1 to 1.</p>\n\n<p>Most casinos consider blackjack a high volume game, and as such they use a multi deck shuffle of 6 or 8 decks in a shoe.</p>\n\n<p>Sorry not much of this was about code, but a blackjack solver should actually play the game correctly, Oh and one more thing. Deeply bested if statements are considered bad form, and can lead to some pretty serious overhead, but I think a lot of your problem is the memory alloc/dealloc. </p>\n\n<p>Plus, when you take cards from the deck, first check to see if they have been used, if used, get another card, if not used then give it to the player/dealer. That will save some cycles too.</p>\n\n<p>Just my two bits.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T22:12:21.573", "Id": "391243", "Score": "0", "body": "Hmm the point was to improve his code, maybe his intentions were different. Although I do frequent casinos, so my order of code accounted for how blackjacks play out, in the proper sequence of checking, except the fact if the dealer shows blackjack as well, counted it towards a draw. His code mentions no soft plays or splits, so didn't build on that. Again not trying to make a new game, just make his game better. All cards in play are removed from the deck in use, but I do like the flag idea over, regenerate the deck. Also yes I was thinking about multi-deck play the entire time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T22:12:42.287", "Id": "391244", "Score": "0", "body": "again though just was trying to spoof up his code verse make a entirely new game" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T23:20:49.007", "Id": "391257", "Score": "0", "body": "Well, I also had a bit of an underlying message to the way I set out the rules for the most part. I set them out in a way that would make it very easy to start at the top, and write code for each segment in order (mostly), and come out at the end with a program that logically emulates casino blackjack correctly. A kind of implementation detail specification if you will. ;) and as I mentioned, it is mostly me just being pedantic :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T00:18:39.427", "Id": "391260", "Score": "0", "body": "Of course, I guess I wasn’t being open minded to the fact it’s something your passionate about, if this was a code for how to do certain things I am passionate about I would have took the same approach as you, cheers :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-02T19:36:36.673", "Id": "202993", "ParentId": "201472", "Score": "0" } }
<p><strong>Question-</strong></p> <p>Generate all prime numbers between two given numbers.</p> <p><a href="https://www.spoj.com/problems/PRIME1/" rel="nofollow noreferrer">https://www.spoj.com/problems/PRIME1/</a></p> <p><strong>My attempt-</strong></p> <p>I used segmented sieve method.</p> <pre><code>t=int(input()) import math def segsieve(x): if x==1: return False for i in range(2,int(math.sqrt(x))+1): if x%i==0: return False return True while t&gt;0: f,l=map(int,input().split()) for j in range(f,l): a=segsieve(j) if a==True: print(j) t-=1 </code></pre> <p><strong>Issue-</strong></p> <p>I am getting time limit exceeded. How can I make it faster?</p>
202480
BAD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-25T20:02:00.157", "Id": "202480", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded", "primes" ], "Title": "Spoj-Prime Generator" }
{ "body": "<h1>Algorithm</h1>\n\n<h2>Hint</h2>\n\n<p>You don't need to check all integers between <code>2</code> and <code>int(math.sqrt(x))+1</code>. You only need to check primes between <code>2</code> and <code>int(math.sqrt(x))+1</code>.</p>\n\n<h1>Stylistic</h1>\n\n<h2><code>__main__</code></h2>\n\n<p>I would add a \"main function\" to your program. This is typically done in Python by:</p>\n\n<pre><code>def main():\n ...\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/20158605/667648\">this answer</a> for more reasons why this paradigm is followed.</p>\n\n<h2><code>sqrt</code></h2>\n\n<p>I technically have not measured the performance of <code>sqrt</code>, but I have more commonly seen your <code>for</code> loop written as:</p>\n\n<pre><code>while i * i &lt; x:\n ...\n</code></pre>\n\n<p>unlike the current:</p>\n\n<pre><code>for i in range(2,int(math.sqrt(x))+1):\n</code></pre>\n\n<p>No need to <code>import math</code> then.</p>\n\n<h2>PEP 8</h2>\n\n<p>According to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> style guide, you should add a space between the mathematical operations. So for instance, instead of:</p>\n\n<pre><code>if x%i==0:\n</code></pre>\n\n<p>it should be:</p>\n\n<pre><code>if x % i == 0:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-26T06:41:37.703", "Id": "390219", "Score": "0", "body": "In your hint it says basically: You don't need to do `A`, do `A` instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-26T06:42:43.443", "Id": "390220", "Score": "0", "body": "Umm your hint is saying what I have already done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-26T07:06:03.040", "Id": "390226", "Score": "0", "body": "@suyashsingh234 I may have miswrote, but do you check only primes between 2 and sqrt(x)? It looks like you check all integers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-26T07:06:31.527", "Id": "390228", "Score": "1", "body": "@Graipher See the comment. I forgot the word \"all integers\" in the first qualifier." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-08-26T02:06:37.127", "Id": "202492", "ParentId": "202480", "Score": "2" } }
<p>I was able to make a program that parse my samtools output file into a table that can be viewed easily in excel. While I was able to get the final result, is there a recommended improvements that be done for my code. I am trying to improve my python skills and transferring over from C and C++.</p> <p>The strategy I used was to split the data I need based on the "+" sign and make it into an array. Then select the elements of the array that were the information that I needed and write it to my file.</p> <h3>My example input:</h3> <pre><code>15051874 + 0 in total (QC-passed reads + QC-failed reads) 1998052 + 0 secondary 0 + 0 supplementary 0 + 0 duplicates 13457366 + 0 mapped (89.41% : N/A) 13053822 + 0 paired in sequencing 6526911 + 0 read1 6526911 + 0 read2 10670914 + 0 properly paired (81.75% : N/A) 10947288 + 0 with itself and mate mapped 512026 + 0 singletons (3.92% : N/A) 41524 + 0 with mate mapped to a different chr 31302 + 0 with mate mapped to a different chr (mapQ&gt;=5) </code></pre> <h3>My output:</h3> <pre><code>FileName Total Secondary Supplementary duplicates mapped paired in sequencing read1 read2 properly paired with itself and mate mapped singletons with mate mapped to a different chr with mate mapped to a different chr (mapQ&gt;=5) 10_HK_S22.merged.samtools.flag.txt 26541257 2332283 0 0 22895440 24208974 12104487 12104487 19003826 19632880 930277 69030 52261 </code></pre> <h3>My Program:</h3> <pre><code>outFile = open("output.count.txt", "w+") #windows platform add the r os.chdir(r"Susceptible\featurecounts") #open the output file to be able to write output. outFile.write("FileName\tTotal\tSecondary\tSupplementary\tduplicates\tmapped\tpaired in sequencing\tread1\t" "read2\tproperly paired\twith itself and mate mapped\tsingletons\twith mate mapped to a different chr\twith mate mapped to a different chr (mapQ&gt;=5)\n") #Iterate through files in directory with the following ending for file in glob.glob(".flag.txt"): #open file after retrieving the name. with open(file, 'r') as counts_file: #empty list/array for storing the outputs list = [] #add the file name to array. list.append(file) #get values from output file. for line in counts_file: list.append(line.split('+')[0]) #write list to file for item in list: outFile.write("%s\t" % item) #write a newline outFile.write("\n") #close the output file outFile.close() </code></pre>
204792
GOOD_ANSWER
{ "AcceptedAnswerId": "204796", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T17:41:37.777", "Id": "204792", "Score": "-2", "Tags": [ "python", "python-3.x" ], "Title": "Parsing of text file to a table" }
{ "body": "<p>Use <code>with ... as ...:</code> statements to open files, and automatically close them.\nThen you don't have to clutter up your program with explicit close statements.</p>\n\n<pre><code>outFile = open(\"output.count.txt\", \"w+\")\n\n# ... code here\n\n#close the output file \noutFile.close() \n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>with open(\"output.count.txt\", \"w+\") as outFile:\n\n # ... code here\n</code></pre>\n\n<hr>\n\n<p>This is ugly and unreadable:</p>\n\n<pre><code>outFile.write(\"FileName\\tTotal\\tSecondary\\tSupplementary\\tduplicates\\tmapped\\tpaired in sequencing\\tread1\\t\"\n \"read2\\tproperly paired\\twith itself and mate mapped\\tsingletons\\twith mate mapped to a different chr\\twith mate mapped to a different chr (mapQ&gt;=5)\\n\")\n</code></pre>\n\n<p>The <code>\\t</code> runs into the next field name, so the eye sees \"tTotal\".\nIt would be better to actually list your field names in a readable form,\nand let the computer properly separate them:</p>\n\n<pre><code>fields = [\"FileName\", \"Total\", \"Secondary\", \"Supplementary\", \"duplicates\", \"mapped\",\n \"paired in sequencing\", \"read1\", \"read2\", \"properly paired\",\n \"with itself and mate mapped\", \"singletons\", \"with mate mapped to a different chr\",\n \"with mate mapped to a different chr (mapQ&gt;=5)\"]\n\noutFile.write(\"\\t\".join(fields) + '\\n')\n</code></pre>\n\n<p>Looping through one iterable, processing each one and creating a new list be\noften done cleaner using list comprehension:</p>\n\n<pre><code> list = []\n #add the file name to array. \n list.append(file)\n #get values from output file.\n for line in counts_file:\n list.append(line.split('+')[0])\n</code></pre>\n\n<p>Could become (without the \"file\" at the start of the list):</p>\n\n<pre><code> values = [ line.split('+')[0] for line in counts_file ]\n</code></pre>\n\n<p>But you take the resulting list and add a <code>\\t</code> character between each value,\nso maybe instead:</p>\n\n<pre><code> values = \"\\t\".join( line.split('+')[0] for line in counts_file )\n</code></pre>\n\n<p>Now, you want to print out the values to the outFile, with the <code>file</code> at the start. f-strings are a new feature in Python. They let you format a string\nwith local variables interpolated into the string. This makes it easy:</p>\n\n<pre><code> outFile.write(f\"{file}\\t{values}\\n\")\n</code></pre>\n\n<p>As a bonus, each line doesn't end with a trailing tab character.</p>\n\n<hr>\n\n<p>Resulting code would be something like:</p>\n\n<pre><code>with open(\"output.count.txt\", \"w+\") as outFile:\n\n fields = [\"FileName\", \"Total\", \"Secondary\", \"Supplementary\", \"duplicates\", \"mapped\",\n \"paired in sequencing\", \"read1\", \"read2\", \"properly paired\",\n \"with itself and mate mapped\", \"singletons\", \"with mate mapped to a different chr\",\n \"with mate mapped to a different chr (mapQ&gt;=5)\"]\n\n outFile.write(\"\\t\".join(fields) + '\\n')\n\n for file in glob.glob(\".flag.txt\"):\n with open(file, 'r') as counts_file:\n values = \"\\t\".join( line.split('+')[0] for line in counts_file )\n outFile.write(f\"{file}\\t{values}\\n\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T08:40:19.307", "Id": "395052", "Score": "1", "body": "Note: string interpolation is present in python from [version 3.6](https://www.python.org/dev/peps/pep-0498/)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T18:38:20.257", "Id": "204796", "ParentId": "204792", "Score": "0" } }
<p>Overall, I feel that my code is a bit verbose.</p> <p><em>game.py</em></p> <pre><code>#!/usr/bin/python3 import sys,os from models import Board, GameState """ Game loop for the minesweeper game. """ class Game: def __init__(self): self.board = Board(rows=10, cols=10) def play(self): self.welcome() while self.board.game_state in [GameState.on_going, GameState.start]: self.board.print_board_wrapper(self.board.print_board_hook) try: raw = input("&gt; ") line = "".join(raw.split()) if line[0] == "f": point = tuple(map(int, line[1:].split(","))) self.board.flag_square(point[0], point[1]) else: point = tuple(map(int, line.split(","))) self.board.click_square(point[0], point[1]) except (IndexError, ValueError): self.help() except KeyboardInterrupt: try: sys.exit(0) except SystemExit: os._exit(0) if self.board.game_state == GameState.lose: print("\n\nYou hit a mine. :(\n") else: print("\n\nYou win!\n") self.board.print_board_wrapper(self.board.print_board_end_hook) def welcome(self): print("\nWelcome to PySweep!") self.help() def help(self): print("\nEnter coordinates") print("&gt; &lt;row&gt;,&lt;column&gt;") print("&gt; 1,1") print("Flag and unflag coordinates") print("&gt; f &lt;row&gt;,&lt;column&gt;") print("&gt; f 1,1") if __name__ == "__main__": game = Game() game.play() </code></pre> <p><em>models.py</em></p> <pre><code>""" Data models for a minesweeper CLI game. """ import random import itertools from enum import Enum class GameState(Enum): start = 0 win = 1 lose = 2 on_going = 3 class Board: """ Represents a minesweeper board with squares. """ def __init__(self, rows, cols): self.rows = rows self.cols = cols self.game_state = GameState.start self.number_of_mines = 0 self.max_mines = (cols-1)*(rows-1) mines_percentage = (100 * self.max_mines / (rows*cols))/3 self.__create_squares(self.cols, self.rows, mines_percentage) def flag_square(self, row, col): if not self.__valid_square(row, col) or self.__get_square(row, col).clicked: return square = self.squares[row][col] square.flag = not square.flag def click_square(self, row, col): """ Click the square and click its neighbors which don't have neighboring mines. """ if not self.__valid_square(row, col) or self.__get_square(row, col).clicked: return square = self.squares[row][col] if self.game_state == GameState.start: square.mine = False for neighbor in square.neighbors(): neighbor.mine = False self.game_state = GameState.on_going if square.mine: self.game_state = GameState.lose return square.clicked = True if square.mine_neighbors() == 0: for neighbor in square.neighbors(): if not neighbor.mine: if neighbor.mine_neighbors() == 0: self.click_square(neighbor.row, neighbor.col) neighbor.clicked = True if self.__win(): self.game_state = GameState.win def print_board_wrapper(self, print_hook): print("\n") col_print = " " for i in range(0, self.cols): col_print += str(i) + " " print(col_print + "\n") for i,row in enumerate(self.squares): row_print = str(i) + " " for square in row: row_print += print_hook(square) print(row_print + "\n") def print_board_hook(self, square): """ Prints the board. If a square is clicked, print the number of neighboring mines. If the square is flagged, print "f". Else print ".". """ if square.clicked: return " " + str(square.mine_neighbors()) + " " elif square.flag: return " f " return " . " def print_board_end_hook(self, square): if square.mine: return " x " return self.print_board_hook(square) def __win(self): for row in self.squares: for square in row: if not square.mine and not square.clicked: return False return True def __get_square(self, row, col): """ Return the square at the given row and column.""" return self.squares[row][col] def __valid_square(self, row, col): return (row &lt; self.rows and row &gt;= 0) and (col &lt; self.cols and col &gt;= 0) def __create_squares(self, cols, rows, mines_percentage): """ Create a grid of squares of size rows by cols. """ self.squares = [[Square(self, row, col, mine=self.__is_mine(mines_percentage)) for col in range(cols)] for row in range(rows)] def __is_mine(self, mines_percentage): """ Determine if a square is a mine while generating the board. """ is_mine = random.randrange(100) &lt; mines_percentage if is_mine: if self.number_of_mines &gt;= self.max_mines: return False self.number_of_mines = self.number_of_mines + 1 return True return False class Square: """ Represents a single square in the minesweeper board. A square may have or may not have a mine, may be clicked or unclicked. """ def __init__(self, board, row, col, mine): self.board = board self.row = row self.col = col self.mine = mine self.flag = False self.clicked = False def mine_neighbors(self): return len(list(filter(lambda square: square.mine, [self.board.squares[point[0]][point[1]] for point in self.__point_neighbors()]))) def neighbors(self): return [self.board.squares[point[0]][point[1]] for point in self.__point_neighbors()] def __point_neighbors(self): row_neighbors = list(filter(lambda val: val &gt;= 0 and val &lt; self.board.rows, [self.row-1, self.row, self.row+1])) col_neighbors = list(filter(lambda val: val &gt;= 0 and val &lt; self.board.cols, [self.col-1, self.col, self.col+1])) neighbor_set = set(itertools.product(row_neighbors, col_neighbors)) neighbor_set.remove((self.row, self.col)) return list(neighbor_set) </code></pre> <p>I think there's lots of places where my code could be made a lot more readable. The hook for the <em>print_board</em> function seems a bit suspect. The <code>__point_neighbors</code> function could probably be improved (having a lambda seems to be overkill).</p> <p>I'm also looking to improve the mine generation algorithm. Currently, each square has an individual probability of being a mine and mine generation is stopped when max_mines is reached. So, the bottom right corner would be likely to have less mines. My solution to the "first click shouldn't be a mine" problem is I clear the space around the first click so you always get the eight spaces around the first click for free.</p> <p>Here's a <a href="https://github.com/kdbeall/pysweep/tree/bfbdf51c87ee89339802fe1b5e195b9ec2d36311" rel="noreferrer">link</a> to the git repository.</p>
205474
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-12T21:31:54.363", "Id": "205474", "Score": "6", "Tags": [ "python", "minesweeper" ], "Title": "Made a minesweeper game in Python" }
{ "body": "<p>Your <code>Game</code> class might not need to be a class at all. You create <code>self.board</code> in the <code>__init__()</code> method, and then only use it in the <code>play()</code> method. Since <code>play()</code> doesn't return until the game is over, <code>board</code> could simply be a local variable, created at the beginning of the <code>play()</code> function. If that is changed, then <code>Game</code> doesn't have any data - just methods - so doesn't need to be a class.</p>\n\n<pre><code>point = tuple(map(int, line[1:].split(\",\")))\nself.board.flag_square(point[0], point[1])\n</code></pre>\n\n<p>This code seems a little verbose. You are creating a tuple to force the conversion of the return value of <code>map</code> into something you can directly use, from the mysterious <code>map object</code> is actually returns. How about:</p>\n\n<pre><code>row, col = map(int, line[1:].split(\",\"))\nself.board.flag_square(row, col)\n</code></pre>\n\n<p>This is a little clearer, bordering on self-documenting. We expect exactly 2 values ... a <code>row</code> and a <code>col</code> value. If the user types in \"f 3,4,7\", your code would muddle on using the 3,4 value, where as the new code will raise a <code>Value Error: too many values to unpack</code>, which your code would catch and prompt the user for better input.</p>\n\n<hr>\n\n<p>The <code>Square</code> class holds too much information. While <code>mine</code>, <code>flag</code> and <code>clicked</code> all seem required, <code>board</code>, <code>row</code> and <code>col</code> are not necessary; adding them has actually complicated your code. Your squares know where they are, so they can tell you who their neighbours are, as well has how many mines are around them. But imagine if they didn't. Not a problem: <code>Board.squares[row][col]</code> holds each square. You just need to ask <code>Board</code> for the neighbours of <code>(row, col)</code> or the number of mine around <code>(row, col)</code>. The code just needs to move from <code>Square</code> to <code>Board</code>, and as these are board-level operations, that makes sense.</p>\n\n<p>How many times is <code>square.mine_neighbors()</code> called? If you start the game clicking (3,4), each time you print the board, you will need to print the number of mines around (3,4), so after <code>n</code> turns, you've called it <code>n</code> times for that square. But on the second turn, you'll have clicked another square, and will have called the function <code>n-1</code> times for that new square. And <code>n-2</code> times for the third square that got clicked, and so on. The result is you're calling <code>square.mine_neighbours()</code> <span class=\"math-container\">\\$O(n^2)\\$</span> times. The mines don't move; the number of neighbours never changes. Perhaps you could store one additional piece of information in <code>Square</code> ... the number of neighbouring mines. Compute that for the entire board at the start.</p>\n\n<hr>\n\n<p><code>Board.print_board_wrapper(self, print_hook)</code>.</p>\n\n<p>This API requires the caller to pass in one of two functions, depending on whether the game is over or not. The <code>Board</code> object itself has a <code>self.game_state</code> member which knows whether the game is over. Why force the caller to provide the correct method?</p>\n\n<pre><code>class Board:\n ...\n def print_board(self):\n if self.game_state in (GameState.start, GameState.on_going):\n print_hook = self.print_board_hook\n else:\n print_hook = self.print_board_end_hook\n self.print_board_wrapper(print_hook)\n</code></pre>\n\n<p>Now the caller can just call <code>print_board()</code>, and the correct board format will be used depending on state.</p>\n\n<p>But wait! Why two \"hook\" methods depending on the game state? The <code>Board.print_board_hook</code> method knows the game state. You could get rid of the two hook methods, and replace them with:</p>\n\n<pre><code> def print_square(self, square):\n \"\"\"...\"\"\"\n\n if self.game_state in (GameState.win, GameState.lose) and square.mine:\n return \" x \"\n elif square.clicked:\n return \" \" + str(square.mine_neighbors()) + \" \"\n elif square.flag:\n return \" f \"\n return \" . \"\n</code></pre>\n\n<hr>\n\n<p>Why does <code>Board</code> have a function to print the game board? It doesn't do any other printing. You could add a graphical UI to the program, and most of <code>Board</code> doesn't have to be changed. The <code>Game</code> would need to be changed, of course, as well as these <code>Board.print_board_*</code> methods.</p>\n\n<p>Perhaps the <code>print_board()</code> function should be moved into <code>Game</code>? In fact, it looks like you intended this, but forgot.</p>\n\n<pre><code>\"\"\" Data models for a minesweeper CLI game. \"\"\"\n</code></pre>\n\n<p>(And \"Data models\" wouldn't have any user I/O methods)</p>\n\n<hr>\n\n<p>A simple mine placement algorithm:</p>\n\n<pre><code>def _add_mines(self, mine_percentage):\n num_mines = self.rows * self.cols * mine_percentage // 100\n\n count = 0\n while count &lt; num_mines:\n row = random.randrange(self.rows)\n col = random.randrange(self.cols)\n if not self.squares[row][col].mine:\n self.squares[row][col].mine = True\n count += 1\n</code></pre>\n\n<p>But, how to ensure the user's starting location isn't a mine? Easy. Make it a mine to begin with. Add all the other mines. Then remove that initial mine.</p>\n\n<pre><code>self.squares[row][col].mine = True\nself._add_mines(mine_percentage)\nself.squares[row][col].mine = False\n</code></pre>\n\n<p>As long as the mine percentage is not high, the number of iterations through the loop shouldn't be much larger than <code>num_mines</code>. To handle larger mine percentages, a different strategy should be used:</p>\n\n<ul>\n<li>Create a list of all board locations</li>\n<li>Remove the user's starting location</li>\n<li>Shuffle the list</li>\n<li>Add mines to the first <code>num_mines</code> locations in the list.</li>\n</ul>\n\n<p>Something like:</p>\n\n<pre><code>locs = [(row, col) for row in range(self.rows) for col in range(self.cols)]\nlocs.remove((initial_row, initial_col))\nrandom.shuffle(locs)\nfor row, col in locs[:num_mines]:\n self.squares[row][col].mine = True\n</code></pre>\n\n<hr>\n\n<p>As you suspected, your <code>neighbors(self)</code> could be improved. You don't need <code>itertools.product</code>, or <code>filter</code> or <code>lambda</code>, nor even the <code>__point_neighbors</code> helper function. List comprehension with a double <code>for</code> loop can replace the <code>product</code> and <code>set</code> creation. Just need a few <code>min</code>/<code>max</code> operations to ensure the loops stay within the confines of the board. Assuming the code is moved to <code>class Board</code>:</p>\n\n<pre><code>def neighbors(self, row, col):\n neighbor_set = { (r, c) for r in range(max(0, row-1), min(self.rows, row+2))\n for c in range(max(0, col-1), min(self.cols, col+2)) }\n neighbor_set.remove((row, col))\n return neighbor_set\n</code></pre>\n\n<p>There is no need to turn the <code>set</code> into a <code>list</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-15T17:33:19.577", "Id": "205616", "ParentId": "205474", "Score": "2" } }
<p>This code that I wrote is supposed to read/write a pipe-delimited file line by line to a new file with some simple text manipulation. (It also adds two new columns) and publishes a "Status Update" ever 100,000 lines to keep me updated on how close it is to completion. </p> <p>I previously posted this code on StackOverflow to get help with incrementing, and someone mentioned that it would be faster if I did not open the second text file, but being extremely new at Python, I do not understand how to do that without potentially breaking the code.</p> <pre><code>counter=1 for line in open(r"C:\Path\name.txt"): spline = line.split("|") if counter==1: with open(r"C:\PATH\2019.txt",'a') as NewFile: spline.insert(23,"Column A") spline.insert(23,"Column B") s="|" newline=s.join(spline) NewFile.write(newline) elif counter &gt; 1 and not spline[22]=="0.00": spline.insert(23,"") spline.insert(23,"") gl=spline[0] gl=gl.strip() if gl[0]=="-": gl="000" + gl gl=gl.upper() spline[0]=gl if gl[:3]=="000": spline[24]="Incorrect" s="|" newline=s.join(spline) with open(r"C:\PATH\PythonWrittenData.txt",'a') as NewFile: NewFile.write(newline) counter+=1 if counter%100000==0: print("Status Update: \n", "{:,}".format(counter)) </code></pre>
216653
GOOD_ANSWER
{ "AcceptedAnswerId": "216661", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T13:23:25.247", "Id": "216653", "Score": "10", "Tags": [ "python", "beginner", "python-3.x", "file", "csv" ], "Title": "Read/write a pipe-delimited file line by line with some simple text manipulation" }
{ "body": "<p>A nice trick you can use in python is to open two (or more) files at once in one line. This is done with something like:</p>\n\n<pre><code>with open('file_one.txt', 'r') as file_one, open('file_two.txt', 'r') as file_two:\n for line in file_one:\n ...\n for line in file_two:\n ...\n</code></pre>\n\n<p>This is a very common way of reading from one file and writing to another without continually opening and closing one of them.</p>\n\n<p>Currently, you're opening and closing the files with each iteration of the loop. Your program loops through the lines in <code>name.txt</code>, checks an <code>if</code> / <code>elif</code> condition, then if either are satisfied, a file is opened, written to, then closed again <em>with every iteration of the loop</em>.</p>\n\n<p>Simply by opening both files at the same time you can stop opening and closing them repeatedly.</p>\n\n<p>For more info on the <code>with</code> statement and other context managers, see <a href=\"https://book.pythontips.com/en/latest/context_managers.html\" rel=\"noreferrer\">here</a>.</p>\n\n<hr>\n\n<p>Another small improvement can be made. At the moment, you check the first <code>if</code> condition every time, but you know it will only actually evaluate to <code>True</code> once. it would be better to remove that check and just always perform that block once. Assign counter <em>after</em> the first block (after where <code>if counter == 1</code> currently is) then replace the <code>elif</code> statement with a <code>while</code> loop.</p>\n\n<hr>\n\n<p>It would be worth getting familiar with <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> if you're going to use Python a lot in the future. It's a standard style guide and will help with the readability of your code (for you and others). Just small stuff like new lines after colons or spaces either side of variable declarations / comparisons.</p>\n\n<hr>\n\n<p>If you include an example file and desired output, there may be more I can help with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T21:07:56.143", "Id": "419141", "Score": "0", "body": "I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T15:20:35.423", "Id": "216661", "ParentId": "216653", "Score": "7" } }
<p>This code that I wrote is supposed to read/write a pipe-delimited file line by line to a new file with some simple text manipulation. (It also adds two new columns) and publishes a "Status Update" ever 100,000 lines to keep me updated on how close it is to completion. </p> <p>I previously posted this code on StackOverflow to get help with incrementing, and someone mentioned that it would be faster if I did not open the second text file, but being extremely new at Python, I do not understand how to do that without potentially breaking the code.</p> <pre><code>counter=1 for line in open(r"C:\Path\name.txt"): spline = line.split("|") if counter==1: with open(r"C:\PATH\2019.txt",'a') as NewFile: spline.insert(23,"Column A") spline.insert(23,"Column B") s="|" newline=s.join(spline) NewFile.write(newline) elif counter &gt; 1 and not spline[22]=="0.00": spline.insert(23,"") spline.insert(23,"") gl=spline[0] gl=gl.strip() if gl[0]=="-": gl="000" + gl gl=gl.upper() spline[0]=gl if gl[:3]=="000": spline[24]="Incorrect" s="|" newline=s.join(spline) with open(r"C:\PATH\PythonWrittenData.txt",'a') as NewFile: NewFile.write(newline) counter+=1 if counter%100000==0: print("Status Update: \n", "{:,}".format(counter)) </code></pre>
216653
BAD_ANSWER
{ "AcceptedAnswerId": "216661", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T13:23:25.247", "Id": "216653", "Score": "10", "Tags": [ "python", "beginner", "python-3.x", "file", "csv" ], "Title": "Read/write a pipe-delimited file line by line with some simple text manipulation" }
{ "body": "<p>Here is another way to organize your code. Instead of an <code>if</code> within the loop, use iterators more explicitly. Concretely:</p>\n\n<pre><code>with open(r\"C:\\Path\\name.txt\") as source:\n lines = iter(source)\n\n # first line\n first_line = next(lines)\n with open(r\"C:\\PATH\\2019.txt\") as summary:\n # ... omitted ...\n\n # remaining lines\n with open(r\"C:\\PATH\\PythonWrittenData.txt\", 'a') as dest:\n for counter, line in enumerate(lines, start=1):\n # ... omitted ...\n\n</code></pre>\n\n<p>I have also used <code>enumerate</code> to update <code>counter</code> and <code>line</code> simultaneously.</p>\n\n<p>The other answer has some more tips on writing good python code. But as far as structuring the opening and closing of files, as well as the main loop, this approach should get you started.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T18:22:23.653", "Id": "419108", "Score": "0", "body": "I'm not sure I understand the reasoning behind `first_line=next(lines)` could you explain how it should be used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T19:11:19.810", "Id": "419122", "Score": "0", "body": "@EmilyAlden Why accept an answer when you don’t understand why that answer works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T19:36:43.513", "Id": "419129", "Score": "0", "body": "@DavidWhite: Honestly I bounced between which answer to accept. I understand the use of `iter` and `enumerate` here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T19:48:50.830", "Id": "419132", "Score": "1", "body": "@EmilyAlden `first_line = next(iterator)` is equivalent to `for first_line in iterator: break`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T19:50:26.657", "Id": "419133", "Score": "0", "body": "@wizzwizz4 Thank you." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-01T15:39:13.337", "Id": "216662", "ParentId": "216653", "Score": "8" } }
<p>This is my first program written outside of using books and tutorials. Any help on style and functionality would be helpful.</p> <pre><code> import sys from textwrap import dedent import os import random os.system('CLS') # board number setup board = [0,1,2, 3,4,5, 6,7,8] # Defines the board layout printed to the console def board_layout(): print(dedent(f''' ************* * {board[0]} | {board[1]} | {board[2]} * *-----------* * {board[3]} | {board[4]} | {board[5]} * *-----------* * {board[6]} | {board[7]} | {board[8]} * ************* ''')) move_count= 0 def main(): while True: #Prints board layout to console. board_layout() #checks for a winner when called at end of each turn def check_winner(): global move_count #list of lists with all the winning combinations for from the tic tac toe board winning_list = [[board[0],board[1],board[2]],[board[3],board[4],board[5],], [board[6],board[7],board[8]],[board[0],board[4],board[8]],[board[2],board[4],board[6]], [board[0],board[3],board[6]],[board[1],board[4],board[7]],[board[2],board[5],board[8]]] #Keeps a reference to winning_list so it is updated at the end of every turn new_list = winning_list #iterates over the lists in winning_list for i,j,k in winning_list: #looks at the lists in winning_list to determine if a list has all x's for a win if i == 'x' and j == 'x' and k == 'x' : print('X wins') end() #looks at the lists in winning_list to determine if a list has all o's for a win elif i == 'o' and j == 'o' and k == 'o' : print('O wins') end() #possible moves is 9 in tic tac toe. If all moves are taken and there is no winner no winner forces a draw. if move_count == 9: print('You Tied') end() #Takes user input for the move move =int(input('Please select a spot: ')) print(move) #Player move, makes sure the spot is not taken and adds 1 to move_count if board[move] !='x' and board[move] != 'o': board[move] = 'x' move_count += 1 check_winner() #npc move, chooses a random spot that is not taken and adds 1 to move_count while True: npc = random.randint(0,8) if board[npc] != 'o' and board[npc] != 'x': board[npc] = 'o' print('Computer chooses spot ', npc) move_count += 1 check_winner() break #If spot is taken prints that the spot is already taken else: print('This spot is taken') #Game ending def end(): print('Thank you for playing') sys.exit() if __name__ == "__main__": main() </code></pre>
217235
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-10T23:41:18.717", "Id": "217235", "Score": "4", "Tags": [ "python", "beginner", "tic-tac-toe" ], "Title": "First Python program: Tic-Tac-Toe" }
{ "body": "<p>The function <code>check_winner()</code> does not need <code>global move_count</code>. Using <code>global</code> is code smell, avoid if at all possible, which tends to be always. But in this case it is completely unnecessary, as <code>move_count</code>, like <code>board</code>, is already accessible in <code>check_winner()</code>.</p>\n\n<p><code>winning_list</code> is constructed every time <code>check_winner()</code> is called. It does not persist from one call to the next, so <code>new_list = winning_list</code> and the comment immediately above it should be removed.</p>\n\n<hr>\n\n<p>The statement <code>move = int(input(...))</code> can crash if the user enters invalid input. Even if a valid integer is given, the integer could be outside the valid range, like <code>42</code>, which will cause when <code>board[move]</code> is evaluated. Place user input in a <code>try ... except</code> statement, inside a loop, and don’t let the program continue until valid input has been given.</p>\n\n<hr>\n\n<p>You have a game loop that handles two turns (a move by both players) each pass through the loop. While this does work, it will paint you into a corner in subsequent programs. 3 or more players is going to make writing the game loop much harder.</p>\n\n<p>It is usually simpler to handle one turn (a move by only one player), in each pass through the loop. At the end of the loop, the “current player” is incremented, wrapping around to the first player when necessary. With only 2 players, this alternates between them. More advanced games may require skipping player when a “lose a turn” move is made. Other games may even reverse the direction of play mid game. All of these would be horrible to try to write the game loop for if each pass through the loop tried to handle all player moves in one pass.</p>\n\n<hr>\n\n<p>When the game loop is change to handle only a single move at each pass, it is much easier to handle the “game over” condition. A <code>while game_is_running</code> loop is all that is required. Or, for tic-tac-toe, you could use:</p>\n\n<pre><code>for move_count in range(9):\n # moves made here\n # break if someone wins\nelse:\n print(\"You Tied\")\n</code></pre>\n\n<p>The <code>else:</code> clause of a <code>for</code> loop only executes if the loop finishes without executing <code>break</code>, so after 9 moves with no winner, it is a tie game.</p>\n\n<p>Using <code>sys.exit()</code> to stop the interpreter on a “game over” condition is a bad idea. It works here, but it makes test code impossible to write, because the program can kill the interpreter, and the test code can’t stop that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-11T07:29:07.587", "Id": "420214", "Score": "0", "body": "@AJNeufed Thank you for the input and i will work on the suggestion made. I will work on the suggestions and post an updated version" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-11T05:42:09.430", "Id": "217245", "ParentId": "217235", "Score": "2" } }
<p>This is my first program written outside of using books and tutorials. Any help on style and functionality would be helpful.</p> <pre><code> import sys from textwrap import dedent import os import random os.system('CLS') # board number setup board = [0,1,2, 3,4,5, 6,7,8] # Defines the board layout printed to the console def board_layout(): print(dedent(f''' ************* * {board[0]} | {board[1]} | {board[2]} * *-----------* * {board[3]} | {board[4]} | {board[5]} * *-----------* * {board[6]} | {board[7]} | {board[8]} * ************* ''')) move_count= 0 def main(): while True: #Prints board layout to console. board_layout() #checks for a winner when called at end of each turn def check_winner(): global move_count #list of lists with all the winning combinations for from the tic tac toe board winning_list = [[board[0],board[1],board[2]],[board[3],board[4],board[5],], [board[6],board[7],board[8]],[board[0],board[4],board[8]],[board[2],board[4],board[6]], [board[0],board[3],board[6]],[board[1],board[4],board[7]],[board[2],board[5],board[8]]] #Keeps a reference to winning_list so it is updated at the end of every turn new_list = winning_list #iterates over the lists in winning_list for i,j,k in winning_list: #looks at the lists in winning_list to determine if a list has all x's for a win if i == 'x' and j == 'x' and k == 'x' : print('X wins') end() #looks at the lists in winning_list to determine if a list has all o's for a win elif i == 'o' and j == 'o' and k == 'o' : print('O wins') end() #possible moves is 9 in tic tac toe. If all moves are taken and there is no winner no winner forces a draw. if move_count == 9: print('You Tied') end() #Takes user input for the move move =int(input('Please select a spot: ')) print(move) #Player move, makes sure the spot is not taken and adds 1 to move_count if board[move] !='x' and board[move] != 'o': board[move] = 'x' move_count += 1 check_winner() #npc move, chooses a random spot that is not taken and adds 1 to move_count while True: npc = random.randint(0,8) if board[npc] != 'o' and board[npc] != 'x': board[npc] = 'o' print('Computer chooses spot ', npc) move_count += 1 check_winner() break #If spot is taken prints that the spot is already taken else: print('This spot is taken') #Game ending def end(): print('Thank you for playing') sys.exit() if __name__ == "__main__": main() </code></pre>
217235
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-10T23:41:18.717", "Id": "217235", "Score": "4", "Tags": [ "python", "beginner", "tic-tac-toe" ], "Title": "First Python program: Tic-Tac-Toe" }
{ "body": "<h2>Function Placement</h2>\n\n<p>You lose a bit of performance and readability by defining <code>check_winner</code> inside your <code>while</code> loop. <code>move_count</code>, <code>board</code> etc are all in global scope, even though they are within that loop:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def check_winner():\n # Rest of function\n\nwhile True:\n</code></pre>\n\n<p>The <code>def end()</code> could also be moved to global scope, because again you are redefining it during every iteration which isn't what you want.</p>\n\n<h2>check_winner</h2>\n\n<p>The <code>new_list = winning_list</code> doesn't do anything, it copies the reference from <code>winning_list</code> and the two variables are tied together unless you did a <code>deep_copy</code>, which creates a new object. Furthermore, I don't really see any use of <code>new_list</code> anywhere, so you can just drop that line entirely.</p>\n\n<p>As @AJNewfeld pointed out, the <code>global move_count</code> can be dropped because, again, <code>move_count</code> is already global and is accessible by all <code>check_winner</code>, as it will look in the <code>locals()</code> mapping first, if <code>move_count</code> isn't in the local mapping (from positional or keyword args taken in by the function), it will search <code>globals()</code>. A <code>NameError</code> is only raised when those don't contain the variable you are looking for.</p>\n\n<h2>Making Moves</h2>\n\n<p>The <code>while</code> loop for <code>npc</code> can be easily refactored so that you aren't possibly iterating over the entire board, and makes the code a bit easier to read. Your <code>board</code> is made up of either two entries: <code>int</code> for open spots and <code>str</code> for taken spots. This means that <code>npc</code>'s move can be a function like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def npc_move():\n # This will give you only the indices for spots that have yet to be taken\n remaining_spots = [i for i, value in enumerate(board) if isinstance(value, int)]\n return random.choice(remaining_spots)\n</code></pre>\n\n<p>Or you could also use a <code>set()</code> globally to represent remaining spots and <code>pop</code> indices out of it:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Declare globally at the beginning \nmoves_left = set(range(9))\n\n# Your while loop can now be to check if the set is empty or not\nwhile moves_left: # A populated set acts as True\n my_move = moves_left.pop(random.choice(moves_left))\n\n # Now moves_left has one fewer element\n</code></pre>\n\n<p>Taking this idea a little further, you could combine the user's move with the npc's move in one function:</p>\n\n<pre><code># The npc default will allow you to set it to True if it's\n# npc's turn, otherwise, no args need to be supplied\ndef make_move(npc=False):\n\n if npc is False:\n user_move = \"\" # dummy default to kick off while loop\n while user_move not in moves_left:\n try:\n user_move = int(input(f\"Choose a move out of {moves_left}: \"))\n return moves_left.pop(user_move)\n except ValueError, KeyError: # invalid int conversion or not in moves_left\n print(\"Invalid move\")\n continue\n\n else:\n return moves_left.pop(random.choice(moves_left)) \n</code></pre>\n\n<p>You can then call it like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>moves_left = set(range(9)) # At beginning of game\n\nnpc_move = make_move(npc=True)\n3\nuser_move = make_move()\n\nChoose a move out of {0, 1, 2, 4, 5, ,6 ,7, 8}: a\nInvalid move\nChoose a move out of {0, 1, 2, 4, 5, ,6 ,7, 8}: 3\nInvalid move\nChoose a move out of {0, 1, 2, 4, 5, ,6 ,7, 8}: 4\n\nuser_move\n4\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-11T13:45:49.613", "Id": "217261", "ParentId": "217235", "Score": "1" } }
<p>This is my first program written outside of using books and tutorials. Any help on style and functionality would be helpful.</p> <pre><code> import sys from textwrap import dedent import os import random os.system('CLS') # board number setup board = [0,1,2, 3,4,5, 6,7,8] # Defines the board layout printed to the console def board_layout(): print(dedent(f''' ************* * {board[0]} | {board[1]} | {board[2]} * *-----------* * {board[3]} | {board[4]} | {board[5]} * *-----------* * {board[6]} | {board[7]} | {board[8]} * ************* ''')) move_count= 0 def main(): while True: #Prints board layout to console. board_layout() #checks for a winner when called at end of each turn def check_winner(): global move_count #list of lists with all the winning combinations for from the tic tac toe board winning_list = [[board[0],board[1],board[2]],[board[3],board[4],board[5],], [board[6],board[7],board[8]],[board[0],board[4],board[8]],[board[2],board[4],board[6]], [board[0],board[3],board[6]],[board[1],board[4],board[7]],[board[2],board[5],board[8]]] #Keeps a reference to winning_list so it is updated at the end of every turn new_list = winning_list #iterates over the lists in winning_list for i,j,k in winning_list: #looks at the lists in winning_list to determine if a list has all x's for a win if i == 'x' and j == 'x' and k == 'x' : print('X wins') end() #looks at the lists in winning_list to determine if a list has all o's for a win elif i == 'o' and j == 'o' and k == 'o' : print('O wins') end() #possible moves is 9 in tic tac toe. If all moves are taken and there is no winner no winner forces a draw. if move_count == 9: print('You Tied') end() #Takes user input for the move move =int(input('Please select a spot: ')) print(move) #Player move, makes sure the spot is not taken and adds 1 to move_count if board[move] !='x' and board[move] != 'o': board[move] = 'x' move_count += 1 check_winner() #npc move, chooses a random spot that is not taken and adds 1 to move_count while True: npc = random.randint(0,8) if board[npc] != 'o' and board[npc] != 'x': board[npc] = 'o' print('Computer chooses spot ', npc) move_count += 1 check_winner() break #If spot is taken prints that the spot is already taken else: print('This spot is taken') #Game ending def end(): print('Thank you for playing') sys.exit() if __name__ == "__main__": main() </code></pre>
217235
WIERD
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-10T23:41:18.717", "Id": "217235", "Score": "4", "Tags": [ "python", "beginner", "tic-tac-toe" ], "Title": "First Python program: Tic-Tac-Toe" }
{ "body": "<p>I made some of the changes suggested by @AJNeufeld. I made the game loop a for i in range(9) and removed all global variables from the code. Put the move by the player in a try/except block to catch IndexError and the loop only handles one turn each go throug and looping back to the beginning when needed(I am not sure if i did this is the best way). End no longer uses the sys.exit() and changed to quit() and now offers am option to play again.</p>\n\n<pre><code>import sys\nfrom textwrap import dedent\nimport os\nimport random\n\nos.system('CLS')\n\n# board number setup\nboard = [0, 1, 2,\n 3, 4, 5,\n 6, 7, 8]\n\n\n# Defines the board layout printed to the console\ndef board_layout():\n print(dedent(f''' \n *************\n * {board[0]} | {board[1]} | {board[2]} *\n *-----------*\n * {board[3]} | {board[4]} | {board[5]} *\n *-----------*\n * {board[6]} | {board[7]} | {board[8]} *\n *************\n '''))\n\n\ndef main():\n players = ('Player','NPC')\n turn = 'Player'\n change_turn = 0\n for moves in range(9):\n if turn == 'Player': \n while True:\n try:\n board_layout()\n player_move = int(input('Please select a spot: '))\n if board[player_move] != 'x' and board[player_move] != 'o':\n board[player_move] = 'x'\n check_winner()\n break\n except IndexError:\n print('please select valid spot')\n if turn == 'NPC':\n # npc move, chooses a random spot that is not taken \n while True:\n npc = random.randint(0, 8)\n if board[npc] != 'o' and board[npc] != 'x':\n board[npc] = 'o'\n print('Computer chooses spot ', npc)\n check_winner()\n break \n try:\n change_turn += 1\n turn = players[change_turn]\n except:\n change_turn = 0\n turn = players[change_turn]\n else:\n print('You Tied')\n end() \n\n\n\n\n\ndef end():\n print('Thank you for playing')\n answer = input('Would you like to play again?: Y/N')\n\n if answer.lower() == 'n':\n quit()\n elif answer.lower() == 'y':\n clear_board()\n main()\n else:\n print('Please choose a valid option')\n end()\n\ndef clear_board():\n for i in range(9):\n board[i] = i\n\n# checks for a winner when called at end of each turn \ndef check_winner():\n\n # list of lists with all the winning combinations for from the tic tac toe board\n winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],\n [board[6], board[7], board[8]], [board[0], board[4], board[8]],\n [board[2], board[4], board[6]],\n [board[0], board[3], board[6]], [board[1], board[4], board[7]],\n [board[2], board[5], board[8]]]\n\n # iterates over the lists in winning_list\n for i, j, k in winning_list:\n # looks at the lists in winning_list to determine if a list has all x's for a win\n if i == 'x' and j == 'x' and k == 'x':\n print('X wins')\n end()\n # looks at the lists in winning_list to determine if a list has all o's for a win\n elif i == 'o' and j == 'o' and k == 'o':\n print('O wins')\n end()\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-12T01:55:14.347", "Id": "420339", "Score": "0", "body": "Are you happy with this new code, or are you hoping for additional review feedback? If the latter, you need to ask a new question, say “First Python program: Tic-Tac-Toe (Followup)”, include a link back to this question, and a link from this question to the follow up question. See “[What should I do when someone answers my question](https://codereview.stackexchange.com/help/someone-answers)” in “Help” for more details. All the feedback I can give you in a comment on this answer is “I don’t like what you’ve done”, but don’t have nearly the space to explain why." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-12T02:48:38.967", "Id": "420343", "Score": "0", "body": "@ AJNeufeld 52 i was hoping for addition feedback. I have posted a follow-up at [link](https://codereview.stackexchange.com/questions/217304/first-python-program-tic-tac-toe-followup)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-11T21:51:03.580", "Id": "217290", "ParentId": "217235", "Score": "0" } }
<p>The following code is my solution for the following Daily Coding Challenge</p> <blockquote> <p>Given an array of numbers, find the maximum sum of any contiguous subarray of the array.</p> <p>For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86.</p> <p>Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any elements.</p> <p>Do this in O(N) time.</p> </blockquote> <p>I think this is done in <code>O(N)</code> time and is the best solution. If someone can think of a better way, I would be interested. </p> <pre><code>array = [4, -2, 7, -9] running_sum = 0 for i in range(1,len(array)): if array[i-1] &gt; 0: array[i] = array[i] + array[i-1] else: array[i-1] = 0 print(max(array)) </code></pre>
222772
GOOD_ANSWER
{ "AcceptedAnswerId": "222798", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T17:35:53.857", "Id": "222772", "Score": "1", "Tags": [ "python", "algorithm", "python-3.x", "programming-challenge", "array" ], "Title": "Maximum contiguous sum in an array" }
{ "body": "<p>I would merge the 2 loops (there is one in the max part), since not all parts are relevant for the maximum:</p>\n\n<pre><code>def best_subsum(array):\n running_sum = 0\n for i in range(1,len(array)):\n if array[i-1] &gt; 0:\n array[i] = array[i] + array[i-1]\n if array[i] &gt; running_sum: running_sum = array[i]\n return running_sum\n\narray = [4, -2, 7, -9]\nprint(best_subsum(array))\n</code></pre>\n\n<p>Note that branch prediction shouldnt be too much of a problem, since running sum is not check until the same if statement in the next succeding iteration.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T01:18:48.703", "Id": "222786", "ParentId": "222772", "Score": "1" } }
<p>The following code is my solution for the following Daily Coding Challenge</p> <blockquote> <p>Given an array of numbers, find the maximum sum of any contiguous subarray of the array.</p> <p>For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86.</p> <p>Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any elements.</p> <p>Do this in O(N) time.</p> </blockquote> <p>I think this is done in <code>O(N)</code> time and is the best solution. If someone can think of a better way, I would be interested. </p> <pre><code>array = [4, -2, 7, -9] running_sum = 0 for i in range(1,len(array)): if array[i-1] &gt; 0: array[i] = array[i] + array[i-1] else: array[i-1] = 0 print(max(array)) </code></pre>
222772
WIERD
{ "AcceptedAnswerId": "222798", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-22T17:35:53.857", "Id": "222772", "Score": "1", "Tags": [ "python", "algorithm", "python-3.x", "programming-challenge", "array" ], "Title": "Maximum contiguous sum in an array" }
{ "body": "<h1>changing mutable object</h1>\n\n<p>Since you are changing the original array, this code run twice can provide strange results. In general I try to avoid changing the arguments passed into a function I write, unless it's explicitly stated, or expected (like <code>list.sort</code>)</p>\n\n<h1><code>accumulate</code></h1>\n\n<p>What you are looking for is the largest difference between tha cumulative sum where the minimum comes before the maximum. Calculating the cumulative sum can be done with <code>itertools.accumulate</code>. Then you just have to keep track of the minimum of this running sum and the difference with the running minimum</p>\n\n<pre><code>def best_sum_accum(array):\n running_min = 0\n max_difference = 0\n for cumsum in accumulate(array):\n if cumsum &gt; running_min:\n max_difference = max(max_difference, cumsum - running_min)\n running_min = min(running_min, cumsum)\n return max_difference\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T10:47:19.440", "Id": "431420", "Score": "0", "body": "Surely this has a time complexity > ```O(N)``` because you have a nested loop? ```for``` and ```max```?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T12:52:00.347", "Id": "431425", "Score": "1", "body": "Not really, you loop 1 timer through the array. On each iteration, you compare 2 numbers, so the time complexity is linear with the length of the array. Space complexity is constant" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T10:29:30.973", "Id": "222798", "ParentId": "222772", "Score": "1" } }
<h3>Problem</h3> <p>Write a method to return a boolean if an input grid is magic square.</p> <hr> <p>A magic square is a <span class="math-container">\$NxN\$</span> square grid (where N is the number of cells on each side) filled with distinct positive integers in the range <span class="math-container">\${1,2,...,n^{2}}\$</span> such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal. The sum is called the magic constant or magic sum of the magic square. </p> <p><a href="https://i.stack.imgur.com/cmWko.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cmWko.png" alt="enter image description here"></a></p> <hr> <h3>Code</h3> <p>I've tried to solve the above problem. If you'd like to review the code and provide any change/improvement recommendations please do so, and I'd really appreciate that.</p> <pre><code>from typing import List import numpy as np def is_magic_square(grid: List[List[int]]) -&gt; bool: """Returns a boolean if an input grid is magic square""" try: grid_length = len(grid) magic_sum = float(grid_length * (grid_length ** 2 + 1) / 2) diag_positive, diag_negative = [], [] diag_count_positive = 0 diag_count_negative = grid_length - 1 col_grid = np.zeros(shape=(grid_length, grid_length)) unique_elements = set() for index_row, lists in enumerate(grid): diag_negative.append(lists[diag_count_negative]) diag_count_negative -= 1 if len(grid[index_row]) != grid_length: return False if sum(lists) != magic_sum: return False for index_col in range(grid_length): unique_elements.add(lists[index_col]) col_grid[index_col][index_row] = lists[index_col] if index_col == grid_length and index_row == grid_length - 1 and len(unique_elements) != grid_length ** 2 - 1: return False if index_row == grid_length - 1: sum_col = sum(col_grid) temp_col = np.array([magic_sum] * grid_length) if str(temp_col) != str(sum_col): return False if diag_count_positive == index_row: diag_positive.append(lists[index_row]) diag_count_positive += 1 if diag_count_positive == grid_length and sum(diag_positive) != magic_sum: return False if index_row == grid_length - 1 and sum(diag_negative) != magic_sum: return False except: return False return True if __name__ == '__main__': # ---------------------------- TEST --------------------------- DIVIDER_DASH_LINE = '-' * 50 GREEN_APPLE = '\U0001F34F' RED_APPLE = '\U0001F34E' magic_squares = [ [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]], [[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]], [[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]], [[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]], [[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]], [[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]], [[8, 1, 6], [3, 5, 7], [4, 9, 2]] ] for magic_square in magic_squares: print(DIVIDER_DASH_LINE) if is_magic_square(magic_square) is True: print(f'{GREEN_APPLE} "{magic_square}" is a magic square.') else: print(f'{RED_APPLE} "{magic_square}" is not a magic square.') </code></pre> <h3>Output</h3> <pre><code>-------------------------------------------------- "[[4, 3, 8], [9, 5, 1], [2, 7, 6]]" is a magic square. -------------------------------------------------- "[[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]]" is a magic square. -------------------------------------------------- "[[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]]" is a magic square. -------------------------------------------------- "[[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]]" is not a magic square. -------------------------------------------------- "[[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]]" is a magic square. -------------------------------------------------- "[[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]]" is not a magic square. -------------------------------------------------- "[[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]]" is a magic square. -------------------------------------------------- "[[8, 1, 6], [3, 5, 7], [4, 9, 2]]" is a magic square. </code></pre> <h3>Source</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Magic_square" rel="noreferrer">Magic Square - Wiki</a></li> </ul>
230972
GOOD_ANSWER
{ "AcceptedAnswerId": "230978", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T18:35:13.637", "Id": "230972", "Score": "7", "Tags": [ "python", "beginner", "algorithm", "matrix", "mathematics" ], "Title": "Magic Square (Python)" }
{ "body": "<p>I normally don't like to do complete rewrites for reviews as I don't think that they're usually helpful. Here though, the major problem that I see with your code is you're trying to do far too much \"manually\". You aren't making good use of built-in Python constructs that automate some of the painful elements. You also have everything in one massive block. I rewrote this from scratch to show how I'd approach the problem fresh.</p>\n\n<p>There are a few discrete problems to solve here:</p>\n\n<ul>\n<li><p>Check that each sums correctly:</p>\n\n<ul>\n<li>Rows</li>\n<li>Columns</li>\n<li>Diagonals</li>\n</ul></li>\n<li><p>Check that the square is in fact a square.</p></li>\n<li><p>Check that it contains the correct set of numbers.</p></li>\n</ul>\n\n<p>I see each of these as distinct problems that should be handled separately. In your current code, you have everything mixed together in one massive function which makes it difficult to tell what is responsible for what job. It's simply not very easy code to read.</p>\n\n<p>I ended up breaking the problem up into multiple <em>tiny</em> functions, then tying everything together in <code>is_magic_square</code>:</p>\n\n<pre><code>from typing import List, Iterable, Callable\nfrom functools import partial\n\nGrid = List[List[int]] # Might as well create an alias for this\n\ndef has_correct_dimensions(grid: Grid) -&gt; bool:\n \"\"\"Returns whether or not the grid is a non-jagged square.\"\"\"\n return all(len(row) == len(grid) for row in grid)\n\n\ndef is_normal_square(grid: Grid) -&gt; bool:\n \"\"\"Returns whether or not the function contains unique numbers from 1 to n**2.\"\"\"\n max_n = len(grid[0]) ** 2\n # Does the set of numbers in the flattened grid contain the same numbers as a range set from 1 to n**2?\n return set(e for row in grid for e in row) == set(range(1, max_n + 1)) \n\n\ndef check_each(iterable: Iterable[Iterable[int]], magic_sum: int) -&gt; bool:\n \"\"\"Returns whether or not every sub-iterable collection sums to the magic sum\"\"\"\n return all(sum(elem) == magic_sum for elem in iterable)\n\n\ndef diagonal_of(grid: Grid, y_indexer: Callable[[int], int]) -&gt; Iterable[int]:\n \"\"\"Generates a line of elements from the grid. y = y_indexer(x).\"\"\"\n return (grid[y_indexer(x)][x] for x in range(len(grid)))\n\n\ndef is_magic_square(grid: Grid) -&gt; bool:\n \"\"\"Returns whether or not the supplied grid is a proper normal magic square.\"\"\"\n n_rows = len(grid)\n magic_sum = n_rows * (n_rows ** 2 + 1) / 2\n\n check = partial(check_each, magic_sum=magic_sum)\n\n return is_normal_square(grid) and \\\n has_correct_dimensions(grid) and \\\n check(grid) and \\ # Rows\n check(zip(*grid)) and \\ # Columns\n check([diagonal_of(grid, lambda x: x),\n diagonal_of(grid, lambda x: len(grid) - x - 1)])\n</code></pre>\n\n<p>Notice how I have small functions with well defined jobs. Also note how I'm making fairly extensive use of high-level Python helpers. <code>all</code> is great whenever you need to ensure that something is True across over an entire collection. And <code>zip</code> can be used to break the grid into columns. </p>\n\n<p>Even with this all broken up into functions, it's still 7 lines shorter than the original. It's also ~10x faster which I certainly didn't expect since I'm doing expensive shortcut stuff like <code>set(e for row in grid for e in row) == set(range(1, max_n + 1))</code>.</p>\n\n<p>My solutions is far from perfect though. Like I said above, I'm doing a few things quite wastefully. I'm using a lot of lazy operations (like with generator expressions), and repeatedly putting a whole <code>range</code> into a set over and over.</p>\n\n<p>The <code>return</code> in <code>is_magic_square</code> could probably be broken up too. I think it's fine, but it might make some people gag. It could be cleaned up a bit using <code>all</code>:</p>\n\n<pre><code>return all([is_normal_square(grid),\n has_correct_dimensions(grid),\n check(grid),\n check(zip(*grid)),\n check([diagonal_of(grid, lambda x: x),\n diagonal_of(grid, lambda x: len(grid) - x - 1)])])\n</code></pre>\n\n<p>At least that gets rid of the ugly line continuations.</p>\n\n<hr>\n\n<p>The major thing in your code that I will point out though is this atrocity:</p>\n\n<pre><code>except:\n return False\n</code></pre>\n\n<p>I think I've mentioned this before: don't do this. If you need to catch an exception, specify the exception, and keep the <code>try</code> in the narrowest scope necessary.</p>\n\n<p>Why? Because, case and point, when I tried to time your function, <code>timeit</code> was showing that your function was executing <em>one million times in 2 seconds</em>. I was blown away. Then I ran the tests though and saw that your code was returning <code>False</code> for every test. After some quick checking, I realized that I had forgotten to import numpy when I pasted your code.</p>\n\n<p>Your code was returning a valid result even though the required packages for the code to run weren't even imported. Stuff like that will eventually bite you via long, painful debugging sessions. Silencing errors is, in my opinion, literally one of the worst things you can possibly do when programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T21:10:32.593", "Id": "230978", "ParentId": "230972", "Score": "6" } }
<h3>Problem</h3> <p>Write a method to return a boolean if an input grid is magic square.</p> <hr> <p>A magic square is a <span class="math-container">\$NxN\$</span> square grid (where N is the number of cells on each side) filled with distinct positive integers in the range <span class="math-container">\${1,2,...,n^{2}}\$</span> such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal. The sum is called the magic constant or magic sum of the magic square. </p> <p><a href="https://i.stack.imgur.com/cmWko.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cmWko.png" alt="enter image description here"></a></p> <hr> <h3>Code</h3> <p>I've tried to solve the above problem. If you'd like to review the code and provide any change/improvement recommendations please do so, and I'd really appreciate that.</p> <pre><code>from typing import List import numpy as np def is_magic_square(grid: List[List[int]]) -&gt; bool: """Returns a boolean if an input grid is magic square""" try: grid_length = len(grid) magic_sum = float(grid_length * (grid_length ** 2 + 1) / 2) diag_positive, diag_negative = [], [] diag_count_positive = 0 diag_count_negative = grid_length - 1 col_grid = np.zeros(shape=(grid_length, grid_length)) unique_elements = set() for index_row, lists in enumerate(grid): diag_negative.append(lists[diag_count_negative]) diag_count_negative -= 1 if len(grid[index_row]) != grid_length: return False if sum(lists) != magic_sum: return False for index_col in range(grid_length): unique_elements.add(lists[index_col]) col_grid[index_col][index_row] = lists[index_col] if index_col == grid_length and index_row == grid_length - 1 and len(unique_elements) != grid_length ** 2 - 1: return False if index_row == grid_length - 1: sum_col = sum(col_grid) temp_col = np.array([magic_sum] * grid_length) if str(temp_col) != str(sum_col): return False if diag_count_positive == index_row: diag_positive.append(lists[index_row]) diag_count_positive += 1 if diag_count_positive == grid_length and sum(diag_positive) != magic_sum: return False if index_row == grid_length - 1 and sum(diag_negative) != magic_sum: return False except: return False return True if __name__ == '__main__': # ---------------------------- TEST --------------------------- DIVIDER_DASH_LINE = '-' * 50 GREEN_APPLE = '\U0001F34F' RED_APPLE = '\U0001F34E' magic_squares = [ [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]], [[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]], [[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]], [[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]], [[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]], [[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]], [[8, 1, 6], [3, 5, 7], [4, 9, 2]] ] for magic_square in magic_squares: print(DIVIDER_DASH_LINE) if is_magic_square(magic_square) is True: print(f'{GREEN_APPLE} "{magic_square}" is a magic square.') else: print(f'{RED_APPLE} "{magic_square}" is not a magic square.') </code></pre> <h3>Output</h3> <pre><code>-------------------------------------------------- "[[4, 3, 8], [9, 5, 1], [2, 7, 6]]" is a magic square. -------------------------------------------------- "[[9, 3, 22, 16, 15], [2, 21, 20, 14, 8], [25, 19, 13, 7, 1], [18, 12, 6, 5, 24], [11, 10, 4, 23, 17]]" is a magic square. -------------------------------------------------- "[[60, 53, 44, 37, 4, 13, 20, 29], [3, 14, 19, 30, 59, 54, 43, 38], [58, 55, 42, 39, 2, 15, 18, 31], [1, 16, 17, 32, 57, 56, 41, 40], [61, 52, 45, 36, 5, 12, 21, 28], [6, 11, 22, 27, 62, 51, 46, 35], [63, 50, 47, 34, 7, 10, 23, 26], [8, 9, 24, 25, 64, 49, 48, 33]]" is a magic square. -------------------------------------------------- "[[35, 26, 17, 1, 62, 53, 44], [46, 37, 21, 12, 3, 64, 55], [57, 41, 32, 23, 14, 5, 66], [61, 52, 43, 34, 25, 16, 7], [2, 63, 54, 45, 36, 27, 11], [13, 4, 65, 56, 47, 31, 22], [24, 15, 6, 67, 51, 42, 33]]" is not a magic square. -------------------------------------------------- "[[1, 35, 4, 33, 32, 6], [25, 11, 9, 28, 8, 30], [24, 14, 18, 16, 17, 22], [13, 23, 19, 21, 20, 15], [12, 26, 27, 10, 29, 7], [36, 2, 34, 3, 5, 31]]" is a magic square. -------------------------------------------------- "[[16, 14, 7, 30, 23], [24, 17, 10, 8, 31], [32, 25, 18, 11, 4], [5, 28, 26, 19, 12], [13, 6, 29, 22, 20]]" is not a magic square. -------------------------------------------------- "[[1, 14, 4, 15], [8, 11, 5, 10], [13, 2, 16, 3], [12, 7, 9, 6]]" is a magic square. -------------------------------------------------- "[[8, 1, 6], [3, 5, 7], [4, 9, 2]]" is a magic square. </code></pre> <h3>Source</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Magic_square" rel="noreferrer">Magic Square - Wiki</a></li> </ul>
230972
GOOD_ANSWER
{ "AcceptedAnswerId": "230978", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T18:35:13.637", "Id": "230972", "Score": "7", "Tags": [ "python", "beginner", "algorithm", "matrix", "mathematics" ], "Title": "Magic Square (Python)" }
{ "body": "<p>One should almost never use a bare <code>except</code> clause. It should always list the exceptions to be caught.</p>\n\n<p>The code would be easier to read and understand, if it were written in section that each tested one aspect of a magic square. Like, is is a square, does it have all the numbers in sequence, do the rows add up to the magic number, do the columns, do the diagonals. Here is a pure python version:</p>\n\n<pre><code>def is_magic_square(grid: List[List[int]]) -&gt; bool:\n \"\"\"Returns a boolean if an input grid is magic square\"\"\"\n\n grid_length = len(grid)\n grid_area = grid_length**2\n magic_sum = float(grid_length * (grid_length ** 2 + 1) / 2)\n\n # check the length of all rows\n if any(len(row) != grid_length for row in grid):\n return False\n\n # check it has all the numbers in sequence \n if set(x for row in grid for x in row) != set(range(1, grid_area + 1)):\n return False\n\n # check all the rows add up to the magic_number\n if any(sum(row) != magic_sum for row in grid):\n return False\n\n # check all the columns add up to the magic_number\n if any(sum(row[col] for row in grid) != magic_sum for col in range(grid_length)):\n return False\n\n # check each diagonal adds up to the magic_number\n if (sum(grid[i][i] for i in range(grid_length)) != magic_sum\n or sum(grid[i][grid_length-i-1] for i in range(grid_length)) != magic_sum ):\n return False\n\n return True\n</code></pre>\n\n<p>Your code used numpy, it has many useful functions for this task. So here is an alternative version using numpy:</p>\n\n<pre><code>def is_magic_square2(grid: List[List[int]]) -&gt; bool:\n \"\"\"Returns a boolean if an input grid is magic square\"\"\"\n\n grid_length = len(grid)\n magic_sum = float(grid_length * (grid_length ** 2 + 1) / 2)\n\n # check the length of all rows\n if any(len(row) != grid_length for row in grid):\n return False\n\n npgrid = np.array(grid)\n\n # check it has all ints from 1 to grid_length**2 (inclusive)\n if len(np.setdiff1d(npgrid, np.arange(1, grid_length**2 + 1))):\n return False\n\n # check all the rows add up to the magic_number\n if any(np.not_equal(npgrid.sum(axis=0), magic_sum)):\n return False\n\n # check all the columns add up to the magic_number\n if any(np.not_equal(npgrid.sum(axis=1), magic_sum)):\n return False\n\n # check both diagonals add up to the magic_number\n if (npgrid.diagonal().sum() != magic_sum\n or np.fliplr(npgrid).diagonal().sum() != magic_sum):\n return False\n\n return True\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-18T22:57:29.520", "Id": "230980", "ParentId": "230972", "Score": "4" } }
<p>I created this program originally for <a href="https://projecteuler.net/problem=14" rel="nofollow noreferrer">Project Euler 14</a>.</p> <p>Here's the code:</p> <pre><code>from sys import setrecursionlimit setrecursionlimit(10 ** 9) def memo(f): f.cache = {} def _f(*args): if args not in f.cache: f.cache[args] = f(*args) return f.cache[args] return _f @memo def collatz(n): if n == 1: return 1 if n % 2: print(3 * n + 1) return 1 + collatz(3 * n + 1) if not n % 2: print(n // 2) return 1 + collatz(n // 2) if __name__ == '__main__': number = None while True: try: number = input('Please enter a number: ') number = int(number) break except ValueError: print(f'Value has to be an interger instead of "{number}"\n') print('\nThe collatz sequence: ') length = collatz(number) print(f'\nLength of the collatz sequence for {number}: {length}') </code></pre> <p>I would like to make this faster and neater if possible.</p>
232981
GOOD_ANSWER
{ "AcceptedAnswerId": "233046", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T08:42:06.470", "Id": "232981", "Score": "2", "Tags": [ "python", "python-3.x", "collatz-sequence" ], "Title": "Collatz sequence using Python 3.x" }
{ "body": "<h2>Useless Code</h2>\n\n<p>Your <code>@memo</code>-ization doesn't do anything of value:</p>\n\n<ul>\n<li>Your mainline calls <code>collatz()</code> exactly once. Unless given the value <code>1</code>, the <code>collatz()</code> function calls itself with <code>3*n + 1</code> or <code>n // 2</code>, and since the Collatz sequence doesn't have any loops until the value <code>1</code> is reached, it will never call itself with a value it has already been called with. So, you are memoizing values which will never, ever be used.</li>\n<li>Your <code>collatz()</code> function doesn't just return a value; it has a side-effect: printing! If you did call <code>collatz()</code> with a value that has already been memoized, nothing will be printed.</li>\n</ul>\n\n<h2>Tail Call, without Tail Call Optimization</h2>\n\n<p>You've increased the recursion limit to <span class=\"math-container\">\\$10^9\\$</span> stack levels, which is impressive. But the algorithm doesn't need to be recursive. A simple loop would work. And since Python cannot do Tail Call Optimization, you should replace recursion with loops wherever possible. Doing so eliminates the need for the increased stack limit:</p>\n\n<pre><code>def collatz(n):\n count = 1\n\n while n &gt; 1:\n if n % 2 != 0:\n n = n * 3 + 1\n else:\n n //= 2\n\n print(n)\n count += 1\n\n return count\n</code></pre>\n\n<h2>Separate Sequence Generation from Printing</h2>\n\n<p>You can create a very simple Collatz sequence generator:</p>\n\n<pre><code>def collatz(n):\n while n &gt; 1:\n yield n\n n = n * 3 + 1 if n % 2 else n // 2\n yield 1\n</code></pre>\n\n<p>Using this generator, the caller can print out the Collatz sequence with a simple loop:</p>\n\n<pre><code>for x in collatz(13):\n print(x)\n</code></pre>\n\n<p>Or, if the caller just wants the length of the Collatz sequence, without printing out each item in the sequence, you can determine the length of the sequence with <code>len(list(collatz(13)))</code>. Better would be to count the items returned by the generator without realizing the list in memory: <code>sum(1 for _ in collatz(13))</code>.</p>\n\n<h2>Project Euler 14</h2>\n\n<p>The above generator works great for determining the sequence from any arbitrary value. If you want to compute the length of <code>collatz(n)</code> for <span class=\"math-container\">\\$1 \\le n \\le 1,000,000\\$</span>, you may want to return to memoization. However, this is Code Review, and while you alluded to PE14, you didn't actually provide code for that, so that cannot be reviewed here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T04:51:06.740", "Id": "233046", "ParentId": "232981", "Score": "2" } }
<p>I am a beginner so please keep it in mind while answering! <strong>For player vs CPU is there any more effective way to make CPU better ??</strong></p> <pre><code>import numpy as np board=['-','-','-', '-','-','-', '-','-','-'] def check_win(): global winner global game_over if board[0]=='X' and board[1]=='X' and board[2]=='X': winner='Player' game_over=True elif board[3]=='X' and board[4]=='X' and board[5]=='X': winner='Player' game_over=True elif board[6]=='X' and board[7]=='X' and board[8]=='X': winner='Player' game_over=True elif board[0]=='X' and board[4]=='X' and board[8]=='X': winner='Player' game_over=True elif board[2]=='X' and board[4]=='X' and board[6]=='X': winner='Player' game_over=True elif board[0]=='X' and board[3]=='X' and board[6]=='X': winner='Player' game_over=True elif board[1]=='X' and board[4]=='X' and board[7]=='X': winner='Player' game_over=True elif board[2]=='X' and board[5]=='X' and board[8]=='X': winner='Player' game_over=True elif board[0]=='O' and board[1]=='O' and board[2]=='O': winner='CPU' game_over=True elif board[3]=='O' and board[4]=='O' and board[5]=='O': winner='CPU' game_over=True elif board[6]=='O' and board[7]=='O' and board[8]=='O': winner='CPU' game_over=True elif board[0]=='O' and board[4]=='O' and board[8]=='O': winner='CPU' game_over=True elif board[2]=='O' and board[4]=='O' and board[6]=='O': winner='CPU' game_over=True elif board[0]=='O' and board[3]=='O' and board[6]=='O': winner='CPU' game_over=True elif board[2]=='O' and board[5]=='O' and board[8]=='O': winner='CPU' game_over=True def res_gm(): board=['-','-','-', '-','-','-', '-','-','-'] play_game() def player_turn(): a=int(input("Enter the position to pux X (1-9) : ")) valid=False while valid==False: if a&lt;=9 and board[a-1]=='-': board[a-1]='X' valid=True elif a=='': print("You Cannot Leave This Empty") else: print("This move is invalid ! ") a=int(input("Enter the position to pux X (1-9) : ")) def Compute(): if board[0]=='O' and board[1]=='O' and board[2]=='-': board[2]='O' main_board() elif board[0]=='O' and board[2]=='O' and board[1]=='-': board[1]='O' main_board() elif board[1]=='O' and board[2]=='O' and board[0]=='-': board[0]='O' main_board() elif board[3]=='O' and board[4]=='O' and board[5]=='-': board[5]='O' main_board() elif board[3]=='O' and board[5]=='O' and board[4]=='-': board[4]='O' main_board() elif board[4]=='O' and board[5]=='O' and board[3]=='-': board[3]='O' main_board() elif board[6]=='O' and board[7]=='O' and board[8]=='-': board[8]='O' main_board() elif board[7]=='O' and board[8]=='O' and board[6]=='-': board[6]='O' main_board() elif board[6]=='O' and board[8]=='O' and board[7]=='-': board[7]='O' main_board() elif board[0]=='O' and board[4]=='O' and board[8]=='-': board[8]='O' main_board() elif board[4]=='O' and board[8]=='O' and board[0]=='-': board[0]='O' main_board() elif board[0]=='O' and board[8]=='O' and board[4]=='-': board[4]='O' main_board() elif board[0]=='X' and board[1]=='X' and board[2]=='-': board[2]='O' main_board() elif board[0]=='X' and board[2]=='X' and board[1]=='-': board[1]='O' main_board() elif board[1]=='X' and board[2]=='X' and board[0]=='-': board[0]='O' main_board() elif board[3]=='X' and board[4]=='X' and board[5]=='-': board[5]='O' main_board() elif board[3]=='X' and board[5]=='X' and board[4]=='-': board[4]='O' main_board() elif board[4]=='X' and board[5]=='X' and board[3]=='-': board[3]='O' main_board() elif board[6]=='X' and board[7]=='X' and board[8]=='-': board[8]='O' main_board() elif board[7]=='X' and board[8]=='X' and board[6]=='-': board[6]='O' main_board() elif board[6]=='X' and board[8]=='X' and board[7]=='-': board[7]='O' main_board() elif board[0]=='X' and board[4]=='X' and board[8]=='-': board[8]='O' main_board() elif board[4]=='X' and board[8]=='X' and board[0]=='-': board[0]='O' main_board() elif board[0]=='X' and board[8]=='X' and board[4]=='-': board[4]='O' main_board() elif board[0]=='X' and board[3]=='X' and board[6]=='-': board[6]='O' main_board() elif board[2]=='X' and board[5]=='X' and board[8]=='-': board[8]='O' main_board() elif board[1]=='X' and board[4]=='X' and board[7]=='-': board[7]='O' main_board() else: valid=False while valid==False: b=np.random.randint(0,9) if board[b]=='-': board[b]='O' main_board() valid=True else: valid=False def main_board(): print(board[0]+'|'+board[1]+'|'+board[2]+' For reference 1|2|3') print(board[3]+'|'+board[4]+'|'+board[5]+' 4|5|6') print(board[6]+'|'+board[7]+'|'+board[8]+' 7|8|9') def play_game(): global game_over global winner main_board() game_over=False n=0 while game_over==False: if n&lt;9 and n%2==0: player_turn() n+=1 check_win() elif n&lt;9 and n%2!=0: Compute() check_win() n=n+1 elif n==9 and board[0]!='-' and board[1]!='-' and board[2]!='-' and board[3]!='-'and board[4]!='-' and board[5]!='-' and board[6]!='-' and board[7]!='-' and board[8]!='-' and game_over==False: print('Tie') winner='None' game_over=True print('The winner is ',winner) print('Choose a game mode : \n1. Player Vs CPU \n2. Player1 vs Player2') q=int(input('Enter the Corresponding number of game mode : ')) while q in [1,2,3]: if q==1: p='y' while p=='y': play_game() p=str(input('Want to play again ? ')) else: print('Exiting Game!') q=3 elif q==2: print('this game mode is not available yet, ask Utkarsh to develop it ') q=int(input('Enter the Corresponding number of game mode : ')) else: quit() else: print('There is no game mode like this ') q=int(input('Enter the Corresponding number of game mode : ')) </code></pre>
236229
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T13:07:12.413", "Id": "236229", "Score": "0", "Tags": [ "python", "python-3.x", "tic-tac-toe" ], "Title": "Tic-Tac-Toe game suggestion" }
{ "body": "<p>You need to fix indentation for the program to run (the fix is easy though, just look at the elif branches on line 102 onwards).</p>\n\n<p>What you've essentially done is an explicit if-else structure where you've hardcoded all possible positions. While this works, it's quite difficult to read and it's easy to make mistakes. Thus, it would be a good idea to use a data structure not only for the board, but for the wins (rows, diagonals, columns) as well:</p>\n\n<pre><code>player_symbol = 'X'\ncpu_symbol = 'O'\n\nboard=np.array(['-','-','-',\n '-','-','-',\n '-','-','-'])\n\nwins = [\n [0,1,2], [3,4,5], [6,7,8], # rows\n [0,4,8], [2,4,6], # diagonals\n [0,3,6], [1,4,7], [2,5,8], # columns\n ]\n</code></pre>\n\n<p>Now, to check for a win we can do something much simpler like:</p>\n\n<pre><code>def check_win():\n player_win = any(len(set(board[pos])) == 1 and player_symbol in board[pos] for pos in wins)\n cpu_win = any(len(set(board[pos])) == 1 and cpu_symbol in board[pos] for pos in wins)\n\n game_over = player_win or cpu_win\n winner = None\n if game_over:\n winner = 'Player' if player_win else 'CPU'\n\n return game_over, winner\n</code></pre>\n\n<p>In here, note that we can simply return values and we don't need global variables which are always difficult to reason about. Further, the \"win checks\" a reduced to simple generator expression: it goes over each element of <code>wins</code>, grabs the corresponding row, column or diagonal from <code>board</code>, checks to see if it has all of the same symbols (i.e., if the <code>set</code> taken over the elements of <code>board</code> has size 1) <em>and</em> checks if the unique symbol it contains is the <code>player_symbol</code> or <code>cpu_symbol</code>.</p>\n\n<ul>\n<li><p>For <code>Compute()</code>, the function could use a better name: it starts with an uppercase letter while all the other functions don't. Also, <code>compute()</code> is a very generic name and it doesn't explain what the function is supposed to move. So perhaps a better name would be e.g., <code>compute_cpu_move()</code>. </p></li>\n<li><p>Now, using the same logic we <em>could</em> beautify <code>Compute()</code> as well but this is not necessarily a great idea. If you are interested in more challenge, you could make the CPU <em>perfect</em> by <a href=\"https://en.wikipedia.org/wiki/Tic-tac-toe#Strategy\" rel=\"nofollow noreferrer\">playing with the optimal strategy</a> or implementing the <a href=\"https://en.wikipedia.org/wiki/Minimax\" rel=\"nofollow noreferrer\">minimax algorithm</a>. </p></li>\n</ul>\n\n<p>There's definitely more we could say here as well, but I hope this is enough to get you going. There are tons of questions and resources on tic-tac-toe on this site and elsewhere online that you can get more inspiration from.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-27T14:11:55.133", "Id": "236234", "ParentId": "236229", "Score": "2" } }
<p>Wrote a python script to web scrape multiple newspapers and arrange them in their respective directories. I have completed the course Using Python to access web data on coursera and I tried to implement what I learned by a mini project. I am sure there would be multiple improvements to this script and I would like to learn and implement them to better.</p> <pre><code>import urllib.request, urllib.error, urllib.parse from bs4 import BeautifulSoup import ssl import requests import regex as re import os from datetime import date, timedelta today = date.today() ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE def is_downloadable(url): """ Does the url contain a downloadable resource """ h = requests.head(url, allow_redirects=True) header = h.headers content_type = header.get('content-type') if 'text' in content_type.lower(): return False if 'html' in content_type.lower(): return False return True # dictionary for newspaper names and their links newspaper = dict({'Economic_times':'https://dailyepaper.in/economic-times-epaper-pdf-download-2020/', 'Times_of_India':'https://dailyepaper.in/times-of-india-epaper-pdf-download-2020/', 'Financial_Express':'https://dailyepaper.in/financial-express-epaper-pdf-download-2020/', 'Deccan_Chronicle':'https://dailyepaper.in/deccan-chronicle-epaper-pdf-download-2020/', 'The_Telegraph':'https://dailyepaper.in/the-telegraph-epaper-pdf-download-2020/', 'The_Pioneer':'https://dailyepaper.in/the-pioneer-epaper-pdf-download-2020/', 'Business_Line':'https://dailyepaper.in/business-line-epaper-pdf-download-2020/', 'Indian_Express':'https://dailyepaper.in/indian-express-epaper-pdf-download-2020/', 'Hindustan_Times':'https://dailyepaper.in/hindustan-times-epaper-pdf-free-download-2020/', 'The_Hindu':'https://dailyepaper.in/the-hindu-pdf-newspaper-free-download/', 'Dainik_Jagran':'https://dailyepaper.in/dainik-jagran-newspaper-pdf/', 'Dainik_Bhaskar':'https://dailyepaper.in/dainik-bhaskar-epaper-pdf-download-2020/', 'Amar_Ujala':'https://dailyepaper.in/amar-ujala-epaper-pdf-download-2020/'}) #dictionary to give serial numbers to each newspaper #I think something better could be done instead of this dictionary serial_num = dict({1:'Economic_times', 2:'Times_of_India', 3:'Financial_Express', 4:'Deccan_Chronicle', 5:'The_Telegraph', 6:'The_Pioneer', 7:'Business_Line', 8:'Indian_Express', 9:'Hindustan_Times', 10:'The_Hindu', 11:'Dainik_Jagran', 12:'Dainik_Bhaskar', 13:'Amar_Ujala'}) print("The following Newspapers are available for download. Select any of them by giving number inputs - ") print("1. Economic Times") print("2. Times of India") print("3. Financial Express") print("4. Deccan Chronicle") print("5. The Telegraph") print("6. The Pioneer") print("7. Business Line") print("8. Indian Express") print("9. Hindustan Times") print("10. The Hindu") print("11. Dainik Jagran") print("12. Dainik Bhaskar") print("13. Amar Ujala") #taking serial numbers for multiple nespapers and storing them in a list serial_index = input('Enter the number for newspapers - ') serial_index = serial_index.split() indices = [int(x) for x in serial_index] for ser_ind in indices: url = newspaper[serial_num[ser_ind]] req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, 'html.parser') tags = soup('a') list_paper = list() directory = serial_num[ser_ind] parent_dir = os.getcwd() path = os.path.join(parent_dir, directory) #make a new directory for given newspaper, if that exists then do nothing try: os.mkdir(path) except OSError as error: pass os.chdir(path) #enter the directory for newspaper #storing links for given newspaper in a list for i in range(len(tags)): links = tags[i].get('href',None) x = re.search("^https://vk.com/", links) if x: list_paper.append(links) print('For how many days you need the '+ serial_num[ser_ind]+' paper?') print('i.e. if only todays paper press 1, if want whole weeks paper press 7') print('Size of each paper is 5-12MB') for_how_many_days = int(input('Enter your number - ')) for i in range(for_how_many_days): url = list_paper[i] req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, 'html.parser') tags = soup('iframe') link = tags[0].get('src',None) date_that_day = today - timedelta(days=i) #getting the date if is_downloadable(link): print('Downloading '+serial_num[ser_ind]+'...') r = requests.get(link, allow_redirects=True) with open(serial_num[ser_ind]+"_"+str(date_that_day)+".pdf",'wb') as f: f.write(r.content) print('Done :)') else: print(serial_num[ser_ind] + ' paper not available for '+ str(date_that_day)) os.chdir('../') #after downloading all the newspapers go back to parent directory <span class="math-container">```</span> </code></pre>
242951
GOOD_ANSWER
{ "AcceptedAnswerId": "242952", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T13:19:50.150", "Id": "242951", "Score": "3", "Tags": [ "python", "beginner", "web-scraping" ], "Title": "Web Scraping Newspapers" }
{ "body": "<h2>Usage of requests</h2>\n\n<p>Strongly consider replacing your use of bare <code>urllib</code> with <code>requests</code>. It's much more usable. Among other things, it should prevent you from having to worry about an SSL context.</p>\n\n<h2>Type hints</h2>\n\n<pre><code>def is_downloadable(url):\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def is_downloadable(url: str) -&gt; bool:\n</code></pre>\n\n<p>And so on for your other functions.</p>\n\n<h2>Boolean expressions</h2>\n\n<pre><code>content_type = header.get('content-type')\nif 'text' in content_type.lower():\n return False\nif 'html' in content_type.lower():\n return False\nreturn True\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>content_type = header.get('content-type', '').lower()\nreturn not (\n 'text' in content_type or\n 'html' in content_type\n)\n</code></pre>\n\n<p>Also note that if a content type is not provided, this function will crash unless you change the default of the <code>get</code> to <code>''</code>.</p>\n\n<h2>Dictionary literals</h2>\n\n<p>This:</p>\n\n<pre><code>newspaper = dict({ ...\n</code></pre>\n\n<p>does not need a call to <code>dict</code>; simply use the braces and they will make a dictionary literal.</p>\n\n<h2>URL database</h2>\n\n<p>Note what is common in all of your newspaper links and factor it out. In other words, all URLs match the pattern</p>\n\n<pre><code>https://dailyepaper.in/...\n</code></pre>\n\n<p>so you do not need to repeat the protocol and host in those links; save that to a different constant.</p>\n\n<h2>Newspaper objects</h2>\n\n<blockquote>\n <p>dictionary to give serial numbers to each newspaper</p>\n \n <p>I think something better could be done instead of this dictionary</p>\n</blockquote>\n\n<p>Indeed. Rather than keeping separate dictionaries, consider making a <code>class Newspaper</code> with attributes <code>name: str</code>, <code>link: str</code> and <code>serial: int</code>.</p>\n\n<p>Then after <code>The following Newspapers are available for download</code>, do not hard-code that list; instead loop through your sequence of newspapers and output their serial number and name.</p>\n\n<h2>List literals</h2>\n\n<pre><code>list_paper = list()\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>papers = []\n</code></pre>\n\n<h2>Get default</h2>\n\n<p>Here:</p>\n\n<pre><code>links = tags[i].get('href',None)\n</code></pre>\n\n<p><code>None</code> is the implicit default, so you can omit it. However, it doesn't make sense for you to allow <code>None</code>, because you immediately require a non-null string:</p>\n\n<pre><code>x = re.search(\"^https://vk.com/\", links)\n</code></pre>\n\n<p>so instead you probably want <code>''</code> as a default.</p>\n\n<h2>String interpolation</h2>\n\n<pre><code>'For how many days you need the '+ serial_num[ser_ind]+' paper?'\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>f'For how many days do you need the {serial_num[ser_ind]} paper?'\n</code></pre>\n\n<h2>Raw transfer</h2>\n\n<pre><code> r = requests.get(link, allow_redirects=True)\n with open(serial_num[ser_ind]+\"_\"+str(date_that_day)+\".pdf\",'wb') as f:\n f.write(r.content)\n</code></pre>\n\n<p>requires that the entire response be loaded into memory before being written out to a file. In the (unlikely) case that the file is bigger than your memory, the program will probably crash. Instead, consider using <code>requests</code>, passing <code>stream=True</code> to your <code>get</code>, and passing <code>response.raw</code> to <code>shutil.copyfileobj</code>. This will stream the response directly to the disk with a much smaller buffer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T14:28:53.797", "Id": "242952", "ParentId": "242951", "Score": "4" } }
<p>Wrote a python script to web scrape multiple newspapers and arrange them in their respective directories. I have completed the course Using Python to access web data on coursera and I tried to implement what I learned by a mini project. I am sure there would be multiple improvements to this script and I would like to learn and implement them to better.</p> <pre><code>import urllib.request, urllib.error, urllib.parse from bs4 import BeautifulSoup import ssl import requests import regex as re import os from datetime import date, timedelta today = date.today() ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE def is_downloadable(url): """ Does the url contain a downloadable resource """ h = requests.head(url, allow_redirects=True) header = h.headers content_type = header.get('content-type') if 'text' in content_type.lower(): return False if 'html' in content_type.lower(): return False return True # dictionary for newspaper names and their links newspaper = dict({'Economic_times':'https://dailyepaper.in/economic-times-epaper-pdf-download-2020/', 'Times_of_India':'https://dailyepaper.in/times-of-india-epaper-pdf-download-2020/', 'Financial_Express':'https://dailyepaper.in/financial-express-epaper-pdf-download-2020/', 'Deccan_Chronicle':'https://dailyepaper.in/deccan-chronicle-epaper-pdf-download-2020/', 'The_Telegraph':'https://dailyepaper.in/the-telegraph-epaper-pdf-download-2020/', 'The_Pioneer':'https://dailyepaper.in/the-pioneer-epaper-pdf-download-2020/', 'Business_Line':'https://dailyepaper.in/business-line-epaper-pdf-download-2020/', 'Indian_Express':'https://dailyepaper.in/indian-express-epaper-pdf-download-2020/', 'Hindustan_Times':'https://dailyepaper.in/hindustan-times-epaper-pdf-free-download-2020/', 'The_Hindu':'https://dailyepaper.in/the-hindu-pdf-newspaper-free-download/', 'Dainik_Jagran':'https://dailyepaper.in/dainik-jagran-newspaper-pdf/', 'Dainik_Bhaskar':'https://dailyepaper.in/dainik-bhaskar-epaper-pdf-download-2020/', 'Amar_Ujala':'https://dailyepaper.in/amar-ujala-epaper-pdf-download-2020/'}) #dictionary to give serial numbers to each newspaper #I think something better could be done instead of this dictionary serial_num = dict({1:'Economic_times', 2:'Times_of_India', 3:'Financial_Express', 4:'Deccan_Chronicle', 5:'The_Telegraph', 6:'The_Pioneer', 7:'Business_Line', 8:'Indian_Express', 9:'Hindustan_Times', 10:'The_Hindu', 11:'Dainik_Jagran', 12:'Dainik_Bhaskar', 13:'Amar_Ujala'}) print("The following Newspapers are available for download. Select any of them by giving number inputs - ") print("1. Economic Times") print("2. Times of India") print("3. Financial Express") print("4. Deccan Chronicle") print("5. The Telegraph") print("6. The Pioneer") print("7. Business Line") print("8. Indian Express") print("9. Hindustan Times") print("10. The Hindu") print("11. Dainik Jagran") print("12. Dainik Bhaskar") print("13. Amar Ujala") #taking serial numbers for multiple nespapers and storing them in a list serial_index = input('Enter the number for newspapers - ') serial_index = serial_index.split() indices = [int(x) for x in serial_index] for ser_ind in indices: url = newspaper[serial_num[ser_ind]] req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, 'html.parser') tags = soup('a') list_paper = list() directory = serial_num[ser_ind] parent_dir = os.getcwd() path = os.path.join(parent_dir, directory) #make a new directory for given newspaper, if that exists then do nothing try: os.mkdir(path) except OSError as error: pass os.chdir(path) #enter the directory for newspaper #storing links for given newspaper in a list for i in range(len(tags)): links = tags[i].get('href',None) x = re.search("^https://vk.com/", links) if x: list_paper.append(links) print('For how many days you need the '+ serial_num[ser_ind]+' paper?') print('i.e. if only todays paper press 1, if want whole weeks paper press 7') print('Size of each paper is 5-12MB') for_how_many_days = int(input('Enter your number - ')) for i in range(for_how_many_days): url = list_paper[i] req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html, 'html.parser') tags = soup('iframe') link = tags[0].get('src',None) date_that_day = today - timedelta(days=i) #getting the date if is_downloadable(link): print('Downloading '+serial_num[ser_ind]+'...') r = requests.get(link, allow_redirects=True) with open(serial_num[ser_ind]+"_"+str(date_that_day)+".pdf",'wb') as f: f.write(r.content) print('Done :)') else: print(serial_num[ser_ind] + ' paper not available for '+ str(date_that_day)) os.chdir('../') #after downloading all the newspapers go back to parent directory <span class="math-container">```</span> </code></pre>
242951
WIERD
{ "AcceptedAnswerId": "242952", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T13:19:50.150", "Id": "242951", "Score": "3", "Tags": [ "python", "beginner", "web-scraping" ], "Title": "Web Scraping Newspapers" }
{ "body": "<p>Just one contribution from me: you can get rid of <strong>redundant</strong> declarations and make your code lighter. The newspapers should be defined just once and then reused. You are almost there. Build a list of dictionaries (or use a database).</p>\n\n<pre><code># dictionary for newspaper names and their links\nnewspapers = (\n {\"name\": 'Economic_times', 'url': 'https://dailyepaper.in/economic-times-epaper-pdf-download-2020/'},\n {\"name\": 'Times_of_India', 'url': 'https://dailyepaper.in/times-of-india-epaper-pdf-download-2020/'},\n {\"name\": 'Financial_Express', 'url': 'https://dailyepaper.in/financial-express-epaper-pdf-download-2020/'},\n {\"name\": 'Deccan_Chronicle', 'url': 'https://dailyepaper.in/deccan-chronicle-epaper-pdf-download-2020/'},\n {\"name\": 'The_Telegraph', 'url': 'https://dailyepaper.in/the-telegraph-epaper-pdf-download-2020/'},\n {\"name\": 'The_Pioneer', 'url': 'https://dailyepaper.in/the-pioneer-epaper-pdf-download-2020/'},\n {\"name\": 'Business_Line', 'url': 'https://dailyepaper.in/business-line-epaper-pdf-download-2020/'},\n {\"name\": 'Indian_Express', 'url': 'https://dailyepaper.in/indian-express-epaper-pdf-download-2020/'},\n {\"name\": 'Hindustan_Times', 'url': 'https://dailyepaper.in/hindustan-times-epaper-pdf-free-download-2020/'},\n {\"name\": 'The_Hindu', 'url': 'https://dailyepaper.in/the-hindu-pdf-newspaper-free-download/'},\n {\"name\": 'Dainik_Jagran', 'url': 'https://dailyepaper.in/dainik-jagran-newspaper-pdf/'},\n {\"name\": 'Dainik_Bhaskar', 'url': 'https://dailyepaper.in/dainik-bhaskar-epaper-pdf-download-2020/'},\n {\"name\": 'Amar_Ujala', 'url': 'https://dailyepaper.in/amar-ujala-epaper-pdf-download-2020/'}\n)\nprint(\"The following Newspapers are available for download. Select any of them by giving number inputs - \")\nfor counter, newspaper in enumerate(newspapers, start=1):\n print(f'{counter}. {newspaper[\"name\"]}')\n\nselected_numbers = input('Enter the number for newspapers - ')\n\nprint(\"You selected the following Newspapers:\")\nfor index in selected_numbers.split():\n newspaper_number = int(index)\n newspaper_detail = newspapers[newspaper_number-1]\n print(f\"Number: {newspaper_number}\")\n print(f\"Name: {newspaper_detail['name']}\")\n print(f\"URL: {newspaper_detail['url']}\")\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\nThe following Newspapers are available for download. Select any of them by giving number inputs - \n1. Economic_times\n2. Times_of_India\n3. Financial_Express\n4. Deccan_Chronicle\n5. The_Telegraph\n6. The_Pioneer\n7. Business_Line\n8. Indian_Express\n9. Hindustan_Times\n10. The_Hindu\n11. Dainik_Jagran\n12. Dainik_Bhaskar\n13. Amar_Ujala\nEnter the number for newspapers - 1 12 13\nYou selected the following Newspapers:\nNumber: 1\nName: Economic_times\nURL: https://dailyepaper.in/economic-times-epaper-pdf-download-2020/\nNumber: 12\nName: Dainik_Bhaskar\nURL: https://dailyepaper.in/dainik-bhaskar-epaper-pdf-download-2020/\nNumber: 13\nName: Amar_Ujala\nURL: https://dailyepaper.in/amar-ujala-epaper-pdf-download-2020/\n</pre>\n\n<p>Warning: the code does not check that the input contains valid numbers (use a regex for that), and that all numbers are within the list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-26T23:37:18.867", "Id": "242978", "ParentId": "242951", "Score": "1" } }
<p>I'm new to programming and this is the first thing I'm doing on my own. I would appreciate it if you could point me ways to optimize this RPG dice roller code in Python!</p> <pre><code>import random def dice_reader(): ##this should read messages like '2 d 6 + 3, 5 d 20 + 2 or just 3 d 8'## message = input('&gt;') reader = message.split(' ') times = reader[0] sides = reader[2] output_with_modifier = [] result = [] if len(reader) == 5: modifier = reader[4] else: modifier = 0 for output in range(int(times)): output = random.randint(1, int(sides)) result.append(output) output_with_modifier = [(int(x) + int(modifier)) for x in result] print(f' Dice rolls: {tuple(result)}') if modifier != 0: print(f' With modifier: {tuple(output_with_modifier)}') end = False while end == False: dice_reader() end_message = input('Again? ') if end_message.lower() == 'no': end = True else: pass </code></pre>
245982
GOOD_ANSWER
{ "AcceptedAnswerId": "245987", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T22:12:25.487", "Id": "245982", "Score": "6", "Tags": [ "python", "beginner" ], "Title": "Easier ways to make an RPG dice roller code?" }
{ "body": "<h2>Mystery inputs</h2>\n<p>It's clear that there's an implied structure to this input:</p>\n<pre><code>message = input('&gt;')\nreader = message.split(' ')\n</code></pre>\n<p>requiring between four and five tokens. I have no idea what those are, and neither does your user. Replace <code>'&gt;'</code> with an actual description of what's expected here.</p>\n<h2>Unpacking</h2>\n<pre><code>times = reader[0]\nsides = reader[2]\n</code></pre>\n<p>can be</p>\n<pre><code>times, _, sides = reader[:3]\n</code></pre>\n<p>though the discarded second item is suspicious. You do need to show what this is, and it probably shouldn't be there.</p>\n<h2>Looping and overwrites</h2>\n<p>This:</p>\n<pre><code>for output in range(int(times)):\n output_with_modifier = [(int(x) + int(modifier)) for x in result]\n</code></pre>\n<p>does not make sense. If you ask for 100 times, <code>output_with_modifier</code> will be calculated 100 times and thrown away 99 of them. Only the last value will be kept. You probably want to de-indent that last assignment so that it happens outside of the loop.</p>\n<h2>More looping</h2>\n<pre><code>end = False\nwhile end == False:\n dice_reader()\n end_message = input('Again? ')\n if end_message.lower() == 'no':\n end = True\nelse:\n pass\n</code></pre>\n<p>First, delete that <code>else; pass</code> - it isn't doing anything. Also, <code>end == False</code> should be <code>not end</code>; but you shouldn't be using a termination variable at all. If you find a <code>no</code>, simply <code>break</code>.</p>\n<h2>Suggested code</h2>\n<p>Some of this may challenge a beginner, but I like to think that CodeReview is for &quot;aspiring advanced programmers&quot;. I've tried to comment it extensively, but feel free to ask questions in the comments.</p>\n<pre><code>import re\nfrom random import randint\nfrom re import Pattern\nfrom typing import ClassVar, Iterable\n\n\nclass Dice:\n &quot;&quot;&quot;\n One specification for dice rolls in Dungeons &amp; Dragons-like format.\n &quot;&quot;&quot;\n\n def __init__(self, times: int, sides: int, modifier: int = 0):\n if times &lt; 1:\n raise ValueError(f'times={times} is not a positive integer')\n if sides &lt; 1:\n raise ValueError(f'sides={sides} is not a positive integer')\n\n self.times, self.sides, self.modifier = times, sides, modifier\n\n # This is a class variable (basically a &quot;static&quot;) that only has one copy\n # for the entire class type, rather than a copy for every class instance\n # It is a regular expression pattern that will allow us to parse user\n # input.\n INPUT_PAT: ClassVar[Pattern] = re.compile(\n # From the start, maybe some whitespace, then a group named &quot;times&quot;\n # that contains one or more digits\n r'^\\s*(?P&lt;times&gt;\\d+)' \n \n # Maybe some whitespace, then the letter &quot;d&quot;\n r'\\s*d'\n \n # Maybe some whitespace, then a group named &quot;sides&quot; that contains one\n # or more digits\n r'\\s*(?P&lt;sides&gt;\\d+)'\n \n # The beginning of a group that we do not store.\n r'(?:'\n \n # Maybe some whitespace, then a &quot;+&quot; character\n r'\\s*\\+'\n \n # Maybe some whitespace, then a group named &quot;modifier&quot; that\n # contains one or more digits\n r'\\s*(?P&lt;modifier&gt;\\d+)'\n \n # End of the group that we do not store; mark it optional\n r')?'\n \n # Maybe some whitespace, then the end.\n r'\\s*$',\n\n # We might use &quot;d&quot; or &quot;D&quot;\n re.IGNORECASE\n )\n\n # This can only be called on the class type, not a class instance. It\n # returns a new class instance, so it acts as a secondary constructor.\n @classmethod\n def parse(cls, message: str) -&gt; 'Rolls':\n match = cls.INPUT_PAT.match(message)\n if match is None:\n raise ValueError(f'Invalid dice specification string &quot;{message}&quot;')\n\n # Make a new instance of this class based on the matched regular\n # expression.\n return cls(\n int(match['times']),\n int(match['sides']),\n # If there was no modifier specified, pass 0.\n 0 if match['modifier'] is None else int(match['modifier']),\n )\n\n @classmethod\n def from_stdin(cls) -&gt; 'Rolls':\n &quot;&quot;&quot;\n Parse and return a new Rolls instance from stdin.\n &quot;&quot;&quot;\n\n while True:\n try:\n message = input(\n 'Enter your dice specification, of the form\\n'\n '&lt;times&gt;d&lt;sides&gt; [+ modifier], e.g. 3d6 or 4d12 + 1:\\n'\n )\n return cls.parse(message)\n except ValueError as v:\n print(v)\n print('Please try again.')\n\n def roll(self, with_modifier: bool = False) -&gt; Iterable[int]:\n &quot;&quot;&quot;\n Return a generator of rolls. This is &quot;lazy&quot; and will only execute the\n rolls that are consumed by the caller, because it returns a generator\n (not a list or a tuple).\n &quot;&quot;&quot;\n mod = self.modifier if with_modifier else 0\n return (\n randint(1, self.sides) + mod\n for _ in range(self.times)\n )\n\n def print_roll(self):\n print(\n 'Dice rolls:',\n ', '.join(str(x) for x in self.roll()),\n )\n\n if self.modifier != 0:\n print(\n 'With modifier:',\n ', '.join(str(x) for x in self.roll(with_modifier=True)),\n )\n\n\ndef test():\n &quot;&quot;&quot;\n This is an automated test method that does some sanity checks on the Dice\n implementation.\n &quot;&quot;&quot;\n \n d = Dice.parse('3 d 6')\n assert d.times == 3\n assert d.sides == 6\n assert d.modifier == 0\n\n d = Dice.parse('3D6 + 2')\n assert d.times == 3\n assert d.sides == 6\n assert d.modifier == 2\n\n try:\n Dice.parse('nonsense')\n raise AssertionError()\n except ValueError as v:\n assert str(v) == 'Invalid dice specification string &quot;nonsense&quot;'\n\n try:\n Dice.parse('-2d5')\n raise AssertionError()\n except ValueError as v:\n assert str(v) == 'Invalid dice specification string &quot;-2d5&quot;'\n\n try:\n Dice.parse('0d6')\n raise AssertionError()\n except ValueError as v:\n assert str(v) == &quot;times=0 is not a positive integer&quot;\n\n d = Dice.parse('100 d 12+3')\n n = 0\n for x in d.roll(True):\n assert 4 &lt;= x &lt;= 15\n n += 1\n assert n == 100\n\n\ndef main():\n test()\n\n dice = Dice.from_stdin()\n dice.print_roll()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T13:06:44.383", "Id": "483318", "Score": "0", "body": "I should've used comments to clarify what this is all about, my bad lol. This code is for reading messages like \"2 d 10 + 3\", for RPG dice rolling. Although \"d\" is completely useless, it makes for the classic virtual dice roller structure. It should print a message with the structure need for reading. Besides that, I didn't about anything you pointed me out, thanks for the help, I didn't expect any answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T20:33:10.030", "Id": "483344", "Score": "0", "body": "Oh my. Thank you very much for your time and suggestions. I will definitely study that, as didn't expect such an answer. I would also like to extend it a bit and ask another question: I'm a little overwhelmed by the amount of stuff that comes along with Python (Atom, Pycharm, Anaconda, virtual environments) and I don't know where to start. What do I really need to play around with Python a little, but without limiting myself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T20:41:18.480", "Id": "483345", "Score": "2", "body": "Personally my favourite environment is PyCharm. It goes a long way to suggesting where things are wrong or non-standard." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T02:18:15.067", "Id": "245987", "ParentId": "245982", "Score": "5" } }
<h1>The application</h1> <p>I'm making a small app (currently ~500 lines) to manage and download books and other media items. Each item is uniquely identify by its <code>(downloader, code)</code> tuple and the index (save in a pickled file) contains the title, authors, and tags (e.g. &quot;scfi-fi&quot;, &quot;comedy&quot;) of each item. The &quot;downloader&quot; is a module in a collection of user-made modules to scrape certain pages for metadata (title, authors and tags). For example, the module <code>example_dl</code>, given either the url <code>example.com/book/123</code> or code <code>123</code>, handles scraping <code>example.com</code> for the book with the code/ID of <code>123</code>, namely its metadata and possibly download the book to a directory.</p> <p>The code below contains the dictionary <code>config</code> for global configuration variables (stored in a config file <code>shelf.yaml</code>), a short description of the classes <code>Item</code> and <code>Shelf</code> and the function I'd like to be reviewed, <code>search_item()</code>.</p> <h1>Code</h1> <pre><code>import sys import os import re import argparse import importlib.util import yaml import pickle # Default configurations PATH = os.path.expanduser(&quot;~/.config/shelf&quot;) config = { &quot;config_file&quot;: PATH + &quot;/shelf.yaml&quot;, &quot;index_file&quot;: PATH + &quot;/data/index&quot;, &quot;favorites_file&quot;: PATH + &quot;/data/favorites&quot;, &quot;downloaders_dir&quot;: PATH + &quot;/downloaders&quot;, &quot;data_dir&quot;: PATH + &quot;/data&quot;, &quot;threads&quot;: 10, } class Item: &quot;&quot;&quot;Items stored in the Shelf Attributes: title: title of the media item authors: set of authors tags: set of tags media: media type the item is stored as (e.g. png, md, pdf) &quot;&quot;&quot; title = None authors = None tags = None media = None class Shelf: &quot;&quot;&quot;Shelf containing indexed data of items Attributes: downloaders: a dict of available downloaders index: Shelf indexing containing data about all items saved. Data is read from index file and is as follows: ( (downloader1, code1) : item_1, (downloader2, code2) : item_2 ) &quot;&quot;&quot; global config downloaders = dict() index = dict() favorites = set() verbosity = 0 def search_item( self, title_regex: str, authors: set[str], tags: set[str], blacklist: set[str], broad_search=False, favorites=False, ) -&gt; list[tuple[str, str]]: &quot;&quot;&quot;Search item in index Args: title_regex: regex to search title by authors: set of authors OR comma-separated string tags: set of tags OR comma-separated string broad_search: If False (Default), returns only when *all* tags match. If True, returns when at least 1 tag matches. favorites: only search items in favorties Returns: A 2-tuple containing the downloader and code. For example: (&quot;test_dl&quot;, &quot;test_code&quot;) &quot;&quot;&quot; if self.verbosity &gt;= 2: print( &quot;Searching with:\n&quot; f&quot;\tTitle regex: {title_regex}\n&quot; f&quot;\tAuthors: {authors}\n&quot; f&quot;\tTags: {tags}\n&quot; f&quot;\tBroad search: {broad_search}\n&quot; f&quot;\tFavorites: {favorites}&quot; ) result = None if favorites: # Search in favorites result = self.favorites if self.verbosity &gt;= 2: print(f&quot;Filtered by favorites: {result}&quot;) if title_regex: # Search with title regex result = { (k, v) for (k, v) in self.index if re.match(title_regex, self.index[(k, v)].title) } if self.verbosity &gt;= 2: print(f&quot;Filtered by title regex: {result}&quot;) if authors: # Search by authors (always broad search) if type(authors) == str: authors = set(authors.split(&quot;,&quot;)) if result: result = { (k, v) for (k, v) in result if authors &amp; self.index[(k, v)].authors } else: result = { (k, v) for (k, v) in self.index if authors &amp; self.index[(k, v)].authors } if self.verbosity &gt;= 2: print(f&quot;Filtered by authors: {result}&quot;) if tags: # Search by tags if type(tags) == str: tags = set(tags.split(&quot;,&quot;)) if broad_search: # Broad search if result: result = { (k, v) for (k, v) in result if tags &amp; self.index[(k, v)].tags } else: result = { (k, v) for (k, v) in self.index if tags &amp; self.index[(k, v)].tags } if self.verbosity &gt;= 2: print(f&quot;Filtered by broad_search: {result}&quot;) else: # Normal search if result: result = { (k, v) for (k, v) in result if not (tags - self.index[(k, v)].tags) } else: result = { (k, v) for (k, v) in self.index if not (tags - self.index[(k, v)].tags) } if self.verbosity &gt;= 2: print(f&quot;Filtered by broad_search: {result}&quot;) if blacklist: if type(blacklist) == str: blacklist = set(blacklist.split(&quot;,&quot;)) if result: result = { (k, v) for (k, v) in result if not blacklist &amp; self.index[(k, v)].tags } else: result = { (k, v) for (k, v) in self.index if not blacklist &amp; self.index[(k, v)].tags } return result </code></pre> <h1>Description of <code>search_item</code></h1> <p>The function <code>search_item</code> goes runs the <code>index</code> dictionary through 5 filters (kinda): <code>favorites</code>, <code>title_regex</code>, <code>author</code>, <code>tags</code>, and <code>blacklist</code>. The switches available to affect the search are <code>-t TITLE_REGEX</code>, <code>-a AUTHOR</code>, -T <code>TAGS</code>, <code>--broad-search</code>, <code>--favorites</code>, <code>--blacklist</code>.</p> <h2><code>if result</code></h2> <p>I have <code>if result</code> and <code>else</code> in almost every filter to hopefully improve speed and memory usage, since not every filter is required to be used in a single search.</p> <h2><code>favorites</code></h2> <p>The <code>Shelf</code> object has a <code>set</code> of 2-tuples, each tuple being <code>(downloader, code)</code>. Since <code>favorites</code> is a subset of <code>Shelf.index.keys()</code>, I simply copy the entire <code>set</code> of <code>favorites</code> to be further filtered.</p> <h2><code>title_regex</code> and <code>author</code></h2> <p>These 2 are similar in implementation. The only major difference is that <code>title_regex</code> is matched using <code>re.match(user_defined_regex, titles_in_index)</code>, while author is filtered with `author in set_of_authors.</p> <h2><code>tags</code></h2> <p>The <code>--broad-search</code> switch is only used with the <code>search_book</code> function when <code>tags</code> is used, and is ignored otherwise.</p> <h3>Normal Search</h3> <p>In normal search, <em>all</em> of the provided tags (comma-separated) must match the book's tags to show up in the result.</p> <h3>Broad search</h3> <p>In broad search, books show up in the result if <em>at least 1</em> of the provided tags is found in the book's <code>set</code> of tags.</p> <h2><code>blacklist</code></h2> <p>Basically the inverse of broad search.</p>
255491
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T07:12:15.603", "Id": "255491", "Score": "2", "Tags": [ "python", "python-3.x", "search" ], "Title": "Searching database of books" }
{ "body": "<p>I'm not going too deeply into flow of that solution, but I have some comments. Hopefully it will be useful to you.</p>\n<ol>\n<li>The first thing is that you should definitely refactor <code>search_item</code> by splitting that to smaller functions which will allow for better reading flow, but also it should help with finding code duplicates. Another benefit is that when in smaller functions, it's easier to comment such code (sometimes just by good name, sometimes with proper docstring).</li>\n<li>You have quite a lot of redundant code, like for example</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>result = {\n (k, v) for (k, v) in result if authors &amp; self.index[(k, v)].authors\n}\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>result = {\n (k, v) for (k, v) in result if tags &amp; self.index[(k, v)].tags\n}\n</code></pre>\n<p>or even in broader scopes, with whole <code>if result: .. if self.verbosity &gt;= 2: ...</code> sections. Right, there are different attributes like <code>authors</code>, <code>tags</code>, etc., but it should be quite easy handle them especially if you'd split that into smaller functions.</p>\n<ol start=\"3\">\n<li><p>these operations like <code>if tags &amp; self.index[(k, v)].tags</code> are not very obvious. Please document them somewhere to avoid confusions when someone will work with your code in future.</p>\n</li>\n<li><p>you don't need to specify whole tuple in these set comprehensions. That</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code> {(k, v) for (k, v) in result if authors &amp; self.index[(k, v)].authors}\n</code></pre>\n<p>could be rewritten to</p>\n<pre class=\"lang-py prettyprint-override\"><code>{key for key in result if authors &amp; self.index[key].authors}\n</code></pre>\n<p>most likely.</p>\n<ol start=\"5\">\n<li>I bet this is because of that you pasted here only a part of your code, but there you have not used imports (almost all of them).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T21:04:31.920", "Id": "255623", "ParentId": "255491", "Score": "2" } }
<h1>The application</h1> <p>I'm making a small app (currently ~500 lines) to manage and download books and other media items. Each item is uniquely identify by its <code>(downloader, code)</code> tuple and the index (save in a pickled file) contains the title, authors, and tags (e.g. &quot;scfi-fi&quot;, &quot;comedy&quot;) of each item. The &quot;downloader&quot; is a module in a collection of user-made modules to scrape certain pages for metadata (title, authors and tags). For example, the module <code>example_dl</code>, given either the url <code>example.com/book/123</code> or code <code>123</code>, handles scraping <code>example.com</code> for the book with the code/ID of <code>123</code>, namely its metadata and possibly download the book to a directory.</p> <p>The code below contains the dictionary <code>config</code> for global configuration variables (stored in a config file <code>shelf.yaml</code>), a short description of the classes <code>Item</code> and <code>Shelf</code> and the function I'd like to be reviewed, <code>search_item()</code>.</p> <h1>Code</h1> <pre><code>import sys import os import re import argparse import importlib.util import yaml import pickle # Default configurations PATH = os.path.expanduser(&quot;~/.config/shelf&quot;) config = { &quot;config_file&quot;: PATH + &quot;/shelf.yaml&quot;, &quot;index_file&quot;: PATH + &quot;/data/index&quot;, &quot;favorites_file&quot;: PATH + &quot;/data/favorites&quot;, &quot;downloaders_dir&quot;: PATH + &quot;/downloaders&quot;, &quot;data_dir&quot;: PATH + &quot;/data&quot;, &quot;threads&quot;: 10, } class Item: &quot;&quot;&quot;Items stored in the Shelf Attributes: title: title of the media item authors: set of authors tags: set of tags media: media type the item is stored as (e.g. png, md, pdf) &quot;&quot;&quot; title = None authors = None tags = None media = None class Shelf: &quot;&quot;&quot;Shelf containing indexed data of items Attributes: downloaders: a dict of available downloaders index: Shelf indexing containing data about all items saved. Data is read from index file and is as follows: ( (downloader1, code1) : item_1, (downloader2, code2) : item_2 ) &quot;&quot;&quot; global config downloaders = dict() index = dict() favorites = set() verbosity = 0 def search_item( self, title_regex: str, authors: set[str], tags: set[str], blacklist: set[str], broad_search=False, favorites=False, ) -&gt; list[tuple[str, str]]: &quot;&quot;&quot;Search item in index Args: title_regex: regex to search title by authors: set of authors OR comma-separated string tags: set of tags OR comma-separated string broad_search: If False (Default), returns only when *all* tags match. If True, returns when at least 1 tag matches. favorites: only search items in favorties Returns: A 2-tuple containing the downloader and code. For example: (&quot;test_dl&quot;, &quot;test_code&quot;) &quot;&quot;&quot; if self.verbosity &gt;= 2: print( &quot;Searching with:\n&quot; f&quot;\tTitle regex: {title_regex}\n&quot; f&quot;\tAuthors: {authors}\n&quot; f&quot;\tTags: {tags}\n&quot; f&quot;\tBroad search: {broad_search}\n&quot; f&quot;\tFavorites: {favorites}&quot; ) result = None if favorites: # Search in favorites result = self.favorites if self.verbosity &gt;= 2: print(f&quot;Filtered by favorites: {result}&quot;) if title_regex: # Search with title regex result = { (k, v) for (k, v) in self.index if re.match(title_regex, self.index[(k, v)].title) } if self.verbosity &gt;= 2: print(f&quot;Filtered by title regex: {result}&quot;) if authors: # Search by authors (always broad search) if type(authors) == str: authors = set(authors.split(&quot;,&quot;)) if result: result = { (k, v) for (k, v) in result if authors &amp; self.index[(k, v)].authors } else: result = { (k, v) for (k, v) in self.index if authors &amp; self.index[(k, v)].authors } if self.verbosity &gt;= 2: print(f&quot;Filtered by authors: {result}&quot;) if tags: # Search by tags if type(tags) == str: tags = set(tags.split(&quot;,&quot;)) if broad_search: # Broad search if result: result = { (k, v) for (k, v) in result if tags &amp; self.index[(k, v)].tags } else: result = { (k, v) for (k, v) in self.index if tags &amp; self.index[(k, v)].tags } if self.verbosity &gt;= 2: print(f&quot;Filtered by broad_search: {result}&quot;) else: # Normal search if result: result = { (k, v) for (k, v) in result if not (tags - self.index[(k, v)].tags) } else: result = { (k, v) for (k, v) in self.index if not (tags - self.index[(k, v)].tags) } if self.verbosity &gt;= 2: print(f&quot;Filtered by broad_search: {result}&quot;) if blacklist: if type(blacklist) == str: blacklist = set(blacklist.split(&quot;,&quot;)) if result: result = { (k, v) for (k, v) in result if not blacklist &amp; self.index[(k, v)].tags } else: result = { (k, v) for (k, v) in self.index if not blacklist &amp; self.index[(k, v)].tags } return result </code></pre> <h1>Description of <code>search_item</code></h1> <p>The function <code>search_item</code> goes runs the <code>index</code> dictionary through 5 filters (kinda): <code>favorites</code>, <code>title_regex</code>, <code>author</code>, <code>tags</code>, and <code>blacklist</code>. The switches available to affect the search are <code>-t TITLE_REGEX</code>, <code>-a AUTHOR</code>, -T <code>TAGS</code>, <code>--broad-search</code>, <code>--favorites</code>, <code>--blacklist</code>.</p> <h2><code>if result</code></h2> <p>I have <code>if result</code> and <code>else</code> in almost every filter to hopefully improve speed and memory usage, since not every filter is required to be used in a single search.</p> <h2><code>favorites</code></h2> <p>The <code>Shelf</code> object has a <code>set</code> of 2-tuples, each tuple being <code>(downloader, code)</code>. Since <code>favorites</code> is a subset of <code>Shelf.index.keys()</code>, I simply copy the entire <code>set</code> of <code>favorites</code> to be further filtered.</p> <h2><code>title_regex</code> and <code>author</code></h2> <p>These 2 are similar in implementation. The only major difference is that <code>title_regex</code> is matched using <code>re.match(user_defined_regex, titles_in_index)</code>, while author is filtered with `author in set_of_authors.</p> <h2><code>tags</code></h2> <p>The <code>--broad-search</code> switch is only used with the <code>search_book</code> function when <code>tags</code> is used, and is ignored otherwise.</p> <h3>Normal Search</h3> <p>In normal search, <em>all</em> of the provided tags (comma-separated) must match the book's tags to show up in the result.</p> <h3>Broad search</h3> <p>In broad search, books show up in the result if <em>at least 1</em> of the provided tags is found in the book's <code>set</code> of tags.</p> <h2><code>blacklist</code></h2> <p>Basically the inverse of broad search.</p>
255491
GOOD_ANSWER
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T07:12:15.603", "Id": "255491", "Score": "2", "Tags": [ "python", "python-3.x", "search" ], "Title": "Searching database of books" }
{ "body": "<h1>Use libraries to join path components</h1>\n<p>Instead of using raw string concatenation, use <a href=\"https://docs.python.org/3/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\"><code>os.path.join</code></a> or <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a>. Both of these provide more robust ways of joining together path components.</p>\n<h1>Static variables in <code>Item</code> should be instance variables</h1>\n<pre class=\"lang-python prettyprint-override\"><code>class Item:\n title = None\n authors = None\n tags = None\n media = None\n</code></pre>\n<p>This definition of <code>Item</code> only supports one item, because the variables are all static when you probably want them to be instance variables. You can correct this by declaring a <code>__init__</code> and initializing <code>self.title</code>, <code>self.authors</code>, etc.</p>\n<pre class=\"lang-python prettyprint-override\"><code>class Item:\n def __init__(\n self, title: str, authors: set[str], tags: set[str], media: Media\n ) -&gt; None:\n self.title = title\n self.authors = authors\n self.tags = tags\n self.media = media\n</code></pre>\n<p>Or even better, make <code>Item</code> a <a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"nofollow noreferrer\"><code>NamedTuple</code></a> or a <a href=\"https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass\" rel=\"nofollow noreferrer\"><code>dataclass</code></a> to save yourself from writing a lot of boilerplate code.</p>\n<h1><code>(downloader, code)</code> deserves its own name</h1>\n<p>Since every <code>Item</code> is uniquely identifiable by this 2-tuple, and since this particular 2-tuple shows up so often, you should really give it a proper name. Maybe something like <code>ItemId</code>. This will make the code easier to read.</p>\n<pre class=\"lang-python prettyprint-override\"><code>from typing NamedTuple\n\nclass ItemId(NamedTuple):\n downloader: str\n code: str\n</code></pre>\n<h1>Unnecessary <code>global</code></h1>\n<pre class=\"lang-python prettyprint-override\"><code>global config\n</code></pre>\n<p><code>global</code> is unnecessary here for several reasons:</p>\n<ul>\n<li>You're not changing what <code>config</code> points to anywhere in the program (at least, not anywhere in the code provided)</li>\n<li>You can read, and thus mutate the dictionary pointed to by <code>config</code> without the <code>global</code> keyword</li>\n<li>Using <code>global</code> to begin with is a code smell. There are much cleaner ways of sharing/communicating state. More on this below.</li>\n</ul>\n<h1><code>Shelf</code></h1>\n<p>Missing from this class definition is the code where you load file contents from the paths in <code>config</code> into <code>Shelf</code>. Based on the above-mentioned <code>global</code> keyword, I'm assuming you're doing the loading inside of <code>Shelf</code>. This works, but there's a cleaner way of doing this.</p>\n<ol>\n<li>Load the files into data structures before instantiating <code>Shelf</code>, e.g. read <code>index_file</code> into <code>index: dict</code>, read <code>favorites_file</code> into <code>favorites: set</code>.</li>\n<li>Initialize <code>Shelf</code> with these data structures on instantiation.</li>\n</ol>\n<p>By doing this, <code>Shelf</code> becomes a lot easier to test because it's no longer responsible for doing file I/O and parsing of the files in <code>config</code>. When you instantiate <code>Shelf</code> for testing, you can just declare and pass in test data directly.</p>\n<h1><code>search_item</code></h1>\n<ul>\n<li>If you declare a parameter's type to be <code>set[str]</code>, it should always be treated as such in the function body. For <code>authors</code>, <code>tags</code>, and <code>blacklist</code>, you are actually treating them as a <code>Union[set[str], str]</code> which is something completely different.</li>\n<li>I will go one step further and say that making <code>search_item</code> responsible for handling a parameter of type <code>Union[set[str], str]</code> is not a good design. <code>search_item</code> is not the right place to parse a user's command-line <code>str</code> input into a <code>set[str]</code>. Any pre-processing/parsing of input like this should be done before calling <code>search_item</code>.</li>\n<li>The return type should be a <code>set</code>, not a list. Technically, the return type as it is written now is actually an <code>Optional[set]</code> because <code>result</code> is initialized to <code>None</code>, and if <code>search_item</code> is called with <code>title_regex=&quot;&quot;, authors=set(), tags=set(), blacklist=set(), favorites=False</code>, we do not step into any of the filter-related if conditions and simply return <code>result</code>. This is probably not what you want.</li>\n<li>An alternative to repeated <code>if self.verbosity &gt;= 2</code> guards followed by <code>print</code> statements might be using the <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\"><code>logging</code></a> module. You can map <code>self.verbosity</code> to a logging level (<code>DEBUG</code>, <code>INFO</code>, <code>WARNING</code>, <code>ERROR</code>, <code>CRITICAL</code>), configure your logger to have that logging level, and then print logs with <code>logging.debug</code>, <code>logging.info</code>, etc. according to how chatty you want the messages to be.</li>\n<li>All of the inner branching on <code>if result</code> for each filtering stage is what I would call a premature optimization, and the code is much harder to read as a result. It's better to write the code to be as clean and maintainable as possible first. If after that you still have concerns about performance, profile your code to see where you can make optimizations.</li>\n<li><code>tags &lt;= self.index[(k, v)].tags</code> (testing if the set of desired tags is a subset of the item's tags) is more straightforward than <code>not (tags - self.index[(k, v)].tags)</code></li>\n<li><code>blacklist.isdisjoint(self.index[(k, v)].tags)</code> is more straightforward than <code>not blacklist &amp; self.index[(k, v)].tags</code></li>\n</ul>\n<p>There is a lot of repetition at each stage where we filter the collection of candidate items in the same way (using set comprehensions), with the only difference being the predicate.</p>\n<p>If we define the predicates (or checks) as functions that judge an <code>Item</code>, with the help of <a href=\"https://docs.python.org/3/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a> we can generate custom predicates, all of the form <code>(Item) -&gt; bool</code>, based on the user's search query.</p>\n<pre class=\"lang-python prettyprint-override\"><code>import re\n\nfrom enum import Enum\nfrom functools import partial\nfrom typing import Callable, NamedTuple\n\nclass Media(Enum):\n EPUB = 1\n MARKDOWN = 2\n PDF = 3\n PNG = 4\n\nclass Item(NamedTuple):\n title: str\n authors: set[str]\n tags: set[str]\n media: Media\n\ndef title_check(title_regex: str, item: Item) -&gt; bool:\n return bool(re.match(title_regex, item.title))\n\ndef authors_check(authors: set[str], item: Item) -&gt; bool:\n return bool(authors &amp; item.authors)\n\ndef tags_broad_check(tags: set[str], item: Item) -&gt; bool:\n return bool(tags &amp; item.tags)\n\ndef tags_normal_check(tags: set[str], item: Item) -&gt; bool:\n return tags &lt;= item.tags\n\ndef blacklisted_tags_check(blacklisted_tags: set[str], item: Item) -&gt; bool:\n return blacklisted_tags.isdisjoint(item.tags)\n\ndef generate_checks(\n title_regex: str,\n authors: set[str],\n tags: set[str],\n blacklisted_tags: set[str],\n broad_search: bool = False,\n) -&gt; list[Callable[[Item], bool]]:\n checks: list[Callable[[Item], bool]] = []\n\n if title_regex:\n checks.append(partial(title_check, title_regex))\n if authors:\n checks.append(partial(authors_check, authors))\n if tags:\n if broad_search:\n checks.append(partial(tags_broad_check, tags))\n else:\n checks.append(partial(tags_normal_check, tags))\n if blacklisted_tags:\n checks.append(partial(blacklisted_tags_check, blacklisted_tags))\n\n return checks\n</code></pre>\n<p>Then, assuming</p>\n<ul>\n<li><code>self.index</code> is a <code>dict[ItemId, Item]</code> and</li>\n<li><code>self.favorites</code> is a <code>set[ItemId]</code></li>\n</ul>\n<p><code>search_item</code> can be refactored like so:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def search_item(\n self,\n title_regex: str,\n authors: set[str],\n tags: set[str],\n blacklisted_tags: set[str],\n broad_search: bool = False,\n favorites: bool = False,\n) -&gt; set[ItemId]:\n if favorites:\n items_to_search = {\n item_id: item\n for item_id, item in self.index.items()\n if item_id in self.favorites\n }\n else:\n items_to_search = self.index\n\n checks = generate_checks(\n title_regex, authors, tags, blacklisted_tags, broad_search\n )\n\n return {\n item_id\n for item_id, item in items_to_search.items()\n if all(check(item) for check in checks)\n }\n</code></pre>\n<p>One advantage of writing it this way is that adding/removing/updating checks is easy, and won't require too many changes to <code>search_item</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T12:33:27.943", "Id": "255716", "ParentId": "255491", "Score": "2" } }
<p>I have recently tried converting a singly linked list from a C program into my own python program. I have tested the code myself but I am still unsure if the program has been converted properly. I would like someone to peer review my code to see if there are any errors in methodology, too many methods, any missing methods, etc.</p> <p>I have tried implementing some of my own singly linked list operations based from the advice from this website: <a href="https://afteracademy.com/blog/types-of-linked-list-and-operation-on-linked-list" rel="nofollow noreferrer">https://afteracademy.com/blog/types-of-linked-list-and-operation-on-linked-list</a></p> <p>The original C Program: <a href="https://people.eng.unimelb.edu.au/ammoffat/ppsaa/c/listops.c" rel="nofollow noreferrer">https://people.eng.unimelb.edu.au/ammoffat/ppsaa/c/listops.c</a></p> <p>My own python code:</p> <pre><code>class Node(): # Node for a single linked list def __init__(self, data): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None self.foot = None def length(self): '''Returns the length of a linked list.''' current_node = self.head node_total = 0 while (current_node != None): node_total += 1 current_node = current_node.next return node_total def is_empty_list(self): '''Checks if a linked list is empty.''' return self.head == None def stack_insert(self, data): '''Inserts a node at the HEAD of the list; LIFO (Last In, First Out).''' new_node = Node(data) # Makes new_node.next point to next node (defualt None if 1st insertion) new_node.next = self.head # Makes the HEAD of linked list point to new node self.head = new_node if (self.foot == None): # First insertion into linked list; node becomes HEAD &amp; FOOT self.foot = new_node def queue_append(self, data): '''Appends a node at the FOOT of the list; FIFO (First In, First Out).''' new_node = Node(data) if (self.head == None): # First insertion into linked list; node becomes HEAD &amp; FOOT self.head = self.foot = new_node else: # Makes the original last node point to the newly appended node self.foot.next = new_node # Makes the newly appended list as the official FOOT of the linked list self.foot = new_node def insert_after(self, data, index): '''Inserts a NEW node AFTER a specific node indicated by index.''' # Need to ensure provided index is within range if (index &lt; 0): print(&quot;ERROR: 'insert_after' Index cannot be negative!&quot;) return elif (index &gt; (self.length() -1)): print(&quot;ERROR: 'insert_after' Index exceeds linked list range!&quot;) return # Use stack_insert to insert as first item elif (self.is_empty_list()) or (index == 0): self.stack_insert(data) return # Use queue_insert to append as last item elif (index == (self.length() -1)): self.queue_append(data) return new_node = Node(data) prior_node = self.head current_node = self.head search_index = 0 # Keep traversering through nodes until desired node while (search_index != index): prior_node = current_node current_node = current_node.next search_index += 1 # Makes prior node is point to target node prior_node = current_node # Makes current node point to the node AFTER target node (default None of last node) current_node = current_node.next # Makes target node point to newly added node prior_node.next = new_node # Makes newly added node point to original node that WAS AFTER target node new_node.next = current_node def delete_head(self): '''Deletes the HEAD node.''' # Linked list is empty if self.is_empty_list(): return old_head = self.head # Adjusts the head pointer to step past original HEAD self.head = self.head.next if (self.head == None): # The only node just got deleted self.foot = None def delete_foot(self): '''Deletes the FOOT node.''' # Linked list is empty if self.is_empty_list(): return old_foot = self.foot prior_node = self.head current_node = self.head # Need to keep cycling until final node is reached while (current_node.next != None): prior_node = current_node current_node = current_node.next # Adjust newly FOOT node to point to nothing prior_node.next = None # Makes linked list forget about original FOOT node self.foot = prior_node def delete_node(self, index): '''Deletes a target node via index.''' # Linked list is empty if self.is_empty_list(): return # Need to ensure index is within proper range elif (index &lt; 0): print(&quot;ERROR: 'delete_node' Index cannot be negative!&quot;) return elif (index &gt; (self.length() -1)): print(&quot;ERROR: 'delete_node' Index exceeds linked list range&quot;) return prior_node = self.head current_node = self.head search_index = 0 # Keep travsersing though nodes until desired node while (search_index != index): prior_node = current_node current_node = current_node.next search_index += 1 # Adjusts node PRIOR to target node to point to the node the AFTER target node prior_node.next = current_node.next def update_node(self, new_data, index): '''Updates target node data via index.''' # Linked list is empty if self.is_empty_list(): print(&quot;ERROR: 'update_node' Linked list is empty; no node data to update!&quot;) return # Need to ensure index is within proper range elif (index &lt; 0): print(&quot;ERROR: 'update_node' Index cannot be negative!&quot;) return elif (index &gt; (self.length() -1)): print(&quot;ERROR: 'update_node' Index exceeds linked list range!&quot;) current_node = self.head search_index = 0 # Keep traversing through nodes until desired node while (search_index != index): current_node = current_node.next search_index += 1 # Can now change data current_node.data = new_data def get_node_data(self, index): '''Extracts that data from a specific node via index.''' # Linked list is empty if self.is_empty_list(): print(&quot;ERROR: 'update_node' Linked list is empty; no node data to update!&quot;) return # Need to ensure index is within proper range elif (index &lt; 0): print(&quot;ERROR: 'update_node' Index cannot be negative!&quot;) return elif (index &gt; (self.length() -1)): print(&quot;ERROR: 'update_node' Index exceeds linked list range!&quot;) # Index matches HEAD or FOOT if (index == 0): return self.head.data elif (index == (self.length() -1)): return self.foot.data current_node = self.head search_index = 0 # Keep traversing though nodes until desired node while (search_index != index): current_node = current_node.next search_index += 1 return current_node.data </code></pre>
256319
GOOD_ANSWER
{ "AcceptedAnswerId": "256351", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T00:53:28.823", "Id": "256319", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "linked-list" ], "Title": "singly linked list python code" }
{ "body": "<p>Your code looks un-Pythonic because you are using methods like <code>length</code> rather dunder methods like <code>__len__</code>.</p>\n<h2>Node</h2>\n<p>Before that we can change <code>Node</code> to use <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\"><code>dataclasses</code></a>. <code>dataclasses</code> will automatically give your class some boiler-plate, like <code>__init__</code> and <code>__repr__</code>. To use <code>dataclasses.dataclass</code> you need to type your class. To type attributes we can use <code>attr: type</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Any\n\nclass Node:\n data: Any\n next: &quot;Node&quot;\n # ...\n</code></pre>\n<p>There are two important parts to note;</p>\n<ul>\n<li>you should try not to use <code>Any</code> as doing so destroys type information.\nHere we can instead use <a href=\"https://docs.python.org/3/library/typing.html#typing.TypeVar\" rel=\"nofollow noreferrer\"><code>typing.TypeVar</code></a> and <a href=\"https://docs.python.org/3/library/typing.html#typing.Generic\" rel=\"nofollow noreferrer\"><code>typing.Generic</code></a>. And</li>\n<li>we have encased the type <code>Node</code> in a string. Before Python 3.10 type annotations are eagerly evaluated. Since we're using the name <code>Node</code> before <code>Node</code> has been assigned, if we didn't the type would fail to resolve.\nWe can use <code>from __future__ import annotations</code> to make Python use lazy evalutaion automatically from Python 3.7+.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\nfrom typing import Generic, TypeVar\n\nT = TypeVar(&quot;T&quot;)\n\nclass Node(Generic[T]):\n data: T\n next: Node\n # ...\n</code></pre>\n<p>We can now change the class to use <code>dataclasses.dataclass</code>. Since we want to be able to not provide <code>next</code> in the <code>__init__</code> we can assign <code>None</code> to <code>next</code>, so that <code>next</code> defaults to <code>None</code> if nothing is provided.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import dataclasses\n\n@dataclasses.dataclass\nclass Node(Generic[T]):\n data: T\n next: Node = None\n\nll = Node(0, Node(1)) # example usage\nprint(ll)\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Node(data=0, next=Node(data=1, next=None))\n</code></pre>\n<p>The nice output helps makes debugging much easier as now we can just print <code>self.head</code> (in the <code>LinkedList</code>) to be able to visually debug any incorrect states. The default <code>__repr__</code> also automatically handles recursion, to aide in debugging.</p>\n<pre class=\"lang-py prettyprint-override\"><code>ll.next.next = ll\nprint(ll)\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Node(data=0, next=Node(data=1, next=...))\n</code></pre>\n<p><strong>Note</strong>: <code>...</code> just means there is recursion here, we would get the same output if we assigned <code>ll.next</code> rather than <code>ll</code>.</p>\n<h2>Linked List</h2>\n<h3>Iterating</h3>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>def length(self):\n '''Returns the length of a linked list.'''\n current_node = self.head\n node_total = 0\n while (current_node != None):\n node_total += 1\n current_node = current_node.next\n return node_total\n</code></pre>\n</blockquote>\n<p>There are some ways <code>length</code> is not Pythonic:</p>\n<ul>\n<li>\n<blockquote>\n<p><a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">For consistency, always use <code>&quot;&quot;&quot;triple double quotes&quot;&quot;&quot;</code> around docstrings.</a></p>\n</blockquote>\n</li>\n<li><p>You should use <code>is</code> when comparing to singletons like <code>None</code>.</p>\n</li>\n<li><p>Please don't use unneeded parentheses.</p>\n<pre class=\"lang-py prettyprint-override\"><code>while current_node is not None:\n</code></pre>\n</li>\n<li><p>Your method's name should be <code>__len__</code> as then you can use <code>len(obj)</code> rather than <code>obj.length()</code>. Doing so can help make <code>LinkedList</code> a drop in replacement for say <code>list</code>.</p>\n</li>\n<li><p>I would define a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator function</a> to iterate through the linked list. Using a generator function can make your code much simpler. We can then use standard iterator parts of Python like <code>for</code> and <code>sum</code> instead.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def __iter__(self):\n curr = self.head\n while curr is not None:\n yield curr.data\n curr = curr.next\n\ndef __len__(self):\n &quot;&quot;&quot;Returns the length of a linked list.&quot;&quot;&quot;\n return sum(1 for _ in self)\n</code></pre>\n<h3>Inserting</h3>\n<p>Rather than defaulting <code>head</code>, and <code>foot</code>, to <code>None</code> we can default to <code>Node(None)</code>.\nWe can then make your code simpler by getting rid of all the <code>if self.head is None</code> code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def queue_append(self, data):\n self.foot.next = Node(data)\n self.foot = self.foot.next\n</code></pre>\n<p><strong>Note</strong>: If you do add a default head then you'd need to change <code>__iter__</code> to not return the default head. However we wouldn't need to change <code>__len__</code>, because <code>__len__</code> is based off <code>__iter__</code>!</p>\n<p>Inserting into the head would also stay simple. The changes we made to <code>Node</code> can also make the code simpler.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def stack_insert(self, data):\n self.head.next = Node(data, self.head.next)\n if self.foot is self.head:\n self.foot = self.head.next\n</code></pre>\n<p>There are some change I'd make to <code>insert_after</code>:</p>\n<ul>\n<li><p>Rather than using <code>stack_insert</code> and <code>queue_append</code>, the code would be far simpler built from scratch.</p>\n</li>\n<li><p>Since <code>length</code>, or <code>__len__</code>, has to iterate through the linked list, calling the function isn't too helpful.</p>\n</li>\n<li><p>Any performance gain from <code>queue_append</code> is lost by using <code>length</code>.</p>\n</li>\n<li><p>By calling <code>stack_insert</code> with an input of 0 your code is prone to making bugs.</p>\n<pre class=\"lang-py prettyprint-override\"><code>ll = LinkedList()\nll.queue_append(&quot;a&quot;)\nll.insert_after(&quot;b&quot;, 0)\nll.insert_after(&quot;c&quot;, 1)\nprint(ll.head)\n</code></pre>\n<pre><code>Node(data='b', next=Node(data='a', next=Node(data='c', next=None)))\n</code></pre>\n</li>\n<li><p>Now that the linked list will always have a root <code>Node</code> we can easily change the function to insert before, rather than after.</p>\n</li>\n<li><p>You should <code>raise</code> errors not print.</p>\n</li>\n</ul>\n<p>In all I'd follow <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def insert(self, index, value):\n if index &lt; 0:\n raise IndexError(&quot;cannot work with negative indexes&quot;)\n curr = self.head\n for _ in range(index):\n curr = curr.next\n if curr is None:\n raise IndexError(f&quot;index, {index}, is out of range&quot;)\n curr.next = Node(value, curr.next)\n if curr is self.foot:\n self.foot = curr.next\n</code></pre>\n<p>Now <code>stack_insert</code> looks quite unneeded; we can just use <code>LinkedList.insert(0, ...)</code> instead.\nAlso if we changed <code>__len__</code> to return from a constant then we could change the code so there is no appreciable gain from <code>queue_append</code>.</p>\n<h3>Deleting</h3>\n<p>Rather than falling for the same problems as insert we should just ignore <code>delete_head</code> and <code>delete_foot</code>.</p>\n<p>Since the code for finding the current node, or previous node for delete, is exactly the same, we can make a function to return a desired node.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _index(self, index):\n if index &lt; 0:\n raise IndexError(&quot;cannot work with negative indexes&quot;)\n curr = self.head\n for _ in range(index):\n curr = curr.next\n if curr is None:\n raise IndexError(f&quot;index, {index}, is out of range&quot;)\n return curr\n</code></pre>\n<p>Now we just need to ensure the <em>next</em> value is is not <code>None</code> as the index would be out of range. And ensure we update <code>self.foot</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def delete_node(self, index):\n prev = self._index(index)\n if prev.next is None:\n raise IndexError(f&quot;index, {index}, is out of range&quot;)\n if prev.next is self.foot:\n self.foot = prev\n prev.next = prev.next.next\n</code></pre>\n<h3>Getting / Updating</h3>\n<p>There should be no suprise. We just call <code>self._index</code> and handle the node however is needed.</p>\n<h3>Pythonisms</h3>\n<ul>\n<li><p>We can use the <a href=\"https://docs.python.org/3/reference/datamodel.html#emulating-container-types\" rel=\"nofollow noreferrer\">container dunder methods</a>:</p>\n<ul>\n<li><code>get_node_data</code> -&gt; <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__getitem__\" rel=\"nofollow noreferrer\"><code>__getitem__</code></a></li>\n<li><code>update_node</code> -&gt; <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__setitem__\" rel=\"nofollow noreferrer\"><code>__setitem__</code></a></li>\n<li><code>delete_node</code> -&gt; <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__delitem__\" rel=\"nofollow noreferrer\"><code>__delitem__</code></a></li>\n</ul>\n</li>\n<li><p>A common Python idiom is negative numbers mean 'go from the end'.\nWe can easily change <code>_index</code> to handle negatives rather than error.</p>\n</li>\n<li><p>You should rename <code>is_empty_list</code> to <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__bool__\" rel=\"nofollow noreferrer\"><code>__bool__</code></a> to allow truthy testing your linked list.</p>\n</li>\n<li><p>You should mimic the names of existing datatypes, like <a href=\"https://docs.python.org/3/tutorial/datastructures.html\" rel=\"nofollow noreferrer\"><code>list</code></a> or <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>collections.deque</code></a>. <strong>Note</strong>: you should <em>not</em> mimic the names of <a href=\"https://docs.python.org/3/library/queue.html\" rel=\"nofollow noreferrer\"><code>queue.Queue</code></a> or <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Queue\" rel=\"nofollow noreferrer\"><code>multiprocessing.Queue</code></a>; both classes are used for a different pattern than your code is for.</p>\n<ul>\n<li><code>stack_insert</code> -&gt; <code>appendleft</code>.</li>\n<li><code>queue_append</code> -&gt; <code>append</code>.</li>\n<li><code>delete_head</code> -&gt; <code>popleft</code>.</li>\n<li><code>delete_foot</code> -&gt; <code>pop</code>.</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\nimport dataclasses\nfrom typing import Generic, TypeVar\n\nT = TypeVar(&quot;T&quot;)\n\n\n@dataclasses.dataclass\nclass Node(Generic[T]):\n data: T\n next: Node = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = self.foot = Node(None)\n self._length = 0\n \n def __iter__(self):\n curr = self.head.next\n while curr is not None:\n yield curr\n\n def __len__(self):\n return self._length\n\n def __bool__(self):\n return self.head.next is None\n\n # You don't need max if you don't want to make a doubly\n # linked list with a foot node like the head node\n def _norm_index(self, index, min=0, max=0):\n index += min if 0 &lt;= index else max\n index = len(self) + 1 + index if index &lt; 0 else index\n if index &lt; min:\n raise IndexError(&quot;out of range min&quot;)\n if len(self) + max &lt; index:\n raise IndexError(&quot;out of range max&quot;)\n return index\n\n def _index(self, index, min=0, max=0):\n try:\n _index = self._norm_index(index, min, max)\n if _index == len(self):\n return self.foot\n curr = self.head\n for _ in range(_index):\n curr = curr.next\n if curr is None:\n raise IndexError(&quot;curr is None&quot;)\n return curr\n except IndexError as e:\n raise IndexError(f&quot;index, {index}, is out of range&quot;).with_traceback(e.__traceback__) from None\n\n def __getitem__(self, index):\n return self._index(index, min=1).data\n\n def __setitem__(self, index, value):\n curr = self._index(index, min=1)\n curr.data = value\n\n def __delitem__(self, index):\n prev = self._index(index - 1 if index &lt; 0 else index)\n if prev.next is None:\n raise IndexError(f&quot;index, {index}, is out of range&quot;)\n if prev.next is self.foot:\n self.foot = prev\n self._length -= 1\n prev.next = prev.next.next\n\n def insert(self, index, value):\n curr = self._index(index)\n self._length += 1\n curr.next = Node(value, curr.next)\n if curr is self.foot:\n self.foot = curr.next\n\n def append(self, value):\n self.insert(-1, value)\n\n def appendleft(self, value):\n self.insert(0, value)\n\n def pop(self):\n del self[-1]\n\n def popleft(self):\n del self[0]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T20:11:22.703", "Id": "256351", "ParentId": "256319", "Score": "4" } }
<p>I wrote a python program to find if a matrix is a magic square or not. It works, but I can't help feeling like I may have overcomplicated the solution. I have seen other implementations that were a lot shorter, but I was wondering how efficient/inefficient my code is and how I could improve it and/or shorten it to achieve the result I am looking for.</p> <pre><code>def main(): matrix = [[4,9,2], [3,5,7], [8,1,6]] result = loShu(matrix) print(result) def loShu(matrix): i = 0 j = 0 for i in range(0, len(matrix)): for j in range(0, len(matrix[j])): if ((matrix[i][j] &lt; 1) or (matrix[i][j] &gt; 9)): return (&quot;This is not a Lo Shu Magic Square - one of the numbers is invalid&quot;) row1 = matrix[0][0] + matrix[0][1] + matrix[0][2] row2 = matrix[1][0] + matrix[1][1] + matrix[1][2] row3 = matrix[2][0] + matrix[2][1] + matrix[2][2] ver1 = matrix[0][0] + matrix[1][0] + matrix[2][0] ver2 = matrix[0][1] + matrix[1][1] + matrix[2][1] ver3 = matrix[0][2] + matrix[1][2] + matrix[2][2] diag1 = matrix[0][0] + matrix[1][1] + matrix[2][2] diag2 = matrix[0][2] + matrix[1][1] + matrix[2][0] checkList = [row1,row2,row3,ver1,ver2,ver3,diag1,diag2] temp = checkList[0] for x in range (0, len(checkList)): if checkList[x] != temp: return (&quot;This is not a Lo Shu Magic Square&quot;) return (&quot;This is a Lo Shu Magic Square&quot;) main() </code></pre>
259665
WIERDgfsd
{ "AcceptedAnswerId": "259666", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-17T15:41:45.807", "Id": "259665", "Score": "1", "Tags": [ "python", "performance", "matrix", "mathematics" ], "Title": "Lo Shu Magic Square (Python)" }
{ "body": "<p>Your solution is hardcoded for matrices of size 3x3 - why not support matrices of arbitrary size as well? It's also difficult to maintain and debug your code, i.e., it's easy to mess up somewhere when you are indexing your rows and columns. Also, imagine you wanted to consider larger matrices: what a nightmare to <em>now</em> modify your existing logic!</p>\n<p>A more robust solution could turn to <a href=\"https://numpy.org/\" rel=\"nofollow noreferrer\">numpy</a>. Specifically, you can check row and column sums by doing <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.matrix.sum.html\" rel=\"nofollow noreferrer\"><code>m.sum()</code></a> and <code>m.sum(axis=1)</code>, and compute the sums of the diagonals via <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.trace.html\" rel=\"nofollow noreferrer\"><code>m.trace()</code></a> or by <code>sum(np.diag(m))</code> and <code>sum(np.diag(np.fliplr(m))</code>.</p>\n<p>As a general comment, just return a boolean value from your function. Let the main program decide what do with this value, i.e., whether to print &quot;this is good&quot;, &quot;This is a Lo Shu Magic Square&quot;, or whatever. In this way, your verifier function stays clean and more generic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-17T17:42:09.387", "Id": "512229", "Score": "0", "body": "That makes sense. This is exactly what I was looking for - a way other than hardcoding. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-17T17:35:07.457", "Id": "259666", "ParentId": "259665", "Score": "3" } }