body
stringlengths
144
5.53k
comments
list
meta_data
dict
question_id
stringlengths
1
6
yield
stringclasses
2 values
answers
list
<p>I want to create a function that takes a numpy array, an axis and an index of that axis and returns the array with the index on the specified axis fixed. What I thought is to create a string that change dynamically and then is evaluated as an index slicing in the array (as showed in <a href="https://stackoverflow.com/a/47354114/11764049">this answer</a>). I came up with the following function:</p> <pre><code>import numpy as np def select_slc_ax(arr, slc, axs): dim = len(arr.shape)-1 slc = str(slc) slice_str = &quot;:,&quot;*axs+slc+&quot;,:&quot;*(dim-axs) print(slice_str) slice_obj = eval(f'np.s_[{slice_str}]') return arr[slice_obj] </code></pre> <h3>Example</h3> <pre><code>&gt;&gt;&gt; arr = np.array([[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [1, 1, 1], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]], dtype='uint8') &gt;&gt;&gt; select_slc_ax(arr, 2, 1) :,2,: array([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=uint8) </code></pre> <p>I was wondering if there is a better method to do this.</p>
[]
{ "AcceptedAnswerId": "265604", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T14:35:05.840", "Id": "265551", "Score": "3", "Tags": [ "python", "numpy" ], "Title": "Dynamically indexing numpy array" }
265551
accepted_answer
[ { "body": "<ul>\n<li>Avoid <code>eval</code> at all costs</li>\n<li>Use the <code>slice</code> built-in for your <code>:</code> components, or the numeric index at the selected axis</li>\n<li>Do not abbreviate your variable names</li>\n<li>Type-hint your function signature</li>\n<li>Turn your example into something resembling a unit test with an <code>assert</code></li>\n<li>Modify the data in your example to add more non-zero entries making it clearer what's happening</li>\n<li>Prefer immutable tuples over mutable lists when passing initialization constants to Numpy</li>\n<li>Prefer the symbolic constants for Numpy types rather than strings</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import numpy as np\n\n\ndef select_slice_axis(array: np.ndarray, index: int, axis: int) -&gt; np.ndarray:\n slices = tuple(\n index if a == axis else slice(None)\n for a in range(len(array.shape))\n )\n return array[slices]\n\n\narr = np.array(\n (\n ((0, 0, 0),\n (0, 0, 0),\n (0, 0, 9)),\n ((0, 1, 0),\n (2, 3, 4),\n (0, 5, 0)),\n ((0, 0, 0),\n (0, 0, 0),\n (8, 0, 0)),\n ),\n dtype=np.uint8,\n)\n\nactual = select_slice_axis(arr, 2, 1)\nexpected = np.array(\n (\n (0, 0, 9),\n (0, 5, 0),\n (8, 0, 0),\n ), dtype=np.uint8\n)\nassert np.all(expected == actual)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T07:51:31.133", "Id": "525143", "Score": "0", "body": "Thank you very much, this is really helpful! Just one more clarification: why `eval` is so bad? Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T12:51:27.720", "Id": "525156", "Score": "1", "body": "It greatly increases the surface area for bugs and security flaws." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-01T16:23:38.230", "Id": "265604", "ParentId": "265551", "Score": "1" } } ]
<p><a href="https://archive.ics.uci.edu/ml/datasets/iris" rel="nofollow noreferrer">Iris Data Set</a> consists of three classes in which versicolor and virginica are not linearly separable from each other.</p> <p>I constructed a subset for these two classes, here is the code</p> <pre><code>from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import numpy as np iris = load_iris() x_train = iris.data[50:] y_train = iris.target[50:] y_train = y_train - 1 x_train, x_test, y_train, y_test = train_test_split( x_train, y_train, test_size=0.33, random_state=2021) </code></pre> <p>and then I built a Logistic Regression model for this binary classification</p> <pre><code>def sigmoid(z): s = 1 / (1 + np.exp(-z)) return s class LogisticRegression: def __init__(self, eta=.05, n_epoch=10, model_w=np.full(4, .5), model_b=.0): self.eta = eta self.n_epoch = n_epoch self.model_w = model_w self.model_b = model_b def activation(self, x): z = np.dot(x, self.model_w) + self.model_b return sigmoid(z) def predict(self, x): a = self.activation(x) if a &gt;= 0.5: return 1 else: return 0 def update_weights(self, x, y, verbose=False): a = self.activation(x) dz = a - y self.model_w -= self.eta * dz * x self.model_b -= self.eta * dz def fit(self, x, y, verbose=False, seed=None): indices = np.arange(len(x)) for i in range(self.n_epoch): n_iter = 0 np.random.seed(seed) np.random.shuffle(indices) for idx in indices: if(self.predict(x[idx])!=y[idx]): self.update_weights(x[idx], y[idx], verbose) else: n_iter += 1 if(n_iter==len(x)): print('model gets 100% train accuracy after {} epoch(s)'.format(i)) break </code></pre> <p>I added the param <code>seed</code> for reproduction.</p> <pre><code>import time start_time = time.time() w_mnist = np.full(4, .1) classifier_mnist = LogisticRegression(.05, 1000, w_mnist) classifier_mnist.fit(x_train, y_train, seed=0) print('model trained {:.5f} s'.format(time.time() - start_time)) y_prediction = np.array(list(map(classifier_mnist.predict, x_train))) acc = np.count_nonzero(y_prediction==y_train) print('train accuracy {:.5f}'.format(acc/len(y_train))) y_prediction = np.array(list(map(classifier_mnist.predict, x_test))) acc = np.count_nonzero(y_prediction==y_test) print('test accuracy {:.5f}'.format(acc/len(y_test))) </code></pre> <p>The accuracy is</p> <pre><code>train accuracy 0.95522 test accuracy 0.96970 </code></pre> <p>the <a href="https://github.com/albert10jp/deep-learning/blob/main/LR_on_not_linearly_separable_data.ipynb" rel="nofollow noreferrer">link</a> is my github repo</p>
[]
{ "AcceptedAnswerId": "265773", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-06T11:00:03.783", "Id": "265767", "Score": "0", "Tags": [ "python", "machine-learning" ], "Title": "Logistic Regression for non linearly separable data" }
265767
accepted_answer
[ { "body": "<p>This is a very nice little project but there are some thing to upgrade here :)</p>\n<hr />\n<p><strong>Code beautification</strong></p>\n<ol>\n<li>Split everything to functions, there is no reason to put logic outside of a function, including the prediction part (this will remove the code duplication) and call everything from a <code>main</code> function. For example a loading function:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def load_and_split_iris(data_cut: int=50, train_test_ratio: float=0,333)\n iris = load_iris()\n x_train = iris.data[data_cut:]\n y_train = iris.target[data_cut:]\n y_train = y_train - 1\n x_train, x_test, y_train, y_test = train_test_split(\n x_train, y_train, test_size=train_test_ratio, random_state=2021)\n return x_train, x_test, y_train, y_test\n</code></pre>\n<ol start=\"2\">\n<li>Magic numbers make your code look bad, turn them into a <code>CODE_CONSTANTS</code>.</li>\n<li>I really like type annotations, it will make your code more understandable for future usage and you will not confuse with the types. I added them in the code example in 1. Another example: <code>def fit(self, x: np.array, y: np.array, verbose: bool=False, seed: int=None):</code>. Type annotation can also declare return type, read into that.</li>\n<li>String formatting, this: <code>'model gets 100% train accuracy after {} epoch(s)'.format(i)</code> and turn into <code>f'model gets 100% train accuracy after {i} epoch(s)'</code>.</li>\n</ol>\n<p><strong>Bug</strong></p>\n<p>You reset the seed every loop (<code>LogisticRegression.fit</code>), in case you are passing <code>None</code> this is fine (since the OS will generate random for you) but if you pass a specific seed the numbers will be the same each time you shuffle. Take the seed setting outside of the loop.</p>\n<p><strong>Future work</strong></p>\n<p>If you are looking to continue the work I recommend to try and create a multiclass logistic regression.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-06T11:59:48.500", "Id": "265773", "ParentId": "265767", "Score": "2" } } ]
<p>Hello everyone I was told to post this here instead of StackOverFlow.</p> <p>I am using PyAutoGUI currently as this was the best tools I could manage to find to use a piece of software that has no native Python function. I am using the mouse and keyboard control to design maps for Dungeons and Dragons using the software Dungeon Painter Studio. It is working as intended and I have figured out a way to actually use my script to create maps on it however, since PyAutoGUI is based on mouse location and pixels it has been quite a manual process.</p> <p>EDIT:</p> <p>Here is a picture of the software with nothing in it just opened up: <a href="https://i.stack.imgur.com/80A6M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/80A6M.png" alt="enter image description here" /></a></p> <p>Here is a picture after the code has been ran: <a href="https://i.stack.imgur.com/9891z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9891z.png" alt="enter image description here" /></a></p> <p>My reason for creating this script is so that I can eventually randomize it to create a random generated map for my D&amp;D campaign that is somewhat original compared to just taking a map off the internet.</p> <p>I am inputting a starting location for the mouse and have it click and moved based on relative location to that starting position. Here is a piece of what it currently looks like:</p> <pre><code>#Switch to dps, maximize window, select the tile hotkey pyautogui.keyDown('altleft'); pyautogui.press('tab'); pyautogui.keyUp('altleft') fw = pyautogui.getActiveWindow() fw.maximize() pyautogui.keyDown('enter') #Select the background tile pyautogui.click('dirt_k.png') #Create background pyautogui.moveTo(9,189) pyautogui.mouseDown(9,189) pyautogui.moveTo(748,808) pyautogui.mouseUp(252,436) #Select the dugeon tile pyautogui.click('dirt_d.png') #Create dungeon floor pyautogui.moveTo(329,807) pyautogui.mouseDown(329,807) pyautogui.moveRel(100,-75) pyautogui.mouseUp() pyautogui.moveRel(-25,0) pyautogui.mouseDown() pyautogui.moveRel(-50,-50) pyautogui.mouseUp() pyautogui.moveRel(-100,0) pyautogui.mouseDown() pyautogui.moveRel(250,-125) pyautogui.mouseUp() pyautogui.moveRel(0,100) pyautogui.mouseDown() pyautogui.moveRel(50,25) pyautogui.mouseUp() pyautogui.moveRel(0,100) pyautogui.mouseDown() pyautogui.moveRel(100,-125) pyautogui.mouseUp() pyautogui.moveRel(0,0) pyautogui.mouseDown() pyautogui.moveRel(-25,-50) pyautogui.mouseUp() pyautogui.moveRel(-75,0) pyautogui.mouseDown() pyautogui.moveRel(175,-100) pyautogui.mouseUp() pyautogui.mouseDown() pyautogui.moveRel(-25,-50) pyautogui.mouseUp() pyautogui.moveRel(25,0) pyautogui.mouseDown() pyautogui.moveRel(-225,-125) pyautogui.mouseUp() </code></pre> <p>It basically continues on like that for hundreds of lines to create a sample map. I was just seeing if anyone else is familiar enough with PyAutoGUI (or any other tools) that would help automated this process a bit more.</p> <p>I have the amount of pixels per square which is roughly 25px so it isn't too hard to calculate. Moving right is +25 left is -25 down is +25 up is -25. So using those measurements I have been able to calculate relative location where the mouse starts and move it around from there.</p> <p>Any advice or help is greatly appreciated, thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T21:08:26.723", "Id": "525195", "Score": "0", "body": "We are missing some information here. Can you include a screenshot of the program you're scripting, and explain why you're scripting it (instead of doing it once by hand?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T21:37:08.890", "Id": "525196", "Score": "0", "body": "Just added an edit with some screenshots so you can see it. The reason I am running this and want to optimize it is so that eventually I can randomly generate these maps to add to my D&D game." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T20:51:02.693", "Id": "265889", "Score": "2", "Tags": [ "python" ], "Title": "Maze generator for Dungeons and Dragons" }
265889
max_votes
[ { "body": "<blockquote>\n<p>My reason for creating this script is so that I can eventually randomize it to create a random generated map for my D&amp;D campaign that is somewhat original compared to just taking a map off the internet.</p>\n</blockquote>\n<p>Given that you want to eventually make a random map, your current approach won't work. You're just using hardcoded values, and there is no way to &quot;randomize&quot; it without fundamentally re-writing it.</p>\n<ul>\n<li>The first change I would recommend is separate the data out. This makes the program shorter, clearer, and easier to change to add something like randomness</li>\n</ul>\n<pre><code>#Create dungeon floor\npyautogui.moveTo(329,807)\npyautogui.mouseDown(329,807)\npyautogui.moveRel(100,-75)\npyautogui.mouseUp()\n\nlines = [\n ((-25, 0), (-50, 50)),\n ((-100,0), (250,-125))\n ((0,100), (50,25)),\n ((0,100), (100,-125)),\n ((0,0), (-25,-50)),\n ((-75,0), (175,-100)),\n ((0,0), (-25,-50)),\n ((25,0), (-225,-125)),\n]\n\nfor down, up in lines:\n pyautogui.moveRel(*down)\n pyautogui.mouseDown()\n pyautogui.moveRel(*up)\n pyautogui.mouseUp()\n</code></pre>\n<ul>\n<li>Work in absolute coordinates, not relative ones. It will make things easier for random dungeons.</li>\n<li>Add comments. Does a particular mouse movement draw a room? Does it draw a line bordering a room? I have literally no idea. In this case, move movement is so opaque it will be useful for you as well, not just other readers.</li>\n<li>As a warning, the whole idea of scripting a dungeon generation program may not be worth it. What happens if you want a map that's bigger than your screen resolution? If you just output your own image directly, it will be easier than scripting in some ways.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T23:17:20.757", "Id": "525199", "Score": "0", "body": "Yes this is perfect and what I was looking for something along these lines (pun intended)! In a all seriousness though I do recognize the limitations of working with a limited amount of screen space right now and was heading in the direction you just explained. Adding the lines like that should really help. As for the limited map spacing, I was planning on just creating multiple that could possibly connected if I wrote in some kind of connection point to be in that would carry over into the next map. This is a great start for me though and I really do appreciate the time you took to answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T23:07:19.260", "Id": "265891", "ParentId": "265889", "Score": "1" } } ]
<p>Python Beginner building an automation irrigation system in Raspberry Pi.</p> <p>The Python has two functions:</p> <ol> <li>Single wire temperature sensor (DS18B20) that prints/monitors temperature</li> <li>Turn on LED (will be relay switch)</li> </ol> <p>The idea is when the temperature gets too hot, it will turn on the switch/Led that will turn on the air conditioning.</p> <p>Looking on advice in two capacities:</p> <ol> <li>To make it cleaner/better code and more efficient</li> <li>How can I use &quot;Temperature&quot; as a global variable so I can use it on other things like a screen/LCD</li> </ol> <pre><code>#import modules import time import board import busio import digitalio from board import * from datetime import date #DigitalIO and Pin setup tempLed = digitalio.DigitalInOut(D17) #PIN LED for too hot sensor. tempLed.direction = digitalio.Direction.OUTPUT tempSensor = digitalio.DigitalInOut(D14) #Temp sensor DS18B20 as configured in terminal tempSensor.switch_to_input(pull=digitalio.Pull.UP) tempSensor.pull = digitalio.Pull.UP #main loop try: while True: tempStore = open(&quot;/sys/bus/w1/devices/28-3cffe076cfcf/w1_slave&quot;) #change this number to the Device ID of your sensor data = tempStore.read() tempStore.close() tempData = data.split(&quot;\n&quot;)[1].split(&quot; &quot;)[9] temperature = float(tempData[2:]) temperature = temperature/1000 print(temperature) if temperature &gt; 24: #change this value to adjust the 'too hot' threshold tempLed.value = True else: tempLed.value = False time.sleep(1) except KeyboardInterrupt: digitalio.cleanup() print (&quot;Program Exited Cleanly&quot;) </code></pre> <p>Sample data:</p> <pre class="lang-none prettyprint-override"><code>70 01 55 05 7f a5 81 66 3d : crc=3d YES 70 01 55 05 7f a5 81 66 3d t=23000 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-10T15:08:18.167", "Id": "525249", "Score": "2", "body": "Your `data.split(\"\\n\")[1].split(\" \")[9]` operation extracts the 10th space-separated word from the second line of `data`. We can't tell how robust that extraction process is without seeing what the sensor returns. Could you provide a sample of the actual data that gets returned from the sensor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T14:20:24.947", "Id": "525313", "Score": "0", "body": "@AJNeufeld - thanks for info; this is data extracted for temperature = 23. First example is data = `70 01 55 05 7f a5 81 66 3d : crc=3d YES\n70 01 55 05 7f a5 81 66 3d t=23000\n` and this is tempData \n`t=23000`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-12T01:19:27.617", "Id": "525373", "Score": "0", "body": "I’ve added the sample data to the question post. Please confirm it was formatted properly, by editing it if it was not." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-10T14:00:33.267", "Id": "265914", "Score": "5", "Tags": [ "python-3.x" ], "Title": "Temperature Sensor that loop and turns on cooling" }
265914
max_votes
[ { "body": "<p>I'm going to assume that your device has a <code>sysfs</code> interface identical to that described in <a href=\"https://albertherd.com/2019/01/20/using-c-to-monitor-temperatures-through-your-ds18b20-thermal-sensor-raspberry-pi-temperature-monitoring-part-3/\" rel=\"noreferrer\">this guide</a>, which based on your code is likely the case.</p>\n<blockquote>\n<p>How can I use &quot;Temperature&quot; as a global variable</p>\n</blockquote>\n<p>is the opposite direction to what you should do. Currently <em>all</em> of your code is global, but you should put some effort into making it re-entrant.</p>\n<p>Other than your global code, one thing that stands out is the non-guaranteed <code>close</code> call, which should be replaced by a <code>with</code> statement.</p>\n<p>You should not need to <code>read()</code> the entire file. Instead, read line-by-line until you find a match.</p>\n<pre><code> if temperature &gt; 24: #change this value to adjust the 'too hot' threshold\n tempLed.value = True\n else: \n tempLed.value = False\n</code></pre>\n<p>should be reduced to</p>\n<pre><code>temp_led.value = temperature &gt; threshold\n</code></pre>\n<p>where <code>threshold</code> is a parameter instead of being hard-coded, and the variable names are PEP8-compliant.</p>\n<pre><code>except KeyboardInterrupt:\n digitalio.cleanup() \n print (&quot;Program Exited Cleanly&quot;)\n</code></pre>\n<p>should instead be</p>\n<pre><code>except KeyboardInterrupt:\n pass\nfinally:\n digitalio.cleanup() \n print (&quot;Program Exited Cleanly&quot;)\n</code></pre>\n<p>In other words, you should clean up regardless of why and how the program exited.</p>\n<p>Don't hard-code the device ID - if you can assume that there's only one such sensor, use glob-matching instead.</p>\n<h2>Suggested (not tested)</h2>\n<pre class=\"lang-py prettyprint-override\"><code>class TempSensor:\n def __init__(self):\n sensor = digitalio.DigitalInOut(D14) # Temp sensor DS18B20 as configured in terminal\n sensor.switch_to_input(pull=digitalio.Pull.UP)\n sensor.pull = digitalio.Pull.UP\n\n parent, = Path('/sys/bus/w1/devices/').glob('28-*')\n self.path = parent / 'w1_slave'\n\n def read(self) -&gt; float:\n with self.path.open() as f:\n for line in f:\n parts = line.split('t=', 1)\n if len(parts) == 2:\n return float(parts[1].rstrip()) / 1000\n raise ValueError('Temperature not found')\n\n\ndef polling_loop(interval: float=1, threshold: float=24) -&gt; None:\n sensor = TempSensor()\n led = digitalio.DigitalInOut(D17) # PIN LED for too hot sensor. \n led.direction = digitalio.Direction.OUTPUT\n\n while True:\n temperature = sensor.read()\n print(temperature)\n led.value = temperature &gt; threshold\n time.sleep(interval)\n\n\ndef main() -&gt; None:\n try:\n polling_loop()\n except KeyboardInterrupt:\n pass\n finally:\n digitalio.cleanup() \n print(&quot;Program Exited Cleanly&quot;)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-10T16:14:58.777", "Id": "265919", "ParentId": "265914", "Score": "10" } } ]
<p>A unix convention is to use <code>-</code> as a placeholder for stdin/stdout in command lines, e.g. <code>gcc -x c -</code> to compile stdin as C. I often find myself writing logic to get this behavior in my Python scripts, so I abstracted it out into a context manager:</p> <pre class="lang-py prettyprint-override"><code>from typing import IO class argfile: def __init__(self, default: IO, filename: str, mode: str = 'r'): self.__file = default if filename == '-' else open(filename, mode) self.__should_close = filename != '-' def __enter__(self) -&gt; IO: return self.__file def __exit__(self, exc_type, exc_value, exc_traceback): self.close() def close(self): if self.__should_close: self.__file.close() </code></pre> <p>Now instead of writing this mess:</p> <pre class="lang-py prettyprint-override"><code>args = parser.parse_args() if args.inputfile == '-': infile = sys.stdin else: infile = open(args.inputfile, 'r') if args.output == '-': outfile = sys.stdout else: outfile = open(args.output, 'w') try: do_work(infile, outfile) finally: if args.output != '-': outfile.close() if args.inputfile != '-': infile.close() </code></pre> <p>I instead write:</p> <pre class="lang-py prettyprint-override"><code>args = parser.parse_args() with argfile(sys.stdin, args.inputfile, 'r') as infile, \ argfile(sys.stdout, args.output, 'w') as outfile: do_work(infile, outfile) </code></pre> <p>I do consider it important to close the files and not close stdin/stdout, as I often call the <code>main()</code> functions of my Python scripts inside other scripts with much longer lifetimes. Also note that I named the class in lowercase because I think of it more as a function call replacing <code>open(...)</code> than as a class constructor.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T16:40:47.557", "Id": "525343", "Score": "0", "body": "Is there a reason you don't use [`type=argparse.FileType(\"r\")`](https://docs.python.org/3.9/library/argparse.html#argparse.FileType) to get automatic handling of '-' as a command line argument?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T20:03:42.133", "Id": "525356", "Score": "0", "body": "@RootTwo Because I didn't know that exists. This is exactly why I asked this question: I wanted someone to tell me I was working too hard. Although I don't quite see how to close the file without closing `stdin`/`stdout` if a `-` was passed..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T20:13:51.897", "Id": "525357", "Score": "0", "body": "@RootTwo I'm not going to use that, though, see https://bugs.python.org/issue13824 . In particular, \"FileType is not what you want for anything but quick scripts that can afford to either leave a file open or to close stdin and/or stdout.\" I don't want to do either of those things. However, that thread does have some other solutions I might prefer" } ]
{ "AcceptedAnswerId": "265978", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T04:48:31.650", "Id": "265935", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "argfile: read/write stdio or specified file depending on command line argument" }
265935
accepted_answer
[ { "body": "<p>The code can be simplified using the <code>contextlib.contextmanager</code> decorator:</p>\n<pre><code>from contextlib import contextmanager\n\n@contextmanager\ndef argfile(default: IO, filename: str, mode: str = 'r'):\n file_like = open(filename, mode) if filename != '-' else default\n yield file_like\n if filename != '-':\n file_like.close()\n</code></pre>\n<p>Use it the same way as your code.</p>\n<p>Is <code>default</code> ever anything other than <code>stdin</code> or <code>stdout</code>? If not, then maybe something like:</p>\n<pre><code>@contextmanager\ndef argfile(filename: str, mode: str = 'r'):\n\n if filename != '-' :\n file_like = open(filename, mode)\n\n else:\n file_like = sys.stdin if mode == 'r' else sys.stdout\n\n yield file_like\n\n if filename != '-':\n file_like.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T01:08:27.467", "Id": "525436", "Score": "0", "body": "I ended up using a modification of the second version which is `if filename == '-': yield sys.stdout if mode == 'w' else sys.stdin; else: with open(...) as f: yield f`, which is a bit shorter and nicer IMO" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-12T05:34:16.303", "Id": "265978", "ParentId": "265935", "Score": "1" } } ]
<p>Could someone please help me out, I'm trying to remove the need to iterate through the dataframe and know it is likely very easy for someone with the knowledge.</p> <p>Dataframe:</p> <pre><code> id racecourse going distance runners draw draw_bias 0 253375 178 Standard 7.0 13 2 0.50 1 253375 178 Standard 7.0 13 11 0.25 2 253375 178 Standard 7.0 13 12 1.00 3 253376 178 Standard 6.0 12 2 1.00 4 253376 178 Standard 6.0 12 8 0.50 ... ... ... ... ... ... ... ... 378867 4802789 192 Standard 7.0 16 11 0.50 378868 4802789 192 Standard 7.0 16 16 0.10 378869 4802790 192 Standard 7.0 16 1 0.25 378870 4802790 192 Standard 7.0 16 3 0.50 378871 4802790 192 Standard 7.0 16 8 1.00 378872 rows × 7 columns </code></pre> <p>What I need is to add a new column with the count of unique races (id) by the conditions defined below. This code works as expected but it is sooo slow....</p> <pre><code>df['race_count'] = None for i, row in df.iterrows(): df.at[i, 'race_count'] = df.loc[(df.racecourse==row.racecourse)&amp;(df.going==row.going)&amp;(df.distance==row.distance)&amp;(df.runners==row.runners), 'id'].nunique() </code></pre>
[]
{ "AcceptedAnswerId": "266030", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T20:23:57.220", "Id": "265968", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "add column with count by constraint" }
265968
accepted_answer
[ { "body": "<p>Sorry, this is not a complete solution, just an idea.</p>\n<p>In Pandas you can split a data frame in subgroups based on one or multiple grouping variables using the <code>groupby</code> method. You can then apply an operation (in this case <code>nunique</code>) to each of the subgroups:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].nunique()\n</code></pre>\n<p>This should give you the number of races with the same characteristics (racecourse, going, ...) but unique values for <code>id</code>.</p>\n<p>Most importantly, this should be much faster than looping over the rows, especially for larger data frames.</p>\n<hr />\n<p><strong>EDIT:</strong></p>\n<p>Here's a complete solution also including the combination with the original data frame (thanks to <em>ojdo</em> for suggesting <code>join</code>/<code>merge</code>)</p>\n<pre class=\"lang-py prettyprint-override\"><code>race_count = df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].nunique()\nrace_count.name = 'race_count'\ndf.merge(race_count, on=['racecourse', 'going', 'distance', 'runners'])\n</code></pre>\n<p>Conveniently, <code>merge</code> broadcasts the values in <code>race_count</code> to all rows of <code>df</code> based on the values in the columns specified by the <code>on</code> parameter.</p>\n<p>This outputs:</p>\n<pre><code> id racecourse going distance runners draw draw_bias race_count \n0 253375 178 Standard 7.0 13 2 0.50 1 \n1 253375 178 Standard 7.0 13 11 0.25 1 \n2 253375 178 Standard 7.0 13 12 1.00 1 \n3 253376 178 Standard 6.0 12 2 1.00 1 \n4 253376 178 Standard 6.0 12 8 0.50 1 \n5 4802789 192 Standard 7.0 16 11 0.50 2 \n6 4802789 192 Standard 7.0 16 16 0.10 2 \n7 4802790 192 Standard 7.0 16 1 0.25 2 \n8 4802790 192 Standard 7.0 16 3 0.50 2 \n9 4802790 192 Standard 7.0 16 8 1.00 2 \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T12:49:19.880", "Id": "525449", "Score": "1", "body": "And to complete this thought, the remaining step \"combine\", simply set the index of this result to the desired column, and `join` it with the original. (The general pattern is called [split-apply-combine](https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html?highlight=split%20apply%20combine#), and is often a good way to express operations.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T13:05:57.290", "Id": "525450", "Score": "0", "body": "Yes, good call. To be honest, I had problems coming up with a good implementation for combining the results (number of unique elements) with the original data frame `df`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-14T14:11:18.747", "Id": "525495", "Score": "0", "body": "This is fantastic, exactly what I needed. Thank you very much and may the force continue to be with you " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T03:41:52.880", "Id": "528825", "Score": "1", "body": "You can do this directly with [`groupby transform`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html) instead of needing `merge` at all -> `df['race_count'] = df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].transform('nunique')`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T14:44:56.287", "Id": "528946", "Score": "0", "body": "@Henry Ecker: Nice solution, very elegant and concise. I did not know about the `groupby transform` method. Cool!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T11:34:48.490", "Id": "266030", "ParentId": "265968", "Score": "2" } } ]
<p>Could someone please help me out, I'm trying to remove the need to iterate through the dataframe and know it is likely very easy for someone with the knowledge.</p> <p>Dataframe:</p> <pre><code> id racecourse going distance runners draw draw_bias 0 253375 178 Standard 7.0 13 2 0.50 1 253375 178 Standard 7.0 13 11 0.25 2 253375 178 Standard 7.0 13 12 1.00 3 253376 178 Standard 6.0 12 2 1.00 4 253376 178 Standard 6.0 12 8 0.50 ... ... ... ... ... ... ... ... 378867 4802789 192 Standard 7.0 16 11 0.50 378868 4802789 192 Standard 7.0 16 16 0.10 378869 4802790 192 Standard 7.0 16 1 0.25 378870 4802790 192 Standard 7.0 16 3 0.50 378871 4802790 192 Standard 7.0 16 8 1.00 378872 rows × 7 columns </code></pre> <p>What I need is to add a new column with the count of unique races (id) by the conditions defined below. This code works as expected but it is sooo slow....</p> <pre><code>df['race_count'] = None for i, row in df.iterrows(): df.at[i, 'race_count'] = df.loc[(df.racecourse==row.racecourse)&amp;(df.going==row.going)&amp;(df.distance==row.distance)&amp;(df.runners==row.runners), 'id'].nunique() </code></pre>
[]
{ "AcceptedAnswerId": "266030", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T20:23:57.220", "Id": "265968", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "add column with count by constraint" }
265968
accepted_answer
[ { "body": "<p>Sorry, this is not a complete solution, just an idea.</p>\n<p>In Pandas you can split a data frame in subgroups based on one or multiple grouping variables using the <code>groupby</code> method. You can then apply an operation (in this case <code>nunique</code>) to each of the subgroups:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].nunique()\n</code></pre>\n<p>This should give you the number of races with the same characteristics (racecourse, going, ...) but unique values for <code>id</code>.</p>\n<p>Most importantly, this should be much faster than looping over the rows, especially for larger data frames.</p>\n<hr />\n<p><strong>EDIT:</strong></p>\n<p>Here's a complete solution also including the combination with the original data frame (thanks to <em>ojdo</em> for suggesting <code>join</code>/<code>merge</code>)</p>\n<pre class=\"lang-py prettyprint-override\"><code>race_count = df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].nunique()\nrace_count.name = 'race_count'\ndf.merge(race_count, on=['racecourse', 'going', 'distance', 'runners'])\n</code></pre>\n<p>Conveniently, <code>merge</code> broadcasts the values in <code>race_count</code> to all rows of <code>df</code> based on the values in the columns specified by the <code>on</code> parameter.</p>\n<p>This outputs:</p>\n<pre><code> id racecourse going distance runners draw draw_bias race_count \n0 253375 178 Standard 7.0 13 2 0.50 1 \n1 253375 178 Standard 7.0 13 11 0.25 1 \n2 253375 178 Standard 7.0 13 12 1.00 1 \n3 253376 178 Standard 6.0 12 2 1.00 1 \n4 253376 178 Standard 6.0 12 8 0.50 1 \n5 4802789 192 Standard 7.0 16 11 0.50 2 \n6 4802789 192 Standard 7.0 16 16 0.10 2 \n7 4802790 192 Standard 7.0 16 1 0.25 2 \n8 4802790 192 Standard 7.0 16 3 0.50 2 \n9 4802790 192 Standard 7.0 16 8 1.00 2 \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T12:49:19.880", "Id": "525449", "Score": "1", "body": "And to complete this thought, the remaining step \"combine\", simply set the index of this result to the desired column, and `join` it with the original. (The general pattern is called [split-apply-combine](https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html?highlight=split%20apply%20combine#), and is often a good way to express operations.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T13:05:57.290", "Id": "525450", "Score": "0", "body": "Yes, good call. To be honest, I had problems coming up with a good implementation for combining the results (number of unique elements) with the original data frame `df`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-14T14:11:18.747", "Id": "525495", "Score": "0", "body": "This is fantastic, exactly what I needed. Thank you very much and may the force continue to be with you " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T03:41:52.880", "Id": "528825", "Score": "1", "body": "You can do this directly with [`groupby transform`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html) instead of needing `merge` at all -> `df['race_count'] = df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].transform('nunique')`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T14:44:56.287", "Id": "528946", "Score": "0", "body": "@Henry Ecker: Nice solution, very elegant and concise. I did not know about the `groupby transform` method. Cool!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T11:34:48.490", "Id": "266030", "ParentId": "265968", "Score": "2" } } ]
<p>I have a list of dictionaries <code>x</code> and a list of random numbers <code>x_randoms</code>. I want to update each of the dictionaries with the values from the list of random numbers. I've done the following and it works, but it feels a bit strange:</p> <pre><code>import random x = [{'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}}, {'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}}, {'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}}] x_randoms = [random.random() for i in range(len(x))] print(&quot;\nBefore loop...&quot;, x) [j.update({'key3': x_randoms[i]}) for i, j in enumerate(x)] print(&quot;\nAfter loop...&quot;, x) </code></pre> <p>The list comp at the bottom is mostly what is bothering me. Is that ok, or can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T18:27:22.783", "Id": "525474", "Score": "2", "body": "This is too hypothetical to be on-topic, unfortunately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-14T18:00:05.593", "Id": "525505", "Score": "0", "body": "If you're not using the result of a list comprehension, it's a huge clue that there's a far clearer way to write your program. In this case, you should be using an imperative-style `for` loop instead." } ]
{ "AcceptedAnswerId": "266041", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T16:58:51.493", "Id": "266039", "Score": "1", "Tags": [ "python" ], "Title": "Updating python dictionary in a loop" }
266039
accepted_answer
[ { "body": "<p>Your suspicions are correct, this is called using comprehension syntax for side-effects, and is normally bad practice.</p>\n<p>A better way to do this is with a <code>for</code> loop</p>\n<pre class=\"lang-py prettyprint-override\"><code>for item in x:\n # this also gets rid of your random number list\n item['key3'] = random.random()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T17:21:21.390", "Id": "266041", "ParentId": "266039", "Score": "8" } } ]
<p>I have a list of dictionaries <code>x</code> and a list of random numbers <code>x_randoms</code>. I want to update each of the dictionaries with the values from the list of random numbers. I've done the following and it works, but it feels a bit strange:</p> <pre><code>import random x = [{'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}}, {'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}}, {'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}}] x_randoms = [random.random() for i in range(len(x))] print(&quot;\nBefore loop...&quot;, x) [j.update({'key3': x_randoms[i]}) for i, j in enumerate(x)] print(&quot;\nAfter loop...&quot;, x) </code></pre> <p>The list comp at the bottom is mostly what is bothering me. Is that ok, or can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T18:27:22.783", "Id": "525474", "Score": "2", "body": "This is too hypothetical to be on-topic, unfortunately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-14T18:00:05.593", "Id": "525505", "Score": "0", "body": "If you're not using the result of a list comprehension, it's a huge clue that there's a far clearer way to write your program. In this case, you should be using an imperative-style `for` loop instead." } ]
{ "AcceptedAnswerId": "266041", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T16:58:51.493", "Id": "266039", "Score": "1", "Tags": [ "python" ], "Title": "Updating python dictionary in a loop" }
266039
accepted_answer
[ { "body": "<p>Your suspicions are correct, this is called using comprehension syntax for side-effects, and is normally bad practice.</p>\n<p>A better way to do this is with a <code>for</code> loop</p>\n<pre class=\"lang-py prettyprint-override\"><code>for item in x:\n # this also gets rid of your random number list\n item['key3'] = random.random()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-13T17:21:21.390", "Id": "266041", "ParentId": "266039", "Score": "8" } } ]
<p>Here I have a multidimensional list in python. Suppose I take an input, how do I find the number of adjacent elements of that input which are alphabets other than itself? If there are multiple indices at which the element is placed, then we have to print the maximum of all possibility. For example, the number of adjacent elements which are equal to 'R' is 2.</p> <pre><code>z=input() #suppose c='R' #print the number of equal and adjacent elements, for c='R' it is 2 l=[['G', '.', 'B', 'C'], ['A', '.', 'R', 'Z'], ['.', '.', 'R', 'B']] #G.BC #A.RZ #..RB </code></pre> <p>This is how I tried it.</p> <pre><code>from collections import OrderedDict x,y,z=input().split() l=[] c=[] x,y=int(x),int(y) def f(e): ls=[] a=e[0] b=e[1] for i in range(int(x)): for j in range(int(y)): t=l[i][j] if i==a and t!=z and t!='.': if j==b-1 or j==b+1: ls.append(t) if j==b and t!=z and t!='.': if i==a-1 or i==a+1: ls.append(t) ls=list(OrderedDict.fromkeys(ls)) return ls for i in range (0,int(x)): s=&quot;&quot; s=input() sl=list(s) for j in range(int(y)): if z==sl[j]: c.append([i,j]) l.append(sl) d=0 for i in range(len(c)): m=f(c[i]) d=max(d,len(m)) print(d) </code></pre> <p>Here function f is used to create a list of elements which satisfy the conditions. z is the character which the user inputs and x,y is the dimension of the list.</p> <pre><code> 'OO WW WW' #Here if the input is W, then the answer should be one. 'G.B. .RR. TTT.' #Here if input is R, then the answer is 2 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T21:09:06.563", "Id": "525712", "Score": "2", "body": "Can you provide extra examples of expected input and output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T13:01:00.000", "Id": "525752", "Score": "2", "body": "Your current wording is unclear. You ask how to find the number of adjacent elements, but then show an implementation. Is this implementation working?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T14:00:05.077", "Id": "525760", "Score": "0", "body": "So if I understand correctly, you are looking for the count of unique letters that are not equal to your target letter, after making a list of all neighbors of all instances of that target letter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:09:06.970", "Id": "525781", "Score": "0", "body": "@Flater Yes, and also it should not be equal to '.'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T17:29:37.540", "Id": "525788", "Score": "0", "body": "What is this code actually supposed to be doing? Is there a problem that this solves? I think that might help clear up what's going on" } ]
{ "AcceptedAnswerId": "266153", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-17T14:57:58.870", "Id": "266135", "Score": "-4", "Tags": [ "python" ], "Title": "How to find adjacent elements in multidimensional list in Python?" }
266135
accepted_answer
[ { "body": "<ul>\n<li>To be honest, I can't quite confirm what you actually want. Since you ask in <code>Code Review</code>, I assume you want someone to review your code and give some advice.</li>\n</ul>\n<h3>advice</h3>\n<ol>\n<li>Please always use meaningful name to variable and function name, don't use something like <code>a</code>, <code>b</code>, <code>x</code>, <code>y</code>, <code>f</code>. They are confusing to the people who read your code. When you read the code and following advice, you will find it. It is OK use <code>i</code>, <code>j</code> in some simple loop. So I replaced most of them, some of them may be not so proper.</li>\n<li>There is no need to record the adjacent elements in <code>ls</code>(result), just <code>+1</code> to the result of <code>f</code>(find_adjacent_elements).</li>\n<li>There is also no need to check the whole <code>l</code>(map), just check the <code>z</code>(base_char) up\\down\\left\\right 4 direction. It can speed up your code especially the size of map is huge.</li>\n<li>Please read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>, it can make your code more readable. Such as <code>a=e[0]</code> should be <code>a = e[0]</code>.</li>\n<li>I fix some other small issues, please check the difference between my code and your code.</li>\n</ol>\n<h3>fixed code:</h3>\n<pre><code>def find_adjacent_elements(base_pos):\n result = 0\n directions = [[1,0],[-1,0],[0,1],[0,-1]]\n for direction in directions:\n try:\n adjacent_element = map[base_pos[0] + direction[0]][base_pos[1] + direction[1]]\n if adjacent_element != base_char and adjacent_element != &quot;.&quot;:\n result += 1\n except IndexError:\n pass\n return result\n \nprint(&quot;please input the columns,rows and base character&quot;)\ncolumns,rows,base_char = input().split()\nmap = []\nbase_char_pos = []\ncolumns,rows = int(columns),int(rows)\nfor i in range(columns):\n map_line = list(input())\n for j in range(rows):\n if base_char == map_line[j]:\n base_char_pos.append([i,j])\n map.append(map_line)\nans = 0\nfor i in range(len(base_char_pos)):\n ans = max(ans,find_adjacent_elements(base_char_pos[i]))\nprint(ans)\n</code></pre>\n<h3>test:</h3>\n<pre><code>please input the columns,rows and base character\n4 4 R\n..A.\n.BRC\n.DRE\n..F.\n\n3\n\nplease input the columns,rows and base character\n2 2 R\nR.\n.R\n\n0\n\nplease input the columns,rows and base character\n3 2 W\nOO\nWW\nWW\n\n1\n\nplease input the columns,rows and base character\n3 4 R\nG.B.\n.RR.\nTTT.\n\n2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T09:17:24.567", "Id": "525737", "Score": "0", "body": "Thank you very much for your advice, I will keep those points in mind . I understood how you just checked the positions around the base character made it more efficient. Thanks for taking out your time and helping me!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T07:27:49.380", "Id": "266153", "ParentId": "266135", "Score": "2" } } ]
<p>I have a Python script that runs as a service, like this:</p> <pre class="lang-py prettyprint-override"><code>import time import traceback while True: time.sleep(60) try: main() except Exception: # Print the traceback, but keep running traceback.print_exc() </code></pre> <p>This runs every 60 seconds, and works great. What I want to do is have my code also listen for the <code>USR1</code> kill signal, and if it triggers, run main() right away. This way, my code can monitor something for changes periodically, but it can also get informed when a change happened, so it can react right away without waiting for the <code>time.sleep()</code> to return.</p> <p>What I ended up with is this:</p> <pre class="lang-py prettyprint-override"><code>from threading import Lock import signal import time import traceback MAIN_RUNNING = Lock() def run_main(): if MAIN_RUNNING.acquire(blocking=False): try: main() except Exception: traceback.print_exc() else: print(&quot;main() is already running - couldn't lock it&quot;) signal.signal(signal.SIGUSR1, lambda *_: run_main()) while True: time.sleep(60) run_main() </code></pre> <p>Does that make sense?</p> <p>Any potential problems I might run into with this?</p> <p>Is there a simpler way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T12:12:09.123", "Id": "525947", "Score": "0", "body": "I get an error when running your code `NameError: name 'main' is not defined` before the expected messages `main() is already running - couldn't lock it` appear. I think your code is more suited to StackOverflow and not Code Review. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T15:15:22.863", "Id": "525963", "Score": "0", "body": "@C.Harley that's because `main` is a stand-in for whatever my code is supposed to do, is irrelevant to the question, and is therefore not defined in the example. My real main function is very large" } ]
{ "AcceptedAnswerId": "266225", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-19T22:58:39.433", "Id": "266224", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Python Service with USR1 kill signal handler" }
266224
accepted_answer
[ { "body": "<p>Your basic code looks fine, but you may encounter one issue if you start doing more complex work.</p>\n<p>Signals are handled in a different context to the context your program is normally executing in - the OS can suspend your program at any time, while it's running or not, to run a signal handler which then may execute more code from your program (if it's a signal for your process).</p>\n<p>This problem gives rise to the concept of &quot;reentrant functions&quot; which can safely have one thread suspended half way through execution, and have another thread enter it and run - without say, stomping on shared global variables or static allocations. There are surprisingly few reentrant functions in the C standard library, and POSIX libraries - see <a href=\"https://man7.org/linux/man-pages/man7/signal-safety.7.html\" rel=\"nofollow noreferrer\">https://man7.org/linux/man-pages/man7/signal-safety.7.html</a> for more information and a list.</p>\n<p>Expect seriously weird bugs or crashes if you call non-reentrant functions from the signal handler context.</p>\n<p>A safer way of handling this is to have the signal handler set a flag in your program when it's called. A daemon thread in your program can poll this flag and run in your program's regular context, when desired.</p>\n<p>Very naïve pseudocode:</p>\n<pre><code>ShouldRun = False\n\nfunc HandleSigUsr1:\n ShouldRun = True\n \nfunc HandleSigUsr1Daemon:\n while (1):\n if ShouldRun == True:\n ShouldRUn = False\n run_main()\n\nsignal.Signal(SIGUSR1, handleSigUsr1)\n</code></pre>\n<p>A slightly more powerful implementation could sleep for a short time (0.001s? 0.01s?) between daemon loops to avoid constantly sucking up CPU time, or poll a file descriptor rather than a variable, to have the OS sleep the daemon until there's new content.</p>\n<p>As a final disclaimer, I'm not sure if Python's signal handling library already does something like this under the hood - it seems like the kind of detail a high level language and runtime like Python would try to hide.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T01:04:37.600", "Id": "266225", "ParentId": "266224", "Score": "3" } } ]
<p>I have written a python script that generates random rows with a provided array. To better explain</p> <pre><code>input : [1,2,3,4,5] output : [1,2,3,4,5] [5,3,4,2,1] [1,2,4,5,3] [1,2,5,3,4] [5,4,3,2,1] [4,3,2,1,5] </code></pre> <p>I am sharing the function which generates the unique random placement of item in array for now</p> <pre><code>def myscore(self): # setting the values which I want in my output array score_array = array.array('i',[0,1,2,3,4]) score_index_len = len(score_array) score_string = '' loopidx=0 while loopidx &lt; score_index_len: #generate random index between number of array item i=randint(0,len(score_array)-1) score_string = score_string + ',' + str(score_array[i]) #remove the index del score_array[i] loopidx = loopidx + 1 return score_string[1:] </code></pre> <p>Please share your code review comments.</p>
[]
{ "AcceptedAnswerId": "266257", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T17:41:40.307", "Id": "266250", "Score": "1", "Tags": [ "python-3.x" ], "Title": "create script to convert array to string with array elements uniquely with randomness" }
266250
accepted_answer
[ { "body": "<h2>Performance</h2>\n<p>Since <a href=\"https://stackoverflow.com/q/38722105/9997212\">f-strings are faster than string concatenation</a>, you can replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array.pop(i))\n</code></pre>\n<p>with</p>\n<pre><code>score_string = score_string + f',{score_array.pop(i)}'\n</code></pre>\n<hr />\n<p>Since <a href=\"https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"nofollow noreferrer\"><code>pop</code></a> removes an element from a list given an index and returns it, you can simplify</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array[i])\ndel score_array[i]\n</code></pre>\n<p>to</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array.pop(i))\n</code></pre>\n<h2>Best practices</h2>\n<p>Since <a href=\"https://docs.python.org/3/library/functions.html#func-range\" rel=\"nofollow noreferrer\"><code>range</code></a> creates a iterable once in the iteration, you can replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>loopidx = 0\nscore_index_len = len(score_array)\n\nwhile loopidx &lt; score_index_len:\n ...\n\n loopidx = loopidx + 1 \n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>for loopidx in range(len(score_array)):\n ...\n</code></pre>\n<hr />\n<p>Since <a href=\"https://docs.python.org/3/library/random.html#random.randint\" rel=\"nofollow noreferrer\"><code>randint</code></a> is an alias for <code>randrange(a, b+1)</code>, you can simplify</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = randint(0, len(score_array)-1)\n</code></pre>\n<p>to</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = randrange(len(score_array))\n</code></pre>\n<hr />\n<p>Just for readability, you could replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + f',{score_array.pop(i)}'\n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string += f',{score_array.pop(i)}'\n</code></pre>\n<hr />\n<p>To avoid using <code>[1:]</code> when returning, you could create a new list and use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>scores = []\nfor loopidx in range(len(score_array)):\n i = randrange(len(score_array))\n scores.append(f'{score_array.pop(i)}')\n \nreturn ','.join(scores)\n</code></pre>\n<h3>Refactored code:</h3>\n<pre class=\"lang-py prettyprint-override\"><code>def myscore():\n score_array = array.array('i',[0,1,2,3,4])\n \n scores = []\n for loopidx in range(len(score_array)):\n i = randrange(len(score_array))\n scores.append(f'{score_array.pop(i)}')\n\n return ','.join(scores)\n</code></pre>\n<h2>Alternative</h2>\n<p>A simpler alternative is just use <a href=\"https://docs.python.org/3/library/random.html#random.shuffle\" rel=\"nofollow noreferrer\"><code>shuffle</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def myscore():\n score_array = array.array('i',[0,1,2,3,4])\n shuffle(score_array)\n return ','.join(map(str, score_array))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T17:39:56.897", "Id": "526053", "Score": "0", "body": "I would argue that if you need the index out of each iteration you should use enumerate as its more idiomatic:" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T03:30:13.717", "Id": "266257", "ParentId": "266250", "Score": "3" } } ]
<p>I have written a python script that generates random rows with a provided array. To better explain</p> <pre><code>input : [1,2,3,4,5] output : [1,2,3,4,5] [5,3,4,2,1] [1,2,4,5,3] [1,2,5,3,4] [5,4,3,2,1] [4,3,2,1,5] </code></pre> <p>I am sharing the function which generates the unique random placement of item in array for now</p> <pre><code>def myscore(self): # setting the values which I want in my output array score_array = array.array('i',[0,1,2,3,4]) score_index_len = len(score_array) score_string = '' loopidx=0 while loopidx &lt; score_index_len: #generate random index between number of array item i=randint(0,len(score_array)-1) score_string = score_string + ',' + str(score_array[i]) #remove the index del score_array[i] loopidx = loopidx + 1 return score_string[1:] </code></pre> <p>Please share your code review comments.</p>
[]
{ "AcceptedAnswerId": "266257", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-20T17:41:40.307", "Id": "266250", "Score": "1", "Tags": [ "python-3.x" ], "Title": "create script to convert array to string with array elements uniquely with randomness" }
266250
accepted_answer
[ { "body": "<h2>Performance</h2>\n<p>Since <a href=\"https://stackoverflow.com/q/38722105/9997212\">f-strings are faster than string concatenation</a>, you can replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array.pop(i))\n</code></pre>\n<p>with</p>\n<pre><code>score_string = score_string + f',{score_array.pop(i)}'\n</code></pre>\n<hr />\n<p>Since <a href=\"https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"nofollow noreferrer\"><code>pop</code></a> removes an element from a list given an index and returns it, you can simplify</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array[i])\ndel score_array[i]\n</code></pre>\n<p>to</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + ',' + str(score_array.pop(i))\n</code></pre>\n<h2>Best practices</h2>\n<p>Since <a href=\"https://docs.python.org/3/library/functions.html#func-range\" rel=\"nofollow noreferrer\"><code>range</code></a> creates a iterable once in the iteration, you can replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>loopidx = 0\nscore_index_len = len(score_array)\n\nwhile loopidx &lt; score_index_len:\n ...\n\n loopidx = loopidx + 1 \n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>for loopidx in range(len(score_array)):\n ...\n</code></pre>\n<hr />\n<p>Since <a href=\"https://docs.python.org/3/library/random.html#random.randint\" rel=\"nofollow noreferrer\"><code>randint</code></a> is an alias for <code>randrange(a, b+1)</code>, you can simplify</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = randint(0, len(score_array)-1)\n</code></pre>\n<p>to</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = randrange(len(score_array))\n</code></pre>\n<hr />\n<p>Just for readability, you could replace</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string = score_string + f',{score_array.pop(i)}'\n</code></pre>\n<p>with</p>\n<pre class=\"lang-py prettyprint-override\"><code>score_string += f',{score_array.pop(i)}'\n</code></pre>\n<hr />\n<p>To avoid using <code>[1:]</code> when returning, you could create a new list and use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>str.join</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>scores = []\nfor loopidx in range(len(score_array)):\n i = randrange(len(score_array))\n scores.append(f'{score_array.pop(i)}')\n \nreturn ','.join(scores)\n</code></pre>\n<h3>Refactored code:</h3>\n<pre class=\"lang-py prettyprint-override\"><code>def myscore():\n score_array = array.array('i',[0,1,2,3,4])\n \n scores = []\n for loopidx in range(len(score_array)):\n i = randrange(len(score_array))\n scores.append(f'{score_array.pop(i)}')\n\n return ','.join(scores)\n</code></pre>\n<h2>Alternative</h2>\n<p>A simpler alternative is just use <a href=\"https://docs.python.org/3/library/random.html#random.shuffle\" rel=\"nofollow noreferrer\"><code>shuffle</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def myscore():\n score_array = array.array('i',[0,1,2,3,4])\n shuffle(score_array)\n return ','.join(map(str, score_array))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T17:39:56.897", "Id": "526053", "Score": "0", "body": "I would argue that if you need the index out of each iteration you should use enumerate as its more idiomatic:" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T03:30:13.717", "Id": "266257", "ParentId": "266250", "Score": "3" } } ]
<p>The following script derives schemas from varied file formats. Can I get this reviewed? What would the improvements look like:</p> <pre><code> def _null_allowed_in_cols(self): for field in self.fields: field[&quot;type&quot;] = self._field_type_converter(field[&quot;type&quot;]) if type(field[&quot;type&quot;]) == list: if &quot;null&quot; not in field[&quot;type&quot;]: field[&quot;type&quot;].insert(0, &quot;null&quot;) else: field[&quot;type&quot;] = [&quot;null&quot;, field[&quot;type&quot;]] def _field_type_converter(self, field_type) -&gt; Union[str, list]: if type(field_type) is dict or type(field_type) is avro.schema.ImmutableDict: return field_type[&quot;type&quot;] elif type(field_type) is list: return list(map(lambda x: self._field_type_converter(x), field_type)) else: return field_type </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T21:22:27.627", "Id": "526206", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](http://meta.codereview.stackexchange.com/a/1765)*." } ]
{ "AcceptedAnswerId": "266330", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T01:51:07.367", "Id": "266308", "Score": "0", "Tags": [ "python", "python-3.x", "json", "apache-kafka" ], "Title": "OOP Refactoring" }
266308
accepted_answer
[ { "body": "<h1><code>_col_type</code></h1>\n<p>You can use a generator expression here to return either the first match or <code>None</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code> # go from this\n def _col_type(self, column_name):\n for column in self.fields:\n if column[&quot;name&quot;] == column_name:\n return column\n return None\n\n # to this\n def _col_type(self, column_name):\n return next((\n col['name'] for col in self.fields if col['name'] == column_name\n ), None)\n</code></pre>\n<h1>Checking types</h1>\n<p>Use <code>isinstance</code> rather than <code>type(val) == cls</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code># instead of this\nif type(field[&quot;type&quot;]) == list:\n # do something\n# or this\nif type(val) is dict:\n # do something\n\n# do this instead\nif isinstance(field['type'], list):\n # do something\n\n# or\nif isinstance(field_type, (dict, avro.schema.ImmutableDict)):\n # do something\n</code></pre>\n<h1>When to use lambda vs function</h1>\n<p>In this statement:</p>\n<pre class=\"lang-py prettyprint-override\"><code>list(map(lambda x: self._field_type_converter(x), field_type))\n</code></pre>\n<p>You don't actually need the lambda:</p>\n<pre class=\"lang-py prettyprint-override\"><code>list(map(self._field_type_converter, field_type))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-23T16:09:42.077", "Id": "266330", "ParentId": "266308", "Score": "1" } } ]
<p>I found abandoned <a href="https://github.com/jruizgit/rules" rel="nofollow noreferrer">project</a> on GitHub and curious is it possible to implement part of it on just Python?</p> <p>Here is most close <a href="https://github.com/jruizgit/rules/blob/master/README.md#python-2" rel="nofollow noreferrer">example of processing</a> I would like to implement:</p> <pre class="lang-py prettyprint-override"><code>from durable.lang import * with ruleset('test'): @when_all(m.subject.matches('3[47][0-9]{13}')) def amex(c): print ('Amex detected {0}'.format(c.m.subject)) @when_all(m.subject.matches('4[0-9]{12}([0-9]{3})?')) def visa(c): print ('Visa detected {0}'.format(c.m.subject)) @when_all(m.subject.matches('(5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|2720)[0-9]{12}')) def mastercard(c): print ('Mastercard detected {0}'.format(c.m.subject)) assert_fact('test', { 'subject': '375678956789765' }) assert_fact('test', { 'subject': '4345634566789888' }) assert_fact('test', { 'subject': '2228345634567898' }) </code></pre> <p><strong>Goal</strong>:</p> <ul> <li>Call functions only under some condition.</li> <li>Track matches and inner function execution in uniformed way.</li> <li>Reuse variables from the same scope to be more flexible with inner functions calls.</li> </ul> <p>I have <a href="https://stackoverflow.com/questions/68912078/is-there-a-better-way-of-conditional-execution-in-python">PoC</a> working, but I wonder is any better <strong>algorithmic</strong> approach to do the same in Python? Most obvious way to do something similar to bellow code. But is there more elegant way to get rid of repeating <code>if ...: processed = True</code> pattern and have this code more <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">DRY</a>?</p> <pre class="lang-py prettyprint-override"><code>def boo(a, c): # do something return True def foo(a, b, c): # do something more return True def setup(a, b, c): processed = False matched = False if a == &quot;boo&quot; and c == 1: matched = True processed = bool(boo(a, c)) if a == &quot;boo&quot; and (c == 2 or b == 3): matched = True processed = bool(foo(a, b, c)) ... if not matched: logger.warning(&quot;Couldn't match any rule&quot;) return processed </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T07:24:09.687", "Id": "526216", "Score": "1", "body": "Hey welcome to Code Review! It looks like your linked Stack Overflow post contains the actual code you want reviewed and what you've posted here is just the alternative code if you were doing it by hand is that right? In that case you actually need to post the code you want reviewed here rather than linking to it. Also edit your post to say _why_ you want this at all, what problem does it solve? That will provide the necessary context to say whether your solution is suitable and how it might be improved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T07:41:24.270", "Id": "526220", "Score": "0", "body": "(The *something* most *similar* to *bellow* should be to *bark*…?!;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T08:47:21.653", "Id": "526226", "Score": "0", "body": "@Greedo I'm not sure which one is better approach. I added an example to clarify idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T08:49:59.677", "Id": "526227", "Score": "0", "body": "@greybeard oh, well. Thanks for catching this. I added missing noun." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T12:01:54.750", "Id": "526241", "Score": "1", "body": "Code review is for code that you wrote and that you know is working. This question seems to indicate that someone else wrote the code and that you don't have it working the way you want to yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T14:59:01.423", "Id": "526259", "Score": "0", "body": "@pacmaninbw that's wrong assumption." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T15:04:24.250", "Id": "526260", "Score": "0", "body": "Also, why it was marked as off-topic. Could someone explain please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T15:09:13.160", "Id": "526261", "Score": "0", "body": "Here is the [help page for on-topic questions](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T15:11:14.820", "Id": "526262", "Score": "0", "body": "5 people closed the question, however, the moderator changed the reason for closure and became the only person to close the question (makes 6 people that closed the question)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T15:11:39.923", "Id": "526263", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/128933/discussion-between-su1tan-and-pacmaninbw)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T20:45:19.180", "Id": "526283", "Score": "0", "body": "(It's rather that `bellow` isn't anything like the opposite of *above* - *below* is.)" } ]
{ "AcceptedAnswerId": "266375", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T06:35:50.140", "Id": "266370", "Score": "1", "Tags": [ "python", "reinventing-the-wheel" ], "Title": "Implementing conditional execution in Python" }
266370
accepted_answer
[ { "body": "<p><strong>Bitwise Operators</strong></p>\n<p>While your use of bitwise operators works fine as far as I can tell, I wouldn't expect them to be used like this in Python. So instead of</p>\n<pre><code>if ((a == &quot;boo&quot;) &amp; ((c == 2) | (b == 3))):\n</code></pre>\n<p>I'd prefer</p>\n<pre><code>if a == &quot;boo&quot; and (c == 2 or b == 3):\n</code></pre>\n<p>Also note that you don't need as many parantheses.</p>\n<hr />\n<p><strong><code>processed = True</code></strong></p>\n<pre><code>if boo(a, c):\n processed = True\n</code></pre>\n<p>can be replaced by</p>\n<pre><code>processed = boo(a, c)\n</code></pre>\n<p>as long as <code>boo</code> (or any other relevant function) returns a <code>bool</code>. If it returns something else you can convert it to a <code>bool</code> explicitly:</p>\n<pre><code>processed = bool(boo(a, c))\n</code></pre>\n<hr />\n<p><strong>EDIT:</strong></p>\n<ul>\n<li>You do not need <code>matched</code>, simply use an <code>if - elif - else</code>-construct</li>\n<li>You <em>can</em> replace <code>processed</code> by storing the matching function call in a variable. I'm not sure if you should though.</li>\n</ul>\n<pre><code>from functools import partial\n\n\ndef setup(a, b, c):\n function_call = lambda: False\n\n if a == &quot;boo&quot; and c == 1:\n function_call = partial(boo, a, c) # alt: lambda: boo(a, c)\n elif a == &quot;boo&quot; and (c == 2 or b == 3):\n function_call = partial(foo, a, b, c) # alt: lambda: foo(a, b, c)\n else:\n logger.warning(&quot;Couldn't match any rule&quot;)\n\n return bool(function_call())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T09:57:57.500", "Id": "526233", "Score": "0", "body": "thanks! But there is a problem: I don't want to be dependent on inner function implementation. Also, if I want to track matches together with function return? Adding more `matched = True` in each step? (sorry, for not being more specific at the beginning)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T11:32:06.593", "Id": "526239", "Score": "0", "body": "I updated my original question with your proposal. But the code is not as DRY as it could be..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T11:46:04.233", "Id": "526240", "Score": "1", "body": "In general, please refrain from editing suggestions from answers into your existing question. Prefer posting a new question with the updated code. I've included some pointers for decreasing repetition in your edited code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T12:06:42.327", "Id": "526242", "Score": "0", "body": "Thanks for `partial` hint!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-25T09:25:32.370", "Id": "266375", "ParentId": "266370", "Score": "2" } } ]
<pre><code>def collatz(n, counter): if n == 1: return counter elif n % 2 == 0: return collatz(n/2, counter + 1) else: return collatz(3*n + 1, counter + 1) print(int(collatz(15, 0))) </code></pre> <p>Is there any way to improve this code? The two arguments passed on the <code>collatz()</code> function rubs me the wrong way. Tells me that should only be one, but I don't know better.</p> <p>My question is an attempt to improving my Python vocabulary as I just barely started. So, what useful Python tool could I have used here to make the code better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T07:38:44.730", "Id": "526293", "Score": "0", "body": "Do Python implementations typically eliminate tail-calls? If not, you're heading for a stack overflow by using recursion..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T15:21:33.407", "Id": "526328", "Score": "4", "body": "@TobySpeight CPython, the reference implementation, doesn't perform any form of tail call elimination" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T16:23:54.723", "Id": "526333", "Score": "2", "body": "See https://tobiaskohn.ch/index.php/2018/08/28/optimising-python-3/ for more information @TobySpeight" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T22:47:22.883", "Id": "526347", "Score": "3", "body": "@Jasmijn: It's not just CPython. Guido van Rossum has said that *NO* Python implementation is allowed to eliminate tail calls. So, any implementation that eliminates tail calls is non-compliant, and thus *by definition* not a Python implementation. Therefore, it is impossible that there is a Python implementation that eliminates tail calls, because if it did, it wouldn't be a Python implementation. (Personally, I find that quite insane: not eliminating tail calls is essentially a memory leak, so why would you *force* implementors to leak memory?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T09:37:10.917", "Id": "526367", "Score": "0", "body": "@JörgWMittag Where do you store traceback information if TCO is allowed? In another stack? Isn't the point that tracebacks are more important than allowing you to use recursion to loop? If you need such levels of recursion you can normally quite easily convert away from an FP approach." } ]
{ "AcceptedAnswerId": "266410", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T06:40:30.310", "Id": "266408", "Score": "10", "Tags": [ "python", "recursion", "collatz-sequence" ], "Title": "My recursive attempt at Collatz Sequence in Python" }
266408
accepted_answer
[ { "body": "<p><strong>Formatting / Spacing</strong></p>\n<p>There should be spaces around operators, such as <code>n / 2</code> or <code>3 * n</code>. Some IDEs can handle this for you through an auto-formatting option (e.g. <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd> for PyCharm on Windows).</p>\n<hr />\n<p><strong>Type hints</strong></p>\n<p>It's useful to provide type hints for arguments and function return values. This increases readability and allows for easier and better error checking. Refer to <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP484</a> for more information.</p>\n<pre><code>def collatz(n: int, counter: int) -&gt; int:\n # function body here\n</code></pre>\n<hr />\n<p><strong>Return values</strong></p>\n<p>Adding these type hints will help us identify the first improvement. As the Collatz sequence only contains integers, our <code>collatz</code> function should only take an integer as the <code>n</code> argument. <code>collatz(n / 2, counter + 1)</code> passes a float, so to keep it consistent we should probably convert it to an <code>int</code> before passing it: <code>collatz(int(n / 2), counter + 1)</code>. Even better, we can use the floor division operator <code>//</code>: <code>collatz(n // 2, counter + 1)</code></p>\n<p>Please note that you do not need to convert the function output to an <code>int</code>, as it will only ever return an <code>int</code> value.</p>\n<hr />\n<p><strong>Default arguments</strong></p>\n<p>There are multiple approaches to improving the handling of the <code>counter</code> argument, which rubs you the wrong way. This is good intuition on your part. With default arguments, Python offers one really concise option:</p>\n<pre><code>def collatz(n: int, counter: int = 0) -&gt; int:\n if n == 1:\n return counter\n elif n % 2 == 0:\n return collatz(n // 2, counter + 1)\n else:\n return collatz(3 * n + 1, counter + 1)\n</code></pre>\n<p>As you can see, the only addition we need to implement is <code>counter = 0</code>, which makes <code>0</code> the default argument for <code>counter</code>. This means that <code>counter</code> will be set to <code>0</code> if the argument is not provided by the caller.</p>\n<p>You can now simply call</p>\n<pre><code>print(collatz(15))\n</code></pre>\n<p>More on <a href=\"https://www.geeksforgeeks.org/default-arguments-in-python/\" rel=\"nofollow noreferrer\">default arguments in Python</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T07:58:43.470", "Id": "526295", "Score": "5", "body": "I would also recommend using `cache` from `itertools`, it will dramatically speed up the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T08:01:37.863", "Id": "526296", "Score": "0", "body": "@N3buchadnezzar I agree, good recommendation!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T08:01:59.287", "Id": "526297", "Score": "2", "body": "The type hints are certainly useful, and I definitely miss it coming from C. Do Python programmers regularly use them? Or is it something that goes away when you're already comfortable using Python?\nThe `counter` variable initialization was my problem; I could not find where it should be put. And so my solution was just to pass it to the function. I know that's not how it should be because I admit my Python knowledge is still very limited. \nYou provided me with easy-to-understand explanations. Thank you :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T08:34:23.537", "Id": "526302", "Score": "1", "body": "Glad to help! I'd say type hints are useful at any level of Python proficiency, as they allow for easier debugging and maintainability. They do probably provide the biggest benefit to beginner and intermediate Pythonistas though =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T08:48:46.573", "Id": "526303", "Score": "0", "body": "Btw why do we care about keeping track of `counter`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T10:12:03.417", "Id": "526306", "Score": "0", "body": "@N3buchadnezzar the goal of the code is to print the length of the collatz sequence. Could you elaborate as to why you asked? I have a beginner understanding of Python, and just programming in general (never touched a DSA topic before)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T21:36:30.720", "Id": "526344", "Score": "0", "body": "@N3buchadnezzar: Because testing the Collatz conjecture isn't just about infinite loop or not; counting the iterations is interesting. https://en.wikipedia.org/wiki/Collatz_conjecture#Empirical_data / https://en.wikipedia.org/wiki/Collatz_conjecture#Visualizations. (Besides visualizations, results may provide some insight into algorithmic optimizations to short-circuit the basic steps; see various answers on [Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?](https://stackoverflow.com/q/40354978) that focus on the algorithm instead of asm)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T21:52:41.800", "Id": "526345", "Score": "0", "body": "(Although I think you already know that based on your comments on your own answer; maybe I misunderstood what you were asking. Maybe you meant why we want a 2nd arg at all, when your answer shows a way to do it with non-tail calls where the eventual count just ends up in a return value. That's good too, but defeats tail-call optimization for languages / implementations that can do that.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T22:24:18.643", "Id": "526346", "Score": "0", "body": "Unless I'm mistaken Python doesn't actually have function overloading, usually it's faked with default arguments or some `*args` trickery. Maybe make that more clear?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T00:30:55.857", "Id": "526348", "Score": "0", "body": "@PeterCordes your second comment hit the nail right on the head about the meaning of my comment. I wrote it in the middle of an lecture, so I had to keep it brief. I elaborated as you said when I got home in my answer =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T09:28:33.803", "Id": "526365", "Score": "0", "body": "@ToddSewell Thanks for your comment, I cleared it up. That's what happens when you edit previously working code while writing the answer without re-running it." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T07:36:01.633", "Id": "266410", "ParentId": "266408", "Score": "9" } } ]
<p>I need to manipulate data found in multiple data files (~100,000 files). One single data file has ~60,000 rows and looks something like this:</p> <pre><code> ITEM: TIMESTEP 300 ITEM: NUMBER OF ATOMS 64000 ITEM: BOX BOUNDS xy xz yz pp pp pp 7.1651861306114756e+02 7.6548138693885244e+02 0.0000000000000000e+00 7.1701550555416179e+02 7.6498449444583821e+02 0.0000000000000000e+00 7.1700670287454318e+02 7.6499329712545682e+02 0.0000000000000000e+00 ITEM: ATOMS id mol mass xu yu zu 1 1 1 731.836 714.006 689.252 5 1 1 714.228 705.453 732.638 6 2 1 736.756 704.069 693.386 10 2 1 744.066 716.174 708.793 11 3 1 715.253 679.036 717.336 . . . . . . . . . . . . . . . . . . </code></pre> <p>I need to extract the x coordinate of the first 20,000 lines and group it together with the x coordinates found in the other data files.</p> <p>Here is the working code:</p> <pre><code>import numpy as np import glob import natsort import pandas as pd data = [] filenames = natsort.natsorted(glob.glob(&quot;CoordTestCode/ParticleCoordU*&quot;)) for f in filenames: files = pd.read_csv(f,delimiter=' ', dtype=float, skiprows=8,usecols=[3]).values data.append(files) lines = 20000 x_pos = np.zeros((len(data),lines)) for i in range(0,len(data)): for j in range(0,lines): x_pos[i][j]= data[i][j] np.savetxt('x_position.txt',x_pos,delimiter=' ') </code></pre> <p>The problem is of course the time it will take to do this for all the 100,000 files. I was able to significantly reduce the time by switching from <code>np.loadtxt</code> to <code>pandas.read_csv</code>, however is still too inefficient. Is there a better approach to this? I read that maybe using I/O streams can reduce the time but I am not familiar with that procedure. Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T12:06:44.313", "Id": "526448", "Score": "0", "body": "what do you mean by too inefficient? How long does it take and how much time do you have? How close to the hardware (read limit of your harddrive) are you?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-26T19:27:10.023", "Id": "266431", "Score": "6", "Tags": [ "python", "performance", "python-3.x", "io" ], "Title": "Reading 100,000 data files in Python" }
266431
max_votes
[ { "body": "<p>Avoid iterating over rows of a dataframe or array. Avoid copying data.</p>\n<p>Process one file at a time...read then write data for each file. There is no need to build a list of all the data.</p>\n<p>Perhaps use <code>np.loadtxt()</code> instead of <code>pd.read_csv()</code>. Use <code>skip</code> and <code>max_rows</code> to limit the amount of data read and parsed by <code>np.loadtxt()</code>. Use <code>unpack=True</code> and <code>ndmin=2</code> so it returns a row instead of a column. Then <code>np.savetxt()</code> will append a <code>'\\n'</code> after each row.</p>\n<p>Something like this (untested):</p>\n<pre><code>import numpy as np\nimport glob\nimport natsort\n\nwith open('x_position.txt', 'a') as outfile:\n\n filenames = natsort.natsorted(glob.glob(&quot;CoordTestCode/ParticleCoordU*&quot;))\n\n for f in filenames:\n data = np.loadtxt(f, skiprows=9, max_rows=20000, usecols=3, unpack=True, ndmin=2)\n\n np.savetxt(outfile, data, fmt=&quot;%7.3f&quot;)\n</code></pre>\n<p>Presuming the data is stored on hard drives, the average rotational latency for a 7200 rpm hard drive is 4.17ms. 100k files at 4.17ms each is about 417 seconds = almost 7 minutes just to seek to the first sector of all those files. Perhaps using <a href=\"https://docs.python.org/3.9/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor\" rel=\"noreferrer\"><code>concurrent.futures.ThreadPoolExecutor</code></a> would let you overlap those accesses and cut down that 7 minutes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T15:25:31.670", "Id": "526380", "Score": "0", "body": "Thank you so much for the useful reply! However, I read in multiple forums that pandas is way faster than numpy.loadtxt due to the fact that the padas library is built in C. Any specific reason you recommend for switching back to np.loadtxt ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T15:46:39.147", "Id": "526384", "Score": "0", "body": "How would ThreadPoolExecutor get around IO latency? I think it should only help with CPU-bound jobs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T16:20:09.923", "Id": "526387", "Score": "0", "body": "@AlessandroPerego Mostly, I was trying to avoid the need tp copy the data from a DataFrame to an ndarray. Try it both ways and see which is faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T16:30:03.930", "Id": "526388", "Score": "1", "body": "@Seb The idea is that when one thread is waiting for IO, another thread can do some non-IO processing. For example, when one thread is waiting for the hard drive to return the next chunk of data, another thread can be parsing a chunk of data it read from a different file. Generally, use threads for IO-bound jobs and processes for CPU-bound jobs, but it depends on the actual workload. Try threads and processes and see which is faster. Another possibility is async using something like the `aiofile` library, but I haven't used it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T01:35:28.813", "Id": "266437", "ParentId": "266431", "Score": "10" } } ]
<p>I want to reduce time complexity of my code that solves the following problem.</p> <blockquote> <p>The program receives a positive distance d followed by a sequence of n events: An event can be either that a person appeared at some position, or that a person disappeared from some position. After each event, your program should output &quot;red&quot; if there are currently at least two persons at distance exactly d, and &quot;yellow&quot; otherwise. Note that initially (before the first event) all positions are empty. The events are given as a 2D array <code>event[0..n-1][0..1]</code>, where <code>event[i][0]</code> is &quot;1&quot; if a person appeared at position <code>event[i][1]</code> (on the x-axis), and &quot;-1&quot; if a person disappeared from that position. The output is an array <code>light[0..n-1]</code> of strings, where <code>light[i]</code> is the color directly after <code>event[i]</code>.</p> </blockquote> <p>I used the following code to solve this problem.</p> <pre><code>def cal_dis(d,pairs): found = False for i in range(0, len(pairs)-1): if(pairs[i+1]- pairs[i]) == d: found = True break return &quot;red&quot; if found else &quot;yellow&quot; def tracker(n,d,event): ret = [&quot;&quot;] * n pairs = [] for i in range(0,n): if event[i][0] == 1: pairs.append(event[i][1]) ret[i]= cal_dis(d,sorted(pairs)) else: pairs.remove(event[i][1]) ret[i]= cal_dis(d,sorted(pairs)) return ret </code></pre> <h2>Sample Input</h2> <blockquote> <p>first row: n d</p> <p>next n rows: two integers; the first one is either -1 or 1, the second one is nonnegative (these n rows correspond to the array &quot;event&quot;)</p> </blockquote> <pre><code>7 4 1 2 1 10 1 6 -1 2 -1 6 1 9 1 14 </code></pre> <h2>Sample Output</h2> <blockquote> <p>n rows each consisting of either the string &quot;red&quot; or &quot;yellow&quot;.</p> </blockquote> <pre><code>yellow yellow red red yellow yellow red </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T09:20:44.543", "Id": "526439", "Score": "1", "body": "In one place the input is called a two-dimensional array, and later it seems to be a file-like. Are the input and output stdin/stdout, or actually in-memory lists?" } ]
{ "AcceptedAnswerId": "266506", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-27T19:44:55.643", "Id": "266456", "Score": "1", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Encode event results as colors" }
266456
accepted_answer
[ { "body": "<p>For a faster algorithm, update a count of neighboring pairs at distance D as you go.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict\n\ndef num_at_distance(d, pairs):\n # Keep track of whether each position is occupied or not.\n # Accepts a distance and a number of positions to update. Each position is a 2-tuple of:\n # - -1 for not-occupied or 1 for occupied\n # - A position which changed.\n # Returns [yellow, yellow, red...] as a generator\n\n # 'occupied' maps a position to whether it's occupied.\n # Everything is unoccupied to start (False).\n # For slightly faster performance you could switch to an array.\n occupied = defaultdict(bool)\n num_at_distance_d = 0\n for now_occupied, position in pairs:\n # A is the position D to the left of the update\n # i is the updated position\n # B is the position D to the right of the update\n a, i, b = position-d, position, position+d\n now_occupied = bool(now_occupied==1)\n\n if occupied[i] != now_occupied:\n occupied[i] = now_occupied\n if occupied[i]:\n # Use the fact that python's True and False are 1 and 0 for some math\n num_at_distance_d += occupied[a] + occupied[b]\n else:\n num_at_distance_d -= occupied[a] + occupied[b]\n if num_at_distance_d == 0:\n yield &quot;yellow&quot;\n else:\n yield &quot;red&quot;\n\nif __name__=='__main__':\n input = 4, [(1,2), (1,10), (1,6), (-1, 2), (-1, 6), (1, 9), (1,4)]\n output = list(num_at_distance(*input))\n print(output)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T23:15:52.590", "Id": "526549", "Score": "0", "body": "Works perfectly!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-29T20:58:09.923", "Id": "266506", "ParentId": "266456", "Score": "1" } } ]
<p>It's a dice game between 2 people using tricky dice. For example,three dice [[1, 1, 4, 6, 7, 8], [2, 2, 2, 6, 7, 7], [3, 3, 3, 5, 5, 8]].</p> <p>The code will decide, in order to win, who chooses the dice first and which die to play. Say if you choose a die first, return the index of the die. Say if you decide to be the second one to choose a die, then specify for each die that your opponent may take, and the die that you would take in return.</p> <p>The code works but please tell me what you think or how to improve it!</p> <pre><code>from itertools import product def count_wins(dice1, dice2): assert len(dice1) == 6 and len(dice2) == 6 dice1_wins, dice2_wins = 0, 0 for p in product(dice1,dice2): if p[0]&gt;p[1]: dice1_wins += 1 elif p[0]&lt;p[1]: dice2_wins += 1 return (dice1_wins, dice2_wins) def find_the_best_dice(dices): assert all(len(dice) == 6 for dice in dices) adj=[[]for _ in range(len(dices))] for i in range(len(dices)-1): for j in range(i+1,len(dices)): a,b=count_wins(dices[i],dices[j]) print('ij',i,j,'ab',a,b) if a&lt;b: adj[i].append(j) elif a&gt;b: adj[j].append(i) else: adj[j].append(i) adj[i].append(j) ans=-1 for i in range(len(adj)): if len(adj[i])==0: ans=i return ans,adj def compute_strategy(dices): assert all(len(dice) == 6 for dice in dices) ans,adj=find_the_best_dice(dices) print(ans,adj) strategy = dict() strategy[&quot;choose_first&quot;] = True strategy[&quot;first_dice&quot;] = 0 if ans!=-1: strategy[&quot;first_dice&quot;] = ans else: strategy.pop(&quot;first_dice&quot;) strategy[&quot;choose_first&quot;] = False for i in range(len(dices)): for k in adj[i]: a,b=count_wins(dices[i],dices[k]) if a!=b: strategy[i]=k break return strategy </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T08:41:41.360", "Id": "526437", "Score": "1", "body": "The plural of \"die\" is \"dice\", and \"dices\" is not a word (yes, English is ridiculous)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T11:23:08.083", "Id": "526445", "Score": "0", "body": "Thanks I didn't know!!" } ]
{ "AcceptedAnswerId": "266468", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T05:00:00.873", "Id": "266465", "Score": "3", "Tags": [ "python", "dice" ], "Title": "Tricky dice game in Python" }
266465
accepted_answer
[ { "body": "<h3>Variable names</h3>\n<p>Some names are not clear enough. What <code>p</code> means, a pair? You don't need a pair:</p>\n<p><code>for p in product(dice1,dice2):</code> =&gt; <code>for side1, side2 in product(dice1,dice2):</code></p>\n<p><code>a,b=count_wins(dices[i],dices[j])</code> =&gt; <code>wins1, wins2 = count_wins(dices[i],dices[j])</code></p>\n<p>What 'adj' means? &quot;Adjacent&quot;? Maybe it should be &quot;wins&quot; or something like this. Make the code readable.</p>\n<h3>Type hints</h3>\n<p>Use them.</p>\n<h3>Indents are important not only in the beginning</h3>\n<p>Put spaces at least right to commas and on the both sides of operators - or at least do it consistently. Sometimes you do, sometimes you don't. That irritating.</p>\n<h3>Use Python features more intensively</h3>\n<pre><code>assert len(dice1) == 6 == len(dice2) #chain compare\n....\nadj=[[] for _ in dices] #you don't need range(len()) if you don't need a number\n....\nfor i, wins in enumerate(adj): #&quot;enumerate&quot; generates index-value pairs\n if not wins: #&quot;len(...) == 0&quot; is just &quot;not ...&quot;\n ans = i\n</code></pre>\n<p>You can make <code>count_wins</code> function much shorter and readable, counting only wins, not losses. This will make you call it twice, but <span class=\"math-container\">\\$O(2n)==2O(n)==O(n)\\$</span>, and <span class=\"math-container\">\\$n\\$</span> is 6, so you lose nothing.</p>\n<pre><code>def count_wins(dice1, dice2):\n assert len(dice1) == 6 and len(dice2) == 6\n return sum(1 for side1, side2 in product(dice1,dice2) if side1&gt;side2)\n</code></pre>\n<p>Or you can do this twice inside <code>count_wins</code> - both ways.</p>\n<h3>Unnecessary and insufficient <code>assert</code>s</h3>\n<p>This code looks like there's only one entry point, at <code>compute_strategy</code>. So other functions probably shouldn't check for list sizes. On the other hand, you don't check many other things like type of input - is it a list of lists of integers? Can there be negative values? There's nothing wrong in extra checking, but if you are validating data - validate it, not just check one assertion several times.</p>\n<p>You can make it a class to make sure all inputs would go through an <code>__init__</code> method.</p>\n<h3>Remove debugging output before showing your code to others</h3>\n<p>I don't think <code>print</code>s belong here, though they could be very useful while debugging.</p>\n<h3>Optimization ideas</h3>\n<p>I don't think comparing 6-element lists needs an optimization, but you still can sort the sides and then bisect search the number of elements less than the other side. This will give you <span class=\"math-container\">\\$O(n*log(n))\\$</span> time instead of yours <span class=\"math-container\">\\$O(n^2)\\$</span> product. Once again - just FYI.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T06:31:48.060", "Id": "266468", "ParentId": "266465", "Score": "5" } } ]
<p>I found interesting the way <a href="https://docs.python-requests.org" rel="nofollow noreferrer">Python's requests</a> library does the <code>status_code</code> data structure initialization (see <a href="https://github.com/psf/requests/blob/aae78010e987a414c176bddbf474cd554505219c/requests/status_codes.py#L107" rel="nofollow noreferrer">code here</a>). I am reusing it in a hobby project, but instead of using just one configuration variable I want it to initialize a few of them, code below:</p> <pre><code>from .models import LookupDict # Copying Requests data structure and some refactor to data initialization network_types = LookupDict(name='network_types') _network_types = { 1: ('GSM',), 2: ('UMTS',), 3: ('LTE',) } def _fill(_globals_var, globals_var): for value, titles in _globals_var.items(): for title in titles: setattr(globals_var, title, value) def _init(): for _globals_var, globals_var in [ (_network_types, network_types) ]: _fill(_globals_var, globals_var) _init() </code></pre> <p>So far it's just defined <code>network_types</code> variable but it could initialize as many as you want with both functions <code>_init</code> and <code>_fill</code>.</p> <p><code>LookupDict</code> is pretty much the same as the <code>requests</code> implementation (see <a href="https://github.com/psf/requests/blob/aae78010e987a414c176bddbf474cd554505219c/requests/structures.py#L89" rel="nofollow noreferrer">code here</a>)</p> <p>Any comments would be very appreciated. Thanks in advance!</p>
[]
{ "AcceptedAnswerId": "266484", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T14:34:06.797", "Id": "266479", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Config Variables Initialization | Python" }
266479
accepted_answer
[ { "body": "<p>With no usage shown, no implementation for <code>LookupDict</code> shown and nothing other than your network type values, this is overdesigned and offers nothing beyond</p>\n<pre><code>class NetworkType(Enum):\n GSM = 1\n UMTS = 2\n LTE = 3\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T18:15:32.397", "Id": "526465", "Score": "0", "body": "I agree with you it is overdesigned if I won't use the purpose this was originally designed for by `requests`, but I just hate to write this, following your example: `NetworkType.GSM.value` every time I will use any of the config values" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T18:28:29.740", "Id": "526469", "Score": "0", "body": "Wouldn't it just be `NetworkType.GSM`? That seems pretty straightforward and readable. The value isn't important in enums, so if your use case is to actually use it, just omit the `(Enum)` from the class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T19:00:10.270", "Id": "526472", "Score": "0", "body": "I actually need the value, thanks for the last tip, I didn't think about it that way" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T21:37:48.083", "Id": "526480", "Score": "0", "body": "PS: LookupDict definition is in the last link" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-28T16:36:02.963", "Id": "266484", "ParentId": "266479", "Score": "3" } } ]
<p>This is my first non-trivial program in my Python. I am coming from a Java background and I might have messed up or ignored some conventions. I would like to hear feedback on my code.</p> <pre><code> import nltk import random file_name = input() file = open(file_name, &quot;r&quot;, encoding=&quot;utf-8&quot;) # nltk.trigrams returns a list of 3-tuples trigrams = list(nltk.trigrams(file.read().split())) file.close() model = {} for trigram in trigrams: head = trigram[0] + &quot; &quot; + trigram[1] tail = trigram[2] model.setdefault(head, {}) model[head].setdefault(tail, 0) model[head][tail] += 1 possible_starting_heads = [] sentence_ending_punctuation = (&quot;.&quot;, &quot;!&quot;, &quot;?&quot;) for key in model.keys(): if key[0].isupper() and not key.split(&quot; &quot;)[0].endswith(sentence_ending_punctuation): possible_starting_heads.append(key) # Generate 10 pseudo-sentences based on model for _ in range(10): tokens = [] # Chooses a random starting head from list head = random.choice(possible_starting_heads) # print(&quot;Head: &quot;, head) tokens.append(head) while True: possible_tails = list(model[head].keys()) weights = list(model[head].values()) # Randomly select elements from list taking their weights into account most_probable_tail = random.choices(possible_tails, weights, k=1)[0] # print(&quot;Most probable tail: &quot;, most_probable_tail) if most_probable_tail.endswith(sentence_ending_punctuation) and len(tokens) &gt;= 5: tokens.append(most_probable_tail) # print(&quot;Chosen tail and ending sentence: &quot;, most_probable_tail) break elif not most_probable_tail.endswith(sentence_ending_punctuation): tokens.append(most_probable_tail) # print(&quot;Chosen tail: &quot;, most_probable_tail) head = head.split(&quot; &quot;)[1] + &quot; &quot; + most_probable_tail elif most_probable_tail.endswith(sentence_ending_punctuation) and len(tokens) &lt; 5: # print(&quot;Ignoring tail: &quot;, most_probable_tail) tokens = [] head = random.choice(possible_starting_heads) tokens.append(head) pseudo_sentence = &quot; &quot;.join(tokens) print(pseudo_sentence) <span class="math-container">```</span> </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T09:32:48.960", "Id": "266521", "Score": "2", "Tags": [ "python", "beginner", "random", "natural-language-processing", "markov-chain" ], "Title": "Markov text generator program in Python" }
266521
max_votes
[ { "body": "<p>In the following, I assume that you use Python3 rather than Python2, though I can't say for sure that it makes a difference.</p>\n<p>First, when you parse your file, you could use a context manager:</p>\n<pre><code>file_name = input()\nwith open(file_name, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:\n # nltk.trigrams returns a list of 3-tuples\n trigrams = list(nltk.trigrams(file.read().split()))\n</code></pre>\n<p>That way, even if an exception is raised by the assignment to trigrams (in either of the 4 method calls), the file stream is properly closed.</p>\n<p>You could simplify your model generation using <code>defaultdict</code> from the <code>collections</code> package. Your way of doing it is actually wrong and I can't say for sure that this option is more pythonic but it might be interesting to know.</p>\n<pre><code>import collections\nmodel = collections.defaultdict(lambda : collections.defaultdict(int))\nfor trigram in trigrams:\n head = trigram[0] + &quot; &quot; + trigram[1]\n tail = trigram[2]\n model[head][tail] += 1\n</code></pre>\n<p>This does not change the behavior of your algorithm, it just feels a bit simpler to me.</p>\n<p>But you can do something more memory-efficient:</p>\n<pre><code>import collections\nmodel = collections.defaultdict(lambda : collections.defaultdict(int))\nfile_name = input()\nwith open(file_name, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:\n # nltk.trigrams returns a list of 3-tuples\n trigrams = nltk.trigrams(file.read().split())\n for trigram in trigrams:\n head = trigram[0] + &quot; &quot; + trigram[1]\n tail = trigram[2]\n model[head][tail] += 1\n</code></pre>\n<p>Since <code>nltk.trigrams</code> returns an iterator, and since you only use it once, you don't actually need to store it in a list (an operation that will take some time and memory to copy everything from the iterator into the list) before iterating over it. You could even completely remove the <code>trigrams</code> variable and directly do <code>for... in nltk.trigrams...</code>.</p>\n<p>Finally, in your <code>while</code> loop, your <code>most_probable_tail</code> is misnamed: it is not the most probable one, it is the one your algorithm randomly selected using a possibly non-uniform law. I would rather call it <code>candidate_tail</code>, or <code>selected_tail</code>, or, even better, simply <code>tail</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T19:28:04.600", "Id": "266534", "ParentId": "266521", "Score": "1" } } ]
<p>In python, I sometimes write a while statement like</p> <pre class="lang-py prettyprint-override"><code>i = 0 while &lt;condition that involves i&gt;: i += 1 </code></pre> <p>The goal is, of course, to check the number of time the condition is true. I was wondering if there's a more simple, pythonic way to do it ? something like <code>i = while &lt;condition that involves i&gt;</code>, maybe with the walrus operator ?</p> <p>Here's a more concrete example:</p> <pre class="lang-py prettyprint-override"><code>def get_word_num_with_character_index(string: str, index: int) -&gt; int: &quot;&quot;&quot; returns the number of the word containing a character, specified by an index :param string: the string to analyze :param index: the index of the character :return: the number of the word containing the specified character &quot;&quot;&quot; split_string = string.split(&quot; &quot;) i = 0 while len(&quot; &quot;.join(split_string[:i])) &lt;= index: i += 1 return i - 1 print(get_word_num_with_character_index(&quot;jean de la fontaine&quot;, 8)) # prints 2, the index of the word containing the 8th character </code></pre> <p>How to simplify it ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T11:07:59.620", "Id": "526611", "Score": "0", "body": "You *can* use the walrus operator here, but I don't think you should: `i = -1`, `while len(\" \".join(split_string[:(i := i + 1)])) <= index: pass`. It's neither simpler nor clearer, it just moves even more logic into the condition without saving a line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T11:09:07.393", "Id": "526612", "Score": "0", "body": "Just to confirm, you're not looking into using enumerate (returns a counter as part of a `for` loop) or using slicing, such as `\"jean de la fontaine\"[8]` - correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T11:34:35.853", "Id": "526613", "Score": "0", "body": "thanks @riskypenguin, but as you pointed out, it only makes the code more complex, so it's not really what I'm looking for. I was just mentioning the walrus operator as a possible idea" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T11:44:42.330", "Id": "526614", "Score": "0", "body": "@C.Harley no, this is just an exemple but i'm trying to get the value of `i` in only one line, using the given condition, in order to get the number of the word in the string where the specified letter is (here, ̀\"jean de la fontaine\"[8]`). Sorry, I know it's not very clear but I don't see how I can explain the function more clearly than in its docstring" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T11:55:21.777", "Id": "526615", "Score": "1", "body": "`sum(1 for _ in itertools.takewhile(lambda i: PREDICATE, itertools.count()))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T17:49:22.427", "Id": "526642", "Score": "0", "body": "What about `return string[:index+1].count(\" \")` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T18:21:21.163", "Id": "526643", "Score": "0", "body": "thanks @SylvainD , but this is an example, and I'm looking for a global solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T19:53:24.117", "Id": "526652", "Score": "0", "body": "To be honest, I have the feeling that it works pretty well. I'd be interested in cases that are not handled properly." } ]
{ "AcceptedAnswerId": "266552", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T10:31:59.630", "Id": "266548", "Score": "2", "Tags": [ "python" ], "Title": "Counting how many times a condition is met in Python" }
266548
accepted_answer
[ { "body": "<p>You <em>could</em> replace your</p>\n<pre><code> i = 0\n while len(&quot; &quot;.join(split_string[:i])) &lt;= index:\n i += 1\n</code></pre>\n<p>with the oneliner using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"noreferrer\"><code>itertools.count</code></a></p>\n<pre><code> i = next(i for i in count() if len(&quot; &quot;.join(split_string[:i])) &gt; index)\n</code></pre>\n<p>or more readably spread over two physical lines (still just one <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#logical-lines\" rel=\"noreferrer\">logical line</a>:</p>\n<pre><code> i = next(i for i in count()\n if len(&quot; &quot;.join(split_string[:i])) &gt; index)\n</code></pre>\n<p>Both have advantages. The <code>while</code> solution has less clutter, the <code>next</code> solution makes it clearer that the whole point of the snippet is to compute <code>i</code>.</p>\n<p>If you already have a function for the condition, a good alternative would be <a href=\"https://docs.python.org/3/library/itertools.html#itertools.dropwhile\" rel=\"noreferrer\"><code>itertools.dropwhile</code></a>:</p>\n<pre><code> def condition(i):\n return len(&quot; &quot;.join(split_string[:i])) &lt;= index\n\n i = next(dropwhile(condition, count()))\n</code></pre>\n<p>As a oneliner, just to see how long/ugly it is in this case:</p>\n<pre><code> i = next(dropwhile(lambda i: len(&quot; &quot;.join(split_string[:i])) &lt;= index, count()))\n</code></pre>\n<p>So I'd likely really only use it if I had it as a function already.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T13:00:39.833", "Id": "526619", "Score": "0", "body": "Thanks a lot! `itertools.count()` is what I needed right now, but I keep `dropwhile()` in mind, it is also very relevant.\nI'm always open to other ideas.\nBut the word \"could\" in your message suggests that this is not a good idea. It's true that it's not very clear. So you recommend not to use it, but to leave the \"while\" as it is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T13:05:29.020", "Id": "526620", "Score": "0", "body": "I meant that as there's nothing wrong with the while loop. In this particular case, I'm undecided which I prefer, while or next. So you *could* switch, but you really don't have to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T13:09:20.023", "Id": "526621", "Score": "0", "body": "Ok, I will keep this in mind, thank you !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T13:12:14.153", "Id": "526622", "Score": "2", "body": "Put differently: Many Python beginners will write or see `while` loops and see experienced coders point out that they're horrible and that it should be done differently, and misunderstand that as \"while loops are *always* horrible\" rather than the meant \"this particular while loop is horrible\". Similar to the misconception \"to be pythonic, I must write this code as a oneliner\" :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-31T12:30:25.130", "Id": "266552", "ParentId": "266548", "Score": "6" } } ]
<p>Here's the problem.</p> <blockquote> <p>Return a copy of x, where the minimum value along each row has been set to 0.</p> <p>For example, if x is:</p> <pre><code>x = torch.tensor([[ [10, 20, 30], [ 2, 5, 1] ]]) </code></pre> <p>Then y = zero_row_min(x) should be:</p> <pre><code>torch.tensor([ [0, 20, 30], [2, 5, 0] ]) </code></pre> <p>Your implementation should use reduction and indexing operations; you should not use any explicit loops. The input tensor should not be modified.</p> <p>Inputs:</p> <ul> <li>x: Tensor of shape (M, N)</li> </ul> <p>Returns:</p> <ul> <li>y: Tensor of shape (M, N) that is a copy of x, except the minimum value along each row is replaced with 0.</li> </ul> </blockquote> <p>It has been hinted at that <a href="https://pytorch.org/docs/stable/generated/torch.clone.html#torch.clone" rel="nofollow noreferrer">clone</a> and <a href="https://pytorch.org/docs/stable/generated/torch.argmin.html#torch.argmin" rel="nofollow noreferrer">argmin</a> should be used.</p> <p>I'm having trouble understanding how to do this without a loop and my current code below (although it gets the problem right) is crude. I'm looking for a better way to solve this problem.</p> <pre><code> x0 = torch.tensor([[10, 20, 30], [2, 5, 1]]) x1 = torch.tensor([[2, 5, 10, -1], [1, 3, 2, 4], [5, 6, 2, 10]]) func(x0) func(x1) def func(x): y = None # g = x.argmin(dim=1) g = x.min(dim=1)[1] if x.shape[0] == 2: x[0,:][g[0]] = 0 x[1,:][g[1]] = 0 elif x.shape[0] == 3: x[0,:][g[0]] = 0 x[1,:][g[1]] = 0 x[2,:][g[2]] = 0 y = x return y </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T16:21:35.987", "Id": "526703", "Score": "0", "body": "The idea should be `copy_of_array[argmin_indices] = 0`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T17:33:11.607", "Id": "526707", "Score": "0", "body": "Can you provide expected shape for each of your variables? e.g. `(1000, 2, 12)` or whatever." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T17:44:20.073", "Id": "526708", "Score": "1", "body": "@Reinderien Sure, `x0 = torch.tensor([[10, 20, 30], [2, 5, 1]])` and `x1 = torch.tensor([[2, 5, 10, -1], [1, 3, 2, 4], [5, 6, 2, 10]])`. I've added them to the original post for clarification as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T17:55:56.567", "Id": "526709", "Score": "0", "body": "@Andrew I believe that's similar to the way I went about solving it. It works, but I have to manually iterate over each row to mutate the min() value." } ]
{ "AcceptedAnswerId": "266602", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T15:47:59.910", "Id": "266597", "Score": "0", "Tags": [ "python", "pytorch" ], "Title": "Set min value of each row of a tensor to zero without using explicit loops" }
266597
accepted_answer
[ { "body": "<p>Not much of a code review, but this should work:</p>\n<pre><code>def zero_min(x):\n y = x.clone()\n y[torch.arange(x.shape[0]), torch.argmin(x, dim=1)] = 0\n return y\n</code></pre>\n<p>In each row, if the minimum is not unique, then only the occurrence with the smallest index will be zeroed out.</p>\n<p>To zero out all the occurrences, you could do something like the following:</p>\n<pre><code>def zero_em_all_min(x):\n y = x.clone()\n y[x == x.min(dim=1, keepdims=True).values] = 0\n return y\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T18:24:07.987", "Id": "526716", "Score": "0", "body": "Thanks, didn't think to use `torch.arange` to iterate through the rows. I'll ask on regular SE in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T18:26:02.620", "Id": "526717", "Score": "0", "body": "@Ryan I'm happy it could be answered, but perhaps that is indeed the better platform for a similar question!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T18:16:27.703", "Id": "266602", "ParentId": "266597", "Score": "0" } } ]
<p>This is the question I tried <a href="https://leetcode.com/problems/string-compression/" rel="nofollow noreferrer">Leetcode: String Compression</a></p> <blockquote> <p>Given an array of characters chars, compress it using the following algorithm:</p> <p>Begin with an empty string s. For each group of consecutive repeating characters in chars:</p> <p>If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.</p> <p>After you are done modifying the input array, return the new length of the array.</p> <p>You must write an algorithm that uses only constant extra space.</p> </blockquote> <p>I tried to solve this solution in <strong>O(n)</strong> time complexity. Even though I did it, it is a lot slower.</p> <pre><code> def compress(self, chars: List[str]) -&gt; int: i = 0 while i &lt; len(chars): count = 0 for char in chars[i:]: if char != chars[i]: break count += 1 if count != 1: list_appending = list(str(count)) chars[i+1:i+count] = list_appending i += 1 + len(list_appending) else: i += 1 return len(chars) </code></pre> <p>Please can you give the reason why my solution is not so fast?? Why is my O(n) solution for Leetcode (443) String Compression not optimal?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T16:57:34.453", "Id": "526705", "Score": "1", "body": "It is not \\$O(n)\\$. List slicing itself is linear in the length of the slice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T06:32:45.827", "Id": "527737", "Score": "0", "body": "Pardon me for that I didn't notice." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T15:48:26.747", "Id": "266598", "Score": "0", "Tags": [ "python", "time-limit-exceeded" ], "Title": "Leetcode (443) String Compression" }
266598
max_votes
[ { "body": "<p>It's not <span class=\"math-container\">\\$O(n)\\$</span> but <span class=\"math-container\">\\$O(n^2)\\$</span>, because:</p>\n<ul>\n<li><code>chars[i:]</code> takes <span class=\"math-container\">\\$O(n)\\$</span> time and space. You could instead move a second index <code>j</code> forwards until the last occurrence and then compute the length as <code>j - i + 1</code>.</li>\n<li><code>chars[i+1:i+count] = list_appending</code> takes <span class=\"math-container\">\\$O(n)\\$</span> time. Instead of replacing all <code>count</code> equal characters, better replace exactly as many as you need for the digits. Then the remaining characters don't get moved and it's <span class=\"math-container\">\\$O(1)\\$</span> (amortized).</li>\n</ul>\n<p>You shrink the list. I'd say you're not supposed to. If you were supposed to shrink the list, why would they want you to return the list length? I think you're supposed to write the compressed data into a prefix of the list and return where that compressed data ends. Like they requested in an <a href=\"https://leetcode.com/problems/remove-duplicates-from-sorted-array/\" rel=\"nofollow noreferrer\">earlier problem</a>.</p>\n<p>Converting <code>str(count)</code> to a list is unnecessary. And I'd find <code>digits</code> a more meaningful name than <code>list_appending</code>.</p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"nofollow noreferrer\">PEP 8</a> suggests to write <code>chars[i+1:i+count]</code> as <code>chars[i+1 : i+count]</code> (and I agree).</p>\n<p>This is essentially a job for <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>, here's a solution using that:</p>\n<pre><code> def compress(self, chars: List[str]) -&gt; int:\n def compress():\n for c, g in groupby(chars):\n yield c\n k = countOf(g, c)\n if k &gt; 1:\n yield from str(k)\n for i, chars[i] in enumerate(compress()):\n pass\n return i + 1\n</code></pre>\n<p>Just for fun a bad but also fast regex solution:</p>\n<pre><code> def compress(self, chars: List[str]) -&gt; int:\n chars[:] = re.sub(\n r'(.)\\1+',\n lambda m: m[1] + str(len(m[0])),\n ''.join(chars))\n return len(chars)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T06:30:00.883", "Id": "527736", "Score": "0", "body": "I really appreciate your efforts. And thanks for the information I would follow rule about clean coding too.\nBut still that code ran so slow only about beating 20% users.\nCan I know why??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T15:34:52.563", "Id": "527779", "Score": "0", "body": "It's not much slower than the faster ones, if at all. Look at the time distribution graph. And LeetCode's timing is unstable. How often did you submit it, and what were the individual results?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T22:00:54.627", "Id": "266610", "ParentId": "266598", "Score": "1" } } ]
<p>Note: this is not the solution for the &quot;Character Picture Grid&quot; problem from Automate the Boring Stuff. Instead, this is an expansion of that problem simply for the sake of understanding nested loops, lists within lists, and iterating through values in order to print a picture on the screen.</p> <p>Thanks to anyone who takes the time to review this. Should I comment more throughout my code so that it's easier to read? Are there ways to shorten this program so that it could run faster? I'm still quite new to programming.</p> <pre><code># This is an expanded version of the Character Picture Grid # problem from Al Sweigart's book, Automate the Boring Stuff With Python. # This function takes in user input to determine what direction to print # the arrow. rightArrow = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] def printArrow(list): rowLength = len(list[0]) # length of x plane coordinates columnLength = len(list) # length of y plane coordinates print('Welcome to Arrow Pointer v1.0!') while True: #main program loop print('\n\nType in one of the following:\n\nup, down, left, right, or end to exit the program.') #user determines direction of arrow to be printed userInput = input() if userInput.lower() == 'right': for i in range(columnLength): for j in range(rowLength): #first loop iterates through main list #nested loop iterates through inner list elements print(list[i][j] + ' ', end='') print('\n') if userInput.lower() == 'left': for i in range(columnLength): for j in range(rowLength - 1, -1, -1): #iterate backwards to print arrow in opposite direction print(list[i][j] + ' ', end='') print('\n') if userInput.lower() == 'down': for i in range(rowLength): for j in range(columnLength): print(list[j][i] + ' ', end='') print('\n') if userInput.lower() == 'up': for i in range(rowLength-1, -1, -1): for j in range(columnLength-1, -1, -1): print(list[j][i] + ' ', end='') print('\n') if userInput.lower() == 'end': quit() printArrow(rightArrow) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T04:14:48.490", "Id": "527824", "Score": "0", "body": "https://codereview.stackexchange.com/a/254846/25834 for reference" } ]
{ "AcceptedAnswerId": "267676", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-03T21:20:10.730", "Id": "267666", "Score": "1", "Tags": [ "python", "performance", "beginner" ], "Title": "Expanding on a problem from Automate the Boring Stuff" }
267666
accepted_answer
[ { "body": "<ul>\n<li>Let's start with the basics. Always use if <code>__name__ == &quot;__main__&quot;: printArrow(rightArrow)</code> instead of directly calling your function (<code>printArrow(rightArrow)</code>) to avoid running it if importing the function in the future from another module.</li>\n<li>A function called <code>printArrow</code> should print an arrow, not ask a user for input, print an arrow, and control the flow of the program. Divide it into def print_arrow(list, direction), main(), etc.</li>\n<li>Instead of using <code>quit()</code> which controls the global execution flow, you can use a plain <code>return</code> when inside a function. Cleaner and follows SRP.</li>\n<li>Naming! In python we don't usually use camelCase for functions; use instead: print_arrow. Same for variables like <code>rowLength</code> -&gt; <code>row_length</code>.</li>\n<li>Pass your code through black or similar to have it nicely formatted (black.vercel.app/), otherwise the small human &quot;errors&quot; show up :)</li>\n<li>Constants in Python, by convention, use all upper case and don't need to be passed into functions (the only exception when globals are generally acceptable). So use <code>rightArrow</code> -&gt; <code>RIGHT_ARROW</code> and <code>def printArrow(list):</code> -&gt; <code>def printArrow():</code>.</li>\n<li>Use comments for the important stuff (the one which I can't trivially deduce from the code itself). What is this arbitrary amount of spaces? <code>' '</code>? Put it into a constant and comment why that many if it has a meaning. E.g., <code>SEPARATOR = ' '</code>.</li>\n<li>There is some code repetition, can't you put this into a function <code>def _print_arrow_auxiliary(x_start: int, x_end: int, x_step: int, y_start: int, y_end: int, y_step: int) -&gt; None:</code>?</li>\n</ul>\n<pre><code>for i in range(rowLength-1, -1, -1):\n for j in range(columnLength-1, -1, -1):\n print(list[j][i] + ' ', end='')\n print('\\n')\n</code></pre>\n<ul>\n<li>It is a matter of taste, but type-hinting your functions does give you many advantages (self-explanatory code, better IDE highlights and suggestions, etc.)...\n<code>def printArrow(list):</code> -&gt; <code>def printArrow(list: List[List[str]]) -&gt; None:</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T17:00:56.310", "Id": "527847", "Score": "0", "body": "Thanks for this response. There are a few things I need clairification on. I don't understand the following line: __name__ == \"__main__\": printArrow(rightArrow). Also, your second point about separating the function into print_arrow(list, direction), main(), etc. What is the purpose of 'main()' in this context?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T17:34:51.690", "Id": "527851", "Score": "0", "body": "First question is answered [here](https://stackoverflow.com/questions/419163/what-does-if-name-main-do), this is a basic in Python, so I suggest you spend some time and make sure you get it! As for separation functions, in general we try to follow [SRP](https://en.wikipedia.org/wiki/Single-responsibility_principle), each function should only do one thing. So print_arrow should do only that, print the arrow, not have the main program loop or ask the user for input. It is a convention to have a function called main() which has the program main loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T21:43:43.953", "Id": "527862", "Score": "0", "body": "Thanks! Last question, how did you determine that I had constants in my code? I'm not aware of the difference between a constant and a variable in Python. I know in JavaScript, the declaration is either var, const, or let, but as far as I know, every variable in Python is a variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T22:22:19.890", "Id": "527865", "Score": "2", "body": "Well, yes. In Python there are no constants. That is, there is no way to enforce a variable is actually constant and never changes. However, us, as ✨responsible programmers✨ do use some variables which we intend to use as constants. If we want to show that a variable is intended to be use as a constant, in Python we use all uppercase like SOME_CONSTANT. In your case, e.g., rightArrow is used but never modified, so let's make it explicit by using the naming convention for constants!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T18:34:29.540", "Id": "532202", "Score": "0", "body": "If you have a moment and it's not too much trouble, would you be willing to take a look at the final product? The only problem I encountered was being unable to create a single function that prints the arrow in all four directions, so I created two functions, one for \"left right\" and one for \"up down\": https://github.com/ajoh504/Automate-The-Boring-Stuff-Exercises/blob/main/CH%204%20Lists/10_character_picture_grid2.py" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T08:06:17.277", "Id": "532233", "Score": "0", "body": "Maybe consider calling lower on user_input just once and storing it instead of repeating it. So: `user_input = input().lower()`. The rest seems fine!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T09:30:40.540", "Id": "267676", "ParentId": "267666", "Score": "2" } } ]
<p>I'm making a program that can add 2 terms that the user types.</p> <p>I think I've got identifying or evaluating the terms down. I used classes because I just recently learned it and I also heard it was good practice in order to make your programs shorter. But, when it comes to adding 2 terms together (which is the code under the <code>else</code> and <code>elif</code> statements) I tried using classes but I have no idea how that would work, so I just sort of brute forced it. Is there a shorter or otherwise better way to code the adding part? Surely there is, and I would appreciate it if someone could show me what to learn or focus on or pretty much just any good advice so that I can code it cleaner.</p> <pre><code>class TermEva: def __init__(self, Variable, Coefficient): self.Variable = Variable self.Coefficient = Coefficient self.ExVariable = Variable if self.Coefficient &lt; 0: self.ExVariable = &quot;-&quot; + self.Variable def SimTerm(self): return &quot;{}{}&quot;.format(self.Coefficient, self.Variable) def Expanded_Form(self): ExpandedForm = [] for n in range(abs(self.Coefficient)): ExpandedForm.append(self.ExVariable) return ExpandedForm Term1 = TermEva(input(&quot;Enter Variable 1: &quot;), int(input(&quot;Enter its Coefficient: &quot;))) Term2 = TermEva(input(&quot;Enter Variable 2: &quot;), int(input(&quot;Enter it's Coefficient: &quot;))) print(Term1.SimTerm()) print(Term2.SimTerm()) if Term1.Variable == Term2.Variable: VariableSum = Term1.Variable CoefficientSum = Term1.Coefficient + Term2.Coefficient ExVariableSum = VariableSum if CoefficientSum &lt; 0: ExVariableSum = &quot;-&quot; + VariableSum ExpandedFormSum = [] for num in range(abs(CoefficientSum)): ExpandedFormSum.append(ExVariableSum) TermSum = str(CoefficientSum) + str(VariableSum) elif Term1.Variable != Term2.Variable: ExTerm1_Variable = Term1.Variable ExTerm2_Variable = Term2.Variable if Term1.Coefficient &lt; 0: ExTerm1_Variable = &quot;-&quot; + Term1.Variable if Term2.Coefficient &lt; 0: ExTerm2_Variable = &quot;-&quot; + Term2.Variable ExpandedFormSum = [] for num in range(abs(Term1.Coefficient)): ExpandedFormSum.append(ExTerm1_Variable) for num in range(abs(Term2.Coefficient)): ExpandedFormSum.append(ExTerm2_Variable) if Term2.Coefficient &lt; 0: TermSum =(Term1.SimTerm() + Term2.SimTerm()) elif Term2.Coefficient &gt;= 0: TermSum =(Term1.SimTerm() + &quot;+&quot; + Term2.SimTerm()) print(TermSum) </code></pre>
[]
{ "AcceptedAnswerId": "267722", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T02:52:13.250", "Id": "267715", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "mathematics" ], "Title": "Ask 2 terms from user and add them" }
267715
accepted_answer
[ { "body": "<p><strong>General</strong></p>\n<p>Attributes, variable names, function names and function arguments should be lowercase / <code>snake_case</code>.</p>\n<p>You should wrap your main procedure in a main function, as well as a <code>if __name__ == '__main__'</code> guard. <a href=\"https://stackoverflow.com/a/419185/9173379\">More info</a>.</p>\n<p>Documentation makes your code easier to read and understand. Use docstrings and comments to explain why and how your code is doing what it's doing.</p>\n<p>Type hints make your code easier to read and understand, use them. <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a> | <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">Python Docs</a></p>\n<hr />\n<p><strong><code>TermEva.__init__</code></strong></p>\n<pre><code>self.ex_variable = ex_variable\nif self.coefficient &lt; 0:\n self.ex_variable = &quot;-&quot; + self.variable\n</code></pre>\n<p>Depending on the value of <code>self.coefficient</code>, <code>self.ex_variable</code> will either be a number or a string. Sticking to the number representation seems more intuitive here:</p>\n<pre><code>self.ex_variable = ex_variable\nif self.coefficient &lt; 0:\n self.ex_variable = self.variable * -1\n</code></pre>\n<p>On closer inspection, your <code>main</code> functionality always passes strings to the constructor of <code>TermEva</code>. I don't think this is intended, as your implementation of <code>TermEva</code> implies the arguments are numbers. You should generally check user input for correctness and then convert it to the desired type.</p>\n<hr />\n<p><strong><code>TermEva.sim_term</code></strong></p>\n<p>f-strings are a great tool for string formatting:</p>\n<pre><code>def sim_term(self):\n return f&quot;{self.coefficient}{self.variable}&quot;\n</code></pre>\n<hr />\n<p><strong><code>TermEva.expanded_form</code></strong></p>\n<p>This pattern of list creation</p>\n<pre><code>expanded_form = []\nfor num in range(abs(self.Coefficient)):\n ExpandedForm.append(self.ExVariable)\n</code></pre>\n<p>can (and often should) be replaced by a more functional approach:</p>\n<ul>\n<li><code>return [self.ex_variable for _ in range(abs(self.coefficient))]</code></li>\n<li><code>return [self.ex_variable] * abs(self.coefficient)</code></li>\n</ul>\n<p>Note that it's convention to use <code>_</code> as a variable name for loop variables you don't actually use. This makes it immediately clear to the reader that the value of <code>num</code> is not needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T09:34:22.117", "Id": "267722", "ParentId": "267715", "Score": "2" } } ]
<p>I am trying to solve the <a href="https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem" rel="nofollow noreferrer">Climbing the leaderboard problem</a> on Hacker Rank. My code passes all the test cases except Test Cases 6 to 9, which I assume are using large data sets.</p> <p>I'm using binary search to find the optimal insertion point for each score and using the index as the rank. I know there are loads of solutions online but I want to pass the test cases with my own code.</p> <p>Original problem: <a href="https://i.stack.imgur.com/lOSCV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lOSCV.png" alt="enter image description here" /></a></p> <pre class="lang-py prettyprint-override"><code>def climbingLeaderboard(ranked, player): climb = [] ranked2 = sorted(set(ranked),reverse = True) for i in player: if i in ranked2: climb.append(ranked2.index(i)+1) elif i &gt; ranked2[0]: climb.append(1) ranked2.insert(0, i) elif i &lt; ranked2[-1]: climb.append(len(ranked2) + 1) ranked2.append(i) else: a = binary_search(ranked2, i, 0,len(ranked2)) climb.append(a+1) ranked2.insert(a, i) return climb def binary_search(arr, n, lo, hi): mid = int((hi+lo)/2) if lo &gt; hi: return lo elif arr[mid] &lt; n: return binary_search(arr, n, lo, mid -1) elif arr[mid] &gt; n: return binary_search(arr, n, mid + 1, hi) else: return mid </code></pre> <p>Where can I optimise my code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T20:22:03.440", "Id": "527946", "Score": "0", "body": "Welcome to Code Review! Please explain / summarize what the challenge task is, so that the question makes sense even if the link goes dead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T10:41:13.537", "Id": "527979", "Score": "0", "body": "Hi, @200_success I have inserted a screenshot of the original problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T11:38:57.077", "Id": "527982", "Score": "0", "body": "I have solved this optimisation, thread can be closed. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T17:25:36.270", "Id": "527999", "Score": "0", "body": "We don't delete questions on Code Review just because you have solved the challenge yourself. Rather, you should post an answer to your own question that explains your successful approach and your thought process, so that future readers can benefit from this post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T17:08:39.683", "Id": "528076", "Score": "1", "body": "I have posted a comment under Anab's proposals with a brief summary of how I solved it in the end." } ]
{ "AcceptedAnswerId": "267741", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T19:28:03.667", "Id": "267740", "Score": "0", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded", "binary-search" ], "Title": "Climbing the leaderboard (Hacker Rank) via binary search" }
267740
accepted_answer
[ { "body": "<p>I see three ways to improve your runtime. I have never done this problem so I can't guarantee that it will be enough to pass all the tests.</p>\n<h2>Sorted input</h2>\n<p>The leaderboard scores are sorted in decreasing order. Your duplicate-removal code converts a sorted list to a set to remove duplicates (O(n)), then converts it back to a list (O(n)), then sorts it (O(n*log(n)). You could use the fact that it is sorted: duplicates will always be side by side. You could do something like the following, for example:</p>\n<pre><code>prev = ranked[0]\nduplicateIndices = set()\nfor index, val in enumerate(ranked[1:], 1):\n if val == prev:\n duplicateIndices.add(index)\n prev = val\nranked2 = [x for i,x in enumerate(ranked) if i not in duplicateIndices]\n</code></pre>\n<p>This may not be the most efficient way to remove duplicate but it runs in O(n).</p>\n<h2>Sorted input 2</h2>\n<p><code>player</code> is sorted as well. That means that after each iteration, the player's rank is at most the previous one. This has two consequences:</p>\n<ol>\n<li>You don't need to add the player's score to <code>ranked2</code> (either two consecutive scores are equal, which is easy enough to detect without altering <code>ranked2</code>, or the second one is strictly better than the first and having inserted the first in <code>ranked2</code> will not change the insertion point of the second)</li>\n<li>The right boundary of your binary search is your previous insertion point.</li>\n</ol>\n<p>This will not change your asymptotical complexity but it should have an interesting effect on your runtime anyway.</p>\n<h2>Skipping the linear search</h2>\n<p>With a single line, your code goes from O(m*log(n)) to O(m*n). Since <code>ranked2</code> is a list, and Python does not know that it is sorted, <code>if i in ranked2</code> will iterate over the entire list searching for a match. This operation runs in O(n) and is repeated for each of the player's score. Besides, you have already handled the equality case in your binary search, so why bother?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T11:38:08.547", "Id": "527981", "Score": "0", "body": "Thanks @Anab I removed the linear search per iteration and made use of the fact that my binary search returns the index if it finds the value in the list. Passed all cases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T17:09:12.837", "Id": "527997", "Score": "0", "body": "Glad that it worked for you. Could you accept the answer if you're satisfied with it?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T19:55:36.573", "Id": "267741", "ParentId": "267740", "Score": "2" } } ]
<p>I made this small program which takes some inputs (emails) and after looking if they exist it looks for the respective id and delete it. It works (I use it with crontab) but seems redundant. I had several problems with split and decode function, mainly because decode gives me lists of strings spaced by a tab. I would like to optimize the code and get rid of all these <code>for</code> loops, because the code seems long and sloppy. Any tips?</p> <pre><code>bastards = [ &quot;team@mail.kamernet.nl&quot;, &quot;supportdesk@kamernet.nl&quot;, &quot;noreply@pararius.nl&quot;, ] with imaplib.IMAP4_SSL(host='imap.gmail.com',port=993) as imap: imap.login(email,password) imap.select('INBOX',readonly=False) listy = [] for bastard in bastards: resp_code, respy = imap.search(None, f'FROM {bastard}') respy = respy[0].decode().split() listy.append(respy) listy = [x for x in listy if x] for i in listy: for j in i: imap.store(j,'+FLAGS','\\Deleted') print('email_deleted') imap.expunge() imap.close() imap.logout() </code></pre>
[]
{ "AcceptedAnswerId": "267764", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T18:29:38.350", "Id": "267762", "Score": "1", "Tags": [ "python" ], "Title": "Cron email-deleter" }
267762
accepted_answer
[ { "body": "<p>The <code>listy</code> comprehension could be refactored into a generator:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def search_emails(imap, senders):\n for sender in senders:\n typ, data = imap.search(None, f'FROM {sender}')\n msg_nums = data[0].decode().split()\n \n # check for content here\n if msg_nums:\n yield msg_nums\n\n\nwith imaplib.IMAP4_SSL(host='imap.gmail.com', port=993) as imap:\n imap.login(email, password)\n imap.select('INBOX', readonly=False)\n\n # also, visually breaking up the program with newlines\n # makes it more readable\n for email in search_emails(imap, senders):\n for j in email:\n imap.store(j, '+FLAGS', '\\\\Deleted')\n print('email_deleted')\n</code></pre>\n<p>This evaluates lazily, so you don't have to keep all of your emails in a list that you filter out later. It filters them as you iterate over the generator.</p>\n<h1><code>for j in email</code></h1>\n<p>This inner loop doesn't need to be there, per the docs on <a href=\"https://docs.python.org/3/library/imaplib.html#imaplib.IMAP4.store\" rel=\"nofollow noreferrer\"><code>IMAP4.store</code></a>, it takes a set of messages, not one at a time:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ~snip~\n for emails in search_emails(imap, senders):\n imap.store(emails, '+FLAGS', '\\\\Deleted')\n print('emails_deleted')\n</code></pre>\n<p>The official docs also don't have the <code>decode</code> section when parsing the output from <code>IMAP4.search</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>typ, data = M.search(None, 'ALL')\n\nfor num in data[0].split(): # &lt;------ Here\n M.store(num, '+FLAGS', '\\\\Deleted')\n</code></pre>\n<p>I haven't used this library, so I won't speculate on why your snippet is different, but just a note.</p>\n<h1>Variable Names</h1>\n<p>Things like <code>for i in iterable</code> and <code>for j in iterable</code> usually imply indices. I'd change the names here to more accurately represent what they are, it makes the code more readable</p>\n<h1>Function Params</h1>\n<p>Add spaces in between your function parameters:</p>\n<pre class=\"lang-py prettyprint-override\"><code># go from this\nimap.login(email,password)\n\n# to this\nimap.login(email, password)\n</code></pre>\n<h1>Passwords</h1>\n<p>You can use the <code>getpass</code> library for a masked password prompt:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from getpass import getpass\n\npassword = getpass()\n</code></pre>\n<p>I'm not sure how you're currently implementing storing the password, since you haven't included it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T10:25:55.670", "Id": "528044", "Score": "0", "body": "incredible explanation" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T19:36:20.990", "Id": "267764", "ParentId": "267762", "Score": "1" } } ]
<p>Please critique my implementation of Quicksort in python 3.8:</p> <pre><code>import random from typing import List def quicksort(A: List[int], left: int, right: int): &quot;&quot;&quot; Sort the array in-place in the range [left, right( &quot;&quot;&quot; if left &gt;= right: return pivot_index = random.randint(left, right - 1) swap(A, left, pivot_index) pivot_new_index = partition(A, left, right) quicksort(A, left, pivot_new_index) quicksort(A, pivot_new_index + 1, right) def partition(A: List[int], left: int, right: int) -&gt; int: &quot;&quot;&quot; in-place partition around first item &quot;&quot;&quot; if left &gt;= right: return left pivot = A[left] # initialize i, j pointers j = left + 1 while j &lt; right and A[j] &lt;= pivot: j += 1 i = j # invariant : # A[left+1 ... i-1] &lt;= pivot # A[i ... j-1] &gt; pivot # A[j ... right( unexplored while j &lt; right: if A[j] &lt;= pivot: swap(A, i, j) i += 1 j += 1 swap(A, left, i - 1) return i - 1 def swap(A: List[int], i: int, j: int): A[i], A[j] = A[j], A[i] </code></pre> <p>I followed Tim Roughgarden's explanations in his MOOC on algorithms. But he assumes the keys are all distinct and says that having Quicksort work efficiently on many duplicated keys is trickier than it seems and point to Robert Sedgewick and Kevin Wayne book on algorithms. I checked it and the partition method looks indeed way different.</p> <p>My current code seems to work even with duplicated keys but I think if all the keys are the same, I will get a O(n²) complexity (partitioned arrays will be very unbalanced). How can I update my current code to address this issue?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:21:48.217", "Id": "528130", "Score": "0", "body": "(Please do *not* change in your code (after the first CR answer): when using round *and* square brackets for the notation of intervals, they are in standard orientation. I've seen mirrored ones when using (round) parentheses exclusively.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:23:33.887", "Id": "528131", "Score": "0", "body": "(*Dual pivot* is superior to *three way (<,=,>) partition*.)" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T09:07:41.443", "Id": "267782", "Score": "0", "Tags": [ "python", "python-3.x", "algorithm", "quick-sort" ], "Title": "Python Quicksort Implementation with duplicates" }
267782
max_votes
[ { "body": "<p>Performance problems with quicksort are due to one single partition getting almost all of the items, incurring repeated &quot;partition cost&quot;.<br />\nIn the extreme (undetected, if for sake of argument) case of <em>all equal keys</em>, the code presented (implementing <a href=\"https://en.m.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme\" rel=\"nofollow noreferrer\">Lomuto's partition scheme</a>) puts all items equal to pivot in the left partition, returning the index of the rightmost one, leading to quadratic time.<br />\nCareful implementations of Hoare partition move values equal to pivot to &quot;the other partition&quot;, resulting in a balanced split here.<br />\n(When implementing dual pivot, checking they differ seems prudent.)</p>\n<p>The minimally invasive change would seem to be to change the way values equal to pivot are handled - <em>either</em></p>\n<ul>\n<li>Keep a toggle indicating where to put the next one - <em>or</em></li>\n<li>Put the item in the partition currently smaller.\n<pre><code>if A[j] &lt; pivot or (\n A[j] == pivot and i-left &lt; j-i):\n</code></pre>\n</li>\n</ul>\n<hr />\n<ul>\n<li>Why restrict items to <code>int</code>?</li>\n<li>Most of the implementation looks minimalistic (down to function docstrings, only - without full-stops).<br />\nThe special handling of values not exceeding pivot before the main loop of <code>partition()</code> doesn't quite seem in line.</li>\n<li>While you can put pivot selection in <code>partition()</code> just as well as in <code>quicksort()</code>, you could put it in a function of its own to emphasize mutual independance.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-10T07:39:00.907", "Id": "268839", "ParentId": "267782", "Score": "2" } } ]
<p>Please critique my implementation of Quicksort in python 3.8:</p> <pre><code>import random from typing import List def quicksort(A: List[int], left: int, right: int): &quot;&quot;&quot; Sort the array in-place in the range [left, right( &quot;&quot;&quot; if left &gt;= right: return pivot_index = random.randint(left, right - 1) swap(A, left, pivot_index) pivot_new_index = partition(A, left, right) quicksort(A, left, pivot_new_index) quicksort(A, pivot_new_index + 1, right) def partition(A: List[int], left: int, right: int) -&gt; int: &quot;&quot;&quot; in-place partition around first item &quot;&quot;&quot; if left &gt;= right: return left pivot = A[left] # initialize i, j pointers j = left + 1 while j &lt; right and A[j] &lt;= pivot: j += 1 i = j # invariant : # A[left+1 ... i-1] &lt;= pivot # A[i ... j-1] &gt; pivot # A[j ... right( unexplored while j &lt; right: if A[j] &lt;= pivot: swap(A, i, j) i += 1 j += 1 swap(A, left, i - 1) return i - 1 def swap(A: List[int], i: int, j: int): A[i], A[j] = A[j], A[i] </code></pre> <p>I followed Tim Roughgarden's explanations in his MOOC on algorithms. But he assumes the keys are all distinct and says that having Quicksort work efficiently on many duplicated keys is trickier than it seems and point to Robert Sedgewick and Kevin Wayne book on algorithms. I checked it and the partition method looks indeed way different.</p> <p>My current code seems to work even with duplicated keys but I think if all the keys are the same, I will get a O(n²) complexity (partitioned arrays will be very unbalanced). How can I update my current code to address this issue?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:21:48.217", "Id": "528130", "Score": "0", "body": "(Please do *not* change in your code (after the first CR answer): when using round *and* square brackets for the notation of intervals, they are in standard orientation. I've seen mirrored ones when using (round) parentheses exclusively.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:23:33.887", "Id": "528131", "Score": "0", "body": "(*Dual pivot* is superior to *three way (<,=,>) partition*.)" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T09:07:41.443", "Id": "267782", "Score": "0", "Tags": [ "python", "python-3.x", "algorithm", "quick-sort" ], "Title": "Python Quicksort Implementation with duplicates" }
267782
max_votes
[ { "body": "<p>Performance problems with quicksort are due to one single partition getting almost all of the items, incurring repeated &quot;partition cost&quot;.<br />\nIn the extreme (undetected, if for sake of argument) case of <em>all equal keys</em>, the code presented (implementing <a href=\"https://en.m.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme\" rel=\"nofollow noreferrer\">Lomuto's partition scheme</a>) puts all items equal to pivot in the left partition, returning the index of the rightmost one, leading to quadratic time.<br />\nCareful implementations of Hoare partition move values equal to pivot to &quot;the other partition&quot;, resulting in a balanced split here.<br />\n(When implementing dual pivot, checking they differ seems prudent.)</p>\n<p>The minimally invasive change would seem to be to change the way values equal to pivot are handled - <em>either</em></p>\n<ul>\n<li>Keep a toggle indicating where to put the next one - <em>or</em></li>\n<li>Put the item in the partition currently smaller.\n<pre><code>if A[j] &lt; pivot or (\n A[j] == pivot and i-left &lt; j-i):\n</code></pre>\n</li>\n</ul>\n<hr />\n<ul>\n<li>Why restrict items to <code>int</code>?</li>\n<li>Most of the implementation looks minimalistic (down to function docstrings, only - without full-stops).<br />\nThe special handling of values not exceeding pivot before the main loop of <code>partition()</code> doesn't quite seem in line.</li>\n<li>While you can put pivot selection in <code>partition()</code> just as well as in <code>quicksort()</code>, you could put it in a function of its own to emphasize mutual independance.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-10T07:39:00.907", "Id": "268839", "ParentId": "267782", "Score": "2" } } ]
<pre><code>print(&quot;Welcome to the Sieve of Eratosthenes, where you can generate prime numbers from 1 to n : &quot;) n = int(input(&quot;Enter your n : &quot;)) y = [y for y in range(1,n) if y*y &lt; n] primes = [p for p in range(2,n+1)] length = len(primes) print(primes) for p in range(2,len(y)+2): for i in range(2,length+1): if(i%p == 0 and i != p ): if(i in primes): primes.remove(i) print(primes) &quot;&quot;&quot; 1.)A range //0 to 100 .x 2.)Multiples can be found using 1 to sqrt(n) .x 3.)Now eliminate all multiples. x &quot;&quot;&quot; </code></pre> <p>OUTPUT</p> <blockquote> <p>Enter your n : 20<br /> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]<br /> [1, 2, 3, 5, 7, 11, 13, 17, 19]</p> </blockquote> <p>So I did this by my own and also I need some suggestions on what can I do to improve the code and can you tell me how good it is?.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T09:24:26.363", "Id": "528235", "Score": "0", "body": "i've updated the code,could you recheck it again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T10:31:22.063", "Id": "528237", "Score": "1", "body": "This always returns that the last number is prime. E.g. n=125 or n=102 return 125 and 102 as prime respectively. No numbers that end in 2 or 5 are prime except 2 and 5 themselves." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T08:47:28.460", "Id": "267887", "Score": "0", "Tags": [ "python", "primes" ], "Title": "My prime sieve using Python" }
267887
max_votes
[ { "body": "<blockquote>\n<pre><code>print(&quot;Welcome to the Sieve of Eratosthenes, where you can generate prime numbers from 1 to n : &quot;)\n</code></pre>\n</blockquote>\n<p>This is not a <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a>. It is a prime sieve in the sense that it takes a list of numbers and removes (or sieves) out those that aren't prime. But it does not follow the algorithm of the Sieve of Eratosthenes.</p>\n<p>Here's what the Sieve of Eratosthenes looks like:</p>\n<pre><code>primes = [p for p in range(2, n + 1)]\n\nfor p in primes:\n if p &gt; n / p:\n break\n\n for i in range(p * p, n + 1, p):\n if i in primes:\n primes.remove(i)\n</code></pre>\n<p>This is not necessarily the optimal version (for example, it might be better to compare <code>p</code> to the square root of <code>n</code> rather than do the <code>n / p</code> each time; or it may be better to use a set rather than a list). Nor is it likely to be the most Pythonic. I don't do Python development, so you should not take anything I suggest as being Pythonic.</p>\n<p>Some things that this does that your version does not:</p>\n<ol>\n<li>It only works on numbers that are prime. The initial loop may look like it is iterating over the entire range. But it actually only iterates over the primes, because the non-primes have been removed before it reaches them (I tested and unlike PHP, Python iterates over the current version of the array, not a copy of the original). It starts with 2 and eliminates all the even numbers.</li>\n<li>It does no trial division. Instead, it uses the Eratosthenes method of taking multiples of the current prime.</li>\n</ol>\n<p>That piece about multiplying rather than dividing is what I would describe as the central principle of the Sieve of Eratosthenes algorithm. So when I say that your version is not a Sieve of Eratosthenes, I mean that it doesn't do that.</p>\n<p>Note: there is nothing wrong with implementing a different sieve. It's possible to write a better one (although I'm not convinced that this is better). The Sieve of Eratosthenes is notable for being relatively good as well as comprehensible with moderate effort. It's not the best performing sieve. I'm just saying that you shouldn't call your version a Sieve of Eratosthenes, as it isn't one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T06:56:47.653", "Id": "528268", "Score": "0", "body": "I like how your SoE code removes values from the list while you're iterating it. Setting a good example here :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T21:43:43.480", "Id": "267903", "ParentId": "267887", "Score": "2" } } ]
<p>I have been coding in Python for a number of years now. I've always felt that Matplotlib code takes up a lot more lines of code than it should. I could be wrong.</p> <p>I have the following function that plots a simple scatter plot graph with two additional solid lines. Is there any way for me to reduce the number of lines to achieve exactly the same outcome? I feel that my code is a little 'chunky'.</p> <p><code>dates</code> contains an array of DateTime values in the yyyy-mm-dd H-M-S format</p> <p><code>return_values</code> - array of floats</p> <p><code>main_label</code> - string</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates %matplotlib inline plt.style.use('ggplot') def plot_returns(dates, return_values, ewma_values, main_label): plt.figure(figsize=(15, 10)) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=31)) plt.scatter(dates, return_values, linestyle = '-', color='blue', s = 3, label = &quot;Daily Returns&quot;) plt.plot(dates, ewma_values, linestyle = '-', color='green', label = &quot;EWMA&quot;) plt.gcf().autofmt_xdate() plt.xlabel('Day', fontsize = 14) plt.ylabel('Return', fontsize = 14) plt.title(main_label, fontsize=14) plt.legend(loc='upper right', facecolor='white', edgecolor='black', framealpha=1, ncol=1, fontsize=12) plt.xlim(left = min(dates)) plt.show() dates = pd.date_range(start = '1/1/2018', end = '10/10/2018') return_values = np.random.random(len(dates)) ewma_values = 0.5 + np.random.random(len(dates))*0.1 plot_returns(dates, return_values, ewma_values, &quot;Example&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T17:32:28.477", "Id": "528290", "Score": "1", "body": "It might be a good idea to include a little more code so people can run an analysis in their IDE. They should be able to reproduce what you're seeing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T19:32:53.843", "Id": "528381", "Score": "0", "body": "Thanks. I've added more code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T22:55:29.280", "Id": "528397", "Score": "0", "body": "Thanks, that runs. So, each of your statements does something specific to get the graph to draw. I don't find it too verbose compared to the example page https://matplotlib.org/2.0.2/users/screenshots.html given that you're drawing two graphs (scatter and line) on one plot. Is there something specific you want to highlight?" } ]
{ "AcceptedAnswerId": "268005", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T12:41:42.690", "Id": "267917", "Score": "1", "Tags": [ "python", "matplotlib" ], "Title": "Plot a simple scatter plot graph with two additional solid lines" }
267917
accepted_answer
[ { "body": "<blockquote>\n<p>Is there any way for me to reduce the number of lines to achieve exactly the same outcome?</p>\n</blockquote>\n<p>should, in isolation, not be your overriding concern, and your code is about as minimally chunky as matplotlib will allow. Your current push - rather than to shed a line or two - should be to increase static testability, maintainability and structure. Said another way, this is not code golf, and not all short code is good code.</p>\n<p>To that end:</p>\n<ul>\n<li>Do not enforce a style in the global namespace - only call that from a routine in the application. What if someone else wants to import and reuse parts of your code?</li>\n<li>Add PEP484 type hints.</li>\n<li>Avoid calling <code>gca</code> and <code>gcf</code>. It's easy, and preferable, to have local references to your actual figure and axes upon creation, and to use methods bound to those specific objects instead of <code>plt</code>. Function calls via <code>plt</code> have more visual ambiguity, and need to infer the current figure and axes; being explicit is a better idea. On top of that, calls to <code>plt</code> are just wrappers to the bound instance methods anyway.</li>\n<li>Choose a consistent quote style. <code>black</code> prefers double quotes but I have a vendetta against <code>black</code> and personally prefer single quotes. It's up to you.</li>\n<li>Do not force a <code>show()</code> in the call to <code>plot_returns</code>, and return the generated <code>Figure</code> instead of <code>None</code>. This will improve reusability and testability.</li>\n<li>Do not use strings for internal date logic. Even if you had to use strings, prefer an unambiguous <code>YYYY-mm-dd</code> ISO format instead of yours.</li>\n<li><code>np.random.random</code> is <a href=\"https://numpy.org/doc/stable/reference/random/index.html\" rel=\"nofollow noreferrer\">deprecated</a>; use <code>default_rng()</code> instead.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from datetime import date\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.figure import Figure\n\n\ndef plot_returns(\n dates: pd.DatetimeIndex,\n return_values: np.ndarray,\n ewma_values: np.ndarray,\n main_label: str,\n) -&gt; Figure:\n fig, ax = plt.subplots(figsize=(15, 10))\n\n ax.scatter(dates, return_values, linestyle='-', color='blue', s=3, label='Daily Returns')\n ax.plot(dates, ewma_values, linestyle='-', color='green', label='EWMA')\n\n fig.autofmt_xdate()\n \n ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))\n ax.xaxis.set_major_locator(mdates.DayLocator(interval=31))\n ax.set_xlabel('Day', fontsize=14)\n ax.set_ylabel('Return', fontsize=14)\n ax.set_title(main_label, fontsize=14)\n ax.legend(loc='upper right', facecolor='white', edgecolor='black', framealpha=1, ncol=1, fontsize=12)\n ax.set_xlim(left=min(dates))\n\n return fig\n\n\ndef main() -&gt; None:\n dates = pd.date_range(start=date(2018, 1, 1), end=date(2018, 10, 10))\n rand = np.random.default_rng()\n return_values = rand.random(len(dates))\n ewma_values = rand.uniform(low=0.5, high=0.6, size=len(dates))\n\n plt.style.use('ggplot')\n plot_returns(dates, return_values, ewma_values, 'Example')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/0Hg8S.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0Hg8S.png\" alt=\"screenshot of matplotlib\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T16:20:48.307", "Id": "268005", "ParentId": "267917", "Score": "1" } } ]
<blockquote> <p>Given a file or directory, create an iterator that returns the non-empty words from the file or from all files <em>recursively</em> in the directory. Only process &quot;.txt&quot; files. Words are sequence of characters separated by whitespace.</p> </blockquote> <pre><code>class WordIterable: def __init__(self, path: str): root = Path(path) self._walker: Optional[Iterator[Path]] = None if root.is_dir(): self._walker = root.rglob(&quot;*.txt&quot;) elif root.suffix == &quot;.txt&quot;: self._walker = (p for p in [root]) self._open_next_file() self._read_next_line() def __iter__(self) -&gt; Iterator[str]: return self def __next__(self) -&gt; str: next_word = self._next_word() if not next_word: self._read_next_line() next_word = self._next_word() if not next_word: self._close_file() self._open_next_file() self._read_next_line() next_word = self._next_word() return next_word if WordIterable._is_not_blank(next_word) else next(self) def _next_word(self) -&gt; Optional[str]: return self._line.pop() if self._line else None def _read_next_line(self) -&gt; None: self._line = self._fp.readline().split()[::-1] def _open_next_file(self) -&gt; None: if self._walker: self._file: Path = next(self._walker, None) if self._file: self._fp = self._file.open(encoding=&quot;utf8&quot;) return raise StopIteration def _close_file(self) -&gt; None: self._fp.close() @staticmethod def _is_not_blank(s: str) -&gt; bool: return s and s != &quot;\n&quot; </code></pre> <p>This works but seems like a lot of code. Can we do better?</p> <p><strong>Edit:</strong></p> <blockquote> <p>What is a &quot;word&quot; and a &quot;non-empty word&quot;?</p> </blockquote> <p>Words are sequence of characters separated by whitespace.</p> <blockquote> <p>The question doesn't say to recursively processes a directory and it's sub-directories, but that's what the code appears to do.</p> </blockquote> <p>It does now.</p> <blockquote> <p>The code only does &quot;.txt&quot; files.</p> </blockquote> <p>Yes.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:38:24.923", "Id": "528328", "Score": "0", "body": "The question is vague and the code makes some assumptions that aren't in the question. For example, what is a \"word\" and a \"non-empty word\"? Just letters? What about numbers or punctuation? Also, the question doesn't say to recursively processes a directory and it's sub-directories, but that's what the code appears to do. Lastly, the question says to process all files in a directory, but the code only does \".txt\" files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:02:39.873", "Id": "528329", "Score": "0", "body": "@RootTwo This question was asked in an interview, and interview questions are sadly, but deliberately vague. I've added an edit for your follow up questions." } ]
{ "AcceptedAnswerId": "267946", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T03:35:41.043", "Id": "267941", "Score": "4", "Tags": [ "python", "io", "iterator" ], "Title": "Iterate through non-empty words from text files" }
267941
accepted_answer
[ { "body": "<p>The code seems overly complicated and complex for a relatively simple task.</p>\n<pre><code>from pathlib import Path\n\ndef words(file_or_path):\n path = Path(file_or_path)\n \n if path.is_dir():\n paths = path.rglob('*.txt')\n else:\n paths = (path, )\n \n for filepath in paths:\n yield from filepath.read_text().split()\n</code></pre>\n<p>The function can take a a directory name or a file name. For both cases, create an iterable, <code>paths</code>, of the files to be processed. This way, both cases can be handled by the same code.</p>\n<p>For each filepath in <code>paths</code> use <code>Path.read_text()</code> to open the file, read it in, close the file, and return the text that was read. <code>str.split()</code> drops leading and trailing whitespace and then splits the string on whitespace. <code>yield from ...</code> yields each word in turn.</p>\n<p>If you don't want to read an entire file in at once, replace the <code>yield from ...</code> with something like:</p>\n<pre><code> with filepath.open() as f:\n for line in f:\n yield from line.split()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T09:58:03.227", "Id": "528336", "Score": "0", "body": "This is great, but I’d like to take it one step further by reading one word at a time instead of the whole line. However, I’m wondering if that can somehow backfire, since reading one character at a time until a white space is encountered isn’t exactly efficient. I wish there was a `readword` function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T15:04:21.520", "Id": "528360", "Score": "0", "body": "The most commonly used python implementations will be based on C, its stdlib, and UNIX philosophy.\nThe IO there is build around lines and line-by-line processing. A `readword` function in python can be implemented very easily, but under the hood the implementation would read the line and discard everything except the word. You would not gain much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T17:27:31.420", "Id": "528374", "Score": "0", "body": "It would be totally possible, although definitely harder and less clean, to read the file in fixed-sized chunks instead of by line. And you would gain the ability to not crash if you come across a file with very long lines, e.g. a 32-gigabyte file without the `\\n` character. Although I suppose such a file would likely [exceed `{LINE_MAX}`](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html) (implementation-defined and only required to be >= 2048) and thus [wouldn't count as a \"text file\" according to the POSIX standard](https://unix.stackexchange.com/q/446237)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T19:40:30.650", "Id": "528383", "Score": "0", "body": "There's one issue with the `yield from` used here, it doesn't check for empty words, which is a requirement in the question. I changed it to `yield from filter(_is_not_blank, line.split())`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T19:59:32.170", "Id": "528385", "Score": "1", "body": "@AbhijitSarkar, `.split()` should already filter out the blanks. Do you have an example input that causes it to return an empty word?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T21:11:49.237", "Id": "528395", "Score": "0", "body": "@RootTwo You're right, I tested with a file containing a line with `\\n` only, a line with spaces and `\\n`, and `split` handled those cases just fine." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:30:43.830", "Id": "267946", "ParentId": "267941", "Score": "6" } } ]
<p>So I did my own take (I wrote my own algorithm) for generating prime numbers from <code>1 to 1000</code>.</p> <pre><code>lst = [y for y in range(1000)] for i in range(0,len(lst)): #i = 1 and i is traversal print(&quot;iterate - &quot; + str(i)) for j in range(i,0,-1): #divisor range print(j) if j != 1 and j &lt; lst[i] and lst[i] % j == 0: if j in lst: lst[i] = 0 break for k in range(len(lst)): if 0 in lst: lst.remove(0) if 1 in lst: lst.remove(1) print(lst) </code></pre> <p>My concerns are</p> <ul> <li>Is this code easy to read?</li> <li>Is this optimal (I don't think so)?</li> <li>What should I do for improving my code?</li> </ul> <p>OUTPUT</p> <blockquote> <p>2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,<br /> 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,<br /> 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,<br /> 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,<br /> 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,<br /> 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,<br /> 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,<br /> 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,<br /> 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,<br /> 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,<br /> 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997</p> </blockquote>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:04:20.983", "Id": "267944", "Score": "4", "Tags": [ "python", "algorithm", "primes" ], "Title": "My prime number generation program in Python" }
267944
max_votes
[ { "body": "<p>I am not a professional Python developer, so I will address only the performance issue: judging from you <code>for</code> loops structure, it seems that the running time of your implementation is <span class=\"math-container\">\\$\\Theta(n^2)\\$</span>, where <span class=\"math-container\">\\$n\\$</span> is the prime limit. However, you can do the same in <span class=\"math-container\">\\$O(n \\log n)\\$</span>, or even, <span class=\"math-container\">\\$O(n \\log \\log n)\\$</span> time. (See below.)</p>\n<pre><code>import math\nimport time\n\n\ndef op_sieve(limit):\n lst = [y for y in range(limit + 1)]\n for i in range(0, len(lst)): # i = 1 and i is traversal\n for j in range(i, 0, -1): # divisor range\n if j != 1 and j &lt; lst[i] and lst[i] % j == 0:\n if j in lst:\n lst[i] = 0\n break\n\n for k in range(len(lst)):\n if 0 in lst:\n lst.remove(0)\n if 1 in lst:\n lst.remove(1)\n return lst\n\n\ndef sieve(limit):\n s = [True for i in range(limit + 1)]\n s[0] = s[1] = False\n\n for i in range(4, limit + 1, 2):\n s[i] = False\n\n for i in range(3, math.floor(math.sqrt(limit)) + 1, 2):\n if s[i]:\n for m in range(2 * i, limit + 1, i):\n s[m] = False\n\n primes = []\n prime_candidate = 0\n for i in s:\n if i:\n primes.append(prime_candidate)\n prime_candidate += 1\n\n return primes\n\n\ndef sieve2(limit):\n s = [True for i in range(limit + 1)]\n s[0] = s[1] = False\n\n for i in range(2, math.floor(math.sqrt(limit)) + 1):\n if s[i]:\n for j in range(i * i, limit + 1, i):\n s[j] = False\n\n primes = []\n prime_candidate = 0\n for i in s:\n if i:\n primes.append(prime_candidate)\n prime_candidate += 1\n\n return primes\n\n\ndef millis():\n return round(time.time() * 1000)\n\n\nlimit = 5000\n\nstart = millis()\noriginal_sieve = op_sieve(limit)\nend = millis()\n\nprint(end - start)\n\nstart = millis()\nmy_sieve = sieve(limit)\nend = millis()\n\nprint(end - start)\n\nstart = millis()\nmy_sieve2 = sieve2(limit)\nend = millis()\n\nprint(end - start)\n\n#print(original_sieve)\n#print(my_sieve)\n#print(my_sieve2)\nprint(&quot;Agreed: &quot;, original_sieve == my_sieve and my_sieve == my_sieve2)\n</code></pre>\n<p>The output might be as follows:</p>\n<pre><code>7199\n2\n2\nAgreed: True\n</code></pre>\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T11:55:49.123", "Id": "267995", "ParentId": "267944", "Score": "2" } } ]
<p>So I did my own take (I wrote my own algorithm) for generating prime numbers from <code>1 to 1000</code>.</p> <pre><code>lst = [y for y in range(1000)] for i in range(0,len(lst)): #i = 1 and i is traversal print(&quot;iterate - &quot; + str(i)) for j in range(i,0,-1): #divisor range print(j) if j != 1 and j &lt; lst[i] and lst[i] % j == 0: if j in lst: lst[i] = 0 break for k in range(len(lst)): if 0 in lst: lst.remove(0) if 1 in lst: lst.remove(1) print(lst) </code></pre> <p>My concerns are</p> <ul> <li>Is this code easy to read?</li> <li>Is this optimal (I don't think so)?</li> <li>What should I do for improving my code?</li> </ul> <p>OUTPUT</p> <blockquote> <p>2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,<br /> 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,<br /> 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,<br /> 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,<br /> 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,<br /> 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,<br /> 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,<br /> 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,<br /> 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,<br /> 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,<br /> 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997</p> </blockquote>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:04:20.983", "Id": "267944", "Score": "4", "Tags": [ "python", "algorithm", "primes" ], "Title": "My prime number generation program in Python" }
267944
max_votes
[ { "body": "<p>I am not a professional Python developer, so I will address only the performance issue: judging from you <code>for</code> loops structure, it seems that the running time of your implementation is <span class=\"math-container\">\\$\\Theta(n^2)\\$</span>, where <span class=\"math-container\">\\$n\\$</span> is the prime limit. However, you can do the same in <span class=\"math-container\">\\$O(n \\log n)\\$</span>, or even, <span class=\"math-container\">\\$O(n \\log \\log n)\\$</span> time. (See below.)</p>\n<pre><code>import math\nimport time\n\n\ndef op_sieve(limit):\n lst = [y for y in range(limit + 1)]\n for i in range(0, len(lst)): # i = 1 and i is traversal\n for j in range(i, 0, -1): # divisor range\n if j != 1 and j &lt; lst[i] and lst[i] % j == 0:\n if j in lst:\n lst[i] = 0\n break\n\n for k in range(len(lst)):\n if 0 in lst:\n lst.remove(0)\n if 1 in lst:\n lst.remove(1)\n return lst\n\n\ndef sieve(limit):\n s = [True for i in range(limit + 1)]\n s[0] = s[1] = False\n\n for i in range(4, limit + 1, 2):\n s[i] = False\n\n for i in range(3, math.floor(math.sqrt(limit)) + 1, 2):\n if s[i]:\n for m in range(2 * i, limit + 1, i):\n s[m] = False\n\n primes = []\n prime_candidate = 0\n for i in s:\n if i:\n primes.append(prime_candidate)\n prime_candidate += 1\n\n return primes\n\n\ndef sieve2(limit):\n s = [True for i in range(limit + 1)]\n s[0] = s[1] = False\n\n for i in range(2, math.floor(math.sqrt(limit)) + 1):\n if s[i]:\n for j in range(i * i, limit + 1, i):\n s[j] = False\n\n primes = []\n prime_candidate = 0\n for i in s:\n if i:\n primes.append(prime_candidate)\n prime_candidate += 1\n\n return primes\n\n\ndef millis():\n return round(time.time() * 1000)\n\n\nlimit = 5000\n\nstart = millis()\noriginal_sieve = op_sieve(limit)\nend = millis()\n\nprint(end - start)\n\nstart = millis()\nmy_sieve = sieve(limit)\nend = millis()\n\nprint(end - start)\n\nstart = millis()\nmy_sieve2 = sieve2(limit)\nend = millis()\n\nprint(end - start)\n\n#print(original_sieve)\n#print(my_sieve)\n#print(my_sieve2)\nprint(&quot;Agreed: &quot;, original_sieve == my_sieve and my_sieve == my_sieve2)\n</code></pre>\n<p>The output might be as follows:</p>\n<pre><code>7199\n2\n2\nAgreed: True\n</code></pre>\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T11:55:49.123", "Id": "267995", "ParentId": "267944", "Score": "2" } } ]
<p>So I did my own take (I wrote my own algorithm) for generating prime numbers from <code>1 to 1000</code>.</p> <pre><code>lst = [y for y in range(1000)] for i in range(0,len(lst)): #i = 1 and i is traversal print(&quot;iterate - &quot; + str(i)) for j in range(i,0,-1): #divisor range print(j) if j != 1 and j &lt; lst[i] and lst[i] % j == 0: if j in lst: lst[i] = 0 break for k in range(len(lst)): if 0 in lst: lst.remove(0) if 1 in lst: lst.remove(1) print(lst) </code></pre> <p>My concerns are</p> <ul> <li>Is this code easy to read?</li> <li>Is this optimal (I don't think so)?</li> <li>What should I do for improving my code?</li> </ul> <p>OUTPUT</p> <blockquote> <p>2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,<br /> 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,<br /> 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,<br /> 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,<br /> 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,<br /> 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,<br /> 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,<br /> 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,<br /> 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,<br /> 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,<br /> 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997</p> </blockquote>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:04:20.983", "Id": "267944", "Score": "4", "Tags": [ "python", "algorithm", "primes" ], "Title": "My prime number generation program in Python" }
267944
max_votes
[ { "body": "<p>I am not a professional Python developer, so I will address only the performance issue: judging from you <code>for</code> loops structure, it seems that the running time of your implementation is <span class=\"math-container\">\\$\\Theta(n^2)\\$</span>, where <span class=\"math-container\">\\$n\\$</span> is the prime limit. However, you can do the same in <span class=\"math-container\">\\$O(n \\log n)\\$</span>, or even, <span class=\"math-container\">\\$O(n \\log \\log n)\\$</span> time. (See below.)</p>\n<pre><code>import math\nimport time\n\n\ndef op_sieve(limit):\n lst = [y for y in range(limit + 1)]\n for i in range(0, len(lst)): # i = 1 and i is traversal\n for j in range(i, 0, -1): # divisor range\n if j != 1 and j &lt; lst[i] and lst[i] % j == 0:\n if j in lst:\n lst[i] = 0\n break\n\n for k in range(len(lst)):\n if 0 in lst:\n lst.remove(0)\n if 1 in lst:\n lst.remove(1)\n return lst\n\n\ndef sieve(limit):\n s = [True for i in range(limit + 1)]\n s[0] = s[1] = False\n\n for i in range(4, limit + 1, 2):\n s[i] = False\n\n for i in range(3, math.floor(math.sqrt(limit)) + 1, 2):\n if s[i]:\n for m in range(2 * i, limit + 1, i):\n s[m] = False\n\n primes = []\n prime_candidate = 0\n for i in s:\n if i:\n primes.append(prime_candidate)\n prime_candidate += 1\n\n return primes\n\n\ndef sieve2(limit):\n s = [True for i in range(limit + 1)]\n s[0] = s[1] = False\n\n for i in range(2, math.floor(math.sqrt(limit)) + 1):\n if s[i]:\n for j in range(i * i, limit + 1, i):\n s[j] = False\n\n primes = []\n prime_candidate = 0\n for i in s:\n if i:\n primes.append(prime_candidate)\n prime_candidate += 1\n\n return primes\n\n\ndef millis():\n return round(time.time() * 1000)\n\n\nlimit = 5000\n\nstart = millis()\noriginal_sieve = op_sieve(limit)\nend = millis()\n\nprint(end - start)\n\nstart = millis()\nmy_sieve = sieve(limit)\nend = millis()\n\nprint(end - start)\n\nstart = millis()\nmy_sieve2 = sieve2(limit)\nend = millis()\n\nprint(end - start)\n\n#print(original_sieve)\n#print(my_sieve)\n#print(my_sieve2)\nprint(&quot;Agreed: &quot;, original_sieve == my_sieve and my_sieve == my_sieve2)\n</code></pre>\n<p>The output might be as follows:</p>\n<pre><code>7199\n2\n2\nAgreed: True\n</code></pre>\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T11:55:49.123", "Id": "267995", "ParentId": "267944", "Score": "2" } } ]
<p>I'm pretty new to python but after watching Mr Robot I felt inspired to make a CLI portscanner. With all the fancy console outputs you see in movies like a progress bar.</p> <p>It's finished and works nicely however I am not very happy with having to write twice <code>global host_IP</code> in <code>main()</code> and <code>scan_tcp()</code>. I have to do this the only way I was able to get a progress bar with tqdm was by using <code>executor.map()</code> which as to my understanding can only take the iterator argument unlucky the <code>executor.submit()</code>. Is there a cleaner way to doing this?</p> <p>I am also interested in any general feedback on the code or performance improvements :)</p> <pre class="lang-py prettyprint-override"><code>import socket import sys import argparse import concurrent.futures import pyfiglet from tqdm import tqdm host_IP = None def resolve_args(): argv = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(&quot;host&quot;, type=_host, help=&quot;Hostname or IP of host system to be scanned&quot;) parser.add_argument(&quot;-s&quot;, &quot;--startPort&quot;, type=_port, default=0, help=&quot;Port number to start scan (0-65535)&quot;) parser.add_argument(&quot;-e&quot;, &quot;--endPort&quot;, type=_port, default=65535, help=&quot;Port number to end scan (0-65535)&quot;) return vars(parser.parse_args(argv)) def _host(s): try: value = socket.gethostbyname(s) except socket.gaierror: raise argparse.ArgumentTypeError(f&quot;Host '{s}' could not be resolved.&quot;) return value def _port(s): try: value = int(s) except ValueError: raise argparse.ArgumentTypeError(f&quot;Expected integer got '{s}'&quot;) if 0 &gt; value &gt; 65535: raise argparse.ArgumentTypeError(f&quot;Port number must be 0-65535, got {s}&quot;) return value def scan_tcp(port): global host_IP sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(1) result = 0 try: answer = sock.connect_ex((host_IP, port)) if answer == 0: result = port sock.close() except socket.error: print(f&quot;Could not connect to host '{host_IP}'&quot;) sys.exit() except KeyboardInterrupt: print(&quot;Exiting...&quot;) sys.exit() return result def print_open_ports(results): results = list(filter(None, results)) for open_port in results: print(f&quot;Port {open_port} is OPEN&quot;) def main(): args = resolve_args() pyfiglet.print_figlet(&quot;PORTSCANNER&quot;, font=&quot;slant&quot;) global host_IP host_IP = args.get(&quot;host&quot;) ports = range(args.get(&quot;startPort&quot;), args.get(&quot;endPort&quot;) + 1) print(f&quot;Starting scan of {host_IP}...&quot;) with concurrent.futures.ThreadPoolExecutor() as executor: results = list(tqdm(executor.map(scan_tcp, ports), total=len(ports))) print(f&quot;Finished scan of {host_IP}!&quot;) print_open_ports(results) if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T11:15:01.213", "Id": "268075", "Score": "2", "Tags": [ "python", "python-3.x", "multithreading" ], "Title": "Avoid global variable due to executor.map()" }
268075
max_votes
[ { "body": "<p>Your</p>\n<pre><code>try:\n value = socket.gethostbyname(s)\nexcept socket.gaierror:\n raise argparse.ArgumentTypeError(f&quot;Host '{s}' could not be resolved.&quot;)\nreturn value\n</code></pre>\n<p>should probably be</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n return socket.gethostbyname(s)\nexcept socket.gaierror as e:\n raise argparse.ArgumentTypeError(f&quot;Host '{s}' could not be resolved.&quot;) from e\n</code></pre>\n<p>in other words, it's usually a good idea to maintain rather than break the exception cause chain.</p>\n<p>I would move your <code>except KeyboardInterrupt</code> up to a <code>try</code> in <code>main</code>, and rather than exiting, just <code>pass</code>. That way testers or external callers of <code>scan_tcp</code> can make their own decisions about how to handle keyboard interrupts.</p>\n<p>Why build up a list of <code>results</code> and defer printing until the end? Why not print results as you find them?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-18T09:11:38.723", "Id": "528685", "Score": "0", "body": "thx for the advice. I build up a list and print at the end as otherwise The progress bar always gets interrupted so u have progressbar port x port y progressbar etc. and I didn't find that very pretty." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T17:48:50.673", "Id": "268089", "ParentId": "268075", "Score": "2" } } ]
<p>I'm pretty new to python but after watching Mr Robot I felt inspired to make a CLI portscanner. With all the fancy console outputs you see in movies like a progress bar.</p> <p>It's finished and works nicely however I am not very happy with having to write twice <code>global host_IP</code> in <code>main()</code> and <code>scan_tcp()</code>. I have to do this the only way I was able to get a progress bar with tqdm was by using <code>executor.map()</code> which as to my understanding can only take the iterator argument unlucky the <code>executor.submit()</code>. Is there a cleaner way to doing this?</p> <p>I am also interested in any general feedback on the code or performance improvements :)</p> <pre class="lang-py prettyprint-override"><code>import socket import sys import argparse import concurrent.futures import pyfiglet from tqdm import tqdm host_IP = None def resolve_args(): argv = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument(&quot;host&quot;, type=_host, help=&quot;Hostname or IP of host system to be scanned&quot;) parser.add_argument(&quot;-s&quot;, &quot;--startPort&quot;, type=_port, default=0, help=&quot;Port number to start scan (0-65535)&quot;) parser.add_argument(&quot;-e&quot;, &quot;--endPort&quot;, type=_port, default=65535, help=&quot;Port number to end scan (0-65535)&quot;) return vars(parser.parse_args(argv)) def _host(s): try: value = socket.gethostbyname(s) except socket.gaierror: raise argparse.ArgumentTypeError(f&quot;Host '{s}' could not be resolved.&quot;) return value def _port(s): try: value = int(s) except ValueError: raise argparse.ArgumentTypeError(f&quot;Expected integer got '{s}'&quot;) if 0 &gt; value &gt; 65535: raise argparse.ArgumentTypeError(f&quot;Port number must be 0-65535, got {s}&quot;) return value def scan_tcp(port): global host_IP sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(1) result = 0 try: answer = sock.connect_ex((host_IP, port)) if answer == 0: result = port sock.close() except socket.error: print(f&quot;Could not connect to host '{host_IP}'&quot;) sys.exit() except KeyboardInterrupt: print(&quot;Exiting...&quot;) sys.exit() return result def print_open_ports(results): results = list(filter(None, results)) for open_port in results: print(f&quot;Port {open_port} is OPEN&quot;) def main(): args = resolve_args() pyfiglet.print_figlet(&quot;PORTSCANNER&quot;, font=&quot;slant&quot;) global host_IP host_IP = args.get(&quot;host&quot;) ports = range(args.get(&quot;startPort&quot;), args.get(&quot;endPort&quot;) + 1) print(f&quot;Starting scan of {host_IP}...&quot;) with concurrent.futures.ThreadPoolExecutor() as executor: results = list(tqdm(executor.map(scan_tcp, ports), total=len(ports))) print(f&quot;Finished scan of {host_IP}!&quot;) print_open_ports(results) if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T11:15:01.213", "Id": "268075", "Score": "2", "Tags": [ "python", "python-3.x", "multithreading" ], "Title": "Avoid global variable due to executor.map()" }
268075
max_votes
[ { "body": "<p>Your</p>\n<pre><code>try:\n value = socket.gethostbyname(s)\nexcept socket.gaierror:\n raise argparse.ArgumentTypeError(f&quot;Host '{s}' could not be resolved.&quot;)\nreturn value\n</code></pre>\n<p>should probably be</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n return socket.gethostbyname(s)\nexcept socket.gaierror as e:\n raise argparse.ArgumentTypeError(f&quot;Host '{s}' could not be resolved.&quot;) from e\n</code></pre>\n<p>in other words, it's usually a good idea to maintain rather than break the exception cause chain.</p>\n<p>I would move your <code>except KeyboardInterrupt</code> up to a <code>try</code> in <code>main</code>, and rather than exiting, just <code>pass</code>. That way testers or external callers of <code>scan_tcp</code> can make their own decisions about how to handle keyboard interrupts.</p>\n<p>Why build up a list of <code>results</code> and defer printing until the end? Why not print results as you find them?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-18T09:11:38.723", "Id": "528685", "Score": "0", "body": "thx for the advice. I build up a list and print at the end as otherwise The progress bar always gets interrupted so u have progressbar port x port y progressbar etc. and I didn't find that very pretty." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T17:48:50.673", "Id": "268089", "ParentId": "268075", "Score": "2" } } ]
<p>I am trying to calculate the time difference between samples that a satellite takes at the same location. I have data currently in a Pandas DataFrame that has latitude, longitude, and time of the sample. Here is a snapshot of the data (it has some extra columns that can be ignored):</p> <pre><code> JulianDay LatSp LonSp AltSp LandMask 34 2.459581e+06 19.699432 -105.036661 410.853638 1 35 2.459581e+06 20.288866 -105.201204 1378.320140 1 36 2.459581e+06 20.808230 -105.350132 271.934574 1 39 2.459581e+06 22.415461 -105.698367 -16.805644 1 40 2.459581e+06 22.948721 -105.799142 164.985525 1 </code></pre> <p>The data though does not need to be exactly at the same location. The resolution is of ~11kmx11km square (0.1x0.1 degrees). So I get an approximate latitude and longitude with the following:</p> <pre><code>specular_df['approx_LatSp'] = round(specular_df['LatSp'],1) specular_df['approx_LonSp'] = round(specular_df['LonSp'],1) </code></pre> <p>The final step (which takes 2 hours for a small sample of the data that I need to run), is to group the data into the given squares and calculate the time difference between each sample inside the square. For this, my intuition points me toward groupby, but then I am not sure how to get the time difference without using a for loop. This for loop is the part that takes two hours. Here is the code I have written for now:</p> <pre><code>grouped = specular_df.groupby(['approx_LatSp', 'approx_LonSp']) buckets = pd.DataFrame(columns=['bucket_LatSp', 'bucket_LonSp', 'SpPoints', 'Revisits', 'MaxRevisit']) for key in tqdm(list(grouped.groups.keys())): group = grouped.get_group(key) times = group['JulianDay'].tolist() times = sorted(times + [sim_end, sim_start]) diff = [t - s for s, t in zip(times, times[1:])] temp = {'bucket_LatSp': key[0], 'bucket_LonSp': key[1], 'SpPoints': group.to_dict(), 'Revisits': diff, 'MaxRevisit': max(diff)} buckets = buckets.append(temp, ignore_index=True) </code></pre> <p>A couple of notes here. The time difference between samples is what is known as Revisit (I store a list of time differences in the revisit column). Since this is just data from a simulation, if there are only two data points in a square and they are close together it could lead to a revisit time that is short (eg simulation of 3 days, samples happen during the first two hours. The difference will be (at most) 2 hours, when in truth it should be closer to 3 days). For this reason I add the simulation start and end in order to get a better approximation of the maximum time difference between samples.</p> <p>The part that I am stuck on is how to compress this for loop whilst still getting similar data (If it is fast enough I wouldn't need the SpPoints column anymore as that is just storing the precise time, and location of each point in that square).</p> <p>Any suggestions would be greatly appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T16:38:51.517", "Id": "529167", "Score": "0", "body": "You will get much better answers faster if you provide a full runnable snippet with some reasonable test data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T20:16:34.667", "Id": "530523", "Score": "0", "body": "Thanks for your feedback, I will certainly do that in the future! In the mean time I was able to find a solution which I am posting below." } ]
{ "AcceptedAnswerId": "268965", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-18T19:47:18.113", "Id": "268125", "Score": "2", "Tags": [ "python", "performance", "pandas" ], "Title": "Finding the difference in one column in a Pandas GroupBy" }
268125
accepted_answer
[ { "body": "<p>I was recently able to resolve this by removing one of my constraints. In the original post I noted that I need to include the start and end time to make up for low simulation time. The actual solution to low simulation time is quite simple; increase the simulation time. I also add a condition that revisit is only counted if it is longer than a couple of hours. With that, you get some pretty reasonable estimates.</p>\n<p>Calculating revisit is still a bit painful though. I include below the code that I used for this, but the difficult part came from <a href=\"https://stackoverflow.com/questions/20648346/computing-diffs-within-groups-of-a-dataframe\">this StackOverflow post.</a></p>\n<pre><code># Round lat and long and then use groupby to throw them all in similar buckets\nspecular_df['approx_LatSp'] = round(specular_df['LatSp'],1)\nspecular_df['approx_LonSp'] = round(specular_df['LonSp'],1)\n\n# Calculate time difference\nspecular_df.sort_values(by=['approx_LatSp', 'approx_LonSp', 'JulianDay'], inplace=True)\nspecular_df['revisit'] = specular_df['JulianDay'].diff()\n\n# Correct for borders\nspecular_df['revisit'].mask(specular_df.approx_LatSp != specular_df.approx_LatSp.shift(1), other=np.nan, inplace=True)\nspecular_df['revisit'].mask(specular_df.approx_LonSp != specular_df.approx_LonSp.shift(1), other=np.nan, inplace=True)\n\n# Get max revisit and store in new DF\nindeces = specular_df.groupby(['approx_LatSp', 'approx_LonSp'])['revisit'].transform(max) == specular_df['revisit']\n\nmax_rev_area_df = specular_df[indeces]\nmax_rev_area_df['revisit'].mask(max_rev_area_df['revisit'] &lt; 0.04, other=np.nan, inplace=True)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T20:21:56.817", "Id": "268965", "ParentId": "268125", "Score": "1" } } ]
<p>In my Python projects, I often define parameters in a TOML, YAML, or JSON file. Those parameters are loaded into a dictionary which is utilized by various functions in the project. See below for some examples. I'm curious on how others would approach this and if there are better ways to work with functions and parameter files.</p> <p><strong>Parameters file</strong></p> <p>Parameters are defined in a TOML file named <code>params.toml</code>.</p> <pre><code>[feedstock] d = 0.8 phi = [ 0.65, 0.8, 0.95 ] k = 1.4 cp = 1800 temp = 60 ei = 1.2 eo = 1.8 rho = 540 [reactor] d = 5.4 h = 8.02 temp = 500 p = 101325 </code></pre> <p>The parameters are loaded into a dictionary named <code>params</code>.</p> <pre class="lang-py prettyprint-override"><code>import toml pfile = 'params.toml' with open(pfile, 'r') as f: params = toml.load(f) </code></pre> <p><strong>Example 1</strong></p> <p>This example explicitly defines each input variable to the function. I like this example because it is obvious on what the inputs are to the function. Values from the parameters dictionary are assigned to variables which are used as inputs to the function.</p> <pre class="lang-py prettyprint-override"><code>def calc_feedx(d, rho, temp): a = (1 / 4) * 3.14 * (d**2) x = a * rho * temp return x d = params['feedstock']['d'] rho = params['feedstock']['rho'] temp = params['feedstock']['temp'] x = calc_feedx(d, rho, temp) </code></pre> <p><strong>Example 2</strong></p> <p>This example only has one input variable to the function which is a dictionary that contains all the parameters utilized by the function. I don't like this approach because it's not obvious what the input parameters are for the function. This example provides the entire dictionary to the function which accesses the parameters from within the function. Not all the parameters defined in the dictionary are used by the function.</p> <pre class="lang-py prettyprint-override"><code>def calc_feedx(params): d = params['feedstock']['d'] rho = params['feedstock']['rho'] temp = params['feedstock']['temp'] a = (1 / 4) * 3.14 * (d**2) x = a * rho * temp return x x = calc_feedx(params) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T03:51:42.370", "Id": "528771", "Score": "0", "body": "Use example 1, but please show all of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T04:19:40.247", "Id": "528772", "Score": "0", "body": "@Reinderien This is all of the code. It's just an example I made up for my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T01:58:36.223", "Id": "528817", "Score": "0", "body": "There is a third option--use `calc_feedx(**params)`. It shortens code a lot, but violates PEP 20's \"Explicit is better than implicit.\". I think all three are reasonable options." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T03:55:28.893", "Id": "528826", "Score": "0", "body": "@ZacharyVance Your suggestion does not work because inputs to `calc_feedx(d, rho, temp)` are only `d`, `rho`, and `temp`. Using `**params` causes an error because the dictionary contains more parameters than what the function uses." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T04:00:38.480", "Id": "528827", "Score": "0", "body": "That's a good point I didn't notice. You could add a **kwargs to calc_feedx which is silently discarded, but that's pretty ugly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T07:52:01.377", "Id": "528837", "Score": "0", "body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)" } ]
{ "AcceptedAnswerId": "268194", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T00:37:53.510", "Id": "268168", "Score": "0", "Tags": [ "python", "configuration" ], "Title": "Utilize values in a parameters file for function inputs" }
268168
accepted_answer
[ { "body": "<p>What is missing is context. Example one is fine, but what if it contained 10 or 15 parameters? That means that you probably have some objects hiding in there.</p>\n<p>The problem with the second example is that you pass the whole params object in, but only need feedstock. calc_feedx(feedstock) would be much more appropriate, which makes it basically equivalent to the first example.</p>\n<p>Which brings me to this point - params object should not live everywhere. In fact it should stay as far away from your main logic as possible. What if you decide to host configuration on a server, are you going to rewrite the logic? Also, what if you change the names you use in the core of the app or in configuration? (These are just the examples off the top of my head). What I'm basically saying is that you should have configuration decoupled from the logic to avoid a potential mess.</p>\n<p>So don't think how you will make the code work with configuration, but how will you make configuration work with code if that makes sense. The way you can go about reading configuration is basically endless and the structure of the configuration could also be independent of your app.</p>\n<p>Edit:</p>\n<p>Here is the example:</p>\n<pre><code>def read_toml_config(path):\n def read(path):\n with open(self.file, 'r') as f:\n return toml.load(f)\n\n def map(raw_config):\n return { &quot;foo&quot;: raw_config[&quot;bar&quot;] }\n\n raw_config = read(path)\n return map(raw_config)\n\n# You decide how config object should look for your app\n# because the properties are determined by the read_toml_config\n# function and not by the path.toml file\nconfig = read_toml_config('path.toml')\n\n# calc_feedx does not know that the config exists\n# all it knows is that foo exists, which it needs\ncalc_feedx(config[&quot;foo&quot;])\n</code></pre>\n<p>You could generify read_toml_config to any other configuration -&gt; you read it in some way and then you map it to your application's needs. And you don't pass the whole configuration around, but just the objects the functions need. And at the same time, you might not read in the whole configuration from path.toml, but just the values you need -&gt; the code becomes the source of truth.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T18:30:55.020", "Id": "528810", "Score": "0", "body": "I think I understand what you're saying. Can you provide a code example of how you would decouple the parameters file (configuration) from the logic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T04:04:27.453", "Id": "528828", "Score": "0", "body": "Mapping the dictionary to another dictionary seems redundant to me. For my work, the parameter names defined in the TOML file are descriptive so there is no need to rename them elsewhere in the project. The parameter names in the code are typically consistent with their names in the parameters file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T08:36:07.493", "Id": "528841", "Score": "0", "body": "You don't always need to map, but it is useful to have the config object defined by your code -> this is the responsibility of read_toml_config." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-20T17:01:20.077", "Id": "268194", "ParentId": "268168", "Score": "1" } } ]
<p>I have just finished an assignment and would like to know what best practices I might be missing in my code. Any help would be hugely appreciated.</p> <pre><code>import random random.seed(42) def alphabet_position(text_): def numeric_position(char_): # Built in method for getting the alphabet position import string return 1+string.ascii_lowercase.index(char_.lower()) # Consider only alphabetic characters return ' '.join([str(numeric_position(t)) for t in text_ if t.isalpha()]) def count_smileys(smileys: list) -&gt; int: import re pattern = r'(:|;)(-|~)?(\)|D)' total = 0 # Add 1 if it matches a face (Only works in Python 3.8 or greater) [total := total + 1 for s in smileys if bool(re.search(pattern, s))] return total class Bingo: def __init__(self, n): self.initial_size = n self.current_ball = None self.picked_balls = [] self.remainder_balls = n def pick_ball(self): # Do not consider the already picked balls for choosing randomly self.current_ball = \ random.choice([i for i in range(1, self.initial_size) if i not in self.picked_balls]) self.picked_balls.append(self.current_ball) self.remainder_balls -= 1 def pick_n_balls(n_): bg = Bingo(75) for i in range(n_+1): bg.pick_ball() output = f&quot;({bg.current_ball}, {bg.picked_balls}, {bg.remainder_balls})&quot; return output def assert_everything(): assert alphabet_position(&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&quot;) == '12 15 18 5 13 9 16 19 21 13 4 15 12 15 18 19 9 20 1 13 5 20 3 15 14 19 5 3 20 5 20 21 18 1 4 9 16 9 19 3 9 14 7 5 12 9 20' assert count_smileys([]) == 0 assert count_smileys([':D',':~)',';~D',':)']) == 4 assert count_smileys([':)',':(',':D',':O',':;']) == 2 assert count_smileys([';]', ':[', ';*', ':$', ';-D']) == 1 assert pick_n_balls(16) == (53, [15, 4, 38, 34, 31, 20, 16, 13, 63, 6, 5, 9, 22, 24, 46, 53], 59) if __name__ == &quot;__main__&quot;: print(alphabet_position(&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&quot;)) print(count_smileys([])) print(count_smileys([':)', ';(', ';}', ':-D'])) print(count_smileys([';D', ':-(', ':-)', ';~)'])) print(count_smileys([';]', ':[', ';*', ':$', ';-D'])) pick_n_balls(16) assert_everything() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T14:17:03.230", "Id": "529034", "Score": "2", "body": "What do `alphabet_position`, `count_smileys` and the Bingo stuff have to do with each other? It seems they're completely unrelated. Also: What are they supposed to do? Task description(s) is/are missing." } ]
{ "AcceptedAnswerId": "268295", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T09:23:05.687", "Id": "268283", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Find alphabet position, count smileys, and play bingo with assertion testing" }
268283
accepted_answer
[ { "body": "<blockquote>\n<pre><code>random.seed(42)\n</code></pre>\n</blockquote>\n<p>We only want to do this in the <code>main</code> guard, not when loaded as a module. It's really part of the test function, not the module.</p>\n<blockquote>\n<pre><code>total = 0\n# Add 1 if it matches a face (Only works in Python 3.8 or greater)\n[total := total + 1 for s in smileys if bool(re.search(pattern, s))]\nreturn total\n</code></pre>\n</blockquote>\n<p>We can use <code>sum()</code> for counting:</p>\n<pre><code>return sum(1 for s in smileys if re.search(pattern, s))\n</code></pre>\n<p>We might want to make a separate function for <code>is_smiley()</code>, simply to make the tests more specific. Also consider compiling the regular expression just once, using <code>re.compile()</code>.</p>\n<p>On the subject of tests, seriously consider using the <code>doctest</code> module, to keep your tests close to the code they exercise. That would look like this for the <code>count_smileys()</code> function:</p>\n<pre><code>import re\n\nSMILEY_REGEX = re.compile(r'(:|;)(-|~)?(\\)|D)')\n\ndef count_smileys(smileys: list) -&gt; int:\n &quot;&quot;&quot;\n Return the number of strings in SMILEYS which contain at least one smiley face.\n\n &gt;&gt;&gt; count_smileys([])\n 0\n &gt;&gt;&gt; count_smileys([':D', ':~)', ';~D', ':)'])\n 4\n &gt;&gt;&gt; count_smileys([':)',':(',':D',':O',':;'])\n 2\n &gt;&gt;&gt; count_smileys([';]', ':[', ';*', ':$', ';-D'])\n 1\n &quot;&quot;&quot;\n return sum(1 for s in smileys if SMILEY_REGEX.search(s))\n\nif __name__ == &quot;__main__&quot;:\n import doctest\n doctest.testmod()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T15:32:05.470", "Id": "529039", "Score": "0", "body": "Just wondering: have you ever written/seen a program exceeding the compiled patterns cache?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T16:27:57.750", "Id": "529045", "Score": "0", "body": "Actually, I'd forgotten the cache. Are you saying it's better to just `re.compile()` every time the function is called? I'm not an expert with `re` internals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T16:36:56.573", "Id": "529048", "Score": "0", "body": "No, I was thinking of just using `re.search`. But the explicit `compile` way [does indeed look much faster](https://tio.run/##bVGxbsIwEN39Fbcg@1BCC1naIMRCVFVql3ZplUYoBVMsEdtyzICE@PXUjkloS2@x/O69e88@fbBbJZM7bZpmY1QFVlRcWBCVVsaC4ZqXlpCa272GGVBKSd8irWCzlyur1K7uNLo0VpQ7oktruZFOZShLj1Nk8fGEc/aBxwVS8vr8@JS9L1@yh@zNc/hopSotdpydhehcS7PauuZP7iigpPZx0thN8oYHdzsbMzcqcCL4M2ry24jm6bTI41Mxz3FRUOxG@1eSzHFzAq5oP7CLFkGNNArNf7KxS/cKaMNeESYBKQjZKANLEBJMKb84SzBteR7mHs7C3ZfcV5/cuJjjW1897lfof6d22@BrFnbIuAvttxiddbNwIOZpUvRabYS0bMjoIFmDrIHCAJiFm85sCGN@j20c6@O0XhgBR3KRY9N8Aw), at least with such short test strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:34:56.047", "Id": "529137", "Score": "0", "body": "@TobySpeight thanks a lot for your answer. I'm struggling to understand though what the difference between re.compile vs re.search is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:47:47.537", "Id": "529139", "Score": "2", "body": "`re.search()` takes a string, which needs to be turned into a regular expression automaton (i.e. compiled) each time the function is called. `re.compile()` does just the compilation, and allows us to reuse the internal form rather than constructing it anew each time we want to search. I think [the documentation](https://docs.python.org/3/library/re.html#re.compile) explains that better than I could!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:55:21.100", "Id": "529141", "Score": "0", "body": "Thanks again! Brilliant answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T12:55:38.427", "Id": "529245", "Score": "1", "body": "@TobySpeight No, `re.search` and others do **not** compile anew each time. At the end of exactly that section you yourself linked to it says *\"**The compiled versions of** [...] and the **module-level matching functions are cached**, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions\"*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T12:55:55.880", "Id": "529246", "Score": "0", "body": "Ah, so explicitly compiling only saves the cache lookup? Thanks for educating me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T13:12:15.480", "Id": "529248", "Score": "0", "body": "As far as I can tell from that documentation and looking at the source code, yes. I'm also trying to verify it experimentally by inserting prints around the caching code, but somehow that makes the code hang/crash every time. I do see a few prints, but not of my test regex but of others." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T13:19:08.317", "Id": "529249", "Score": "0", "body": "Apparently somehow it just didn't like my prints. So I collected data in a list `re.foo` instead and printed that afterwards. Trying `re.search('foo', 'foobar')` five times led to [this lookup](https://github.com/python/cpython/blob/1f08d16c90b6619607fe0656328062ab986cce29/Lib/re.py#L294) failing once and succeeding the remaining four times." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T14:37:20.263", "Id": "268295", "ParentId": "268283", "Score": "4" } } ]
<pre><code>import random import string def random_char(y): return ''.join(random.choice(string.ascii_uppercase) for x in range(y)) p1 = str(random.randrange(1, 99)) p2 = str(random_char(5)) p3 = str(random.randrange(1, 9)) p4 = str(random_char(2)) p5 = str(random.randrange(1, 9)) p6 = str(random_char(1)) # Y p7 = str(random.randrange(1, 9)) # 7 p8 = str(random_char(3)) # AUS result = p1 + p2+p3+p4+p5+p6+p7+p8 print(result) </code></pre> <p>I generate a specific code like &quot;31SPZVG2CZ2R8WFU&quot; How can i do it in a more elegant way?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T11:55:01.000", "Id": "529023", "Score": "0", "body": "Do you want this to be `1-2 digits + 5*random uppercased letters + ...` or it can be any random string?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T11:57:42.137", "Id": "529024", "Score": "0", "body": "Yes, exactly. I model 31SPZVG2CZ2R8WFU this key as example. So digits+strs.. etc" } ]
{ "AcceptedAnswerId": "268292", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T11:51:19.193", "Id": "268290", "Score": "1", "Tags": [ "python", "random" ], "Title": "Generate random string to match a specific pattern" }
268290
accepted_answer
[ { "body": "<p>In your <code>random_char</code> function, you don't use <code>x</code> at all. Replace it with <code>_</code> (it's conventional in python to use <code>_</code> for throwaway variables). <code>y</code> could also be renamed to something more descriptive. The name of the function could also be renamed to <code>random_chars</code> since you're generating one or more of them.</p>\n<p>Also, use string formatting instead of all those extra variables:</p>\n<pre><code>def generate_key():\n return (f&quot;{random.randrange(1, 9)}{random_chars(5)}{random.randrange(1, 9)}{random_chars(2)}&quot; \n f&quot;{random.randrange(1, 9)}{random_chars(1)}{random.randrange(1, 9)}{random_chars(3)}&quot;)\n</code></pre>\n<p>Note that the f-strings are available for Python versions &gt;= 3.6</p>\n<p>As a side note, there's this nice <a href=\"https://github.com/asciimoo/exrex\" rel=\"nofollow noreferrer\">exrex</a> which can:</p>\n<blockquote>\n<p>Generate all - or random - matching strings to a given regular\nexpression and more. It's pure python, without external dependencies.</p>\n</blockquote>\n<p>Given some pattern (similar to what you want):</p>\n<pre><code>r&quot;(\\d[A-Z]{1,4}){4}&quot;\n</code></pre>\n<ul>\n<li><code>(...){4}</code> matches the previous token exactly 4 times.</li>\n<li><code>\\d</code> matches a digit (equivalent to <code>[0-9]</code>)</li>\n<li><code>[A-Z]{1,4}</code> matches the previous token between 1 and 4 times, as many times as possible, giving back as needed (greedy)</li>\n<li><code>A-Z</code> matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)</li>\n</ul>\n<p><em>Note: I'm not a regex expert so there might be an easier / more correct version of this.</em></p>\n<p>I think you can use this regex which returns exactly the pattern you want: <code>\\d{1,2}[A-Z]{5}\\d[A-Z]{2}\\d[A-Z]{1}\\d[A-Z]{3}</code></p>\n<p>Your entire code could be rewritten as:</p>\n<pre><code>import exrex\n\nrandom_key = exrex.getone(r'(\\d[A-Z]{1,4}){4}')\nprint(random_key)\n</code></pre>\n<p>Which would generate:</p>\n<pre><code>'3C2BBV3NGKJ2XYJ'\n</code></pre>\n<p>For more information about regular expressions feel free to search on the internet to get familiar with them. For tests, I usually use <a href=\"https://regex101.com/\" rel=\"nofollow noreferrer\">regex101</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T12:57:05.110", "Id": "529028", "Score": "0", "body": "As an advice, before accepting an answer try to wait 1-2 days to see alternative solutions/improvements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T13:26:29.963", "Id": "529031", "Score": "0", "body": "Is this right? The pattern you're using doesn't seem to follow the OP's, for instance having two leading digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T13:40:55.460", "Id": "529032", "Score": "1", "body": "@Reinderien It's just an example. I've specified in my answer that this regex might not be as the one in the question. And with a bit of effort from OP it can be easily modified/customized. More, that is an alternate solution for OP to have in mind ^^. //L.E: added a similar regex" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T12:36:51.060", "Id": "268292", "ParentId": "268290", "Score": "2" } } ]
<p>So, I just managed to finish a problem that was proposed to me, and I find it very difficult since I started learning looping with <code>for</code> and using <strong>lists</strong> recently, I thought about sharing the problem and my solution with you guys so you could give me some advice on how I should make my code better or different ways to solve the problem, hopefully you guys can help me, thank you for your attention and sorry if I made some mistakes, I am new to programming.</p> <p><em><strong>Question</strong></em></p> <blockquote> <p>Write a function that receives a list with natural numbers, verify if such list has repeated numbers, if so remove them. The function should return a correspondent list with no repeated elements. The list should be returned in ascending order.</p> </blockquote> <pre><code>def remove_repeated_numbers(z): x = 1 for i in z: y = x while y &lt;= (len(z) - 1): if i == z[y]: del z[y] y = (y - 1) #Once z[y] is deleted, should check same spot again y = (y + 1) x = (x + 1) list_finished = sorted(z[:]) return list_finished def main(): run = True z = [] while run: u = int(input(&quot;Entry value: &quot;)) if u != 0: z.append(u) else: run = False print(remove_repeated_numbers(z)) main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T07:44:27.363", "Id": "529082", "Score": "0", "body": "You may be interested in the SO question [What is the cleanest way to do a sort plus uniq on a Python list?](//stackoverflow.com/q/2931672/4850040)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T12:26:45.807", "Id": "529113", "Score": "1", "body": "Do you know that your ENTIRE script can be replaced with this ONE-liner: `sorted(set(l))`? This is extremely basic, `set` is a built-in data type that is ordered without duplicates with fast membership checking that is exactly what is designed to do this sort of thing, and then you just need to use `sorted` function to return a sorted (shallow) copy of the list. Type casting is by far the most efficient and readable way to do this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:44:06.207", "Id": "529138", "Score": "0", "body": "@XeнεiΞэnвϵς I tried your `sorted(set(l))`. Didn't work. Got `NameError: name 'l' is not defined`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:43:50.567", "Id": "529157", "Score": "0", "body": "@BolucPapuccuoglu `NameError: name 'z' is not defined`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:46:44.180", "Id": "529161", "Score": "0", "body": "Oh boy I did not knew that @XeнεiΞэnвϵς LOL, but I just figured it out, anyways, I'm pretty sure the Question wanted me to do it by myself, but anyways thank you for your tip." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:48:48.410", "Id": "529163", "Score": "3", "body": "@BolucPapuccuoglu Yeah, but XeнεiΞэnвϵς said to replace ENTIRE script with that (shouting already theirs)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T01:09:09.133", "Id": "268315", "Score": "6", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Remove repeated numbers from a list" }
268315
max_votes
[ { "body": "<p>It's a good start. Depending on what class this is for, the person (teacher?) who proposed this question to you might care about time complexity of your solution. Your solution is going to have a number of problems there, since:</p>\n<ul>\n<li><code>del z[y]</code> is linear-time (&quot;O(n)&quot;)</li>\n<li>That occurs within a loop over the list, within <em>another</em> loop over the list, making the solution worst-case cubic if I'm not mistaken.</li>\n</ul>\n<p>The trivial and common solution is to scrap the whole routine and replace it with calls to two built-ins:</p>\n<pre><code>from typing import Iterable, List\n\n\ndef remove_repeated_numbers(numbers: Iterable[int]) -&gt; List[int]:\n return sorted(set(numbers))\n</code></pre>\n<p>I will leave it as an exercise to you to read the <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"noreferrer\">documentation</a> and determine the complexity of this implementation.</p>\n<p>This will construct a set from the numbers, which guarantees uniqueness but not order; and then constructs a sorted list from that. Interpreted literally, the question doesn't call for the existence of a <code>main</code> but I don't know how picky the problem is.</p>\n<p>Other things to note:</p>\n<ul>\n<li>Don't use single-letter variables</li>\n<li>Add type hints for greater clarity</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T03:04:23.770", "Id": "268317", "ParentId": "268315", "Score": "7" } } ]
<p>So, I just managed to finish a problem that was proposed to me, and I find it very difficult since I started learning looping with <code>for</code> and using <strong>lists</strong> recently, I thought about sharing the problem and my solution with you guys so you could give me some advice on how I should make my code better or different ways to solve the problem, hopefully you guys can help me, thank you for your attention and sorry if I made some mistakes, I am new to programming.</p> <p><em><strong>Question</strong></em></p> <blockquote> <p>Write a function that receives a list with natural numbers, verify if such list has repeated numbers, if so remove them. The function should return a correspondent list with no repeated elements. The list should be returned in ascending order.</p> </blockquote> <pre><code>def remove_repeated_numbers(z): x = 1 for i in z: y = x while y &lt;= (len(z) - 1): if i == z[y]: del z[y] y = (y - 1) #Once z[y] is deleted, should check same spot again y = (y + 1) x = (x + 1) list_finished = sorted(z[:]) return list_finished def main(): run = True z = [] while run: u = int(input(&quot;Entry value: &quot;)) if u != 0: z.append(u) else: run = False print(remove_repeated_numbers(z)) main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T07:44:27.363", "Id": "529082", "Score": "0", "body": "You may be interested in the SO question [What is the cleanest way to do a sort plus uniq on a Python list?](//stackoverflow.com/q/2931672/4850040)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T12:26:45.807", "Id": "529113", "Score": "1", "body": "Do you know that your ENTIRE script can be replaced with this ONE-liner: `sorted(set(l))`? This is extremely basic, `set` is a built-in data type that is ordered without duplicates with fast membership checking that is exactly what is designed to do this sort of thing, and then you just need to use `sorted` function to return a sorted (shallow) copy of the list. Type casting is by far the most efficient and readable way to do this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T14:44:06.207", "Id": "529138", "Score": "0", "body": "@XeнεiΞэnвϵς I tried your `sorted(set(l))`. Didn't work. Got `NameError: name 'l' is not defined`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:43:50.567", "Id": "529157", "Score": "0", "body": "@BolucPapuccuoglu `NameError: name 'z' is not defined`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:46:44.180", "Id": "529161", "Score": "0", "body": "Oh boy I did not knew that @XeнεiΞэnвϵς LOL, but I just figured it out, anyways, I'm pretty sure the Question wanted me to do it by myself, but anyways thank you for your tip." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T15:48:48.410", "Id": "529163", "Score": "3", "body": "@BolucPapuccuoglu Yeah, but XeнεiΞэnвϵς said to replace ENTIRE script with that (shouting already theirs)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T01:09:09.133", "Id": "268315", "Score": "6", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Remove repeated numbers from a list" }
268315
max_votes
[ { "body": "<p>It's a good start. Depending on what class this is for, the person (teacher?) who proposed this question to you might care about time complexity of your solution. Your solution is going to have a number of problems there, since:</p>\n<ul>\n<li><code>del z[y]</code> is linear-time (&quot;O(n)&quot;)</li>\n<li>That occurs within a loop over the list, within <em>another</em> loop over the list, making the solution worst-case cubic if I'm not mistaken.</li>\n</ul>\n<p>The trivial and common solution is to scrap the whole routine and replace it with calls to two built-ins:</p>\n<pre><code>from typing import Iterable, List\n\n\ndef remove_repeated_numbers(numbers: Iterable[int]) -&gt; List[int]:\n return sorted(set(numbers))\n</code></pre>\n<p>I will leave it as an exercise to you to read the <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"noreferrer\">documentation</a> and determine the complexity of this implementation.</p>\n<p>This will construct a set from the numbers, which guarantees uniqueness but not order; and then constructs a sorted list from that. Interpreted literally, the question doesn't call for the existence of a <code>main</code> but I don't know how picky the problem is.</p>\n<p>Other things to note:</p>\n<ul>\n<li>Don't use single-letter variables</li>\n<li>Add type hints for greater clarity</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T03:04:23.770", "Id": "268317", "ParentId": "268315", "Score": "7" } } ]
<p>I tried to write the program so that it runs without error but I want to improve the program so that it follows the Single Responsibility Principle. What changes can I make to improve this program? I am a beginner in programming and not good at pseudocode or commenting so if there is anything I can do to also improve there.</p> <pre><code> &quot;&quot;&quot; Pseudocode: def main(): set plants list day = 0 food = 0 display welcome() display plants() report_day() display_menu() get choice.lower() while choice != quit: if wait: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T05:29:11.917", "Id": "529207", "Score": "0", "body": "I'm not sure why you removed the Python part of your program, since it makes your question off-topic. If the Python code works, you can put it back. If it doesn't work, the question wasn't ready for review. Please take a look at the [help/on-topic]." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T00:22:30.063", "Id": "268364", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "functional-programming" ], "Title": "Garden simulator" }
268364
max_votes
[ { "body": "<h2>Pseudocode</h2>\n<p>First, your block-quoted pseudo-code is too much like code, and not enough pseudo. The purpose of pseudo-code is understanding. If it doesn't help you to understand, or if it doesn't help someone else (like a professor) to understand, then you're doing it wrong. In general, I'd suggest writing your pseudo-code in successive waves of refinement. Something like this:</p>\n<pre><code>while not done:\n get user choice()\n if choice is 'wait':\n get rainfall()\n if rainfall amount &lt; threshold:\n kill one plant()\n produce food from plants remaining()\n if choice is 'add plant':\n add new plant()\n if choice is 'display plants':\n display plants()\n if choice is 'quit':\n quit()\n \n print daily report()\n</code></pre>\n<p>That's probably enough to get yourself started writing code, and it might be enough to make a teacher happy. The details should be in the code itself, unless you are forced to change your logic.</p>\n<h2>Naming</h2>\n<p>You need to read and apply the <a href=\"https://www.pep8.org\" rel=\"nofollow noreferrer\">Python style guide.</a></p>\n<p>In particular: documentation for functions goes in the function's docstring. Constants should be ALL_CAPS.</p>\n<h2>Functions</h2>\n<p>You have some good functions. But I submit to you that each time you have a comment in your code, that's probably a good place for a function. Sometimes, you can combine several comments into a single function, but in general, if you're explaining what happens, you can explain better using a function and its accompanying docstring:</p>\n<pre><code> if rainfall &lt; high_threshold: \n plant_die = random.choice(plants) # pick random a plant for too little rain\n print(f&quot;Sadly, your {plant_die} plant has died&quot;) \n plants.remove(plant_die) # remove plant from list\n</code></pre>\n<p>Could be rewritten as:</p>\n<pre><code>if rainfall &lt; high_threshold:\n one_plant_dies(plants)\n</code></pre>\n<h2>Wrapping</h2>\n<p>Your text output functions are relying on the <code>print()</code> statement to emit each line. This means that wrapping of text is occurring at the line level.</p>\n<p>In many cases, you would do better to use the <a href=\"https://docs.python.org/3/library/textwrap.html\" rel=\"nofollow noreferrer\"><code>textwrap</code> </a> module to perform wrapping for you, and put entire paragraphs in <em>&quot;&quot;&quot;triple quotes.&quot;&quot;&quot;</em></p>\n<h2>Results</h2>\n<p>You have written all your functions as procedures -- subroutines that do not return a value. If you haven't encountered the <code>return</code> statement, I encourage you to read about it. You will find it very hard to use the SRP if you cannot return values.</p>\n<p>Much of your code looks like:</p>\n<pre class=\"lang-none prettyprint-override\"><code>print some information\nget some input\n</code></pre>\n<p>That sort of thing is a good candidate for encapsulation in a function that returns <em>well validated</em> result. Thus, your code might be something like:</p>\n<pre><code>def get_user_preference(params):\n while True:\n print some information\n get some input\n if input is valid:\n return result(input)\n</code></pre>\n<h2>main()</h2>\n<p>There's a standard way to handle calling the main entry point of your program or module:</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<p>The purpose and value of this is that it will call <code>main()</code> when you just run <code>python mycode.py</code> but it will <em>not</em> call anything if you <code>import mycode</code>. This is valuable if you are writing a program that is also a library, or if you are using a unit test driver that will import your code into its test engine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T02:20:46.223", "Id": "529203", "Score": "0", "body": "thank you so much. I was able to fix my code and create the 3 functions for wait option. I still don't understand how I can come up with psuedo code prior to programming, but I will be working on that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-25T01:46:30.813", "Id": "268365", "ParentId": "268364", "Score": "2" } } ]
<p>I want to check null values in excel files where there are many sub folders. I have wrote a python code to check the null values in excel files in each and every folder and the code was working fine but I need to simplify the code.</p> <pre><code>import os ,uuidtre import numpy as np import pandas as pd import logging path =r&quot;C:\Users\Documents\python\Emp&quot; files = os.listdir(path) for filename in files: pathchild=path+'\\'+filename file = os.listdir(pathchild) files_xls = [f for f in file if f[-4:]== 'xlsx' ] child_folders= [f for f in file if f[-4:]!= 'xlsx'] for f1 in files_xls: filepath=pathchild+'\\'+f1 df = pd.read_excel(filepath, engine='openpyxl') count_nan = df.isnull().sum().sum() logging.basicConfig(filename='nanTest.log', level=logging.INFO,format='%(message)s') if count_nan ==0: none=' No none value in the excel file' else: none=' There is none values founded in the excel file' output='File name: '+ f1, 'File path: '+ filepath, none logging.info(output) for f2 in child_folders: patha=pathchild+'\\'+f2 file1 = os.listdir(patha) files_xls1 = [f for f in file1 if f[-4:]== 'xlsx'] for f3 in files_xls1: filechildpath=patha+'\\'+f3 df = pd.read_excel(filechildpath, engine='openpyxl') count_nan = df.isnull().sum().sum() if count_nan ==0: none=' No none value in the excel file' else: none=' There is none values founded in the excel file' output='File name: '+ f3,'File path: '+ filepath, none logging.info(output) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:07:35.237", "Id": "268439", "Score": "1", "Tags": [ "python-3.x" ], "Title": "Python code to check the null values in excel files" }
268439
max_votes
[ { "body": "<p>Use <code>print()</code> or <code>write()</code> for normal program output. The <code>logging</code> module is generally for recording information about how the program is running, e.g., for debugging, performance monitoring, etc.</p>\n<p>I'd recommend using <code>pathlib</code> in the standard library. <code>Path.rglob()</code> would be useful, it recursively searches directories for files with names that match a pattern, such as &quot;*.xlsx&quot;. Using it lets you eliminate the nested loops and a lot of the file/path handling code.</p>\n<p><code>pd.read_excel()</code> accepts a <code>pathlib.Path</code> for the first argument.</p>\n<p>The code collects the counts and path for each file, so the information can be sorted. This makes it easier to see which files have nulls, because they are grouped together.</p>\n<p>Use <code>f-strings</code> instead of string concatenation.</p>\n<p>I don't have excel files on this machine, so this code isn't tested:</p>\n<pre><code>import pandas as pd\nimport pathlib\n\nnull_counts = []\n\nstart_path = pathlib.Path(r&quot;C:\\Users\\Documents\\python\\Emp&quot;)\n\nfor file_path in start_path.rglob('*.xlsx'):\n\n df = pd.read_excel(file_path, engine='openpyxl')\n count_nan = df.isnull().sum().sum()\n\n null_counts.append((count_nan, file_path))\n\n\nnull_counts.sort(reverse=True)\n\nwith open('nanTest.log', 'wt') as output:\n for count, filepath in null_counts:\n print(f&quot;{count:5} {filepath}&quot;, file=output)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T20:29:54.690", "Id": "268451", "ParentId": "268439", "Score": "1" } } ]
<p>I have the below data and am obtaining the expected output column for it.</p> <pre class="lang-none prettyprint-override"><code>DATA EXPECTED_OUTPUT EXPLANATION ---------------------------------------------------------------------------------------------- 123 0000000123 7 leading 0s to get to 10 characters. nan None If data is not numeric, then null/None output. 123a None If data is not numeric, then null/None output. 1111111111119 1111111119 If data length &gt;10, truncate to right 10 characters. 0 0000000000 9 leading 0s to get to 10 characters. 123.0 0000000123 Remove decimal part and leading 0s to get to 10 characters. </code></pre> <p>I have 3 ways currently of doing so, but I'm unsure whether they are the optimal solution to handle all data possibilities.</p> <pre><code># Option 1 df['DATA'] =pd.to_numeric(df['DATA'], errors='coerce').fillna(0).\ astype(np.int64).apply(str).str.zfill(10) </code></pre> <pre><code># Option 2 df['DATA'] = df['DATA'].map('{:0&gt;10}'.format).astype(str).\ str.slice(0, 10) </code></pre> <pre><code># Option 3 df['DATA'] = df['DATA'].astype(str).str.split('.', expand=True)[0].str\ .zfill(10).apply(lambda x_trunc: x_trunc[:10]) </code></pre> <p>Any help on how to improve the way of doing this will be truly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:33:52.073", "Id": "529433", "Score": "1", "body": "You might want to look through the answers to [Padding a hexadecimal string with zeros](/q/67611/75307), as it's a very similar problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T00:39:39.537", "Id": "529485", "Score": "1", "body": "@TobySpeight Sadly, I don't think that's going to buy OP a lot, since the pandas vectorized approach doesn't support the typical native approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T06:55:15.563", "Id": "529494", "Score": "0", "body": "@Reinderien, fair enough - I've never worked with pandas, so I'm speaking from a relatively ignorant position." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T07:01:16.050", "Id": "268462", "Score": "0", "Tags": [ "python", "python-3.x", "comparative-review" ], "Title": "Convert string to 10 character string with leading zeros if necessary" }
268462
max_votes
[ { "body": "<p>Are you sure you want the non-numeric case to result in <code>None</code>? Pandas more commonly uses <code>NaN</code>. Anyway.</p>\n<p>You're missing an important test case: what do you want to happen for values with a non-zero post-decimal half?</p>\n<p>Option 1 is broken because you're just substituting 0 for non-numeric cases.</p>\n<p>Option 2 is non-vectorized due to the <code>map</code>, and will not catch <code>123a</code>; so it's broken too. As a bonus, your <code>slice(0, 10)</code> is slicing from the wrong end of the string.</p>\n<p>Option 3 is non-vectorized due to the <code>apply</code>, and does manual parsing of the decimal which is slightly awkward; it's also not going to catch non-numerics so it's broken.</p>\n<p>So I mean... if I were to be picky, none of your code is functioning as intended so closure would be justified; but what the heck:</p>\n<p>One approach that does not break vectorization and meets all of the edge cases would be</p>\n<ul>\n<li>Call <code>to_numeric(errors='coerce')</code> as you do in #1</li>\n<li>For valid numerals only, maintaining the original index:\n<ul>\n<li>cast to <code>int</code> to drop the decimal</li>\n<li>cast to <code>str</code></li>\n<li><code>zfill</code> and <code>slice</code> (from the end, not the beginning)</li>\n</ul>\n</li>\n<li>Save back to the data frame on valid indices only</li>\n<li>Fill the invalid indices with <code>None</code> (<code>fillna</code> is not sufficient for this purpose)</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\n\ndf = pd.DataFrame(\n [\n 123,\n float('nan'),\n '123a',\n 1111111111119,\n 0,\n 123.0,\n 123.4,\n ],\n columns=('DATA',)\n)\nas_floats = pd.to_numeric(df.DATA, errors='coerce')\nas_strings = (\n as_floats[pd.notna(as_floats)]\n .astype(int)\n .astype(str)\n .str.zfill(10)\n .str.slice(-10)\n)\ndf['out'] = as_strings\ndf.loc[pd.isna(as_floats), 'out'] = None\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T00:56:42.703", "Id": "268491", "ParentId": "268462", "Score": "2" } } ]
<p>I am required to code (as part of a 3-question assignment) a variable-size connect 4 board with a standard size of 6x7, with a minimum size of 2x2 and a maximum of 20x20. The professor said that he could do it in 20 lines, and the maximum one can write is 3 times that. My code sits uncomfortably close to it at 58 lines. What can I do to cut it down without using user-defined functions?</p> <pre class="lang-py prettyprint-override"><code>r, c, p, a, std, b = 0, 0, 0, '', input('Standard game? (y/n): '), ' ' if std == 'y': r, c = 6, 7 else: r, c = int(input('r? (2 - 20): ')), int(input('c? (2 - 20): ')) if r &lt; 11 and c &lt; 11: for i in range (r-1, -1, -1): a = str(i) for j in range (c): a = a + str(' ·') #repeats the dot for j times print(a + ' ') for j in range (c): b = b + ' ' + str(j) #adds successive nos. to the bottom row, ie the index print(b + ' ') elif r &lt; 11 and c &gt;= 11: a, b = ' ', ' ' for i in range (r-1, -1, -1): a = ' ' + str(i) + ' ' for j in range (c): a = a + ' ' + str('· ') print(a) for j in range (10): b = b + ' ' + str(j) for j in range (10, c): b = b + ' ' + str(j) print(b + ' ') elif r &gt;= 11 and c &lt; 11: b = ' ' for i in range (r-1, 9, -1): a = str(i) + ' ' for j in range (c): a = a + str(' · ') print(a) #repeats the dot for j times for j &gt;= 10 (i.e. no space) for i in range (9, -1, -1): a = ' ' + str(i) + ' ' for j in range (c): a = a + str(' · ') print(a) #repeats the dot for j times for j &lt; 10 (space) for j in range (c): b = b + ' ' + str(j) print(b + ' ') else: a, b = ' ', ' ' for i in range (r-1, 9, -1): a = str(i) + ' ' for j in range (c): a = a + str(' · ') print(a) #repeats the dot for j times for j &gt;= 10 (i.e. no space) for i in range (9, -1, -1): a = ' ' + str(i) + ' ' for j in range (c): a = a + str(' · ') print(a) for j in range (10): b = b + ' ' + str(j) for j in range (10, c): b = b + ' ' + str(j) print(b + ' ') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:55:03.320", "Id": "529435", "Score": "1", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T18:29:38.683", "Id": "529470", "Score": "1", "body": "Are you not allowed to use user-defined functions? What kind of class is this?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T08:42:02.990", "Id": "268466", "Score": "2", "Tags": [ "python", "homework", "connect-four" ], "Title": "Print a Connect 4 board" }
268466
max_votes
[ { "body": "<p>I will focus on creating a readable, maintainable and scalable implementation. Even without sacrificing readbaility (by avoiding things like multiple variable assignments per line), this implementation comes in at only 15 lines. This number could be reduced further by inlining some variables, etc. but I don't think that's worth doing here.</p>\n<p>Please note that this does not include proper validation of user input, which is generally a good idea.</p>\n<hr />\n<p><strong>Complete code</strong></p>\n<p>I added some blank lines for the sake of readability:</p>\n<pre><code>standard_game = input('Standard game? (y/n): ').lower() == &quot;y&quot;\n\nif standard_game:\n ROWS = 6\n COLUMNS = 7\nelse:\n ROWS = int(input('ROWS? (2 - 20): '))\n COLUMNS = int(input('COLUMNS? (2 - 20): '))\n \nwidth_y_axis_elements = len(str(ROWS - 1))\nwidth_x_axis_elements = len(str(COLUMNS - 1)) + 1\n\ndots = '·'.rjust(width_x_axis_elements) * COLUMNS\n\nfor i in range(ROWS - 1, -1, -1):\n label = str(i).rjust(width_y_axis_elements)\n print(f&quot;{label}{dots}&quot;)\n \nx_axis = ''.join(map(lambda s: s.rjust(width_x_axis_elements), map(str, range(COLUMNS))))\nprint(f&quot;{' ' * width_y_axis_elements}{x_axis}&quot;)\n</code></pre>\n<p>The key to simplifying this implementation is realizing that <code>ROWS</code> and <code>COLUMNS</code> being below or above 10 aren't actually special cases. You only need to consider the length of the highest number on each axis and then pad everything accordingly. For this we use <a href=\"https://www.w3schools.com/python/ref_string_rjust.asp\" rel=\"nofollow noreferrer\"><code>str.rjust</code></a>. Once you understand this conceptually, the implementation is rather straightforward. Don't hesitate to ask for clarifiction if necessary!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T15:44:08.577", "Id": "529529", "Score": "0", "body": "Thanks for your input! My class hasn't introduced str.rjust or f threads yet, so I'm not sure if I'm allowed to use this, but I'll take that idea in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T22:55:16.103", "Id": "529556", "Score": "0", "body": "You can easily replace f-strings with string concatenation, so `f\"{label}{dots}\"` becomes `label + dots`. You could also implement `str.rjust` on your own by checking the length of your input string, comparing it to the desired length and adding spaces to the front of the string until the desired length is reached." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-28T18:14:53.150", "Id": "268482", "ParentId": "268466", "Score": "2" } } ]
<p>I was messing around with the csv package and I tried to implement a class that returns csv objects whenever I need to open a csv file directly from a url(and occasionally prints out something).I am still very green and I would like to know if there is something I can do to optimize this code.You are going to find the description of every method in each docstring.There are still some functionalities that I want to add, but I would like to know if the design of this very simple class is acceptable and if there is something that I could make better or faster. Thank you for your attention and time.</p> <pre><code>import csv, urllib.request class read_CSV_URL: def __init__(self, url): self.request = urllib.request.urlopen(url) def read_csv_from_url(self, delimiter=&quot;,&quot;, num_of_lines=&quot;all&quot;, print_lines=False) -&gt; object: &quot;&quot;&quot; Read a csv file form a url. Three default values: 1. Delimiter is a standard coma. 2. Number of lines that are going to be printed In case you wanted just the first three lines of your file you can just set num_of_lines=3. 3. In case you want to print the lines set, print_lines=True. &quot;&quot;&quot; lines = [l.decode('utf-8') for l in self.request.readlines()] # decode response csv_object = csv.reader(lines, delimiter=delimiter) if print_lines: if num_of_lines == &quot;all&quot;: for line in csv_object: print(line) else: for number in range(num_of_lines): row = next(csv_object) print(row) return csv_object def read_csv_from_url_as_dict(self, delimiter=&quot;,&quot;, num_of_lines=&quot;all&quot;, print_lines=False) -&gt; object: &quot;&quot;&quot; Read a csv file form a url as a dictionary. Three default values: 1. Delimiter is a standard coma. 2. Number of lines that are going to be printed In case you wanted just the first three lines of your file you can just set num_of_lines=3. 3. In case you want to print the lines set, print_lines=True. &quot;&quot;&quot; lines = [l.decode('utf-8') for l in self.request.readlines()] # decode response csv_object = csv.DictReader(lines, delimiter=delimiter) if print_lines: if num_of_lines == 'all': for dicty in csv_object: print(dicty) else: for number in range(num_of_lines): print(next(csv_object)) return csv_object def get_key(self, key : str, csv_object): &quot;&quot;&quot; Get a single key given a csv_dictionary_object. &quot;&quot;&quot; listy = [] for row in csv_object: listy.append(row[key]) return listy def get_keys(self, csv_object, **kwargs) -&gt; list: listy = [] for row in csv_object: sub_list = [] for key in kwargs.values(): sub_list.append(row[key]) listy.append(sub_list) return listy csv_1 = read_CSV_URL('http://winterolympicsmedals.com/medals.csv') print(csv_1.read_csv_from_url_as_dict(print_lines=True)) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-29T14:14:30.187", "Id": "268506", "Score": "1", "Tags": [ "python", "object-oriented" ], "Title": "optimization csv from url analyzer" }
268506
max_votes
[ { "body": "<p>This is doing too much. You're trying to support reading rows as both a list and a dict; both printing and not; and reading all lines or some lines.</p>\n<p>Change the class name to follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.</p>\n<p>Drop most of your configuration options.</p>\n<ul>\n<li>Don't print lines as you go. This was debugging code and can be removed in the final version.</li>\n<li>Either return <code>list</code> or <code>dict</code> items but not both--write two classes if you really need both options.</li>\n<li>Always read all lines. Let the user directly iterate over the class. As a feature, support streaming access--I assume the reason you're avoiding reading all lines is so you can print faster.</li>\n<li>Drop <code>get_key</code> and <code>get_keys</code> entirely, make them a static method, or move them out of the class.</li>\n</ul>\n<p>A piece of example code, the way I would want to use this as a user:</p>\n<pre><code>for row in read_CSV_URL('http://winterolympicsmedals.com/medals.csv'):\n​ print(row)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-10T02:28:31.430", "Id": "268834", "ParentId": "268506", "Score": "3" } } ]
<p>I have a directory that includes a number of subdirectories. Each subdirectories contains subdirectories of its own. I'd like to construct a list of all sub-subdirectories in python. Here is my attempt:</p> <pre><code>import os list_of_lists = [[sub_dir + '/' + sub_subdir for sub_subdir in os.listdir(my_dir + '/' + sub_dir)] for sub_dir in os.listdir(my_dir)] flat_list = [item for sublist in list_of_lists for item in sublist] </code></pre> <p>Is there a better/more efficient/more aesthetic way to construct this?</p> <p>To clarify, here is an example:</p> <pre><code>My_dir | |--sub_dir_1 | | | |--sub_sub_dir_1 | | | |--sub_sub_dir_2 | |--sub_dir_2 | | | |--sub_sub_dir_1 | |--sub_dir_3 | |--sub_sub_dir_1 | |--sub_sub_dir_2 | |--sub_sub_dir_2 </code></pre> <p>In this example, the output that I'm looking for is <code>['sub_dir_1/sub_sub_dir_1', 'sub_dir_1/sub_sub_dir_2', 'sub_dir_2/sub_sub_dir_1', 'sub_dir_3/sub_sub_dir_1', 'sub_dir_3/sub_sub_dir_2', 'sub_dir_3/sub_sub_dir_3']</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T23:08:20.753", "Id": "529620", "Score": "1", "body": "Your example has only two levels. Do you care about deeper hierarchy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T10:05:14.500", "Id": "529659", "Score": "1", "body": "[os.walk](https://docs.python.org/3/library/os.html#os.walk) is what you are looking for. e.g. `[folder for folder, folders, files in os.walk(\".\") if not folders]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:02:45.823", "Id": "529670", "Score": "0", "body": "@vnp No, I don't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:17:29.193", "Id": "529673", "Score": "0", "body": "@stefan Beautiful! Thanks!" } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T16:23:50.120", "Id": "268541", "Score": "0", "Tags": [ "python", "file-system" ], "Title": "Efficient way to construct list of sub-subdirectories in python" }
268541
max_votes
[ { "body": "<p>The os module provides many functions to interact with operating system features, and one such method is <code>os.walk()</code>, which generates and fetch the files and folders in a directory tree. It can traverse the tree either top-down or bottom-up search, and by default, it sets as top-down search.</p>\n<p><strong>What you are looking for is to get the subdirectories with absolute path</strong> and using the <code>os.walk()</code> method you can retrieve the subdirectories in the absolute path.</p>\n<p>Below code gets both files and sub-directories but you can modify it to get only the subfolders according to your need.</p>\n<pre><code># import OS module\nimport os\n\n# List all the files and directories\npath = &quot;C:\\Projects\\Tryouts&quot;\nfor (root, directories, files) in os.walk(path, topdown=False):\n for name in files:\n print(os.path.join(root, name))\n for name in directories:\n print(os.path.join(root, name))\n</code></pre>\n<p>The other alternate way is to use the <code>glob</code> module. The glob module helps you retrieve the files/path matching a specified pattern as the glob supports the wildcard search. We can get both files and folders using the glob module.</p>\n<p>Source: <a href=\"https://itsmycode.com/python-list-files-in-a-directory/\" rel=\"nofollow noreferrer\">List Files and folders in a Directory</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T04:01:37.353", "Id": "529813", "Score": "1", "body": "You've been dropping links to your blog in your answers. Please take a look at [\"how not to be a spammer\"](//codereview.stackexchange.com/help/promotion) and consider making the affiliation more explicitly apparent in your answers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T23:44:47.507", "Id": "268632", "ParentId": "268541", "Score": "1" } } ]
<p>I have a directory that includes a number of subdirectories. Each subdirectories contains subdirectories of its own. I'd like to construct a list of all sub-subdirectories in python. Here is my attempt:</p> <pre><code>import os list_of_lists = [[sub_dir + '/' + sub_subdir for sub_subdir in os.listdir(my_dir + '/' + sub_dir)] for sub_dir in os.listdir(my_dir)] flat_list = [item for sublist in list_of_lists for item in sublist] </code></pre> <p>Is there a better/more efficient/more aesthetic way to construct this?</p> <p>To clarify, here is an example:</p> <pre><code>My_dir | |--sub_dir_1 | | | |--sub_sub_dir_1 | | | |--sub_sub_dir_2 | |--sub_dir_2 | | | |--sub_sub_dir_1 | |--sub_dir_3 | |--sub_sub_dir_1 | |--sub_sub_dir_2 | |--sub_sub_dir_2 </code></pre> <p>In this example, the output that I'm looking for is <code>['sub_dir_1/sub_sub_dir_1', 'sub_dir_1/sub_sub_dir_2', 'sub_dir_2/sub_sub_dir_1', 'sub_dir_3/sub_sub_dir_1', 'sub_dir_3/sub_sub_dir_2', 'sub_dir_3/sub_sub_dir_3']</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T23:08:20.753", "Id": "529620", "Score": "1", "body": "Your example has only two levels. Do you care about deeper hierarchy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T10:05:14.500", "Id": "529659", "Score": "1", "body": "[os.walk](https://docs.python.org/3/library/os.html#os.walk) is what you are looking for. e.g. `[folder for folder, folders, files in os.walk(\".\") if not folders]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:02:45.823", "Id": "529670", "Score": "0", "body": "@vnp No, I don't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T14:17:29.193", "Id": "529673", "Score": "0", "body": "@stefan Beautiful! Thanks!" } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-30T16:23:50.120", "Id": "268541", "Score": "0", "Tags": [ "python", "file-system" ], "Title": "Efficient way to construct list of sub-subdirectories in python" }
268541
max_votes
[ { "body": "<p>The os module provides many functions to interact with operating system features, and one such method is <code>os.walk()</code>, which generates and fetch the files and folders in a directory tree. It can traverse the tree either top-down or bottom-up search, and by default, it sets as top-down search.</p>\n<p><strong>What you are looking for is to get the subdirectories with absolute path</strong> and using the <code>os.walk()</code> method you can retrieve the subdirectories in the absolute path.</p>\n<p>Below code gets both files and sub-directories but you can modify it to get only the subfolders according to your need.</p>\n<pre><code># import OS module\nimport os\n\n# List all the files and directories\npath = &quot;C:\\Projects\\Tryouts&quot;\nfor (root, directories, files) in os.walk(path, topdown=False):\n for name in files:\n print(os.path.join(root, name))\n for name in directories:\n print(os.path.join(root, name))\n</code></pre>\n<p>The other alternate way is to use the <code>glob</code> module. The glob module helps you retrieve the files/path matching a specified pattern as the glob supports the wildcard search. We can get both files and folders using the glob module.</p>\n<p>Source: <a href=\"https://itsmycode.com/python-list-files-in-a-directory/\" rel=\"nofollow noreferrer\">List Files and folders in a Directory</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T04:01:37.353", "Id": "529813", "Score": "1", "body": "You've been dropping links to your blog in your answers. Please take a look at [\"how not to be a spammer\"](//codereview.stackexchange.com/help/promotion) and consider making the affiliation more explicitly apparent in your answers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-03T23:44:47.507", "Id": "268632", "ParentId": "268541", "Score": "1" } } ]
<p>I created a computer program which takes a list of names and dishes chosen. The program then counts how many dishes and which dish are ordered. The result is then returned from a function. The algorithm is currently a brute force O(N*M) where N is the number of dishes and M is the number of people. Below is the code.</p> <pre><code> def count_items(rows, orders): counted = [] has_found = False for row, order in enumerate(orders): has_found = False for col, count in enumerate(counted): if count[0] == order[1]: has_found = True counted[col] = (order[1], counted[col][1] + 1) if not has_found: counted.append((order[1], 1)) return counted def test_count_matching(): assert count_items(0, []) == [] assert count_items(1, [(&quot;Bob&quot;, &quot;apple&quot;)]) == [(&quot;apple&quot;, 1)] assert count_items(2, [(&quot;Bob&quot;, &quot;apple&quot;), (&quot;John&quot;, &quot;apple&quot;)]) == [( &quot;apple&quot;, 2)] assert count_items(2, [(&quot;Bob&quot;, &quot;apple&quot;), (&quot;Bob&quot;, &quot;apple&quot;)]) == [(&quot;apple&quot;, 2)] assert count_items(2, [(&quot;Bob&quot;, &quot;apple&quot;), (&quot;John&quot;, &quot;pear&quot;)]) == [(&quot;apple&quot;, 1), (&quot;pear&quot;, 1)] def tests(): test_count_matching() if __name__ == &quot;__main__&quot;: tests() </code></pre>
[]
{ "AcceptedAnswerId": "268600", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T14:57:33.393", "Id": "268596", "Score": "2", "Tags": [ "python-3.x" ], "Title": "Counting Restaurant Orders" }
268596
accepted_answer
[ { "body": "<ul>\n<li>Add PEP484 typehints</li>\n<li>Don't count things yourself when <code>Counter</code> exists and is more suitable for the task</li>\n<li><code>rows</code> is ignored, so drop it from your arguments list</li>\n<li>Your assertions, main guard and function structure are pretty good; keep it up!</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Tuple, Iterable, Counter\n\n\ndef count_items(orders: Iterable[Tuple[str, str]]) -&gt; Counter[str]:\n return Counter(order for user, order in orders)\n\n\ndef test_count_matching():\n assert count_items([]) == Counter()\n assert count_items([(&quot;Bob&quot;, &quot;apple&quot;)]) == Counter({&quot;apple&quot;: 1})\n assert count_items([(&quot;Bob&quot;, &quot;apple&quot;), (&quot;John&quot;, &quot;apple&quot;)]) == Counter({&quot;apple&quot;: 2})\n assert count_items([(&quot;Bob&quot;, &quot;apple&quot;), (&quot;Bob&quot;, &quot;apple&quot;)]) == Counter({&quot;apple&quot;: 2})\n assert count_items([(&quot;Bob&quot;, &quot;apple&quot;), (&quot;John&quot;, &quot;pear&quot;)]) == Counter({&quot;apple&quot;: 1, &quot;pear&quot;: 1})\n\n\ndef tests():\n test_count_matching()\n\n\nif __name__ == &quot;__main__&quot;:\n tests()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T20:18:10.140", "Id": "529764", "Score": "0", "body": "The counter's keys need to be the last part of the tuple and not include the person's name. The reason is that the kitchen knows the order and needs to know how many times to cook that dish to complete the order for a group of people." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T20:30:42.073", "Id": "529766", "Score": "0", "body": "@AkashPatel _The counter's keys need to be the last part of the tuple and not include the person's name_ - right... which is what's happening here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T20:42:16.480", "Id": "529767", "Score": "0", "body": "Sorry, I think misinterpreted the order variable as having both." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T17:21:09.907", "Id": "268600", "ParentId": "268596", "Score": "3" } } ]
<p>I am trying to create a code for the Basic evapotranspiration equation by Hargreaves. I have attached a screenshot of the equation to be replicated. <a href="https://i.stack.imgur.com/ScK16.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ScK16.png" alt="Hargreaves equation" /></a></p> <p>I want to create a class wherein I can input data which consists of tmin, tmax, tmean, day and lat. I have written the code below based on what I can understand from the equation.</p> <pre><code>import math import numpy as np class Hargreaves: #Instantiating the class def __init__(self, tmin, tmax, tmean, day, lat): self.tmin = tmin self.tmax = tmax self.tmean = tmean self.day = day self.lat = lat # latrad = pyeto.deg2rad(lat) # Convert latitude to radians # day_of_year = datetime.date(2014, 2, 1).timetuple().tm_yday # setting the gsc value @property def gsc(self): return 0.082 # Calculating d @property def d(self): return 0.409 * math.sin((2*math.pi) * (self.day/365) - 1.39) # Calculating ws @property def ws(self): return math.acos(-math.tan(self.lat) * math.tan(self.d)) # Calculating dr @property def dr(self): return 1 + 0.033 * math.cos((2*math.pi) * (self.day/365)) # Calculating Radiation @property def ra(self): return 24 * 60 * (self.gsc/math.pi) * self.dr * self.ws * math.sin(self.lat) * math.sin(self.d) + (math.cos(self.lat) * math.cos(self.d) * math.sin(self.ws)) # Function to calculate evapotranspiration @property def et(self): return (0.0023/2.45) * (self.tmean + 17.8) * ((self.tmax - self.tmin) ** 0.5 ) * self.ra </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T03:55:00.457", "Id": "529908", "Score": "3", "body": "I have concerns about the accuracy of that math (fixed year durations?), but that's a separable issue and I'll have to assume that you need an implementation faithful to this reference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T08:31:21.180", "Id": "529925", "Score": "1", "body": "@Reinderien Correct - [this](https://pyeto.readthedocs.io/en/latest/hargreaves.html) existing implementation the author of the question seems to be aware of (some code copied verbatim!) *does* have proper conversion to Julian Days (the now-commented *.tm_yday*)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T09:06:43.050", "Id": "529932", "Score": "0", "body": "@Reinderien Yes, I had previously converted the day to Julian days, but after looking at my data source, I found that the day variable will be provided in Julian days." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T09:50:50.707", "Id": "529936", "Score": "0", "body": "Why does math in your image seem so complicated but in code so easy? xD" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T19:36:08.560", "Id": "530036", "Score": "1", "body": "Units are wrong for solar constant and extraterrestrial radiation. `a/b/c` is not the same as `a/(b/c)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T07:13:18.600", "Id": "530063", "Score": "0", "body": "Did you write the LaTeX documentation?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T07:24:02.597", "Id": "268639", "Score": "8", "Tags": [ "python", "python-3.x", "object-oriented", "python-2.x", "classes" ], "Title": "Calculate evapotranspiration" }
268639
max_votes
[ { "body": "<p>I wonder if there is a need for a class here? It seems <code>class Hargreaves</code> has no responsibilities and is solely used to compute the evapotranspiration value based on the inputs provided in the constructor. Should a function be used instead?</p>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nimport numpy as np\n\ndef hargreaves(tmin, tmax, tmean, day, lat):\n gsc = 0.082\n dr = 1 + 0.033 * math.cos((2*math.pi) * (day/365))\n d = 0.409 * math.sin((2*math.pi) * (day/365) - 1.39)\n ws = math.acos(-math.tan(lat) * math.tan(d))\n ra = 24 * 60 * (gsc/math.pi) * dr * ws * math.sin(lat) * math.sin(d) + (math.cos(lat) * math.cos(d) * math.sin(ws))\n et = (0.0023/2.45) * (tmean + 17.8) * ((tmax - tmin) ** 0.5 ) * ra\n return et\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T06:11:39.610", "Id": "529914", "Score": "2", "body": "I'd agree if it were the only equation being so treated. In a complex system I'd however expect an interface \"Equation\" with a calculate method that takes another interface \"Parameters\" as input and returns an interface \"Output\" or something of the kind, then multiple implementations of that that can be plugged in as needed. But maybe I'm overthinking things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-05T09:07:25.460", "Id": "529933", "Score": "0", "body": "Great solution, but I want to try to implementing a class for this particular equation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T05:04:08.047", "Id": "529992", "Score": "2", "body": "@jwenting Given that functions are first class types in python I suspect you are overengineering. It sounds like you are trying to duplicate `<class 'function'>`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-04T08:23:14.140", "Id": "268640", "ParentId": "268639", "Score": "35" } } ]
<p>I have written the following function to read multiple CSV files into pandas dataframes. Depending on the use case, the user can pass optional resampling (frequency and method) and/or a date range (start/end). For both options I'd like to check if both keywords were given and raise errors if not.</p> <p>My issue is that reading the CSV files can potentially take quite a bit of time and it's quite frustrating to get the value error 5 minutes after you've called the function. I could duplicate the <code>if</code> statements at the top of the function. However I'd like to know if there is a more readable way or a best practice that avoids having the same <code>if</code>/<code>else</code> statements multiple times.</p> <pre><code>def file_loader(filep,freq:str = None, method: str =None ,d_debut: str =None,d_fin: str =None): df= pd.read_csv(filep,\ index_col=0,infer_datetime_format=True,parse_dates=[0],\ header=0,names=['date',filep.split('.')[0]])\ .sort_index() if d_debut is not None: if d_fin is None: raise ValueError(&quot;Please provide an end timestamp!&quot;) else: df=df.loc[ (df.index &gt;= d_debut) &amp; (df.index &lt;= d_fin)] if freq is not None: if method is None: raise ValueError(&quot;Please provide a resampling method for the given frequency eg. 'last' ,'mean'&quot;) else: ## getattr sert à appeler ...resample(freq).last() etc avec les kwargs en string ex: freq='1D' et method ='mean' df= getattr(df.resample(freq), method)() return df </code></pre>
[]
{ "AcceptedAnswerId": "268719", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T13:19:44.563", "Id": "268717", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Read CSV, with date filtering and resampling" }
268717
accepted_answer
[ { "body": "<p>It's normal to do the parameter checking first:</p>\n<pre><code>def file_loader(filep, freq: str = None, method: str = None,\n d_debut: str = None, d_fin: str = None):\n if d_debut is not None and d_fin is None:\n raise ValueError(&quot;Please provide an end timestamp!&quot;)\n if freq is not None and method is None:\n raise ValueError(&quot;Please provide a resampling method for the given frequency e.g. 'last' ,'mean'&quot;)\n</code></pre>\n<p>You might prefer to check that <code>d_fin</code> and <code>d_debut</code> are either both provided or both defaulted, rather than allowing <code>d_fin</code> without <code>d_debut</code> as at present:</p>\n<pre><code> if (d_debut is None) != (d_fin is None):\n raise ValueError(&quot;Please provide both start and end timestamps!&quot;)\n</code></pre>\n<p>Then after loading, the conditionals are simple:</p>\n<pre><code> if d_debut is not None:\n assert(d_fin is not None) # would have thrown earlier\n df = df.loc[df.index &gt;= d_debut and df.index &lt;= d_fin]\n \n if freq is not None:\n assert(method is not None) # would have thrown earlier\n df = getattr(df.resample(freq), method)()\n</code></pre>\n<p>The assertions are there to document something we know to be true. You could omit them safely, but they do aid understanding.</p>\n<hr />\n<p>It may make sense to provide a useful default <code>method</code> rather than None. Similarly, could the <code>df.index &gt;= d_debut and df.index &lt;= d_fin</code> test be adapted to be happy with one or the other cutoff missing? For example:</p>\n<pre><code> if d_debut is not None or d_fin is not None:\n df = df.loc[(d_debut is None or df.index &gt;= d_debut) and \n (d_fin is None or df.index &lt;= d_fin)]\n</code></pre>\n<p>Then we wouldn't need the parameter checks at all.</p>\n<hr />\n<p>Code style - please take more care with whitespace (consult PEP-8) for maximum readability. Lots of this code seems unnecessarily bunched-up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T14:29:45.290", "Id": "530019", "Score": "0", "body": "Thanks for your answer. I'd rather the function force the user to understand exactly what data he is getting, hence the strict checks. I don't understand why you have assert statements. As you've commented, errors would have been raised at the top. And my bad for the styling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T14:40:38.153", "Id": "530022", "Score": "0", "body": "The asserts are there to document something we know to be true. You could omit them safely, but they do aid understanding." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T14:20:00.633", "Id": "268719", "ParentId": "268717", "Score": "1" } } ]
<p>I am currently finalising the class for a trading strategy and wanted to know if the below could be re-written in a shorter way that will let it run faster?</p> <p>This is PCA1 df:</p> <pre><code> USDJPY EURUSD GBPUSD AUDUSD GBPAUD date pca_component 2019-10-08 weights_2 0.438064 -0.546646 0.433956 0.411839 0.389035 2019-10-09 weights_2 -0.976341 -0.002841 -0.089620 -0.010523 0.196488 2019-10-10 weights_2 -0.971039 -0.009815 0.214701 0.048983 -0.092149 2019-10-11 weights_2 -0.747259 0.104055 -0.174377 -0.287954 0.563429 2019-10-14 weights_2 0.026438 -0.040705 0.715500 -0.200801 -0.667370 ... ... ... ... ... ... ... 2021-09-29 weights_2 0.882239 -0.018798 0.355097 0.279886 -0.129888 2021-09-30 weights_2 0.328128 -0.901789 -0.062934 -0.061846 0.267064 2021-10-01 weights_2 0.954694 0.020833 -0.111151 0.250181 -0.114808 2021-10-04 weights_2 -0.653506 -0.490579 -0.296858 -0.483868 -0.100047 2021-10-05 weights_2 0.221695 0.738876 0.156838 0.322064 0.525919 </code></pre> <p>Backtesting function - just for background</p> <pre><code>import bt # backtesting library # Backtesting package def backtesting(self, signal, price, commission, initial_capital=10000, strategy_name='Strategy', progress_bar=False): # Define the strategy bt_strategy = bt.Strategy(strategy_name, [bt.algos.WeighTarget(signal), bt.algos.Rebalance()]) def my_comm(q, p): return commission bt_backtest = bt.Backtest(bt_strategy, price, initial_capital=initial_capital, commissions=my_comm, progress_bar=progress_bar, integer_positions=True) bt_result = bt.run(bt_backtest) return bt_result, bt_backtest </code></pre> <p>Now, the code:</p> <pre><code>store_nlargest = [] for i in range(5, 10): n_largest_weights = PCA1.nlargest(i, returns.columns) store_nlargest.append(n_largest_weights) store_df = [] results = [] for i in range(len(store_nlargest)): create_df = pd.DataFrame(store_nlargest [i]) labels = [f&quot;Part_{u+1}&quot; for u in range(len(store_nlargest))] store_df .append(create_df) df_concat = pd.concat(store_df, keys=labels) weights = df_concat[df_concat.index.get_level_values(0)==labels[i]] weights = weights.droplevel(1) backtest_returns = backtesting(weights, prices, 3, initial_capital=10000000, strategy_name='Strategy', progress_bar=True) results.append(backtest_returns ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T19:14:35.657", "Id": "530034", "Score": "1", "body": "Please revisit your indentation - it's not going to work in its current state" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T21:44:05.510", "Id": "530040", "Score": "1", "body": "I'm new to codereview so I don't know if this should be answer or comment. But if you want better performance, you don't need to call .nlargest multiple times. Just call it with the largest value (9) and select the first i rows. And you don't need to create an intermediary dataframe and put them in lists. It would become less readable but generator expressions would probably be faster. Then again I really don't understand why you're concatenating dataframes and selecting the one you created in that loop? The values of create_df and weights are identical?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T02:31:50.930", "Id": "530052", "Score": "0", "body": "Yeah, I made errors in my original code. I have made amends which is above though I will try your largest value suggestion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T02:52:08.033", "Id": "530054", "Score": "2", "body": "I rolled back the last edit. It is against this review policy to update the code after the answer has been posted., because it invalidates the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T06:59:23.253", "Id": "530059", "Score": "0", "body": "@kubatucka, those are good observations about the code - please write an answer, and earn yourself some reputation points!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T18:17:54.453", "Id": "530128", "Score": "1", "body": "@vpn; Ok, but it sounds like the original code was not _correct_. Vote to close? (Sorry @Kale!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-08T13:26:17.647", "Id": "530174", "Score": "0", "body": "Rather than add or alter the code after an answer, post a follow up question with the correct code. Link the follow up question to this question. Accept the answer to this question." } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T17:52:45.777", "Id": "268726", "Score": "-2", "Tags": [ "python", "performance" ], "Title": "A custom trading strategy" }
268726
max_votes
[ { "body": "<p>The structure of your code is weird; are you sure it's doing what you want? If it is, <em>strongly</em> consider adding comments or better variable names or something to make it clearer what it's supposed to be doing. Without such explanation, it looks like you have code inside your loop that ought to go outside it.</p>\n<p>That said, I think this is the same behavior as what you've written:</p>\n<pre class=\"lang-py prettyprint-override\"><code>store_nlargest = [PCA1.nlargest(i, returns.columns)\n for i\n in range(5, 10)]\nlabels = [f&quot;Part_{u+1}&quot; for (u, _) in enumerate(store_nlargest)]\n\nstore_df = [] # persistent? reused? \n\ndef make_weights(i, nlargest):\n store_df.append(pd.DataFrame(nlargest)) # still contains data from prior call?\n df_concat = pd.concat(store_df, keys=labels) # needs better name.\n return df_concat[\n df_concat.index.get_level_values(0) == labels[i]\n ].droplevel(1)\n\nresults = [backtesting(make_weights(i, nlargest), prices, 3,\n initial_capital=10000000,\n strategy_name='Strategy',\n progress_bar=True)\n for (i, nlargest)\n in enumerate(store_nlargest)]\n</code></pre>\n<p>This isn't perfect, but I think it does a better job of making its weirdness explicit. You could make a case that the <code>results</code> list-comprehension should still be a <code>for</code> loop because it contains mutation of <code>store_df</code> as a side-effect; I don't really understand what supposed to be happening there so I won't take a side.</p>\n<p>A lot of folks in python like to use lists for everything, but they're not <em>perfect</em> for most things. They're mutable, and it's nice to have everything that <em>can</em> be immutable be immutable. They're also &quot;eager&quot;, whereas lazy generators aren't much more work to write (but do require careful use).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T02:28:36.580", "Id": "530051", "Score": "0", "body": "You are right the code does not do what I wanted it to do - I made blunders. I have updated it, though the issue is speed is more speed than length. I have updated the code which does what I need it to do. It creates weights of the assets based on the nlargest n range and then runs the backtest. Is there a way to speed it up?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-11T02:42:41.553", "Id": "530317", "Score": "0", "body": "Is there an `nlargest` outside `make_weights(i, nlargest)`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T19:20:10.257", "Id": "268728", "ParentId": "268726", "Score": "2" } } ]
<p>I am currently finalising the class for a trading strategy and wanted to know if the below could be re-written in a shorter way that will let it run faster?</p> <p>This is PCA1 df:</p> <pre><code> USDJPY EURUSD GBPUSD AUDUSD GBPAUD date pca_component 2019-10-08 weights_2 0.438064 -0.546646 0.433956 0.411839 0.389035 2019-10-09 weights_2 -0.976341 -0.002841 -0.089620 -0.010523 0.196488 2019-10-10 weights_2 -0.971039 -0.009815 0.214701 0.048983 -0.092149 2019-10-11 weights_2 -0.747259 0.104055 -0.174377 -0.287954 0.563429 2019-10-14 weights_2 0.026438 -0.040705 0.715500 -0.200801 -0.667370 ... ... ... ... ... ... ... 2021-09-29 weights_2 0.882239 -0.018798 0.355097 0.279886 -0.129888 2021-09-30 weights_2 0.328128 -0.901789 -0.062934 -0.061846 0.267064 2021-10-01 weights_2 0.954694 0.020833 -0.111151 0.250181 -0.114808 2021-10-04 weights_2 -0.653506 -0.490579 -0.296858 -0.483868 -0.100047 2021-10-05 weights_2 0.221695 0.738876 0.156838 0.322064 0.525919 </code></pre> <p>Backtesting function - just for background</p> <pre><code>import bt # backtesting library # Backtesting package def backtesting(self, signal, price, commission, initial_capital=10000, strategy_name='Strategy', progress_bar=False): # Define the strategy bt_strategy = bt.Strategy(strategy_name, [bt.algos.WeighTarget(signal), bt.algos.Rebalance()]) def my_comm(q, p): return commission bt_backtest = bt.Backtest(bt_strategy, price, initial_capital=initial_capital, commissions=my_comm, progress_bar=progress_bar, integer_positions=True) bt_result = bt.run(bt_backtest) return bt_result, bt_backtest </code></pre> <p>Now, the code:</p> <pre><code>store_nlargest = [] for i in range(5, 10): n_largest_weights = PCA1.nlargest(i, returns.columns) store_nlargest.append(n_largest_weights) store_df = [] results = [] for i in range(len(store_nlargest)): create_df = pd.DataFrame(store_nlargest [i]) labels = [f&quot;Part_{u+1}&quot; for u in range(len(store_nlargest))] store_df .append(create_df) df_concat = pd.concat(store_df, keys=labels) weights = df_concat[df_concat.index.get_level_values(0)==labels[i]] weights = weights.droplevel(1) backtest_returns = backtesting(weights, prices, 3, initial_capital=10000000, strategy_name='Strategy', progress_bar=True) results.append(backtest_returns ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T19:14:35.657", "Id": "530034", "Score": "1", "body": "Please revisit your indentation - it's not going to work in its current state" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T21:44:05.510", "Id": "530040", "Score": "1", "body": "I'm new to codereview so I don't know if this should be answer or comment. But if you want better performance, you don't need to call .nlargest multiple times. Just call it with the largest value (9) and select the first i rows. And you don't need to create an intermediary dataframe and put them in lists. It would become less readable but generator expressions would probably be faster. Then again I really don't understand why you're concatenating dataframes and selecting the one you created in that loop? The values of create_df and weights are identical?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T02:31:50.930", "Id": "530052", "Score": "0", "body": "Yeah, I made errors in my original code. I have made amends which is above though I will try your largest value suggestion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T02:52:08.033", "Id": "530054", "Score": "2", "body": "I rolled back the last edit. It is against this review policy to update the code after the answer has been posted., because it invalidates the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T06:59:23.253", "Id": "530059", "Score": "0", "body": "@kubatucka, those are good observations about the code - please write an answer, and earn yourself some reputation points!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T18:17:54.453", "Id": "530128", "Score": "1", "body": "@vpn; Ok, but it sounds like the original code was not _correct_. Vote to close? (Sorry @Kale!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-08T13:26:17.647", "Id": "530174", "Score": "0", "body": "Rather than add or alter the code after an answer, post a follow up question with the correct code. Link the follow up question to this question. Accept the answer to this question." } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T17:52:45.777", "Id": "268726", "Score": "-2", "Tags": [ "python", "performance" ], "Title": "A custom trading strategy" }
268726
max_votes
[ { "body": "<p>The structure of your code is weird; are you sure it's doing what you want? If it is, <em>strongly</em> consider adding comments or better variable names or something to make it clearer what it's supposed to be doing. Without such explanation, it looks like you have code inside your loop that ought to go outside it.</p>\n<p>That said, I think this is the same behavior as what you've written:</p>\n<pre class=\"lang-py prettyprint-override\"><code>store_nlargest = [PCA1.nlargest(i, returns.columns)\n for i\n in range(5, 10)]\nlabels = [f&quot;Part_{u+1}&quot; for (u, _) in enumerate(store_nlargest)]\n\nstore_df = [] # persistent? reused? \n\ndef make_weights(i, nlargest):\n store_df.append(pd.DataFrame(nlargest)) # still contains data from prior call?\n df_concat = pd.concat(store_df, keys=labels) # needs better name.\n return df_concat[\n df_concat.index.get_level_values(0) == labels[i]\n ].droplevel(1)\n\nresults = [backtesting(make_weights(i, nlargest), prices, 3,\n initial_capital=10000000,\n strategy_name='Strategy',\n progress_bar=True)\n for (i, nlargest)\n in enumerate(store_nlargest)]\n</code></pre>\n<p>This isn't perfect, but I think it does a better job of making its weirdness explicit. You could make a case that the <code>results</code> list-comprehension should still be a <code>for</code> loop because it contains mutation of <code>store_df</code> as a side-effect; I don't really understand what supposed to be happening there so I won't take a side.</p>\n<p>A lot of folks in python like to use lists for everything, but they're not <em>perfect</em> for most things. They're mutable, and it's nice to have everything that <em>can</em> be immutable be immutable. They're also &quot;eager&quot;, whereas lazy generators aren't much more work to write (but do require careful use).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T02:28:36.580", "Id": "530051", "Score": "0", "body": "You are right the code does not do what I wanted it to do - I made blunders. I have updated it, though the issue is speed is more speed than length. I have updated the code which does what I need it to do. It creates weights of the assets based on the nlargest n range and then runs the backtest. Is there a way to speed it up?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-11T02:42:41.553", "Id": "530317", "Score": "0", "body": "Is there an `nlargest` outside `make_weights(i, nlargest)`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-06T19:20:10.257", "Id": "268728", "ParentId": "268726", "Score": "2" } } ]
<p>To get the Firefox default profile, I am using the following program.</p> <pre><code>import glob from pathlib import Path import re x = glob.glob(str(Path.home()) + '/.mozilla/firefox/*/') r = re.compile(&quot;.*default-release.*&quot;) firefox_default_profile = list(filter(r.match, x))[0] print(firefox_default_profile) </code></pre> <p>The logic is simple. The path looks like <code>~/.mozilla/firefox/5ierwkox.default-release</code>.</p> <p>In the whole path the only variable is the <code>5ierwkox</code>. It varies from person to person.</p> <p>The program works fine, but I am wondering if I have over-complicated the code or not.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-08T09:04:40.093", "Id": "530150", "Score": "1", "body": "What do you mean by \"get the Firefox default profile\"? The full path to the folder it is in? Or something else? Can you [clarify](https://codereview.stackexchange.com/posts/268770/edit)? Please respond by [editing (changing) your question](https://codereview.stackexchange.com/posts/268770/edit), not here in comments (***without*** \"Edit:\", \"Update:\", or similar - the question should appear as if it was written right now)." } ]
{ "AcceptedAnswerId": "268771", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T21:32:24.963", "Id": "268770", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Get the Firefox Default Profile" }
268770
accepted_answer
[ { "body": "<ul>\n<li>You don't need to import <code>glob</code>; <code>pathlib.Path</code> has a <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob\" rel=\"noreferrer\"><code>Path.glob</code></a> method.</li>\n<li>You don't need to import <code>re</code>; you can merge the regex into the glob - <code>.*default-release.*</code> become <code>*default-release*</code>.</li>\n<li>You can use <code>next(...)</code> rather than <code>list(...)[0]</code>.</li>\n<li>By passing <code>None</code> as a second argument to <code>next</code> we can prevent the code from erroring if the user doesn't have a Firefox profile.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import pathlib\n\nprofiles = pathlib.Path.home().glob(&quot;.mozilla/firefox/*default-release*/&quot;)\nfirefox_default_profile = next(profiles, None)\nprint(firefox_default_profile)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T22:13:56.760", "Id": "530133", "Score": "3", "body": "Note. This returns a `Path` object instead of a `str`. (And it will return `None` instead of raising an exception if the default profile cannot be found.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T22:22:05.227", "Id": "530134", "Score": "2", "body": "@AJNeufeld You are certainly correct. Depending on what Python version one is running may mean the code no-longer works as expected. Requiring a call to `str` before being passed to some functions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T22:11:09.160", "Id": "268771", "ParentId": "268770", "Score": "8" } } ]
<p>I found I need to loop through a list to create a brute force algorithm. Therefore, I decided to make a library, but to generalize the result by using a generator. There are three cases which is every single element, every pair of elements, and every triple of elements. The cases store a variable which contains the generator function. Currently, the generator is required to be nested with no parameters inside a function which takes the data structure as a parameter. Therefore, the average space complexity is O(1) in the three cases. The code is below.</p> <pre><code> def test_generator(): yield &quot;a&quot; yield &quot;b&quot; def singles(generator): &quot;&quot;&quot; average time: O(n) where n is the number of yields from generator average space: O(1) &quot;&quot;&quot; for at in generator(): yield at def test_singles(): assert list(singles(test_generator)) == [&quot;a&quot;, &quot;b&quot;] def pairs(generator): &quot;&quot;&quot; average time: O(n * n) where n is the number of yields from generator average space: O(1) &quot;&quot;&quot; first_generator = generator second_generator = generator for first in first_generator(): second_generator = generator for second in second_generator(): yield first, second def test_pairs(): assert list(pairs(test_generator)) == [(&quot;a&quot;, &quot;a&quot;), (&quot;a&quot;, &quot;b&quot;), (&quot;b&quot;, &quot;a&quot;), (&quot;b&quot;, &quot;b&quot;)] def triples(generator): &quot;&quot;&quot; average time: O(n * n * n) where n is the number of yields average sapce: O(1) &quot;&quot;&quot; first_generator = generator second_generator = generator third_generator = generator for first in first_generator(): second_generator = generator for second in second_generator(): third = third_generator for third in third_generator(): yield first, second, third def test_triples(): assert list(triples(test_generator)) == [(&quot;a&quot;, &quot;a&quot;, &quot;a&quot;), (&quot;a&quot;, &quot;a&quot;, &quot;b&quot;), (&quot;a&quot;, &quot;b&quot;, &quot;a&quot;), (&quot;a&quot;, &quot;b&quot;, &quot;b&quot;), (&quot;b&quot;, &quot;a&quot;, &quot;a&quot;), (&quot;b&quot;, &quot;a&quot;, &quot;b&quot;), (&quot;b&quot;, &quot;b&quot;, &quot;a&quot;), (&quot;b&quot;, &quot;b&quot;, &quot;b&quot;)] def tests(): test_singles() test_pairs() test_triples() if __name__ == &quot;__main__&quot;: tests() </code></pre>
[]
{ "AcceptedAnswerId": "268918", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-11T18:50:06.573", "Id": "268884", "Score": "2", "Tags": [ "python", "python-3.x", "generator" ], "Title": "Library to Help Loop with Generators" }
268884
accepted_answer
[ { "body": "<h1>Unnecessary variables</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n &quot;&quot;&quot;\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n &quot;&quot;&quot;\n first_generator = generator \n second_generator = generator \n for first in first_generator():\n second_generator = generator \n for second in second_generator():\n yield first, second \n</code></pre>\n<p>The value of <code>second_generator</code> does not change in the loop. Therefore, the assignment to <code>second_generator</code> in the loop may be omitted.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n &quot;&quot;&quot;\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n &quot;&quot;&quot;\n first_generator = generator \n second_generator = generator \n for first in first_generator():\n for second in second_generator():\n yield first, second \n</code></pre>\n<p>In fact, the value of <code>generator</code> never changes, so <code>first_generator</code> and <code>second_generator</code> always equal <code>generator</code>. Thus <code>first_generator</code> and <code>second_generator</code> are redundant variables and may be omitted entirely.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n &quot;&quot;&quot;\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n &quot;&quot;&quot;\n for first in generator():\n for second in generator():\n yield first, second \n</code></pre>\n<p>Identical improvements may be applied to the <code>triples</code> function.</p>\n<h1>Useless assignment</h1>\n<pre class=\"lang-py prettyprint-override\"><code> third = third_generator \n for third in third_generator():\n yield first, second, third \n</code></pre>\n<p>The assignment to <code>third</code> before the loop is immediately overwritten by the <code>for ... in ...</code> loop statement, which also assigns values to <code>third</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T17:35:33.157", "Id": "268918", "ParentId": "268884", "Score": "0" } } ]
<p>I found I need to loop through a list to create a brute force algorithm. Therefore, I decided to make a library, but to generalize the result by using a generator. There are three cases which is every single element, every pair of elements, and every triple of elements. The cases store a variable which contains the generator function. Currently, the generator is required to be nested with no parameters inside a function which takes the data structure as a parameter. Therefore, the average space complexity is O(1) in the three cases. The code is below.</p> <pre><code> def test_generator(): yield &quot;a&quot; yield &quot;b&quot; def singles(generator): &quot;&quot;&quot; average time: O(n) where n is the number of yields from generator average space: O(1) &quot;&quot;&quot; for at in generator(): yield at def test_singles(): assert list(singles(test_generator)) == [&quot;a&quot;, &quot;b&quot;] def pairs(generator): &quot;&quot;&quot; average time: O(n * n) where n is the number of yields from generator average space: O(1) &quot;&quot;&quot; first_generator = generator second_generator = generator for first in first_generator(): second_generator = generator for second in second_generator(): yield first, second def test_pairs(): assert list(pairs(test_generator)) == [(&quot;a&quot;, &quot;a&quot;), (&quot;a&quot;, &quot;b&quot;), (&quot;b&quot;, &quot;a&quot;), (&quot;b&quot;, &quot;b&quot;)] def triples(generator): &quot;&quot;&quot; average time: O(n * n * n) where n is the number of yields average sapce: O(1) &quot;&quot;&quot; first_generator = generator second_generator = generator third_generator = generator for first in first_generator(): second_generator = generator for second in second_generator(): third = third_generator for third in third_generator(): yield first, second, third def test_triples(): assert list(triples(test_generator)) == [(&quot;a&quot;, &quot;a&quot;, &quot;a&quot;), (&quot;a&quot;, &quot;a&quot;, &quot;b&quot;), (&quot;a&quot;, &quot;b&quot;, &quot;a&quot;), (&quot;a&quot;, &quot;b&quot;, &quot;b&quot;), (&quot;b&quot;, &quot;a&quot;, &quot;a&quot;), (&quot;b&quot;, &quot;a&quot;, &quot;b&quot;), (&quot;b&quot;, &quot;b&quot;, &quot;a&quot;), (&quot;b&quot;, &quot;b&quot;, &quot;b&quot;)] def tests(): test_singles() test_pairs() test_triples() if __name__ == &quot;__main__&quot;: tests() </code></pre>
[]
{ "AcceptedAnswerId": "268918", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-11T18:50:06.573", "Id": "268884", "Score": "2", "Tags": [ "python", "python-3.x", "generator" ], "Title": "Library to Help Loop with Generators" }
268884
accepted_answer
[ { "body": "<h1>Unnecessary variables</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n &quot;&quot;&quot;\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n &quot;&quot;&quot;\n first_generator = generator \n second_generator = generator \n for first in first_generator():\n second_generator = generator \n for second in second_generator():\n yield first, second \n</code></pre>\n<p>The value of <code>second_generator</code> does not change in the loop. Therefore, the assignment to <code>second_generator</code> in the loop may be omitted.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n &quot;&quot;&quot;\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n &quot;&quot;&quot;\n first_generator = generator \n second_generator = generator \n for first in first_generator():\n for second in second_generator():\n yield first, second \n</code></pre>\n<p>In fact, the value of <code>generator</code> never changes, so <code>first_generator</code> and <code>second_generator</code> always equal <code>generator</code>. Thus <code>first_generator</code> and <code>second_generator</code> are redundant variables and may be omitted entirely.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pairs(generator):\n &quot;&quot;&quot;\n average time: O(n * n) where n is the number of yields from generator \n average space: O(1) \n &quot;&quot;&quot;\n for first in generator():\n for second in generator():\n yield first, second \n</code></pre>\n<p>Identical improvements may be applied to the <code>triples</code> function.</p>\n<h1>Useless assignment</h1>\n<pre class=\"lang-py prettyprint-override\"><code> third = third_generator \n for third in third_generator():\n yield first, second, third \n</code></pre>\n<p>The assignment to <code>third</code> before the loop is immediately overwritten by the <code>for ... in ...</code> loop statement, which also assigns values to <code>third</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T17:35:33.157", "Id": "268918", "ParentId": "268884", "Score": "0" } } ]
<p>Find shape of n-dim array that'd be formed from nested list of lists with variable lengths if we were to pad the lists to same length at each nest level. E.g.</p> <pre><code>ls = [[1], [2, 3], [4, 5, 6]] # (3, 3) because ls_padded = [[1, 0, 0], [2, 3, 0], [4, 5, 6]] </code></pre> <h4>Attempt</h4> <pre class="lang-py prettyprint-override"><code>def find_shape(seq): try: len_ = len(seq) except TypeError: return () shapes = [find_shape(subseq) for subseq in seq] return (len_,) + tuple(max(sizes) for sizes in itertools.zip_longest(*shapes, fillvalue=1)) </code></pre> <h4>Problem</h4> <p>Too slow for large arrays. Can it be done faster? <a href="https://replit.com/@OverLordGoldDra/SpryFaintCgi#main.py" rel="nofollow noreferrer">Test &amp; bench code</a>.</p> <p>Solution shouldn't require list values at final nest depth, only basic attributes (e.g. <code>len</code>), as that depth in application contains 1D arrays on GPU (and accessing values moves them back to CPU). It must work on <strong>n-dim arrays</strong>.</p> <p><strong>Exact goal</strong> is to attain such padding, but with choice of padding from left or from right. The data structure is a list of lists that's to form a 5D array, and only the final nest level contains non-lists, which are 1D arrays. First two nest levels have fixed list lengths (can directly form array), and the 1D arrays are of same length, so the only uncertainty is on 3rd and 4th dims.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T01:22:33.863", "Id": "530455", "Score": "0", "body": "Is there a reason you're seemingly rewriting [basic NumPy functionality](https://numpy.org/devdocs/reference/generated/numpy.shape.html) here? Why not use NumPy to manage your arrays? How large/layers deep are you dealing with? Could you write a class abstraction that stores the length upon construction? I can say right off the bat that `(len_,) + tuple(...)` allocates 2 unnecessary objects that just go straight to the garbage collector after the concatenation but this seems like a micro-optimization given that depth would be unlikely to be huge, I'd imagine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T16:08:26.233", "Id": "530501", "Score": "0", "body": "Given that if you know nothing about the sequence, you'll have to check every element recursively, you can't do better algorithmicly speaking. You could maybe optimize the implementation but not much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T18:56:40.187", "Id": "530506", "Score": "0", "body": "@ggorlen End goal is to create the padded n-dim array as described, except need freedom to pad from left or right. I have the full function and `find_shape` is the bottleneck, especially when ran on GPU. Numpy can only create ragged, and not on GPU; Pytorch is used. If you have something in mind for this goal, I can open a question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T01:38:15.817", "Id": "530613", "Score": "0", "body": "What do you mean with \"Solution shouldn't require list values, only basic attributes\"? You can't check a value's attributes without the value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T17:28:10.370", "Id": "530666", "Score": "0", "body": "@don'ttalkjustcode `len(x)` doesn't require knowing `x[0]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T17:34:23.767", "Id": "530668", "Score": "0", "body": "Right, but it requires knowing `x`. And you don't know whether `x` is a list until you look at it. Same for `x[0]`. You need to look at it anyway, because it could be a list. Btw, is that \"Solution shouldn't require list values\" paragraph part of the \"Problem\" section, i.e., you're saying your solution *does* have that problem, i.e., it does \"require list values\"? Or is that paragraph an epilogue to the question, not intended to describe a problem with your solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T17:48:28.820", "Id": "530669", "Score": "0", "body": "Hmm... is it guaranteed that all *numbers* are at the same depth and that there are no lists at that depth? Or could there be cases like `[1, [2, 3]]` or `[4, [], 5]`? And can there be empty lists (your `fillvalue=1` somewhat suggests \"no\")?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T18:36:28.653", "Id": "530671", "Score": "0", "body": "@don'ttalkjustcode Updated. Yes, it's guaranteed, and no empties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T19:09:33.483", "Id": "530674", "Score": "1", "body": "Ok, that allows much optimization. So it's guaranteed 5D and only third and fourth are unknown? That would also allow simpler code, and in that case it would help if your Test & bench code reflected that (that's excellent stuff, btw, I wish every question was that helpful :-), so that solutions making those assumptions would work there." } ]
{ "AcceptedAnswerId": "269021", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-12T23:35:09.490", "Id": "268932", "Score": "1", "Tags": [ "python", "array", "iteration", "nested" ], "Title": "Variable length nested list of lists pad shape" }
268932
accepted_answer
[ { "body": "<p>From your question:</p>\n<blockquote>\n<p>The data structure is a list of lists that's to form a 5D array, and only the final nest level contains non-lists, which are 1D arrays. First two nest levels have fixed list lengths (can directly form array), and the 1D arrays are of same length, so the only uncertainty is on 3rd and 4th dims.</p>\n</blockquote>\n<p>From your comment:</p>\n<blockquote>\n<p>and no empties</p>\n</blockquote>\n<p>We can make it much faster by taking advantage of that specification.</p>\n<p>Your solution walks over <em>everything</em>. Including the numbers, at the recursion leafs. Even always catching exceptions there, and <a href=\"https://docs.python.org/3/faq/design.html#how-fast-are-exceptions\" rel=\"nofollow noreferrer\">&quot;catching an exception is expensive&quot;</a></p>\n<p>Instead, for the fixed-size dimensions just take the first length, and for the others run over all their lists and take the maximum length.</p>\n<pre><code>from itertools import chain\n\ndef find_shape_new(seq):\n flat = chain.from_iterable\n return (\n len(seq),\n len(seq[0]),\n max(map(len, flat(seq))),\n max(map(len, flat(flat(seq)))),\n len(seq[0][0][0][0]),\n )\n</code></pre>\n<p>(Only partially tested, as your Test &amp; bench code doesn't adhere to your specification.)</p>\n<p>Could also be generalized, maybe like this:</p>\n<pre><code>def find_shape_new(seq, num_dims=None, fixed_dims=None):\n ...\n</code></pre>\n<p>Parameters:</p>\n<ul>\n<li><code>fixed_dims</code> would be a set naming the fixed dimensions. Like <code>{0, 1, 4}</code> or <code>{1, 2, 5}</code> for your specification above. For each fixed dimension, the function would use the <code>len(seq[0][0][0][0])</code> way, and for each non-fixed dimension, it would use the <code>max(map(len, flat(flat(seq))))</code> way.</li>\n<li><code>num_dims</code> would tell the dimensionality, e.g., for a 5D array it would be 5. If unknown, represented by <code>None</code>, you'd just keep going until you reach a number instead of a list. That would involve looking at a number, but only at one.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T21:14:29.363", "Id": "530678", "Score": "0", "body": "So basically take short route for dims 0, 1, 4 and apply a faster `find_shape_old` on the rest? It's what I had in mind but hoped there's better, though it may very well be that better isn't needed - will test this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T22:24:11.357", "Id": "530681", "Score": "0", "body": "@OverLordGoldDragon That, plus not looking at dim 5. It should be a lot better. Looking forward to your results. This is visiting almost only what needs to be visited, so I don't see how you'd hope for something better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T19:06:11.347", "Id": "530857", "Score": "0", "body": "I omitted the simplifying parts to avoid \"divide and conquer\" solutions, instead focusing on the irreducible worst-case. Perhaps exhaustive iteration is the only way, which shifts optimization to parallelization. Your answer includes things I didn't think of, and I like that it can easily target the fixed dims, so I'll take it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T20:12:53.270", "Id": "269021", "ParentId": "268932", "Score": "1" } } ]
<p>I have the following code snippet:</p> <pre><code>for index, row in df.iterrows(): if row['MSI Status'] == 'MSS': print(row['Patient ID']) for dirpath, dirnames, filenames in os.walk(path): for dirname in dirnames: joined_path = os.path.join(path, dirname) if row['Patient ID'] in dirname: shutil.copytree(joined_path, os.path.join('/SeaExp/mona/MSS_Status/MSS', dirname)) if row['MSI Status'] == 'MSI-H': print(row['Patient ID']) for dirpath, dirnames, filenames in os.walk(path): for dirname in dirnames: joined_path = os.path.join(path, dirname) if row['Patient ID'] in dirname: shutil.copytree(joined_path, os.path.join('/SeaExp/mona/MSS_Status/MSI-H', dirname)) </code></pre> <p>I only have 100 rows in my df but I have many directories in my os.walk. I understand my code is not written well or not efficient and is slow and I hope to get some feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T19:03:40.760", "Id": "530507", "Score": "1", "body": "What does the file structure look like?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T17:55:19.713", "Id": "268961", "Score": "0", "Tags": [ "python", "file-system", "pandas" ], "Title": "Combining iterrows of pandas with os.walk given I have a lot of directories" }
268961
max_votes
[ { "body": "<ul>\n<li><p>First off, you seem to have a typo: <code>os.path.join(path, dirname)</code> should almost certainly be <code>os.path.join(dirpath, dirname)</code>. The only way I could see this not causing problems is if all the directories you want to copy are immediate children of <code>path</code> - and in that case you don't want <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\"><code>os.walk</code></a> at all, but should instead use <a href=\"https://docs.python.org/3/library/os.html#os.scandir\" rel=\"nofollow noreferrer\"><code>os.scandir</code></a>. But going forward I'll assume that <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\"><code>os.walk</code></a> is in fact needed here</p>\n</li>\n<li><p>Since the target directory's name matches the <code>MSI Status</code> field, and those two loops are otherwise identical, it'd be easy to merge those two loops into a single one, ending with something like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>destination = os.path.join(&quot;/SeaExp/mona/MSS_Status&quot;, row[&quot;MSI Status&quot;], dirname)\nshutil.copytree(joined_path, destination)\n</code></pre>\n</li>\n<li><p>If those are the only two statuses that are possible, you'd be able to get rid of the <code>if</code>s entirely. If not, you can still simplify it to something akin to <code>if row['MSI Status'] in {'MSI-H', 'MSS'}:</code></p>\n</li>\n<li><p>Back to <a href=\"https://docs.python.org/3/library/os.html#os.walk\" rel=\"nofollow noreferrer\"><code>os.walk</code></a> issues, once you've found a directory to copy, will you ever need to copy any subdirectory of that directory? For example, for a patient with ID <code>somebody</code>, would you want/need to copy <em>both</em> <code>./somebody/</code> and <code>./somebody/appointment_history/somebody_2020-12-13</code> independently? If not, you should modify the <code>dirnames</code> list while iterating to avoid descending into the directories you've already copied - which could perhaps look like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for dirpath, dirnames, filenames in os.walk(path):\n remaining = []\n\n for dirname in dirnames:\n if row['Patient ID'] in dirname:\n source = os.path.join(path, dirname)\n destination = os.path.join('/SeaExp/mona/MSS_Status', row['MSI Status'], dirname)\n else:\n remaining.append(dirname)\n\n dirnames[:] = remaining # Note the use of [:] to update in-place\n</code></pre>\n</li>\n<li><p>Finally, pandas' <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iterrows.html\" rel=\"nofollow noreferrer\"><code>iterrows</code></a> is almost certainly faster than <code>os.walk</code>, so if we're going to do one of those multiple times, it might be best to let that be the <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iterrows.html\" rel=\"nofollow noreferrer\"><code>iterrows</code></a>. You might save time by turning your code inside-out like so:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for dirpath, dirnames, filenames in os.walk(path):\n remaining = []\n\n for index, row in df.iterrows():\n for dirname in dirnames:\n if row['Patient ID'] in dirname:\n source = os.path.join(dirpath, dirname)\n destination = os.path.join(\n '/SeaExp/mona/MSS_Status',\n row['MSI Status'],\n dirname\n )\n shutil.copytree(source, destination)\n else:\n remaining.append(dirname)\n\n dirnames[:] = remaining\n\n\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T11:06:16.740", "Id": "530560", "Score": "1", "body": "If one were to combine our answers, your final bullet point would have the benefit of never walking down trees we've copied from ever. Gaining an even larger benefit than either of our answers would have standing alone. Nice answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-13T20:30:31.630", "Id": "268966", "ParentId": "268961", "Score": "5" } } ]
<p>I have very recently learned some Python and found out about web scraping.</p> <p>This is my first bash at writing some code to get a playlist from a site I had previously been copying and pasting. I would love it if someone could have a look at the code and review it for me. Any advice, tips, suggestions welcome.</p> <p>sample URL - <a href="https://www.bbc.co.uk/programmes/m000yzhb" rel="nofollow noreferrer">https://www.bbc.co.uk/programmes/m000yzhb</a></p> <pre><code># Create environment by importing required functions from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup # Ask user for URL of playlist my_url = input(&quot;paste the URL here: &quot;) # Grab and process URL. Having uClient.Close() in this section bugged out - not sure why. uClient = uReq(my_url) page_html = uClient.read() page_soup = soup(page_html, &quot;html.parser&quot;) # Prep CSV file for writing. filename = &quot;take the floor.csv&quot; f = open(filename,&quot;w&quot;) # Find the section with the date of the broadcast and assign it to a variable. containers = page_soup.findAll(&quot;div&quot;,{&quot;class&quot;:&quot;broadcast-event__time beta&quot;}) date_container = containers[0] # Pull the exact info and assign it to a variable. show_date = str(date_container[&quot;title&quot;]) # Find the section with the playlist in it and assign it to a variable. containers = page_soup.findAll(&quot;div&quot;,{&quot;class&quot;:&quot;feature__description centi&quot;}) title_container = containers[0] # Pull the exact info and assign it to a variable. dance_title = str(title_container) # Clean the data a little dance1 = dance_title.replace(&quot;&lt;br/&gt;&quot; , &quot; &quot;) dance2 = dance1.replace(&quot;&lt;p&gt;&quot;, &quot; &quot;) #Write to CSV. f.write(show_date + &quot;,&quot; + dance2.replace(&quot;&lt;/p&gt;&quot;,&quot;&quot;)) f.close() </code></pre> <p>Notes: My next steps with this code (but I dont know where to start) would be to have this code run automatically once per month finding the webpages itself.(4 most recent broadcasts)</p> <p>Also worth noting is that I have added some code in here to show some data manipulation but I actually do this manipulation with a macro in excel since I found it easier to get the results I wanted that way.</p> <p>I have really enjoyed this project. I have learnt a huge amount and it has saved me a bunch of time manually copying and pasting this data to a word document.</p> <p>Thank you for taking this time to look at this any suggestions or tips are greatly appreciated!</p> <p>Cheers</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T16:38:00.860", "Id": "268990", "Score": "2", "Tags": [ "python", "web-scraping", "beautifulsoup" ], "Title": "Web scraping playlist from website and writing to CSV" }
268990
max_votes
[ { "body": "<p>I don't think the CSV format is benefiting you all that much here. You haven't written header names, and it seems you only have one column - and maybe only one row? Either you should have multiple columns with headers, or give up on CSV and just call it a text file.</p>\n<p>Otherwise:</p>\n<ul>\n<li>Prefer Requests over <code>urllib</code></li>\n<li>Check for errors during the HTTP request</li>\n<li>If possible, constrain the part of the DOM that BeautifulSoup parses, using a strainer</li>\n</ul>\n<p>The first part could look like:</p>\n<pre><code>def download_programme(session: Session, name: str) -&gt; str:\n with session.get(\n 'https://www.bbc.co.uk/programmes/' + name,\n headers={'Accept': 'text/html'},\n ) as response:\n response.raise_for_status()\n return response.text\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T19:49:06.057", "Id": "268997", "ParentId": "268990", "Score": "2" } } ]
<p>I need to classify URLs from a DataFrame and modify it by exact match and contains conditions:</p> <pre><code>class PageClassifier: def __init__(self, contains_pat, match_pat): &quot;&quot;&quot; :param match_pat: A dict with exact match patterns in values as lists :type match_pat: dict :param contains_pat: A dict with contains patterns in values as lists :type contains_pat: dict &quot;&quot;&quot; self.match_pat = match_pat self.contains_pat = contains_pat def worker(self, data_frame): &quot;&quot;&quot; Classifies pages by type (url patterns) :param data_frame: DataFrame to classify :return: Classified by URL patterns DataFrame &quot;&quot;&quot; try: for key, value in self.contains_pat.items(): reg_exp = '|'.join(value) data_frame.loc[data_frame['url'].str.contains(reg_exp, regex=True), ['page_class']] = key for key, value in self.match_pat.items(): data_frame.loc[data_frame['url'].isin(value), ['page_class']] = key return data_frame except Exception as e: print('page_classifier(): ', e, type(e)) df = pd.read_csv('logs.csv', delimiter='\t', parse_dates=['date'], chunksize=1000000) contains = {'catalog': ['/category/', '/tags', '/search'], 'resources': ['.css', '.js', '.woff', '.ttf', '.html', '.php']} match = {'info_pages': ['/information', '/about-us']} classify = PageClassifier(contains, match) new_pd = pd.DataFrame() for num, chunk in enumerate(df): print('Start chunk ', num) new_pd = pd.concat([new_pd, classify.worker(chunk)]) new_pd.to_csv('classified.csv', sep='\t', index=False) </code></pre> <p>But it is very slow and takes to much RAM when I work with files over 10GB. How can I search and modify data faster? I need &quot;exact match&quot; and &quot;contains&quot; patterns searching in one func.</p>
[]
{ "AcceptedAnswerId": "269005", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-14T19:00:27.540", "Id": "268992", "Score": "1", "Tags": [ "python", "python-3.x", "csv", "pandas" ], "Title": "How to speed up the search by patterns matching and modifying a DataFrame" }
268992
accepted_answer
[ { "body": "<p>The first thing I notice here that will tank performance the most is:</p>\n<pre><code>new_pd = pd.concat([new_pd, classify.worker(chunk)])\n</code></pre>\n<p>cs95 outlines this issue very well in <a href=\"https://stackoverflow.com/a/56746204/15497888\">their answer here</a>. The general advice is &quot;NEVER grow a DataFrame!&quot;. Essentially creating a new copy of the DataFrame in each iteration is quadratic in time complexity as the entire DataFrame is copied each iteration, <em>and</em> the DataFrame only gets larger which ends up costing more and more time.</p>\n<p>If we wanted to improve this approach we might consider something like:</p>\n<pre><code>df_list = []\nfor num, chunk in enumerate(df):\n df_list.append(classify.worker(chunk))\n\nnew_pd = pd.concat(df_list, ignore_index=True)\nnew_pd.to_csv('classified.csv', sep='\\t', index=False)\n</code></pre>\n<p>However, assuming we don't ever need the entire DataFrame in memory at once, and given that our <code>logs.csv</code> is so large that we need to <em>read it</em> in chunks, we should also consider <em>writing out</em> our DataFrame in chunks:</p>\n<pre><code>for num, chunk in enumerate(df):\n classify.worker(chunk).to_csv(\n 'classified.csv', sep='\\t', index=False,\n header=(num == 0), # only write the header for the first chunk,\n mode='w' if num == 0 else 'a' # append mode after the first iteration\n )\n</code></pre>\n<hr />\n<p>In terms of reading in the file, we appear to only using the <code>url</code> and <code>page_class</code> columns. Since we're not using the DateTime functionality of the <code>date</code> column we don't need to take the time to parse it.</p>\n<pre><code>df = pd.read_csv('logs.csv', delimiter='\\t', chunksize=1000000)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T07:00:45.647", "Id": "530620", "Score": "0", "body": "Thanks for your answer. Especially for \"header=(num == 0), mode='w' if num == 0 else 'a'\". This was very useful example for my practice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T04:35:09.097", "Id": "269005", "ParentId": "268992", "Score": "2" } } ]
<blockquote> <p><strong>Input</strong><br /> The first line of input contains a string s: the word misspelled by your partner. Assume that your partner did not add or remove any letters; they only replaced letters with incorrect ones. The next line contains a single positive integer n indicating the number of possible valid words that your partner could have meant to write. Each of the next n lines contains each of these words. There is guaranteed to be at least one word of the same length as the misspelled word.</p> <p><strong>Output</strong><br /> Output a single word w: the word in the dictionary of possible words closest to the misspelled word. &quot;Closeness&quot; is defined as the minimum number of different characters. If there is a tie, choose the word that comes first in the given dictionary of words.</p> </blockquote> <pre><code>Example: input deat 6 fate feet beat meat deer dean output beat </code></pre> <blockquote> </blockquote> <pre><code>s = input() n = int(input()) count_list = [] word_list = [] final = [] count = 0 for i in range(n): N = input() for j in range(len(N)): if s[j] == N[j]: count += 1 count_list.append(count) word_list.append(N) count = 0 max_c = count_list[0] for i in range(len(count_list)): if count_list[i] &gt; max_c: max_c = count_list[i] indices = [index for index, val in enumerate(count_list) if val == max_c] for i in range(len(indices)): final.append(word_list[indices[i]]) print(final[0]) </code></pre> <p>This is what I managed to write. This code passed 3 test cases but failed the 4th. I tried to do final.sort() to put them in alphabetical order, but it fails on the 2nd test case (I can only see the 1st test case which is included in this post). What can I do to fix this? The code only allows words with the same number of characters as the control string, which might be causing the wrong test case since one of the test cases might have more or less characters than the control string? Can someone help?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T13:59:56.697", "Id": "530713", "Score": "0", "body": "Related: [Calculate Levenshtein distance between two strings in Python](https://codereview.stackexchange.com/questions/217065/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T12:12:12.450", "Id": "530764", "Score": "0", "body": "Please add a link to the programming challenge." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T10:00:30.540", "Id": "269031", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Find the closest match to a string" }
269031
max_votes
[ { "body": "<h1>Code Review</h1>\n<p>Your code doesn't pass all of the test cases, so by some definitions, it is not ready for a code review. However, it is close enough to working and has several code-habits that should be corrected, that I'll give you a Code Review anyway.</p>\n<h2>Variable names</h2>\n<p>Both <code>count_list</code> and <code>word_list</code> are nice, descriptive variable names. <code>final</code> is ok, but not very descriptive (final what?). However, variable names like <code>s</code>, <code>n</code>, <code>N</code> are terrible, especially in global scope. The fact the <code>n</code> is a count, and <code>N</code> is a string is outright confusing.</p>\n<p><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP 8: The Style Guide for Python Code</a> recommends all variable names should be in <code>snake_case</code>. Uppercase letters are used only in <code>NAMED_CONSTANTS</code> and <code>ClassNames</code>.</p>\n<h2>Variable Types</h2>\n<p><code>count_list</code> and <code>word_list</code> are parallel data structures. <code>count_list[j]</code> is the count of matching letters in <code>word_list[j]</code>.</p>\n<p>The would be better expressed as a dictionary. Ie) <code>match_length = {}</code> and <code>match_length[word] = count</code>. As of Python 3.6 (December 2016), dictionaries are ordered by insertion order, so determining which word came before other words is still possible.</p>\n<h2>Throw-away variables</h2>\n<p>In the first loop, <code>for i in range(n):</code>, the variable <code>i</code> is never used. PEP-8 recommends using <code>_</code> for these kind of variables. Ie) <code>for _ in range(n):</code></p>\n<h2>Initialize before use</h2>\n<p>You have:</p>\n<pre class=\"lang-py prettyprint-override\"><code>count = 0\n\nfor i in range(n):\n ...\n \n for j in range(len(N)):\n if s[j] == N[j]:\n count += 1 \n ...\n count = 0\n</code></pre>\n<p>The variable <code>count</code> is set to zero in two different statements. The first initialization is before the outer loop, so it looks like it might be counting items found in the outer loop, but it is not; it is counting in the inner loop. This should be reorganized:</p>\n<pre class=\"lang-py prettyprint-override\"><code>\nfor i in range(n):\n ...\n count = 0\n \n for j in range(len(N)):\n if s[j] == N[j]:\n count += 1 \n ...\n</code></pre>\n<p>Now you only have one location where <code>count</code> is reset to zero. The code should be easier to understand.</p>\n<h2>Loop over values, not indices</h2>\n<p>The inner loop iterates over the indices of <code>N</code>, assigning successive values to <code>j</code>, but the contents of the loop only ever uses <code>j</code> as an index: <code>s[j]</code> and <code>N[j]</code>. Python is optimized for iterating over the values in containers.</p>\n<pre class=\"lang-py prettyprint-override\"><code>\n count = 0\n for s_letter, candidate_word_letter in zip(s, N):\n if s_letter == candidate_word_letter:\n count += 1\n</code></pre>\n<h2>Built in functions</h2>\n<pre class=\"lang-py prettyprint-override\"><code>max_c = count_list[0]\nfor i in range(len(count_list)):\n if count_list[i] &gt; max_c:\n max_c = count_list[i]\n</code></pre>\n<p>This is reinventing the wheel. It is such a common operation, Python has a built-in function for doing it.</p>\n<pre class=\"lang-py prettyprint-override\"><code>max_c = max(count_list)\n</code></pre>\n<h1>Incorrect Output</h1>\n<blockquote>\n<p>This code passed 3 test cases but failed the 4th</p>\n</blockquote>\n<p>Relook at your problem description. Print it out. Using a pen, cross off all the conditions that you test for. At the end, you should see something which you haven't tested. Adding a check for that will solve your problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T12:14:14.133", "Id": "530765", "Score": "1", "body": "I'm going to leave the question open because this is a good answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T18:40:36.877", "Id": "269043", "ParentId": "269031", "Score": "3" } } ]
<p>I have solved <a href="https://www.codechef.com/problems/REDALERT" rel="nofollow noreferrer">this problem from the CodeChef platform</a> using the Python prorgamming language</p> <p>Here is the code:</p> <pre><code>test_cases = int(input()) for _ in range(test_cases): n, d, h = [int(x) for x in input().split()] rain_amounts = [int(y) for y in input().split()] red_alert = False water_level = 0 for rain_amount in rain_amounts: if rain_amount &gt; 0: water_level += rain_amount if rain_amount == 0: if water_level &lt; d: water_level = 0 else: water_level -= d if water_level &gt; h: red_alert = True if red_alert: print(&quot;YES&quot;) else: print(&quot;NO&quot;) </code></pre> <p>My solution received an ACCEPTED judgement and I would like feedback on my implementation, coding style, and everything in between.</p> <p>Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T22:15:24.667", "Id": "530787", "Score": "3", "body": "Please make the question self contained. E.g include the information from the link =)" } ]
{ "AcceptedAnswerId": "269080", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T20:11:20.537", "Id": "269078", "Score": "2", "Tags": [ "python", "programming-challenge" ], "Title": "CodeChef - Red Alert" }
269078
accepted_answer
[ { "body": "<p>I like your code =) What it does is clear, and your variable names and spacing is correct. There is not much of an algorithm to speak of here, so instead I will focus on structure.</p>\n<p>It is always a good idea to separate inputs from actions. This can be done using a if_main guard, and clear functions. Something like this passes the first test case</p>\n<pre><code>def is_red_alert(precipitation, drainage, waterlogging):\n\n water_level = 0\n\n for rain_today in precipitation:\n if rain_today &gt; 0:\n water_level += rain_today\n if rain_today == 0:\n if rain_today &lt; drainage:\n water_level = 0\n else:\n water_level -= drainage\n return water_level &gt; waterlogging\n\n\nif __name__ == &quot;__main__&quot;:\n test_cases = int(input())\n\n for _ in range(test_cases):\n _, drainage, waterlogging = [int(x) for x in input().split()]\n precipitation = [int(y) for y in input().split()]\n\n if is_red_alert(precipitation, drainage, waterlogging):\n print(&quot;YES&quot;)\n else:\n print(&quot;NO&quot;)\n</code></pre>\n<p>Otherwise the code is the same. I will change the name of a few of the variables throughout as naming is hard.. =) We can tidy up the logic a bit using <code>min</code> and <code>max</code>. Something like this</p>\n<pre><code>for day in precipitation:\n accumulation += max(0, day)\n if day == 0:\n accumulation -= min(drainage, accumulation)\n elif accumulation &gt; limit:\n return True\nreturn accumulation &gt; limit\n</code></pre>\n<p>Firstly we do not have to check if the precipitation of the current day is negative. We can just use <code>max(0, today)</code> [Yes, this <em>is</em> slower].\nInstead of setting the water level (or in my case the accumulation of water) we can just subtract the smallest number between <code>drainage</code> and <code>accumulation</code>. I will let you go through to check out what happens when <code>drainage &lt; accumulation</code>, and <code>drainage &gt; accumulation</code>. Similarly we only need to check if we are above the limit if the rain today is greater than zero. Otherwise there is no change.</p>\n<p>We can also add some descriptive typing hints to further explain what is going on in the code</p>\n<h2>Code</h2>\n<pre><code>from typing import Annotated\n\nPrecipitation = Annotated[\n list[int],\n &quot;The amount water released from clouds in the form of rain, snow, or hail over n days&quot;,\n]\nDrainage = Annotated[\n int,\n &quot;The amount of water removed on a dry day&quot;,\n]\nWaterMax = Annotated[\n int,\n &quot;The total amount of water before triggering an warning&quot;,\n]\n\n\ndef is_red_alert(\n precipitation: Precipitation, drainage: Drainage, limit: WaterMax\n) -&gt; bool:\n &quot;Returns True if the citys water level becomes larger than a given limit&quot;\n\n accumulation = 0\n\n for day in precipitation:\n accumulation += max(0, day)\n if day == 0:\n accumulation -= min(drainage, accumulation)\n elif accumulation &gt; limit:\n return True\n return accumulation &gt; limit\n\n\nif __name__ == &quot;__main__&quot;:\n test_cases = int(input())\n\n for _ in range(test_cases):\n _, drainage, water_limit = list(map(int, input().split()))\n precipitation = list(map(int, input().split()))\n\n if is_red_alert(precipitation, drainage, water_limit):\n print(&quot;YES&quot;)\n else:\n print(&quot;NO&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T02:43:59.440", "Id": "530795", "Score": "0", "body": "Thanks for such a comprehensive and thoughtful review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-17T23:51:52.057", "Id": "269080", "ParentId": "269078", "Score": "1" } } ]
<p>How can I shorten my code for this? There are 6 variable sets of numbers, someone picks a number between 1-63, if their number is in a set, you add the first number of the list to the magic number variable. If it is not, you don't add anything, and move to the next set. I have used multiple while loops, but want a more effective way to do this.</p> <pre><code>number_set1 = [2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31, 34, 35, 38, 39, 42, 43, 46, 47, 50, 51, 54, 55, 58, 59, 62, 63] number_set2 = [8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 56, 57, 58, 59, 60, 61, 62, 63] number_set3 = [4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31, 36, 37, 38, 39, 44, 45, 46, 47, 52, 53, 54, 55, 60, 61, 62, 63] number_set4 = [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] number_set5 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63] number_set6 = [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] answer = '' magic_number = 0 index = 0 print('I can read your mind... think of a number between 1 to 63 (inclusive)') print('Don\'t tell me... just be sure to keep it in your mind... I\'ll work it out') print('by having you answer a few, simple questions.... :)') answer = input('Would you like to play? [Yes|No] :') if answer != &quot;Yes&quot; and answer != &quot;No&quot;: print(&quot;\nPlease enter either 'Yes' or 'No'.&quot;) while answer == 'Yes' and index == 0: question = input('Is your number in deck 1? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set1[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 1: question = input('Is your number in deck 2? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set2[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 1 or index == 2: question = input('Is your number in deck 3? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set3[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 2 or index == 3: question = input('Is your number in deck 4? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set4[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 3 or index == 4: question = input('Is your number in deck 5? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set5[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 4 or index == 5: question = input('Is your number in deck 6? [Yes|No]: ') if question == 'Yes': magic_number = magic_number + number_set6[0] index = index + 1 if question == 'No': index = index + 1 # Display the secret number to the screen and amaze your friends! ; ) print('The number you are thinking about is.....', magic_number) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T02:27:32.520", "Id": "269081", "Score": "7", "Tags": [ "python" ], "Title": "Magic number game in Python" }
269081
max_votes
[ { "body": "<p>Welcome to Code Review! Congratulations on having a working game/project :)</p>\n<p>I have a few pointers to help you minimizing the code length, and probably make it easily extensible. Some of these might be considered personal quirks; so YMMV.</p>\n<h2>The deck</h2>\n<p>You're asking the user if their number; at a given state of the run; in any of the given decks. However, for a new player; you never really show the decks ever.</p>\n<p>Is the user supposed to remember <strong>the entire deck</strong>? Perhaps showing the deck before asking if the number is in the same would be better, unless you're using printed cards to act as the deck.</p>\n<h2>Functions</h2>\n<p>Use functions for doing something that you see being repeated. In your case, one of the examples is asking user for <code>Yes/No</code>. Let a function ask for user input, and return <code>True</code>/<code>False</code> for y/n values, and the while loop can live inside this little function.</p>\n<h2>User experience</h2>\n<p>Asking user to input <code>Yes</code>/<code>No</code> seems counter intuitive in the sense that you want them to input these exactly as shown. In general, a lot of cli programs accept <code>y</code>/<code>Y</code>/<code>Yes</code>/<code>yes</code> and variations thereof to be the same. You can have a validation with a small if-clause for acceptable values like so:</p>\n<pre><code>if choice not in {&quot;Yes&quot;, &quot;No&quot;}:\n print(&quot;Please enter Yes/No&quot;)\n</code></pre>\n<h2>if-main clause</h2>\n<p>Put the core logic of your run inside the famous <code>if __name__ == &quot;__main__&quot;</code> block. I will not go into details on the benefits, and just leave a link to <a href=\"https://stackoverflow.com/q/419163/1190388\">this excellent Stack Overflow discussion</a> about the same.</p>\n<h2>Mathematics</h2>\n<p>The game works using the concept of boolean algebra. Each set of numbers is actually only setting one of the bits in the binary representation. You can leverage this fact to generate the table dynamically (or to a custom upper limit) and let another function just set the bit value at correct position in the binary representation be set to <span class=\"math-container\">\\$ 1 \\$</span>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T04:32:33.890", "Id": "269082", "ParentId": "269081", "Score": "5" } } ]
<p>How can I shorten my code for this? There are 6 variable sets of numbers, someone picks a number between 1-63, if their number is in a set, you add the first number of the list to the magic number variable. If it is not, you don't add anything, and move to the next set. I have used multiple while loops, but want a more effective way to do this.</p> <pre><code>number_set1 = [2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31, 34, 35, 38, 39, 42, 43, 46, 47, 50, 51, 54, 55, 58, 59, 62, 63] number_set2 = [8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 56, 57, 58, 59, 60, 61, 62, 63] number_set3 = [4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31, 36, 37, 38, 39, 44, 45, 46, 47, 52, 53, 54, 55, 60, 61, 62, 63] number_set4 = [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] number_set5 = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63] number_set6 = [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63] answer = '' magic_number = 0 index = 0 print('I can read your mind... think of a number between 1 to 63 (inclusive)') print('Don\'t tell me... just be sure to keep it in your mind... I\'ll work it out') print('by having you answer a few, simple questions.... :)') answer = input('Would you like to play? [Yes|No] :') if answer != &quot;Yes&quot; and answer != &quot;No&quot;: print(&quot;\nPlease enter either 'Yes' or 'No'.&quot;) while answer == 'Yes' and index == 0: question = input('Is your number in deck 1? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set1[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 1: question = input('Is your number in deck 2? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set2[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 1 or index == 2: question = input('Is your number in deck 3? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set3[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 2 or index == 3: question = input('Is your number in deck 4? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set4[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 3 or index == 4: question = input('Is your number in deck 5? [Yes|No] :') if question == 'Yes': magic_number = magic_number + number_set5[0] index = index + 1 if question == 'No': index = index + 1 while answer == 'Yes' and index == 4 or index == 5: question = input('Is your number in deck 6? [Yes|No]: ') if question == 'Yes': magic_number = magic_number + number_set6[0] index = index + 1 if question == 'No': index = index + 1 # Display the secret number to the screen and amaze your friends! ; ) print('The number you are thinking about is.....', magic_number) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T02:27:32.520", "Id": "269081", "Score": "7", "Tags": [ "python" ], "Title": "Magic number game in Python" }
269081
max_votes
[ { "body": "<p>Welcome to Code Review! Congratulations on having a working game/project :)</p>\n<p>I have a few pointers to help you minimizing the code length, and probably make it easily extensible. Some of these might be considered personal quirks; so YMMV.</p>\n<h2>The deck</h2>\n<p>You're asking the user if their number; at a given state of the run; in any of the given decks. However, for a new player; you never really show the decks ever.</p>\n<p>Is the user supposed to remember <strong>the entire deck</strong>? Perhaps showing the deck before asking if the number is in the same would be better, unless you're using printed cards to act as the deck.</p>\n<h2>Functions</h2>\n<p>Use functions for doing something that you see being repeated. In your case, one of the examples is asking user for <code>Yes/No</code>. Let a function ask for user input, and return <code>True</code>/<code>False</code> for y/n values, and the while loop can live inside this little function.</p>\n<h2>User experience</h2>\n<p>Asking user to input <code>Yes</code>/<code>No</code> seems counter intuitive in the sense that you want them to input these exactly as shown. In general, a lot of cli programs accept <code>y</code>/<code>Y</code>/<code>Yes</code>/<code>yes</code> and variations thereof to be the same. You can have a validation with a small if-clause for acceptable values like so:</p>\n<pre><code>if choice not in {&quot;Yes&quot;, &quot;No&quot;}:\n print(&quot;Please enter Yes/No&quot;)\n</code></pre>\n<h2>if-main clause</h2>\n<p>Put the core logic of your run inside the famous <code>if __name__ == &quot;__main__&quot;</code> block. I will not go into details on the benefits, and just leave a link to <a href=\"https://stackoverflow.com/q/419163/1190388\">this excellent Stack Overflow discussion</a> about the same.</p>\n<h2>Mathematics</h2>\n<p>The game works using the concept of boolean algebra. Each set of numbers is actually only setting one of the bits in the binary representation. You can leverage this fact to generate the table dynamically (or to a custom upper limit) and let another function just set the bit value at correct position in the binary representation be set to <span class=\"math-container\">\\$ 1 \\$</span>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-18T04:32:33.890", "Id": "269082", "ParentId": "269081", "Score": "5" } } ]
<p>This is for leetcode problem: <a href="https://leetcode.com/problems/majority-element" rel="nofollow noreferrer">https://leetcode.com/problems/majority-element</a></p> <p>There is something wrong with the way I create solutions, and not sure how to stop doing it. Basically the problem is I always create a count variable. Here is it called greatest_count. For the if statement, I create a conditional, which I think is fine, but I feel like I don't need the additional greatest_count variable here but not sure a better way to write it. I always seem to think I need to count it and check it against the previous counts. Do I need this? How can I write this without needing the count variable? or without using the greatest unique? Any ways to optimize this would be great to know.</p> <p>Problem area:</p> <pre><code>if unique_count &gt; greatest_count: greatest_count = unique_count greatest_unique = i </code></pre> <p>Here is the full code:</p> <pre><code>class Solution: def majorityElement(self, nums): unique_nums = set(nums) greatest_unique = 0 greatest_count = 0 for i in unique_nums: unique_count = nums.count(i) if unique_count &gt; greatest_count: greatest_count = unique_count greatest_unique = i return greatest_unique </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:36:08.813", "Id": "530961", "Score": "4", "body": "Thank you for providing the link, however, links can break. Please include the text of the programming challenge in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:42:24.457", "Id": "530963", "Score": "2", "body": "It's not clear from question, but I'm assuming the code is passing all tests?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T06:08:04.480", "Id": "531002", "Score": "0", "body": "Check out [Moore's algorithm](https://en.wikipedia.org/wiki/Boyer–Moore_majority_vote_algorithm)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T09:57:42.980", "Id": "531637", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
{ "AcceptedAnswerId": "269159", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:33:33.160", "Id": "269156", "Score": "-2", "Tags": [ "python", "programming-challenge" ], "Title": "leetcode 169 optimzations reducing complexity" }
269156
accepted_answer
[ { "body": "<h2>Your code, simplified:</h2>\n<p>Here's an alternative that uses fewer variables. It involves tuple comparisons in <code>max(num_cnt_max, num_cnt)</code>:</p>\n<pre><code>CNT, NUM = 0, 1\nclass Solution:\n def majorityElement(self, nums):\n unique_nums = set(nums)\n num_cnt_max = (0, 0)\n \n for num in unique_nums:\n num_cnt = (nums.count(num), num)\n num_cnt_max = max(num_cnt_max, num_cnt)\n return num_cnt_max[CNT]\n</code></pre>\n<hr />\n<h2>Use <code>Counter</code> instead of <code>set</code> and <code>list.count</code>:</h2>\n<p>Another suggestion is to use <a href=\"https://docs.python.org/3/library/collections.html?highlight=counter#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a> instead of the combination of <code>set</code> and <code>list.count</code> your solution uses. In case you're not familiar with <code>Counter</code>, here's an example of its usage:</p>\n<pre><code>from collections import Counter\n\nnums = [1, 6, 3, 9, 3, 4, 3, 1]\nnums_counter = Counter(nums)\nprint(nums) # Counter({3: 3, 1: 2, 6: 1, 9: 1, 4: 1})\n</code></pre>\n<p>The relationship between <code>nums</code> and <code>nums_counter</code> is that <code>nums_counter[num] == nums.count(num)</code>. Creating a <code>Counter</code> (<code>Counter(nums)</code>) and then accessing it (<code>nums_counter[num]</code>) repeatedly is probably faster than repeatedly calling <code>nums.count(num)</code>.</p>\n<h2>Use information given in the problem statement:</h2>\n<p>Another suggestion is to use the information that the majority element appears more than <code>N / 2</code> times. In a list of <code>N</code> elements how many different elements can have a count of more than <code>N / 2</code>? Using that information would let you break out of the foo loop earlier and you'd know which element is the majority just by looking at its count, so you would not have to maintain the intermediate <code>num_cnt_max</code> variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T22:13:14.443", "Id": "530983", "Score": "2", "body": "You should make note of the [`Counter.most_common([n])`](https://docs.python.org/3/library/collections.html?highlight=counter#collections.Counter.most_common) method, which reduces the code to one statement `return Counter(nums).most_common(1)[0]`. But what you really should do is provide a **review** of the OP's code, since alternate-solution-only answers are not valid answers on this site." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T19:47:04.363", "Id": "269159", "ParentId": "269156", "Score": "0" } } ]
<p>I have been working on this question, <a href="https://open.kattis.com/problems/sequences" rel="nofollow noreferrer">https://open.kattis.com/problems/sequences</a>.</p> <blockquote> <p>You are given a sequence, in the form of a string with characters ‘0’, ‘1’, and ‘?’ only. Suppose there are <em>n</em> ‘?’s. Then there are 2ⁿ ways to replace each ‘?’ by a ‘0’ or a ‘1’, giving 2ⁿ different 0-1 sequences (0-1 sequences are sequences with only zeroes and ones).</p> <p>For each 0-1 sequence, define its number of inversions as the minimum number of adjacent swaps required to sort the sequence in non-decreasing order. In this problem, the sequence is sorted in non-decreasing order precisely when all the zeroes occur before all the ones. For example, the sequence 11010 has 5 inversions. We can sort it by the following moves: 11010 → 11001 → 10101 → 01101 → 01011 → 00111.</p> <p>Find the sum of the number of inversions of the 2ⁿ sequences, modulo 1000000007 (10⁹+7).</p> <p><strong>Input</strong><br /> The first and only line of input contains the input string, consisting of characters ‘0’, ‘1’, and ‘?’ only, and the input string has between 1 to 500000 characters, inclusive.</p> <p><strong>Output</strong><br /> Output an integer indicating the aforementioned number of inversions modulo 1000000007</p> </blockquote> <p>In summary, I am given a string of 1s, 0s, and ?s. All question marks are basically variables that can become 1s and 0s. In each case, I have to sum up the minimum number of inversions (a swap of two adjacent characters), needed to sort the string into non-decreasing order, i.e, all 0s before 1s. For example, 0?1? has four cases: 0010, 0011, 0110, and 0111, and need 1, 0, 2, and 0 inversions respectively, summing up to 3. I am able to get the answer right however my code is too slow:</p> <pre><code>string = input() zero = 0 # is the number of 0's total = 0 # total number of inversions questions = 0 # number of questions marks count = 0 # sum of indexes of questions marks for i in range(len(string)): if string[i] == '?': count = count + i questions = questions + 1 elif string[i] == '0': zero = zero + 1 total = total + i if questions != 0: total = total * 2 ** questions + count * 2 ** (questions - 1) triangular = 0 for i in range (zero): triangular = triangular + i Choosy = 1 for i in range(questions + 1): total = total - triangular * Choosy triangular = triangular + zero + i Choosy = Choosy * (questions - i) // (i + 1) print(total) </code></pre> <p>Basically, the idea of my code is that for each case, the number of inversions needed is simply the sum of all indexes of 0 takeaway the (number of 0s -1)th triangular number. Therefore, all I need to do is add up all of the indexes of 0s, times by the number of cases, and add all indexes of questions marks, times the number of cases/2, since each question mark is a 0 exactly half the time. I then calculate the number of cases that within the question marks, there are 0, 1, 2 ..., (number of question mark) 0s using combinations, times by the (number of 0s -1)th triangular number, and minus this off the total. My code works kind of quickly but as I start putting around 20,000 question marks as my input, it starts to take more than a second. However, I need it to take 500,000 question marks as input and return a value within a second. Any ideas on how to make it faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T13:05:10.987", "Id": "531134", "Score": "0", "body": "is the 2k or \\$ 2^k \\$?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T13:40:04.480", "Id": "531139", "Score": "0", "body": "It is 2^k or two to the power of k" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T12:30:24.380", "Id": "269223", "Score": "5", "Tags": [ "python", "programming-challenge", "sorting", "time-limit-exceeded" ], "Title": "Counting swaps in a sequence sorting algorithm" }
269223
max_votes
[ { "body": "<p>Disclaimer. This ia not a proper review, but an extended comment.</p>\n<p>Nice work with understanding the core of the problem. You just need to go one extra mile to come up with the closed form solution.</p>\n<p>If you rewrite the loop as</p>\n<pre><code>Choosy = 1\nsub = 0\nfor i in range(questions + 1):\n sub += triangular * Choosy\n triangular += zero + 1\n Choosy = Choosy * (questions - i) // (i + 1)\ntotal -= sub\n</code></pre>\n<p>it becomes obvious that the value it calculates is (<span class=\"math-container\">\\$q\\$</span> and <span class=\"math-container\">\\$z\\$</span> correspond to <code>zero</code> and <code>questions</code>)</p>\n<p><span class=\"math-container\">\\$\\displaystyle \\sum_{i=0}^q \\binom{q}{i}T_{z+i} = \\sum_{i=0}^q \\binom{q}{i}\\dfrac{(z+i)(z+i+1)}{2} = \\dfrac{1}{2}\\sum_{i=0}^q \\binom{q}{i}(i^2 + (2z+1)i + z(z+1)) =\\$</span></p>\n<p><span class=\"math-container\">\\$\\displaystyle \\dfrac{1}{2}\\sum_{i=0}^q \\binom{q}{i}i^2 + \\dfrac{2z+1}{2}\\sum_{i=0}^q \\binom{q}{i}i + \\dfrac{z(z+1)}{2}\\sum_{i=0}^q \\binom{q}{i}\\$</span></p>\n<p>Each term has a closed form. You don't need to loop at all.</p>\n<p>Ironically, this problem wouldn't teach you how to iterate. Rather it teaches to <em>not</em> iterate.</p>\n<p>A word of warning. You'd have to deal with quite large powers of 2. Do not compute them naively. Check out <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring\" rel=\"noreferrer\">exponentiation by squaring</a>, and take the modulo after each multiplication.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:17:22.737", "Id": "531189", "Score": "0", "body": "Hello is it appropriate to equate the summation symbol (the sidewards M) with a for i in range loop in python where the top value is the highest value for i and the bottom value is the starting value? Also thanks for your comment!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:24:30.660", "Id": "531191", "Score": "0", "body": "also i dont understand this last bit 12∑=0()2+2+12∑=0()+(+1)2∑=0(), sorry i dont know how to write with proper maths notation like you did." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T18:30:21.090", "Id": "269234", "ParentId": "269223", "Score": "6" } } ]
<p>Take input n1 and n2 and check if they have the same greatest factor. If they do, print that factor. If they don't, print &quot;No&quot;. <br/></p> <p>example:<br/> input:<br/> 6<br/> 9<br/> output:<br/> 3<br/></p> <p>input:<br/> 15<br/> 27<br/> output:<br/> No<br/></p> <pre><code>n1=int(input()) n2=int(input()) l1=[] l2=[] for i in range(1,n1): if n1%i==0: l1.append(i) l1.sort(reverse=True) cf1=l1[0] for j in range(1,n2): if n2%j==0: l2.append(j) l2.sort(reverse=True) cf2=l2[0] if cf1==cf2: print(cf1) else: print(&quot;No&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T14:20:14.897", "Id": "531263", "Score": "0", "body": "Your code is not finding the greatest common factor. It's finding if the greatest factors of the two numbers are equal. The usual way to find the greatest common factor is the Euclidean algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T15:40:26.720", "Id": "531269", "Score": "0", "body": "The GCF of 15 and 27 should be 3. I've voted to close this question, since we only review code that is working correctly on this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T17:04:45.697", "Id": "531272", "Score": "0", "body": "@200_success no, we have to check if the greatest is same or not. for 15 it is 5 and for 27 it is 9 so not equal" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T17:05:04.947", "Id": "531273", "Score": "0", "body": "@Teepeemm how to use euclidean algorithm?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T17:11:09.640", "Id": "531276", "Score": "0", "body": "Sorry, I misinterpreted \"common greatest factor\" as \"greatest common factor\". I've edited the post to remove that confusion, and retracted my close vote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T18:06:11.427", "Id": "531283", "Score": "0", "body": "@200_success it's okay and thank you :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T20:08:36.790", "Id": "531289", "Score": "0", "body": "The Euclidean algorithm is usually implemented along the lines of `gcf(a,b)=gcf(b,a%b)` and then recursing (or with a while loop). But that's not what your code is doing (if that's what it's supposed to be doing, then you've misinterpreted your requirement)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T22:37:13.920", "Id": "531298", "Score": "1", "body": "(I'm somewhat ill at ease with the problem statement not explicitly excluding a natural number as its own factor.)" } ]
{ "AcceptedAnswerId": "269291", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T10:25:00.940", "Id": "269290", "Score": "0", "Tags": [ "python", "python-3.x", "mathematics" ], "Title": "Print greatest factor if it is same for both numbers" }
269290
accepted_answer
[ { "body": "<p>At any point, 1 is always common factor of any two numbers. Your code works perfectly. But if you want to write a shorter code, check the condition if both numbers are divisible by any number using for loop going from range 2 (1 is always factor) to min of both numbers. Take a new variable f which is <code>False</code> initially. If the condition is satisfied i.e. if both nos are divisible by a no, change f to <code>True</code>. Then, out of the loop, write an if condition, if f==True then print the number or else the condition was never satisfied and f is False and print &quot;no&quot;. Your code:</p>\n<pre><code>n1=int(input(&quot;Enter n1&quot;))\nn2=int(input(&quot;Enter n2&quot;))\nf=False\nfor i in range(2,min([n1,n2])):\n if n1%i==0 and n2%i==0:\n g=i\n f=True\nif f:\n print(g)\nelse:\n print(&quot;no&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T14:18:39.173", "Id": "531262", "Score": "2", "body": "This is a (slow) implementation of finding the greatest common factor, but that's not what OP's code dos." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T00:08:23.840", "Id": "531303", "Score": "0", "body": "(Ignoring not checking factors higher than any common ones: How about `for i in range(min([n1,n2])//2, 1, -1):` ?)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T11:18:13.443", "Id": "269291", "ParentId": "269290", "Score": "0" } } ]
<p>So a little context to understand the code:</p> <ol> <li>This is a helper function to solve a bigger problem <a href="https://leetcode.com/problems/dungeon-game/" rel="nofollow noreferrer">here</a></li> <li>Quick summary: A Knight is in a dungeon/2D grid of Ints, starts at 0,0 and must reach the last cell at the bottom right to find the princess</li> <li>The purpose of this helper function is to return all neighbors of a given starting point, given some constraints:</li> </ol> <ul> <li>The knight's starting point is always upper-left - 0,0</li> <li>The knight can only travel right or down, 1 cell at a time</li> <li>The target / base case is bottom right of the grid/dungeon where the princess is</li> </ul> <p><strong>Code below</strong></p> <pre><code>def get_neighbors(d, x, y, coll): # d == abbr. for dungeon is our board # For example: #[-8, -13, -8] #[-24, 28, 28] #[-13, -13, -30] # coll == abbr. for collection, how I keep track of all returned neighbors # We start our knight in the upper left hand corner row_length = len(d) col_length = len(d[0]) if (x,y) == (row_length - 1, col_length - 1): # Once we reach the bottom right corner we are done return coll for dx in range(0, 2): for dy in range(0, 2): if dx == 0 and dy == 0 or dx == 1 and dy == 1: # If cell is not to the bottom or to the right, skip it continue if x + dx &gt; len(d[x]) - 1 or y + dy &gt; len(d) - 1: # Out of bounds check continue neighbor = (x + dx, y + dy) # I'm wondering why I even need this line, if I am only going to the right and to the bottom each time # Why do I need to guard against duplicates if neighbor not in coll: coll.append(neighbor) get_neighbors(d, x + dx, y + dy, coll) return coll </code></pre> <p>Is there anything I should do differently?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:37:45.560", "Id": "531426", "Score": "0", "body": "Travel \"right and down\" diagonally, or \"either right or down\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:41:25.787", "Id": "531427", "Score": "0", "body": "@Reinderien Right or down, no diagonal, good point" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:49:04.823", "Id": "531428", "Score": "0", "body": "I think you need to show much more of your code, not just this function - because some of the issues with this code, when fixed, will require a different calling convention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:50:36.563", "Id": "531429", "Score": "0", "body": "@Reinderien Ok duly noted. I'll return with the rest of the code once I have it done, thanks for the input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T20:18:18.453", "Id": "531435", "Score": "0", "body": "@SergioBost Don't you end up with all the cells (i,j) with i and/or j >= than x,y in your collection?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T20:22:24.350", "Id": "531436", "Score": "0", "body": "@kubatucka If you're referring to dx, dy, then yes, since I'm only moving forward (right or down) never backwards (left or up)" } ]
{ "AcceptedAnswerId": "269369", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T15:54:58.540", "Id": "269364", "Score": "1", "Tags": [ "python", "recursion", "depth-first-search" ], "Title": "Helper get_all_neighbors (in a grid) function - python" }
269364
accepted_answer
[ { "body": "<p>Welcome to CodeReview!</p>\n<p>Disclaimer: As noted in the comments, a review of this code is limited since I don't know the entire codebase / algorithmic approach. So this review is limited to this function's current implementation.</p>\n<hr />\n<p><strong>Naming</strong></p>\n<p><code>d</code> and <code>coll</code> are hard-to-understand names, <code>dungeon</code> and <code>collection</code> are already an improvement. <code>collection</code> however is almost meaningless, as it says nothing about the data stored in the variable. Since the function is called <code>get_neighbors</code>, the return value should probably be called <code>neighbors</code> (<code>coll.append(neighbor)</code> is another hint). If you find yourself needing comments to explain your variable names, you should change them. Reading this line <code># d == abbr. for dungeon is our board</code> is already a lot of unnecessary work compared to simply reading <code>dungeon</code> in the first place. Stick to meaningful and readable variable names, that do not require further explanation.</p>\n<hr />\n<p><strong>Type annotations</strong></p>\n<p>Including type annotations significantly increases the readability of your code. It also allows for better error-checking:</p>\n<pre><code>def get_neighbors(dungeon: list[list[int]], x: int, y: int, neighbors: list[tuple[int, int]])\\\n -&gt; list[tuple[int, int]]:\n</code></pre>\n<hr />\n<p><strong>Miscellaneous</strong></p>\n<hr />\n<p>You might have rows and columns the wrong way round. I would expect <code>dungeon</code> to be a list of rows, <code>y</code> to indicate the row and <code>x</code> to indicate the column. Your current implementation handles <code>dungeon</code> like a list of columns.</p>\n<hr />\n<p><code>if x + dx &gt; len(d[x]) - 1 or y + dy &gt; len(d) - 1: # Out of bounds check</code>:</p>\n<ul>\n<li>You don't need to access <code>len(d[x])</code> (<code>d[x]</code> should also be <code>d[y]</code> by the way), as <code>dungeon</code> is a rectangle, simply use <code>len(d[0])</code></li>\n<li>You already calculated and stored <code>row_length</code> &amp; <code>col_length</code>, use them</li>\n</ul>\n<hr />\n<pre><code>for dx in range(0, 2):\n for dy in range(0, 2):\n if dx == 0 and dy == 0 or dx == 1 and dy == 1:\n continue\n</code></pre>\n<p>should be way simpler:</p>\n<pre><code>for dx, dy in ((1, 0), (0, 1)):\n</code></pre>\n<p>While this might be fine for only two directions, a module- or class-level constant <code>DIRECTIONS = ((1, 0), (0, 1))</code> would be even better, especially once the number of directions increases.</p>\n<pre><code>for dx, dy in DIRECTIONS:\n</code></pre>\n<hr />\n<pre><code># I'm wondering why I even need this line, if I am only going to the right and to the bottom each time\n# Why do I need to guard against duplicates\nif neighbor not in coll:\n coll.append(neighbor)\n</code></pre>\n<p>In you current implementation you need to perform this check, because different paths can lead to the same cell. Consider the simplest example of the two paths (1. DOWN -&gt; 2. RIGHT) and (1. RIGHT-&gt; 2. DOWN).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T18:42:51.620", "Id": "531434", "Score": "0", "body": "Very clear explanation, thanks. I'll make sure to be more thorough next time around." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:54:18.770", "Id": "269369", "ParentId": "269364", "Score": "1" } } ]
<ul> <li><p>x and y are two-dimensional arrays with dimensions (AxN) and (BxN), i.e. they have the same number of columns.</p> </li> <li><p>I need to get a matrix of Euclidean distances between each pair of rows from x and y.</p> </li> </ul> <p>I have already written four different methods that give equally good results. But the first three methods are not fast enough, and the fourth method consumes too much memory.</p> <p>1:</p> <pre><code>from scipy.spatial import distance def euclidean_distance(x, y): return distance.cdist(x, y) </code></pre> <p>2:</p> <pre><code>import numpy as np import math def euclidean_distance(x, y): res = [] one_res = [] for i in range(len(x)): for j in range(len(y)): one_res.append(math.sqrt(sum(x[i] ** 2) + sum(y[j] ** 2) - 2 * np.dot(x[i], np.transpose(y[j])))) res.append(one_res) one_res = [] return res </code></pre> <p>3:</p> <pre><code>import numpy as np def euclidean_distance(x, y): distances = np.zeros((x.T[0].shape[0], y.T[0].shape[0])) for x, y in zip(x.T, y.T): distances = np.subtract.outer(x, y) ** 2 + distances return np.sqrt(distances) </code></pre> <p>4:</p> <pre><code>import numpy as np def euclidean_distance(x, y): x = np.expand_dims(x, axis=1) y = np.expand_dims(y, axis=0) return np.sqrt(((x - y) ** 2).sum(-1)) </code></pre> <p>It looks like the second way could still be improved, and it also shows the best timing. Can you help me with the optimization, please?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T01:40:57.547", "Id": "531616", "Score": "1", "body": "Welcome to Code Review@SE. Time allowing, (re?)visit [How to get the best value out of Code Review](https://codereview.meta.stackexchange.com/q/2436). As per [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask), the title of a CR question (*and*, preferably, [the code itself](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring)) should state what the code is to accomplish." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T02:04:43.513", "Id": "531619", "Score": "2", "body": "It may help the non-mathheads if you added why&how 2-4 compute the distances. Please add how the result is going to be used - e.g, for comparisons, you don't need sqrt (`cdist(x, y, 'sqeuclidean')`). Do you need all values at once/as a matrix? Otherwise, a *generator* may help. What are typical dimensions of `x` and `y`?" } ]
{ "AcceptedAnswerId": "269504", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T18:14:16.877", "Id": "269436", "Score": "2", "Tags": [ "python", "performance", "comparative-review", "numpy" ], "Title": "How can I optimize this pairwise Euclidean distance search algorithm?" }
269436
accepted_answer
[ { "body": "<h3>Performance:</h3>\n<p>A way to use broadcasting but avoid allocating the 3d array is to separate the distance formula into $(x - y) ** 2 = x^2 + y^2 - 2xy$.</p>\n<pre><code>squared_matrix = np.sum(A ** 2,axis=1 )[:,np.newaxis] - 2 * (A@B.T) + np.sum(B ** 2,axis=1 )[np.newaxis,:]\ndistance_matrix = np.sqrt(squared_matrix)\n</code></pre>\n<p>Check:</p>\n<pre><code>np.allclose(distance_matrix,euclidean_distance(A,B))\n&gt;&gt;&gt; True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T12:46:06.953", "Id": "531716", "Score": "1", "body": "You can probably write this with np.einsum in a more succinct way but einsum makes my head hurt." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T12:41:55.283", "Id": "269504", "ParentId": "269436", "Score": "1" } } ]
<p>I'm pretty new to learning Python. I wrote a very basic script that takes your pizza order and recites it back when you're done placing your order:</p> <pre><code>available_toppings = ['mushrooms', 'onions', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese','sausage','spinach'] requested_toppings = [] size = input(&quot;Would you like a large, medium, or small pizza? &quot;) ordering = True while ordering == True: topping = input(&quot;What topping would you like on your pizza? &quot;) if topping.lower() in available_toppings: print(&quot;Yes, we have that.&quot;) requested_toppings.append(topping) elif topping not in available_toppings: print(&quot;Sorry, we do not have &quot; + topping + &quot;.&quot;) add_more = False while add_more == False: answer = input(&quot;Would you like to add another topping? Yes or no? &quot;) if answer.lower() == &quot;y&quot; or answer.lower() == &quot;yes&quot;: add_more = True elif answer.lower() == &quot;n&quot; or answer.lower() == &quot;no&quot;: print(&quot;Ok, you ordered a {} &quot;.format(size) + &quot;pizza with:&quot;) for requested_topping in requested_toppings: print(requested_topping) add_more = True ordering = False elif answer.lower() != &quot;n&quot; or answer.lower() != &quot;no&quot; or answer.lower() != &quot;y&quot; or answer.lower() != &quot;yes&quot;: print(&quot;Sorry, I didn't catch that.&quot;) continue </code></pre> <p>I was just wondering if anyone has any tips to clean up the code a bit. I'm sure there is an easier way to accomplish what this script can do and would love to learn some tricks. I would also like to add that while loops still confuse me a bit and even though I got this to run, I really don't know if I did them right.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:14:07.690", "Id": "531640", "Score": "0", "body": "You don't need `elif topping not in available_toppings:`. It's fine with just `else:`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:16:24.670", "Id": "531641", "Score": "0", "body": "`print(\"Ok, you ordered a {} \".format(size) + \"pizza with:\")` can be `print(f\"Ok, you ordered a {size} pizza with:\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:20:02.833", "Id": "531642", "Score": "0", "body": "bro your code act weird when you do not provide topping it goes in endless loop it will keep on asking would you like another topping again and again as you give no to it as input" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:23:24.003", "Id": "531643", "Score": "0", "body": "and print the list of topping as user will chose from them" } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:07:30.663", "Id": "269455", "Score": "1", "Tags": [ "python" ], "Title": "Cleaning up a basic Python script that takes and recites a pizza order" }
269455
max_votes
[ { "body": "<p>Firstly, you should add <code>else</code> instead of elif in -</p>\n<pre><code>elif topping not in available_toppings:\n print(&quot;Sorry, we do not have &quot; + topping + &quot;.&quot;)\n</code></pre>\n<p>You can use</p>\n<pre><code>else:\n print(&quot;Sorry, we do not have &quot; + topping + &quot;.&quot;)\n</code></pre>\n<p>And instead of</p>\n<pre><code>elif answer.lower() != &quot;n&quot; or answer.lower() != &quot;no&quot; or answer.lower() != &quot;y&quot; or answer.lower() != &quot;yes&quot;:\n print(&quot;Sorry, I didn't catch that.&quot;)\n continue\n</code></pre>\n<p>You should use</p>\n<pre><code>else:\n print(&quot;Sorry, I didn't catch that.&quot;)\n continue\n</code></pre>\n<p>And you should also check if the size of the pizza is correct, it can be invalid. You should also print the topping list, as it will help user pick.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:52:06.643", "Id": "531644", "Score": "0", "body": "You can even add a few functions if you want." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:16:48.990", "Id": "269456", "ParentId": "269455", "Score": "1" } } ]
<p>I wanted to have a factory-method, but without the <code>if</code> statements that are often seen in examples of this pattern. So I came up with this, and would like to know: is this a right approach, should there be any impovements?</p> <p>some things I considered:</p> <ul> <li>It is using Enum because that makes it possible to iterate or list the possible options.</li> <li>using <code>getattr</code> to call the class dynamically</li> </ul> <pre class="lang-py prettyprint-override"><code>class Red: name = &quot;red&quot; class Blue: name = &quot;blue&quot; class Colors(Enum): red = Red blue = Blue @classmethod def factory(cls, name): if any(e.name == name for e in cls): target = cls[name] else: #default target = cls.blue return getattr(sys.modules[__name__], target.value.__name__)() print(Colors.factory(&quot;red&quot;)) print(Colors.factory(&quot;red&quot;)) print(Colors.factory(&quot;red2&quot;)) print(list(Colors)) </code></pre> <pre><code>### result &lt;__main__.Red object at 0x7fd7cc2e2250&gt; &lt;__main__.Red object at 0x7fd7cc2e2430&gt; &lt;__main__.Blue object at 0x7fd7cc30c700&gt; [&lt;Colors.red: &lt;class '__main__.Red'&gt;&gt;, &lt;Colors.blue: &lt;class '__main__.Blue'&gt;&gt;] </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T09:04:16.237", "Id": "269572", "Score": "2", "Tags": [ "python", "factory-method" ], "Title": "Factory pattern using enum" }
269572
max_votes
[ { "body": "<h3>Using enums in Python</h3>\n<p>The posted code doesn't take advantage of most of the benefits provides by enums in Python.</p>\n<p>The typical use case of enums is to make decisions depending on a given enum member.\nFor example,\nin the context of the posted code,\nI can imagine a <code>create_foo</code> method which takes as parameter a value of <code>Color</code> type that is an enum,\nand callers would use <code>create_foo(Color.RED)</code> to create a foo object with one of the supported colors.</p>\n<p>Another common use case would be iterating over an enum type,\nfor example to display the available choices to users.</p>\n<p>In the posted code, only the iteration capability is used, and only internally.\nFor this simpler purpose, a simpler and better option would be using a dictionary:</p>\n<pre><code>SUPPORTED_COLORS = {\n &quot;red&quot;: Red,\n &quot;blue&quot;: Blue,\n}\n\ndef create_color(name):\n if name in SUPPORTED_COLORS:\n return SUPPORTED_COLORS[name]()\n\n return Blue()\n</code></pre>\n<hr />\n<p>Since the parameter of the factory method is a string,\nit doesn't help to find the accepted values.\nI have to read the implementation to know, which violates good encapsulation.</p>\n<p>You may argue that taking a string parameter makes it possible to accept unsupported values and fall back to a default. I think that without a specific use case to justify this need, it's likely to be more harmful than beneficial to bypass type safety this way.</p>\n<p>I find it unexpected to have a factory method as part of an enum type.\nI would not look for a factory method there.\nWhen I see an enum, I expect to use its members, or iterate over it.</p>\n<hr />\n<p>Based on the documentation of <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\">enum support</a>,\n<em>enum members</em> should be named with <code>UPPER_CASE</code>, for example:</p>\n<pre><code>class Color(Enum):\n RED = auto\n BLUE = auto\n</code></pre>\n<p>Based on the examples on the page, it seems that singular noun is recommended as the name of the enum (<code>Color</code> rather than <code>Colors</code>).</p>\n<h3>Implementing the factory method pattern in Python</h3>\n<blockquote>\n<p>I wanted to have a factory-method, but without the if statements that are often seen in examples of this pattern.</p>\n</blockquote>\n<p>Why is that, really? What is the real problem you're trying to solve?\nWhen you try to do something that is different from what is &quot;often seen&quot;,\nI suggest to take a step back,\nand ask yourself if you really have a good reason to not follow a well established pattern.\nChances are that you are missing something, or you don't have a real need.</p>\n<p>Also keep in mind that &quot;often seen&quot; patterns are easier for everyone to understand, <em>because they are often seen</em>.\nWhen you take a different approach,\nthere is a high risk that readers will be surprised by it.\nSo it had better have a good justification to exist, and be rock solid.</p>\n<p>There is nothing fundamentally wrong with if statements in the factory method in general. On the other hand, I can imagine situations where a complex if-else chain could be replaced with something better, but I would have to be more specific about the problem to justify the need for improvement.</p>\n<p>I was surprised by the posted code, at multiple points.\nWhen I read the question title &quot;Factory pattern using enum&quot;, I expected to see:</p>\n<ul>\n<li>A factory method that takes an enum parameter</li>\n<li>The factory method decides what to return based on the enum parameter</li>\n</ul>\n<p>Reading on, when I saw &quot;but without the <code>if</code> statements&quot;, I expected a dictionary mapping enum members to some value or creator function, replacing if-else chain with dictionary lookup.</p>\n<hr />\n<p>I think <a href=\"https://realpython.com/factory-method-python/\" rel=\"noreferrer\">this tutorial on realpython.com</a> explains very nicely how to implement this pattern well in Python.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T16:12:58.367", "Id": "531870", "Score": "0", "body": "\"I find it unexpected to have a factory method as part of an enum type.\" So do I , that is why I posted the code here. But the reasoning was simple: first I used a regular class, but that would require some extra methods to make it iterable - Enum is a quick way to solve this, and works well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T11:50:27.537", "Id": "269580", "ParentId": "269572", "Score": "6" } } ]
<p>For a college assignment, I was tasked with the following (excerpt from provided code file):</p> <blockquote> <p>Find one string of characters that is not present in the list. You are provided a function that loads the strings from the provided file, <code>sequences.txt</code>. You may not use any libraries that assist you in completing this solution. This specifically includes the <code>random</code> and <code>string</code> library. Your function must return two values: the string not present in the list, and a boolean value representing if the value is present in the list. Ensure to use documentation strings and comments to explain your program! Good luck!</p> </blockquote> <p>Below is my solution, with a description of the algorithm is provided in the docstring. The main thing I'm worried about is my solution. I'm concerned there is a much easier solution, just not as elegant; like switching the first character of the first string and comparing that. It's not a 100% sure solution, but I'm sure it works most of the time. Mine is a sure solution, from my understanding.</p> <p>I should mention, the file <code>sequences.txt</code> contains 1000 lines, where each line is 1000 characters long, each character either A or B.</p> <p>Any and all critiques and recommendations are welcome and considered!</p> <pre><code>&quot;&quot;&quot; Find one string of characters that is not present in the list. You are provided a function that loads the strings from the provided file, `sequences.txt`. You may not use any libraries that assist you in completing this solution. This specifically includes the `random` and `string` library. Your function must return two values: the string not present in the list, and a boolean value representing if the value is present in the list. Ensure to use documentation strings and comments to explain your program! Good luck! @professor XXXXXXXX @class CS 1350 @due Nov 15, 2021 Provide your details below: @author Ben Antonellis @date Nov 2nd, 2021 &quot;&quot;&quot; # PROVIDED FUNCTIONS # def load_sequences(): sequences = [] with open('sequences.txt', 'r') as input_file: for line in input_file: sequences.append(line.strip()) return sequences # PROVIDE YOUR SOLUTION BELOW # from typing import Tuple # For code clarity def find_excluded() -&gt; Tuple[str, bool]: &quot;&quot;&quot; This algorithm marches through each string in the list, and for every string flips the n-th character. By doing this, this ensures the string is different from each string by at least one character. &quot;&quot;&quot; strings = load_sequences() string_index = 0 result = &quot;&quot; for idx, _ in enumerate(strings): result += &quot;A&quot; if strings[idx][string_index] == &quot;B&quot; else &quot;B&quot; string_index += 1 return result, result in strings result, should_be_false = find_excluded() print(result) print(should_be_false) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T22:16:29.827", "Id": "532104", "Score": "0", "body": "I think you forgot to increment the string index. As is this would fail with the following input of 2 strings : 'AB', 'BA' . But would work with strings[idx][idx]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T04:23:08.810", "Id": "532116", "Score": "0", "body": "@kubatucka Thanks for the catch, somehow that didn't make it into the copy-paste!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T09:35:57.637", "Id": "532140", "Score": "1", "body": "How returning empty string (or any other less-then-1000-long string) fails to meet the requirements?" } ]
{ "AcceptedAnswerId": "269712", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T21:55:52.977", "Id": "269667", "Score": "1", "Tags": [ "python", "python-3.x", "algorithm", "homework" ], "Title": "Generate a string that is not present in a list" }
269667
accepted_answer
[ { "body": "<p>Your algorithm is correct and will always provide a correct answer as the list length equals the string length. As @Toby already pointed out you shall not maintain two indices as you walk row and column on a diagonal.</p>\n<p>Additionally I want to give two more points.</p>\n<h1>Do not mix in the I/O operation with your processing function</h1>\n<p>That does bind your algorithm to the filename and does not allow generic usage and testing. Instead do a function that takes a list of strings and returns a single string. As your algorithm always provides a solution there is no need to return the truth value other than your appointment of course.</p>\n<pre><code>def find_excluded(strings: str) -&gt; Tuple[str, bool]:\n s = ...\n return (s, False)\n</code></pre>\n<p>which you use then like</p>\n<pre><code>strings = load_sequences()\nresult, should_be_false = find_excluded(strings)\n</code></pre>\n<p>Now we can easily do simple tests like</p>\n<pre><code>strings = [&quot;AA&quot;, &quot;AB&quot;]\nresult, _ = find_excluded(strings)\nassert len(result) == len(strings)\nassert result not in strings\n</code></pre>\n<p>You can also test edge cases etc.</p>\n<h1>Try to think in algorithms/filters applied to sequences of data</h1>\n<p>This is very often much more readable and self documenting if you chose good names for your temporaries/functions/expressions. As your algorithm walks the diagonal we name a temporary like that. For the character replacemaent a name like 'invert' sounds nice as the code is binary.</p>\n<pre><code>def find_excluded(strings: str) -&gt; Tuple[str, bool]:\n diagonal = [s[i] for i, s in enumerate(strings)]\n invert = {'A':'B', 'B':'A'}\n inverted = [invert[c] for c in diagonal]\n return (''.join(inverted), False)\n</code></pre>\n<p>That is pretty readdable, isn't it? Note: you may replace the list comprehensions by generator expressions. That allows working on big iterables efficiently.</p>\n<pre><code>def find_excluded(strings: str) -&gt; Tuple[str, bool]:\n diagonal = (s[i] for i, s in enumerate(strings))\n invert = {'A':'B', 'B':'A'}\n inverted = (invert[c] for c in diagonal)\n return (''.join(inverted), False)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-03T19:15:22.140", "Id": "269712", "ParentId": "269667", "Score": "2" } } ]
<p><strong>Context:</strong> I am trying to perform a <code>scan()</code> on a DynamoDB table and apply some conditional operators to a filter expression. The operators however are passed in via AWS Lambda's event field. This means the operator is determined by an external user and my code needs to handle all possible cases. <code>conditionAPIParam</code> is what contains the passed in parameter.</p> <p><strong>Current Solution:</strong> I currently use an if conditional to compare the operator to a set constant and then construct different versions of the db scan() command based on which operator is used.</p> <p><strong>Problem:</strong> This means that I have to construct a different version of the command per operator that I support. This is extremely redundant and leads to a lot of repeated code.</p> <p><strong>Question:</strong> Is there any way I could utilize the same command but just swap the operator (e.g. <code>gt()</code>, <code>begins_with()</code>, <code>lt()</code>) based on the provided conditional?</p> <p><strong>Code:</strong></p> <pre class="lang-py prettyprint-override"><code>GREATER_THAN = &quot;gt&quot; LESS_THAN = &quot;lt&quot; EQUAL = &quot;eq&quot; if conditionAPIParam == GREATER_THAN: query_response = table.scan( FilterExpression=Attr('Timestamp').gt(timestampAPIParam) &amp; Attr('Rule').contains(ruleAPIParam) # The default rule param is '' which is a part of every string ) elif conditionAPIParam == LESS_THAN: query_response = table.scan( FilterExpression=Attr('Timestamp').lt(timestampAPIParam) &amp; Attr('Rule').contains(ruleAPIParam) ) elif conditionAPIParam == EQUAL: query_response = table.scan( FilterExpression=Attr('Timestamp').begins_with(timestampAPIParam) &amp; Attr('Rule').contains(ruleAPIParam) # The default rule param is '' which is a part of every string ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T23:58:15.277", "Id": "532315", "Score": "0", "body": "Can you indicate where `Attr` comes from? I've been unable to find documentation on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T06:01:18.113", "Id": "532326", "Score": "0", "body": "It comes from boto3: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/dynamodb.html#boto3.dynamodb.conditions.Attr" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T08:06:45.090", "Id": "532334", "Score": "1", "body": "Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
{ "AcceptedAnswerId": "269750", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T20:39:34.560", "Id": "269743", "Score": "3", "Tags": [ "python" ], "Title": "Scanning a DynamoDB table using a filter expression with multiple possible comparison operators" }
269743
accepted_answer
[ { "body": "<p>Yes, you should simplify this. Make a dictionary whose key is any of the potential values for <code>conditionAPIParam</code>, and value is a non-bound class function reference.</p>\n<pre class=\"lang-py prettyprint-override\"><code>PARAMS = {\n 'gt': Attr.gt,\n 'lt': Attr.lt,\n 'eq': Attr.begins_with,\n}\nquery_response = table.scan(\n FilterExpression=PARAMS[conditionAPIParam](\n Attr('Timestamp'), # self\n timestampAPIParam,\n ) &amp; Attr('Rule').contains(ruleAPIParam)\n)\n</code></pre>\n<p>With a non-bound reference, the first parameter must be <code>self</code>, which in all cases will be <code>Attr('Timestamp')</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T06:06:42.160", "Id": "532327", "Score": "0", "body": "Interesting solution. Does this solution work because Python allows us to use functions as values to keys in a dict?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T08:59:35.267", "Id": "532336", "Score": "0", "body": "@Reinderien What would be the differences/pros/cons of using this approach vs getattr/methodcaller ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:02:57.267", "Id": "532356", "Score": "1", "body": "@PrithviBoinpally Python allows us to use functions as values basically anywhere (not just in a dict)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:06:43.143", "Id": "532357", "Score": "2", "body": "@kubatucka This approach is simple and compatible with static analysis. A `getattr` approach defeats static analysis and will not benefit from e.g. IDE autocomplete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T00:09:33.917", "Id": "532426", "Score": "1", "body": "@Reinderien That's probably true, but OP should also be aware that they could use `getattr(Attr('Timestamp'),conditionAPIParam)(timestampAPIParam)` and not need `PARAMS`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T01:22:00.900", "Id": "532428", "Score": "2", "body": "@Teepeemm Not directly they can't. Note the difference between `eq` and `begins_with`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T00:09:59.060", "Id": "269750", "ParentId": "269743", "Score": "5" } } ]
<p>I have this piece of code where it based on this condition:</p> <ol> <li>Box Color can only be in red, white and black</li> <li>If the box's type is A then any color is allowed</li> <li>Box's type C is not allowed at all</li> <li>For the gift, only green and blue color is allowed and the size cannot be small</li> <li>Box and gift color cannot be same</li> </ol> <p>views.py</p> <pre><code> boxColor = [&quot;red&quot;, &quot;white&quot;, &quot;black&quot;] giftColor = [&quot;green&quot;, &quot;blue&quot;] if box.color != gift.color: if gift.color in giftColor and gift.size != &quot;small&quot;: if (box.type == &quot;A&quot;) or (box.type != &quot;C&quot; and box.color in boxColor): return True else: return False else: return False else: return False </code></pre> <p>Is there is a way to simplify my code that I can make this more efficient ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:10:31.030", "Id": "532462", "Score": "0", "body": "Welcome to Code Review@SE. A `return` statement looks lacking context without a `def`, and the title doesn't follow site conventions: Please (re)visit [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)" } ]
{ "AcceptedAnswerId": "269812", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T12:04:25.537", "Id": "269810", "Score": "1", "Tags": [ "python" ], "Title": "Checking whether box and gift colors satisfy the given criteria" }
269810
accepted_answer
[ { "body": "<p>Yes, this should be simplified. Prefer sets since you're doing membership checks, and write this as a boolean expression rather than a series of <code>if</code> checks with <code>return</code>s:</p>\n<pre><code>return (\n box.type != 'C'\n and (\n box.type == 'A'\n or box.color in {'red', 'white', 'black'}\n )\n and box.color != gift.color\n and gift.size != 'small'\n and gift.color in {'green', 'blue'}\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T13:48:22.203", "Id": "532466", "Score": "0", "body": "Thankyou so much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T12:52:26.303", "Id": "269812", "ParentId": "269810", "Score": "1" } } ]
<p>I was on Hacker Rank for the first time and there was <a href="https://www.hackerrank.com/challenges/py-collections-namedtuple/problem" rel="nofollow noreferrer">a question</a> that required to get the inputs from STDIN and use <code>collections.namedtuple()</code>. It was my first time working with getting inputs from STDIN so the way I acquired the inputs and used them to calculate the data might not be efficient.</p> <p>The question was to calculate the average mark of the students and was given a multiple line string input with specific data about the student (like: NAME, CLASS, ID) in which one of them is MARKS (I have added an image of a sample STDIN input data below to explain better). But the layout of the input data could change so the code must be able to figure out where the MARKS are in the data and also get the number of students in order to calculate the average of their marks.</p> <p>I came up with a quick way to solve this but was wondering how to appropriately and efficiently acquire the input data and perform the calculation.</p> <p>Briefly, what is a better (pythony, efficient, shorter) way to write my code?</p> <pre><code># Enter your code here. Read input from STDIN. Print output to STDOUT from collections import namedtuple import sys data = [line.rstrip().split() for line in sys.stdin.readlines()] sOMCache = []; n = 0 dataLength = len(data) if 'MARKS' in data[1] : marksIndex = data[1].index('MARKS') for i in range(dataLength) : if n &gt; 1 : sOMCache.append(data[n][marksIndex]) n += 1 sOM = sum([int(x) for x in sOMCache]) Point = namedtuple('Point','x,y') pt1 = Point(int(sOM), int((data[0][0]))) dot_product = ( pt1.x / pt1.y ) print (dot_product) </code></pre> <h2>Samples</h2> <p>Testcase 01:</p> <pre><code>5 ID MARKS NAME CLASS 1 97 Raymond 7 2 50 Steven 4 3 91 Adrian 9 4 72 Stewart 5 5 80 Peter 6 </code></pre> <p>Expected output: <code>78.00</code></p> <hr /> <p>Testcase 02:</p> <pre><code>5 MARKS CLASS NAME ID 92 2 Calum 1 82 5 Scott 2 94 2 Jason 3 55 8 Glenn 4 82 2 Fergus 5 </code></pre> <p>Expected output: <code>81.00</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:24:03.117", "Id": "532672", "Score": "0", "body": "@200_success oh so thats what they meant by change the img to text data. Thanks for the edit." } ]
{ "AcceptedAnswerId": "269888", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T09:12:25.020", "Id": "269868", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "parsing" ], "Title": "Find the average score, given data in a table with labeled columns not in a fixed order" }
269868
accepted_answer
[ { "body": "<p>I liked the fact that you used the <code>sum()</code> builtin function, but I have no idea what <code>sOM</code> or <code>sOMCache</code> mean in <code>sOM = sum([int(x) for x in sOMCache])</code> — &quot;Sum of marks&quot;, maybe? But the capitalization is weird by <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python standards</a>, and this isn't a cache — you wouldn't just eject data from this &quot;cache&quot;, would you?</p>\n<p>I think, as you probably suspected, that you missed the mark for this exercise. The main issues with your solution are:</p>\n<ul>\n<li>Misunderstanding the <code>Point</code>. What you're computing here is an average, not a dot product. The dot product in the tutorial was just to illustrate how you can access member fields within a <code>namedtuple</code> using <code>.x</code> or <code>.y</code>.</li>\n<li>Failure to take advantage of <code>namedtuple</code>. If you do things right, you should be able to write something like <code>row.MARKS</code> to get the value of the <code>MARKS</code> column for a particular <code>row</code>.</li>\n<li>Lack of expressiveness, such that it's not obvious what the code intends to do at a glance.</li>\n</ul>\n<h2>Suggested solution</h2>\n<pre><code>from collections import namedtuple\nfrom statistics import mean\nimport sys\n\ndef records(line_iter):\n &quot;&quot;&quot;\n Read records, one per line, space-separated, following a header.\n \n The header consists of two lines: the first line contains an integer\n specifying the number of records, and the second line specifies the\n column names. Records are yielded as namedtuples, where the fields\n have names specified by the second header row.\n &quot;&quot;&quot;\n n = int(next(line_iter))\n Record = namedtuple('Record', next(line_iter))\n for _ in range(n):\n yield Record(*next(line_iter).split())\n\nprint(mean(float(rec.MARKS) for rec in records(sys.stdin)))\n</code></pre>\n<p>Explanation:</p>\n<p>The final line of code drives all the work: read records from STDIN, and print the mean of the <code>MARKS</code> column. I've chosen to interpret the marks as <code>float</code>s for versatility, but if you're sure that the data are all integers then you could call <code>int(rec.MARKS)</code> instead.</p>\n<p>All of the work to read the input is handled by a generator function. The <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a> describes what it does. As you can see, it takes advantage of the <code>namedtuple</code> to let you refer to the column of interest later.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T21:01:59.617", "Id": "269888", "ParentId": "269868", "Score": "5" } } ]
<p>I wrote the following code to read out a bill from a file and then putting it into a bills-list.</p> <p>The bill contains: &quot;company&quot;, &quot;customer&quot;, Year, Month, Day, Amount, &quot;credit/debit&quot;</p> <p>Is there a nicer way using list comprehension to make this code look better?</p> <pre><code>def read_bills(file = &quot;bills.csv&quot;): &quot;&quot;&quot;Read bills from the file system 'bills.csv'&quot;&quot;&quot; # Create a list in which each bill is entered. bills = [] for line in open(file): bill = line.strip().split(',') for i in range(len(bill)): if i &gt; 1 and i &lt; 5: bill[i] = int(bill[i].strip()) elif i == 5: bill[i] = float(bill[i].strip()) else: bill[i] = bill[i].strip() bills.append(bill) return bills </code></pre> <p><a href="https://i.stack.imgur.com/RcYg5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RcYg5.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:18:20.897", "Id": "532646", "Score": "0", "body": "Use Pandas? That will make this one line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:27:55.467", "Id": "532647", "Score": "0", "body": "Can't use panadas unfortunately" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:28:53.927", "Id": "532648", "Score": "1", "body": "And why would that be? Is this for school?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:29:57.873", "Id": "532649", "Score": "2", "body": "Also: it's good that you've told us your columns, but can you show us the first few lines of a file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:42:02.330", "Id": "532650", "Score": "0", "body": "Yes, and I added a screenshot of the first few lines of a file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T18:01:52.770", "Id": "532652", "Score": "7", "body": "Screenshots are useless; please post a few lines of a file **as text**, including header line…." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T23:45:26.133", "Id": "532675", "Score": "1", "body": "Pandas may be a bit heavy for this but why not use the built-in Python [CSV module](https://docs.python.org/3/library/csv.html) ? It appears that you are parsing a simple CSV file so there is no need for a fancy line parsing routine. Plus, using a [DictReader](https://docs.python.org/3/library/csv.html#csv.DictReader) you could use column names. This would be so much more straightforward." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:52:06.247", "Id": "532708", "Score": "1", "body": "When you try to parse CSV by splitting, you are doing it wrong. Try the implementation on [this CSV](https://en.wikipedia.org/wiki/Comma-separated_values#Example)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:59:48.020", "Id": "269885", "Score": "4", "Tags": [ "python", "homework" ], "Title": "Read bills from a bills.csv file" }
269885
max_votes
[ { "body": "<p>The least appealing, most tedious part of the current code is the conditional\nlogic to handle data conversion. Since you're dealing with a limited number of\ncolumns, you can use a data structure to eliminate the conditionals. (In my\nexperience, smarter or more convenient/suitable data structures are often the\nmost powerful devices to simplify algorithmic logic.) For example, to parse a\nsingle line, one could write something like this:</p>\n<pre><code>def parse_line(line):\n types = (str, str, int, int, int, float, str)\n raw_vals = [val.strip() for val in line.strip().split(',')]\n return [f(val) for val, f in zip(raw_vals, types)]\n</code></pre>\n<p>And if that line-parsing function existed, the overall bill-parsing\nfunction would be pretty trivial:</p>\n<pre><code>def read_bills(file_path):\n with open(file_path) as fh:\n return [parse_line(line) for line in fh]\n</code></pre>\n<p>Don't overlook the implicit suggestion here: separate the detailed logic (line\nparsing) from larger orchestration (opening a file and processing it line by\nline). The latter can usually be quite simple, hardly worth testing or worrying\nabout too much, while the former often requires more effort to ensure\ncorrectness. Reducing the footprint of the code requiring in-depth testing\nis usually a good move to make.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:15:35.827", "Id": "532718", "Score": "0", "body": "I don't believe you need the `.strip()` in `line.strip().split(',')` as each value is stripped after the split." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:23:41.463", "Id": "532722", "Score": "0", "body": "@benh Only the no-argument form of `str.split()` includes the auto-magical behavior of also removing whitespace surrounding the delimiter. For example, do some experimenting with this: `'Foo Bar, Blah, 123'.split(',')`. Alas, further stripping is required. One could do it all in a single split by using `re.split()`, but I probably wouldn't take that route -- extra complexity with little benefit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T18:42:35.893", "Id": "269887", "ParentId": "269885", "Score": "6" } } ]
<p>In my python-based project I have the following problem: I have a list with many entries, with each entry being an object of the same class. This is demonstrated in the code below:</p> <pre><code>#!/usr/bin/env python3 class demo_class: &quot;&quot;&quot;Example class for demonstration&quot;&quot;&quot; def __init__(self, val_a, val_b, val_c): self.val_a = val_a self.val_b = val_b self.val_c = val_c def print_something(self): &quot;&quot;&quot;Foo-function, executed for demonstration&quot;&quot;&quot; print(str(self.val_a) + &quot;, &quot; + str(self.val_b) + &quot;, &quot; + str(self.val_c)) #Data generation list_of_demo_classes = [] for i in range(0, 2): for j in range(0, 2): for k in range(0, 2): local_demo_class = demo_class(val_a = i, val_b = j, val_c = k) list_of_demo_classes.append(local_demo_class) </code></pre> <p>Now I would first select all elements where <code>val_a = 0</code> and <code>val_b = 0</code>, afterwards all elements where <code>val_a = 0</code> and <code>val_b = 1</code>, and so on, until I have called all entries in the list. The current approach is</p> <pre><code>#How can I optimize this? for i in range(0, 2): for j in range(0, 2): for k in range(0, 2): for elem in list_of_demo_classes: if elem.val_a != i: continue if elem.val_b != j: continue if elem.val_c != k: continue elem.print_something() </code></pre> <p>but this approach does look rather brute-force for me. Are there better solutions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T16:06:59.423", "Id": "532825", "Score": "3", "body": "Hey I'm afraid this is too hypothetical to be reviewed? You might need list comprehensions, maybe? Can't say without the complete code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T17:39:19.817", "Id": "532831", "Score": "0", "body": "@kubatucka: This is my full code broken down to an MWE. What I basically want is: \"Get all elements from list `list_of_demo_classes` for which `val_a == i` and `val_b == j`, and then iterate over all possible entries for `val_a` and `val_b`\". My current approach is shown above, but it looks inefficient to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T19:20:22.247", "Id": "532837", "Score": "3", "body": "\"_Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site._\" Minimal Working Examples are for **Stack Overflow**. At **Code Review**, we want actual code, so we can provide a real review. For instance `demo_class` is a horrible class name for several reasons, but creating a review for that is meaningless since it isn't a real class name." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T15:36:26.133", "Id": "269953", "Score": "-1", "Tags": [ "python" ], "Title": "Getting all elements in list with certain attribute value in python - Improved solution compared to loop" }
269953
max_votes
[ { "body": "<p>As best I can tell — based more on your code's behavior than your description of it — you have some objects and you want to print them all in an\norder based on their attribute values. If so, a <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclass</a> could help by\neliminating most of the boilerplate code and by supporting attribute-based\nsorting directly (via <code>order = True</code>). Here's a brief demonstration:</p>\n<pre><code>from dataclasses import dataclass\nfrom random import randint\n\n@dataclass(order = True)\nclass Element:\n a: int\n b: int\n c: int\n\nelements = [\n Element(randint(1, 3), randint(0, 2), randint(0, 2))\n for _ in range(10)\n]\n\nfor e in sorted(elements):\n print(e)\n</code></pre>\n<p>Output from one run:</p>\n<pre><code>Element(a=1, b=0, c=1)\nElement(a=1, b=2, c=2)\nElement(a=2, b=2, c=1)\nElement(a=2, b=2, c=1)\nElement(a=2, b=2, c=2)\nElement(a=3, b=0, c=0)\nElement(a=3, b=1, c=1)\nElement(a=3, b=1, c=2)\nElement(a=3, b=2, c=1)\nElement(a=3, b=2, c=1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T18:38:18.880", "Id": "269955", "ParentId": "269953", "Score": "1" } } ]
<p>I coded a little loop that reduces a dataset by computing the mean of X rows every X rows. <br>I'm working with a dataset of a certain size (8 Millions rows for 10 columns) and my code takes too long to compute the whole dataset.<br> I am using Pandas.<br> Is there a way to improve my loop to make it more efficient and faster ?</p> <pre class="lang-py prettyprint-override"><code> # data is the dataset, pd.DataFrame() # # nb_row is the number of rows to collapse # for example : nb_row = 12 would reduce the dataset by x12 # by computing the mean of 12 rows every 12 rows nb_row = 12 raw_columns = [&quot;f1&quot;, &quot;f2&quot;, &quot;f3&quot;, &quot;f4&quot;] # column names for i in range(0, len(data), nb_row): new_df = new_df.append( pd.DataFrame( [[data[elem].iloc[i : i + nb_row].mean() for elem in raw_columns]], columns=raw_columns, ) ) </code></pre> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T03:11:13.710", "Id": "532941", "Score": "0", "body": "Is one of those \"x rows\" in the top row supposed to be something else? Otherwise, I think youve pretty much got it covered... : ) 3 out of 3 ain't bad; it's perfect! ...sry, I would've edited, but it's slightly over my head. Didn't want to mess it up." } ]
{ "AcceptedAnswerId": "270003", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T19:05:06.057", "Id": "269957", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Compute the mean of every X rows of a pandas DataFrame" }
269957
accepted_answer
[ { "body": "<p>Your current code breaks two major pandas antipatterns, explained in depth by <a href=\"https://stackoverflow.com/users/4909087/cs95\">@cs95</a>:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/a/55557758/13138364\">Avoid iterating a DataFrame</a></li>\n<li><a href=\"https://stackoverflow.com/a/56746204/13138364\">Avoid growing a DataFrame</a></li>\n</ul>\n<p>The more idiomatic approaches are <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.mean.html\" rel=\"nofollow noreferrer\"><code>groupby.mean</code></a> (fastest) and <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html\" rel=\"nofollow noreferrer\"><code>rolling.mean</code></a>:</p>\n<p><a href=\"https://i.stack.imgur.com/GZAE1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GZAE1.png\" width=\"320\"></a></p>\n<hr />\n<h3>1. <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.mean.html\" rel=\"nofollow noreferrer\"><code>groupby.mean</code></a> (fastest)</h3>\n<p>(This is ~5.5x faster than <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html\" rel=\"nofollow noreferrer\"><code>rolling.mean</code></a> at 8M rows.)</p>\n<p>Generate pseudo-groups with <code>data.index // nb_row</code> and take the <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.mean.html\" rel=\"nofollow noreferrer\"><code>groupby.mean</code></a>:</p>\n<pre><code>nb_row = 12\nnew_df = data.groupby(data.index // nb_row).mean()\n\n# f1 f2 f3 f4\n# 0 -0.171037 -0.288915 0.026885 -0.083732\n# 1 -0.018497 0.329961 0.107714 -0.430527\n# ... ... ... ... ...\n# 666665 -0.648026 0.232827 0.290072 0.535636\n# 666666 -0.373699 -0.260689 0.122012 -0.217035\n# \n# [666667 rows x 4 columns]\n</code></pre>\n<p>Note that if the real <code>data</code> has a custom index (instead of a default <code>RangeIndex</code>), then use <code>groupby(np.arange(len(df)) // nb_row)</code> instead.</p>\n<hr />\n<h3>2. <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html\" rel=\"nofollow noreferrer\"><code>rolling.mean</code></a></h3>\n<p><a href=\"https://codereview.stackexchange.com/a/269965/238890\">rak1507's answer</a> covers <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html\" rel=\"nofollow noreferrer\"><code>rolling.mean</code></a> but is missing a key detail.</p>\n<p><code>rolling(nb_row)</code> uses a window size of <code>nb_row</code> <strong>but slides 1 row at a time, not every <code>nb_row</code> rows.</strong></p>\n<ul>\n<li><p>That means slicing with <code>[nb_row-1:]</code> results in the wrong output shape (it's not reduced by a factor of <code>nb_row</code> as described in the OP):</p>\n<pre><code>new_df = data.rolling(nb_row).mean()[nb_row-1:]\nnew_df.shape\n\n# (7999989, 4)\n</code></pre>\n</li>\n<li><p>Instead we should slice with <code>[nb_row::nb_row]</code> to get every <code>nb_row</code><sup>th</sup> row:</p>\n<pre><code>new_df = data.rolling(nb_row).mean()[nb_row::nb_row]\nnew_df.shape\n\n# (666666, 4)\n</code></pre>\n</li>\n</ul>\n<hr />\n<h3>Timings (8M rows*)</h3>\n<pre><code>%timeit data.groupby(data.index // nb_row).mean()\n631 ms ± 56.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n<pre><code>%timeit data.rolling(nb_row).mean()[nb_row::nb_row]\n3.47 s ± 274 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n<p><sup><em>* <code>data = pd.DataFrame(np.random.random((8_000_000, 4)), columns=['f1', 'f2', 'f3', 'f4'])</code></em></sup></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T09:04:26.347", "Id": "532959", "Score": "1", "body": "Oops yeah you're right I forgot to slice every nth element too. Nice answer - til about groupby" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T00:43:23.983", "Id": "270003", "ParentId": "269957", "Score": "3" } } ]
<p>I got this HW question from my freshman year at college - &quot;Create a python function to check whether a string containing only lowercase letters has any repetition in it&quot;.</p> <p>So, I did it a few ways:</p> <ol> <li><p>Brute forced it by checking if a character in the string was present in the substring to the right of it using a nested <code>for</code> loop.</p> </li> <li><p>Created a list and stored every new character in it. Looped through each character in the string and checked if a character was in the list. If so, the string wasn't unique.</p> </li> </ol> <p>Both of these work but I'm looking for another solution. I came up with the following. Can you please tell me how inefficient this one would be?</p> <pre><code>def isUnique(string): ascii_product = 1 for chr in string: ascii_prime = 2 ** (ord(chr) - 95) - 1 if ascii_product % ascii_prime == 0: return False ascii_product *= ascii_prime else: return True </code></pre> <p>If the code is too horrible to understand, here's what I'm trying to do. I loop through each character in the string and with its ASCII value, I create a unique Mersenne prime number associated with it. I then check if the product is divisible by the prime. If it is, the string is not unique. Otherwise, I multiply the product by the prime.</p> <p>This code works as well but I wanted to know how bad it is in terms of efficiency. Also, what's the best way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T10:46:04.313", "Id": "533105", "Score": "7", "body": "\"I create a unique Mersenne prime number\". No you don't. ;) It's a creative idea, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T03:29:44.753", "Id": "533237", "Score": "0", "body": "I got the logic wrong too... probably should have tried a few more values before thinking it worked" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T08:15:41.730", "Id": "533250", "Score": "0", "body": "I think that if you indeed used prime numbers and not just `2**i - 1`, the code would work. It would become really slow, e.g. with a long string of unique unicode chars, but it should work as far as I can tell." } ]
{ "AcceptedAnswerId": "270024", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T17:11:10.397", "Id": "270022", "Score": "15", "Tags": [ "python", "python-3.x" ], "Title": "Check whether a lowercase string has any character repetition" }
270022
accepted_answer
[ { "body": "<p>You should use <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"noreferrer\">sets</a> which are an unordered collection <em>without duplicates</em>. Sets are <a href=\"https://en.wikipedia.org/wiki/Set_(abstract_data_type)\" rel=\"noreferrer\">a fundamental data structure</a> found in many programming languages.</p>\n<p>You should also strive to be a bit more Pythonic. A more natural solution would be as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_unique(string: str) -&gt; bool:\n return len(string) == len(set(string))\n</code></pre>\n<p>I have also used <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> which can also be omitted. Here, they convey that the argument to the function should be a string and return value a boolean. You can learn about later if you want to get more serious with Python.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:09:12.420", "Id": "532988", "Score": "0", "body": "A simple improvement to make this a valid answer would be at least to explain why you've changed `isUnique` to `is_unique`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:30:15.527", "Id": "532990", "Score": "0", "body": "This is a cool solution. Thanks for sharing. Quick side question, how do I write more Pythonic code? Will reading other people's code help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:35:10.883", "Id": "532991", "Score": "0", "body": "@AJNeufeld Thanks for the tip, I added some clarification. I hope someone else can chime in with a more deeper review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:36:22.770", "Id": "532992", "Score": "0", "body": "@1d10t There are many ways in which you can get better. Reading other people's code, reading good books or other material, writing code & getting feedback... all of that should work more or less." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:45:15.040", "Id": "532993", "Score": "0", "body": "@Juho thank you for helping me out. I'm guessing this is probably the most atrocious code you've seen in your life. You think I got any chance as a programmer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:46:49.937", "Id": "532994", "Score": "0", "body": "@1d10t Absolutely - no one's perfect when starting out. If you like it, just keep practicing and feel free to ask more questions here too :-) Good luck!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:49:04.287", "Id": "532995", "Score": "2", "body": "@1d10t \"Pythonic\" doesn't have a standardized meaning. However code which follow's [PEP 8](https://www.python.org/dev/peps/pep-0008/) tends to be more Pythonic than other code. Additionally things like Ned Batchelder's \"Loop Like A Native\" advice also makes code more Pythonic, however the idioms are common in other languages now too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T20:37:51.527", "Id": "533227", "Score": "0", "body": "This may be inefficient if `str` contains the full works of Shakespeare or something large. An optimization may be `len(string) < 26 && len(string) == len(set(string))` If then len is greater than the number of available characters then they can't be unique. Assumes: Standard ASCII 0->127" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T17:44:26.270", "Id": "270024", "ParentId": "270022", "Score": "15" } } ]
<p>I got this HW question from my freshman year at college - &quot;Create a python function to check whether a string containing only lowercase letters has any repetition in it&quot;.</p> <p>So, I did it a few ways:</p> <ol> <li><p>Brute forced it by checking if a character in the string was present in the substring to the right of it using a nested <code>for</code> loop.</p> </li> <li><p>Created a list and stored every new character in it. Looped through each character in the string and checked if a character was in the list. If so, the string wasn't unique.</p> </li> </ol> <p>Both of these work but I'm looking for another solution. I came up with the following. Can you please tell me how inefficient this one would be?</p> <pre><code>def isUnique(string): ascii_product = 1 for chr in string: ascii_prime = 2 ** (ord(chr) - 95) - 1 if ascii_product % ascii_prime == 0: return False ascii_product *= ascii_prime else: return True </code></pre> <p>If the code is too horrible to understand, here's what I'm trying to do. I loop through each character in the string and with its ASCII value, I create a unique Mersenne prime number associated with it. I then check if the product is divisible by the prime. If it is, the string is not unique. Otherwise, I multiply the product by the prime.</p> <p>This code works as well but I wanted to know how bad it is in terms of efficiency. Also, what's the best way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T10:46:04.313", "Id": "533105", "Score": "7", "body": "\"I create a unique Mersenne prime number\". No you don't. ;) It's a creative idea, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T03:29:44.753", "Id": "533237", "Score": "0", "body": "I got the logic wrong too... probably should have tried a few more values before thinking it worked" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T08:15:41.730", "Id": "533250", "Score": "0", "body": "I think that if you indeed used prime numbers and not just `2**i - 1`, the code would work. It would become really slow, e.g. with a long string of unique unicode chars, but it should work as far as I can tell." } ]
{ "AcceptedAnswerId": "270024", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T17:11:10.397", "Id": "270022", "Score": "15", "Tags": [ "python", "python-3.x" ], "Title": "Check whether a lowercase string has any character repetition" }
270022
accepted_answer
[ { "body": "<p>You should use <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"noreferrer\">sets</a> which are an unordered collection <em>without duplicates</em>. Sets are <a href=\"https://en.wikipedia.org/wiki/Set_(abstract_data_type)\" rel=\"noreferrer\">a fundamental data structure</a> found in many programming languages.</p>\n<p>You should also strive to be a bit more Pythonic. A more natural solution would be as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_unique(string: str) -&gt; bool:\n return len(string) == len(set(string))\n</code></pre>\n<p>I have also used <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> which can also be omitted. Here, they convey that the argument to the function should be a string and return value a boolean. You can learn about later if you want to get more serious with Python.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:09:12.420", "Id": "532988", "Score": "0", "body": "A simple improvement to make this a valid answer would be at least to explain why you've changed `isUnique` to `is_unique`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:30:15.527", "Id": "532990", "Score": "0", "body": "This is a cool solution. Thanks for sharing. Quick side question, how do I write more Pythonic code? Will reading other people's code help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:35:10.883", "Id": "532991", "Score": "0", "body": "@AJNeufeld Thanks for the tip, I added some clarification. I hope someone else can chime in with a more deeper review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:36:22.770", "Id": "532992", "Score": "0", "body": "@1d10t There are many ways in which you can get better. Reading other people's code, reading good books or other material, writing code & getting feedback... all of that should work more or less." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:45:15.040", "Id": "532993", "Score": "0", "body": "@Juho thank you for helping me out. I'm guessing this is probably the most atrocious code you've seen in your life. You think I got any chance as a programmer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:46:49.937", "Id": "532994", "Score": "0", "body": "@1d10t Absolutely - no one's perfect when starting out. If you like it, just keep practicing and feel free to ask more questions here too :-) Good luck!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:49:04.287", "Id": "532995", "Score": "2", "body": "@1d10t \"Pythonic\" doesn't have a standardized meaning. However code which follow's [PEP 8](https://www.python.org/dev/peps/pep-0008/) tends to be more Pythonic than other code. Additionally things like Ned Batchelder's \"Loop Like A Native\" advice also makes code more Pythonic, however the idioms are common in other languages now too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T20:37:51.527", "Id": "533227", "Score": "0", "body": "This may be inefficient if `str` contains the full works of Shakespeare or something large. An optimization may be `len(string) < 26 && len(string) == len(set(string))` If then len is greater than the number of available characters then they can't be unique. Assumes: Standard ASCII 0->127" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T17:44:26.270", "Id": "270024", "ParentId": "270022", "Score": "15" } } ]
<p>I have some code that uses a <code>lambda</code> to enhance the functionality. For backward compatibility reasons, this lambda can take one or two arguments. To handle these cases, I now use <code>except TypeError</code> to differentiate in the calls:</p> <pre><code># This should work for both these cases: # l = lambda x: x+2 # l = lambda x,y: x+y try: value = l(10) except TypeError: value = l(10, 20) </code></pre> <p>This works, but could this be made better? What if I decide to have three or more arguments for example?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T10:52:57.187", "Id": "270111", "Score": "0", "Tags": [ "python", "lambda" ], "Title": "Is using except TypeError the right way to do this?" }
270111
max_votes
[ { "body": "<p>I would move the lambda into a full function. There are some schools of though that lambdas should never be assigned and persisted to variables (the alterative being they're directly passed as arguments.</p>\n<p>What your existing code shows is that you'd like the second argument (<code>y</code>) to be optional with a default value of 2 (or is it 20?). Therefore, you could do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def l(x, y=2):\n return x + y\n\nvalue = l(10) # 12\nvalue = l(10, 20) # 30\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T18:00:34.873", "Id": "533281", "Score": "0", "body": "Please refrain from answering low-quality questions that are likely to get closed. Once you've answered, that [limits what can be done to improve the question](/help/someone-answers#help-post-body), making it more likely that your efforts are wasted. It's better to wait until the question is properly ready before you answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T16:21:36.717", "Id": "270124", "ParentId": "270111", "Score": "1" } } ]
<p>I have to write a program in python that will take a number and print a right triangle attempting to use all numbers from 1 to that number. For example:</p> <pre><code>Enter number: 10 Output: 7 8 9 10 4 5 6 2 3 1 Enter number: 6 Output: 4 5 6 2 3 1 Enter number: 20 Output: 11 12 13 14 15 7 8 9 10 4 5 6 2 3 1 </code></pre> <p>For which I have written the following function</p> <pre><code>def print_right_triangle(num): c = 1 k = 0 l = [] while(k &lt; num-1): v = [] for i in range(c): v.append(k+1) k += 1 c += 1 if k &gt; num: break l.append(v) p = len(l) for i in range(p): for j in l[p-(i+1)]: print(j, end=' ') print() return None print_right_triangle(10) </code></pre> <p>It's giving the same output and solved my problem. <strong>I was wondering is there any more pythonic way to do this</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T11:43:43.367", "Id": "533499", "Score": "2", "body": "One liner with a bit of maths to find x(x+1)/2 = n: lambda x: [print(\\*range(1+i*~-i//2, 1+i*-~i//2)) for i in range(int(((1+8*x)**.5-1)/2), 0, -1)]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:27:37.203", "Id": "533509", "Score": "0", "body": "@rak1507 Thank you so much!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:14:34.953", "Id": "533518", "Score": "0", "body": "@rak1507 could you please explain 1+i*~-i//2 this, its so tricky to understand this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:38:39.513", "Id": "533522", "Score": "1", "body": "~-i is magic for (i-1) so it's 1 + i * (i-1) // 2 (sorry: code golfing habits die hard)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T18:54:55.980", "Id": "533542", "Score": "0", "body": "@rak1507 ohhokay....got it..thank you so much for responding!" } ]
{ "AcceptedAnswerId": "270221", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T11:13:24.437", "Id": "270218", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Printing reverse number triangle" }
270218
accepted_answer
[ { "body": "<h3>Optimized != pythonic</h3>\n<p>Optimized means &quot;spending less resources&quot;. &quot;Pythonic&quot; means &quot;using idiomatic Python features&quot;. Sometimes they come together, sometimes don't. Pythonic code is clean and maintainable, while optimized can be very unclear and need many comments.</p>\n<p>Anyway, optimization should start with making the code readable, and pythonic code should be readable.</p>\n<h3>Make more use of Python features</h3>\n<p>List comprehensions, range arguments and unpacking can be very handy. This code</p>\n<pre><code> v = []\n for i in range(c):\n v.append(k+1)\n k += 1\n</code></pre>\n<p>is clearly just a</p>\n<pre><code> v = [k+1+i for i in range(c)]\n k += c\n</code></pre>\n<p>and, changing the range arguments,</p>\n<pre><code> v = list(range(k+1, k+c))\n k += c\n</code></pre>\n<p>And this code</p>\n<pre><code> for j in l[p-(i+1)]:\n print(j, end=' ')\n print()\n</code></pre>\n<p>can be written as</p>\n<pre><code> print(*l[p-(i+1)])\n</code></pre>\n<p>and</p>\n<pre><code>p = len(l)\nfor i in range(p):\n print(*l[p-(i+1)])\n</code></pre>\n<p>is walking the <code>l</code> list backwards, so it's</p>\n<pre><code>for line in reversed(l):\n print(*line)\n</code></pre>\n<p>This is pythonic.</p>\n<h3>Optimizations</h3>\n<p>Change the algorithm. Here you're gathering all the number in a list to output them. But the numbers are all in order, so you can easily avoid lists at all - just make loops with <code>print</code>s.</p>\n<p>First, read <a href=\"https://en.wikipedia.org/wiki/Triangular_number\" rel=\"nofollow noreferrer\">some theory</a>.</p>\n<p>Now you know that only numbers that equal <code>n*(n+1)/2</code> can be used to build such triangles. You can solve <code>n*(n+1)/2 = num</code> as a quadratic equation and round n down to get the number of lines without loops like <a href=\"https://codereview.stackexchange.com/users/251597/rak1507\">rak1507</a> did.</p>\n<p>Next, find formulas for starting and ending numbers in each line to put them into range arguments.</p>\n<p>And now you can code it in three lines.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:27:19.363", "Id": "533508", "Score": "0", "body": "Thank you so much!! for this wonderful explaination" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T12:38:30.200", "Id": "270221", "ParentId": "270218", "Score": "3" } } ]
<p>I have a class <code>Scholar</code> which is basically a teacher in a university. I have to calculate the yearly salary of a scholar instance where the formula is <code>12-month salary + bonus</code><br/> the bonus is determined by the academic_position <br/> if the teacher is:</p> <ul> <li>a Professor --&gt; bonus = 70000</li> <li>an Associate Professor --&gt; bonus = 50000</li> <li>an Assistant Professor --&gt; bonus = 30000</li> </ul> <p>I want to keep the <code>bonus</code> in a separate variable so i implemented it in <code>__init__</code>, but it looks messy. not sure if it is the way to do or not. do you have any suggestion on my code? Is there a way to improve readibility? what normally a pythonista do with this kind of problem?</p> <pre><code>class Scholar: def __init__(self, name, salary, academic_position): self.name = name self.salary = salary self.academic_position = academic_position if self.academic_position == 'Professor': self.bonus = 70000 elif self.academic_position == 'Associate Professor': self.bonus = 50000 elif self.academic_position == 'Assistance Professor': self.bonus = 30000 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T17:28:04.707", "Id": "533583", "Score": "0", "body": "It's likely that it doesn't even make sense to set such an instance variable in the constructor. But we can't really advise you properly based on the tiny code excerpt you've shown here." } ]
{ "AcceptedAnswerId": "270224", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T12:41:45.070", "Id": "270222", "Score": "2", "Tags": [ "python", "object-oriented", "constructor" ], "Title": "Setting instance variable for salary bonus based on academic position" }
270222
accepted_answer
[ { "body": "<p>If you have to stick to using this specific structure, I'd do it like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n _ACADEMIC_POSITIONS_BONUS_MAP = {\n 'Professor': 70000,\n 'Associate Professor': 50000,\n 'Assistance Professor': 30000,\n }\n\n def __init__(self, name, salary, academic_position):\n self.name = name\n self.salary = salary\n self.academic_position = academic_position\n\n @property\n def bonus(self):\n for academic_position, bonus in self._ACADEMIC_POSITIONS_BONUS_MAP.items():\n if self.academic_position == academic_position:\n return bonus\n\n raise ValueError(\n f&quot;Invalid academic position. Allowed: &quot;\n f&quot;{', '.join(self._ACADEMIC_POSITIONS_BONUS_MAP)}&quot;\n )\n</code></pre>\n<p>And as other have mentioned, instead of iterating through the dict itself you can just do this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n # ...\n\n @property\n def bonus(self):\n return self._ACADEMIC_POSITIONS_BONUS_MAP[self.academic_position]\n</code></pre>\n<p>We've created a map between each type of <code>academic_position</code> and its specific <code>bonus</code> and a <code>@property</code> where we return the bonus.</p>\n<p>And then you can use it like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>professor = Scholar(&quot;John Doe&quot;, 30000, &quot;Professor&quot;)\nassociate_professor = Scholar(&quot;Associate John Doe&quot;, 30000, &quot;Associate Professor&quot;)\nassistance_professor = Scholar(&quot;Assistance John Doe&quot;, 30000, &quot;Assistance Professor&quot;)\n\n\nprint(professor.bonus)\nprint(associate_professor.bonus)\nprint(assistance_professor.bonus)\n</code></pre>\n<p>Now, when you need to add another <code>academic_position</code>, you just have to modify <code>_ACADEMIC_POSITIONS_BONUS_MAP</code>.</p>\n<p>Next, in order to calculate the yearly salary, just create another method within your class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n # ...\n\n def get_yearly_salary(self):\n # Note: multiply the salary with 12 if it's monthly-based\n return self.salary + self.bonus\n</code></pre>\n<p>Note: I'm not sure if <code>@property</code> is the best way of doing this. You could've just done something along the lines:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n _ACADEMIC_POSITIONS_BONUS_MAP = {\n 'Professor': 70000,\n 'Associate Professor': 50000,\n 'Assistance Professor': 30000,\n }\n\n def __init__(self, name, salary, academic_position):\n self.name = name\n self.salary = salary\n self.academic_position = academic_position\n\n self.bonus = self.get_bonus()\n\n def get_bonus(self):\n for academic_position, bonus in self._ACADEMIC_POSITIONS_BONUS_MAP.items():\n if self.academic_position == academic_position:\n return bonus\n\n raise ValueError(\n f&quot;Invalid academic position. Allowed: &quot;\n f&quot;{', '.join(self._ACADEMIC_POSITIONS_BONUS_MAP)}&quot;\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:53:30.337", "Id": "533514", "Score": "0", "body": "@ Grajdeano Alex thanks you so much for your answers. so basically @property is like an attribute which has immediate invoked call? we can access simply just like it is an instance variable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:56:17.247", "Id": "533515", "Score": "0", "body": "and you're suggesting that I should write get_bonus() instead of the @property bonus in order to protect the variable from changing outside the class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:10:17.973", "Id": "533517", "Score": "0", "body": "Basically yes. For a deeper read [have at this](https://www.programiz.com/python-programming/property)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:15:53.573", "Id": "533519", "Score": "0", "body": "thanks for the knowledges" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T18:18:48.310", "Id": "533540", "Score": "2", "body": "Iterating over a `dict` to check a value for equality against each key seems to defeat the purpose of using a `dict`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T19:00:19.603", "Id": "533543", "Score": "0", "body": "@GrajdeanuAlex I downvoted this answer because of the terrible use of the dict - it's not great to suggest answers to new people when you clearly haven't got a solid grasp of python yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T10:16:19.220", "Id": "533576", "Score": "1", "body": "@FMc yep, that's correct. It was pretty late when I wrote this. Added extra-comments for that part now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T10:18:33.570", "Id": "533577", "Score": "0", "body": "@rak1507 Fixed now. We're all learning here :) Next time if something is wrong, answer the question yourself and pinpoint what's wrong in other answers and why instead of just throwing out words. That't how OP and others can learn." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:25:46.207", "Id": "270224", "ParentId": "270222", "Score": "1" } } ]
<p>I have a class <code>Scholar</code> which is basically a teacher in a university. I have to calculate the yearly salary of a scholar instance where the formula is <code>12-month salary + bonus</code><br/> the bonus is determined by the academic_position <br/> if the teacher is:</p> <ul> <li>a Professor --&gt; bonus = 70000</li> <li>an Associate Professor --&gt; bonus = 50000</li> <li>an Assistant Professor --&gt; bonus = 30000</li> </ul> <p>I want to keep the <code>bonus</code> in a separate variable so i implemented it in <code>__init__</code>, but it looks messy. not sure if it is the way to do or not. do you have any suggestion on my code? Is there a way to improve readibility? what normally a pythonista do with this kind of problem?</p> <pre><code>class Scholar: def __init__(self, name, salary, academic_position): self.name = name self.salary = salary self.academic_position = academic_position if self.academic_position == 'Professor': self.bonus = 70000 elif self.academic_position == 'Associate Professor': self.bonus = 50000 elif self.academic_position == 'Assistance Professor': self.bonus = 30000 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T17:28:04.707", "Id": "533583", "Score": "0", "body": "It's likely that it doesn't even make sense to set such an instance variable in the constructor. But we can't really advise you properly based on the tiny code excerpt you've shown here." } ]
{ "AcceptedAnswerId": "270224", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T12:41:45.070", "Id": "270222", "Score": "2", "Tags": [ "python", "object-oriented", "constructor" ], "Title": "Setting instance variable for salary bonus based on academic position" }
270222
accepted_answer
[ { "body": "<p>If you have to stick to using this specific structure, I'd do it like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n _ACADEMIC_POSITIONS_BONUS_MAP = {\n 'Professor': 70000,\n 'Associate Professor': 50000,\n 'Assistance Professor': 30000,\n }\n\n def __init__(self, name, salary, academic_position):\n self.name = name\n self.salary = salary\n self.academic_position = academic_position\n\n @property\n def bonus(self):\n for academic_position, bonus in self._ACADEMIC_POSITIONS_BONUS_MAP.items():\n if self.academic_position == academic_position:\n return bonus\n\n raise ValueError(\n f&quot;Invalid academic position. Allowed: &quot;\n f&quot;{', '.join(self._ACADEMIC_POSITIONS_BONUS_MAP)}&quot;\n )\n</code></pre>\n<p>And as other have mentioned, instead of iterating through the dict itself you can just do this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n # ...\n\n @property\n def bonus(self):\n return self._ACADEMIC_POSITIONS_BONUS_MAP[self.academic_position]\n</code></pre>\n<p>We've created a map between each type of <code>academic_position</code> and its specific <code>bonus</code> and a <code>@property</code> where we return the bonus.</p>\n<p>And then you can use it like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>professor = Scholar(&quot;John Doe&quot;, 30000, &quot;Professor&quot;)\nassociate_professor = Scholar(&quot;Associate John Doe&quot;, 30000, &quot;Associate Professor&quot;)\nassistance_professor = Scholar(&quot;Assistance John Doe&quot;, 30000, &quot;Assistance Professor&quot;)\n\n\nprint(professor.bonus)\nprint(associate_professor.bonus)\nprint(assistance_professor.bonus)\n</code></pre>\n<p>Now, when you need to add another <code>academic_position</code>, you just have to modify <code>_ACADEMIC_POSITIONS_BONUS_MAP</code>.</p>\n<p>Next, in order to calculate the yearly salary, just create another method within your class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n # ...\n\n def get_yearly_salary(self):\n # Note: multiply the salary with 12 if it's monthly-based\n return self.salary + self.bonus\n</code></pre>\n<p>Note: I'm not sure if <code>@property</code> is the best way of doing this. You could've just done something along the lines:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n _ACADEMIC_POSITIONS_BONUS_MAP = {\n 'Professor': 70000,\n 'Associate Professor': 50000,\n 'Assistance Professor': 30000,\n }\n\n def __init__(self, name, salary, academic_position):\n self.name = name\n self.salary = salary\n self.academic_position = academic_position\n\n self.bonus = self.get_bonus()\n\n def get_bonus(self):\n for academic_position, bonus in self._ACADEMIC_POSITIONS_BONUS_MAP.items():\n if self.academic_position == academic_position:\n return bonus\n\n raise ValueError(\n f&quot;Invalid academic position. Allowed: &quot;\n f&quot;{', '.join(self._ACADEMIC_POSITIONS_BONUS_MAP)}&quot;\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:53:30.337", "Id": "533514", "Score": "0", "body": "@ Grajdeano Alex thanks you so much for your answers. so basically @property is like an attribute which has immediate invoked call? we can access simply just like it is an instance variable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:56:17.247", "Id": "533515", "Score": "0", "body": "and you're suggesting that I should write get_bonus() instead of the @property bonus in order to protect the variable from changing outside the class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:10:17.973", "Id": "533517", "Score": "0", "body": "Basically yes. For a deeper read [have at this](https://www.programiz.com/python-programming/property)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:15:53.573", "Id": "533519", "Score": "0", "body": "thanks for the knowledges" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T18:18:48.310", "Id": "533540", "Score": "2", "body": "Iterating over a `dict` to check a value for equality against each key seems to defeat the purpose of using a `dict`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T19:00:19.603", "Id": "533543", "Score": "0", "body": "@GrajdeanuAlex I downvoted this answer because of the terrible use of the dict - it's not great to suggest answers to new people when you clearly haven't got a solid grasp of python yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T10:16:19.220", "Id": "533576", "Score": "1", "body": "@FMc yep, that's correct. It was pretty late when I wrote this. Added extra-comments for that part now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T10:18:33.570", "Id": "533577", "Score": "0", "body": "@rak1507 Fixed now. We're all learning here :) Next time if something is wrong, answer the question yourself and pinpoint what's wrong in other answers and why instead of just throwing out words. That't how OP and others can learn." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:25:46.207", "Id": "270224", "ParentId": "270222", "Score": "1" } } ]
<p><a href="https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem" rel="nofollow noreferrer">Climbing the Leaderboard</a></p> <blockquote> <p>An arcade game player wants to climb to the top of the leaderboard and track their ranking. The game uses Dense Ranking, so its leaderboard works like this:</p> <p>The player with the highest score is ranked number <span class="math-container">\$1\$</span> on the leaderboard. Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.</p> <h3>Example</h3> <p><span class="math-container">\$ranked = [100, 90, 90, 80]\$</span></p> <p><span class="math-container">\$player = [70, 80, 105]\$</span></p> <p>The ranked players will have ranks 1, 2, 2, and 3, respectively. If the player's scores are 70, 80 and 105, their rankings after each game are 4<sup>th</sup>, 3<sup>rd</sup> and 1<sup>st</sup>. Return <code>[4, 3, 1]</code>.</p> <h3>Function Description</h3> <p>Complete the climbingLeaderboard function in the editor below.</p> <p>climbingLeaderboard has the following parameter(s):</p> <ul> <li><code>int ranked[n]</code>: the leaderboard scores</li> <li><code>int player[m]</code>: the player's scores</li> </ul> <h3>Returns</h3> <ul> <li><code>int[m]</code>: the player's rank after each new score</li> </ul> <h3>Input Format</h3> <p>The first line contains an integer <span class="math-container">\$n\$</span>, the number of players on the leaderboard. The next line contains space-separated integers <span class="math-container">\$ranked[i]\$</span>, the leaderboard scores in decreasing order. The next line contains an integer, <span class="math-container">\$m\$</span>, the number games the player plays. The last line contains space-separated integers <span class="math-container">\$player[i]\$</span>, the game scores.</p> <h3>Constraints</h3> <ul> <li><span class="math-container">\$1 &lt;= n &lt;= 2 x 10^5\$</span></li> <li><span class="math-container">\$1 &lt;= m &lt;= 2 x 10^5\$</span></li> <li><span class="math-container">\$0 &lt;= ranked[i] &lt;= 10^9\$</span> for <span class="math-container">\$0 &lt;= i &lt; n\$</span></li> <li>The existing leaderboard, <span class="math-container">\$ranked\$</span>, is in descending order.</li> <li>The player's scores, <span class="math-container">\$scores\$</span>, are in ascending order.</li> </ul> <h3>Subtask</h3> <p>For <span class="math-container">\$60%\$</span> of the maximum score:</p> <ul> <li><span class="math-container">\$1 &lt;= n &lt;= 200\$</span></li> <li><span class="math-container">\$1 &lt;= m &lt;= 200\$</span></li> </ul> <h3>Sample Input 1</h3> <pre><code>7 100 100 50 40 40 20 10 4 5 25 50 120 </code></pre> <h3>Sample Output 1</h3> <p>6 4 2 1</p> </blockquote> <p>I keep getting timed out. I think my general logic is right but how can my code be optimized more?</p> <p>I know there are solutions using the bisect module but I've seen very simple ones without using that. From what I can think of, maybe using while loops will speed things up?</p> <pre><code>def climbingLeaderboard(ranked, player): ranked=[i for n, i in enumerate(ranked) if i not in ranked[:n]] #remove duplicates player_rank=[] ranking=len(ranked)+1 start=1 for pi,ps in enumerate(player[::-1]): for ri,r in enumerate(ranked,start=start): if ps&gt;=r: player_rank.append(ri) break else: ranked=ranked[1:] start+=1 else: player_rank.append(ranking) return player_rank[::-1] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T00:22:20.913", "Id": "533887", "Score": "0", "body": "Are you sure the code works at all?" } ]
{ "AcceptedAnswerId": "270377", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T23:02:08.233", "Id": "270371", "Score": "1", "Tags": [ "python", "programming-challenge", "time-limit-exceeded", "binary-search" ], "Title": "HackerRank - Climbing the Leaderboard: I don't understand why my code is exceeding the time limit" }
270371
accepted_answer
[ { "body": "<p><strong>Removing duplicates efficiently</strong></p>\n<pre><code>ranked=[i for n, i in enumerate(ranked) if i not in ranked[:n]]\n</code></pre>\n<p>This line creates a copy of <code>ranked</code> at each iteration, which makes it inefficient.\nSince <code>ranked</code> is already sorted, create a new list and add elements one by one if different from the previous.</p>\n<p>Alternatively, you can use a dictionary that is ordered from Python 3.7.</p>\n<pre><code>ranked = list(dict.fromkeys(ranked))\n</code></pre>\n<p><strong>Rank assignment</strong></p>\n<p>The second part of the algorithm creates many copies of <code>ranked</code> in <code>ranked=ranked[1:]</code>, which might be the issue. As you said, using a while loop can speed things up. Refactored code:</p>\n<pre><code>def climbingLeaderboard(ranked, player):\n ranked = list(dict.fromkeys(ranked))\n player_rank = []\n ranking = len(ranked) + 1\n start = 0\n for pi, ps in enumerate(player[::-1]):\n j = start\n while j &lt; len(ranked):\n if ps &gt;= ranked[j]:\n player_rank.append(j + 1)\n break\n start += 1\n j += 1\n if j == len(ranked):\n player_rank.append(ranking)\n return player_rank[::-1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T22:47:29.377", "Id": "533949", "Score": "0", "body": "Thanks it worked! I think ranked=ranked[1:] was the problem. I'm a bit new to code optimization, can you explain more about how that creates many copies of ranked?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T01:39:02.710", "Id": "533956", "Score": "0", "body": "@MysteriousShadow I am glad I could help. `ranked=ranked[1:]` creates many copies because it's in the for-loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T06:18:31.200", "Id": "270377", "ParentId": "270371", "Score": "2" } } ]
<p>As already written in the title I want to count the numbers in the range (x+1, y) where x and y are integers, in which the sum of the digits in odd places have the same parity of the ones in even places. I made this code:</p> <pre><code>def findIntegers(x, y): count = 0 for k in range(int(x)+1, int(y)+1): odd_sum = 0 even_sum = 0 k = str(k) odd_sum += sum([int(k[i]) for i in range(1, len(k), 2) if i % 2 == 1]) even_sum += sum([int(k[i]) for i in range(0, len(k), 2) if i % 2 == 0]) if (odd_sum % 2) == (even_sum % 2): count += 1 return count </code></pre> <p>The code works but for very big range it's very slow. How can I improve my code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T11:23:41.837", "Id": "533994", "Score": "1", "body": "And clarify the task; is x excluded from the range and y included?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T02:45:23.210", "Id": "534053", "Score": "0", "body": "\"even places have same parity as odd places\" reduces to very simple rule: the mod 2 sum of **all** the digits equals 0. No need to break it into two pieces. Also, if you just look at some example ranges you'll notice a very simple pattern to the count, so you don't need to actually run through the values." } ]
{ "AcceptedAnswerId": "270428", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T10:25:13.987", "Id": "270414", "Score": "6", "Tags": [ "python", "performance", "integer", "interval" ], "Title": "Count the numbers in a range in which the sum of the odds digits have the same parity of the evens one" }
270414
accepted_answer
[ { "body": "<p>First some code simplifications and other adjustments. (1) Your sum\ncalculations don't need the conditional tests, because the ranges already\nensure compliance. (2) They also don't need to be wrapped in a <code>[]</code>. (3)\nEven better, if you switch from ranges to slices, you don't need to loop with\nin the sum calculations: just give a slice directly to <code>sum()</code>. In order to do\nthat, you can perform string-to-int conversion in one place, before summing.\n(4) Because <code>bool</code> is a subclass of <code>int</code>, your count-incrementing code does\nnot require conditional logic. (5) This function is difficult to describe and\nname compactly, but your current name is especially vague. Here's a possible\nrenaming. (6) Finally, and this is done purely to simplify the rest of the\ndiscussion, I have modified the function to do the counting over an inclusive\nrange.</p>\n<pre><code>def n_parity_balanced_integers(x, y):\n count = 0\n for number in range(x, y + 1):\n digits = tuple(map(int, str(number)))\n count += sum(digits[0::2]) % 2 == sum(digits[1::2]) % 2\n return count\n</code></pre>\n<p>Such edits improve the code, but they do not significantly affect the\nalgorithm's speed. It's still a brute-force solution. The key to making further\nprogress is to find a pattern that can be used to radically reduce the needed\ncomputation. One way to find these patterns is to experiment with the data. For\nexample:</p>\n<pre><code># A brief experiment.\nchecks = [\n (0, 9),\n (0, 99),\n (0, 999),\n (0, 9999),\n (10, 19),\n (20, 29),\n (10, 39),\n]\nfor lower, upper in checks:\n print(f'{lower}-{upper}:', n_parity_balanced_integers(lower, upper))\n\n# Output\n0-9: 5\n0-99: 50\n0-999: 500\n0-9999: 5000\n10-19: 5\n20-29: 5\n10-39: 15\n</code></pre>\n<p>In other words, over any inclusive range spanning an entire power-of-ten's\nworth of numbers (or any multiple of that, such as <code>10-39</code>), you can instantly\ncompute the answer without iterating over every discrete number in the range.\nSo the trick to this problem is to start with the full range, decompose it into\nsubcomponents that can be computed instantly, and then brute-force any\nstraggling bits. Give that a shot a see what you come up with.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T20:35:01.453", "Id": "270428", "ParentId": "270414", "Score": "5" } } ]
<p>I have some code that needs to return a <code>datetime</code> of the next 9am or 9pm, UTC. I've figured out some code to do this, but it feels unnecessarily complex to me. Is there a way to simplify this?</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime, timezone, timedelta class NineOClockTimes: @staticmethod def get_next_nineoclock_time(current_time: datetime) -&gt; datetime: if current_time.hour &lt; 9: return NineOClockTimes._get_nineoclock_time(current_time, hour=9) elif current_time.hour &gt;= 21: return NineOClockTimes._get_nineoclock_time(current_time, hour=9, next_day=True) return NineOClockTimes._get_nineoclock_time(current_time, hour=21) @staticmethod def _get_nineoclock_time(current_time, hour, next_day=False): new_time = current_time.replace( hour=hour, minute=0, second=0, microsecond=0, tzinfo=timezone.utc, ) if next_day: new_time += timedelta(days=1) return new_time </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T05:27:41.037", "Id": "534370", "Score": "0", "body": "what if the given `current_time` was 9:49 AM in UTC+1 timezone? (8:49 AM UTC)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:54:12.150", "Id": "534377", "Score": "0", "body": "@hjpotter92 I don't understand the question." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T00:40:14.073", "Id": "270558", "Score": "3", "Tags": [ "python", "python-3.x", "datetime" ], "Title": "Finding the next 9am/pm from now" }
270558
max_votes
[ { "body": "<p>Your function <code>_get_nineoclock_time</code> does two things, it replaces the <code>timezone</code> and it returns the next 9 O'clock time. The function will return different values depending on whether <code>current_time</code> has a timezone or not. That may be unexpected and seems a likely source of bugs. I'd set the timezone somewhere else.</p>\n<p>It is easy to calculate how many hours to add from midnight based on the current hour. Then use <code>timedelta</code> to add that many hours.</p>\n<pre><code>def get_next_nineoclock_time(current_time: datetime) -&gt; datetime:\n hours = 9 if current_time.hour &lt; 9 else 21 if current_time.hour &lt; 21 else 33\n \n midnight = current_time.replace(\n hour=0,\n minute=0,\n second=0,\n microsecond=0,\n )\n \n return midnight + timedelta(hours=hours)\n</code></pre>\n<p>Your could use this formula for <code>hours</code>, but I thinks it is less clear:</p>\n<pre><code>hours = 9 + 12*((current_time.hour + 3)//12)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T03:25:42.203", "Id": "534490", "Score": "0", "body": "Coincidentally, we realized that time zone issue today. I like this solution, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:29:06.083", "Id": "534566", "Score": "0", "body": "@DanielKaplan this timezone issue was what I had pointed out earlier in the comment on question :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T17:16:01.307", "Id": "534577", "Score": "0", "body": "@hjpotter92 ah, sorry I didn't understand it" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T02:32:15.377", "Id": "270603", "ParentId": "270558", "Score": "3" } } ]
<p><a href="https://www.hackerrank.com/challenges/absolute-permutation/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/absolute-permutation/problem</a></p> <p>I know that if you work out the math and logic first, the algorithm can be simplified greatly (shifting indices), but is that the only way to solve this and pass all test cases? Checking if a value is in a list can be slow, but I don't know how to optimize/change that to a better code. Without altering the whole logic of my code, is it possible to tweak it to pass all test cases?</p> <pre><code>def absolutePermutation(number, k): newlist=[] for i in range(1,number+1): bigger=k+i smaller=i-k tmp=set(newlist) if (bigger&gt;number and smaller&lt;=0) or (bigger&gt;number and smaller in tmp) or (smaller&lt;=0 and bigger in tmp): return [-1] if smaller&lt;=0 or smaller in tmp: newn=bigger else: newn=smaller #print(newn) newlist.append(newn) return newlist </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T05:11:46.277", "Id": "534369", "Score": "0", "body": "_Does_ it pass all the test cases?" } ]
{ "AcceptedAnswerId": "270562", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T01:44:59.950", "Id": "270560", "Score": "0", "Tags": [ "python", "performance", "combinatorics" ], "Title": "Absolute Permutation | Hacker Rank: Any way to make this python code faster without changing it's whole logic?" }
270560
accepted_answer
[ { "body": "<p>Yeah, you are recreating <code>tmp</code> every iteration of your loop. This makes your solution O(n^2). You could easily make your solution O(n) by setting <code>tmp</code> before your loop and then updating it along with <code>newlist</code>. The reason your current solution is O(n^2) is that building the tmp set with all the items in newlist would take as long as new list. For example, if <code>newlist=[1,2,3,4,5,6,7,...1000]</code> then constructing the tmp set would take 1000 steps.</p>\n<pre><code>def absolutePermutation(number, k):\n newlist=[]\n tmp=set()\n for i in range(1,number+1):\n bigger=k+i\n smaller=i-k\n if (bigger&gt;number and smaller&lt;=0) or (bigger&gt;number and smaller in tmp) or (smaller&lt;=0 and bigger in tmp):\n return [-1]\n\n if smaller&lt;=0 or smaller in tmp:\n newn=bigger\n else:\n newn=smaller\n\n #print(newn)\n\n newlist.append(newn)\n tmp.add(newn)\n\n return newlist\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T00:53:29.337", "Id": "534485", "Score": "0", "body": "Nice! Such a simple change actually passed all the tests. So I don't need the most efficient but hard to get to algorithm to solve this. Thanks for noticing the inefficiency!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T05:47:27.680", "Id": "270562", "ParentId": "270560", "Score": "1" } } ]
<p>I was doing the Magic Ball 8 project (its task is to read a user's question and output a prediction) on Python and wrote the following code:</p> <pre><code>from random import choice from time import sleep list_of_predictions = [ &quot;Undoubtedly&quot;, &quot;It seems to me - yes&quot;, &quot;It is not clear yet, try again&quot;, &quot;Do not even think&quot;, &quot;A foregone conclusion&quot;, &quot;Most likely&quot;, &quot;Ask later&quot;, &quot;My answer is no&quot;, &quot;No doubt&quot;, &quot;Good prospects&quot;, &quot;Better not to tell&quot;, &quot;According to my information - no&quot;, &quot;You can be sure of this&quot;, &quot;Yes&quot;, &quot;Concentrate and ask again&quot;, &quot;Very doubtful&quot; ] print('I am a magic ball, and I know the answer to any of your questions.') sleep(1) n = input(&quot;What is your name?\n&quot;) print(f'Greetings, {n}.') sleep(1) def is_question(question): return q[-1] == '?' def is_valid_question(question): return ('When' or 'How' or 'Where') not in q again = 'yes' while again == 'yes': print('Enter a question, it must end with a question mark.') q = input() if is_question(q) and is_valid_question(q): sleep(2) print(choice(list_of_predictions)) elif not is_question(q): print('You entered not a question!') continue else: print('You have entered a question that cannot be answered &quot;yes&quot; or &quot;no&quot;!') continue sleep(1) again = input('Are there any other questions?\n') sleep(1) a = input('Come back if they arise!\n') </code></pre> <p>The main feature of my program is that it checks if the user has entered a question, which can be answered &quot;yes&quot; or &quot;no&quot;. It also works with small delays in time (for realism). What do you think about my project implementation?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:57:38.307", "Id": "534378", "Score": "0", "body": "You probably want to reject \"Why?\" and \"Who?\" questions as well..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:58:55.127", "Id": "534379", "Score": "0", "body": "Yes, need to take this into account" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:00:07.657", "Id": "534437", "Score": "4", "body": "@TobySpeight - \"Is the Who the greatest rock band of all time?\" And now we see the difficulty of natural language processing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T20:06:46.647", "Id": "534450", "Score": "0", "body": "@ribs2spare - did you miss the `not` in that condition?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T20:09:56.470", "Id": "534451", "Score": "0", "body": "Sure did! Deleted it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T22:21:01.033", "Id": "534469", "Score": "2", "body": "Forgive me if I am missing some quirk of python, but don't the `is_question` and `is_valid_question` functions completely ignore their inputs as currently implemented?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:36:03.473", "Id": "534477", "Score": "0", "body": "@LOTGP You are completely correct. Also, `('When' or 'How' or 'Where') not in q` will only test `'When' not in q`, since `('When' or 'How' or 'Where')` will evaluate to simply `'When'` ... the first truthy value. A proper way of writing what was intended would be `return all(term not in question for term in ('When', 'How', 'Where'))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T07:27:13.173", "Id": "534506", "Score": "0", "body": "Thanks for the clarification, debugged." } ]
{ "AcceptedAnswerId": "270573", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:40:35.363", "Id": "270566", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Magic ball 8 program" }
270566
accepted_answer
[ { "body": "<p>I'd like to address how you handle the yes/no question controlling the loop.</p>\n<p>The relevant sections of your code are:</p>\n<pre class=\"lang-py prettyprint-override\"><code>again = 'yes'\n\nwhile again == 'yes':\n # [...]\n again = input('Are there any other questions?\\n')\n # [...]\n</code></pre>\n<p>Almost all user input are interpreted as &quot;no&quot;. However, the user has no information that they are supposed to enter the exact string <code>yes</code> for a positive answer. It is common for command line programs to accept <code>y</code> or <code>n</code> as an input, but neither of these will be treated as a positive answer in your code. Same for <code>Yes</code>, <code>YES</code> (different capitalization), <code> yes</code>, <code>yes </code> (leading/trailing white space), <code>yeah</code>, <code>yep</code> (different words), while all of these answer are clearly positives.</p>\n<p>Similarly, inputs that are neither positive nor negative will be interpreted as negative, while the issue may be a typo or a misunderstanding of the answer expected. In this case, the input should be discarded, extra information given to the user on why, and the question asked again.</p>\n<p>This makes handling this input much more complex, but as asking yes/no questions is very common in CLI programs, if you write a function that handles this, you only need to write it once and you are then free to reuse it many more times in the future.</p>\n<p>My take on it is:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_yes_no_input(prompt):\n POSITIVE_VALUES = ['yes',\n 'y',\n 'yeah',\n 'yep',\n 'true',\n '1']\n NEGATIVE_VALUES = ['no',\n 'n',\n 'nope',\n 'false',\n '0']\n while True:\n print(prompt)\n val = input('&gt; ').strip().lower()\n if val in POSITIVE_VALUES:\n return True\n if val in NEGATIVE_VALUES:\n return False\n print('Invalid answer. Please answer yes or no.')\n</code></pre>\n<p>Some comments on my code:</p>\n<ul>\n<li>since the function is meant to be reusable, it takes the question text as an argument (<code>prompt</code>)</li>\n<li>it returns a boolean value, as it can be handled differently according to the use case, and they are easier to work with than strings</li>\n<li>it uses constant lists for positive and negative answer, from which you can easily add or remove values</li>\n<li>the input is <code>strip</code>ped to handle potential leading/trailing white space</li>\n<li>the input is <code>lower</code>ed to handle capitalization issues</li>\n<li>if the input is neither positive or negative, it is rejected and information about the expected answer is given</li>\n</ul>\n<p>Use in your code would be something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>again = True\n\nwhile again:\n # [...]\n again = get_yes_no_input('Are there any other questions?')\n # [...]\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:15:06.430", "Id": "534388", "Score": "0", "body": "Or more advanced way NLP can be used if you want more, happy coding ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:36:49.353", "Id": "534411", "Score": "0", "body": "Thank you for the recomendations!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:41:04.370", "Id": "534413", "Score": "0", "body": "Why did You capitalize lists of positive and negative values? I want the program to match the PEP-8, are list names allowed to be formatted like that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:56:49.110", "Id": "534414", "Score": "0", "body": "@vlados155 All caps are used for constants. Although PEP8 recommends this for module-level constants, there is no recommendations for method- or class-level constants, so I did what I thought was best. You are free to disagree with me and use another naming convention in this case, just be consistent throughout your own code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T14:04:15.900", "Id": "534415", "Score": "0", "body": "Thank You for the clarification." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:01:15.107", "Id": "270573", "ParentId": "270566", "Score": "5" } } ]
<p>I am learning Python and for practice I have written this function which sorts a list.</p> <p>Can you please provide feedback on how I have structured it and what better ways could be there to write it for optimization/structuring?</p> <pre><code>originallist=[5, 4, 0, 3, 2,1] lowervalue=int() duplicatelist=originallist[:] ## This list is used to compare each element of the list with the first index of original list sortedlist=[] ## Sorted list while len(originallist)&gt;0: # See if there are any elements left in list original list lowervalue=0.01 for i in duplicatelist: if originallist[0]&lt;=i: temp=originallist[0] print('Temp: ', temp) elif originallist[0]&gt;i: temp=i print('Temp: ', temp) if lowervalue&gt;temp or lowervalue==0.01: lowervalue=temp print('LowerValue: ', lowervalue) sortedlist.append(lowervalue) print('Sorted List: ', sortedlist) duplicatelist.remove(lowervalue) print('Duplicate List: ', duplicatelist) originallist.remove(lowervalue) print('original List: ', originallist, ' \n') print(f'Sorted List :' , sortedlist) </code></pre> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:22:15.813", "Id": "534443", "Score": "0", "body": "You've implemented an insertion sort (I think), which is inherently not really an optimal way to sort things. Do you want answers within the context of implementing insertion sorting in python or optimal sorting of a list in general? (i.e. `originallist.sort()`) :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:33:02.610", "Id": "534447", "Score": "0", "body": "Thank you for the feedback @JeffUk! It would be great if you could share insights on optimal sorting of list in general. list.sort(). And also any feedback to improve the thinking pattern to develop the algorithms based on the above code e.g. if I should be changing the mindset to approach a problem etc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:36:25.147", "Id": "534448", "Score": "0", "body": "@JeffUK It's selection sort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:46:59.923", "Id": "534449", "Score": "0", "body": "@KellyBundy I was just about to change my comment after doing some research. Should have taken Compsci instead of IT.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T22:17:20.147", "Id": "534467", "Score": "1", "body": "I have added the [tag:reinventing-the-wheel] tag as otherwise the answer \"use the [Timsort](https://en.wikipedia.org/wiki/Timsort) built into Python from Python 2.3 by using `list.sort()` or `sorted`\" is 'the best' but possibly not too helpful answer." } ]
{ "AcceptedAnswerId": "270602", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:47:50.107", "Id": "270567", "Score": "0", "Tags": [ "python", "beginner", "python-3.x", "sorting", "reinventing-the-wheel" ], "Title": "Simple sort function" }
270567
accepted_answer
[ { "body": "<p>There's some odd features to this code, even for a coding practice exercise. Python of course has <a href=\"https://docs.python.org/3.7/library/functions.html#sorted\" rel=\"nofollow noreferrer\">a couple</a> of <a href=\"https://docs.python.org/3.7/library/stdtypes.html#list.sort\" rel=\"nofollow noreferrer\">list sorting</a> techniques which <strong>you should absolutely use</strong> in normal circumstances.</p>\n<p>So <em>accepting</em> that you are doing this for practice, I wonder what the point of the <code>duplicatelist</code> is? Or indeed <code>temp</code>? Are these development fossils of some earlier process that you have modified? Looping across this list just seems to find the minimum value in the remaining original list anyway, so</p>\n<pre><code>originallist=[5, 4, 8, 2, 3, 6, 0, 1, 7]\n\nsortedlist=[] ## Sorted list \n\nwhile len(originallist)&gt;0: # See if there are any elements left in original list\n\n lowervalue = originallist[0]\n for i in originallist: \n if lowervalue &gt; i:\n lowervalue = i\n print('New LowerValue: ', lowervalue)\n\n sortedlist.append(lowervalue)\n print('Growing Sorted List: ', sortedlist)\n originallist.remove(lowervalue)\n print('Reduced Original List: ', originallist, ' \\n')\n \n\nprint('Sorted List :' , sortedlist)\n</code></pre>\n<p>would apparently do the same.</p>\n<p>Of course there is also a <a href=\"https://docs.python.org/3.7/library/functions.html#min\" rel=\"nofollow noreferrer\">min</a> function that would find <code>lowervalue</code> quickly. This eliminates the inner loop (is this maybe why you didn't use it?):</p>\n<pre><code>originallist = [5, 4, 8, 2, 3, 6, 0, 1, 7]\n\nsortedlist=[] ## Sorted list \n\nwhile len(originallist)&gt;0: # See if there are any elements left in original list\n\n lowervalue = min(originallist)\n print('LowerValue: ', lowervalue)\n\n sortedlist.append(lowervalue)\n print('Growing Sorted List: ', sortedlist)\n originallist.remove(lowervalue)\n print('Reduced Original List: ', originallist, ' \\n')\n \n\nprint('Sorted List :' , sortedlist)\n</code></pre>\n<p>Using <code>remove</code> from a list can be slow - effectively rewriting the remainder of the list. For the purposes you have here, I don't think it makes an appreciable difference and has the slight advantage of being easy to understand.</p>\n<p>One construct you will often see in a reducing list is phrasing the <code>while</code> loop like this:</p>\n<pre><code>while originallist:\n</code></pre>\n<p>... any non-empty list evaluates as <code>True</code> in such a test, so this is the same test as you are making.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T01:42:38.223", "Id": "534486", "Score": "0", "body": "@Syed You have to be careful with magic numbers as sentinel values. If I put `0.01` into your original list, it doesn't get sorted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:15:58.907", "Id": "534510", "Score": "0", "body": "Thank you soo much Joffan!\n\nYour code makes a lot more sense. It is just that I was viewing the problem from very different perspective (given I have started with python recently with no back experience in algorithms and coding). The initial thought was to compare the originallist elements with itself and to visualize it better I went ahead with duplicating the list and comparing the elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:16:05.617", "Id": "534511", "Score": "0", "body": "The thought process behind the variable **temp** was there to store the smaller value when ever it compared 2 elements (the one from original list being compared to the one from duplicate). And then compare it with **lowervalue** to see if it is smaller among the list till that point in the iteration. But I can see your method is much simpler and efficient. I just could not see it that way while coding. \n\nI did not use the min function intentionally as I was trying to write code without python helping with the built in functions for practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:17:29.217", "Id": "534512", "Score": "0", "body": "Yes Teepeemm! I was struggling with what value to initialize for **lowervalue** but now i see we should do it with the first value of originallist as in the above code!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T00:31:28.110", "Id": "270602", "ParentId": "270567", "Score": "3" } } ]
<p>I want to find if all of a list of substrings exist in a string, in the correct order (with or without spaces between them), it seems to be a good use for regex.</p> <p>I think I need to build a regex filter of <code>&quot;a.*b.*c&quot;</code> and use search to find that anywhere in my string.</p> <p>Are there any other approaches I could consider or built in functions that might do this for me?</p> <pre><code>from re import search def are_substrings_in_text(substrings,text): return search(&quot;&quot;.join([s+&quot;.*&quot; for s in substrings]),text) is not None print(are_substrings_in_text([&quot;a&quot;,&quot;b&quot;,&quot;c&quot;],&quot;abacus&quot;)) # &gt;True print(are_substrings_in_text([&quot;a&quot;,&quot;c&quot;,&quot;b&quot;],&quot;abacus&quot;)) # &gt;False print(are_substrings_in_text([&quot;a&quot;,&quot;c&quot;,&quot;z&quot;],&quot;abacus&quot;)) # &gt;False </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T18:51:19.507", "Id": "270589", "Score": "0", "Tags": [ "python", "regex" ], "Title": "Python function for finding if all substrings exist in a string in sequence" }
270589
max_votes
[ { "body": "<p>The problem with your current approach is that it can give incorrect results\nor raise an exception if any of the substrings contain characters that\nhave special meaning in Python regular expressions.</p>\n<pre><code>are_substrings_in_text(['a', '.', 's'], 'abacus')) # Returns True\nare_substrings_in_text(['a', '+', 's'], 'abacus')) # Raises exception\n</code></pre>\n<p>The solution is to escape such characters so that they are handled as\nliteral substrings. This illustration also makes a few cosmetic adjustments\nto simplify things for readability:</p>\n<pre><code>from re import search, escape\n\ndef are_substrings_in_text(substrings, text):\n pattern = '.*'.join(escape(s) for s in substrings)\n return bool(search(pattern, text))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:21:27.913", "Id": "534475", "Score": "2", "body": "Any reason you're not using `'.*'.join(escape(s) for s in substrings)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:51:12.867", "Id": "534482", "Score": "1", "body": "@AJNeufeld I blame my aging mind." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:32:56.553", "Id": "270593", "ParentId": "270589", "Score": "4" } } ]
<p>When fridays_135 is called, a list of dates between the start date and end date is produces by date_range. That list is then narrowed down to just the Friday dates and then grouped by month by fridays_by_month. Finally, fridays_135 loops through those groups of months, extracts the 0th, 2nd, and 4th element in that list, and then appends them to the fri_135 list to produce a list of dates corresponding to the 1st, 3rd, and 5th Friday of ever month within the original date range, ordered by year and then by month.</p> <pre><code>from datetime import date, timedelta start_date = date(2021, 1, 1) end_date = date(2025, 12, 31) ''' Returns a list of dates between two dates (inclusive)''' def date_range(start = start_date, end = end_date): delta = end - start dates = [start + timedelta(days=i) for i in range(delta.days + 1)] return dates ''' Returns a list of lists containing the Friday dates for each month in a given range''' def fridays_by_month(): year = range(1, 13) years = range(start_date.year, end_date.year + 1) date_range_fris = [date for date in date_range() if date.strftime('%a') == &quot;Fri&quot;] range_fris = [] for yr in years: for month in year: month_fris = [] for date in date_range_fris: if date.strftime('%m') == str(f'{month:02}') and date.year == yr: month_fris.append(date) range_fris.append(month_fris) month_fris = [] return range_fris '''Returns a list of first, third, and fifth Fridays of each month in a given range of years, as a string, ordered by year and then by month''' def fridays_135(): fri_ordinals = [0, 2, 4] month_fris = fridays_by_month() fri_135 = [] for month in month_fris: for index, date in enumerate(month): if index in fri_ordinals: fri_135.append(str(date)) return fri_135 print(fridays_135()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T09:21:49.910", "Id": "534619", "Score": "0", "body": "You shouldn't use comments to describe your function, but [docstrings](https://www.python.org/dev/peps/pep-0257/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T19:08:55.710", "Id": "534628", "Score": "0", "body": "I have rolled back Rev 5 → 3. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T22:18:36.907", "Id": "534635", "Score": "0", "body": "For `start_date = date(2021, 1, 8)`, the first date you produce is `'2021-01-08'`. Is that actually correct? That's the month's second Friday..." } ]
{ "AcceptedAnswerId": "270628", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:01:04.153", "Id": "270620", "Score": "3", "Tags": [ "python", "python-3.x", "datetime" ], "Title": "Produce a list of every 1st, 3rd, and 5th Friday of each month in a date range" }
270620
accepted_answer
[ { "body": "<p>It seems rather inefficient to generate every date, then filter out non-Fridays, then filter out ones that arent't the first, third, or fifth Friday. Calculate directly them instead.</p>\n<p>Find the first Friday in the range:</p>\n<pre><code>friday = start + timedelta((FRIDAY - start.weekday())%7)\n</code></pre>\n<p>Move forward a week if it's not the 1st, 3rd, or 5th Friday:</p>\n<pre><code>ONE_WEEK = timedelta(weeks=1)\n\nweek = (friday.day - 1)//7 + 1\nif week not in (1,3,5):\n friday += ONE_WEEK\n</code></pre>\n<p>While <code>friday</code> is still in the data range, yield the date. If it's the 1st or 3d Friday, add one week, otherwise add two weeks (day 22 is the start of the 4th week):</p>\n<pre><code>TWO_WEEKS = timedelta(weeks=2)\n\nwhile friday &lt; end:\n yield friday\n \n if friday.day &lt; 22:\n friday += TWO_WEEKS\n else:\n friday += ONE_WEEK\n</code></pre>\n<p>Putting it all together:</p>\n<pre><code># date.weekday() returns 0 for Monday, so 4 = Friday\nFRIDAY = 4\n\nONE_WEEK = timedelta(weeks=1)\nTWO_WEEKS = timedelta(weeks=2)\n\ndef gen_friday_135(start, end):\n friday = start + timedelta((FRIDAY - start.weekday())%7)\n \n week = (friday.day - 1)//7 + 1\n if week not in (1,3,5):\n friday += ONE_WEEK\n\n while friday &lt; end:\n yield friday\n \n if friday.day &lt; 22:\n friday += TWO_WEEKS\n else:\n friday += ONE_WEEK\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T22:17:58.293", "Id": "534596", "Score": "0", "body": "Wow, almost all of my code is is unnecessary!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T18:15:50.843", "Id": "534625", "Score": "0", "body": "What is the purpose of the minus 1 in the week variable? I tried the generator with and without that minus 1, and it produced the same list in both cases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T23:39:50.363", "Id": "534640", "Score": "1", "body": "@StephenWilliams, `friday.day` returns integers in the range 1-31. The minus one converts it so the range starts at zero so the // operator gives the correct week number. Without it, the formula would calculate the 7th as being in the second week." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T02:56:20.860", "Id": "534647", "Score": "0", "body": "That makes sense to me. I'm still wondering why its removal didn't affect the list, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T04:24:42.123", "Id": "534648", "Score": "1", "body": "@StephenWilliams, without the -1 `gen_friday_135(start=date(2021, 5, 2),\n end=date(2021, 5, 30))` will yield the 5/14 and 5/28 (the 2nd and 4th Fridays) instead of 5/7 and 5/21 (the 1st and 3rd Fridays)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T20:00:08.687", "Id": "270628", "ParentId": "270620", "Score": "9" } } ]
<p>I had to write a custom function to load a yaml file from the current working directory. The function itself works and my intention was to write it in a pure fashion but my senior colleague told me that the way I wrote this function is utterly bad and I have to rewrite it.</p> <p>Which commandment in Python did I violate? Can anyone tell me what I did wrong here and how a &quot;professional&quot; solution would look like?</p> <pre><code>from typing import Dict import yaml from yaml import SafeLoader from pathlib import Path import os def read_yaml_from_cwd(file: str) -&gt; Dict: &quot;&quot;&quot;[reads a yaml file from current working directory] Parameters ---------- file : str [.yaml or .yml file] Returns ------- Dict [Dictionary] &quot;&quot;&quot; path = os.path.join(Path.cwd().resolve(), file) if os.path.isfile(path): with open(path) as f: content = yaml.load(f, Loader=SafeLoader) return content else: return None content = read_yaml_from_cwd(&quot;test.yaml&quot;) print(content) </code></pre>
[]
{ "AcceptedAnswerId": "270626", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T18:13:04.213", "Id": "270625", "Score": "2", "Tags": [ "python", "python-3.x", "file-system" ], "Title": "Read file from current path in Python" }
270625
accepted_answer
[ { "body": "<p>Which commandment did you violate? Using <code>os.path</code> and <code>pathlib</code> in the same breath! <code>pathlib</code> is an object-oriented replacement to <code>os.path</code>.</p>\n<pre><code> path = os.path.join(Path.cwd().resolve(), file)\n if os.path.isfile(path):\n with open(path) as f:\n</code></pre>\n<p>could be written as:</p>\n<pre><code> path = Path.cwd().joinpath(file)\n if path.is_file():\n with path.open() as f:\n</code></pre>\n<p>or since you're starting at the current directory, simply:</p>\n<pre><code> path = Path(file)\n if path.is_file():\n with path.open() as f:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:00:03.640", "Id": "534587", "Score": "0", "body": "I am using `ruamel yaml` in my own project, so I might be missremembering the details. I thought one could simply do `content = yaml.load(path, Loader=SafeLoader)` directly on the path without having to explicitly open it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:05:33.057", "Id": "534589", "Score": "0", "body": "@N3buchadnezzar That may be true; I haven't used `yaml` at all. My answer focused on the mashup between `os.path` and `pathlib`, stopping just before the `yaml.load(...)` line for that very reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:06:06.347", "Id": "534590", "Score": "0", "body": "thank you, very helpful!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T18:55:31.570", "Id": "270626", "ParentId": "270625", "Score": "3" } } ]
<p>I am trying to write a simple rock paper scissors game in pycharm using classes and pygame. So far, I have not incorporated pygame yet. My idea is to import images that change in regards to the user's choice and the computer's random choice.</p> <p>This is what I have so far:</p> <pre><code>import random class RockPaperScissors: def __init__(self): self.wins = 0 self.losses = 0 self.ties = 0 self.options = {'rock': 0, 'paper': 1, 'scissors': 2} def random_choice(self): return random.choice(list(self.options.keys())) def check(self, player, machine): result = (player - machine) % 3 if result == 0: self.ties += 1 print(&quot;It is a tie!&quot;) elif result == 1: self.wins += 1 print(&quot;You win!&quot;) elif result == 2: self.losses += 1 print(&quot;The machine wins! Do you wish to play again?&quot;) def score(self): print(f&quot;You have {self.wins} wins, {self.losses} losses, and &quot; f&quot;{self.ties} ties.&quot;) def play(self): while True: user = input(&quot;What would you like to choose? (The choices are ROCK,PAPER,SCISSORS): &quot;).lower() if user not in self.options.keys(): print(&quot;Invalid input, try again!&quot;) else: machine_choice = self.random_choice() print(f&quot;You've picked {user}, and the computer picked {machine_choice}.&quot;) self.check(self.options[user], self.options[machine_choice]) def re_do(self): retry = input('Do you wish to play again? (y/n): ').lower() if retry == 'n': exit() elif retry == 'y': self.play() else: print(&quot;Invalid input&quot;) if __name__ == &quot;__main__&quot;: game = RockPaperScissors() while True: game.play() game.score() game.re_do() </code></pre> <p>In the future, I would like to convert this to use <code>pygame</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T21:18:07.060", "Id": "534594", "Score": "0", "body": "Could you double check your indentation? If you highlight everything and click `{}`, that should get you started. Otherwise, your last few lines aren't rendering correctly." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T20:52:34.433", "Id": "270630", "Score": "1", "Tags": [ "python", "beginner", "rock-paper-scissors" ], "Title": "Simple Rock Paper Scissors game in Python" }
270630
max_votes
[ { "body": "<h1>Good things</h1>\n<p>You mostly follow PEP8 styling conventions, making your code quite readable. The only exception I see is an extra blank line at the beginning of the <code>score</code> and <code>play</code> methods.</p>\n<p>Also, it is good thinking to wrap your game state into a class for future integration into a more complex project. It is also a good use of a main guard at the end.</p>\n<p>However, there are things that need to be improved to reach your end goal.</p>\n<h1>Things to improve</h1>\n<h2>Game loop logic</h2>\n<p>Your game loop logic fails completely: execution loops forever inside the <code>play()</code> method, and thus the <code>game.score()</code> and <code>game.re_do()</code> are never called. The game never ends and the total score is never diplayed.</p>\n<p>You should remove one of the infinite loop, and handle it properly.</p>\n<p>I would have a <code>run(self)</code> instance method that goes something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class RockPaperScissors\n\n # some stuff\n\n def run(self):\n play_again = True\n while play_again:\n player_move = get_player_input()\n machine_move = get_machine_input()\n winner = get_winner(player_move, machine_move)\n show_message(winner, score)\n play_again = get_yes_no_input()\n\n\nif __name__ == &quot;__main__&quot;:\n game = RockPaperScissors()\n game.run()\n</code></pre>\n<p>It still has some issues I'll address later (for later integration in a PyGame project), but at it should behave as expected potential issues can be worked on one at a time, in each of the method called.</p>\n<h2>Separation of concern</h2>\n<p>Although you tried to separate logic (by implementing a game class) from display, you failed and mix both all over the code.</p>\n<p>For example, the <code>check()</code> method should return the winner instead of displaying a message. Further down the line, if you want to implement a GUI with PyGame, you can handle a function return, or query the state of member variables, but a <code>print</code> output will be no use.</p>\n<p>Same goes from getting input. Eventually, inputs will be supplied by a PyGame instance through widgets or something. You should put all console-related actions (<code>print</code> and <code>input</code>) in separate methods that you should be able to override, depending on how you want to use the game class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T10:51:28.027", "Id": "270645", "ParentId": "270630", "Score": "2" } } ]
<p>I want to print the below pattern</p> <pre><code>* * * * * * * * * * * * * * * </code></pre> <p><strong>My logic written</strong></p> <pre><code>for row in range(1,6): for col in range(1,6): if row is col: print(row * '* ') </code></pre> <p>Can someone review the code and suggest any improvements needed</p> <p>The code which i have written is it a right approach ?</p>
[]
{ "AcceptedAnswerId": "270640", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T04:21:23.580", "Id": "270639", "Score": "3", "Tags": [ "python", "design-patterns" ], "Title": "Design a pattern using python" }
270639
accepted_answer
[ { "body": "<p>Welcome to Code Review.</p>\n<p>Your code is literally 4 lines. So there isn't much to review.</p>\n<ul>\n<li><p>Do not use the <code>is</code> operator to compare the integers. See <a href=\"https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is\">difference between <code>is</code> and <code>==</code></a></p>\n</li>\n<li><p>You can save the nested loop: you are already ensuring <code>col == row</code> so you can instead write:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>for row in range(1,6):\n print(&quot;* &quot; * row)\n</code></pre>\n<ul>\n<li>If we want to get technical, the code you have written has a time complexity of <strong>O(n^3)</strong>, but the problem can be solved in <strong>O(n^2)</strong>. You can read more on this topic <a href=\"https://www.google.com/amp/s/www.mygreatlearning.com/blog/why-is-time-complexity-essential/%3famp\" rel=\"nofollow noreferrer\">here</a>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T05:01:41.520", "Id": "270640", "ParentId": "270639", "Score": "4" } } ]