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 v... | 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) > 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": "@Gar... |
<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 v... | 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(po... |
<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 v... | 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 t... |
<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... | 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 incompatibiliti... |
<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 gi... | 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()... |
<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 gi... | 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 re... |
<p>I have a grid as </p>
<pre><code>>>> data = np.zeros((3, 5))
>>> 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), ... | 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>>>> import numpy as np\n>>> [j for j... |
<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 meth... | 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 m... |
<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 meth... | 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>>>> e = EasyCSV('.')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n ... |
<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-... | 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... |
<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><... | 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 t... | {
"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",
... |
<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><... | 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 t... | {
"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>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><... | 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 t... | {
"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... |
<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><... | 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 t... | {
"body": "<p>Use split, like so:</p>\n\n<pre><code>>>> filecontent = \"13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234\";\n>>> items = filecontent.split(\";\");\n>>> items;\n['13P397', 'Fotostuff', 't', 'IBM', 'IBM lalala 123|IBM lalala 1234'... |
<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... | 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>>>>... |
<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... | 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.p... |
<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... | 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>>>> zcr(numpy.array([0, 1, 2, 3, 4, 5, 6, 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 a... | 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 ... |
<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 a... | 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>>=</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> instea... |
<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)
... | 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... |
<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 ... | 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 p... |
<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>ParryBladeWi... | 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?... |
<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>
<blockquot... | 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.repl... |
<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>
<blockquot... | 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 # <-- Python 2, or\nfrom str import maketrans # <-- Python 3\n\ndef are_isomorph(string1, string2):\n return len(string1) == len(str... |
<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>
<blockquot... | 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 yo... |
<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>
<blockquot... | 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>>>> 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 ch... |
<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
... | 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": [
{... |
<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
... | 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... |
<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
... | 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=... |
<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 ... | 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 you... |
<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 ... | 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></p... |
<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 eleme... | 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 ite... | {
"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>>>> a, b = 'foo bar is here'.split()[:2]\n>>> a, b\n('foo', 'bar')\n</code></pre>\n\n<p>In Python 3 (<code>_</code> used by convention, double u... |
<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.choi... | 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>de... |
<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.choi... | 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><... |
<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>
<... | 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 c... |
<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 templat... | 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 t... |
<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... | 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.ran... |
<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.2... | 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>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">buil... | 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... |
<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):
... | 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, ... |
<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, (mayb... | 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 an... |
<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 citie... | 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 lang... |
<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 citie... | 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\nwi... |
<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
... | 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 & 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 libr... |
<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'... | 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 a... |
<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="http... | 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 ... | {
"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 we... |
<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('pos... | 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... |
<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 stu... | 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 ... |
<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 suggestion... | 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 simulat... | {
"body": "<p>Take a look at these lines:</p>\n\n<pre><code>while (int(user_1_score) <= int(hold_score)):\n if (int(user_1_card_count)<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 a... |
<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 suggestion... | 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 simulat... | {
"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 ... |
<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(... | 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 ad... |
<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... | 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() \... |
<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):
... | 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 loca... |
<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 StackO... | 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 wi... | {
"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<... |
<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 StackO... | 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 wi... | {
"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\\20... |
<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 ... | 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 ... |
<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 ... | 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-... |
<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 ... | 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 neede... |
<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... | 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 ... | {
"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] > 0:\n array[i] = array[i] + array[i-1]\n if array... |
<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... | 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 ... | {
"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>accum... |
<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^... | 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 e... |
<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^... | 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 i... |
<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:
... | 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 ... |
<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... | 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 ... |
<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 t... | 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</cod... |
<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 t... | 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... |
<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('>... | 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('>')\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>'>'</code> with... |
<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. "scfi-fi", "comedy&q... | 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 s... |
<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. "scfi-fi", "comedy&q... | 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 no... |
<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 m... | 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>d... |
<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 a... | 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 ni... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.