body
stringlengths
144
5.53k
comments
list
meta_data
dict
question_id
stringlengths
1
6
yield
stringclasses
2 values
answers
list
<p><strong>Problem:</strong></p> <p>Given a string <code>aaabbcccaad</code> print the no. of occurrence of the character in the same order in which the character occurred.</p> <p>Expected output: <code>(a, 3), (b, 2), (c, 3), (a, 2), (d, 1)</code></p> <p><strong>The approach:</strong></p> <ol> <li>Loop through each character.</li> <li>When the next character is not same as the current character, record the next character and its position.</li> <li>count of occurence = Iterate the <code>pos_list</code> (position list ), take the difference</li> <li>Return character and its count in in the same order</li> </ol> <p><strong>Solution:</strong></p> <pre><code>def seq_count(word): wlen = len(word) pos = 0 pos_list=[pos] alph = [word[0]] result = [] for i in range(wlen): np = i+1 if np &lt; wlen: if word[i] != word[i+1]: pos = i+1 pos_list.append(pos) alph.append(word[i+1]) pos_list.append(wlen) for i in range(len(pos_list)-1): result.append((alph[i], pos_list[i+1] - pos_list[i])) return result print seq_count(&quot;aaabbcccaad&quot;) </code></pre> <p>Note:</p> <p>I know this may not be the conventional solution, i was finding difficult to count the character and maintain its count as we iterate through the string, since I'm a beginner in python. Pls let me know how can i do it better.</p>
[]
{ "AcceptedAnswerId": "260991", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T16:04:50.980", "Id": "260986", "Score": "2", "Tags": [ "python" ], "Title": "Return character frequency in the order of occurrence" }
260986
accepted_answer
[ { "body": "<p>Problems like this tend to be annoying: so close to a simple solution, except for the need to be adjusting state during the loop. In this case, <code>itertools.groupby()</code> offers a shortcut, because its grouping function defaults to an identity, which is exactly what you need.</p>\n<pre><code>from itertools import groupby\n\ndef seq_count(word):\n return [\n (char, len(tuple(g)))\n for char, g in groupby(word)\n ]\n</code></pre>\n<p>If you don't want to use another library, you can reduce the bookkeeping a bit by yielding rather than returning and by iterating directly over the characters rather than messing around with indexes. But even with such simplifications, tedious annoyances remain. Anyway, here's one way to reduce the pain a little. The small code comments are intended to draw attention to the general features of this pattern, which occurs in many types of problems.</p>\n<pre><code>def seq_count(word):\n if word:\n # Initialize.\n prev, n = (word[0], 0)\n # Iterate.\n for char in word:\n if char == prev:\n # Adjust state.\n n += 1\n else:\n # Yield and reset.\n yield (prev, n)\n prev, n = (char, 1)\n # Don't forget the last one.\n if n:\n yield (prev, n)\n\nexp = [('a', 3), ('b', 2), ('c', 3), ('a', 2), ('d', 1)]\ngot = list(seq_count(&quot;aaabbcccaad&quot;))\nprint(got == exp) # True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T18:30:59.157", "Id": "515050", "Score": "0", "body": "Thanks! The first solution looks really good. But most of the interviewers won't accept that. Any suggestions to improve upon these kinda solution thinking?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T18:50:39.637", "Id": "515056", "Score": "2", "body": "@ManivG Find better interviewers! Mostly I'm joking, but not entirely. Don't forget that you are interviewing them too. Sensible interviewers will reward a candidate familiar with the full power of a language (eg knowing `itertools`), even if they also ask for a roll-your-own solution. As far as improving, I advise lots of practice trying to solve **practical problems** (eg on StackOverflow or here). Place less emphasis on problems requiring semi-fancy algorithms and focus heavily on bread-and-butter questions. Pay attention to how different people solve such problems and steal their ideas." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T17:14:15.327", "Id": "260991", "ParentId": "260986", "Score": "3" } } ]
<p><strong>Problem:</strong></p> <p>Given a string <code>aaabbcccaad</code> print the no. of occurrence of the character in the same order in which the character occurred.</p> <p>Expected output: <code>(a, 3), (b, 2), (c, 3), (a, 2), (d, 1)</code></p> <p><strong>The approach:</strong></p> <ol> <li>Loop through each character.</li> <li>When the next character is not same as the current character, record the next character and its position.</li> <li>count of occurence = Iterate the <code>pos_list</code> (position list ), take the difference</li> <li>Return character and its count in in the same order</li> </ol> <p><strong>Solution:</strong></p> <pre><code>def seq_count(word): wlen = len(word) pos = 0 pos_list=[pos] alph = [word[0]] result = [] for i in range(wlen): np = i+1 if np &lt; wlen: if word[i] != word[i+1]: pos = i+1 pos_list.append(pos) alph.append(word[i+1]) pos_list.append(wlen) for i in range(len(pos_list)-1): result.append((alph[i], pos_list[i+1] - pos_list[i])) return result print seq_count(&quot;aaabbcccaad&quot;) </code></pre> <p>Note:</p> <p>I know this may not be the conventional solution, i was finding difficult to count the character and maintain its count as we iterate through the string, since I'm a beginner in python. Pls let me know how can i do it better.</p>
[]
{ "AcceptedAnswerId": "260991", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T16:04:50.980", "Id": "260986", "Score": "2", "Tags": [ "python" ], "Title": "Return character frequency in the order of occurrence" }
260986
accepted_answer
[ { "body": "<p>Problems like this tend to be annoying: so close to a simple solution, except for the need to be adjusting state during the loop. In this case, <code>itertools.groupby()</code> offers a shortcut, because its grouping function defaults to an identity, which is exactly what you need.</p>\n<pre><code>from itertools import groupby\n\ndef seq_count(word):\n return [\n (char, len(tuple(g)))\n for char, g in groupby(word)\n ]\n</code></pre>\n<p>If you don't want to use another library, you can reduce the bookkeeping a bit by yielding rather than returning and by iterating directly over the characters rather than messing around with indexes. But even with such simplifications, tedious annoyances remain. Anyway, here's one way to reduce the pain a little. The small code comments are intended to draw attention to the general features of this pattern, which occurs in many types of problems.</p>\n<pre><code>def seq_count(word):\n if word:\n # Initialize.\n prev, n = (word[0], 0)\n # Iterate.\n for char in word:\n if char == prev:\n # Adjust state.\n n += 1\n else:\n # Yield and reset.\n yield (prev, n)\n prev, n = (char, 1)\n # Don't forget the last one.\n if n:\n yield (prev, n)\n\nexp = [('a', 3), ('b', 2), ('c', 3), ('a', 2), ('d', 1)]\ngot = list(seq_count(&quot;aaabbcccaad&quot;))\nprint(got == exp) # True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T18:30:59.157", "Id": "515050", "Score": "0", "body": "Thanks! The first solution looks really good. But most of the interviewers won't accept that. Any suggestions to improve upon these kinda solution thinking?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T18:50:39.637", "Id": "515056", "Score": "2", "body": "@ManivG Find better interviewers! Mostly I'm joking, but not entirely. Don't forget that you are interviewing them too. Sensible interviewers will reward a candidate familiar with the full power of a language (eg knowing `itertools`), even if they also ask for a roll-your-own solution. As far as improving, I advise lots of practice trying to solve **practical problems** (eg on StackOverflow or here). Place less emphasis on problems requiring semi-fancy algorithms and focus heavily on bread-and-butter questions. Pay attention to how different people solve such problems and steal their ideas." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T17:14:15.327", "Id": "260991", "ParentId": "260986", "Score": "3" } } ]
<p>I have written a function that takes as input a list of 5 numbers, then the program's goal is to return the largest drop in the list. It is important to understand that [5, 3, ...] is a decrease of 2 and that [5, 20, .....] is a decrease of 0. In short, a decrease can only be from left to right and the largest decrease can for example also be the decrease from the 1st number to the 4th number, they do not necessarily have to be next to each other.</p> <pre><code>def biggest_drop(temperature): difference = 0 new_temperature = temperature.copy() a = 0 for i in temperature: del new_temperature[0] for j in new_temperature: if i &lt;= j: False else: a = i - j if a &gt; difference: difference = a return difference </code></pre> <p>The good news is the code works, the bad news is that because of the double for loop there is already a Big-O notation of O(n<sup>2</sup>). However, the program must have a Big-O notation of O(n<sup>1</sup>) and I don't know how to fix this and where the speed of the code is also high enough. For example, here I have made a fairly sloppy alternative, but it is too slow:</p> <pre><code>def biggest_drop(temperature): difference = 0 a = 0 b = temperature[1] c = temperature[2] d = temperature[3] e = temperature[4] for i in temperature: if temperature[0] &lt;= temperature[1] &lt;= temperature[2] &lt;= temperature[3] &lt;= temperature[4]: return 0 elif i &gt; b: a = i - b if a &gt; difference: difference = a elif i &gt; c: a = i - c if a &gt; difference: difference = a elif i &gt; d: a = i - d if a &gt; difference: difference = a elif i &gt; e: a = i - e if a &gt; difference: difference = a return difference </code></pre> <p>Do you have a better idea how my code complies with the big-O notation of O(n<sup>1</sup>) and is also fast enough for larger n, in other words lists with more than 5 integers?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T16:40:17.500", "Id": "515174", "Score": "2", "body": "Welcome to Code Review! – The site standard is for the title to simply state the task accomplished by the code, not your concerns about it. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T16:40:52.883", "Id": "515175", "Score": "0", "body": "Btw, what is n if the input is always a list of 5 numbers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T16:44:28.780", "Id": "515176", "Score": "0", "body": "apologies, I only now understand from the command that the one larger n creates a larger list of integers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T16:47:32.617", "Id": "515177", "Score": "0", "body": "Which a quick Google search I found this https://math.stackexchange.com/a/1172157/42969 and this https://stackoverflow.com/q/15019851/1187415, which might be what you are looking for." } ]
{ "AcceptedAnswerId": "261085", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T15:31:21.323", "Id": "261070", "Score": "3", "Tags": [ "python", "algorithm", "comparative-review", "complexity" ], "Title": "Find the largest decrease in a sequence of numbers" }
261070
accepted_answer
[ { "body": "<p>This can be solved in a single pass, e.g., O(n).</p>\n<p>For each temperature, subtract it from the highest temperature seen so far to get the drop. Keep track of the largest drop. Also update the highest temperature.</p>\n<pre><code>def biggest_drop(temperatures):\n highest = temperatures[0]\n largest_drop = 0\n\n for temperature in temperatures:\n drop = highest - temperature\n largest_drop = max(largest_drop, drop)\n\n highest = max(temperature, highest)\n\n return largest_drop\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T21:01:27.540", "Id": "261085", "ParentId": "261070", "Score": "5" } } ]
<p>I understand there is <a href="https://codereview.stackexchange.com/questions/222292/character-picture-grid-exercise-automatetheboringstuff">another question</a> on this already, however this is what I coded and wanted to know if this would raise any red flags?</p> <p>Regarding the Character picture exercise located at the end the following page: <a href="https://automatetheboringstuff.com/chapter4/" rel="nofollow noreferrer">https://automatetheboringstuff.com/chapter4/</a></p> <blockquote> <p>Say you have a list of lists where each value in the inner lists is a one-character string, like this:</p> <pre><code>grid = [['.', '.', '.', '.', '.', '.'], ['.', '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', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] </code></pre> <p>You can think of <code>grid[x][y]</code> as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The <code>(0, 0)</code> origin will be in the upper-left corner, the x-coordinates increase going right, and the y-coordinates increase going down.</p> <p>Copy the previous grid value, and write code that uses it to print the image.</p> <pre><code>..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O.... </code></pre> </blockquote> <p>It's different in that it doesn't hard-code the length of the list.</p> <pre><code>grid = [['.', '.', '.', '.', '.', '.'], ['.', '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', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] x = 0 y = 0 for y in range(len(grid[x])): for x in range(len(grid)): print(grid[x][y],end='') print() </code></pre> <p>Thanks for the help and let me know if this is not appropriate to post!</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T08:22:45.130", "Id": "261128", "Score": "2", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Automate The Boring Stuff - Character Picture Grid" }
261128
max_votes
[ { "body": "<p>It's wasteful to use <code>range()</code> and then only use the result for indexing.</p>\n<p>Instead, just iterate directly over the values:</p>\n<pre><code>for col in range(len(grid[0])):\n for row in grid:\n print(row[col],end='')\n print()\n</code></pre>\n<p>We can simplify, though - use the <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a> function to transpose the array:</p>\n<pre><code>transposed = zip(*grid)\n\nfor row in transposed:\n for col in row:\n print(col,end='')\n print()\n</code></pre>\n<p>The next simplification is instead of printing one character at a time, we can use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>join</code></a> to form strings for printing:</p>\n<pre><code>for row in zip(*grid):\n print(''.join(row))\n</code></pre>\n<p>And we can join all the rows using <code>'\\n'.join()</code>, giving this final version:</p>\n<pre><code>print('\\n'.join(''.join(x) for x in zip(*grid)))\n</code></pre>\n<p>Equivalently, using <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\"><code>map</code></a>:</p>\n<pre><code>print('\\n'.join(map(''.join, zip(*grid))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T05:20:33.180", "Id": "515375", "Score": "0", "body": "This is great, thanks @toby. \n\nCan I ask why using range here is wasteful? the idea was to build a code that can work with any number of rows/columns.\n\nI got to learn a lot here, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T07:02:49.390", "Id": "515381", "Score": "1", "body": "Perhaps \"wasteful\" isn't exactly the right word. My point is that we don't need to count the columns and create indexes when it's simpler to iterate the columns directly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T12:05:00.837", "Id": "261134", "ParentId": "261128", "Score": "3" } } ]
<p>I understand there is <a href="https://codereview.stackexchange.com/questions/222292/character-picture-grid-exercise-automatetheboringstuff">another question</a> on this already, however this is what I coded and wanted to know if this would raise any red flags?</p> <p>Regarding the Character picture exercise located at the end the following page: <a href="https://automatetheboringstuff.com/chapter4/" rel="nofollow noreferrer">https://automatetheboringstuff.com/chapter4/</a></p> <blockquote> <p>Say you have a list of lists where each value in the inner lists is a one-character string, like this:</p> <pre><code>grid = [['.', '.', '.', '.', '.', '.'], ['.', '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', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] </code></pre> <p>You can think of <code>grid[x][y]</code> as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The <code>(0, 0)</code> origin will be in the upper-left corner, the x-coordinates increase going right, and the y-coordinates increase going down.</p> <p>Copy the previous grid value, and write code that uses it to print the image.</p> <pre><code>..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O.... </code></pre> </blockquote> <p>It's different in that it doesn't hard-code the length of the list.</p> <pre><code>grid = [['.', '.', '.', '.', '.', '.'], ['.', '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', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] x = 0 y = 0 for y in range(len(grid[x])): for x in range(len(grid)): print(grid[x][y],end='') print() </code></pre> <p>Thanks for the help and let me know if this is not appropriate to post!</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T08:22:45.130", "Id": "261128", "Score": "2", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Automate The Boring Stuff - Character Picture Grid" }
261128
max_votes
[ { "body": "<p>It's wasteful to use <code>range()</code> and then only use the result for indexing.</p>\n<p>Instead, just iterate directly over the values:</p>\n<pre><code>for col in range(len(grid[0])):\n for row in grid:\n print(row[col],end='')\n print()\n</code></pre>\n<p>We can simplify, though - use the <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a> function to transpose the array:</p>\n<pre><code>transposed = zip(*grid)\n\nfor row in transposed:\n for col in row:\n print(col,end='')\n print()\n</code></pre>\n<p>The next simplification is instead of printing one character at a time, we can use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>join</code></a> to form strings for printing:</p>\n<pre><code>for row in zip(*grid):\n print(''.join(row))\n</code></pre>\n<p>And we can join all the rows using <code>'\\n'.join()</code>, giving this final version:</p>\n<pre><code>print('\\n'.join(''.join(x) for x in zip(*grid)))\n</code></pre>\n<p>Equivalently, using <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\"><code>map</code></a>:</p>\n<pre><code>print('\\n'.join(map(''.join, zip(*grid))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T05:20:33.180", "Id": "515375", "Score": "0", "body": "This is great, thanks @toby. \n\nCan I ask why using range here is wasteful? the idea was to build a code that can work with any number of rows/columns.\n\nI got to learn a lot here, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T07:02:49.390", "Id": "515381", "Score": "1", "body": "Perhaps \"wasteful\" isn't exactly the right word. My point is that we don't need to count the columns and create indexes when it's simpler to iterate the columns directly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T12:05:00.837", "Id": "261134", "ParentId": "261128", "Score": "3" } } ]
<p>My .bash_aliases file contains several aliases. In the beginning, when I wanted to see the aliases, I print the .bash_aliases file,</p> <p>The output wasn't readable at all, so I created a python script to make it better. To call my python script, I use the alias <code>print_aliases_manual</code></p> <p>What is the most pythonic way to write the following script?</p> <p>Here is my python script:</p> <pre><code> class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' with open('/home/pi/.bash_aliases', 'r') as f: lines = f.readlines() for line in lines: if r'##' in line: print(f'{bcolors.HEADER}{bcolors.UNDERLINE}{bcolors.BOLD}{line}{bcolors.ENDC}') elif r'#' in line: print(f'{bcolors.WARNING}{line}{bcolors.ENDC}') elif r'alias' in line: drop_alias = line.replace('alias', '') new_line = drop_alias.replace('=', ' ') print(f'{bcolors.OKGREEN}{new_line}') else: print(f'{line}') </code></pre> <p>Here is my bash_aliases file:</p> <pre><code>### Aliases list divided by category: ## General commands: alias cdd=&quot;cd /home/pi/Desktop/speedboat/&quot; alias dc=&quot;sudo docker-compose&quot; alias pm2=&quot;sudo pm2&quot; ## Cellular related commands: alias pc=&quot;ping -I wwan0 www.google.com&quot; alias qmi=&quot;sudo qmicli -d /dev/cdc-wdm0 -p&quot; ## AWS relaeted commands: alias dlogs=&quot;sudo docker logs -f iot_service&quot; ## Git commands: alias gp=&quot;sudo git pull&quot; alias gc=&quot;sudo git checkout&quot; ## scripts to run when deleting speedboat directory is needed: # copying files to Desktop alias stodtop=&quot;sudo -E sh /home/pi/Desktop/speedboat/scripts/copy_files_to_desktop.sh&quot; # copying files from Desktop alias sfromdtop=&quot;sudo -E sh /home/pi/Desktop/speedboat/scripts/copy_files_from_desktop_to_speedboat.sh&quot; ## verifications test and updates scripts # run speedboat verifications tests alias sinsta=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/installation_verification.sh&quot; # run local unittests alias slocalt=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/run_local_unittest.sh&quot; # pull os updates from git and execute alias supdate=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/updates-speedboat.sh&quot; ## speedboat start and stop scripts (dockers and PM2) alias startr=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/start_speedboat.sh&quot; alias stopr=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/stop_speedboat.sh&quot; ## AWS related scripts: alias secrl=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/ecr-login.sh&quot; alias slog=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/log_register.sh&quot; ## Command to run speedboat aliases manual: alias print_aliases_manual=&quot;python3 /home/pi/Desktop/speedboat/verification/test_verification_speedboat/colored_aliases_manual.py&quot; </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T22:28:45.050", "Id": "261163", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "Python script that make my .bash_aliases file MUCH more readable and clear" }
261163
max_votes
[ { "body": "<p><strong><code>print</code></strong></p>\n<p>f-Strings are a great and convenient tool for including variables and calculations in strings. I'd say they're generally not needed when printing only variables. For example</p>\n<pre><code>print(f'{bcolors.WARNING}{line}{bcolors.ENDC}')\n</code></pre>\n<p>could become</p>\n<pre><code>print(bcolors.WARNING, line, bcolors.ENDC, sep='')\n</code></pre>\n<p>However I'm not sure which of the two is more pythonic, I personally prefer the latter for readability.</p>\n<p>You could also consider pulling out formatting into seperate variables to increase readability.</p>\n<pre><code>HEADER_FORMAT = &quot;&quot;.join((bcolors.HEADER, bcolors.UNDERLINE, bcolors.BOLD, &quot;{}&quot;, bcolors.ENDC))\n\nprint(HEADER_FORMAT.format(line))\n</code></pre>\n<hr />\n<p><strong><code>in</code> vs. <code>startswith</code></strong></p>\n<p>I'd recommend using <code>str.startswith</code> instead of <code>str in str</code> for checking prefixes.</p>\n<pre><code>if r'##' in line:\n</code></pre>\n<p>becomes</p>\n<pre><code>if line.startswith(r&quot;##&quot;):\n</code></pre>\n<p>This is less error-prone and conveys your intentions more explicitly, without the need to look at the source file. As there aren't any escape characters in your prefixes, you also don't need to make it a raw string. You can simply drop the <code>r</code>:</p>\n<pre><code>if line.startswith(&quot;##&quot;):\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T07:36:24.927", "Id": "515386", "Score": "2", "body": "@Reinderien Maybe I‘m looking at the wrong line here, but the second print has its seperator set to an empty string via the sep argument." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T13:01:52.880", "Id": "515403", "Score": "1", "body": "You're right, my apologies" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T23:09:27.483", "Id": "261166", "ParentId": "261163", "Score": "10" } } ]
<p>My .bash_aliases file contains several aliases. In the beginning, when I wanted to see the aliases, I print the .bash_aliases file,</p> <p>The output wasn't readable at all, so I created a python script to make it better. To call my python script, I use the alias <code>print_aliases_manual</code></p> <p>What is the most pythonic way to write the following script?</p> <p>Here is my python script:</p> <pre><code> class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' with open('/home/pi/.bash_aliases', 'r') as f: lines = f.readlines() for line in lines: if r'##' in line: print(f'{bcolors.HEADER}{bcolors.UNDERLINE}{bcolors.BOLD}{line}{bcolors.ENDC}') elif r'#' in line: print(f'{bcolors.WARNING}{line}{bcolors.ENDC}') elif r'alias' in line: drop_alias = line.replace('alias', '') new_line = drop_alias.replace('=', ' ') print(f'{bcolors.OKGREEN}{new_line}') else: print(f'{line}') </code></pre> <p>Here is my bash_aliases file:</p> <pre><code>### Aliases list divided by category: ## General commands: alias cdd=&quot;cd /home/pi/Desktop/speedboat/&quot; alias dc=&quot;sudo docker-compose&quot; alias pm2=&quot;sudo pm2&quot; ## Cellular related commands: alias pc=&quot;ping -I wwan0 www.google.com&quot; alias qmi=&quot;sudo qmicli -d /dev/cdc-wdm0 -p&quot; ## AWS relaeted commands: alias dlogs=&quot;sudo docker logs -f iot_service&quot; ## Git commands: alias gp=&quot;sudo git pull&quot; alias gc=&quot;sudo git checkout&quot; ## scripts to run when deleting speedboat directory is needed: # copying files to Desktop alias stodtop=&quot;sudo -E sh /home/pi/Desktop/speedboat/scripts/copy_files_to_desktop.sh&quot; # copying files from Desktop alias sfromdtop=&quot;sudo -E sh /home/pi/Desktop/speedboat/scripts/copy_files_from_desktop_to_speedboat.sh&quot; ## verifications test and updates scripts # run speedboat verifications tests alias sinsta=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/installation_verification.sh&quot; # run local unittests alias slocalt=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/run_local_unittest.sh&quot; # pull os updates from git and execute alias supdate=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/updates-speedboat.sh&quot; ## speedboat start and stop scripts (dockers and PM2) alias startr=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/start_speedboat.sh&quot; alias stopr=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/stop_speedboat.sh&quot; ## AWS related scripts: alias secrl=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/ecr-login.sh&quot; alias slog=&quot;sudo sh /home/pi/Desktop/speedboat/scripts/log_register.sh&quot; ## Command to run speedboat aliases manual: alias print_aliases_manual=&quot;python3 /home/pi/Desktop/speedboat/verification/test_verification_speedboat/colored_aliases_manual.py&quot; </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T22:28:45.050", "Id": "261163", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "Python script that make my .bash_aliases file MUCH more readable and clear" }
261163
max_votes
[ { "body": "<p><strong><code>print</code></strong></p>\n<p>f-Strings are a great and convenient tool for including variables and calculations in strings. I'd say they're generally not needed when printing only variables. For example</p>\n<pre><code>print(f'{bcolors.WARNING}{line}{bcolors.ENDC}')\n</code></pre>\n<p>could become</p>\n<pre><code>print(bcolors.WARNING, line, bcolors.ENDC, sep='')\n</code></pre>\n<p>However I'm not sure which of the two is more pythonic, I personally prefer the latter for readability.</p>\n<p>You could also consider pulling out formatting into seperate variables to increase readability.</p>\n<pre><code>HEADER_FORMAT = &quot;&quot;.join((bcolors.HEADER, bcolors.UNDERLINE, bcolors.BOLD, &quot;{}&quot;, bcolors.ENDC))\n\nprint(HEADER_FORMAT.format(line))\n</code></pre>\n<hr />\n<p><strong><code>in</code> vs. <code>startswith</code></strong></p>\n<p>I'd recommend using <code>str.startswith</code> instead of <code>str in str</code> for checking prefixes.</p>\n<pre><code>if r'##' in line:\n</code></pre>\n<p>becomes</p>\n<pre><code>if line.startswith(r&quot;##&quot;):\n</code></pre>\n<p>This is less error-prone and conveys your intentions more explicitly, without the need to look at the source file. As there aren't any escape characters in your prefixes, you also don't need to make it a raw string. You can simply drop the <code>r</code>:</p>\n<pre><code>if line.startswith(&quot;##&quot;):\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T07:36:24.927", "Id": "515386", "Score": "2", "body": "@Reinderien Maybe I‘m looking at the wrong line here, but the second print has its seperator set to an empty string via the sep argument." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T13:01:52.880", "Id": "515403", "Score": "1", "body": "You're right, my apologies" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T23:09:27.483", "Id": "261166", "ParentId": "261163", "Score": "10" } } ]
<p>I am new to python and I am trying to write a function with various actions based on the parameters sent. I am checking if the data has valid format then it publishes to /accepted otherwise to /rejected. If the data is fine then it does the function and then publishes to /success otherwise to /failure</p> <p>Here is what i am doing now -</p> <pre><code>def data_handler(event, context): try: input_topic = context.topic input_message = event response = f'Invoked on topic {input_topic} with message {input_message}' logging.info(response) client.publish(topic=input_topic + '/accepted', payload=json.dumps({'state': 'accepted'})) except Exception as e: logging.error(e) client.publish(topic=input_topic + '/rejected', payload=json.dumps({'state': 'rejected'})) try: print('Perform the function based on input message') client.publish(topic=input_topic + '/success', payload=json.dumps({'state': 'Execution succeeded'})) except Exception as e: logging.error(e) client.publish(topic=input_topic + '/failure', payload=json.dumps({'state': 'Execution failed'})) </code></pre> <p>This works as of now but i think there should be a better way to implement this. Any idea?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T17:27:40.010", "Id": "515430", "Score": "1", "body": "It would be nice to see this used in a `__main__` context where example input is given. There are a lot of questions around this, like \"What is `client`?\" If your entire program isn't proprietary code, it would be best to just post the whole thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T17:33:52.973", "Id": "515432", "Score": "0", "body": "This is a big project for which this a small module i need to write. This is an AWS lambda function which is event triggered. The event parameter brings in the JSON payload. The client is the aws iot client which can publish to the specific topics based on MQTT" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T17:18:51.110", "Id": "261198", "Score": "2", "Tags": [ "python", "performance" ], "Title": "Better way to structure and optimise try except statements" }
261198
max_votes
[ { "body": "<p>Given that there isn't much here to analyse purely based on performance since we don't know what those other function calls do, here are some minor changes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def data_handler(message, topic):\n try:\n logging.debug(f'Invoked on topic {topic} with message {message}')\n client.publish(topic=topic + '/pass', payload=json.dumps({'state': 'pass'}))\n except Exception as e:\n logging.error(e)\n client.publish(topic=topic + '/fail', payload=json.dumps({'state': 'fail'}))\n</code></pre>\n<p>Both try/catch blocks in your code look identical, and you should have only one endpoint that needs to be communicated with. If you really <em>need</em> both, then there should be a separate function to have this code.</p>\n<p>It also seems pretty redundant that you're publishing to a <code>pass</code> and <code>fail</code> endpoint and have a payload that says whether or not it passed or failed. You should know that status based on the endpoint that receives the message.</p>\n<p>You can have the payload be more descriptive as well to remove multiple endpoints. Something like <code>{'formatted': true, 'error': ''}</code> is far more informative.</p>\n<p>Lastly, you can just pass your one-off variables into this function, like so: <code>data_handler(event, context.topic)</code>. If your <code>event</code> really is just a post message and not a posting event object, then that should be clarified somewhere in the code base.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T21:56:03.180", "Id": "515458", "Score": "0", "body": "The different topics are used in order to convey different situations -\n`/accepted` - to publish a message when the payload is correctly formatted and can be parsed\n`/rejected` - incorrect formatting and cannot be parsed\n\nIf the publish on accepted is successful then try to publish to the `/success` topic to convey that the task was correctly performed (such as some OS configuration)\nIf the publish on `/success` is somehow not successful then publish on `/failure`.\n\nSeems like a separate function for the success / failure would work." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T17:47:47.193", "Id": "261200", "ParentId": "261198", "Score": "1" } } ]
<p>I'm brushing up on Python, working my way through <a href="https://www.manning.com/books/python-workout" rel="noreferrer">Python Workout</a>. One of the exercises is to emulate the Python zip() function, assuming each iterable passed to the function is of the same length. Here's what I've come up with:</p> <pre><code>def myzip(*args): result = [[] for _ in range(len(args[0]))] for i, v in enumerate(args): for j, w in enumerate(v): result[j].append(w) for i, v in enumerate(result): result[i] = tuple(v) return result </code></pre> <p>While my function works, I have a hunch there must be a more succinct way of achieving the same thing (forgoing the nested loops). Is there? I'm running Python 3.9.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T17:56:32.013", "Id": "261202", "Score": "6", "Tags": [ "python", "reinventing-the-wheel" ], "Title": "Emulating Python zip() Function" }
261202
max_votes
[ { "body": "<p>You should not apply <code>len</code>, because that requires that the first argument be at least as strong as a <code>Collection</code>, when <code>zip</code> should not need that guarantee and should only need <code>Iterable</code> which is a weaker type.</p>\n<p>Gathering results in memory can be inefficient and lead to memory starvation. It's worth noting that an in-memory approach might actually execute more quickly than a generator but you would want to test this.</p>\n<p>Attempt some type hinting. The amount of type-hinting you can do here is fairly limited, but you can do better than nothing.</p>\n<p>It's also worth noting that the <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\">official documentation has a reference implementation</a>.</p>\n<h2>Suggested</h2>\n<pre><code>from typing import Any, Iterable, Tuple\n\n\ndef myzip(*args: Iterable[Any]) -&gt; Iterable[Tuple[Any, ...]]:\n first_iter, *other_iters = (iter(a) for a in args)\n\n for first in first_iter:\n yield (first, *(\n next(other) for other in other_iters\n ))\n\n\nfor a, b in myzip([1, 2, 3], [4, 5, 6]):\n print(a, b)\n</code></pre>\n<h2>Alternate</h2>\n<p>This version does not need to wrap the first argument in an iterator.</p>\n<pre><code>def myzip(first_iter: Iterable[Any], *args: Iterable[Any]) -&gt; Iterable[Tuple[Any, ...]]:\n others = [iter(a) for a in args]\n\n for first in first_iter:\n yield (first, *(\n next(other) for other in others\n ))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T18:14:42.337", "Id": "261205", "ParentId": "261202", "Score": "7" } } ]
<p>I am trying to implement a basic hash table using a list of tuples. The code produce the desired output. Please help me improve my code as I feel there are a lot of while loops.</p> <pre><code>#global variables to keep track of the hash table count = 0 size = 1000 def hash_table(size): return [None] * size def hash_item(key, value): return (key,value) def hash_func(key): #simple hash function index = hash(key) % 1000 return index def insert_hash(table,key,value): index = hash_func(key) item = hash_item(key,value) global count global size if count == size: raise Exception(&quot;Hash table limit reached&quot;) if table[index] == None: table[index] = item else: collision_handler(table, index, item) count = count + 1 def print_hash(table,key): index = hash_func(key) while table[index][0] != key: #in case there is a collision: index = index + 1 print(table[index]) def delete_hash(table,key): index = hash_func(key) while table[index][0] != key: index = index + 1 table.pop(index) def collision_handler(table,index,item): #handling collisions using open addressing while table[index] != None: index = index + 1 table[index] = item a = hash_table(size) b = hash_func('1') insert_hash(a, '1','john') print_hash(a,'1') delete_hash(a,'1') insert_hash(a,'1','edward') print_hash(a,'1') </code></pre>
[]
{ "AcceptedAnswerId": "261213", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T17:59:28.057", "Id": "261204", "Score": "2", "Tags": [ "python", "reinventing-the-wheel", "hash-map" ], "Title": "Implementing hash table in Python using Tuples" }
261204
accepted_answer
[ { "body": "<p>Despite the code produce the desired output in your simple test case, your implementation is quite flawed.</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = hash_table(size)\n\ninsert_hash(a, 1, 'john')\ninsert_hash(a, 2, 'edward')\ndelete_hash(a, 1)\nprint_hash(a, 2)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Traceback (most recent call last):\n File &quot;C:/Code Review/hash_table.py&quot;, line 53, in &lt;module&gt;\n print_hash(a, 2)\n File &quot;C:/Code Review/hash_table.py&quot;, line 30, in print_hash\n while table[index][0] != key: #in case there is a collision:\nTypeError: 'NoneType' object is not subscriptable\n&gt;&gt;&gt; \n</code></pre>\n<p>The issue: <code>table.pop(index)</code> will move items after the one being delete forward by one position in the table. Given that they are indexed by the hash values, this would mean that they can't be found anymore.</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = hash_table(size)\n\nfor _ in range(2000):\n insert_hash(a, 1, 'john')\n delete_hash(a, 1)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Traceback (most recent call last):\n File &quot;C:/Code Review/hash_table.py&quot;, line 51, in &lt;module&gt;\n insert_hash(a, 1, 'john')\n File &quot;C:/Code Review/hash_table.py&quot;, line 22, in insert_hash\n if table[index] == None:\nIndexError: list index out of range\n&gt;&gt;&gt; \n</code></pre>\n<p>After each insert/delete, the table size has shrunk by one item. After a thousand insert/deletes, the table can't hold any values!</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = hash_table(size)\n\ninsert_hash(a, 999, 'john')\ninsert_hash(a, 999, 'edward')\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Traceback (most recent call last):\n File &quot;C:/Code Review/hash_table.py&quot;, line 51, in &lt;module&gt;\n insert_hash(a, 999, 'edward')\n File &quot;C:/Code Review/hash_table.py&quot;, line 25, in insert_hash\n collision_handler(table, index, item)\n File &quot;C:/Code Review/hash_table.py&quot;, line 42, in collision_handler\n while table[index] != None:\nIndexError: list index out of range\n&gt;&gt;&gt; \n</code></pre>\n<p>A collision at the last slot in the hash table doesn't have room to handle the collision, despite the table only having a 999 empty slots. You need to use circular addressing.</p>\n<p>You need to add more test cases, and rework the code to handle these issues. I generated these issues quickly by exploiting the fact that <code>hash(int) == int</code> for sufficiently small integers, but they would arise using strings for keys as well. It is just be harder to generate cases which deterministicly fail using string keys.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-25T22:40:56.277", "Id": "261213", "ParentId": "261204", "Score": "1" } } ]
<p>I was doing the following exercise:</p> <blockquote> <p>Create an algorithm which asks the user a number from 1 to 7, and each number represents a day on the week. For example, 1 represents Sunday, 2 represents Monday and so on. The user will type this number and the program will show them the name of the day on the week and if it's a business day or a weekend.</p> </blockquote> <p>I tried to do it in a object-oriented way and using Python. Can someone please verify if my code is within the Python and object-oriented &quot;standards&quot;? Because I'm not sure whether it is, and I need a review.</p> <p>Here's my code:</p> <pre><code>class DayOnWeek: ERROR_MESSAGE = 'Invalid weekday. Try again:' NUMBER_NAME_ASSOCIATIONS = { 1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday' } def __init__(self): self._day_number = 0 self._day_name = None self._category = None @property def day_name(self): return self._day_name @property def category(self): return self._category @property def day_number(self): return self._day_number @day_number.setter def day_number(self, value): if 1 &lt;= value &lt;= 7: self._day_number = value self._day_name = DayOnWeek.NUMBER_NAME_ASSOCIATIONS[self._day_number] else: raise ValueError(DayOnWeek.ERROR_MESSAGE) if 2 &lt;= value &lt;= 6: self._category = 'Business day' else: self._category = 'Weekend' class DayOnWeekInterface: def __init__(self): self._day_on_week = DayOnWeek() def request_day_number(self): while True: try: day_num = input('Type the number of the day on the week (ex: 1 - Sunday):') day_num = int(day_num) self._day_on_week.day_number = day_num break except ValueError: print(DayOnWeek.ERROR_MESSAGE) self.show_day_on_week() def show_day_on_week(self): day_num = self._day_on_week.day_number day_name = self._day_on_week.day_name day_category = self._day_on_week.category print(f'The day {day_num} is {day_name.lower()}') print(f'{day_name} is a {day_category.lower()}') DayOnWeekInterface().request_day_number() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T15:29:58.447", "Id": "515536", "Score": "1", "body": "@gnasher729 You're welcome to add an answer saying so." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T00:57:30.057", "Id": "261219", "Score": "9", "Tags": [ "python", "beginner", "datetime" ], "Title": "Simple day-of-week program" }
261219
max_votes
[ { "body": "<p>Your <code>DayOnWeek</code> object is mutable, allowing you to set the <code>.day_number</code> property. For such a simple object is not a good idea. An immutable object is better.</p>\n<p>There are exactly 7 days of the week. For a one-of-seven choice, the go-to data-storage structure is an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>Enum</code></a>. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\nclass DayOfWeek(Enum):\n Sunday = 1\n Monday = 2\n Tuesday = 3\n Wednesday = 4\n Thursday = 5\n Friday = 6\n Saturday = 7\n\n @property\n def weekend(self):\n return self in {DayOfWeek.Saturday, DayOfWeek.Sunday}\n\n @property\n def category(self):\n return 'Weekend' if self.weekend else 'Business day'\n\n @property\n def number(self):\n return self.value\n</code></pre>\n<p>Borrowing Reideerien's <code>request_day_number()</code> function you'd use the <code>DayOfWeek</code> enum like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n day_no = request_day_number()\n day = DayOfWeek(day_no)\n\n print(f'Day {day.number} is {day.name}')\n print(f'{day.name} is a {day.category} day')\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T08:23:43.263", "Id": "519375", "Score": "0", "body": "Hi AJNeufeld. You have provided an alternate solution. However, answers must make at least one [insightful observation](/help/how-to-answer), and must explain why the change is better than the OP's code. Failure to follow the IO rule can result in your answer being deleted." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T04:47:57.737", "Id": "261229", "ParentId": "261219", "Score": "9" } } ]
<p>This is code for a caesar cipher that I wrote, I would love for anyone who can to offer any improvements/corrections/more efficient methods they can think of. Thanks.</p> <pre class="lang-py prettyprint-override"><code>alphabet=[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;,&quot;I&quot;,&quot;J&quot;,&quot;K&quot;,&quot;L&quot;,&quot;M&quot;,&quot;N&quot;,&quot;O&quot;,&quot;P&quot;,&quot;Q&quot;,&quot;R&quot;,&quot;S&quot;,&quot;T&quot;,&quot;U&quot;,&quot;V&quot;,&quot;W&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;Z&quot;,&quot; &quot;,&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;0&quot;,&quot;,&quot;,&quot;.&quot;] enc_text=[] dec_text=[] def number_check(a): valid=False while valid==False: try: number=int(a) valid=True except ValueError: print(&quot;Invalid entry, You must enter a number.&quot;) a=input(&quot;please enter a number.\n&quot;) return number def encrypt(): for x in org_text: index=alphabet.index(x) enc_letter=(index+int(enc_key))%39 new_let=alphabet[enc_letter] enc_text.append(new_let) return enc_text def decipher(): for x in message: index=alphabet.index(x) dec_letter=(index-int(enc_key))%39 new_let=alphabet[dec_letter] dec_text.append(new_let) return dec_text enc_key=number_check(input(&quot;Please enter your encryption key:\n&quot;)) org_text=input(&quot;please enter the message you would like encrypted:\n&quot;).upper() message=encrypt() message1=&quot;&quot;.join(message) print(message1) decode=decipher() decode1=&quot;&quot;.join(decode) print(decode1) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-26T13:22:47.867", "Id": "261241", "Score": "5", "Tags": [ "python", "python-3.x", "caesar-cipher" ], "Title": "A caesar cipher code" }
261241
max_votes
[ { "body": "<p>If you look at your <code>encrypt()</code> and <code>decrypt()</code> you might notice that they are mirror images of each other based on <code>key</code>. This might allow us to base them both on a common function that does the rotation for us.</p>\n<p>Let's try this via a closure. Since we have a closure, this will also provide us an opportunity to remove most of the global junk.</p>\n<p>Remember that there is still the &quot;invalid character&quot; issue to deal with though when using this code.</p>\n<pre><code>## --------------------------\n## Calling this closure returns a pair of function that can be used\n## encrypt and decrypt plain text messages.\n## Note that decryption is a mirror of encryption.\n## --------------------------\ndef make_crypt():\n ## remove alphabet from our global context.\n alpha = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890,.&quot;\n len_alpha = len(alpha)\n\n ## this *might* be faster than using alpha.index(letter)\n alpha_index = {letter: index for index, letter in enumerate(alpha)}\n\n ## --------------------------\n ## a function to do rotation based on a key with\n ## a direction.\n ## --------------------------\n def crypt(text_in, key):\n return &quot;&quot;.join([\n alpha[ (alpha_index[letter] + key) % len_alpha ]\n for letter in text_in\n ])\n ## --------------------------\n\n ## --------------------------\n ## return a pair of functions that we can use\n ## --------------------------\n return (\n lambda text, key: crypt(text, key),\n lambda text, key: crypt(text, -key)\n )\n ## --------------------------\n\nencrypt, decrypt = make_crypt()\n## --------------------------\n\n## --------------------------\n## Get our encryption key and ensure that it is an int\n## --------------------------\ndef get_key():\n try:\n return int(input(&quot;Please enter your integer encryption key:\\n&quot;))\n except ValueError:\n print(&quot;Invalid entry, encryption key must enter an integer.&quot;)\n return get_key()\n## --------------------------\n\nenc_key = get_key()\norg_text = input(&quot;please enter the message you would like encrypted:\\n&quot;).upper()\n\nsecret_message = encrypt(org_text, enc_key)\nprint(secret_message)\n\ndecoded_message = decrypt(secret_message, enc_key)\nprint(decoded_message)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:51:21.757", "Id": "262632", "ParentId": "261241", "Score": "2" } } ]
<blockquote> <p>Sum of Pairs</p> <p>Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.</p> <pre><code>sum_pairs([11, 3, 7, 5], 10) # ^--^ 3 + 7 = 10 == [3, 7] sum_pairs([4, 3, 2, 3, 4], 6) # ^-----^ 4 + 2 = 6, indices: 0, 2 * # ^-----^ 3 + 3 = 6, indices: 1, 3 # ^-----^ 2 + 4 = 6, indices: 2, 4 # * entire pair is earlier, and therefore is the correct answer == [4, 2] sum_pairs([0, 0, -2, 3], 2) # there are no pairs of values that can be added to produce 2. == None/nil/undefined (Based on the language) sum_pairs([10, 5, 2, 3, 7, 5], 10) # ^-----------^ 5 + 5 = 10, indices: 1, 5 # ^--^ 3 + 7 = 10, indices: 3, 4 * # * entire pair is earlier, and therefore is the correct answer == [3, 7] Negative numbers and duplicate numbers can and will appear. NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out. </code></pre> </blockquote> <pre><code>def sum_pairs(ints, s): ''' Params: ints: list[int] s: int --- sum Return First two values from left in ints that add up to form sum ''' ints_dict = {k:v for v,k in enumerate(ints)} # O(n) earliest_ending_idx = float('inf') earliest_pair = None for idx, num in enumerate(ints): # O(n) if idx &gt;= earliest_ending_idx: return earliest_pair try: second_num_idx = ints_dict[s-num] if second_num_idx != idx: if max(second_num_idx, idx) &lt; earliest_ending_idx: earliest_ending_idx = max(second_num_idx, idx) earliest_pair = [num, s-num] except KeyError: # s-num not in dict pass return earliest_pair </code></pre> <p>It seems to me that my code is O(n) in time complexity but I can't submit the solution since it took too long to run. Am I mistaken in my analysis and is there a better way to solve this problem?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T12:41:27.543", "Id": "515597", "Score": "0", "body": "Welcome to the Code Review Community. Please provide the programming challenge description in the question. If we don't have an idea of what the code is supposed to do, we really can't review the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T17:33:41.170", "Id": "515641", "Score": "0", "body": "Rather than pasting a screenshot of the problem statement, please paste a quoted `>` text block verbatim. Otherwise this is not searchable." } ]
{ "AcceptedAnswerId": "261332", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T09:49:00.533", "Id": "261275", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Python Sum of Pairs Codewars Solution requires optimization" }
261275
accepted_answer
[ { "body": "<p>You have the right idea with storing the complements, i.e. <code>s-num</code>.</p>\n<p>However, there's no need to store indices. The iteration can be stopped when a pair is found, so iterating through the list in the usual manner will yield the first such pair.</p>\n<pre><code>def sum_pairs(ints, s):\n complement_dict = {}\n \n for i in ints:\n if i in complement_dict:\n return [s-i, i]\n else:\n complement_dict[s - i] = i\n\n return None\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:33:20.420", "Id": "261332", "ParentId": "261275", "Score": "1" } } ]
<p>I'm working with a pandas dataframe which describes the start and end time of visits. A toy example of the data could be as follows:</p> <pre><code>import pandas as pd data = pd.DataFrame({&quot;start&quot;: [pd.Timestamp(&quot;2020-01-01 01:23:45&quot;), pd.Timestamp(&quot;2020-01-01 01:45:12&quot;)], &quot;end&quot;: [pd.Timestamp(&quot;2020-01-01 02:23:00&quot;), pd.Timestamp(&quot;2020-01-01 03:12:00&quot;)]}) </code></pre> <p>I want to break down these visits into periods: from 01:00 to 02:00, there were two visitors, from 02:00 to 03:00, also two, and from 03:00 to 04:00, only one of the visitors was present. To achieve this, I'm generating bounds for my periods and generate a dataframe with overlaps:</p> <pre><code>periods = pd.DataFrame({&quot;period_start&quot;: pd.date_range(start = &quot;2020-01-01 01:00:00&quot;, end = &quot;2020-01-01 03:00:00&quot;, freq = &quot;1H&quot;), &quot;period_end&quot;: pd.date_range(start = &quot;2020-01-01 02:00:00&quot;, end = &quot;2020-01-01 04:00:00&quot;, freq = &quot;1H&quot;)}) def has_overlap(A_start, A_end, B_start, B_end): latest_start = max(A_start, B_start) earliest_end = min(A_end, B_end) return latest_start &lt;= earliest_end periods_breakdown = pd.DataFrame() for i in range(3): ps = periods.period_start[i] pe = periods.period_end[i] periods_breakdown[&quot;period&quot; + str(i)] = data.apply(lambda row: has_overlap(row.start, row.end, ps, pe), axis = 1) </code></pre> <p>On the toy data, this code returns</p> <pre><code> period0 period1 period2 0 True True False 1 True True True </code></pre> <p>The problem is that the actual data has 1M visits that I want to break down over 6000 periods, and the code runs for roughly 140 hours.</p> <ol> <li>Is there a better way to count visitors from this sort of data?</li> <li>Are there performance improvements to this code?</li> </ol>
[]
{ "AcceptedAnswerId": "261394", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T10:38:19.707", "Id": "261278", "Score": "4", "Tags": [ "python", "performance", "datetime", "pandas" ], "Title": "For each of the visitors, find if they were present within a time period: code is running slow" }
261278
accepted_answer
[ { "body": "<p>As I worked more with these data, I realized that two problems were keeping me away from a decent performance:</p>\n<ol>\n<li>There is a big overhead with using <code>pandas</code>, and</li>\n<li>The data about visits is sparse, and I should make use of it</li>\n</ol>\n<p>So, the same data can be calculated by starting with an <code>np.zeros</code> matrix of a corresponding size, and setting <code>1</code>s within the range of each visit. Since the resulting data is purely numeric, it's better kept in a <code>numpy</code> array, not in a <code>pandas</code> dataframe. I also made use of <code>floor</code> and <code>ceil</code> functions for <code>pd.Timestamp</code> mentioned in <a href=\"https://codereview.stackexchange.com/a/261335/138891\">Lenormju's answer</a> to produce the following code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>range_start = min(data.start).floor(&quot;H&quot;)\nrange_end = max(data.end).ceil(&quot;H&quot;)\nrange_n = (range_end - range_start) // pd.Timedelta(&quot;1H&quot;)\n\nperiod_breakdown = np.zeros([len(data.index), range_n])\nfor i, row in data.iterrows():\n start_offset = (row.start.floor(&quot;H&quot;) - range_start) // pd.Timedelta(&quot;1H&quot;)\n end_offset = (row.end.ceil(&quot;H&quot;) - range_start) // pd.Timedelta(&quot;1H&quot;)\n period_breakdown[i,start_offset:end_offset] = 1\n</code></pre>\n<p>which runs for 15 minutes on the same dataset.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:40:20.493", "Id": "515930", "Score": "0", "body": "it used to take 140 hours, is getting down to 0,25 hour sufficient ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T07:24:41.390", "Id": "515935", "Score": "0", "body": "@Lenormju yes, 0,25 hours is quite sufficient." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-29T23:23:31.733", "Id": "261394", "ParentId": "261278", "Score": "0" } } ]
<p>The general problem I'm trying to solve is that I have a code base that has zero documentation so I'm trying to automatically generate some diagrams of classes in package that I'm analyzing using erdantic.</p> <p>Trying to make this as reusable as possible, so I have a <code>generate_diagrams()</code> function that should take in one argument, which is the package I want to iterate through.</p> <p>I often feel like I throw the terms <em>module</em> and <em>package</em> around interchangeably — I might be doing it now — so I defaulted my argument to the name &quot;directory&quot;. But I feel that's not right since I'm not passing in a path.</p> <p>Should I change the argument in <code>generate_diagrams()</code> below? What's a more accurate name?</p> <pre><code>import erdantic as erd import glob import importlib import example.models from os import path, makedirs def draw_diagram(module, cls_name, output_path): &quot;&quot;&quot; Args: module: module object cls_name: name of the class that's associated with the module output_path: path where diagram to be saved Returns: void - outputs .png file at given path &quot;&quot;&quot; try: diagram = erd.create(module.__getattribute__(cls_name)) diagram.models diagram.draw(f&quot;{output_path}/{cls_name}.png&quot;) except erd.errors.UnknownModelTypeError: pass def generate_diagrams(directory): &quot;&quot;&quot; Args: directory: package you have imported that contains module(s) you wish to diagram Returns: void - generates diagram using draw_diagram function &quot;&quot;&quot; doc_path = path.dirname(__file__) modules = glob.glob(path.join(path.dirname(directory.__file__), &quot;*.py&quot;)) module_names = [path.basename(f)[:-3] for f in modules if path.isfile(f) and not f.endswith('__init__.py')] for module_name in module_names: if not path.exists(path.join(doc_path, module_name)): print(f'Making {module_name} directory') makedirs(module_name) module = importlib.import_module(f'{directory.__name__}.{module_name}') classes = dict([(name, cls) for name, cls in module.__dict__.items() if isinstance(cls, type)]) for name, cls in classes.items(): print(f'Drawing {module_name}.{name} diagram') draw_diagram(module, cls_name=name, output_path=path.join(doc_path, module_name)) def main(): generate_diagrams(directory=example.models) if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T17:49:09.327", "Id": "515739", "Score": "0", "body": "Have you tried Doxygen?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T18:37:32.697", "Id": "515746", "Score": "0", "body": "I have not. First time trying to automate diagram building. Is that the standard?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T18:42:52.077", "Id": "515747", "Score": "0", "body": "I don't know if I'd call it standard, but it's popular and well-established. I'd give that a shot before writing any code" } ]
{ "AcceptedAnswerId": "261350", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T06:04:30.783", "Id": "261322", "Score": "3", "Tags": [ "python" ], "Title": "Program that provides diagrams for documentation" }
261322
accepted_answer
[ { "body": "<p>The Doxygen recommendation notwithstanding,</p>\n<ul>\n<li>Consider adding PEP484 type hints, particularly to the signatures of functions such as <code>draw_diagram</code>. For that method, it's not really correct Python terminology to call the return value &quot;void&quot; - it's <code>None</code>.</li>\n<li>Does the single-expression statement <code>diagram.models</code> actually have any effect? If so that deserves a comment.</li>\n<li>Rather than <code>glob.glob</code> consider <code>pathlib.Path.glob</code> which has some usage niceties</li>\n<li><code>path.basename(f)[:-3]</code> is a very fragile way of acquiring a stem. Again, <code>pathlib.Path</code> can do a better job.</li>\n</ul>\n<p>The line</p>\n<pre><code>dict([(name, cls) for name, cls in module.__dict__.items() if isinstance(cls, type)])\n</code></pre>\n<p>first of all should not use an inner list, since <code>dict</code> can directly accept a generator; and secondly would be better-represented as a dictionary comprehension:</p>\n<pre><code>{name: cls for name, cls in module.__dict__.items() if isinstance(cls, type)}\n</code></pre>\n<p>This loop:</p>\n<pre><code> for name, cls in classes.items():\n print(f'Drawing {module_name}.{name} diagram')\n draw_diagram(module, cls_name=name, output_path=path.join(doc_path, module_name))\n</code></pre>\n<p>doesn't actually use <code>cls</code>, so should only iterate over the dictionary's keys, not its items.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T20:34:02.977", "Id": "515753", "Score": "0", "body": "All great suggestions. What's the protocol? Should I add an edited version of the changes? I also reconfigured to a class structure so I could add a logger to track exceptions in the draw diagram method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T20:35:19.823", "Id": "515754", "Score": "0", "body": "If you think you've gotten all that you can out of this round, and enough time has passed that it's unlikely you'll get another answer (this is a judgement call on your behalf), then accept whichever answer you think has the highest value and post a new question with your revised code. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:19:17.303", "Id": "516089", "Score": "0", "body": "One last question before I accept this answer. What is your thoughts on the argument name \"directory\" for the generate_diagram() function? Is it more appropriately a package?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T16:21:52.320", "Id": "516090", "Score": "0", "body": "Packages are not a thing in Python - it's a module. Just as important as the name is the typehint, in this case `types.ModuleType`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T19:00:35.227", "Id": "261350", "ParentId": "261322", "Score": "1" } } ]
<p>I have some Python code that runs as part of an Azure Synapse Analytics Apache Spark Notebook (or Synapse Notebook) and would like to add effective error handling. The code simply executes a given SQL script against the database. The code runs but I sometimes see errors like <code>attempt to use closed connection</code>. I would like to do the following:</p> <ul> <li>Improve code that I wrote through peer review</li> <li><s>Can I improve the error handling? eg pseudo-code <code>if connection still open close connection</code></s></li> <li><s>The code using SQL auth works. I would like to authenticate as the Managed Identity, I've tried using the object id of the MI in the connection string with <code>Authentication=ActiveDirectoryMsi</code> but it didn't work</s></li> </ul> <h2>Cell1 - parameters</h2> <pre><code>pAccountName = 'someStorageAccount' pContainerName = 'someContainer' pRelativePath = '/raw/sql/some_sql_files/' pFileName = 'someSQLscript.sql' </code></pre> <h1>Cell 2 - main</h1> <pre><code>import pyodbc from pyspark import SparkFiles try: # Add the file to the cluster so we can view it sqlFilepath = f&quot;&quot;&quot;abfss://{pContainerName}&quot;&quot;&quot; + &quot;@&quot; + f&quot;&quot;&quot;{pAccountName}.dfs.core.windows.net{pRelativePath}{pFileName}&quot;&quot;&quot; sc.addFile(sqlFilepath, False) # Open the file for reading with open(SparkFiles.getRootDirectory() + f'/{pFileName}', 'r') as f: lines = f.read() ## read all text from a file into a string # Open the database connection conn = pyodbc.connect( 'DRIVER={ODBC Driver 17 for SQL Server};' 'SERVER=someServer.sql.azuresynapse.net;' 'DATABASE=someDatabase;UID=batchOnlyUser;' 'PWD=youWish;', autocommit = True ) # Split the script into batches separated by &quot;GO&quot; for batch in lines.split(&quot;GO&quot;): conn.execute(batch) # execute the SQL statement except: raise finally: # Tidy up conn.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:25:11.433", "Id": "515703", "Score": "1", "body": "Can you show an example of what someSQLscript contains?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:41:58.787", "Id": "515704", "Score": "0", "body": "It could be any sql script really, so anything from just `select @@version` to big create table, insert statements etc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T14:43:28.647", "Id": "515705", "Score": "0", "body": "Welcome to the Code Review Community. We can review the code and make suggestions on how to improve it. We can't help you write new code or debug the code. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask). At least 2 things are making the question off-topic, the first is that your valid concerns about security are making you use generic names. The second is that `Authentication=ActiveDirectoryMsi` doesn't work. We can only review working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:17:35.860", "Id": "515713", "Score": "1", "body": "@pacmaninbw Per e.g. https://codereview.meta.stackexchange.com/a/696/25834 I don't see the generic names as a problem, and it's common practice to omit or change credentials; that on its own is not a reason for closure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T16:38:30.697", "Id": "515733", "Score": "1", "body": "Welcome to Code Review! The current question title, asks for code to be written, which is off-topic for Code Review. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T18:51:42.890", "Id": "515748", "Score": "0", "body": "So if I change it to “Review error handling...” instead of “Add effective ...” would that help?" } ]
{ "AcceptedAnswerId": "261341", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T09:34:26.110", "Id": "261325", "Score": "0", "Tags": [ "python", "azure" ], "Title": "Add effective error handling to Python Notebook in Azure Synapse Analytics" }
261325
accepted_answer
[ { "body": "<p>Ignoring your closed-connection and managed-identity questions, since (a) I don't know how to answer them and (b) on their own they're off topic, there is still review to be done:</p>\n<ul>\n<li>A Pythonic way to tell the standard library to format your URI instead of you doing it yourself is to call into <code>urlunparse</code></li>\n<li>Consider using <code>pathlib</code></li>\n<li><code>connect</code> accepts kwargs as an alternative to the conn string, and the former will lay out your connection parameters more nicely</li>\n<li><code>except / raise</code> is redundant and should be deleted</li>\n<li>Your <code>try</code> starts too early and should only start <em>after</em> the connection has been established</li>\n<li>You're not reading a lines list; you're reading content, which would be a better variable name</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from pathlib import Path\nfrom urllib.parse import urlunparse, ParseResult\nimport pyodbc\nfrom pyspark import SparkFiles\n\n\npAccountName = 'someStorageAccount'\npContainerName = 'someContainer'\npRelativePath = '/raw/sql/some_sql_files/'\npFileName = 'someSQLscript.sql'\n\n# Add the file to the cluster so we can view it\nsql_filename = urlunparse(\n ParseResult(\n scheme='abfss',\n netloc=f'{pContainerName}@{pAccountName}.dfs.core.windows.net',\n path=f'{pRelativePath}{pFileName}',\n params=None, query=None, fragment=None,\n )\n)\n\nsc.addFile(sql_filename, False)\n\n# Open the file for reading\nsql_file_path = Path(SparkFiles.getRootDirectory()) / pFileName\nwith sql_file_path.open() as f:\n content = f.read()\n\n# Open the database connection\nconn = pyodbc.connect(\n DRIVER='{ODBC Driver 17 for SQL Server}',\n SERVER='someServer.sql.azuresynapse.net',\n DATABASE='someDatabase',\n UID='batchOnlyUser',\n PWD='youWish',\n autocommit=True,\n)\n\ntry:\n # Split the script into batches separated by &quot;GO&quot;\n for batch in content.split(&quot;GO&quot;):\n conn.execute(batch) # execute the SQL statement\nfinally:\n conn.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:45:58.417", "Id": "515716", "Score": "1", "body": "ok useful, thank you. I'm going to leave it open for a few days but have upvoted and will consider marking as answer later." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T15:37:58.603", "Id": "261341", "ParentId": "261325", "Score": "1" } } ]
<p>I'm using Flask on Python and I'm displaying the username at the top of the site (and it's working) as follows:</p> <pre class="lang-py prettyprint-override"><code>@app.route(&quot;/&quot;) @login_required def index(): &quot;&quot;&quot;Queries the user's First Name to display in the title&quot;&quot;&quot; names = db.execute(&quot;&quot;&quot; SELECT first_name FROM users WHERE id=:user_id &quot;&quot;&quot;, user_id = session[&quot;user_id&quot;] ) return render_template(&quot;index.html&quot;, names = names) </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;header class=&quot;mainHeader&quot;&gt; {% for name in names %} &lt;h1&gt;{{ name[&quot;first_name&quot;] }}' Bookshelf&lt;/h1&gt; {% else %} &lt;h1&gt;Your Bookshelf&lt;/h1&gt; {% endfor %} &lt;/header&gt; </code></pre> <p>I don't know if it is necessary, but here is my database configuration:</p> <p><a href="https://i.stack.imgur.com/Fu0kC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fu0kC.png" alt="TABLE: users -- id: integer, email: text, first_name: text, last_name: text, picture: text" /></a></p> <p>Although it is working, I believe that it is not ideal to use for loop to display just one name. Does anyone have any suggestions?</p> <hr> Editing to include login routine: <pre class="lang-py prettyprint-override"><code>@app.route(&quot;/login&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;]) def login(): &quot;&quot;&quot;Log user in&quot;&quot;&quot; # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == &quot;POST&quot;: # Ensure email and password was submitted result_checks = is_provided(&quot;email&quot;) or is_provided(&quot;password&quot;) if result_checks is not None: return result_checks # Query database for email rows = db.execute(&quot;SELECT * FROM users WHERE email = ?&quot;, request.form.get(&quot;email&quot;)) # Ensure email exists and password is correct if len(rows) != 1 or not check_password_hash(rows[0][&quot;hash&quot;], request.form.get(&quot;password&quot;)): return &quot;E-mail ou Senha inválidos&quot; # Remember which user has logged in session[&quot;user_id&quot;] = rows[0][&quot;id&quot;] session[&quot;email&quot;] = request.form.get(&quot;email&quot;) # Redirect user to home page return redirect(&quot;/&quot;) # User reached route via GET (as by clicking a link or via redirect) else: return render_template(&quot;login.html&quot;) </code></pre>
[]
{ "AcceptedAnswerId": "261357", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T22:43:07.053", "Id": "261356", "Score": "0", "Tags": [ "python", "sqlite", "session", "flask" ], "Title": "Getting a username from a database and displaying it in HTML" }
261356
accepted_answer
[ { "body": "<p>according to the query, it seems that the row count is either 0 or 1. so the loop would either have no iterations (the <code>else</code> part) or have exactly one iteration.</p>\n<p>in terms of performance, I think that any improvement here is not dramatic.</p>\n<p>however, in terms of choosing the right coding tools for the job, it seems that a loop is not the right tool.</p>\n<p>maybe the following would be better:</p>\n<pre><code>@app.route(&quot;/&quot;)\n@login_required\ndef index():\n &quot;&quot;&quot;Queries the user's First Name to display in the title&quot;&quot;&quot;\n names = db.execute(&quot;&quot;&quot;\n SELECT first_name\n FROM users\n WHERE id=:user_id\n &quot;&quot;&quot;,\n user_id = session[&quot;user_id&quot;] \n )\n first_name = names[0][&quot;first_name&quot;] if names else None\n return render_template(&quot;index.html&quot;, first_name = first_name)\n</code></pre>\n<p>and then:</p>\n<pre><code>&lt;header class=&quot;mainHeader&quot;&gt;\n {% if first_name %}\n &lt;h1&gt;{{ first_name }}'s Bookshelf&lt;/h1&gt;\n {% else %}\n &lt;h1&gt;Your Bookshelf&lt;/h1&gt;\n {% endif %}\n&lt;/header&gt;\n</code></pre>\n<p>note: I didn't test the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T23:28:44.653", "Id": "515761", "Score": "0", "body": "It is working fine! I really appreciate! The `else` was there because I was trying to implement an if statement and then I forgot to remove before inserting the code here. Thanks @Ron!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-28T22:56:36.340", "Id": "261357", "ParentId": "261356", "Score": "1" } } ]
<p>My very first computer program, a very simple income tax calculator. What can I do to get the same outcome with better efficiency?</p> <pre><code># 2021 income tax calculator print ('What\'s your yearly income after you deduct all expenses?') myincome = int(input()) base = (myincome*.1) e = (max(myincome-9950,0)*.02) ex = (max(myincome-40525,0)*.1) ext = (max(myincome-86376,0)*.02) extr = (max(myincome-164926,0)*.08) extra = (max(myincome-209426,0)*.03) extras = (max(myincome-523601,0)*.02) tax = base + e + ex + ext + extr + extra + extras print ('You\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax') print () while True: print ('Try Different Income:') myincome = int(input()) base = (myincome*.1) e = (max(myincome-9950,0)*.02) ex = (max(myincome-40525,0)*.1) ext = (max(myincome-86376,0)*.02) extr = (max(myincome-164926,0)*.08) extra = (max(myincome-209426,0)*.03) extras = (max(myincome-523601,0)*.02) tax = base + e + ex + ext + extr + extra + extras print ('You\'re gonna get screwed about~$',str(tax) + ' dollars in Federal income tax') print () continue </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T08:24:17.273", "Id": "515867", "Score": "1", "body": "Hi @JJZ - what if someone enters a negative value for income? Or zero? And where's the formula from (maybe add where the calcuation is from - since you mention the YR the calc is for).. AND it's for US Federal Taxes?" } ]
{ "AcceptedAnswerId": "261416", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T06:32:29.213", "Id": "261407", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Simple Income Tax Calculator" }
261407
accepted_answer
[ { "body": "<ol>\n<li>You should split your code into reusable functions instead of manually rewriting / copying code.</li>\n<li>You should put your code into a <code>main()</code> function and wrap the call to it in a <code>if __name__ == &quot;__main__&quot;</code> condition. More info <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">here</a>.</li>\n<li>Variable names like <code>e, ex, ext, ...</code> aren't descriptive.</li>\n<li>You should include error handling for user input.</li>\n<li>You don't need seperate variables for every single tax bracket, rather you want a list of all tax brackets to iterate over.</li>\n<li>Depending on the income, you shouldn't always need to calculate all tax brackets. Once a bracket doesn't apply to the income, the subsequent brackets won't apply either.</li>\n<li>There should not be a space in <code>print (...)</code></li>\n<li>There should be spaces around operators and commas in <code>e = (max(myincome-9950,0)*.02)</code> -&gt; <code>e = (max(myincome - 9950, 0) * .02)</code></li>\n<li>If applicable, use your IDEs auto-formatting feature (e.g. <code>Ctrl</code> + <code>Alt</code> + <code>L</code> in PyCharm) to automatically avoid the aforementioned formatting issues.</li>\n<li>f-Strings make printing text including variables really convenient and handle string conversion for you.</li>\n<li>Type annotations are generally a good idea. They're beneficial to readability and error-checking.</li>\n</ol>\n<hr />\n<p><strong>Suggested code</strong></p>\n<pre><code>TAX_BRACKETS = [\n (0, 0.1),\n (9950, 0.02),\n (40525, 0.1),\n (86376, 0.02),\n (164926, 0.08),\n (209426, 0.03),\n (523601, 0.02)\n]\n\n\ndef get_income(prompt: str = &quot;&quot;, force_positive: bool = False) -&gt; int:\n try:\n income = int(input(prompt))\n except ValueError:\n print(&quot;Could not convert income to integer, please try again.&quot;)\n return get_income(prompt=prompt, force_positive=force_positive)\n\n if force_positive and income &lt; 0:\n print(&quot;Income must not be negative, please try again.&quot;)\n return get_income(prompt=prompt, force_positive=force_positive)\n\n return income\n\n\ndef calculate_income_tax(income: float) -&gt; float:\n tax = 0\n\n for bracket, rate in TAX_BRACKETS:\n if bracket &gt; income:\n break\n\n tax += (income - bracket) * rate\n\n return tax\n\n\ndef print_tax(tax: float) -&gt; None:\n print(f&quot;You're gonna get screwed about~${tax} dollars in Federal income tax\\n&quot;)\n\n\ndef main():\n income = get_income(prompt=&quot;What's your yearly income after you deduct all expenses?\\n&quot;)\n federal_income_tax = calculate_income_tax(income)\n print_tax(federal_income_tax)\n\n while True:\n income = get_income(prompt=&quot;Try different income:\\n&quot;)\n federal_income_tax = calculate_income_tax(income)\n print_tax(federal_income_tax)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T10:18:34.293", "Id": "261416", "ParentId": "261407", "Score": "3" } } ]
<p>I created a class to handle maps in my RPG game, before it became a class this was a collection of functions I created, but I thought it could be used as a class. although this code is working but i am not sure what i made. changing the function set to OOP confuses me.</p> <pre><code>import os import pygame import helper_func as hf class Map: def __init__(self): self.map = [] self.images = {} self.tile_size = (50, 50) def load_map(self, path): ''' load map from txt to 2d list ''' f = open(path, &quot;r&quot;) file = f.read() f.close() sep = file.split(&quot;\n&quot;) for tile in sep: numbers = tile.split(&quot;,&quot;) self.map.append(numbers) @staticmethod def generate_key(image): result = [] for char in image: try: if isinstance(int(char), int): result.append(char) except Exception: pass return &quot;&quot;.join(result) def map_images(self, path): ''' load tileset image to dictionary ''' images = os.listdir(path) for image in images: key = Map.generate_key(image) self.images[key] = hf.load_image(f&quot;{path}/{image}&quot;, self.tile_size[0], self.tile_size[1]) def render(self, screen): y = 0 for row in self.map: x = 0 for tile in row: screen.blit(self.images[tile], (x, y)) x += self.tile_size[0] y += self.tile_size[1] </code></pre> <p>Is there anything that needs to be fixed?</p>
[]
{ "AcceptedAnswerId": "261490", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T07:49:08.107", "Id": "261412", "Score": "4", "Tags": [ "python", "python-3.x", "object-oriented", "game", "pygame" ], "Title": "class that handles the rpg game map" }
261412
accepted_answer
[ { "body": "<p><code>Map.tile_size</code> seems awkward. You never use the tuple as whole, only the individual <code>[0]</code> and <code>[1]</code> components. Perhaps use two members (<code>Map.tile_width</code> and <code>Map.tile_height</code>) would be clearer, and possibly slightly faster due to removing one level of lookup.</p>\n<p>In <code>Map.load_map</code>, you split lines of text on commas, and assign it to <code>numbers</code>, but actually you just have a list of strings which presumably happen to look like numbers. What are these numbers? <code>0</code> to <code>9</code>? <code>00</code> to <code>99</code>? If they are small integers (0-255), you might store them very compactly as a <code>bytearray()</code>, or <code>bytes()</code> object. If the range of values is larger that a byte, you could use <code>array.array()</code>.</p>\n<p><code>Map.generate_key</code>: you’re using <code>try: catch:</code> to test if a character is in the range <code>'0'</code> to <code>'9'</code>? That is very expensive test, more so because you then test <code>isinstance(…, int)</code> which must be true if <code>int(char)</code> didn’t return an exception! The <code>isdecimal()</code> function can easily determine if the character is a digit, and the entire function body could be replaced with a single statement:</p>\n<pre><code> return &quot;&quot;.join(char for char in image if char.isdecimal())\n</code></pre>\n<p><code>map_images</code> is a very uninformative name. <code>load_map_images</code> would be better. <code>os.listdir(path)</code> is giving you ALL the files in the directory, which means you can’t have any backup files, readme files, or source-code control files in that directory. You should probably use a <code>glob()</code> to find only <code>*.png</code> files (or .gif, or whatever image format you are using).</p>\n<p>Your images are stored by by “key”, which is only the digits in the filename. So, <code>water0.png</code> and <code>grass0.png</code> would both be stored as under the key <code>&quot;0&quot;</code>, with the last one overwriting any previous ones. You might want to check for uniqueness or collisions.</p>\n<p>Which begs the question, why are you storing the map as numbers? Maybe “grass”, “forest”, “nw-road” would be clearer than “12”, “17”, “42”.</p>\n<p><code>render</code> seems to be only able to render the entire map. Perhaps that is all that is necessary for the game in question, but in many games, you’d usually render a small region around a given x,y coordinate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T23:32:36.920", "Id": "261490", "ParentId": "261412", "Score": "2" } } ]
<p>Can some one help me on how to eliminate repetition to reduce duplication score on the below classes created in the code</p> <pre><code>class EnquiryFilterSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = '__all__' class EnquirySerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = '__all__' def update(self, instance, validated_data): # making sure if broker is not fetched then replace null value with # some resonable data as it will help in duing filter if len(validated_data.get('email_broker', instance.email_broker)) == 0: instance.email_broker = not_avbl instance.save() return instance class EnquiryBrokerNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['broker_email_id'] class EnquiryAssignedUserSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['email_assigned_user'] class EnquiryInsuredNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_insured_name'] class EnquiryObligorNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_obligor_name'] class EnquiryCountryNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['el_country_name'] class EnquiryLimitSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['enquirylog_limit'] class EnquiryDecisionSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_underwriter_decision'] class NotesSerializer(serializers.ModelSerializer): class Meta: model = notes fields = '__all__' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T07:22:17.073", "Id": "520455", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:52:44.647", "Id": "261426", "Score": "1", "Tags": [ "python", "database", "django", "serialization", "rest" ], "Title": "Wanted to eliminate the repetition in the classes created to reduce duplication" }
261426
max_votes
[ { "body": "<p><code>type</code> is just another type. Classes can be created in, and returned from, functions just fine. An approach kind of like</p>\n<pre><code>def basic_model_serializer(model, fields):\n _model, _fields = model, fields\n\n class _internal(serializers.ModelSerializer):\n class Meta:\n model = _model\n fields = _fields\n\n return _internal\n\nEnquiryFilterSerializer = basic_model_serializer(enquirylog, '__all__')\nEnquiryBrokerNameSerializer = basic_model_serializer(enquirylog, ['broker_email_id'])\n...\nNotesSerializer = basic_model_serializer(notes, '__all__')\n\nclass EnquirySerializer(serializers.ModelSerializer):\n ... # unchanged due to update()\n</code></pre>\n<p>would let you abstract over the few differences of the most similar classes in a pretty natural way. Is it an improvement over your existing code? Maybe in some ways, maybe not in others.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:35:08.027", "Id": "515929", "Score": "0", "body": "I am getting error saying Unresolved reference to 'model' and Unresolved reference to 'fields'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:45:55.590", "Id": "515932", "Score": "0", "body": "@Sherlock Right, sorry about that, I got it too but forgot to put my workaround in the answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T13:48:56.897", "Id": "515969", "Score": "0", "body": "Thank you I resolved the errors" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T19:48:23.747", "Id": "261435", "ParentId": "261426", "Score": "1" } } ]
<p>Can some one help me on how to eliminate repetition to reduce duplication score on the below classes created in the code</p> <pre><code>class EnquiryFilterSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = '__all__' class EnquirySerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = '__all__' def update(self, instance, validated_data): # making sure if broker is not fetched then replace null value with # some resonable data as it will help in duing filter if len(validated_data.get('email_broker', instance.email_broker)) == 0: instance.email_broker = not_avbl instance.save() return instance class EnquiryBrokerNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['broker_email_id'] class EnquiryAssignedUserSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['email_assigned_user'] class EnquiryInsuredNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_insured_name'] class EnquiryObligorNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_obligor_name'] class EnquiryCountryNameSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['el_country_name'] class EnquiryLimitSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['enquirylog_limit'] class EnquiryDecisionSerializer(serializers.ModelSerializer): class Meta: model = enquirylog fields = ['ef_underwriter_decision'] class NotesSerializer(serializers.ModelSerializer): class Meta: model = notes fields = '__all__' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T07:22:17.073", "Id": "520455", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T15:52:44.647", "Id": "261426", "Score": "1", "Tags": [ "python", "database", "django", "serialization", "rest" ], "Title": "Wanted to eliminate the repetition in the classes created to reduce duplication" }
261426
max_votes
[ { "body": "<p><code>type</code> is just another type. Classes can be created in, and returned from, functions just fine. An approach kind of like</p>\n<pre><code>def basic_model_serializer(model, fields):\n _model, _fields = model, fields\n\n class _internal(serializers.ModelSerializer):\n class Meta:\n model = _model\n fields = _fields\n\n return _internal\n\nEnquiryFilterSerializer = basic_model_serializer(enquirylog, '__all__')\nEnquiryBrokerNameSerializer = basic_model_serializer(enquirylog, ['broker_email_id'])\n...\nNotesSerializer = basic_model_serializer(notes, '__all__')\n\nclass EnquirySerializer(serializers.ModelSerializer):\n ... # unchanged due to update()\n</code></pre>\n<p>would let you abstract over the few differences of the most similar classes in a pretty natural way. Is it an improvement over your existing code? Maybe in some ways, maybe not in others.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:35:08.027", "Id": "515929", "Score": "0", "body": "I am getting error saying Unresolved reference to 'model' and Unresolved reference to 'fields'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T06:45:55.590", "Id": "515932", "Score": "0", "body": "@Sherlock Right, sorry about that, I got it too but forgot to put my workaround in the answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T13:48:56.897", "Id": "515969", "Score": "0", "body": "Thank you I resolved the errors" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T19:48:23.747", "Id": "261435", "ParentId": "261426", "Score": "1" } } ]
<pre class="lang-py prettyprint-override"><code>from itertools import cycle # Integers represent Chinese characters main_text = &quot;234458674935346547521456767378878473562561423&quot; text_with_commentary = &quot;2344586749215432678652353465475214561655413164653413216576737887847356152352561423&quot; iter_main = iter(main_text) iter_comm = iter(text_with_commentary) marked_up = [] x = next(iter_main) y = next(iter_comm) i = 0 j = 0 def commentary_start(): global x, y, i, j, marked_up while x == y and j &lt; len(text_with_commentary): try: marked_up.append(y) x = next(iter_main) y = next(iter_comm) i += 1 j += 1 except: return marked_up.append(&quot;{{&quot;) return marked_up def commentary_end(): global x, y, i, j, marked_up while x != y: marked_up.append(y) y = next(iter_comm) j += 1 if main_text[i+1] == text_with_commentary[j+1] and \ main_text[i+2] == text_with_commentary[j+2]: marked_up.append(&quot;}}&quot;) else: marked_up.append(y) y = next(iter_comm) j += 1 commentary_end() return marked_up def mark_up_commentary(): global marked_up while j &lt; len(text_with_commentary): try: commentary_start() commentary_end() except: break marked_up = &quot;&quot;.join(marked_up) return marked_up mark_up_commentary() # Expected result: &quot;2344586749{{215432678652}}35346547521456{{16554131646534132165}}76737887847356{{15235}}2561423&quot; </code></pre> <p>The above code compares two sets of strings, character by character, to markup commentary text that is interspersed between the main text.</p> <p>The code makes use of the iterators <code>iter_main</code> and <code>inter_comm</code> to check if the next character in the commented text is the same as the next character of the main text, adding double braces to mark up commentary text that deviates from the main text at the relevant positions.</p> <p>I would like to seek help to improve the code in these respects:</p> <ol> <li>See if the code can be made more concise and efficient.</li> <li>The current method is actually quite hard-coded and mechanical, which makes little room for minor deviations in the texts, which is actually unavoidable in the real world. I would hence like to know whether fuzzy text-comparison tools that make use of concepts such as Levenshtein distance can be implemented to make the code more robust and flexible.</li> <li>Are there good libraries to recommend for the task?</li> </ol>
[]
{ "AcceptedAnswerId": "261468", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T11:14:01.563", "Id": "261462", "Score": "2", "Tags": [ "python", "strings", "iterator" ], "Title": "Compare strings to markup commentary in main text" }
261462
accepted_answer
[ { "body": "<blockquote>\n<p>Are there good libraries to recommend for the task?</p>\n</blockquote>\n<p>Yes, and it's built-in: read about <code>difflib</code>.</p>\n<blockquote>\n<p>I would hence like to know whether fuzzy text-comparison tools [...] can be implemented</p>\n</blockquote>\n<p>Off-topic for CodeReview.</p>\n<p>Avoid globals, use <code>difflib</code>, and this becomes</p>\n<pre><code>from difflib import SequenceMatcher\nfrom typing import Iterable\n\n\ndef diff(main_text: str, text_with_commentary: str) -&gt; Iterable[str]:\n matcher = SequenceMatcher(a=main_text, b=text_with_commentary, autojunk=False)\n for op, a0, a1, b0, b1 in matcher.get_opcodes():\n right = text_with_commentary[b0: b1]\n if op == 'equal':\n yield right\n elif op == 'insert':\n yield '{' + right + '}'\n else:\n raise ValueError(f&quot;{op} indicates malformed text&quot;)\n\n\ndef test():\n actual = ''.join(\n diff(\n main_text=(\n &quot;2344586749&quot;\n &quot;35346547521456&quot;\n &quot;76737887847356&quot;\n &quot;2561423&quot;\n ),\n text_with_commentary=(\n &quot;2344586749&quot;\n &quot;215432678652&quot;\n &quot;35346547521456&quot;\n &quot;16554131646534132165&quot;\n &quot;76737887847356&quot;\n &quot;15235&quot;\n &quot;2561423&quot;\n ),\n )\n )\n\n expected = (\n &quot;2344586749&quot;\n &quot;{215432678652}&quot;\n &quot;35346547521456&quot;\n &quot;{16554131646534132165}&quot;\n &quot;76737887847356&quot;\n &quot;{15235}&quot;\n &quot;2561423&quot;\n )\n assert actual == expected\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:17:31.720", "Id": "515972", "Score": "0", "body": "Could you explain the logic of the code to me? This is the first time I've come across a generator function. Seems like I am supposed to use it with `''.join([i for i in diff(main_text, text_with_commentary)])`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:24:44.337", "Id": "515973", "Score": "1", "body": "Close, but it would just be `''.join(diff(....))`. It's just yielding strings that the user can choose to do with it what they like - join, or otherwise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:51:17.463", "Id": "515976", "Score": "0", "body": "What does `Iterable[str]` at the function annotation do? Is it there just to indicate that this function returns an iterable string?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T14:55:54.720", "Id": "515978", "Score": "0", "body": "An iterable of strings - in other words, if you `for x in diff()`, `x` will be a string on each iteration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T02:40:25.110", "Id": "516039", "Score": "0", "body": "The variables `op, a0, a1, b0, b1` seem to map to my globals `marked_up, x, y, i, j`, but not exactly. What are the differences between these two sets of variables other than globality?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T03:02:02.170", "Id": "516041", "Score": "0", "body": "They have totally different purposes. Read about `get_opcodes` here: https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.get_opcodes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T04:05:12.030", "Id": "516044", "Score": "1", "body": "`SequenceMatcher(None, a, b)` would return a tuple that describes how string `a` transcribes to string `b`. `op` is the tag, while `a0, a1` and `b0, b1` are the position indicators of the stretch of matching or mismatching strings between `a` and `b`. Is this understanding correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T13:10:13.370", "Id": "516081", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/124949/discussion-between-reinderien-and-sati)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-31T13:27:15.477", "Id": "261468", "ParentId": "261462", "Score": "3" } } ]
<p>I have the following code where I am trying to map columns from the input file to output.</p> <p>I have written it using multiple loops. Is there a way to write this more efficiently?</p> <h3>input.csv:</h3> <pre><code> Name, Age, Gender, Nation Joe, 18, Male, British </code></pre> <h3>output.csv:</h3> <pre><code>First_name, Age_Years, Gender_F_M, Religion, Nationality Joe, 18, Male, , British </code></pre> <h3>code:</h3> <pre><code>import csv renamed_headers = { &quot;First_name&quot;: &quot;Name&quot;, &quot;Age_Years&quot;:&quot;Age&quot;, &quot;Gender_F_M&quot;:&quot;Gender&quot;, &quot;Religion&quot;: None, &quot;Nationality&quot;: &quot;Nation&quot;, } with open(&quot;input.csv&quot;) as input_file, open(r&quot;output.csv&quot;, &quot;w&quot;, newline=&quot;&quot;) as output_file: reader = csv.DictReader(input_file, delimiter=&quot;,&quot;) writer = csv.writer(output_file, delimiter=&quot;,&quot;) # write headers header_line = [] for header_name in renamed_headers.keys(): header_line.append(header_name) writer.writerow(header_line) # write values for item in reader: row_to_write = [] print(item) for value in renamed_headers.values(): if value: row_to_write.append(item[value]) else: row_to_write.append(&quot;&quot;) writer.writerow(row_to_write) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:06:19.040", "Id": "516068", "Score": "0", "body": "I suspect that all the parts involving \"writerow\" should be one level of indentation deeper (so that we are still in the \"with\" block)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:07:22.553", "Id": "516069", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:07:33.280", "Id": "516070", "Score": "0", "body": "ah apologies the renamed header names were the wrong way round" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:08:36.463", "Id": "516071", "Score": "0", "body": "Is \"less code\" your only concern? Why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:10:25.270", "Id": "516072", "Score": "0", "body": "@Mast and if theres a more efficient way to write it - i feel as if I am looping too much in write row - what would be the best practice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:48:41.603", "Id": "516073", "Score": "0", "body": "I think your write headers and write values sections are both wrongly indented. Now the file gets closed before you're done with the writing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T11:55:59.710", "Id": "516074", "Score": "0", "body": "I suggest you take a look at `pandas` if you ever need something more sophisticated than this. [Read](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html) the `.csv`. Optionally [select](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html) some columns. [Rename](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html) the columns. [Save](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html) the data as a `.csv`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T12:18:30.773", "Id": "516076", "Score": "0", "body": "I've fixed your indentation (the alternative was closing the question). Please double-check your indentation next time yourself, it's *very* important in Python as it will completely change how your program works if it's pasted wrong. Please double-check if what I've made of it is indeed how it looks like in your IDE as well." } ]
{ "AcceptedAnswerId": "261534", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-01T10:38:38.893", "Id": "261504", "Score": "3", "Tags": [ "python", "python-3.x", "csv" ], "Title": "Mapping CSV columns" }
261504
accepted_answer
[ { "body": "<p>You have made a good decision to read the rows as dicts. You can simplify the\ncode further by taking fuller advantage of the <code>csv</code> library's ability to write\ndicts as well.</p>\n<p>It's a good habit to write data transformation programs like this with a\nseparation between data collection, data conversion, and data output -- at\nleast if feasible, given other important considerations. Such separation has\nmany benefits related to testing, debugging, and flexibility in the face of\nevolving requirements. In addition, drawing clear boundaries tends to\nresult in code that is easier to read and understand quickly.</p>\n<p>Another good habit for such programs is to avoid hardcoding files paths\nin the script (other than as default values). It's often handy, for example,\nto test and debug with small files. Paths to those alternative files can\ncome from command-line arguments.</p>\n<p>If you want to be rigorous, you could extract a few more constants\nout of the code.</p>\n<p>An illustration:</p>\n<pre class=\"lang-python prettyprint-override\"><code>\nimport csv\nimport sys\n\nRENAMED_HEADERS = {\n 'First_name': 'Name',\n 'Age_Years':'Age',\n 'Gender_F_M':'Gender',\n 'Religion': None,\n 'Nationality': 'Nation',\n}\n\nDELIMITER = ','\n\nPATHS = ('input.csv', 'output.csv')\n\ndef main(args):\n input_path, output_path = args or PATHS\n rows = read_rows(input_path)\n converted = convert_rows(rows)\n write_rows(output_path, converted)\n\ndef read_rows(path):\n with open(path) as fh:\n reader = csv.DictReader(fh, delimiter=DELIMITER)\n return list(reader)\n\ndef convert_rows(rows):\n return [\n {\n new : r.get(old, '')\n for new, old in RENAMED_HEADERS.items()\n }\n for r in rows\n ]\n\ndef write_rows(path, rows):\n header = list(RENAMED_HEADERS)\n with open(path, 'w', newline='') as fh:\n writer = csv.DictWriter(fh, fieldnames=header, delimiter=DELIMITER)\n writer.writeheader()\n writer.writerows(rows)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T04:52:16.190", "Id": "261534", "ParentId": "261504", "Score": "2" } } ]
<p>I had this <a href="https://codereview.stackexchange.com/questions/261387/python-trivia-game-getting-questions-and-answers-off-a-website" title="This Stackexchange post">trivia game</a>, and from the review I got I improved my game. One of the improvements I made was this short function, to check the correctness of an answer (so if the correct answer was &quot;Yellowstone park in Wyoming&quot;, &quot;Yellowstone park&quot; could be accepted. The code I have below works, but I would like it to be smarter, as the current code is simple. Any ideas? Thanks.</p> <pre><code>def check(answer, correct, percentage): matches = 0 if len(answer) &lt; len(correct): for x in range(len(answer)): if answer[x] == correct[x]: matches += 1 total = len(correct) else: for x in range(len(correct)): if answer[x] == correct[x]: matches += 1 total = len(answer) matches_percentage = (matches/total * 100) if matches_percentage &gt;= percentage: return True else: return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T22:15:26.353", "Id": "516167", "Score": "2", "body": "the requirements are not clear enough. e.g. will \"park in\" be a good answer in your example? is the order of the words important? e.g. will \"Wyoming Yellowstone\" have the same rank as \"Yellowstone Wyoming\"? define better requirements and then the implementation can be discussed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:15:06.707", "Id": "516174", "Score": "1", "body": "Take a look at [`difflib.SequenceMatcher`](https://docs.python.org/3.9/library/difflib.html#sequencematcher-examples) in the standard library. It has a `ratio()` method that returns a similarity score on a scale of 0.0 to 1.0." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T21:57:14.470", "Id": "261561", "Score": "0", "Tags": [ "beginner", "python-3.x" ], "Title": "Short function to check if an entered answer is close to a correct one" }
261561
max_votes
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code> if matches_percentage &gt;= percentage:\n return True\n else:\n return False\n</code></pre>\n<p>is a verbose way of writing</p>\n<pre class=\"lang-py prettyprint-override\"><code> return matches_percentage &gt;= percentage\n</code></pre>\n<p>In <code>matches_percentage = (matches/total * 100)</code>, the parentheses are unnecessary.</p>\n<p>You could compute <code>total</code> with just one <code>max(...)</code> expression:</p>\n<pre><code>total = max(len(correct), len(answer))\n</code></pre>\n<p>That just leaves comparing successive elements of <code>correct</code> and <code>answer</code> and counting matches until you run out of terms from one list or the other. The <code>zip(...)</code> function is ideal for that.</p>\n<pre><code>matches = sum(a == b for a, b in zip(correct, answer))\n</code></pre>\n<p>I believe that reduces your function to four statements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T01:52:16.763", "Id": "261562", "ParentId": "261561", "Score": "1" } } ]
<p>I had this <a href="https://codereview.stackexchange.com/questions/261387/python-trivia-game-getting-questions-and-answers-off-a-website" title="This Stackexchange post">trivia game</a>, and from the review I got I improved my game. One of the improvements I made was this short function, to check the correctness of an answer (so if the correct answer was &quot;Yellowstone park in Wyoming&quot;, &quot;Yellowstone park&quot; could be accepted. The code I have below works, but I would like it to be smarter, as the current code is simple. Any ideas? Thanks.</p> <pre><code>def check(answer, correct, percentage): matches = 0 if len(answer) &lt; len(correct): for x in range(len(answer)): if answer[x] == correct[x]: matches += 1 total = len(correct) else: for x in range(len(correct)): if answer[x] == correct[x]: matches += 1 total = len(answer) matches_percentage = (matches/total * 100) if matches_percentage &gt;= percentage: return True else: return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T22:15:26.353", "Id": "516167", "Score": "2", "body": "the requirements are not clear enough. e.g. will \"park in\" be a good answer in your example? is the order of the words important? e.g. will \"Wyoming Yellowstone\" have the same rank as \"Yellowstone Wyoming\"? define better requirements and then the implementation can be discussed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:15:06.707", "Id": "516174", "Score": "1", "body": "Take a look at [`difflib.SequenceMatcher`](https://docs.python.org/3.9/library/difflib.html#sequencematcher-examples) in the standard library. It has a `ratio()` method that returns a similarity score on a scale of 0.0 to 1.0." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T21:57:14.470", "Id": "261561", "Score": "0", "Tags": [ "beginner", "python-3.x" ], "Title": "Short function to check if an entered answer is close to a correct one" }
261561
max_votes
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code> if matches_percentage &gt;= percentage:\n return True\n else:\n return False\n</code></pre>\n<p>is a verbose way of writing</p>\n<pre class=\"lang-py prettyprint-override\"><code> return matches_percentage &gt;= percentage\n</code></pre>\n<p>In <code>matches_percentage = (matches/total * 100)</code>, the parentheses are unnecessary.</p>\n<p>You could compute <code>total</code> with just one <code>max(...)</code> expression:</p>\n<pre><code>total = max(len(correct), len(answer))\n</code></pre>\n<p>That just leaves comparing successive elements of <code>correct</code> and <code>answer</code> and counting matches until you run out of terms from one list or the other. The <code>zip(...)</code> function is ideal for that.</p>\n<pre><code>matches = sum(a == b for a, b in zip(correct, answer))\n</code></pre>\n<p>I believe that reduces your function to four statements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T01:52:16.763", "Id": "261562", "ParentId": "261561", "Score": "1" } } ]
<p>I had this <a href="https://codereview.stackexchange.com/questions/261387/python-trivia-game-getting-questions-and-answers-off-a-website" title="This Stackexchange post">trivia game</a>, and from the review I got I improved my game. One of the improvements I made was this short function, to check the correctness of an answer (so if the correct answer was &quot;Yellowstone park in Wyoming&quot;, &quot;Yellowstone park&quot; could be accepted. The code I have below works, but I would like it to be smarter, as the current code is simple. Any ideas? Thanks.</p> <pre><code>def check(answer, correct, percentage): matches = 0 if len(answer) &lt; len(correct): for x in range(len(answer)): if answer[x] == correct[x]: matches += 1 total = len(correct) else: for x in range(len(correct)): if answer[x] == correct[x]: matches += 1 total = len(answer) matches_percentage = (matches/total * 100) if matches_percentage &gt;= percentage: return True else: return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T22:15:26.353", "Id": "516167", "Score": "2", "body": "the requirements are not clear enough. e.g. will \"park in\" be a good answer in your example? is the order of the words important? e.g. will \"Wyoming Yellowstone\" have the same rank as \"Yellowstone Wyoming\"? define better requirements and then the implementation can be discussed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:15:06.707", "Id": "516174", "Score": "1", "body": "Take a look at [`difflib.SequenceMatcher`](https://docs.python.org/3.9/library/difflib.html#sequencematcher-examples) in the standard library. It has a `ratio()` method that returns a similarity score on a scale of 0.0 to 1.0." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T21:57:14.470", "Id": "261561", "Score": "0", "Tags": [ "beginner", "python-3.x" ], "Title": "Short function to check if an entered answer is close to a correct one" }
261561
max_votes
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code> if matches_percentage &gt;= percentage:\n return True\n else:\n return False\n</code></pre>\n<p>is a verbose way of writing</p>\n<pre class=\"lang-py prettyprint-override\"><code> return matches_percentage &gt;= percentage\n</code></pre>\n<p>In <code>matches_percentage = (matches/total * 100)</code>, the parentheses are unnecessary.</p>\n<p>You could compute <code>total</code> with just one <code>max(...)</code> expression:</p>\n<pre><code>total = max(len(correct), len(answer))\n</code></pre>\n<p>That just leaves comparing successive elements of <code>correct</code> and <code>answer</code> and counting matches until you run out of terms from one list or the other. The <code>zip(...)</code> function is ideal for that.</p>\n<pre><code>matches = sum(a == b for a, b in zip(correct, answer))\n</code></pre>\n<p>I believe that reduces your function to four statements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T01:52:16.763", "Id": "261562", "ParentId": "261561", "Score": "1" } } ]
<p>I had this <a href="https://codereview.stackexchange.com/questions/261387/python-trivia-game-getting-questions-and-answers-off-a-website" title="This Stackexchange post">trivia game</a>, and from the review I got I improved my game. One of the improvements I made was this short function, to check the correctness of an answer (so if the correct answer was &quot;Yellowstone park in Wyoming&quot;, &quot;Yellowstone park&quot; could be accepted. The code I have below works, but I would like it to be smarter, as the current code is simple. Any ideas? Thanks.</p> <pre><code>def check(answer, correct, percentage): matches = 0 if len(answer) &lt; len(correct): for x in range(len(answer)): if answer[x] == correct[x]: matches += 1 total = len(correct) else: for x in range(len(correct)): if answer[x] == correct[x]: matches += 1 total = len(answer) matches_percentage = (matches/total * 100) if matches_percentage &gt;= percentage: return True else: return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T22:15:26.353", "Id": "516167", "Score": "2", "body": "the requirements are not clear enough. e.g. will \"park in\" be a good answer in your example? is the order of the words important? e.g. will \"Wyoming Yellowstone\" have the same rank as \"Yellowstone Wyoming\"? define better requirements and then the implementation can be discussed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T04:15:06.707", "Id": "516174", "Score": "1", "body": "Take a look at [`difflib.SequenceMatcher`](https://docs.python.org/3.9/library/difflib.html#sequencematcher-examples) in the standard library. It has a `ratio()` method that returns a similarity score on a scale of 0.0 to 1.0." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-02T21:57:14.470", "Id": "261561", "Score": "0", "Tags": [ "beginner", "python-3.x" ], "Title": "Short function to check if an entered answer is close to a correct one" }
261561
max_votes
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code> if matches_percentage &gt;= percentage:\n return True\n else:\n return False\n</code></pre>\n<p>is a verbose way of writing</p>\n<pre class=\"lang-py prettyprint-override\"><code> return matches_percentage &gt;= percentage\n</code></pre>\n<p>In <code>matches_percentage = (matches/total * 100)</code>, the parentheses are unnecessary.</p>\n<p>You could compute <code>total</code> with just one <code>max(...)</code> expression:</p>\n<pre><code>total = max(len(correct), len(answer))\n</code></pre>\n<p>That just leaves comparing successive elements of <code>correct</code> and <code>answer</code> and counting matches until you run out of terms from one list or the other. The <code>zip(...)</code> function is ideal for that.</p>\n<pre><code>matches = sum(a == b for a, b in zip(correct, answer))\n</code></pre>\n<p>I believe that reduces your function to four statements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-03T01:52:16.763", "Id": "261562", "ParentId": "261561", "Score": "1" } } ]
<p>I created an algorithm for generating Latin Square. The algorithm uses the first n permutations (Not n!) orderings of a distinct row of numbers. This is then assigned to a 2d list.</p> <pre><code>import itertools def latin_square(rows, numbers): assert rows is not None, &quot;row is required to not be None&quot; assert rows &gt;= 0, &quot;row is required to be zero or more, including zero&quot; assert numbers is not None, &quot;numbers is required to not be None&quot; square = [[numbers[0] for row in range(rows)] for col in range(rows)] line = [] for row, line in enumerate(itertools.permutations(numbers, rows)): if row == rows: break for col in range(len(line)): square[row][col] = line[col] return square def test_latin_square(): assert latin_square(1, [1]) == [[1]] assert latin_square(2, [0, 1]) == [[0, 1], [1, 0]] assert latin_square(2, [-1, -2]) == [[-1, -2], [-2, -1]] assert latin_square(3, [3, 2, 1]) == [[3, 2, 1], [3, 1, 2], [2, 3, 1]] test_latin_square() </code></pre>
[]
{ "AcceptedAnswerId": "262637", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T15:24:53.687", "Id": "262630", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Generating a Latin Square" }
262630
accepted_answer
[ { "body": "<p><strong>Functionality</strong></p>\n<p>Your code is incorrect, as you can see in your fourth test case:</p>\n<pre><code>latin_square(3, [3, 2, 1]) == [[3, 2, 1],\n [3, 1, 2],\n [2, 3, 1]]\n</code></pre>\n<p>This is not a latin square, since there are two 3s in the first column and two 1s in the third column. This seems like you wrote the code first and then copied its output to the test cases. It should obviously be the other way round.</p>\n<p>The most straight-forward approach would probably be simply rotating the list of <code>numbers</code> by one in either direction to get each next row. You should of course make sure to only use distinct numbers from the provided input list <code>numbers</code>.</p>\n<hr />\n<p><strong>Other suggestions</strong></p>\n<p>These suggestions will improve the existing implementation, but will <strong>not</strong> fix the incorrect functionality.</p>\n<hr />\n<p><code>assert</code> statements should only be used for testing, as they will be ignored in optimized mode. More about optimized mode <a href=\"https://stackoverflow.com/a/5142453/9173379\">here</a>. Rather you should check these conditions with an <code>if</code>-statement and raise meaningful errors (instead of <code>AssertionErrors</code>). <code>ValueError</code> or <code>TypeError</code> should be the most fitting here (but you could implement your own custom exceptions). One example:</p>\n<pre><code>if len(set(numbers)) &lt; rows:\n raise ValueError(f&quot;Number of distinct numbers must be greater than or equal to {rows=}&quot;)\n</code></pre>\n<p>You also don't need to explicitly check for <code>rows is None</code> and <code>numbers is None</code>, as <code>None</code> values will lead to a <code>TypeError</code> anyway. Manually checking and providing a meaningful message to the user usually doesn't hurt though.</p>\n<hr />\n<p><code>square = [[numbers[0] for _ in range(rows)] for _ in range(rows)]</code></p>\n<p>It's a well-known convention to name variables you don't use <code>_</code>. That immediately makes it clear to the reader that it's not used and removes unnecessary information.</p>\n<hr />\n<p>You're doing too much manual work:</p>\n<ol>\n<li>You don't need to fill <code>square</code> with values only to replace them later</li>\n<li>You don't need to initialize <code>line</code> at all</li>\n<li>You shouldn't (most likely ever) do this:</li>\n</ol>\n<pre><code>for col in range(len(line)):\n square[row][col] = line[col]\n</code></pre>\n<p>All this snippet does is set the value of <code>square[row]</code> to <code>list(line)</code>:</p>\n<pre><code>square = []\n\nfor row, line in enumerate(itertools.permutations(numbers, rows)):\n if row == rows:\n break\n\n square.append(list(line))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T17:45:14.430", "Id": "518384", "Score": "0", "body": "Could I replace the code with just sifting without generating permutations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T18:21:36.337", "Id": "518393", "Score": "0", "body": "I presume you mean shifting. Shifting will of course produce certain permutations, but you don't need `itertools.permutations` for it. Simply take `rows` number of distinct numbers for the first row, then keep shifting them (left or right) by one to get the subsequent row. You're very welcome to come back here for further feedback once you've implemented that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T16:40:03.137", "Id": "262637", "ParentId": "262630", "Score": "5" } } ]
<p>I want to sort object list named schedules according to arrivalT. if arrivalT is equal, I want to sort according to burst, if arrivalT and bursT both equal I want to sort according to id. Is my custom comparitor implementaion correct?</p> <pre><code>from functools import cmp_to_key class Pair: def __init__(self, id, arrivalT, burstT): self.id = id self.arrivalT = arrivalT self.burstT = burstT def compare(p1, p2): if p1.arrivalT &lt; p2.arrivalT: return -1 elif p1.arrivalT &lt; p2.arrivalT: return 1 else: if p1.burstT &lt; p1.burstT: return -1 elif p1.burstT &gt; p2.burstT: return 1 else: if p1.id &lt; p2.id: return -1 elif p1.id &gt; p2.id: return 1 n = len(id) schedules = [] for i in range(n): schedules.append(Pair(id[i], arrival[i], burst[i])) schedules = sorted(schedules, key = cmp_to_key(compare)) for i in schedules: print(i.id, i.arrivalT, i.burstT) id =[1, 2, 3, 4] arrival = [2, 0, 4, 5] burst = [3, 4, 2, 4 ] shortestJobFirst(id, arrival, burst) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T20:04:41.593", "Id": "518572", "Score": "2", "body": "In terms of correctness insofar as correct results, you need to be at least somewhat confident that your implementation is correct before this is eligible for review. The purpose of review isn't to validate correctness, it's to talk about how well-structured the implementation is, standards adherence, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T07:16:59.363", "Id": "518593", "Score": "0", "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": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T20:01:31.923", "Id": "262732", "Score": "0", "Tags": [ "python" ], "Title": "Is my custom operator for sorting in python correct?" }
262732
max_votes
[ { "body": "<p>As suggested in another review, you could write a specific function to sort the\nobjects as you like in this one use case. Or you could package these objects up\nas <code>namedtuple</code> instances, and just sort them directly. But you might not want\nto convert to <code>nametuple</code> (maybe your class needs some other behaviors). In\nthat case, you have a few options.</p>\n<p>One is to use a <code>dataclass</code> and arrange the attributes in the order than you\nwant sorting to occur. This approach is similar to the <code>nametuple</code> strategy in\nthe sense that you must declare the attributes in the desired sorting-order.</p>\n<pre><code>from dataclasses import dataclass\n\n@dataclass(frozen = True, order = True)\nclass Job:\n arrivalT: int\n burstT: int\n id: int\n</code></pre>\n<p>Another option is to define the <code>__lt__()</code> method in the class, so that\nPython's built-in sorting functions can compare the objects directly.</p>\n<pre><code>@dataclass(frozen = True)\nclass Job:\n id: int\n arrivalT: int\n burstT: int\n\n def __lt__(self, other):\n return (\n (self.arrivalT, self.burstT, self.id) &lt;\n (other.arrivalT, other.burstT, other.id)\n )\n</code></pre>\n<p>Or if you need more flexibility at runtime, you could write a general purpose\nfunction to allow you to sort any objects based on any combination of\nattributes. This approach would make more sense in situations where you don't\nknow in advance how things should be sorted.</p>\n<pre><code>@dataclass(frozen = True)\nclass Job:\n id: int\n arrivalT: int\n burstT: int\n\ndef attrs_getter(*attributes):\n return lambda x: tuple(getattr(x, a) for a in attributes)\n\n# Usage example.\njobs = [Job(1, 4, 3), Job(2, 1, 4), Job(3, 4, 2), Job(4, 1, 4)]\njobs.sort(key = attrs_getter('arrivalT', 'burstT', 'id'))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T07:35:36.153", "Id": "518595", "Score": "0", "body": "Great answer! I particularly liked hooking into `__lt__`. I just want to mention that my first snippet works perfectly fine using a class as well. I just found it convinient in this case to switch to a named tuple =)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-06T23:52:18.783", "Id": "262737", "ParentId": "262732", "Score": "3" } } ]
<p>I was looking into Python 3.10's <a href="https://www.python.org/dev/peps/pep-0622/" rel="nofollow noreferrer">Structural Pattern Matching</a> syntax, and I want to refactor one of my code that uses <code>if-else</code>, using structural pattern matching. My code works, but I'm trying to find out if there's a better way to deal with a particular section.</p> <p>Let's consider this simple example problem, let's say I have the following list:</p> <pre><code>data = [ # index [1, 2, 5, 3, 4], # 0 [7, 5, 8, 4, 9], # 1 [2, 3, 4, 4, 5], # 2 [1, 3, 1, 6, 7], # 3 [5, 6, 0, 7, 8], # 4 [4, 3, 0, 7, 5], # 5 [4, 4, 4, 5, 4], # 6 [5, 2, 9, 3, 5], # 7 ] </code></pre> <p>What I want to do is:</p> <pre><code>IF: (there is a `4` *or* `5` at the *beginning*) prepend an `'l'`. ELIF: (there is a `4` *or* `5` at the *end*) prepend a `'r'`. ELIF: (there is a `4` *or* `5` at *both ends* of the list) IF: (Both are equal) prepend a `'b2'`, ELSE: prepend `'b1'` ELSE: IF : (There are at least **two** occurrences of `4` *and/or* `5`) prepend `'t'` ELSE: prepend `'x'` </code></pre> <p>Each inner_list may contain <strong>arbitrary amount of elements</strong>.</p> <h3>Expected Result</h3> <pre><code>index append_left 0 'r' 1 't' 2 'r' 3 'x' 4 'l' 5 'b1' 6 'b2' 7 'b2' </code></pre> <p>Now, I can do this using structural pattern matching, with the following code:</p> <pre><code>for i, inner_list in enumerate(data): match inner_list: case [(4 | 5) as left, *middle, (4 | 5) as right]: data[i].insert(0, ('b1', 'b2')[left == right]) case [(4 | 5), *rest]: data[i].insert(0, 'l') case [*rest, (4 | 5)]: data[i].insert(0, 'r') case [_, *middle, _] if (middle.count(4) + middle.count(5)) &gt;= 2: ## This part ## data[i].insert(0, 't') case _: data[i].insert(0, 'x') pprint(data) </code></pre> <h3>Output</h3> <pre><code>[['r', 1, 2, 5, 3, 4], ['t', 7, 5, 8, 4, 9], ['r', 2, 3, 4, 4, 5], ['x', 1, 3, 1, 6, 7], ['l', 5, 6, 0, 7, 8], ['b1', 4, 3, 0, 7, 5], ['b2', 4, 4, 4, 5, 4], ['b2', 5, 2, 9, 3, 5]] </code></pre> <p>The problem is the <code>##</code> marked block above. Of course I can move that part inside the block, and check there, but I was wondering whether the <code>if</code> part can be avoided altogether, i.e. some pattern that would match at least two <code>4</code> and/or <code>5</code>s.</p> <hr /> <p><strong>EDIT</strong> The <code>[_, *middle, _]</code> part is actually me being suggestive that I am looking for a pattern to match the scenario, I'm aware, in actuality this could be done like: <code>case _ if sum(i in (4, 5) for i in inner_list) &gt;= 2</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:44:57.200", "Id": "518699", "Score": "1", "body": "The reason why I mentioned the syntax `[(4 | 5), *rest]` is unfortunate is because it _slices_ the list which can be an expensive operation. Now, for every case you are performing a seperate slice. `[(4 | 5), *rest]` slices, `[_, *middle, _]` slices etc. The syntax in itself is clear, but not efficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:49:26.327", "Id": "518700", "Score": "0", "body": "Yes, I concur, I just added the edit for `[_, *middle, _]`, which is unnecessary in every sense. At least the `*rest` part would be useful if I needed to use the `rest` (which I don't at the moment)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T23:32:30.637", "Id": "518908", "Score": "0", "body": "The implementation for `[(4|5), *rest]` isn't necessarily inefficient. There can only be one starred field, so the implementation could try to match the other parts of the pattern first. If the other parts succeed, the `*rest` matches whatever is left over--it always succeeds. So the actual slicing only has to occurs for a successful match. If you use `*_` instead of `*rest` the slicing isn't needed at all. Patterns like this, that match the beginning and/or end of a sequence, would be rather common and would be a good optimization target for the interpreter developers." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T15:47:55.480", "Id": "262769", "Score": "3", "Tags": [ "python", "pattern-matching" ], "Title": "Structural Pattern Matching syntax to match a value in a list" }
262769
max_votes
[ { "body": "<p>Like you, I am excited about Python's new pattern matching. Unfortunately,\nI don't think your use case is a good fit. Every tool has strengths\nand weaknesses. In this specific situation, ordinary <code>if-else</code> logic\nseems easier to write, read, and understand. For example:</p>\n<pre><code>def get_prefix(xs):\n lft = xs[0]\n rgt = xs[-1]\n T45 = (4, 5)\n if lft in T45 and rgt in T45:\n return 'b2' if lft == rgt else 'b1'\n elif lft in T45:\n return 'l'\n elif rgt in T45:\n return 'r'\n elif sum(x in T45 for x in xs) &gt; 1:\n return 't'\n else:\n return 'x'\n\nnew_rows = [[get_prefix(row)] + row for row in data]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:40:45.160", "Id": "518690", "Score": "0", "body": "I kind of agree. And this is how my code was originally written, but thought I'd give the new thing a go, to see if I can use it to replace if else completely. btw isn't adding two lists O(n) as opposed to `insert` which is O(1)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:50:06.587", "Id": "518693", "Score": "0", "body": "I am mistaken, insert is indeed O(n), I conflated with deque.appendleft" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:56:17.300", "Id": "518694", "Score": "1", "body": "@Cyttorak Sadly, I mostly ignored your specific question (ie, is it *possible*). I don't know for certain. But if it's possible, it's likely to be even more elaborate than the current code you have. Regarding insert, your second comment is right. That said, if you care about speed, measure it for your specific case. These things can have counter-intuitive results, because some Python operations occur at C-speed, others at Python-speed. I wrote my example code that way mostly out of habit: functions should not mutate without good reason. But your use case might want to mutate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T18:20:23.090", "Id": "518695", "Score": "0", "body": "Yes, mutation would be fine here. About the potential solution being more elaborate, I was looking for something like this: in order to match key `b` in a dictionary `d = {'a': 'foo', 'b': 'bar', 'c': 'baz'}` it is sufficient to do `case {'b': 'bar', **rest}:`. Of course, it is easy for dicts as the keys are unique, and was historically thought of as unordered. But I was just checking if there were some new ways introduced in the new syntax that would make matching middle elements possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T07:02:35.913", "Id": "518746", "Score": "0", "body": "why not make the variable left and right instead of lft and rgt" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:36:40.590", "Id": "518774", "Score": "0", "body": "@hjpotter92 Shorter names are beneficial in a variety of ways (easier to type, read, and visually scan), but they do come at a cost (can be less clear). *In this specific context*, my judgment was that the short names are perfectly clear, and the vars were going to be used repeatedly, increasing the benefit of brevity. Basically, it was a cost-benefit decision -- like many other decisions when writing software." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-07T17:34:31.170", "Id": "262773", "ParentId": "262769", "Score": "4" } } ]
<h2>What it does</h2> <p>Calculates the mean difference for a list of any combination of ints (I think).</p> <h2>What I want to know</h2> <p>The only other way I can think of doing this is using recursion.</p> <p>I’d like to know if there are other better ways to do this.</p> <p>Also the reason I done this is because I wanted to calculate the mean difference between time stamps I have in another script, so used this as an exercise, that one will be more difficult since it’s 24 hr time, when it gets to the part of switching from:</p> <p><code>12:00 -&gt; 00:00</code></p> <h3>Code:</h3> <pre class="lang-py prettyprint-override"><code>nums = [3, 1, 2, 5, 1, 5, -7, 9, -8, -3, 3] l = len(nums) - 1 diff_list = [] for i in range(l): diff = nums[0] - nums[1] if diff &lt; 0: diff = nums[1] - nums[0] diff_list.append(diff) nums.pop(0) mean = sum(diff_list)/len(diff_list) print(round(mean, 1)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T08:59:52.423", "Id": "518756", "Score": "0", "body": "I would advice you against using list comprehensions for timestamps. Time can be a tricky thing to deal with, timezones, leap years, leap seconds. Etc. Again a [quick google search](https://stackoverflow.com/questions/36481189/python-finding-difference-between-two-time-stamps-in-minutes), should head you in the direction of always using [`datetime`](https://docs.python.org/3/library/datetime.html) when dealing with time. Feel free to post a follow up question if you want further comments on your particular implementation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T10:51:50.070", "Id": "518762", "Score": "0", "body": "Thank you, I think I will once I get going with it, you’ve been very helpful thanks :)" } ]
{ "AcceptedAnswerId": "262788", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T06:06:03.417", "Id": "262786", "Score": "4", "Tags": [ "python-3.x", "mathematics" ], "Title": "Mean difference calculator for any int combination" }
262786
accepted_answer
[ { "body": "<h3><a href=\"https://en.wikipedia.org/wiki/Reinventing_the_wheel\" rel=\"nofollow noreferrer\">Reinventing the wheel</a></h3>\n<p>Now I will try not to sound too harsh, but did you attempt to google the problem at hand before starting? Building habits in programming is important, but it is equally important to building upon existing code. A quck search gives me the following useful links <a href=\"https://stackoverflow.com/questions/63588328/minimum-absolute-difference-between-elements-in-two-numpy-arrays\">here</a>, <a href=\"https://stackoverflow.com/questions/2400840/python-finding-differences-between-elements-of-a-list\">here</a> and <a href=\"https://stackoverflow.com/questions/29745593/finding-differences-between-all-values-in-an-list\">here</a>.</p>\n<h3>General comments</h3>\n<pre><code>l = len(nums) - 1\n</code></pre>\n<p>This needs a better name. A good rule of thumb is to avoid <a href=\"https://medium.com/pragmatic-programmers/avoid-single-letter-names-11c621cbd188\" rel=\"nofollow noreferrer\">single letter variables</a>. Secondly this variable is only used once, and thus is not needed. As you could have done</p>\n<pre><code>for i in range(len(nums)-1):\n</code></pre>\n<p>which is just as clear. As mentioned the next part could be shortened to</p>\n<pre><code>diff = abs(nums[0] - nums[1])\n</code></pre>\n<p>Perhaps the biggest woopsie in your code is <code>nums.pop(0)</code> for two reasons</p>\n<ol>\n<li>It modifies your original list. Assume you have calculated and the mean differences, but now want to access the first element in your list: <code>nums[0]</code> what happens?</li>\n<li>Secondly <code>pop</code> is an expensive operation, as it shifts the indices for every element in the list for every pop.</li>\n</ol>\n<p>Luckily we are iterating over the indices so we can use them to avoid poping. Combining we get</p>\n<pre><code>for i in range(len(nums) - 1):\n diff = abs(nums[i-1] - nums[i])\n diff_list.append(diff)\n</code></pre>\n<p>However, this can be written in a single line if wanted as other answers have shown. <code>zip</code> is another solution for a simple oneliner, albeit it should be slightly slower due to slicing. I do not know how important performance is to you, so zip might be fine</p>\n<pre><code>[abs(j - i) for i, j in zip(nums, nums[1:])]\n</code></pre>\n<p>If speed is important it could be worth checking out <code>numpy</code></p>\n<h3>Improvements</h3>\n<p>Combining everything, adding hints and struct and a numpy version we get</p>\n<pre><code>import numpy as np\nfrom typing import List\n\n\ndef element_difference_1(nums: List[int]) -&gt; List[int]:\n return [abs(j - i) for i, j in zip(nums, nums[1:])]\n\n\ndef element_difference_2(nums: List[int]) -&gt; List[int]:\n return [abs(nums[i + 1] - nums[i]) for i in range(len(nums) - 1)]\n\n\ndef mean_value(lst: List[int]) -&gt; float:\n return sum(lst) / len(lst)\n\n\ndef mean_difference(nums: List[int], diff_function, rounding: int = 1) -&gt; None:\n num_diffs = diff_function(nums)\n mean = mean_value(num_diffs)\n return round(mean, rounding)\n\n\ndef mean_difference_np(lst) -&gt; float:\n return np.mean(np.abs(np.diff(lst)))\n\n\nif __name__ == &quot;__main__&quot;:\n nums = [3, 1, 2, 5, 1, 5, -7, 9, -8, -3, 3]\n print(mean_difference(nums, element_difference_1))\n print(mean_difference(nums, element_difference_2))\n print(mean_difference_np(np.array(nums)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T08:25:06.330", "Id": "518754", "Score": "0", "body": "Thank you, I wanted this to be list comprehensions (got a bunch from you) as I’m getting bored of for loops I like your approach, they should’ve just made python a strictly typed language I’m seeing everyone importing from typing these days. I didn’t google it heh heh I was just practicing in preparation for finding the difference between my timestamp script, didn’t know pop was expensive thanks for the heads up, the list is disposable, that’s why I wasn’t worried about messing it up :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T09:02:03.147", "Id": "518757", "Score": "0", "body": "Thanks for going through all that with me I’ll keep this and learn from it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T07:20:45.500", "Id": "262788", "ParentId": "262786", "Score": "4" } } ]
<p>I was looking at a dataset with a <code>year</code> column. I wanted all the years with matching a particular event. I then get a list of years which is not easy to read:</p> <pre><code>2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020 </code></pre> <p>It would be much better to display them as:</p> <pre><code>2010-2013, 2015, 2017-2020 </code></pre> <p>I was looking for a builtin function in Python, but eventually, I wrote this:</p> <pre><code>import numpy as np def ranges(array): start = None for i, k in zip(np.diff(array, append=[array[-1]]), array): if i == 1: if start is None: start = k continue yield(k if start is None else (start, k)) start = None </code></pre> <p>Is there a more pythonic way that does the same with less?</p> <p>At the end I could do this:</p> <pre><code>years = [2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020] ', '.join([f'{x[0]}-{x[1]}' if isinstance(x, tuple) else str(x) for x in ranges(years)]) </code></pre>
[]
{ "AcceptedAnswerId": "262801", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T13:32:50.247", "Id": "262797", "Score": "5", "Tags": [ "python", "algorithm" ], "Title": "Find all subranges of consecutive values in an array" }
262797
accepted_answer
[ { "body": "<p>I'm glad you asked this question, as I've had a difficult time finding the solution recently as well. However, I have now found that the solution is to use the <code>more_itertools</code> <a href=\"https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consecutive_groups\" rel=\"nofollow noreferrer\">consecutive_groups</a> function:</p>\n<pre><code>from more_itertools import consecutive_groups\nx = [2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019, 2020]\n\n# create an intermediate list to avoid having unnecessary list calls in the next line\nsubsets = [list(group) for group in consecutive_groups(x)]\n\nresult = [f&quot;{years[0]}-{years[-1]}&quot; if len(years) &gt; 1 else f&quot;{years[0]}&quot; for years in subsets]\n# ['2010-2013', '2015', '2017-2020']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T14:33:14.837", "Id": "262801", "ParentId": "262797", "Score": "5" } } ]
<p>Sorted List value using algorithm <strong>selection sort</strong>. Can you please review and let me know where I can improve.</p> <pre><code>months = {&quot;January&quot;: 1, &quot;February&quot;: 2, &quot;March&quot;: 3, &quot;April&quot;: 4, &quot;May&quot;: 5, &quot;June&quot;: 6, &quot;July&quot;: 7, &quot;August&quot;: 8, &quot;September&quot;: 9, &quot;October&quot;: 10, &quot;November&quot;: 11, &quot;December&quot;: 12} L = [&quot;March&quot;, &quot;January&quot;, &quot;December&quot;] #creating list L1 L1 = [months[L[i]] for i in range(len(L))] print(L1) #sorting list using algorithm selection sort for i in range(1,len(L1)): j = 0 if L1[j] &gt; L1[i] : L1[j], L1[i] = L1[i] ,L1[j] print(L1) #Replacing values with key sorted_list = [ k for k,v in months.items() if v in L1] print(sorted_list) </code></pre>
[]
{ "AcceptedAnswerId": "262815", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T17:32:28.540", "Id": "262812", "Score": "0", "Tags": [ "python", "reinventing-the-wheel" ], "Title": "sorting list using selection sort algorithm" }
262812
accepted_answer
[ { "body": "<p>Put your code in functions. Maybe this is pedantic, but it's not really an\n<em>algorithm</em> if you cannot reuse it. If the logic is floating around with\nvarious setup and printing code, it's not reusable in any convenient sense.</p>\n<p>Your demo code isn't doing what you think it's doing. Comment out the sorting\ncode, and the printed result is the same: the month names in proper order. Why?\nBecause <code>sorted_list</code> is being driven by the ordering of the <code>months</code> dict, not\nthe we-hope-its-sorted <code>L1</code>. As an experiment, move January to the end of that\ndict, and watch what happens.</p>\n<pre><code># The order of sorted_list is not affected by whether L1 is sorted.\nsorted_list = [k for k, v in months.items() if v in L1]\n</code></pre>\n<p>Even if it were fixed, your demo code is not well-suited to the problem at hand\n-- checking whether your sort algorithm is correct. Instead, your demo code is\ngood for addressing a different question: how to sort dict keys based on dict\nvalues. Here's one way:</p>\n<pre><code># Sorting dict keys based on dict values -- a different question.\nsorted_names = sorted(months, key = lambda name: months[name])\n</code></pre>\n<p>A better way to test your sorting algorithm is to shuffle the values, sort them\nwith your algorithm, and check your sorted list against what the Python\n<code>sort()</code> function gives us. It's easy to write and a good way to check many\nmore cases than anything you could manually type. Here's one illustration of\nhow you might check it. You could easily wrap a loop around this kind of\ntesting to include a wider range of list sizes (including edge cases like <code>vals = []</code> or <code>vals = [1]</code>).</p>\n<pre><code>from random import shuffle\n\ndef main():\n # Some data that needs sorting.\n vals = list(range(1, 13))\n shuffle(vals)\n\n # Sort both ways and compare.\n expected = sorted(vals)\n selection_sort(vals)\n if vals != expected:\n print('GOT', vals)\n print('EXP', expected)\n\ndef selection_sort(L1):\n # L1 is a non-standard Python variable name. In a general sorting\n # function, where you have no idea what the values represent,\n # an idiomatic name would be xs (one x, many xs).\n for i in range(1,len(L1)):\n j = 0\n if L1[j] &gt; L1[i] :\n L1[j], L1[i] = L1[i] ,L1[j]\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Your sorting algorithm isn't working. Here's output from one run:</p>\n<pre><code>GOT [1, 7, 8, 4, 12, 10, 2, 11, 6, 5, 9, 3]\nEXP [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n</code></pre>\n<p>If you add these suggestions to your code, and do some debugging work, I'm sure\nyou'll figure out a correct implementation. For example, you are not finding\nthe index of the minimum value in the rest of the list -- a key concept in\nWikpedia's description of <a href=\"https://en.wikipedia.org/wiki/Selection_sort\" rel=\"nofollow noreferrer\">selection\nsort</a>. Come back for another code\nreview after you have another draft.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T20:34:33.070", "Id": "518796", "Score": "0", "body": "Thank you for explanation. I could figure out where I was going wrong. I have posted code below. Please review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T21:36:51.763", "Id": "518797", "Score": "2", "body": "@ch2019 You are very welcome and your new implementation is much closer. But take a look at that Wikipedia page -- especially the animation and the corresponding pseudo-code. Each pass over the list checks only the **rest of the list** (the growing yellow portion in the animation). Your new code is checking the entire list with each pass, so you're doing too much work. Also, I don't know all of the rules around here, but I suspect the policy is to post subsequent drafts for review as brand new questions rather than as alternative answers (that's just a guess on my part)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T22:00:16.733", "Id": "518798", "Score": "0", "body": "@ch2019 Also, your new code is still missing the essence of selection sort: **finding the minimum value** in the rest of the list." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-08T18:24:11.557", "Id": "262815", "ParentId": "262812", "Score": "4" } } ]
<p>For academic purposes I want to reinvent Blue Green Red to Grayscale function in Python. I am new to Python so I believe my code below can still be optimized.</p> <pre><code>import cv2 import numpy as np data = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]], [ [0, 0, 0], [128, 128, 128], [255, 255, 255], ]], dtype=np.uint8) rows = len(data) cols = len(data[0]) grayed = [] for i in range(rows): row = [] for j in range(cols): blue, green, red = data[i, j] gray = int(0.114 * blue + 0.587 * green + 0.299 * red) row.append(gray) grayed.append(row) grayed = np.array(grayed, dtype=np.uint8) print(data) print(grayed) wndData = &quot;data&quot; wndGrayed = &quot;greyed&quot; cv2.namedWindow(wndData, cv2.WINDOW_NORMAL) cv2.imshow(wndData, data) cv2.namedWindow(wndGrayed, cv2.WINDOW_NORMAL) cv2.imshow(wndGrayed, grayed) cv2.waitKey() </code></pre> <p>Could you review my code above and make it much better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T10:39:58.230", "Id": "518836", "Score": "0", "body": "How is `0.114 * blue + 0.587 * green + 0.299 * red` grey? I would expect grey to be `blue/3 + green/3 + red/3`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T14:08:36.963", "Id": "518849", "Score": "0", "body": "@Reinderien: There are many algorithms to convert one color space to others." } ]
{ "AcceptedAnswerId": "262842", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T07:45:20.747", "Id": "262835", "Score": "3", "Tags": [ "python", "opencv" ], "Title": "Reinventing BGR to Grayscale OpenCV convert function in Python" }
262835
accepted_answer
[ { "body": "<p>It appears that you are calculating linear combinations. If you are already using <code>numpy</code>, then the same can be achieved by broadcasting the dot product (with <code>@</code>):</p>\n<pre><code>import numpy as np\n\ndata = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]], \n [[0, 0, 0], [128, 128, 128], [255, 255, 255]]], dtype=np.uint8)\n\ncoefficients = np.array([0.114,0.587, 0.299])\n\ngreyed = (data @ coefficients).astype(np.uint8)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T15:22:52.273", "Id": "518862", "Score": "0", "body": "Just another note that `grayed = np.round(data @ coefficients).astype(np.uint8)` will make the result identical to one produced by `cv2.cvtColor` function. Kevin from Phyton chat room found this solution. :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T10:50:03.347", "Id": "262842", "ParentId": "262835", "Score": "5" } } ]
<p>First of all, I am playing around with python for about a week tops. Absolute beginner here.</p> <p>My story: I work as an IT administrator so I am familiar with eg. PS on a very basic level. I actually got into python due to the fact that I am plotting/farming chia. Now a rather long holiday is coming up, so I thought to myself I might as well write a discord bot with a couple of commands that would allow me to monitor pc resourcer, perhaps initiate PC restarts and etc....</p> <p>Now I got a couple of functions done including the one I want to ask about, this script is giving back the number of files on the specified locations with the extension .plot.</p> <p>First of all, this script is doing what I want it to do. However! Its very static, meaning I actually set locations in variables, which is good for now, but in the perfect scenario it would certinaly not list files with .plot extension should they be in any other location.</p> <p>My second concern is that even though I have used functions to connect to my samba server (which is running on a PI4) I have a feeling this part of the code is not being used. And as long as I previously autechnicated against the IP shares on windows my script would work with the &quot;cached&quot; credentials.</p> <p>All in all here is my code, it is probably a HUGE mess, but! could you please provide some insight on specific parts of the code to make it better, &quot;more professional&quot; so to say.</p> <pre><code>#!/usr/local/bin/python3 import os from smb.SMBConnection import SMBConnection host=&quot;xxx.xxx.xxx.xxx&quot; #ip or domain name to SMB server username=&quot;***&quot; #SAMBA server username password=&quot;xxxxx&quot; #SAMBA server password sharename=&quot;\\\\xxx.xxx.xxx.xxx\\chia1&quot; sharename2=&quot;\\\\xxx.xxx.xxx.xxx\\chia2&quot; sharename3=&quot;I:&quot; conn=SMBConnection(username,password,&quot;&quot;,&quot;&quot;,use_ntlm_v2 = True) result = conn.connect(host, 445) for root, dirs, files in os.walk(sharename): for Files in files: if Files.endswith(&quot;.plot&quot;): totalfiles += 1 for root, dirs, files in os.walk(sharename2): for Files in files: if Files.endswith(&quot;.plot&quot;): totalfiles += 1 for root, dirs, files in os.walk(sharename3): for Files in files: if Files.endswith(&quot;.plot&quot;): totalfiles += 1 result = &quot;:page_facing_up: Total number of plots: &quot; printoutput = ('{}{}'.format(result, totalfiles)) print('{}{}'.format(result, totalfiles)) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T22:57:08.747", "Id": "262868", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "file-system" ], "Title": "Count *.plot files in certain directories on network filesystems" }
262868
max_votes
[ { "body": "<p>It's generally a very bad idea to put credentials in a program. That's\na bigger topic, and the best approach will vary depending on your situation.\nBut you should address this problem.</p>\n<p>When naming things, let ordinary English usage guide you: plural for\ncollections (lists, tuples, dicts, etc) and singular for individual values. For\nexample, use <code>files</code> and <code>file</code> (or even just <code>f</code> if the context is clear), not\n<code>files</code> and <code>Files</code>.</p>\n<p>Let your code breathe by putting spaces around operators and related items\n(equal signs, commas, etc). It helps with readability and often editability\n(latter can depend on the editor). Search for PEP8 if you want more details on\nrecommended naming and layout practices (PEP8 is not gospel, but it is a good\nstarting point).</p>\n<p>It's often a good idea to group similar data into collections: for example,\na tuple/list/dict of <code>shares</code> rather than <code>sharename</code>, <code>sharename2</code>, <code>sharename3</code>.</p>\n<p>When you see repetition in your code, get rid of it. It's as simple as that.\nUsually, you can do this by writing a function to generalize the behavior: for\nexample, a function taking a <code>share</code> and returning a count. In your specific\ncase, the grouping of the shares in a collection provides a more direct route:\nkill the repetition via a loop over that collection. And since the logic inside\nthe loop is just counting, you can stick the whole thing in a single <code>sum()</code>\nexpression (this works because <code>bool</code> is a subclass of <code>int</code>).</p>\n<pre><code>shares = (\n &quot;\\\\\\\\xxx.xxx.xxx.xxx\\\\chia1&quot;,\n &quot;\\\\\\\\xxx.xxx.xxx.xxx\\\\chia2&quot;,\n &quot;I:&quot;,\n)\n\next = '.plot'\n\ntotalfiles = sum(\n f.endswith(ext)\n for share in shares\n for _, _, files in os.walk(share)\n for f in files\n)\n</code></pre>\n<p>You asked about making the script less hardcoded. The most natural\nway to do that is via command-line arguments and the <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a> module.\nThat's a bigger topic, but the basic idea is that the share paths and the extension\n(<code>.plot</code>) should be variable parameters with default values. Run the script\nwithout arguments, and it will do the default thing. Run it with arguments\nand/or options, and it will use different parameters. That's the time-tested\nway to go with scripts like this, and the internet is full of examples\nillustrating how to set up <code>argparse</code>.</p>\n<p>Finally, if you intend to write more scripts as you build\nyour <strong>Chia Empire</strong>,\njust adopt the practice of putting all code inside of functions.\nIt might seem like an unnecessary hassle at first, but this\nis another one of those time-tested ideas. The benefits are\nnumerous. Here's the basic structure:</p>\n<pre><code>import sys\n\ndef main(args):\n # Program starts here.\n print(args)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T19:55:26.110", "Id": "519037", "Score": "0", "body": "Thank you! I managed to edit my code according to your inputs! Looks much better and feels more smooth." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-09T23:37:16.477", "Id": "262869", "ParentId": "262868", "Score": "5" } } ]
<p>I am dealing with a string <code>draw_result</code> that can be in one of the following formats:</p> <pre><code>&quot;03-23-27-34-37, Mega Ball: 13&quot; &quot;01-12 + 08-20&quot; &quot;04-15-17-25-41&quot; </code></pre> <p>I always start with <code>draw_result</code> where the value is one from the above values. I want to get to:</p> <pre><code>[3, 23, 27, 34, 37] [1, 12, 8, 20] [4, 15, 17, 25, 41] </code></pre> <p>I have created <a href="https://www.mycompiler.io/view/IQJ8ZGS" rel="nofollow noreferrer">this fiddle</a> to show the code working.</p> <p><strong>CODE</strong></p> <pre><code>draw_result = &quot;04-15-17-25-41&quot; # change to &quot;01-12 + 08-20&quot; or &quot;04-15-17-25-41&quot; or &quot;03-23-27-34-37, Mega Ball: 13&quot; to test def convert_to_int_array(draw_result): results_as_array = None if ',' in draw_result: target = draw_result.split(',', 1)[0] results_as_array = target.split('-') elif '+' in draw_result: target = draw_result.split('+') temp = &quot;-&quot;.join(target) results_as_array = temp.split('-') else: results_as_array = draw_result.split('-') for index in range(0, len(results_as_array)): results_as_array[index] = int(results_as_array[index].strip()) return results_as_array result_from_function = convert_to_int_array(draw_result) print(result_from_function) </code></pre> <p>The code works, but I want to know if what I've done is good or bad? Can it be done better in terms of readability &amp; fewer lines of code?</p> <p>I do not want to sacrifice readability/n00b friendliness for fewer lines of code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T23:28:46.263", "Id": "519055", "Score": "2", "body": "Just to understand the setup here: why is the `13` excluded in the first example?" } ]
{ "AcceptedAnswerId": "262934", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T11:41:06.510", "Id": "262933", "Score": "3", "Tags": [ "python" ], "Title": "Converting a string to an array of integers" }
262933
accepted_answer
[ { "body": "<p>Nice solution, a few suggestions:</p>\n<ul>\n<li>The function name <code>convert_to_int_array</code> seems too general. Consider a more specific name, for example, <code>extract_numbers</code>, or something similar.</li>\n<li>There is no need to initialize <code>results_as_array</code> to <code>None</code>.</li>\n<li>Mapping a list of strings to integers:\n<pre><code>for index in range(0, len(results_as_array)):\n results_as_array[index] = int(results_as_array[index].strip())\nreturn results_as_array\n</code></pre>\nlooks like the job for <code>map</code>:\n<pre><code>return list(map(int, results_as_array))\n</code></pre>\nSince the result of <code>map</code> is a generator, it needs to be converted to a list with <code>list</code>.</li>\n<li><strong>Tests</strong>: I noticed this line:\n<pre><code>draw_result = &quot;04-15-17-25-41&quot; # change to &quot;01-12 + 08-20&quot; or &quot;04-15-17-25-41&quot; or &quot;03-23-27-34-37, Mega Ball: 13&quot; to test\n</code></pre>\ntesting by changing <code>draw_result</code> manually it is time-consuming. A better way would be to keep the tests in a dictionary and to use <code>assert</code>. For example:\n<pre class=\"lang-py prettyprint-override\"><code>tests = {\n &quot;04-15-17-25-41&quot;: [4, 15, 17, 25, 41],\n &quot;01-12 + 08-20&quot;: [1, 12, 8, 20],\n &quot;03-23-27-34-37, Mega Ball: 13&quot;: [3, 23, 27, 34, 37]\n}\n\nfor lottery_string, expected_output in tests.items():\n assert expected_output == convert_to_int_array(lottery_string)\n</code></pre>\nIf you want to explore more &quot;unit testing&quot; have a look at <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\">unittest</a>.</li>\n</ul>\n<hr />\n<p>Alternative approach:</p>\n<ol>\n<li>Remove <code>, Mega Ball: 13</code> if exists</li>\n<li>Extract all numbers with a regular expression</li>\n</ol>\n<pre><code>import re\n\ndef extract_numbers(draw_result):\n draw_result = draw_result.split(',')[0]\n matches = re.findall(r'\\d+', draw_result)\n return list(map(int, matches))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T12:30:53.467", "Id": "518994", "Score": "1", "body": "Excellent suggestions, thank you very much. I'll skip the `regex` approach since it isn't n00b friendly. Well, I've been coding a while (not in python mind you) and regex is still magic to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T16:08:02.540", "Id": "519005", "Score": "4", "body": "I'd offer that the regex here is extremely legible, and if it doesn't meet the criterion of being newbie-friendly, it's a great opportunity for the newbie to level up. This is about as simple as regexes get." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-12T06:23:54.563", "Id": "519067", "Score": "0", "body": "@J86 thanks, I am glad I could help. FYI, I added a section about testing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-11T12:26:35.543", "Id": "262934", "ParentId": "262933", "Score": "4" } } ]
<p>First of all, I chose the nearest data points/training examples</p> <pre><code>import numpy as np import copy nearest_setosa = np.array([[1.9, 0.4],[1.7, 0.5]]) nearest_versicolour = np.array([[3. , 1.1]]) </code></pre> <p>and then I labeled negative examples as -1, and kept the label for the positive example.</p> <pre><code>x_train = np.concatenate((nearest_setosa, nearest_versicolour), axis=0) y_train = [-1, -1, 1] </code></pre> <p>This is a simplified version of sign function.</p> <pre><code>def predict(x): if np.dot(model_w, x) + model_b &gt;= 0: return 1 else: return -1 </code></pre> <p>I decided to update the weights once the model makes a wrong prediction.</p> <pre><code>def update_weights(idx, verbose=False): global model_w, model_b, eta model_w += eta * y_train[idx] * x_train[idx] model_b += eta * y_train[idx] if verbose: print(model_b) print(model_w) </code></pre> <p>The following code tests a bunch of learning rates(eta) and initial weights to find one which have the model converge with the minimal iteration.</p> <pre><code>eta_weights = [] for w in np.arange(-1.0, 1.0, .1): for eta in np.arange(.1, 2.0, .1): model_w = np.asarray([w, w]) model_b = 0.0 init_w = copy.deepcopy(w) for j in range(99): indicator = 0 for i in range(3): if y_train[i] != predict(x_train[i]): update_weights(i) else: indicator+=1 if indicator&gt;=3: break eta_weights.append([j, eta, init_w, model_w, model_b]) </code></pre> <p>I'm not sure if some classic search algorithms, e.g. binary search, are applicable to this particular case.</p> <p>Is it common to loop so many layers? Is there a better way to do the job?</p>
[]
{ "AcceptedAnswerId": "263151", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T14:46:47.610", "Id": "263027", "Score": "2", "Tags": [ "python", "algorithm", "machine-learning" ], "Title": "a prototype of finding the (almost) best learning rate and initial weights so that a perceptron converges with the minimal iteration" }
263027
accepted_answer
[ { "body": "<h2>There are certainly things you could improve</h2>\n<p>This use of global is quite confusing: you are using eta, model_w and model_b as a local variables to the <code>for eta in np.arange(.1, 2.0, .1)</code>, not as a global state. A cleaner way to do that would be to pass them as parameters to update_weights.</p>\n<hr />\n<p>The way j is used outside of the loop is not very clear (even if it should work as intended). What I suggest is to use another variable for that (why not calling it n_iter?). It would look like:</p>\n<pre><code> n_iter = 99\n for j in range(n_iter):\n indicator = 0\n ...\n if indicator&gt;=3:\n n_iter = j\n break\n eta_weights.append([n_iter, eta, init_w, model_w, model_b])\n</code></pre>\n<p>As a bonus now you can tell if your loop broke because of the last point (n_iter=98) or if it ran until the end (n_iter=99)</p>\n<hr />\n<p>Why are you using a copy, let even a deepcopy, here? w is only a number (non-mutable), so you can simply do: <code>init_w = w</code></p>\n<hr />\n<p>Layers of loop are not an issue as long as the code stays readable. Here I'd say it is ok. If you still want to shorten it you can use itertools.product:</p>\n<pre><code>import itertools\nfor w, eta in itertools.product(np.arange(-1.0, 1.0, .1), np.arange(.1, 2.0, .1)):\n print(f&quot;w={w}, eta={eta}&quot;)\n</code></pre>\n<hr />\n<p>I am not sure where you want to use search algorithms. Yes, in the worst case you have to loop 300 times but there is no easy fix here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T23:11:34.777", "Id": "519548", "Score": "0", "body": "Thank you so much. Your suggestion is quite helpful! `j` in the loop is to find the value for the actual number of iterations to reach the stopping criterion, something like the `n_iter_` attribute in [sklearn.linear_model.Perceptron](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Perceptron.html). any more comments on it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T11:20:09.407", "Id": "519570", "Score": "0", "body": "@AlbertJ I see!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T15:33:50.357", "Id": "263151", "ParentId": "263027", "Score": "3" } } ]
<h2>What it does</h2> <ul> <li>Converts melting point and boiling point from degrees celsius to kelvin</li> <li>These are in a dict which is in a tuple as no changes should be made to it</li> <li>No user input</li> </ul> <h2>Purpose</h2> <p>Learning exercise to understand classes and OOP</p> <h2>What I need help with</h2> <ul> <li>Is this how you do classes?</li> <li>Is this correct OOP?</li> <li>Suggest any improvements?</li> </ul> <h3>Code:</h3> <pre class="lang-py prettyprint-override"><code>from typing import Dict class ConvertToKelvin: def __init__(self, substance: str, data: Dict[str, int]): self.substance = substance self.data = data def to_kelvin(self, celsius: int) -&gt; int: return celsius + 273 def __str__(self): sub = self.substance mp = self.to_kelvin(self.data[&quot;mp&quot;]) bp = self.to_kelvin(self.data[&quot;bp&quot;]) return f'{sub}:\n mp: {mp}K\n bp: {bp}K\n' data = ( ConvertToKelvin( 'water', { 'bp': 0, 'mp': 100 } ), ConvertToKelvin( 'imaginary', { 'bp': 30, 'mp': 120 } ), ) print('\n'.join(str(i) for i in data)) </code></pre> <h3>Output:</h3> <pre><code>water: mp: 373K bp: 273K imaginary: mp: 393K bp: 303K </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T17:08:38.013", "Id": "519193", "Score": "0", "body": "`to_kelvin(self, celsius: int)` seems more like a general utility function rather than a method related to or acting on `ConvertToKelvin`. If this was more integrated, I might expect `ConvertToKelvin` to have a property `celsius` similar to `substance` and that one would get the converted value via `to_kelvin(self)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T19:21:02.760", "Id": "519213", "Score": "0", "body": "That’s right, it’s because I’m so used to just using functions to do things having a hard time grasping OOP as for some things I just don’t get how they can be used as a ‘blueprint’" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T00:04:02.173", "Id": "519234", "Score": "0", "body": "Is `bp` = \"boiling point\" and `mp` = \"melting point\"? Do you have those switched?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T19:46:39.167", "Id": "519330", "Score": "0", "body": "Yeah… err thanks :)" } ]
{ "AcceptedAnswerId": "263035", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T15:38:22.077", "Id": "263030", "Score": "3", "Tags": [ "python-3.x", "object-oriented", "classes" ], "Title": "Temperature Converter: °C to K" }
263030
accepted_answer
[ { "body": "<ul>\n<li>ConvertToKelvin sounds like a method (it's a verb), when you actually need a noun</li>\n<li>You're actually capturing two different things - a temperature, and a substance</li>\n<li>The figure of 273 is incorrect and should actually be 273.15</li>\n<li>Avoid dictionaries for the purposes of internal state representation</li>\n<li>These are simple enough that a <code>dataclass</code> is well-suited, and should be immutable given the nature of your data hence why <code>frozen</code> is set</li>\n<li>Your use of <code>int</code> should probably be <code>float</code> instead. Temperatures are not discrete values.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass Temperature:\n celsius: float\n\n @property\n def kelvin(self) -&gt; float:\n return self.celsius + 273.15\n\n def __str__(self):\n return f'{self.kelvin} K'\n\n\n@dataclass(frozen=True)\nclass Substance:\n name: str\n melt: Temperature\n boil: Temperature\n\n def __str__(self):\n return (\n f'{self.name}:\\n'\n f' melt: {self.melt}\\n'\n f' boil: {self.boil}\\n'\n )\n\n\nsubstances = (\n Substance(\n 'water',\n Temperature(celsius=0),\n Temperature(celsius=100),\n ),\n Substance(\n '2-methylobenzenol (o-cresol)',\n Temperature(celsius=30),\n Temperature(celsius=191),\n ),\n)\n\nprint('\\n'.join(str(i) for i in substances))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T19:19:11.850", "Id": "519212", "Score": "0", "body": "Thank you, I used your last answer as a base to get familiar with classes and also to understand what you done which was impressive as all the guides deal only with user input like setting a value manually. There’s just one thing I don’t get how would you implement this as a ‘blueprint’? Thanks for correcting me on the precise value of converting to K, since you seem to be a man who loves precision, I think it’s just `K` Rather than degrees K :) but it was a good point for using a float thanks again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T19:53:56.707", "Id": "519215", "Score": "0", "body": "You're right; I never knew that! Per Wikipedia, _Unlike the degree Fahrenheit and degree Celsius, the kelvin is not referred to or written as a degree._" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T19:58:40.613", "Id": "519216", "Score": "0", "body": "As for a \"blueprint\", there's a large collection of strategies for class representation in Python and which to use varies widely based on circumstance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T21:11:37.177", "Id": "519222", "Score": "0", "body": "I’m just curious how you know some of the stuff you come out with, can’t find any guides that show the cool things you’ve shown me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T12:06:47.800", "Id": "519263", "Score": "0", "body": "Time in the job, research in the PEPs and the Python documentation (most of the Python tutorial content on the internet is junk)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T22:59:30.280", "Id": "519547", "Score": "0", "body": "I was going to use this structure replacing the `Substance` class with `Thing` class and `Temperature` to `Calculate` for printing the price and names of things I want to buy plus the total, is it possible to add up the temperatures in this example or would I be better of changing to a dict for this case? @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T00:07:26.063", "Id": "519550", "Score": "1", "body": "Stop using dicts. Don't name a class Calculate - that's the name of a method (verb), not a class (noun)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T03:11:58.287", "Id": "519556", "Score": "0", "body": "Point taken, but is it possible to add up the temps for a total using this structure? That’s all I want to know @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T13:24:45.590", "Id": "519578", "Score": "0", "body": "Let's please continue this in https://chat.stackexchange.com/rooms/126623/temperature-classes" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T17:17:31.330", "Id": "263035", "ParentId": "263030", "Score": "3" } } ]
<p><strong>Motivation:</strong> I was solving an array based i/o problem and encountered Time Limit Errors, it was later found that the code for java ran roughly <code>10x</code> slower than the python implementation.</p> <p><strong>Question</strong>: I would like to know which part of my code failed in the latter implementation (in Java) given that the algorithmic complexity for both the codes is the same. And what should I use in order to avoid it.</p> <hr /> <p>The problem is from <a href="https://www.hackerearth.com/practice/codemonk/" rel="nofollow noreferrer">https://www.hackerearth.com/practice/codemonk/</a> and a direct link doesn't exist.</p> <p>Given problem abstract: If an indexed array <code>arr</code> is given, print the contents of the array whose index is shifted by a constant.</p> <p>Example:</p> <pre><code>let arr=1,2,3,4 then arr shift 3 towards right means 2,3,4,1 </code></pre> <p>Input format:</p> <ul> <li>first line: number of test cases</li> <li>for each test case: <ul> <li>first line contains n,k where n represents number of elements and k represents the shifting</li> <li>the second line contains the elements of the array</li> </ul> </li> </ul> <p>Here is my <em>fast</em> python code</p> <pre class="lang-py prettyprint-override"><code>from sys import stdin t= int(input()) for i in range(t): n,k=list(map(int,input().split())) a=list(map(int,stdin.readline().split())) for i in range(n): print(a[(i-k)%n],end=&quot; &quot;) print(&quot;\n&quot;) </code></pre> <p>Here are the results:</p> <p><img src="https://i.stack.imgur.com/dcdb9m.png" alt="result" />.</p> <p>Now, I wrote another solution in Java</p> <pre class="lang-java prettyprint-override"><code>//imports for BufferedReader import java.io.BufferedReader; import java.io.InputStreamReader; //import for Scanner and other utility classes import java.util.*; class TestClass { public static void main(String args[] ) throws Exception { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); Scanner s = new Scanner(System.in); int t = Integer.parseInt(input.readLine()); while(t--&gt;0){ String[] nk = input.readLine().split(&quot; &quot;); int n = Integer.parseInt(nk[0]); int k = Integer.parseInt(nk[1]); String [] arr = input.readLine().split(&quot; &quot;); for(int i = 0; i &lt; n ; i++){ System.out.printf(&quot;%s &quot;,arr[(i-k%arr.length+arr.length)%(arr.length)]); } System.out.printf(&quot;%n&quot;); } } } </code></pre> <p>And here are the results:</p> <p><img src="https://i.stack.imgur.com/zld7Pm.png" alt="results" />.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T21:32:35.677", "Id": "519224", "Score": "0", "body": "The standard comment/answer for performance questions: get yourself a decent profiler to find out what method call consumes the majority of time. I wouldn't be surprised to see some `Scanner` methods making the hot spots." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T21:40:01.743", "Id": "519225", "Score": "0", "body": "How `Scanner s` is used at all here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T21:44:57.590", "Id": "519227", "Score": "0", "body": "`i-k%arr.length+arr.length` is vulnerable to integer overflow. That _may_ explain timeouts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T03:39:47.403", "Id": "519239", "Score": "0", "body": "@vnp Oh, that is unnecessary here, although removing it didnt make a difference" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T03:45:05.207", "Id": "519241", "Score": "0", "body": "@vnp pretty sure it isn't an overflow ...The time required for the failed test case is 3 seconds (tested on tio.run)...I cannot share the link, it is too long." } ]
{ "AcceptedAnswerId": "263053", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-14T20:49:05.717", "Id": "263043", "Score": "3", "Tags": [ "python", "java", "performance", "array", "time-limit-exceeded" ], "Title": "Java i/o speed less than python i/o while printing an array" }
263043
accepted_answer
[ { "body": "<h1>Python Code</h1>\n<ul>\n<li><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP-8</a> recommends\n<ul>\n<li>a space around binary operators like <code>=</code>.</li>\n<li>a space after commas (<code>n, k = …</code>)</li>\n<li>using the throw away variable (<code>_</code>) for loops which do not need the loop index for anything (<code>for _ in range(t):</code>)</li>\n</ul>\n</li>\n<li>the <code>list(…)</code> is unnecessary in the assignment to <code>n,k</code></li>\n<li>the <code>map(int, …)</code> is unnecessary for the <code>a</code> array, as you are simply parroting the values back out.</li>\n<li>there is no need to use <code>stdin.readline()</code>, you could simply use <code>input()</code> like the previous lines.</li>\n<li>one-letter variables should not be used unless it is very clear what that variable name means. <code>n</code> and <code>k</code> are from the problem statement, so are ok. <code>t</code>, on the other hand, is very obfuscating.</li>\n</ul>\n<p>Improved (readability &amp; speed) code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>num_tests = int(input())\nfor _ in range(num_tests):\n n, k = map(int, input().split())\n arr = input().split()\n for i in range(n):\n print(arr[(i-k) % n], end=' ')\n print(&quot;\\n&quot;)\n</code></pre>\n<h1>Java Code</h1>\n<ul>\n<li><code>Scanner s</code> is unused.</li>\n<li><code>t</code> is an obfuscating variable name</li>\n<li>try-with-resources should be used to ensure the <code>BufferedReader</code> and <code>InputStreamReader</code> are properly closed.</li>\n<li><code>n</code> should be the array length, why use <code>arr.length</code>?</li>\n</ul>\n<p>Performance issues:</p>\n<ul>\n<li>Double module operation: <code>(i-k%arr.length+arr.length)%(arr.length)</code>. <code>-k%arr.length+arr.length</code> is a constant. You could move that computation out of the loop. Or, if <code>k</code> is always in <code>0 &lt;= k &lt;= n</code>, simply use <code>(i-k+n)%n</code>.</li>\n<li><code>printf(&quot;%s &quot;)</code> may be slowing your program down by creating a brand new string combining the arr element and a space. Using <code>System.out.print(arr[(i-k+n)%n]); System.out.print(' ');</code> may be faster.</li>\n</ul>\n<p>And the number 1 performance issue …</p>\n<p><a href=\"https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/String.html#split(java.lang.String)\" rel=\"nofollow noreferrer\"><code>String[] String::split(String regex)</code></a></p>\n<p>… you are using the Regular Expression engine to split the string into words!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T04:50:22.583", "Id": "519242", "Score": "0", "body": "I'll try these out, by the way, what method should I use instead of split? i was looking at the Reader class when I found that split is the updated method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T05:06:56.493", "Id": "519243", "Score": "0", "body": "Now, after [updating](https://tio.run/##hZA/T8MwEMX3fAoLqZJDlajMAQYQQyUmylY6mObaXpOcLdtpQaifPZxboGka4Jbzn/fe/ey12qhEG6B1XjQNVkZbL9Z8mKJO7@rFAizkT6BysFnUuR6Tqf3EW1BVn6L2WKaXWRTNS@WceAbn7/erj0hwmfq1xLlwXnluG425qBSS5ECkpVB26aYzEQu/snrrxMPbHIxHTV/2UKd8AgOPuBEE286VDEdnuHLy7jxUKVIcZz@hSF6ElDF5WIJNjbIOeCP38Snb80ckkG3PdoUlSJ8kt6P4iBfq8Bp@CBWc2Y1InSnRywtxwWEnvkBBfRRUTEez1uhvcfGL@KorDsJiQFkPpmBOZe1/oG3jQlsZxiObRhm3a8bmPhx2PmI/5fDfmqMNz/OSh00lJsWQ4oGkuIva6zln2EV/G16o5TiKo8N2FzXNJw) I fail only [1 test case](https://i.stack.imgur.com/AmCOm.png)...thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T07:45:52.353", "Id": "519250", "Score": "1", "body": "Also using printf(\"%n\") to output A newline instead of println() is a bit wasteful. Before we had the split(Strign) method we had to use StringTokenizer for splitting strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T13:54:07.323", "Id": "519285", "Score": "0", "body": "[`StringUtils.split(str, ' ')`](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split-java.lang.String-char-) would be a great option, if you can use the Apache commons libraries. Failing that, you might have to roll your own ... or rethink the problem and come up with a different solution that doesn't require splitting the input into `n` tokens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T18:19:58.493", "Id": "519423", "Score": "0", "body": "StringUtils is unfortunately not supported on the platform . . . given that it's because of the regex based input splitting, I think I should linear search and find partitions...then use substrings" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-15T03:54:58.067", "Id": "263053", "ParentId": "263043", "Score": "6" } } ]
<p>I tried making a music player with tkinter in python but there's an error about module not callable but I'm not able to fix it. Can someone help?</p> <pre><code>import tkinter as Tk import pygame import os def __init__(self,root): self.root = root # title of the window self.root.title(&quot;MusicPlayer&quot;) # window geometry self.root.geometry(&quot;1000x200+200+200&quot;) # initiating pygame pygame.init() # initiating pygame mixer pygame.mixer.init() # declaring track variable self.track = StringVar() # Declaring status variable self.status = StringVar() #creating the track frames for song label &amp; status label trackframe = LabelFrame(self.root,text='Song Track',font=('times new roman',15,'bold'),bg='Navyblue',fg='white',bd='5',relief=GROOVE) trackframe.place(x=0,y=0,width=600,height=100) # inserting song track label songtrack = Label(trackframe,textvariable=self.track,width=20,font=('time new roman',24,'bold'),bg='orange',fg='gold').grid(row=0,column=0,padx=10,pady=5) # inserting status label trackstatus = Label(trackframe,textvariable=self.status,font=('times new roman',24,'bold'),bf='orange',fg='gold').grid(row=0,column=1,padx=10,pady=5) # creating button frame buttonframe = LabelFrame(self.root,text='control panel',font=('times new roman',15,'bold'),bg='grey',fg='white',bd=5,relief=GROOVE) buttonframe.place(x=0,y=100,widht=600,height=100) # inserting play button playbtn = Button(buttonframe, text='PLAYSONG',command=self.playsong,width=10,height=1,font=('times new roman',16,'bold'),fg='navyblue',bg='pink').grid(row=0,cloumn=0,padx=10,pady=5) # inserting pause button #this might need to be renamed playbtn = Button(buttonframe,text='PAUSE',command=self.pausesong,widht=8,height=1,font=('times new roman',16,'bold'),fg='navyblue',bg='pink').grid(row=0,cloumn=1,padx=10,pady=5) # inserting unpause button playbtn = Button(buttonframe,text='UNPAUSE',command=self.unpausesong,widht=10,height=1,font=('times new roman',16,'bold'),fg='navyblue',bg=&quot;pink&quot;).grid(row=0,column=2,padx=10,pady=5) # Inserting Stop Button playbtn = Button(buttonframe,text=&quot;STOPSONG&quot;,command=self.stopsong,width=10,height=1,font=(&quot;times new roman&quot;,16,&quot;bold&quot;),fg=&quot;navyblue&quot;,bg=&quot;pink&quot;).grid(row=0,column=3,padx=10,pady=5) # creating playlist frame songsframe = LabelFrame(self.root, text=&quot;Song Playlist&quot;,font=('times new roman',15,'bold'),bg='grey',fg='white',bd=5,relief=GROOVE) songsframe.place(x=600,y=0,wodht=400,height=200) # inserting scrollbar scrol_y = Scrollbar(songsframe, orient=VERTICAL) # Inserting playlist listbox self.playlist = Listbox(songsframe, yscrollcommand=scrol_y.set, selectbackground='gold',selectmode=SINGLE,font=('times new roman',12,'bold'),bg='silver',fg='navyblue',bd=5,relief=GROOVE) # applying scrollbar to listbox scrol_y.pack(side=RIGHT,fill=Y) scrol_y.config(command=self.playlist.yview) self.playlist.pack(fill=BOTH) # changing directory for fethcing songs os.chdir('D:\python\music_player\songs') # FETCHING SONGS songstracks = os.listdir() # inserting songs into playlist for track in songtracks: self.playlist.insert(END,track) def playsong(self): # displaying selected song title self.track.set(self.playlist.get(ACTIVE)) # displaying status self.status.set('-Playing') # loading selected song pygame.mixer.music.load(self.playlist.get(ACTIVE)) # PLAYING selected song pygame.mixer.music.play() def stopsong(self): # displaying status self.status.set('-Stopped') # stopped song pygame.mixer.music.stop() def pausesong(self): # displaying status self.status.set('-Paused') # paused song pygame.mixer.music.pause() def unpausesong(self): # it will display the status self.status.set('-Playing') # playing back song pygame.mixer.music.unpause() root = Tk() # In order to create an empty window # Passing Root to MusicPlayer Class MusicPlayer(root) root.mainloop() <span class="math-container">```</span> </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T10:41:00.843", "Id": "263101", "Score": "0", "Tags": [ "python", "tkinter" ], "Title": "Tkinter music player" }
263101
max_votes
[ { "body": "<blockquote>\n<p><code>imported tkinter as Tk</code></p>\n</blockquote>\n<blockquote>\n<p><code>root = Tk() # In order to create an empty window</code></p>\n</blockquote>\n<p>You imported tkinter under the name Tk, which coincidentally matches with the <code>Tk()</code> class of the tkinter module. By doing <code>Tk()</code> you are basically calling <code>tkinter()</code>, which is not a valid method or function.</p>\n<p>I suggest you use <code>import tkinter as tk</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T11:33:25.250", "Id": "263103", "ParentId": "263101", "Score": "3" } } ]
<p>I have the following implementation for the <code>__lt__</code>. Could you please check if it's okay to compare objects like that?</p> <pre><code>class Record(NamedTuple): video_id: str uuid: Optional[UUID] mac: Optional[str] s3_bucket: str s3_key: str reference_date: date @staticmethod def _lt(a: Any, b: Any) -&gt; bool: if a and b: return a &lt; b if a is None and b: return True return False def __lt__(self, other: &quot;Record&quot;) -&gt; Union[bool, Type[&quot;NotImplementedType&quot;]]: if not isinstance(other, Record): return NotImplemented for field in self._fields: self_ = getattr(self, field) other_ = getattr(other, field) if self_ == other_: continue return self._lt(self_, other_) return False </code></pre>
[]
{ "AcceptedAnswerId": "263132", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T15:53:44.697", "Id": "263112", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "Named tuple with less-than operator" }
263112
accepted_answer
[ { "body": "<p>This code is dangerous:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if a and b:\n return a &lt; b\n if a is None and b:\n return True\n return False\n</code></pre>\n<p>Consider <code>a = -1</code> and <code>b = 0</code>. <code>a and b</code> is <code>False</code> because <code>b</code> is falsey, so <code>a &lt; b</code> is never computed.</p>\n<p>Since <code>a is None</code> is false, we skip to <code>return False</code>, yielding a surprising result for <code>Record._lt(-1, 0)</code></p>\n<p>You should explicitly test <code>a is not None and b is not None</code> instead of <code>a and b</code>.</p>\n<p>Based on your typing, it currently doesn’t look like you’d pass in an <code>int</code> or a <code>float</code>, but if the class changes in the future, or is used as the model for another similar class, the unexpected behaviour might arise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T08:29:03.263", "Id": "519467", "Score": "0", "body": "what do you think about using @dataclass(order=True) instead of custom __lt__ method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:21:49.073", "Id": "519830", "Score": "0", "body": "A `@dataclass` is mutable (assuming `frozen=True` is not specified), where as tuples, including `NamedTuple`, are immutable. Without knowing more about the class and it's intended usages, it is hard to give a definitive answer. I like both `@dataclass` and `NamedTuple`, but they are different animals used for different things." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T05:29:19.150", "Id": "263132", "ParentId": "263112", "Score": "8" } } ]
<p>This python program analyzes movie data by finding the average budget of films in a data set - it also identifies films that exceed the average budget calculated.</p> <p>I need advice on my code in terms of (architecture, risks, opportunities, design) so that I can learn how I can code better &amp; grow my skills.</p> <pre><code># List of movies and their budgets movies = [ ('Avengers: Endgame', 400000000), ('Pirates of the Caribbean: On Stranger Tides', 379000000), ('Avengers: Age of Ultron', 365000000), ('Star Wars: Ep. VII: The Force Awakens', 306000000), ('Avengers: Infinity War', 300000000) ] # Allows user to input how many movies they want to add to the list add_new_movie = int(input('How many movies do you want to add? ')) # Takes the name and budget of the movie the user entered and add the movie to the list for _ in range(add_new_movie): name = input('Enter movie name: ') budget = input('Enter movie budget: ') new_movie = (name, int(budget)) movies.append(new_movie) # List representing over budget movies and counter to keep track of the total budget of all the movies in the list over_budget_movies = [] total_budget = 0 # Adds together the budget of each movie for movie in movies: total_budget += movie[1] # Calculates the average cost of all movies in the list average_budget = int(total_budget / len(movies)) # If the movie budget is over the average budget, how much the movies are over budget will be calculated and added to the over budget list for movie in movies: if movie[1] &gt; average_budget: over_budget_movies.append(movie) over_average_cost = movie[1] - average_budget print( f&quot;{movie[0]} was ${movie[1]:,}: ${over_average_cost:,} over average.&quot;) print() # Prints how many movies were over the average budget print( f&quot;There were {len(over_budget_movies)} movies with budgets that were over average.&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T09:25:34.547", "Id": "519566", "Score": "2", "body": "This is entirely irrelevant to your specific question, but in terms of data analysis, [Hollywood accounting](https://en.wikipedia.org/wiki/Hollywood_accounting) is a good example of [garbage in, garbage out](https://en.wikipedia.org/wiki/Garbage_in,_garbage_out)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T21:02:37.470", "Id": "263164", "Score": "6", "Tags": [ "python", "python-3.x" ], "Title": "Analyzing average movie budgets using Python 3" }
263164
max_votes
[ { "body": "<p><strong>Data entry without persistence does not make sense in most contexts</strong>. If a\nhuman has to type the data, save it somewhere. It could be a JSON file, CSV\nfile, database, whatever you would like to try. This kind of approach -- where\nthe data lives separately from the code -- has many benefits. It's a good\nvehicle for learning as well, so give it a shot.</p>\n<p><strong>Data entry and reporting are different tasks</strong>. Sometimes you want to add new\ndata to the system. Sometimes you want to analyze that data, get reports, etc.\nIn its simplest form, that might call for a program with 3 functions: a <code>main()</code>\nfunction where the user decides what to do (add data or get a report), and then\none function for each task.</p>\n<p><strong>Use meaningful data objects rather than generic collections</strong>. Currently, you\nrepresent a movie as a 2-tuple. But that's not very declarative: for example,\nyour code has to use <code>movie[1]</code> rather than <code>movie.budget</code>. Modern Python makes\nit super easy to create simple data objects (eg, namedtuple, dataclass, or\nattrs-based classes).</p>\n<p><strong>Avoid mixing computation and printing, if feasible</strong>. It's a good practice to\nseparate computation and anything that has &quot;side effects&quot;. Printing is the most\ncommon example of a side effect. This is a huge topic in computer science, and\nyou can learn more about it as you go forward. But when you're learning, just\ntry to get in the habit of keeping different things separate: for example,\ndon't print over-budget movies while you are creating a list of them.</p>\n<p>Here's an illustration of those ideas (ignoring data entry):</p>\n<pre><code>from collections import namedtuple\n\n# Meaningful data objects.\n\nMovie = namedtuple('Movie', 'title budget')\n\nmovies = [\n Movie('Avengers: Endgame', 400000000),\n Movie('Pirates of the Caribbean: On Stranger Tides', 379000000),\n Movie('Avengers: Age of Ultron', 365000000),\n Movie('Star Wars: Ep. VII: The Force Awakens', 306000000),\n Movie('Avengers: Infinity War', 300000000)\n]\n\n# Computation.\n\ntotal_budget = sum(m.budget for m in movies)\naverage_budget = int(total_budget / len(movies))\nover_budget_movies = [m for m in movies if m.budget &gt; average_budget]\n\n# Printing.\n\nprint(f'Number of overbudget movies: {len(over_budget_movies)}')\nfor m in over_budget_movies:\n diff = m.budget - average_budget\n print(f'{m.title} was ${m.budget}: ${diff} over average.')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T06:01:55.060", "Id": "519560", "Score": "0", "body": "You could also use `total_budget // len(movies)` (floor division, which is identical to casting to an integer for positive numbers). A better version would actually be to round to the nearest whole number (e.g. 3.75 -> 4 instead of 3)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T23:40:27.433", "Id": "263169", "ParentId": "263164", "Score": "9" } } ]
<p>In this python program, I built a ticketing system with functionality such as keeping track of tickets sold and error handling in case there are any invalid inputs.</p> <p>I need advice on my code in terms of (architecture, risks, opportunities, design) so that I can learn how I can code better &amp; grow my skills.</p> <pre><code>TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_remaining = 100 def calculate_price(ticket_amount): return (ticket_amount * TICKET_PRICE) + SERVICE_CHARGE while tickets_remaining &gt;= 1: print('There are {} tickets remaining'.format(tickets_remaining)) # Capture the user's name and assign it to a new variable name = input('What is your name?: ') # Ask how many tickets they would like and calculate the price ticket_amount = input( '{}, How many tickets would you like?: '.format(name)) # Expect a ValueError to happen and handle it appropriately try: ticket_amount = int(ticket_amount) # Raise a ValueError if the request is more tickets than there are available if ticket_amount &gt; tickets_remaining: raise ValueError( 'Sorry, there are only {} tickets remaining.'.format(tickets_remaining)) except ValueError as err: print('Sorry, invalid input {}'.format(err)) else: price = calculate_price(ticket_amount) print('Your total is ${} for {} tickets'.format(price, ticket_amount)) # Prompt the user if they want to proceed Y/N proceed = input( 'Would you like to proceed with your purchase? yes/no: ') if proceed.lower() == 'yes': # TODO: Gather credit card information and process it print('Sold!') tickets_remaining -= ticket_amount else: print('Thank you {}, hope to see you again soon.'.format(name)) # Notify the user when the tickets are sold out print('Sorry, the tickets are sold out.') </code></pre> <p>‘’’</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T00:43:18.017", "Id": "263171", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Ticketing program using Python 3" }
263171
max_votes
[ { "body": "<ol>\n<li><p>Overall, your code looks pretty clean and well explained;</p>\n</li>\n<li><p>When you want to get a 'yes' or 'no' from the user I advise you to just check the character you need the user to type so that you disregard typos or excesses. So instead of <code>if proceed.lower() == 'yes'</code> I usually use <code>if 'y' in proceed.lower()</code>;</p>\n</li>\n<li><p>You used the Python-3.x tag, so I believe you are using the latest version of Python, so I would consider using f-Strings. With that, I would make the following changes:</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>TICKET_PRICE = 10\nSERVICE_CHARGE = 2\n\ntickets_remaining = 100\n\n\ndef calculate_price(ticket_amount):\n return (ticket_amount * TICKET_PRICE) + SERVICE_CHARGE\n\n\nwhile tickets_remaining &gt;= 1:\n print(f'There are {tickets_remaining} tickets remaining')\n\n # Capture the user's name and assign it to a new variable\n name = input('What is your name?: ')\n\n # Ask how many tickets they would like and calculate the price\n ticket_amount = input(f'{name}, How many tickets would you like?: ')\n # Expect a ValueError to happen and handle it appropriately\n try:\n ticket_amount = int(ticket_amount)\n # Raise a ValueError if the request is more tickets than there are available\n if ticket_amount &gt; tickets_remaining:\n raise ValueError(f'Sorry, there are only {tickets_remaining} tickets remaining.')\n except ValueError as err:\n print(f'Sorry, invalid input {err}')\n else:\n price = calculate_price(ticket_amount)\n print(f'Your total is ${price} for {ticket_amount} tickets')\n\n # Prompt the user if they want to proceed Y/N\n proceed = input('Would you like to proceed with your purchase? yes/no: ')\n if 'y' in proceed.lower():\n\n # TODO: Gather credit card information and process it\n\n print('Sold!')\n tickets_remaining -= ticket_amount\n else:\n print(f'Thank you {name}, hope to see you again soon.')\n\n# Notify the user when the tickets are sold out\nprint('Sorry, the tickets are sold out.')\n\n</code></pre>\n<p>As I told you, overall your code is pretty clean and I didn't see much to change, but I hope I somehow helped.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T01:58:56.573", "Id": "263173", "ParentId": "263171", "Score": "3" } } ]
<p>I'm getting the highest value and its respective from a dictionary and printing it out for the user.</p> <p>Even though it's working, I'm wondering if I'm doing it in the cleanest way. Here it is:</p> <pre class="lang-py prettyprint-override"><code>People = {'Harry': 20, 'Ron': 19, 'Hermione': 21, 'Hagrid': 54} print(max(People, key=People.get), max(People.values())) # Result: Hagrid 54 </code></pre> <p>What would you do differently from this?</p>
[]
{ "AcceptedAnswerId": "263177", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T01:07:14.113", "Id": "263172", "Score": "9", "Tags": [ "python", "hash-map" ], "Title": "The cleanest way to print the max value and its key from a dictionary" }
263172
accepted_answer
[ { "body": "<blockquote>\n<p>What would you do differently from this?</p>\n</blockquote>\n<ul>\n<li><p><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">PEP 8</a>: Variable names should be lowercase. <code>People</code> -&gt; <code>people</code>.</p>\n</li>\n<li><p>As @FMc suggested in the comment, better to separate computation and printing. It is easier to understand and change.</p>\n</li>\n<li><p>An alternative (that I find more readable) is to use a lambda in the <code>max</code> function and unpack the tuple afterward:</p>\n<pre><code>people = {'Harry': 20, 'Ron': 19, 'Hermione': 21, 'Hagrid': 54}\nentry = max(people.items(), key=lambda x: x[1])\nprint(*entry)\n# Result: Hagrid 54\n</code></pre>\n<p>Or unpacking directly:</p>\n<pre><code>key, value = max(people.items(), key=lambda x: x[1])\nprint(key, value)\n# Result: Hagrid 54\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>Edit:</h2>\n<p>Using <a href=\"https://docs.python.org/3/library/operator.html#operator.itemgetter\" rel=\"noreferrer\">operator.itemgetter</a>, as suggested in the comments:</p>\n<pre><code>import operator\n\npeople = {'Harry': 20, 'Ron': 19, 'Hermione': 21, 'Hagrid': 54}\nkey, value = max(people.items(), key=operator.itemgetter(1))\nprint(key, value)\n# Result: Hagrid 54\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T07:14:18.197", "Id": "519564", "Score": "2", "body": "More readable - and likely more efficient, since we only invoke `max()` once here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T16:02:07.847", "Id": "519609", "Score": "2", "body": "I knew `sort` had a `key` parameter, but didn't know `max` had it too. Learn something new every day." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T04:39:26.887", "Id": "263177", "ParentId": "263172", "Score": "20" } } ]
<p>This is how I handle configuration in my python code, currently, but I guess it might look magic to people, and it is cumbersome to code. How can this be improved? Are there better solutions?</p> <p>The purpose is to have a general working configuration stored in UPPER CASE in global variables at the beginning of the file. When first run, it creates a <code>config.json</code> file with that configuration. That can be edited by the user, and it would supersede the default configuration, if run again. In order to still benefit from typing hints in modern IDEs, the <code>cfg[]</code> dict is not used directly, but the configuration is written back to the global variables.</p> <p>This is cumbersome to code, and it contains a lot of repetition. Every variable is touched multiple times.</p> <p>How can I improve this system and make it more elegant and transparent?</p> <pre><code>import json from typing import Any, Dict CONFIG_FILE = 'config.json' GLOBAL_CONFIG_EXAMPLE_PORT = 3 def read_config() -&gt; Dict[str, Any]: try: with open(CONFIG_FILE) as config_file: return json.load(config_file) except FileNotFoundError: pass # generate standard config file cfg = { 'example': { 'port': GLOBAL_CONFIG_EXAMPLE_PORT, }, } with open(CONFIG_FILE, 'w') as f: json.dump(cfg, f) set_global_variables(cfg) return cfg def set_global_variables(cfg: Dict[str, Any]): global GLOBAL_CONFIG_EXAMPLE_PORT GLOBAL_CONFIG_EXAMPLE_PORT = cfg['example']['port'] def main(): cfg: Dict[str, Any] = read_config() print(cfg['example']['port'], GLOBAL_CONFIG_EXAMPLE_PORT) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>A real-life config file would be this:</p> <pre><code>{ &quot;mqtt&quot;: { &quot;host&quot;: &quot;10.21.1.77&quot;, &quot;port&quot;: 1883, &quot;topic&quot;: &quot;EXTENSE/Lab/XYZ/move/#&quot;, &quot;topic_ack&quot;: &quot;EXTENSE/Lab/XYZ/move/ack&quot; }, &quot;signal&quot;: { &quot;save&quot;: true, &quot;length&quot;: 60 }, &quot;sensor&quot;: { &quot;num&quot;: 5, &quot;trigger&quot;: 4 }, &quot;logging&quot;: { &quot;level&quot;: 10, &quot;filename&quot;: &quot;log.txt&quot;, &quot;console&quot;: true, &quot;format&quot;: &quot;%(asctime)s %(levelname)s: %(message)s&quot; } } </code></pre> <p>PS: How would you go about writing a test for this, efficiently?</p> <p>Addendum: Is it feasible and sensible to do some magic on the variable name which is all upper case, split them by underscore, and create the dict automatically?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T12:12:35.143", "Id": "519672", "Score": "1", "body": "Can you include an example JSON file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T12:45:03.167", "Id": "519673", "Score": "0", "body": "certainly, @Reinderien :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T17:52:55.033", "Id": "519824", "Score": "0", "body": "@Reinderien i updated the config file, perhaps this illustrates the use a little better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T02:00:30.457", "Id": "519842", "Score": "0", "body": "What is supposed to happen when a section (like 'mqtt') or an item (like 'host') is missing from the config file. Does it fall back to the default or is it an error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T07:38:43.660", "Id": "519856", "Score": "0", "body": "@RootTwo The graceful thing would be to fall back on the default. For me, the concept of cascading configuration, overwriting what is specified, applies. It would be nice if the config file was updated with the missing information. That way you have one place with all the configuration information collected and easy to view." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:04:01.200", "Id": "519948", "Score": "1", "body": "I don't know if it's just me, but I just store configurations in .py files and import the variables from the files, and I used .__name__, repr() and json.dumps() and quotes and some code to print these configurations to python files. I know it's dirty but it is very effective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:49:21.477", "Id": "519957", "Score": "0", "body": "@XeнεiΞэnвϵς where is some code to look at this? This idea had not occurred to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:53:55.880", "Id": "519958", "Score": "1", "body": "If you really want to know, I will post an answer tomorrow, but not today." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T08:48:55.510", "Id": "520164", "Score": "0", "body": "@XeнεiΞэnвϵς you wanted to post code here." } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T11:12:14.927", "Id": "263215", "Score": "3", "Tags": [ "python", "json", "configuration" ], "Title": "How to handle configuration from a config file and global variables transparently in python?" }
263215
max_votes
[ { "body": "<p><code>read_config</code> does not do what's on the tin: it attempts to read the config, conditionally writes out a default config, and sets globals. Those obligations should be separated.</p>\n<p>Also, your <code>example</code> is a mystery: is it a section? Currently it offers no value and a flat dictionary would be simpler to manipulate.</p>\n<p><code>GLOBAL_CONFIG_EXAMPLE_PORT</code> on its own is not a useful global. Consider instead moving the entire default configuration dictionary to a global constant.</p>\n<p>Something like:</p>\n<pre><code>import json\nfrom typing import Any, Dict\n\nCONFIG_FILE = 'config.json'\n\nDEFAULT_CONFIG = {\n 'port': 3,\n}\n\n\ndef read_config() -&gt; Dict[str, Any]:\n with open(CONFIG_FILE) as f:\n return json.load(f)\n\n\ndef write_config(config: Dict[str, Any]) -&gt; None:\n with open(CONFIG_FILE, 'w') as f:\n json.dump(config, f)\n\n\ndef load_or_default_config() -&gt; None:\n try:\n config = read_config()\n except FileNotFoundError:\n config = DEFAULT_CONFIG\n write_config(config)\n\n globals().update(config)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T18:42:14.613", "Id": "519826", "Score": "0", "body": "thanks for telling me about globals()! I like your approach a lot, and it's a lot more elegant than mine. However, it lacks the list of global variables at the beginning of the program which I thought to be a part of a good python coding style, and replaces it with a dict. Do you think that's a step forward?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T18:55:26.387", "Id": "519827", "Score": "0", "body": "How would your approach handle multi-level global constants, like in the real-life config example above? @reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:01:39.963", "Id": "519828", "Score": "0", "body": "Spin up a `@dataclass` for each section so that the section variables have types; have a global class instance for each section" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:07:03.947", "Id": "519829", "Score": "0", "body": "and how would you combine those dataclasses into one? could you do the example in the (real life) config file and update your code, perhaps?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:26:17.617", "Id": "519831", "Score": "0", "body": "i mean: in my example you would have four global classes, because there are four sections. how do you combine those four classes into one dict to write into a config file, and how do you read them back into the right class, if there is a config file that you parsed and need to split up into the correct classes?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T13:50:56.170", "Id": "263283", "ParentId": "263215", "Score": "3" } } ]
<p>This is how I handle configuration in my python code, currently, but I guess it might look magic to people, and it is cumbersome to code. How can this be improved? Are there better solutions?</p> <p>The purpose is to have a general working configuration stored in UPPER CASE in global variables at the beginning of the file. When first run, it creates a <code>config.json</code> file with that configuration. That can be edited by the user, and it would supersede the default configuration, if run again. In order to still benefit from typing hints in modern IDEs, the <code>cfg[]</code> dict is not used directly, but the configuration is written back to the global variables.</p> <p>This is cumbersome to code, and it contains a lot of repetition. Every variable is touched multiple times.</p> <p>How can I improve this system and make it more elegant and transparent?</p> <pre><code>import json from typing import Any, Dict CONFIG_FILE = 'config.json' GLOBAL_CONFIG_EXAMPLE_PORT = 3 def read_config() -&gt; Dict[str, Any]: try: with open(CONFIG_FILE) as config_file: return json.load(config_file) except FileNotFoundError: pass # generate standard config file cfg = { 'example': { 'port': GLOBAL_CONFIG_EXAMPLE_PORT, }, } with open(CONFIG_FILE, 'w') as f: json.dump(cfg, f) set_global_variables(cfg) return cfg def set_global_variables(cfg: Dict[str, Any]): global GLOBAL_CONFIG_EXAMPLE_PORT GLOBAL_CONFIG_EXAMPLE_PORT = cfg['example']['port'] def main(): cfg: Dict[str, Any] = read_config() print(cfg['example']['port'], GLOBAL_CONFIG_EXAMPLE_PORT) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>A real-life config file would be this:</p> <pre><code>{ &quot;mqtt&quot;: { &quot;host&quot;: &quot;10.21.1.77&quot;, &quot;port&quot;: 1883, &quot;topic&quot;: &quot;EXTENSE/Lab/XYZ/move/#&quot;, &quot;topic_ack&quot;: &quot;EXTENSE/Lab/XYZ/move/ack&quot; }, &quot;signal&quot;: { &quot;save&quot;: true, &quot;length&quot;: 60 }, &quot;sensor&quot;: { &quot;num&quot;: 5, &quot;trigger&quot;: 4 }, &quot;logging&quot;: { &quot;level&quot;: 10, &quot;filename&quot;: &quot;log.txt&quot;, &quot;console&quot;: true, &quot;format&quot;: &quot;%(asctime)s %(levelname)s: %(message)s&quot; } } </code></pre> <p>PS: How would you go about writing a test for this, efficiently?</p> <p>Addendum: Is it feasible and sensible to do some magic on the variable name which is all upper case, split them by underscore, and create the dict automatically?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T12:12:35.143", "Id": "519672", "Score": "1", "body": "Can you include an example JSON file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T12:45:03.167", "Id": "519673", "Score": "0", "body": "certainly, @Reinderien :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T17:52:55.033", "Id": "519824", "Score": "0", "body": "@Reinderien i updated the config file, perhaps this illustrates the use a little better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T02:00:30.457", "Id": "519842", "Score": "0", "body": "What is supposed to happen when a section (like 'mqtt') or an item (like 'host') is missing from the config file. Does it fall back to the default or is it an error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T07:38:43.660", "Id": "519856", "Score": "0", "body": "@RootTwo The graceful thing would be to fall back on the default. For me, the concept of cascading configuration, overwriting what is specified, applies. It would be nice if the config file was updated with the missing information. That way you have one place with all the configuration information collected and easy to view." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:04:01.200", "Id": "519948", "Score": "1", "body": "I don't know if it's just me, but I just store configurations in .py files and import the variables from the files, and I used .__name__, repr() and json.dumps() and quotes and some code to print these configurations to python files. I know it's dirty but it is very effective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:49:21.477", "Id": "519957", "Score": "0", "body": "@XeнεiΞэnвϵς where is some code to look at this? This idea had not occurred to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:53:55.880", "Id": "519958", "Score": "1", "body": "If you really want to know, I will post an answer tomorrow, but not today." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T08:48:55.510", "Id": "520164", "Score": "0", "body": "@XeнεiΞэnвϵς you wanted to post code here." } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T11:12:14.927", "Id": "263215", "Score": "3", "Tags": [ "python", "json", "configuration" ], "Title": "How to handle configuration from a config file and global variables transparently in python?" }
263215
max_votes
[ { "body": "<p><code>read_config</code> does not do what's on the tin: it attempts to read the config, conditionally writes out a default config, and sets globals. Those obligations should be separated.</p>\n<p>Also, your <code>example</code> is a mystery: is it a section? Currently it offers no value and a flat dictionary would be simpler to manipulate.</p>\n<p><code>GLOBAL_CONFIG_EXAMPLE_PORT</code> on its own is not a useful global. Consider instead moving the entire default configuration dictionary to a global constant.</p>\n<p>Something like:</p>\n<pre><code>import json\nfrom typing import Any, Dict\n\nCONFIG_FILE = 'config.json'\n\nDEFAULT_CONFIG = {\n 'port': 3,\n}\n\n\ndef read_config() -&gt; Dict[str, Any]:\n with open(CONFIG_FILE) as f:\n return json.load(f)\n\n\ndef write_config(config: Dict[str, Any]) -&gt; None:\n with open(CONFIG_FILE, 'w') as f:\n json.dump(config, f)\n\n\ndef load_or_default_config() -&gt; None:\n try:\n config = read_config()\n except FileNotFoundError:\n config = DEFAULT_CONFIG\n write_config(config)\n\n globals().update(config)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T18:42:14.613", "Id": "519826", "Score": "0", "body": "thanks for telling me about globals()! I like your approach a lot, and it's a lot more elegant than mine. However, it lacks the list of global variables at the beginning of the program which I thought to be a part of a good python coding style, and replaces it with a dict. Do you think that's a step forward?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T18:55:26.387", "Id": "519827", "Score": "0", "body": "How would your approach handle multi-level global constants, like in the real-life config example above? @reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:01:39.963", "Id": "519828", "Score": "0", "body": "Spin up a `@dataclass` for each section so that the section variables have types; have a global class instance for each section" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:07:03.947", "Id": "519829", "Score": "0", "body": "and how would you combine those dataclasses into one? could you do the example in the (real life) config file and update your code, perhaps?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:26:17.617", "Id": "519831", "Score": "0", "body": "i mean: in my example you would have four global classes, because there are four sections. how do you combine those four classes into one dict to write into a config file, and how do you read them back into the right class, if there is a config file that you parsed and need to split up into the correct classes?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T13:50:56.170", "Id": "263283", "ParentId": "263215", "Score": "3" } } ]
<p>This is a Python script that generates ngrams using a set of rules of what letters can follow a letter stored in a dictionary.</p> <p>The output is then preliminarily processed using another script, then it will be filtered further using an api of sorts by number of words containing the ngrams, the result will be used in pseudoword generation.</p> <p>This is the generation part:</p> <pre class="lang-py prettyprint-override"><code>from string import ascii_lowercase import sys LETTERS = set(ascii_lowercase) VOWELS = set('aeiouy') CONSONANTS = LETTERS - VOWELS BASETAILS = { 'a': CONSONANTS, 'b': 'bjlr', 'c': 'chjklr', 'd': 'dgjw', 'e': CONSONANTS, 'f': 'fjlr', 'g': 'ghjlrw', 'h': '', 'i': CONSONANTS, 'j': '', 'k': 'hklrvw', 'l': 'l', 'm': 'cm', 'n': 'gn', 'o': CONSONANTS, 'p': 'fhlprst', 'q': '', 'r': 'hrw', 's': 'chjklmnpqstw', 't': 'hjrstw', 'u': CONSONANTS, 'v': 'lv', 'w': 'hr', 'x': 'h', 'y': 'sv', 'z': 'hlvw' } tails = dict() for i in ascii_lowercase: v = BASETAILS[i] if type(v) == set: v = ''.join(sorted(v)) tails.update({i: ''.join(sorted('aeiou' + v))}) def makechain(invar, target, depth=0): depth += 1 if type(invar) == str: invar = set(invar) chain = invar.copy() if depth == target: return sorted(chain) else: for i in invar: for j in tails[i[-1]]: chain.add(i + j) return makechain(chain, target, depth) if __name__ == '__main__': invar = sys.argv[1] target = int(sys.argv[2]) if invar in globals(): invar = eval(invar) print(*makechain(invar, target), sep='\n') </code></pre> <p>I want to ask about the <code>makechain</code> function, I used <code>set</code>s because somehow the results can contain duplicates if I used <code>list</code>s, though the result can be cast to <code>set</code>, I used a nested <code>for</code> loop and a recursive function to simulate a variable number of for loops.</p> <p>For example, <code>makechain(LETTERS, 4)</code> is equivalent to:</p> <pre class="lang-py prettyprint-override"><code>chain = set() for a in LETTERS: chain.add(a) for a in LETTERS: for b in tails[a]: chain.add(a + b) for a in LETTERS: for b in tails[a]: for c in tails[b]: chain.add(a + b + c) for a in LETTERS: for b in tails[a]: for c in tails[b]: for d in tails[c]: chain.add(a + b + c + d) </code></pre> <p>Obviously <code>makechain(LETTERS, 4)</code> is much better than the nested for loop approach, it is much more flexible.</p> <p>I want to know, is there anyway I can use a function from <code>itertools</code> instead of the nested <code>for</code> loop to generate the same results more efficiently?</p> <p>I am thinking about <code>itertools.product</code> and <code>itertools.combinations</code> but I just can't figure out how to do it.</p> <p>Any help will be appreciated.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T06:58:24.067", "Id": "263271", "Score": "3", "Tags": [ "python", "performance", "beginner", "python-3.x" ], "Title": "Python script that makes ngrams" }
263271
max_votes
[ { "body": "<blockquote>\n<p>Any help will be appreciated</p>\n</blockquote>\n<p>A few suggestions on something that I noticed:</p>\n<ul>\n<li><p>In the function <code>makechain</code> the <code>else</code> after the <code>return</code> is not necessary.</p>\n</li>\n<li><p>Typo in: <code>VOWELS = set('aeiouy')</code>, there is an extra <code>y</code>.</p>\n</li>\n<li><p>This part:</p>\n<pre><code>LETTERS = set(ascii_lowercase)\nVOWELS = set('aeiou')\nCONSONANTS = LETTERS - VOWELS\n\nBASETAILS = {\n 'a': CONSONANTS,\n 'b': 'bjlr',\n 'c': 'chjklr',\n 'd': 'dgjw',\n ....\n }\n\ntails = dict()\n\nfor i in ascii_lowercase:\n v = BASETAILS[i]\n if type(v) == set:\n v = ''.join(sorted(v))\n tails.update({i: ''.join(sorted('aeiou' + v))})\n</code></pre>\n<p>seems to do the following:</p>\n<ol>\n<li>Create a dictionary with mixed value's type (strings and sets)</li>\n<li>Convert all values to string</li>\n<li>Sort dictionary's values</li>\n</ol>\n<p>It could be simplified to:</p>\n<ol>\n<li>Create a dictionary where all values are strings</li>\n<li>Sort dictionary's values</li>\n</ol>\n<p>Additionally, having <code>VOWELS</code> as a set and <code>CONSONANTS</code> as a string is a bit confusing. Would be better to use only one type.</p>\n<p>Code with suggestions above:</p>\n<pre><code>LETTERS = ascii_lowercase\nVOWELS = 'aeiou'\nCONSONANTS = ''.join(set(LETTERS) - set(VOWELS))\n\nBASETAILS = {\n 'a': CONSONANTS,\n 'b': 'bjlr',\n 'c': 'chjklr',\n 'd': 'dgjw',\n ....\n }\n\ntails = dict()\n\nfor i in ascii_lowercase:\n v = BASETAILS[i]\n tails.update({i: ''.join(sorted(VOWELS + v))})\n</code></pre>\n<p>In this way, you also avoid sorting twice.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T11:05:14.927", "Id": "263279", "ParentId": "263271", "Score": "2" } } ]
<blockquote> <p>Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.</p> <p>The following variables contain values as described below:</p> <p><code>balance</code> - the outstanding balance on the credit card</p> <p><code>annualInterestRate</code> - annual interest rate as a decimal</p> <p><code>monthlyPaymentRate</code> - minimum monthly payment rate as a decimal</p> <p>For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print</p> <p><code>Remaining balance: 813.41</code></p> <p>instead of</p> <p><code>Remaining balance: 813.4141998135</code></p> <p>So your program only prints out one thing: the remaining balance at the end of the year in the format:</p> <p><code>Remaining balance: 4784.0</code></p> <p>A summary of the required math is found below:</p> <p><span class="math-container">\begin{align*} \text{Monthly interest rate} &amp;= \frac{\text{Annual interest rate}}{12} \\ \text{Minimum monthly payment} &amp;= \text{Minimum monthly payment rate} \times \text{Previous balance} \\ \text{Monthly unpaid balance} &amp;= \text{Previous balance} \\ &amp;- \text{Minimum monthly payment} \\ \text{Updated balance each month} &amp;= \text{Monthly unpaid balance} \\ &amp;+ (\text{Monthly interest rate} \times \text{Monthly unpaid balance}) \end{align*}</span></p> </blockquote> <h1>Code</h1> <pre class="lang-py prettyprint-override"><code>def balances(initial_balance, annual_interest_rate, minimum_monthly_payment_rate): balance = initial_balance monthly_interest_rate = annual_interest_rate / 12 for month in range(13): minimum_monthly_payment = balance * minimum_monthly_payment_rate monthly_unpaid_balance = balance - minimum_monthly_payment yield {'month': month, 'minimum_monthly_payment': minimum_monthly_payment, 'balance': balance} balance = monthly_unpaid_balance + (monthly_unpaid_balance * monthly_interest_rate) def main(): *bs, remaining_balance = balances(balance, annualInterestRate, monthlyPaymentRate) print('Remaining Balance: {}'.format(round(remaining_balance['balance'], 2))) # Testing data balance = 484 annualInterestRate = .2 monthlyPaymentRate = .04 ## ifname_main does not work in grader if __name__ == '__main__': main() </code></pre> <p>Thanks in advance.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T15:45:42.960", "Id": "263287", "Score": "3", "Tags": [ "python", "programming-challenge", "generator" ], "Title": "Q: Paying Debt Off a Year, MIT edX 6.001 U2/PS2/P1" }
263287
max_votes
[ { "body": "<ul>\n<li>Could use some PEP484 type hints</li>\n<li><code>range(13)</code> is awkward - there's no point in yielding the initial balance, so just yield adjusted balances and do it 12 times</li>\n<li>No point in yielding the month, payment and balance; just yield the balance. Even if you needed to yield all three, a dictionary is not a great way to do it. Tuples are standard; or a dataclass is better-structured.</li>\n<li>No need to call <code>format</code> or <code>round</code>. Just use <code>.2f</code>. Note that this contravenes the specification's <code>Remaining balance: 4784.0</code> but that's dumb; this is a money quantity so the precision should be fixed.</li>\n<li>Your <code>balances</code> is fine as a generator, but why limit it to 12 iterations? The more generic and useful implementation simply iterates forever. Use <code>islice</code> to pull 12 values, ignoring all but the last.</li>\n</ul>\n<h2>Suggested (iterative)</h2>\n<pre><code>from itertools import islice\nfrom typing import Iterable\n\n\ndef balances(\n initial_balance: float,\n annual_interest_rate: float,\n minimum_monthly_payment_rate: float,\n) -&gt; Iterable[float]:\n balance = initial_balance\n monthly_interest_rate = annual_interest_rate / 12\n\n while True:\n minimum_monthly_payment = balance * minimum_monthly_payment_rate\n monthly_unpaid_balance = balance - minimum_monthly_payment\n balance = monthly_unpaid_balance * (1 + monthly_interest_rate)\n yield balance\n\n\ndef main():\n for balance in islice(\n balances(\n initial_balance=484.00,\n annual_interest_rate=0.20,\n minimum_monthly_payment_rate=0.04,\n ),\n 12,\n ):\n pass\n\n print(f'Remaining Balance: {balance:.2f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Simplifying the inner loop would replace it with</p>\n<pre><code>balance *= (1 - minimum_monthly_payment_rate) * (1 + monthly_interest_rate)\n</code></pre>\n<p>which is equivalent.</p>\n<h2>Suggested (compound)</h2>\n<p>Even better is to get rid of the loop entirely, and just use a power:</p>\n<pre><code>def compound(\n initial_balance: float,\n annual_interest_rate: float,\n minimum_monthly_payment_rate: float,\n months: int,\n) -&gt; float:\n monthly_interest_rate = annual_interest_rate / 12\n\n return initial_balance * (\n (1 - minimum_monthly_payment_rate) * (1 + monthly_interest_rate)\n ) ** months\n\n\ndef main():\n balance = compound(\n initial_balance=484.00,\n annual_interest_rate=0.20,\n minimum_monthly_payment_rate=0.04,\n months=12,\n )\n\n print(f'Remaining Balance: {balance:.2f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:35:08.323", "Id": "519873", "Score": "0", "body": "Wouldn't it be useless to yield negative balances?\n\nMaybe make it `while balance >= 0`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:56:25.327", "Id": "519874", "Score": "0", "body": "Possible. Add that if you want. There are some (non-credit-card) account types that would benefit from being able to represent both credit and debit states." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:58:15.290", "Id": "519884", "Score": "0", "body": "That said, do a little math and you'll find that the balance never goes to or below zero for a finite number of iterations." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T01:17:31.360", "Id": "263303", "ParentId": "263287", "Score": "2" } } ]
<blockquote> <p>Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.</p> <p>The following variables contain values as described below:</p> <p><code>balance</code> - the outstanding balance on the credit card</p> <p><code>annualInterestRate</code> - annual interest rate as a decimal</p> <p><code>monthlyPaymentRate</code> - minimum monthly payment rate as a decimal</p> <p>For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print</p> <p><code>Remaining balance: 813.41</code></p> <p>instead of</p> <p><code>Remaining balance: 813.4141998135</code></p> <p>So your program only prints out one thing: the remaining balance at the end of the year in the format:</p> <p><code>Remaining balance: 4784.0</code></p> <p>A summary of the required math is found below:</p> <p><span class="math-container">\begin{align*} \text{Monthly interest rate} &amp;= \frac{\text{Annual interest rate}}{12} \\ \text{Minimum monthly payment} &amp;= \text{Minimum monthly payment rate} \times \text{Previous balance} \\ \text{Monthly unpaid balance} &amp;= \text{Previous balance} \\ &amp;- \text{Minimum monthly payment} \\ \text{Updated balance each month} &amp;= \text{Monthly unpaid balance} \\ &amp;+ (\text{Monthly interest rate} \times \text{Monthly unpaid balance}) \end{align*}</span></p> </blockquote> <h1>Code</h1> <pre class="lang-py prettyprint-override"><code>def balances(initial_balance, annual_interest_rate, minimum_monthly_payment_rate): balance = initial_balance monthly_interest_rate = annual_interest_rate / 12 for month in range(13): minimum_monthly_payment = balance * minimum_monthly_payment_rate monthly_unpaid_balance = balance - minimum_monthly_payment yield {'month': month, 'minimum_monthly_payment': minimum_monthly_payment, 'balance': balance} balance = monthly_unpaid_balance + (monthly_unpaid_balance * monthly_interest_rate) def main(): *bs, remaining_balance = balances(balance, annualInterestRate, monthlyPaymentRate) print('Remaining Balance: {}'.format(round(remaining_balance['balance'], 2))) # Testing data balance = 484 annualInterestRate = .2 monthlyPaymentRate = .04 ## ifname_main does not work in grader if __name__ == '__main__': main() </code></pre> <p>Thanks in advance.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T15:45:42.960", "Id": "263287", "Score": "3", "Tags": [ "python", "programming-challenge", "generator" ], "Title": "Q: Paying Debt Off a Year, MIT edX 6.001 U2/PS2/P1" }
263287
max_votes
[ { "body": "<ul>\n<li>Could use some PEP484 type hints</li>\n<li><code>range(13)</code> is awkward - there's no point in yielding the initial balance, so just yield adjusted balances and do it 12 times</li>\n<li>No point in yielding the month, payment and balance; just yield the balance. Even if you needed to yield all three, a dictionary is not a great way to do it. Tuples are standard; or a dataclass is better-structured.</li>\n<li>No need to call <code>format</code> or <code>round</code>. Just use <code>.2f</code>. Note that this contravenes the specification's <code>Remaining balance: 4784.0</code> but that's dumb; this is a money quantity so the precision should be fixed.</li>\n<li>Your <code>balances</code> is fine as a generator, but why limit it to 12 iterations? The more generic and useful implementation simply iterates forever. Use <code>islice</code> to pull 12 values, ignoring all but the last.</li>\n</ul>\n<h2>Suggested (iterative)</h2>\n<pre><code>from itertools import islice\nfrom typing import Iterable\n\n\ndef balances(\n initial_balance: float,\n annual_interest_rate: float,\n minimum_monthly_payment_rate: float,\n) -&gt; Iterable[float]:\n balance = initial_balance\n monthly_interest_rate = annual_interest_rate / 12\n\n while True:\n minimum_monthly_payment = balance * minimum_monthly_payment_rate\n monthly_unpaid_balance = balance - minimum_monthly_payment\n balance = monthly_unpaid_balance * (1 + monthly_interest_rate)\n yield balance\n\n\ndef main():\n for balance in islice(\n balances(\n initial_balance=484.00,\n annual_interest_rate=0.20,\n minimum_monthly_payment_rate=0.04,\n ),\n 12,\n ):\n pass\n\n print(f'Remaining Balance: {balance:.2f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Simplifying the inner loop would replace it with</p>\n<pre><code>balance *= (1 - minimum_monthly_payment_rate) * (1 + monthly_interest_rate)\n</code></pre>\n<p>which is equivalent.</p>\n<h2>Suggested (compound)</h2>\n<p>Even better is to get rid of the loop entirely, and just use a power:</p>\n<pre><code>def compound(\n initial_balance: float,\n annual_interest_rate: float,\n minimum_monthly_payment_rate: float,\n months: int,\n) -&gt; float:\n monthly_interest_rate = annual_interest_rate / 12\n\n return initial_balance * (\n (1 - minimum_monthly_payment_rate) * (1 + monthly_interest_rate)\n ) ** months\n\n\ndef main():\n balance = compound(\n initial_balance=484.00,\n annual_interest_rate=0.20,\n minimum_monthly_payment_rate=0.04,\n months=12,\n )\n\n print(f'Remaining Balance: {balance:.2f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:35:08.323", "Id": "519873", "Score": "0", "body": "Wouldn't it be useless to yield negative balances?\n\nMaybe make it `while balance >= 0`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:56:25.327", "Id": "519874", "Score": "0", "body": "Possible. Add that if you want. There are some (non-credit-card) account types that would benefit from being able to represent both credit and debit states." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:58:15.290", "Id": "519884", "Score": "0", "body": "That said, do a little math and you'll find that the balance never goes to or below zero for a finite number of iterations." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T01:17:31.360", "Id": "263303", "ParentId": "263287", "Score": "2" } } ]
<blockquote> <p>Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.</p> <p>The following variables contain values as described below:</p> <p><code>balance</code> - the outstanding balance on the credit card</p> <p><code>annualInterestRate</code> - annual interest rate as a decimal</p> <p><code>monthlyPaymentRate</code> - minimum monthly payment rate as a decimal</p> <p>For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print</p> <p><code>Remaining balance: 813.41</code></p> <p>instead of</p> <p><code>Remaining balance: 813.4141998135</code></p> <p>So your program only prints out one thing: the remaining balance at the end of the year in the format:</p> <p><code>Remaining balance: 4784.0</code></p> <p>A summary of the required math is found below:</p> <p><span class="math-container">\begin{align*} \text{Monthly interest rate} &amp;= \frac{\text{Annual interest rate}}{12} \\ \text{Minimum monthly payment} &amp;= \text{Minimum monthly payment rate} \times \text{Previous balance} \\ \text{Monthly unpaid balance} &amp;= \text{Previous balance} \\ &amp;- \text{Minimum monthly payment} \\ \text{Updated balance each month} &amp;= \text{Monthly unpaid balance} \\ &amp;+ (\text{Monthly interest rate} \times \text{Monthly unpaid balance}) \end{align*}</span></p> </blockquote> <h1>Code</h1> <pre class="lang-py prettyprint-override"><code>def balances(initial_balance, annual_interest_rate, minimum_monthly_payment_rate): balance = initial_balance monthly_interest_rate = annual_interest_rate / 12 for month in range(13): minimum_monthly_payment = balance * minimum_monthly_payment_rate monthly_unpaid_balance = balance - minimum_monthly_payment yield {'month': month, 'minimum_monthly_payment': minimum_monthly_payment, 'balance': balance} balance = monthly_unpaid_balance + (monthly_unpaid_balance * monthly_interest_rate) def main(): *bs, remaining_balance = balances(balance, annualInterestRate, monthlyPaymentRate) print('Remaining Balance: {}'.format(round(remaining_balance['balance'], 2))) # Testing data balance = 484 annualInterestRate = .2 monthlyPaymentRate = .04 ## ifname_main does not work in grader if __name__ == '__main__': main() </code></pre> <p>Thanks in advance.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T15:45:42.960", "Id": "263287", "Score": "3", "Tags": [ "python", "programming-challenge", "generator" ], "Title": "Q: Paying Debt Off a Year, MIT edX 6.001 U2/PS2/P1" }
263287
max_votes
[ { "body": "<ul>\n<li>Could use some PEP484 type hints</li>\n<li><code>range(13)</code> is awkward - there's no point in yielding the initial balance, so just yield adjusted balances and do it 12 times</li>\n<li>No point in yielding the month, payment and balance; just yield the balance. Even if you needed to yield all three, a dictionary is not a great way to do it. Tuples are standard; or a dataclass is better-structured.</li>\n<li>No need to call <code>format</code> or <code>round</code>. Just use <code>.2f</code>. Note that this contravenes the specification's <code>Remaining balance: 4784.0</code> but that's dumb; this is a money quantity so the precision should be fixed.</li>\n<li>Your <code>balances</code> is fine as a generator, but why limit it to 12 iterations? The more generic and useful implementation simply iterates forever. Use <code>islice</code> to pull 12 values, ignoring all but the last.</li>\n</ul>\n<h2>Suggested (iterative)</h2>\n<pre><code>from itertools import islice\nfrom typing import Iterable\n\n\ndef balances(\n initial_balance: float,\n annual_interest_rate: float,\n minimum_monthly_payment_rate: float,\n) -&gt; Iterable[float]:\n balance = initial_balance\n monthly_interest_rate = annual_interest_rate / 12\n\n while True:\n minimum_monthly_payment = balance * minimum_monthly_payment_rate\n monthly_unpaid_balance = balance - minimum_monthly_payment\n balance = monthly_unpaid_balance * (1 + monthly_interest_rate)\n yield balance\n\n\ndef main():\n for balance in islice(\n balances(\n initial_balance=484.00,\n annual_interest_rate=0.20,\n minimum_monthly_payment_rate=0.04,\n ),\n 12,\n ):\n pass\n\n print(f'Remaining Balance: {balance:.2f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Simplifying the inner loop would replace it with</p>\n<pre><code>balance *= (1 - minimum_monthly_payment_rate) * (1 + monthly_interest_rate)\n</code></pre>\n<p>which is equivalent.</p>\n<h2>Suggested (compound)</h2>\n<p>Even better is to get rid of the loop entirely, and just use a power:</p>\n<pre><code>def compound(\n initial_balance: float,\n annual_interest_rate: float,\n minimum_monthly_payment_rate: float,\n months: int,\n) -&gt; float:\n monthly_interest_rate = annual_interest_rate / 12\n\n return initial_balance * (\n (1 - minimum_monthly_payment_rate) * (1 + monthly_interest_rate)\n ) ** months\n\n\ndef main():\n balance = compound(\n initial_balance=484.00,\n annual_interest_rate=0.20,\n minimum_monthly_payment_rate=0.04,\n months=12,\n )\n\n print(f'Remaining Balance: {balance:.2f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:35:08.323", "Id": "519873", "Score": "0", "body": "Wouldn't it be useless to yield negative balances?\n\nMaybe make it `while balance >= 0`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:56:25.327", "Id": "519874", "Score": "0", "body": "Possible. Add that if you want. There are some (non-credit-card) account types that would benefit from being able to represent both credit and debit states." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:58:15.290", "Id": "519884", "Score": "0", "body": "That said, do a little math and you'll find that the balance never goes to or below zero for a finite number of iterations." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T01:17:31.360", "Id": "263303", "ParentId": "263287", "Score": "2" } } ]
<p>While learning about python tkinter, I decided to make a digital clock:</p> <pre><code>from datetime import datetime import tkinter as tk from threading import Thread import time class clock(): def __init__(self): self.display = tk.Tk() def start(self): def get(): self.display.geometry(&quot;215x62&quot;) self.display.title(&quot;Clock&quot;) while True: try: now = datetime.now() current_time = now.strftime(&quot;%H:%M %p&quot;) lbl = tk.Label(self.display, text=str(current_time), background = 'black', font = (&quot;Helvetica&quot;, 37), foreground = 'red') lbl.place(x=0, y=0) time.sleep(0.1) except: break receive_thread = Thread(target=get) receive_thread.start() self.display.mainloop() clock = clock() clock.start() </code></pre> <p>Is there any way to make this clock better?</p> <p>Any comments, answers, or steps in the right direction would be appreciated.</p>
[]
{ "AcceptedAnswerId": "263348", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T21:43:26.403", "Id": "263346", "Score": "7", "Tags": [ "python", "tkinter", "timer" ], "Title": "Digital clock with Python Tkinter" }
263346
accepted_answer
[ { "body": "<p>To start, it's crucial that you stop creating a brand new label ten times a second. Just modify the existing one. Also, this is so simple that a class is not called for. Move as much as possible away from your thread, into your setup routine. Finally, your use of <code>%H</code> is likely incorrect given that you also include <code>%p</code>; you probably want <code>%I</code> for a 12-hour clock.</p>\n<p>This all suggests:</p>\n<pre><code>from datetime import datetime\nimport tkinter as tk\nfrom threading import Thread\nfrom time import sleep\n\n\ndef main():\n display = tk.Tk()\n display.geometry('215x62')\n display.title('Clock')\n\n lbl = tk.Label(\n display,\n background='black',\n font=('Helvetica', 37),\n foreground='red',\n )\n lbl.place(x=0, y=0)\n\n def get():\n while True:\n now = datetime.now()\n lbl.config(text=now.strftime('%I:%M %p'))\n sleep(0.1)\n\n receive_thread = Thread(target=get)\n receive_thread.start()\n display.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Ten times a second is overkill, and you can safely make this much sleepier. Do not make a thread at all; use an <code>after()</code> timer, and calculate when exactly the clock should tick:</p>\n<pre><code>from datetime import datetime\nimport tkinter as tk\nfrom time import time\n\n\ndef main() -&gt; None:\n display = tk.Tk()\n display.geometry('215x62')\n display.title('Clock')\n\n lbl = tk.Label(\n display,\n background='black',\n font=('Helvetica', 37),\n foreground='red',\n )\n lbl.place(x=0, y=0)\n\n def tick() -&gt; None:\n now = datetime.now()\n lbl.config(text=now.strftime('%I:%M %p'))\n\n until_next = round(\n 1000 * (60 - time()%60)\n )\n display.after(ms=until_next, func=tick)\n\n tick()\n display.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T02:35:34.167", "Id": "519915", "Score": "0", "body": "Reiderien always displaying his beautiful codes. " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T02:47:04.373", "Id": "519918", "Score": "0", "body": "@ArnonDePaula thank you <3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T08:56:56.610", "Id": "519935", "Score": "0", "body": "Won't your second code run into stack size limitations after 1000 seconds, since each invocation of `tick` starts a new one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T12:28:17.603", "Id": "519941", "Score": "1", "body": "@Graphier I don't think so. `after` is asynchronous. It's not going to recurse - this is telling tk to use the event loop and schedule a callback for a later time." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T23:35:52.057", "Id": "263348", "ParentId": "263346", "Score": "8" } } ]
<p><strong>Problem statement:</strong> I have the following access log, get the count by timestamp(hh:mm) and sort the count based on minute. And write it into the CSV file.</p> <p><code>access.log:</code></p> <pre><code>172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 401 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 200 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 401 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.1.3 - - [25/Sep/2002:14:04:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 401 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.1.3 - - [25/Sep/2002:14:05:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 200 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.1.3 - - [25/Sep/2002:14:05:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 200 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; </code></pre> <p>expected output:</p> <pre><code>#cat output.csv: 14:04, 4 14:05, 2 </code></pre> <p><strong>My solution:</strong></p> <pre><code>import re import csv log_list = {} with open('access.log','r') as loglines: for line in loglines: if line != &quot;\n&quot;: re_pattern = '([\d\.?]+) - - \[(.*?)\] &quot;(.*?)&quot; (.*?) (.*?) &quot;(.*?)&quot; &quot;(.*?)&quot;' re_match = re.match(re_pattern, line) timestamp = re_match.groups()[1] hh_mm = timestamp[12:17] if hh_mm in log_list: log_list[hh_mm] += 1 else: log_list[hh_mm] = 1 srtd_list = sorted(log_list.items(), key=lambda i:i[0]) with open('parsed_file.csv','w') as parsed_file: csv_writer = csv.writer(parsed_file) for item in srtd_list: csv_writer.writerow(item) </code></pre> <p><strong>Follow up questions:</strong></p> <ol> <li>Any other efficient way to perform this?</li> <li>How can i improve the book keeping of the count, if the file size is 10GB or if the file is ever growing.</li> <li>Efficient way to do the same for a file which gonna keep rotate hourly.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:17:37.450", "Id": "519953", "Score": "1", "body": "Why is this being done in the first place? There are multiple strange things going on here, including that you're divorcing the time from the date. Is this for some kind of log traffic histogram only paying attention to the time of day?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:48:20.260", "Id": "519976", "Score": "0", "body": "yes., that's right! @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T19:54:06.627", "Id": "519990", "Score": "1", "body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T05:47:29.397", "Id": "520002", "Score": "0", "body": "i see! and noted that point. thanks! @TobySpeight" } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T11:01:14.770", "Id": "263360", "Score": "3", "Tags": [ "python" ], "Title": "Parsing log file and returning timestamp ordered output" }
263360
max_votes
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code>log_list = {}\n...\n if hh_mm in log_list:\n log_list[hh_mm] += 1\n else:\n log_list[hh_mm] = 1\n...\n</code></pre>\n<p>This can be replaced with a <code>Counter</code> where unknown keys default to zero.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nlog_list = Counter()\n...\n log_list[hh_mm] += 1\n...\n</code></pre>\n<p><code>re_pattern</code> does not need to be redefined each time through the loop. It should be moved outside of the loop, possibly to the top of the file as a constant (ie, named in all caps: <code>RE_PATTERN</code>), and maybe even compiled using <code>re.compile(…)</code></p>\n<p>There is no point capturing patterns you aren’t using. You just need <code>(…)</code> around the timestamp re pattern.</p>\n<p>From <code>srtd_list</code> on, you can outdent one level. You’ve finished reading the <code>loglines</code>, so you should allow the file to be closed immediately.</p>\n<p>The <code>key=…</code> in <code>sorted(…)</code> is unnecessary, since you are sorting on the guaranteed-unique first element of a tuple.</p>\n<hr />\n<p>You don’t need regex at all to do this. You could write the first part of the code as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import csv\nfrom collections import Counter\n\nwith open('access.log','r') as loglines:\n log_list = Counter(line.split()[3][13:18]\n for line in loglines\n if line != '\\n')\nsrtd_list = sorted(log_list.items())\n…\n</code></pre>\n<p>This is simultaneously simpler and more cryptic. Comment it well if you use it!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:50:15.170", "Id": "519977", "Score": "0", "body": "1. Good suggestion on the collections\n2. `re_pattern` in the loop is not an intended one - will correct it, thanks for highlighting it\n3. Sorted is required, because i need sort it based on `hh:mm`\n4. Regarding regex vs split, will test out which one would be performant and use that. Thanks for the suggestion there too.\n\nAny thoughts on the followup questions? Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T19:25:50.077", "Id": "519985", "Score": "0", "body": "Regarding: \"_3. Sorted is required, because i need sort it based on hh:mm_\". I think you misunderstood me. `srtd_list = sorted(log_list.items(), key=lambda i:i[0])` will behave the same way `srtd_list = sorted(log_list.items())` does, because without a `key=...` argument, it sorts based on the natural ordering of each item, and since the items are dictionary key-value pairs, the first element of each item (the key) is unique, so it ends up sorting based on the dictionary keys, as desired." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T19:37:06.543", "Id": "519988", "Score": "0", "body": "Your CSV file will have, at most 1440 lines in it, regardless of the size of the input log (10GB, 10TB, 10PB, 10EB, 10ZB, 10YB ...) since there are only 24*60 distinct minutes in the day." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T14:39:00.027", "Id": "263370", "ParentId": "263360", "Score": "3" } } ]
<p>Second day coding so I'm new to this. I have made this simple calculator but I repeat the code in order to use the previous answer in the next calculation. I've been trying to simplify it but I can't seem to figure it out. Whatever I try breaks the code. Any feed back helps. Here is the code</p> <pre><code># Beginning calculator code first_number = &quot;a&quot; second_number = &quot;&quot; carry_number = &quot;&quot; operation = &quot;&quot; while first_number == &quot;a&quot;: first_number = float(input(&quot;Enter your first number: &quot;)) operation = input(&quot;You can enter c to exit calculator \nWhat operation? &quot;) second_number = float(input(&quot;What is your second number? &quot;)) if operation == &quot;+&quot;: carry_number = (first_number + second_number) elif operation == &quot;-&quot;: carry_number = (first_number - second_number) elif operation == &quot;/&quot;: carry_number = (first_number / second_number) elif operation == &quot;*&quot;: carry_number = (first_number * second_number) print(first_number, operation, second_number, &quot;=&quot;, carry_number) first_number = carry_number while True: operation = input(&quot;You can enter c to exit calculator \nWhat operation? &quot;) if operation == &quot;c&quot;: quit() second_number = float(input(&quot;What is your second number? &quot;)) if operation == &quot;+&quot;: carry_number = (first_number + second_number) elif operation == &quot;-&quot;: carry_number = (first_number - second_number) elif operation == &quot;/&quot;: carry_number = (first_number / second_number) elif operation == &quot;*&quot;: carry_number = (first_number * second_number) print(first_number, operation, second_number, &quot;=&quot;, carry_number) first_number = carry_number </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T15:19:16.747", "Id": "520118", "Score": "1", "body": "Welcome and thanks for joining CodeReview! I hope that you get some good feedback; this is a great first question." } ]
{ "AcceptedAnswerId": "263458", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T14:43:10.593", "Id": "263456", "Score": "4", "Tags": [ "python", "beginner" ], "Title": "Calculator for basic arithmetic operations" }
263456
accepted_answer
[ { "body": "<ul>\n<li>Notice that you have a bunch of repeated code; let's reduce this</li>\n<li>There's no need to pre-initialize your variables in the first five lines of your code</li>\n<li>Your first <code>while</code> loop doesn't deserve to exist; the condition is only evaluated <code>True</code> once</li>\n<li>No need to surround your operations in parens</li>\n</ul>\n<p>There's a lot of other things you could do to improve this, but without getting too advanced, you could write this to be as simple as</p>\n<pre><code># Beginning calculator code\n\nfirst_number = float(input('Enter your first number: '))\n\nwhile True:\n print('You can enter c to exit calculator')\n operation = input('What operation? ')\n if operation == 'c':\n quit()\n \n second_number = float(input('What is your second number? '))\n if operation == '+':\n carry_number = first_number + second_number\n elif operation == '-':\n carry_number = first_number - second_number\n elif operation == '/':\n carry_number = first_number / second_number\n elif operation == '*':\n carry_number = first_number * second_number\n\n print(first_number, operation, second_number, '=', carry_number)\n first_number = carry_number\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T17:20:01.033", "Id": "520131", "Score": "0", "body": "First off thank you for the explanation. It made sense to me right away when you wrote it like that. So when you said I don't need to pre-initialize the variables you meant the lines that I wrote \"first number = second number = etc..\". The program automatically can keep track of the values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T17:21:02.623", "Id": "520132", "Score": "1", "body": "Lines like `first_number = \"a\"` that get overwritten before they're read." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T15:32:20.587", "Id": "263458", "ParentId": "263456", "Score": "4" } } ]
<p>I need to know if there is any way I can optimize my code so that it does not use 0.6% of my total memory - which is approx. 22.4MB. This is a really small script that runs for as long as the raspberry pi is ON. 22.4MB for this basic, simple, light code is too much. If less or no optimization is there, then please let me know how 22.4MB is justified.</p> <p>I am pasting the htop screenshot and my full script.</p> <p><a href="https://i.stack.imgur.com/XKwmP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XKwmP.png" alt="htop" /></a></p> <pre><code>from gpiozero import CPUTemperature from time import sleep, time from requests import post class TemperatureBot: def __init__(self): self.lastAlertSent = -1 self.chatId = &quot;123&quot; self.botToken= &quot;123&quot; self.temperatureThreshold = 60 self.alertInterval = 300 alertResp = self.sendAlertToUser(f&quot;Initializing temperature bot for 123 - &quot; \ f&quot;your pi&quot;) if alertResp is not True: print(&quot;Could not initialize bot for 123. Try later.&quot;) return self.temperaturePolling() def sendAlertToUser(self, alertMsg): try: url=f&quot;https://api.telegram.org/bot{self.botToken}&quot;\ f&quot;/sendMessage?chat_id={self.chatId}&amp;text={alertMsg}&quot; r = post(url,timeout=20) if(r.status_code &gt;=400): print(&quot;Error sending alert. Here's the response: &quot;, r.text) return False return True except Exception as e: raise e def temperaturePolling(self): try: while(True): currentTemp = CPUTemperature().temperature if(currentTemp &gt; self.temperatureThreshold): if(time() - self.lastAlertSent &gt; self.alertInterval): alertResp = self.sendAlertToUser(f&quot;Temperature Danger: &quot;\ f&quot;{currentTemp}°C. &quot;\ f&quot;Please cool your Stan &quot;\ f&quot;or it will burn!!&quot;) if alertResp == True: self.lastAlertSent = time() else: print(&quot;Could not send alert message.&quot;) continue sleep(30) except KeyboardInterrupt: pass if __name__ == &quot;__main__&quot;: TemperatureBot() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T23:51:13.083", "Id": "520155", "Score": "2", "body": "I don't think it'll get much lower - at least on my system, `python -c 'import requests, time; time.sleep(600)' &` uses similar amounts of memory even though all it does is import `requests` and go to sleep" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T20:38:35.590", "Id": "520418", "Score": "0", "body": "@SaraJ I thought there was something wrong in my code login which is taking too much memory but it's them libraries! Thanks for demonstration!" } ]
{ "AcceptedAnswerId": "263475", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T22:14:08.803", "Id": "263471", "Score": "6", "Tags": [ "python", "memory-optimization", "raspberry-pi", "status-monitoring", "telegram" ], "Title": "Python script which sends telegram message if Raspberry Pi's temperature crosses 60 °C" }
263471
accepted_answer
[ { "body": "<ul>\n<li><code>chatId</code> -&gt; <code>chat_id</code> and similar for other members and method names, by PEP8 standard</li>\n<li><code>f&quot;Initializing temperature bot for 123 - &quot;</code> does not need to be an f-string - it has no fields</li>\n<li>if <code>alertResp</code> is not true, you should be raising an exception, not early-returning</li>\n<li><code>if alertResp is not True</code> is equivalent to <code>if not alertResp</code></li>\n<li><code>temperaturePolling</code> should not be called from your constructor - the constructor is only for initialization</li>\n<li><code>post</code> returns a response that should be used in a <code>with</code> context manager</li>\n<li><code>status_code &gt;= 400</code> can safely be replaced with <code>r.ok</code>, or better yet <code>r.raise_for_status()</code></li>\n<li><code>except Exception as e: raise e</code> should be deleted entirely</li>\n<li><code>except KeyboardInterrupt: pass</code> is fine <em>if</em> it's done at the upper level, but not in your polling routine</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T19:33:52.917", "Id": "520188", "Score": "0", "body": "> \"except Exception as e: raise e should be deleted entirely\"\n.\n\nBut we have to catch after a try block, so how do we do that if we remove the block entirely?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T19:34:47.030", "Id": "520189", "Score": "1", "body": "Remove the `try` as well. It's not helping you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T19:42:24.833", "Id": "520192", "Score": "0", "body": "Thanks @Reinderien, have made the changes and made a note of the same for future. BTW, when I'm calling this polling routine at the upper level(say pollingCaller), the code gets stuck in the while loop of this polling routine and the code following the pollingCaller doesn't get executed. In your experience do you have any solutions to that? Or should I ask that as a separate question on stackexchange?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T19:43:19.557", "Id": "520193", "Score": "0", "body": "Under what conditions does the polling loop end? What kind of code would execute after?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T19:52:23.093", "Id": "520196", "Score": "0", "body": "This script I am planning to run it as a cron job on system reboot. @reboot thingy. So I don't think that the polling loop ever ends (as long as the system is ON). The code that is followed by the polling calling is telegram bot codes, basically some listeners, callbacks. Please have a glimpse here:\nhttps://pastebin.com/5y6Rs8xe" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T20:37:58.833", "Id": "520199", "Score": "0", "body": "That doesn't make sense. If the polling loop never ends, why have code after it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T20:37:03.363", "Id": "520417", "Score": "0", "body": "I resolved the problem by using two separate python scripts using cron job: One for pollingCaller and the second one for temperatureBot. Both do polling until system turns off and both are separated completely - no correlation anymore." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T02:01:41.703", "Id": "263475", "ParentId": "263471", "Score": "3" } } ]
<p>I want to compare 2 images using <code>numpy</code>. This is what I have got so far. One of the outputs should be a white image with black pixels where pixels are different.</p> <p>I am sure it's possible to make it more efficient by better use of numpy, e.g. the <code>for</code> loop can be avoided. Or maybe there is a function/package that has implemented something similar already?</p> <pre><code> import gc import PIL import numpy as np def compare_images(image_to_test_filename, image_benchmark_filename): print('comparing', image_to_test_filename, 'and', image_benchmark_filename) image_benchmark = plt.imread(image_benchmark_filename) image_to_test = plt.imread(image_to_test_filename) assert image_to_test.shape[0] == image_benchmark.shape[0] and image_to_test.shape[1] == image_benchmark.shape[1] diff_pixel = np.array([0, 0, 0], np.uint8) true_array = np.array([True, True, True, True]) diff_black_white = np.zeros([image_benchmark.shape[0], image_benchmark.shape[1], 3], dtype=np.uint8) + 255 is_close_pixel_by_pixel = np.isclose(image_to_test, image_benchmark) nb_different_rows = 0 for r, row in enumerate(is_close_pixel_by_pixel): diff_indices = [c for c, elem in enumerate(row) if not np.all(elem == true_array)] if len(diff_indices): diff_black_white[r][diff_indices] = diff_pixel nb_different_rows += 1 dist = np.linalg.norm(image_to_test - image_benchmark) / (image_to_test.shape[0] * image_to_test.shape[1]) if nb_different_rows &gt; 0: print(&quot;IS DIFFERERENT! THE DIFFERENCE IS (% OF ALL PIXELS)&quot;, dist * 100) im = PIL.Image.fromarray(diff_black_white) im.save(image_to_test_filename+'_diff.png') del im del image_benchmark del image_to_test del diff_black_white gc.collect() return dist, None </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T15:18:31.050", "Id": "520170", "Score": "0", "body": "@Reinderien done!" } ]
{ "AcceptedAnswerId": "263497", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T14:30:43.343", "Id": "263487", "Score": "2", "Tags": [ "python", "numpy" ], "Title": "Efficient Comparison Of Two Images Using Numpy" }
263487
accepted_answer
[ { "body": "<p>First, this of course depends on your definition of different. I believe right now that your comparison is far too strict, given the defaults for <code>isclose</code>. I did a trivial modification of a .jpg, and with one decode/encode pass it still produced 6% of pixels with an RGB distance of more than 20. <code>isclose</code> applies both a relative and absolute tolerance, but it's probable that for your purposes absolute-only is simpler.</p>\n<p>I find f-strings a more natural form of string formatting because the in-line field expressions remove any need of your eyes to scan back and forth between field placeholder and expression. This does not impact performance. Also note the use of <code>%</code> in this context removes the need to divide by 100.</p>\n<p>PEP484 type hinting also does not impact performance, but makes the code more legible and verifiable.</p>\n<p>Note that it's &quot;almost never&quot; appropriate to <code>del</code> and <code>gc</code> yourself. The garbage collector is there for a reason, and in the vast, vast majority of cases, will act reasonably to free nonreferenced memory without you having to intervene. The one thing you should be doing here that you aren't is moving the images to a <code>with</code> for context management, which will guarantee resource cleanup on scope exit.</p>\n<p>This problem is fully vectorizable so should see no explicit loops at all. Just calculate a black-and-white distance from an absolute threshold in one pass. Your original implementation was taking longer to execute than I had patience for, but the following suggestion executes in less than a second:</p>\n<pre><code>import numpy as np\nfrom PIL import Image\nfrom matplotlib.pyplot import imread\n\n\n# Maximum allowable Frobenius distance in RGB space\nEPSILON = 20\n\n\ndef compare_images(\n image_to_test_filename: str,\n image_benchmark_filename: str,\n) -&gt; float:\n print(f'comparing {image_to_test_filename} and {image_benchmark_filename}')\n\n image_benchmark = imread(image_benchmark_filename)\n image_to_test = imread(image_to_test_filename)\n assert image_to_test.shape == image_benchmark.shape\n\n diff_black_white = (\n np.linalg.norm(image_to_test - image_benchmark, axis=2) &gt; EPSILON\n ).astype(np.uint8)\n n_different = np.sum(diff_black_white)\n\n if n_different &gt; 0:\n diff_fraction = n_different / image_benchmark.size\n print(f'IS DIFFERERENT! THE DIFFERENCE OF ALL PIXELS IS {diff_fraction:.2%}')\n im = Image.fromarray(diff_black_white * 255)\n im.save(f'{image_to_test_filename}_diff.png')\n\n dist = np.linalg.norm(image_to_test - image_benchmark) / image_benchmark.size\n return dist\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T10:48:55.167", "Id": "520213", "Score": "1", "body": "Thanks! I have found one more actually: image_benchmark.shape[0] * image_benchmark.shape[1] out to be image_benchmark.size, right? (this is 1). )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T10:50:10.400", "Id": "520214", "Score": "0", "body": "2. Could I ask why you prefer `print(f'comparing {i1} and {i2}')` over `print('comparing', i1, 'and', i2)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T10:51:04.847", "Id": "520215", "Score": "0", "body": "3. What would be the benefit of typing the inputs - is it the performance improvement? Is it significant in this case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T10:52:00.803", "Id": "520216", "Score": "0", "body": "np.linalg.norm along axis 2 is brilliant, I did not know it can be used like this, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T13:12:04.693", "Id": "520228", "Score": "1", "body": "Yes, `size` is better for this purpose; edited for the other points." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T19:31:02.993", "Id": "263497", "ParentId": "263487", "Score": "2" } } ]
<p>Playing on leetcode coding problem: &quot;Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.&quot;</p> <p>I realized that my understanding of Python was not so good. I always thought that: since list are mutable object they are kind of passed by reference; so i always try to make a copy of the list before feeding the function to avoid inappropriate behavour as i did below:</p> <pre><code>class Solution: def generateParenthesis(self, n: int) -&gt; List[str]: res = [] def add_parenthesis(l,o,f): if len(l)==2*n: res.append(&quot;&quot;.join(l)) return if f&lt;o: return if o&gt;0: lp = l.copy() lp.append(&quot;(&quot;) add_parenthesis(lp,o-1,f) if f&gt;0: lm = l.copy() lm.append(&quot;)&quot;) add_parenthesis(lm,o,f-1) add_parenthesis(['('],n-1,n) return res </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T12:59:26.410", "Id": "520288", "Score": "0", "body": "We can't review your friend's code here, nor do we explain how code works - you're expected to understand that if you wrote it! Additionally, your title should summarise the _problem being solved_ (e.g. \"Generate valid combinations of parentheses\") rather than the coding mechanism you used to achieve it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T13:27:55.013", "Id": "520290", "Score": "3", "body": "Ok i will make some changes!" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T11:50:58.157", "Id": "263547", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "balanced-delimiters" ], "Title": "Generate valid combinations of parentheses" }
263547
max_votes
[ { "body": "<p>In the future, for purposes for code review, please include an example case to run. This makes it easier for reviewers.</p>\n<pre><code>if __name__ == '__main__':\n all_solutions = Solution().generate_parentheses(4)\n print(all_solutions)\n</code></pre>\n<h2>Style</h2>\n<ul>\n<li>Your variable names are <code>l</code>, <code>o</code>, <code>f</code>, <code>p</code>, <code>m</code>, <code>lp</code>, <code>lm</code>, and <code>res</code>. Use descriptive names instead.</li>\n<li>Not all code needs comments, but algorithmic code usually does. Add an explanation of how this works.</li>\n<li>The <code>Solution</code> class doesn't do anything. Drop it, and just define your function directly.</li>\n</ul>\n<h2>Data structures</h2>\n<ul>\n<li>It's considered bad style to mutate variables not passed into the function. You're essentially using <code>res</code> as a global variable. Global variables are bad, for a variety of reasons. See if you can rewrite it without a global variable, and choose whichever you like better.</li>\n<li>Since you output a string at the end, go ahead and just pass around strings the whole time instead of lists. The main advantage of lists would be to avoid copying them, but you're already doing that everywhere.</li>\n<li>There are a <strong>lot</strong> of different ways to generate parentheses. You may consider writing a python <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator</a> instead, using <code>yield</code> or a generator expression. That way, you don't have to store a result list, which will matter for large values of <code>n</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T07:41:17.423", "Id": "269284", "ParentId": "263547", "Score": "1" } } ]
<p>I just want your opinion about that code! :)</p> <pre><code>import random class Error(Exception): def __init__(self, error=None): self.error = error def __str__(self): return str(self.error) class HashTable(object): def __init__(self): self.length = 20 self.keys = [] self.table = [[] for _ in range(self.length)] def __len__(self): return self.length def __setitem__(self, key, value): self.keys.append(key) hashed_key = self._hash(key) self.table[hashed_key].append((value)) #Wartosc jest dodawana do listy pod hashowanym indeksem def _hash(self, key) : return hash(key) % self.length def show_list(self): return self.table def __getitem__(self, key): for el in self.table[self._hash(key)]: if el[0] == key: return el[1] def __delitem__(self, key): for el in self.table[self._hash(key)]: if el[0] == key: self.table[self._hash(key)].remove(el) def __iter__(self): def Generator(data): mylist = [_ for _ in data] for i in mylist: yield i return Generator(self.table) L = HashTable() content = [] with open(&quot;song.txt&quot;, 'r', encoding = 'utf8') as travis: for line in travis: for word in line.split(): content.append(word) for c in content: L[c] = c for x in L: print(x) </code></pre> <p>I've also will be really greateful for any tips and how to improve this one! :D</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T14:40:50.200", "Id": "520398", "Score": "1", "body": "I'm going to assume that you're not using a built-in dictionary for learning purposes etc., but that would greatly simplify this code." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T13:39:10.687", "Id": "263552", "Score": "1", "Tags": [ "python", "reinventing-the-wheel", "hash-map" ], "Title": "Hashing Table in Python" }
263552
max_votes
[ { "body": "<p>My opinion is that you should test better, before asking for code review.</p>\n<pre><code>line = &quot; #Wartosc jest dodawana do listy pod hashowanym indeksem&quot;\nfor word in line.split():\n content.append(word)\nfor c in content:\n L[c] = c\nprint(L[&quot;jest&quot;])\n</code></pre>\n<p>Put a <code>print</code> statement inside each of your functions, for example <code>print('__getitem__ ran')</code>. Then keep modifying your test code until you see all of them. Right now you are not using all your methods.</p>\n<p>Edit: Also, this is not really something I will code review once tested. The correct review is to replace it with:</p>\n<pre><code>HashTable = dict\n</code></pre>\n<p>Both the readability and efficiency are miles better than yours!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-01T09:18:47.283", "Id": "266580", "ParentId": "263552", "Score": "1" } } ]
<p>I have this function:</p> <pre class="lang-py prettyprint-override"><code>import re def check_and_clean_sequence(sequence, alphabet): &quot;&quot;&quot; Function to check and clean up all ambiguous bases in a sequence. Ambigous bases are bases that are not in the sequence alphabet, ie. 'ACGT' for DNA sequences. Inputs: sequence - a string representing a DNA sequence. alphabet - set/string representing the allowed characters in a sequence. Outputs: cleaned_sequence - cleaned sequence or a string. &quot;&quot;&quot; if set(sequence).issubset(alphabet): return sequence else: return cleaning_ambiguous_bases(sequence) def cleaning_ambiguous_bases(sequence): &quot;&quot;&quot; Function to clean up all ambiguous bases in a sequence. Ambiguous bases are bases that are not in the sequence alphabet, ie. 'ACGT' for DNA sequences. Inputs: sequence - a string representing a DNA sequence. Outputs: integer - a new clean up string representing a DNA sequence without any ambiguous characteres. &quot;&quot;&quot; # compile the regex with all ambiguous bases pat = re.compile(r'[NRYWXSKM]') # look for the ambiguous bases and replace by # nothing new_seq = re.sub(pat, '', sequence) return new_seq </code></pre> <p>The performance in jupyter notebook with timeit is around:</p> <pre class="lang-none prettyprint-override"><code>%timeit check_and_clean_sequence(seq, iupac_dna) 200 ms ± 436 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) </code></pre> <p>This was calculated with a DNA sequence with 5539776 pb or 5539.776 kpb. The sequence can be downloaded from: <a href="https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/005/845/GCF_000005845.2_ASM584v2/GCF_000005845.2_ASM584v2_genomic.fna.gz" rel="nofollow noreferrer">E. coli genome</a></p> <p>The function receive a big string and check if there are any characters that are not in the allowed alphabet (in the case the IUPAC DNA = 'ACGT'). If the sequence has they are cleaned up and the function returns a new sequence, otherwise return the original one.</p> <p>Are there are tips or tricks to improve this time?</p> <p>Toy example:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; alphabet = 'ACGT' &gt;&gt;&gt; toy_sequence = 'AGCTAGGGACATTGAGGACCACCACAXYXMAAAAAA' &gt;&gt;&gt; check_and_clean_sequence(toy_sequence, alphabet) 'AGCTAGGGACATTGAGGACCACCACAAAAAAA' </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T17:23:38.417", "Id": "520327", "Score": "6", "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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T21:23:38.340", "Id": "520425", "Score": "2", "body": "Like I said before - please stop modifying (including adding) code in your post. If you have an updated version then you can create a new post and [edit] to add a link to it." } ]
{ "AcceptedAnswerId": "263589", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T14:30:27.030", "Id": "263553", "Score": "8", "Tags": [ "python", "python-3.x", "regex", "bioinformatics" ], "Title": "Filter out ambiguous bases from a DNA sequence" }
263553
accepted_answer
[ { "body": "<p>From the bioinformatics side, not the python one: Your return will be non-useful for further processing whenever an ambiguous base has been present, because it changes index locations! You'll want to fix that before worrying about how long it takes to run...</p>\n<p>DNA and RNA are themselves a form of coding language: three base units ('codons') describe amino acids. Whenever a base is deleted, a 'frameshift' occurs: every codon after that point now starts a space sooner than it should. (In vivo, a single frameshift mutation is usually sufficient to completely shut off one - or more! - genes. In other words, this is not a trivial situation.) <strong>You cannot <em>interpret</em> genetic sequences correctly if you change the index location of the bases!</strong></p>\n<p>There are three paths to usefully 'cleaning' your genome information, depending on why you wanted to do that in the first place:</p>\n<ol>\n<li><p>If space is at a premium:</p>\n<p>Drawing from Kraigolas: use the code as described, but rather than replacing with the empty string, replace with a uniform &quot;this base is ambiguous&quot; marker, thus maintaining index locations. ('N' is the standard for this specific application.)</p>\n<pre><code> pattern = re.compile(r&quot;[^ACGT]&quot;)\n print(pattern.sub(&quot;N&quot;, toy_sequence))\n</code></pre>\n<p>Another solution in this vein is to store bases as tuples of (index [type:int], base type [could handle a number of ways]) but this is probably space-inefficient</p>\n</li>\n<li><p>If neither space nor preprocessing are an optimization concern: Don't do any deletion or substitution of these characters at all.</p>\n<p>Look at the documentation related to the source of your sequences; there will either be an interpretation key for their specific method <a href=\"https://genomevolution.org/wiki/index.php/Ambiguous_nucleotide\" rel=\"nofollow noreferrer\">or they'll be using the standard lookup table</a>.\nWhen a subsequent step will be to interpret a sequence into an amino acid string (likely application) or to look for &quot;similar&quot; sequences in a database (also a likely application), knowing the difference between the code that means &quot;either A or T&quot; and the code that means &quot;either C or G&quot; will <em>save</em> you processing time and/or get less ambiguous <em>results</em>.</p>\n</li>\n<li><p>If preprocessing is a concern:</p>\n<p>As in 2, refer to the appropriate <a href=\"https://genomevolution.org/wiki/index.php/Ambiguous_nucleotide\" rel=\"nofollow noreferrer\">lookup table</a> for what ambiguous codes mean.\nRead your sequence into a [length of sequence]x4 array of binary values.\nColumn 1 is &quot;can be A?&quot;, column 2 is &quot;can be T?&quot;, etc. -</p>\n<p>Example: AGCCNCS would become</p>\n<pre><code> 1 0 0 0\n 0 0 1 0\n 0 0 0 1\n 0 0 0 1\n 1 1 1 1\n 0 0 0 1\n 0 0 1 1\n</code></pre>\n<p>As appropriate codon matches (there are almost always more than one) for specific amino acids can be easily described in the same way, it's relatively trivial to use this format for a variety of purposes, and it removes assorted other headaches with accurately interpreting the ambiguous codes.</p>\n<p>(For examples of how to apply them - treating the bin as if they're integers, if the dot product of each row in two sequence matrixes is at least 1, you have a 'match' of codes!)</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T20:32:54.567", "Id": "520416", "Score": "0", "body": "Man you totally right I just having a hard time coding this kmers count functions efficiently. I know there are a lot of tools out there but I am learning python them I need to code to learn! Then I am write my own code! But some times some obvious details get out of control. Thanks to you I avoid a big mistake. Thank you a lot. I will go back to basics and use something like if set(kmer).issubset(set(alphabet)) to avoid ambiguous kmers in the final counts. This way I will keep all the indexes corrects. Thank you a lot! Its better a slow and correct code than a quick and wrong one. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T16:02:03.740", "Id": "263589", "ParentId": "263553", "Score": "7" } } ]
<p>Consider the infinite sequence <code>u</code>, where <code>u</code> is defined as follows:</p> <ul> <li>The number <code>u(0) = 1</code> is the first one in <code>u</code>.</li> <li>For every <code>x</code> in <code>u</code>, then <code>y = 2 * x + 1</code> and <code>z = 3 * x + 1</code> are also in <code>u</code>.</li> <li>There are no other numbers in <code>u</code>.</li> <li><code>u</code> is sorted in increasing order, with no duplicates</li> </ul> <h4>The sequence:</h4> <blockquote> <pre><code>u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, …… ] </code></pre> </blockquote> <p>1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on...</p> <h4>Task:</h4> <p>Given parameter <code>n</code>, the function <code>dbl_linear</code> (or <code>dblLinear</code>...) returns the element <code>u(n)</code> of the ordered sequence <code>u</code>.</p> <h1>The code:</h1> <pre><code>def dbl_linear(n): u = [1] if n &gt; 0: y, z = 2*1+1, 3*1+1 u.append(y), u.append(z) for i in range(1,n): y, z = u[i]*2+1, u[i]*3+1 u.append(y), u.append(z) u = sorted(u) u = sorted(list(set(u))) return u[n] </code></pre> <p>The code passed the initial tests, but failed others due to execution timing out. Can I optimize the code (or algorithm) to increase speed?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T06:52:29.067", "Id": "520360", "Score": "5", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T06:41:34.227", "Id": "263573", "Score": "1", "Tags": [ "python", "python-3.x", "time-limit-exceeded" ], "Title": "Compute members of the infinite series generated by 2n+1 and 3n+1" }
263573
max_votes
[ { "body": "<h1>Algorithm</h1>\n<p>Because we keep all the duplicates until we've finished generating the list, we're doing much more work than we need to. For each number we reach, we generate two more, and since we're not merging duplicates at that time, that means our work scales as O(2ⁿ). Merging as we go (as <a href=\"/a/263585/75307\">recommended by Kraigolas</a>) reduces that, and reduces the storage required to O(n).</p>\n<h1>Implementation</h1>\n<p>Since there's only one sequence, but we may want to access it several times during the program, it's worth memoizing the work done so far, to avoid repeating the calculations. We just need to keep the sorted set of results, and the position up to which we have computed additional elements for.</p>\n<h1>Alternative algorithm</h1>\n<p>It might be worth considering working from the result set: consider every number in turn and decide whether it's a member of the sequence (<code>x</code> is a member only if either of <code>(x-1)/2</code> and <code>(x-1)/3</code> is a member). This requires only the members of the sequence up to <code>x</code> to be stored.</p>\n<p>That approach would look something like this:</p>\n<pre><code>import bisect\nimport itertools\n\nu = [1] # The sequence\n\ndef contains(a, x):\n &quot;&quot;&quot;\n True if sorted list a contains element x\n &gt;&gt;&gt; contains([1, 2, 3, 4], 2)\n True\n &gt;&gt;&gt; contains([1, 2, 3, 4], 5)\n False\n &quot;&quot;&quot;\n i = bisect.bisect_left(a, x)\n return i != len(a) and a[i] == x\n\ndef dbl_linear(n):\n &quot;&quot;&quot;\n Finds the nth element from the list beginning with 1,\n where 2n+1 and 3n+1 are members for each n that's a member\n\n &gt;&gt;&gt; dbl_linear(0)\n 1\n &gt;&gt;&gt; dbl_linear(1)\n 3\n &gt;&gt;&gt; dbl_linear(2)\n 4\n &gt;&gt;&gt; dbl_linear(10)\n 22\n &quot;&quot;&quot;\n global u\n if n &lt; len(u):\n return u[n]\n for x in itertools.count(u[-1]+1):\n if contains(u, (x-1)/2) or contains(u, (x-1)/3):\n u += [x]\n if n &lt; len(u):\n return u[n]\n\n\n\nif __name__ == &quot;__main__&quot;:\n import doctest\n doctest.testmod()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T07:01:07.990", "Id": "263613", "ParentId": "263573", "Score": "1" } } ]
<p>This code solves <a href="https://projecteuler.net/problem=35" rel="nofollow noreferrer">Project Euler problem 35</a>:</p> <blockquote> <p>The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million?</p> </blockquote> <pre class="lang-py prettyprint-override"><code>from collections import deque def sieve(limit): nums = [True] * (limit+1) nums[0] = nums[1] = False for i, is_prime in enumerate(nums): if is_prime: yield i for n in range(i*i, limit+1, i): nums[n] = False def rotations(n): l = deque(list(str(n))) r = [] for _ in range(len(l)): r.append(int(&quot;&quot;.join(list(l)))) l.rotate() return r def circular_prime(n): cp = [] s = list(sieve(n)) for i in s: r = rotations(i) flags = [False] * len(r) for k, j in enumerate(r): if j in s: flags[k] = True if all(flags): print(i) cp.append(i) return len(cp) print(circular_prime(1000000)) </code></pre> <p>How can I speed it up? It takes too long if I run it with standard Python interpreter. However, I am able to reduce execution time to 13 seconds by running in &quot;pypy&quot; interpreter.</p>
[]
{ "AcceptedAnswerId": "263584", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T12:21:38.283", "Id": "263583", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "primes" ], "Title": "Count prime numbers whose rotations are all prime" }
263583
accepted_answer
[ { "body": "<h3>Don't check if there are even digits</h3>\n<p>Add</p>\n<pre><code>if n&lt;10:\n return [n]\nif any(even in str(n) for even in &quot;02468&quot;):\n return []\n</code></pre>\n<p>into <code>rotations</code>, because every number (except for 2) with the last even digit will not be prime, there's no sense in generating rotations for those.</p>\n<h3>Avoid excessive conversions</h3>\n<p><code>l = deque(str(n))</code> - no <code>list</code> conversion needed\nAlso check string slices - you can do rotations just with them, not the deque.</p>\n<h3>Avoid changing the collection while you're iterating over it</h3>\n<pre><code>for i, is_prime in enumerate(nums):\n ...\n nums[n] = False\n</code></pre>\n<p>is bad. Refactor it - maybe into while loop.</p>\n<h3>Use list comprehensions</h3>\n<p><code>flags</code> variable is clearly a mess. Let's see...</p>\n<pre><code> flags = [False] * len(r)\n for k, j in enumerate(r):\n flags[k] = j in s #True for True, False for False\n if all(flags):\n</code></pre>\n<p>Ok, now move it into the initialization of flags.</p>\n<pre><code> flags = [j in s for k,j in enumerate(r)]\n if all(flags):\n</code></pre>\n<p>k is not needed. And flags too:</p>\n<pre><code> if all(j in s for j in r):\n</code></pre>\n<p>This looks better and works faster - because it stops after the first False. But now we don't need r:</p>\n<pre><code> if all(j in s for j in rotations(i)):\n</code></pre>\n<p>And now you can rewrite <code>rotations</code> to use <code>yield</code> instead of creating the list. This will be much faster.</p>\n<h3>Don't transform the sieve into the list</h3>\n<p>You spend time and memory for nothing. Work with the sieve, not with the list. Searching in the sieve will be <span class=\"math-container\">\\$O(1)\\$</span>, not <span class=\"math-container\">\\$O(n)\\$</span> (<code>if s[j]</code> instead of <code>if j in s</code>). The <code>for i</code> loop now will be over the whole range (2..n), skipping if not s[i].</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T14:03:54.000", "Id": "520391", "Score": "0", "body": "Really appreciate the detailed review. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T04:16:59.823", "Id": "520451", "Score": "3", "body": "Not only if there are even digits! A 5 is bad in any multi-digit, since rotations will eventually move the 5 to the end, and form a multiple of 5. The only viable digits are 1, 3, 7, and 9. Ie, `n < 10 or set(str(n)) <= {'1', '3', '7', '9'}`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T13:16:58.550", "Id": "263584", "ParentId": "263583", "Score": "5" } } ]
<p>I have implemented a correct version of DFS (with comments explaining the implementation):</p> <pre><code>from lark import Lark, tree, Tree, Token def dfs(root_node : Tree, f) -&gt; Tree: &quot;&quot;&quot; To do DFS we need to implement a stack. In other words we need to go down the depth until the depth has been fully processed. In other words what you want is the the current child you are adding to the dequeue to be processed first i.e. you want it to skip the line. To do that you can append to the front of the queue (with append_left and then pop_left i.e. pop from that same side). :param root_node: :param f: :return: &quot;&quot;&quot; dq = deque([root_node]) while len(dq) != 0: current_node = dq.popleft() # to make sure you pop from the front since you are adding at the front. current_node.data = f(current_node.data) # print(current_node.children) for child in reversed(current_node.children): dq.appendleft(child) return root_node </code></pre> <p>with unit test:</p> <pre><code> print() # token requires two values due to how Lark works, ignore it ast = Tree(1, [Tree(2, [Tree(3, []), Tree(4, [])]), Tree(5, [])]) # the key is that 3,4 should go first than 5 because it is DFS dfs(ast, print) </code></pre> <p>the output is as I expected it:</p> <pre><code>1 2 3 4 5 </code></pre> <p>however, it looks rather strange to have a <code>reversed</code> in the code (plus it looks inefficient unless the list is implemented with a head and tail pointer list). How does one change this code so that it looks like the standard &quot;append to the end and pop from the same end&quot;. Doing that blindly however for trees leads to wrong printing:</p> <pre><code>def dfs_stack(ast : Tree, f) -&gt; Tree: stack = [ast] while len(stack) != 0: current_node = stack.pop() # pop from the end, from the side you are adding current_node.data = f(current_node.data) for child in current_node.children: stack.append(child) return ast </code></pre> <p>see output:</p> <pre><code>1 5 2 4 3 </code></pre> <p>note my second implementation is based on <a href="https://codereview.stackexchange.com/questions/247368/depth-first-search-using-stack-in-python?newreg=d2760a7347504f6ebadfd329d6f127ca">Depth First Search Using Stack in Python</a> which is for graphs. Perhaps the reason I need to reverse it is because I am traversing a tree where the children ordering matters but the children ordering does not matter in a graph and it makes that code look cleaner (so there is no clear way of how to add for a graph but the invariant of &quot;traversing the children before the siblings&quot; is respected just not in the order I'd expect for trees).</p> <p>Is there a way to remove the <code>reversed</code> so that the code is still correct and it looks more similar to the standard DFS?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T22:22:07.280", "Id": "263604", "Score": "1", "Tags": [ "python", "tree", "depth-first-search" ], "Title": "How does one write DFS in python with a Deque without reversed for Trees?" }
263604
max_votes
[ { "body": "<blockquote>\n<p>Doing that blindly however for trees leads to wrong printing</p>\n</blockquote>\n<p>No surprise here. In the initial version the deque functions like a stack, so when you change it to the honest-to-goodness stack nothing changes: you still need to push children nodes in the reverse order (stack is last-in-first-out, so the last child pushed will be processed first).</p>\n<p>There are few options avoid reversal.</p>\n<ul>\n<li><p>A plain old recursion.</p>\n</li>\n<li><p>If the goal is to not recurse, don't push a list of children. Push generators instead.</p>\n</li>\n</ul>\n<p>Edit:</p>\n<p>A quick-and-dirty example with generators:</p>\n<pre><code>def generate_children(node):\n for child in node.children:\n yield child\n\ndef dfs(node):\n print(node.data)\n stk = [generate_children(node)]\n\n while stk:\n try:\n child = next(stk[-1])\n print(child.data)\n stk.append(generate_children(child))\n except StopIteration:\n stk.pop()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T22:56:14.520", "Id": "520439", "Score": "0", "body": "how do you \"push generators\" or what does that mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T23:16:23.847", "Id": "520440", "Score": "0", "body": "For every node you could define a generator, which `yield`s the node's children one by one in order. See edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T09:30:04.890", "Id": "520462", "Score": "0", "body": "FWIW you'd need an iterator, which a generator is a subclass of. You can just replace `generate_children(child)` with `iter(child.children)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T17:44:45.980", "Id": "520507", "Score": "0", "body": "@vnp thanks for the comment \"stack is last-in-first-out, so the last child pushed will be processed first\" that makes sense! I am glad that my reverse sorting is correct + efficient. Perhaps if I had a way to loop backwards without reversing that would be nice. I guess that is what `reversed` does since it returns an iterator." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T22:48:38.897", "Id": "263606", "ParentId": "263604", "Score": "2" } } ]
<p>CodeSignal put out a challenge by Uber that involves writing a &quot;fare estimator&quot; that involves a function dependent on cost per minute, cost per mile, ride time and ride distance.</p> <p>The formula is along the lines of:</p> <pre><code>fare = (cost per minute) * (ride time) + (cost per mile) * (ride distance) </code></pre> <p>where <code>ride time</code> and <code>ride distance</code> are constant integers (or floats) and <code>cost per minute</code> and <code>cost per mile</code> are lists of integers and floats (as cost per minute and cost per mile depend on the car type).</p> <p>This is my solution:</p> <pre><code>def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile): y, f = [], lambda w, x, y, z: (w * x) + (y * z) for a, b in zip(cost_per_minute, cost_per_mile): y.append(f(a, ride_time, b, ride_distance)) return y </code></pre> <p>I'm just looking for any kind of feedback on the code. Is there a better way to implement it? Can you recommend better coding styles? Is my algorithm good or is it a steaming pile of wank? Leave any feedback you want!</p> <p>You can check out the full challenge here (but you might need to sign up): <a href="https://app.codesignal.com/company-challenges/uber/HNQwGHfKAoYsz9KX6" rel="nofollow noreferrer">https://app.codesignal.com/company-challenges/uber/HNQwGHfKAoYsz9KX6</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T19:40:26.973", "Id": "520510", "Score": "1", "body": "Can you show how you expect the function to be called? In particular, it helps to know what types the arguments will be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T23:13:35.347", "Id": "520525", "Score": "0", "body": "It's just called by an external code judge (I didn't implement a main function)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T04:49:07.720", "Id": "520535", "Score": "0", "body": "Ah, sorry, I see you have described the types of the arguments in the paragraph above the code." } ]
{ "AcceptedAnswerId": "263638", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T17:21:41.857", "Id": "263636", "Score": "1", "Tags": [ "python-3.x", "programming-challenge", "lambda", "community-challenge" ], "Title": "An implementation of Uber's \"Fare Estimator\" [CodeSignal]" }
263636
accepted_answer
[ { "body": "<p>Here are a few tips:</p>\n<ul>\n<li><p>Unless it makes the code easier to read, avoid multiple assignments in one line. making your code shorter does not necessarily make it better, faster nor more maintainable.</p>\n</li>\n<li><p>Give better names to your variables</p>\n</li>\n<li><p>Use <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a></p>\n</li>\n</ul>\n<p>So, your code could be changed to this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterable\n\ndef fareEstimator(ride_time: float, ride_distance: float, cost_per_minute_list: Iterable[float],\n cost_per_mile_list: Iterable[float]) -&gt; Iterable[float]:\n result = []\n\n def calculateFare(ride_time: float, ride_distance: float, cost_per_minute: float,\n cost_per_mile: float) -&gt; float:\n return ride_time*cost_per_minute + ride_distance*cost_per_mile\n\n for cost_per_minute, cost_per_mile in zip(cost_per_minute_list, cost_per_mile_list):\n result.append(calculateFare(ride_time, ride_distance, cost_per_minute, cost_per_mile))\n\n return result\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T18:50:13.297", "Id": "263638", "ParentId": "263636", "Score": "3" } } ]
<pre><code>if __name__ == '__main__': url='http://pokemondb.net/pokedex/all' #Create a handle, page, to handle the contents of the website page = requests.get(url) #Store the contents of the website under doc doc = lh.fromstring(page.content) #Parse data that are stored between &lt;tr&gt;..&lt;/tr&gt; of HTML tr_elements = doc.xpath('//tr') # Create empty list col = [] # For each row, store each first element (header) and an empty list for t in tr_elements[0]: name = t.text_content() col.append((name, [])) # Since out first row is the header, data is stored on the second row onwards for j in range(1, len(tr_elements)): # T is our j'th row T = tr_elements[j] # If row is not of size 10, the //tr data is not from our table if len(T) != 10: break # i is the index of our column i = 0 # Iterate through each element of the row for t in T.iterchildren(): data = t.text_content() # Check if row is empty if i &gt; 0: # Convert any numerical value to integers try: data = int(data) except: pass # Append the data to the empty list of the i'th column col[i][1].append(data) # Increment i for the next column i += 1 Dict = {title: column for (title, column) in col} df = pd.DataFrame(Dict) </code></pre> <p>In the above code, I am calling an API and storing the data in tr_elements, and then by using for loop I am trying to append the headers(names of columns) and empty list to col list then I am iterating through each element of tr_elements and appending to the empty list (col list created before) after converting any numerical data to an integer type. In the end, I am creating a dictionary and then converting it to a data frame (screenshot attached). So, I want to know if I can write the above code more efficiently in a pythonic way?</p> <p><a href="https://i.stack.imgur.com/A38fn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A38fn.png" alt="Screen shot of final data frame after running my code" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T15:32:09.737", "Id": "520565", "Score": "0", "body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-03T02:48:06.960", "Id": "520701", "Score": "0", "body": "Please include your imports." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-03T02:49:08.300", "Id": "520702", "Score": "0", "body": "Why is it going to Pandas?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-03T02:50:08.850", "Id": "520703", "Score": "0", "body": "Finally: no, you're not calling an API; you're scraping a web page." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T15:29:15.147", "Id": "263671", "Score": "3", "Tags": [ "python", "web-scraping", "pandas", "pokemon" ], "Title": "Collect Pokémon from a URL and store them in a dataframe" }
263671
max_votes
[ { "body": "<ul>\n<li>Not having any idea what <code>lh</code> is, I can't recommend using it over BeautifulSoup</li>\n<li>Your main guard is a good start, but you should write some actual methods</li>\n<li>Use <code>https</code> unless you have a really, really, really good reason</li>\n<li>Don't blindly attempt to convert every single cell to an integer - you know which ones should and should not have ints so use that knowledge to your advantage</li>\n<li>Never <code>except/pass</code></li>\n<li>The table does not have jagged cells, so use of a proper selector will not need your length-ten check</li>\n<li>Don't use j-indexing into the rows - just iterate over search results. Also, selecting only rows in the <code>tbody</code> will obviate your one-row index skip</li>\n<li>Don't capitalize local variables like <code>Dict</code></li>\n<li>Consider using the data's <code>#</code> as the dataframe index</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from typing import Iterable, Dict, Any\n\nimport pandas as pd\nimport requests\nfrom bs4 import Tag, BeautifulSoup\n\n\ndef get_page_rows() -&gt; Iterable[Dict[str, Tag]]:\n with requests.get('https://pokemondb.net/pokedex/all') as resp:\n resp.raise_for_status()\n doc = BeautifulSoup(resp.text, 'lxml')\n\n table = doc.select_one('table#pokedex')\n heads = [th.text for th in table.select('thead th')]\n\n for row in table.select('tbody tr'):\n yield dict(zip(heads, row.find_all('td')))\n\n\ndef tags_to_dict(row: Dict[str, Tag]) -&gt; Dict[str, Any]:\n data = {\n k: int(row[k].text)\n for k in (\n # Skip Total - it's a computed column\n 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed',\n )\n }\n data.update((k, row[k].text) for k in ('#', 'Name'))\n\n return data\n\n\nif __name__ == '__main__':\n df = pd.DataFrame.from_records(\n (tags_to_dict(row) for row in get_page_rows()),\n index='#',\n )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-03T03:26:47.153", "Id": "263713", "ParentId": "263671", "Score": "1" } } ]
<p>I want to move all markdown (.md) files from one folder to another. The folder structure I have:</p> <pre><code>. |-- Root11 | |-- FolderOne | | |-- file1.md | | |-- file1.txt | | |-- file2.md | | |-- file2.txt | | |-- file3.md | | |-- file3.txt | | |-- file4.md | | |-- file4.txt | | |-- file5.md | | `-- file5.txt | `-- FolderTwo |-- Root12 | |-- FolderOne | | |-- file1.md | | |-- file1.txt | | |-- file2.md | | |-- file2.txt | | |-- file3.md | | |-- file3.txt | | |-- file4.md | | |-- file4.txt | | |-- file5.md | | `-- file5.txt | `-- FolderTwo |-- Root13 | |-- FolderOne | | |-- file1.md | | |-- file1.txt | | |-- file2.md | | |-- file2.txt | | |-- file3.md | | |-- file3.txt | | |-- file4.md | | |-- file4.txt | | |-- file5.md | | `-- file5.txt | `-- FolderTwo |-- Root14 | |-- FolderOne | | |-- file1.md | | |-- file1.txt | | |-- file2.md | | |-- file2.txt | | |-- file3.md | | |-- file3.txt | | |-- file4.md | | |-- file4.txt | | |-- file5.md | | `-- file5.txt | `-- FolderTwo `-- Root15 |-- FolderOne | |-- file1.md | |-- file1.txt | |-- file2.md | |-- file2.txt | |-- file3.md | |-- file3.txt | |-- file4.md | |-- file4.txt | |-- file5.md | `-- file5.txt `-- FolderTwo 15 directories, 50 files </code></pre> <p>In the above scenario, I want to move all markdown (.md) files from <code>FolderOne</code> to <code>FolderTwo</code> under folders <code>Root11</code> to <code>Root15</code>.</p> <p>The current code I have in Python:</p> <pre><code>cur_path = os.getcwd() outer_folder_path = f&quot;{cur_path}\\root\\&quot; folder1 = &quot;FolderOne&quot; folder2 = &quot;FolderTwo&quot; root_dir, root_folders, _ = next(os.walk(outer_folder_path)) for root_folder in root_folders: root_folder = os.path.join(root_dir, root_folder) folder_path, folder_with_name_folders, _ = next(os.walk(root_folder)) for folder_with_name_folder in folder_with_name_folders: if folder_with_name_folder == folder1: check_this_folder = os.path.join(folder_path, folder_with_name_folder) file_path, _, files = next(os.walk(check_this_folder)) for _file in files: if _file.endswith(&quot;.md&quot;): input_file = os.path.join(file_path, _file) ouput_file = input_file.replace(folder1, folder2) os.rename(input_file, ouput_file) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T23:37:47.610", "Id": "520614", "Score": "2", "body": "I suspect the `pathlib` module would simplify things a lot for your task: `for path in pathlib.Path(outer_folder_path).rglob('*.md'): ...`" } ]
{ "AcceptedAnswerId": "263712", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T18:40:41.607", "Id": "263679", "Score": "1", "Tags": [ "python", "python-3.x", "file-system" ], "Title": "Move all markdown files from one folder to another in Python" }
263679
accepted_answer
[ { "body": "<p>As @FMc suggests, the sugar in <code>pathlib</code> will make this much easier. Even if you weren't to use it, the old glob methods are preferred over your iterate-and-check.</p>\n<p>This can be as simple as</p>\n<pre><code>from pathlib import Path\n\nfor root in (Path.cwd() / 'root').glob('Root*'):\n dest = root / 'FolderTwo'\n for md in (root / 'FolderOne').glob('*.md'):\n md.rename(dest / md.name)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T02:41:19.787", "Id": "520750", "Score": "0", "body": "I have some trouble running this. It doesn't seem like it's doing anything; it's not throwing an error either. I added it to a Python file which is stored in the same place as the `Root{11..15}` folders. I'm on Windows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T02:53:39.110", "Id": "520751", "Score": "0", "body": "You need another level of directory between yourself and Root<n>, namely `root`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-03T02:44:24.950", "Id": "263712", "ParentId": "263679", "Score": "3" } } ]
<p>I'm solving this <a href="https://www.prepbytes.com/panel/mycourses/125-days-expert-coder-program/python/week/1/logic-building/codingAssignment/DISNUM" rel="nofollow noreferrer">challenge</a>:</p> <blockquote> <p>Given a positive integer number, you have to find the smallest <em>good</em> number greater than or equal to the given number. The positive integer is called <em>good</em> if it can be represented as a sum of distinct powers of 3 (i.e. no duplicates of powers of 3 are allowed).</p> </blockquote> <p>The code passes all the test cases in the editor, but when submitted to online judge it is failing because of time limit exceeded. Give time limit 1 second, my code execution is taking 1.01 second</p> <hr /> <pre><code>t = int(input()) while t &gt; 0: N = int(input()) i=N while i &gt; 0: if i % 3 == 2: N=N+1 i=N continue i //= 3 print(N) t = t - 1 </code></pre> <hr /> <h3>Test Case</h3> <p>Input:</p> <pre class="lang-none prettyprint-override"><code>5 3 46 65 89 113 </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>3 81 81 90 117 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-05T03:54:41.183", "Id": "520818", "Score": "0", "body": "Your test case output is missing the output from $5$. It should be $9$, I believe." } ]
{ "AcceptedAnswerId": "263747", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T08:32:09.383", "Id": "263745", "Score": "4", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Find next smallest number that's representable as a sum of distinct powers of 3" }
263745
accepted_answer
[ { "body": "<p>The best approach would be to use ternary numbers, at least at development. Number that's representable as a sum of power of 3 in ternary would consist of 0's and 1's only. So:</p>\n<p>repeat:</p>\n<ul>\n<li>convert the number to ternary;</li>\n<li>if there's no 2's in it - return it;</li>\n<li>if there're 2's - find the leftmost 2, change all digits starting with it into 0 and add 1 to the next digit to the left.</li>\n</ul>\n<p>I think it can be done in one pass of conversion into ternary.</p>\n<p>Update: here's my code, it's <span class=\"math-container\">\\$O(log(n))\\$</span> (yours is <span class=\"math-container\">\\$O(nlog(n))\\$</span>):</p>\n<pre><code>def find_distinct_pow3(number):\n result = 0 \n power = 1\n while number:\n number, digit = divmod(number, 3)\n if digit&lt;2:\n result += power*digit #just copying the digit into the result\n else:\n result = 0 #discarding current result (after the digit 2)\n number += 1 #increasing the digit before 2\n power *= 3\n return result\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T23:00:52.657", "Id": "520810", "Score": "0", "body": "execution time 0.02 sec,thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T10:58:29.877", "Id": "263747", "ParentId": "263745", "Score": "8" } } ]
<p>I currently this code working, but its performance is very poor — 1.45 seconds seems a bit too much for a simple recursive if statement that only checks attribute values.</p> <pre><code>def _check_delete_status(self, obj) -&gt; bool: obj_name = obj._sa_class_manager.class_.__name__ self.visited.append(obj_name) if getattr(obj, 'status', 'deleted').lower() != 'deleted': children = [parent for parent in self._get_parents(self._get_table_by_table_name(obj_name)) if parent not in self.visited] for child in children: if (child_obj := getattr(obj, child, None)) and child not in self.visited: if self._check_delete_status(child_obj): return True else: return True return False </code></pre> <p>Although <code>self._get_parents</code> seems like a counterintuitive name (it's used elsewhere in the code), in this case it is still very useful to this solution: It returns a list with all possible attribute names that object might have as children. For example, an object named <code>appointment</code> will have <code>['patient', 'schedule']</code> as response; of which <code>patient</code> will have <code>[]</code> since it doesn't have any children, and <code>schedule</code> will have <code>['physiotherapist', 'address', 'patient', 'service']</code> returned.</p> <p>When those values are then used on <code>getattr(object, child_name)</code> it returns the object corresponding to the child.</p> <p>I tried to think on how to do this iteratively, but couldn't up come with any solutions.</p> <p>PS: The reason for the <code>self.visited</code> list, is that sometimes an object might have the exact same object nested inside, and since they have the same values they can be skipped.</p> <p><strong>EDIT:</strong> The &quot;helper&quot; methods:</p> <pre><code>def _get_table_by_table_name(self, table_name: str) -&gt; Table: return self._all_models[table_name]['table'] </code></pre> <pre><code>@staticmethod def _get_parents(table: Table) -&gt; set: parents = set() if table.foreign_keys: for fk in table.foreign_keys: parent_name = fk.column.table.name parents.add(parent_name) if parent_name != table.name else None return parents </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T22:50:26.103", "Id": "520809", "Score": "1", "body": "This is a class method - so please show the whole class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T23:02:49.990", "Id": "520811", "Score": "0", "body": "@Reinderien The whole class is a bit too big, but I've included the other methods used." } ]
{ "AcceptedAnswerId": "263759", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T19:04:40.133", "Id": "263758", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Checks if all nested objects don't have 'status' attribute as 'deleted'" }
263758
accepted_answer
[ { "body": "<p>Your code is improperly using lists.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>children = [parent for parent in self._get_parents(self._get_table_by_table_name(obj_name)) if parent not in self.visited]\n</code></pre>\n</blockquote>\n<p>By using a list comprehension you <em>have</em> to generate every parent <em>before</em> you can validate a parent. Lets instead use say you want to know if 0 is in <code>range(1_000_000)</code>. What your code would be doing is building a list of 1 million numbers <em>before</em> you check the first value is 0.</p>\n<p>You should use a generator expression, or just use standard <code>for</code> loops, to build <code>children</code> so we can exit early. (Of course doing so would rely on <code>self._get_parents</code> and <code>self._get_table_by_table_name</code> not returning lists. Which I don't have access to, so cannot comment on.)</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>self.visited.append(obj_name)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>parent not in self.visited\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>child not in self.visited\n</code></pre>\n</blockquote>\n<p>We know <code>self.visited</code> is a list. So we know <code>in</code> runs in <span class=\"math-container\">\\$O(n)\\$</span> time. You want to instead use a set which runs in <span class=\"math-container\">\\$O(1)\\$</span> time.</p>\n<hr />\n<p>Ignoring changing <code>self.visited</code> to a set you can simplify the code using <code>any</code> and a generator expression.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _check_delete_status(self, obj) -&gt; bool:\n obj_name = obj._sa_class_manager.class_.__name__\n self.visited.append(obj_name)\n if getattr(obj, 'status', 'deleted').lower() == 'deleted':\n return True\n else:\n return any(\n child not in self.visited\n and (child_obj := getattr(obj, child, None))\n and child not in self.visited\n and self._check_delete_status(child_obj)\n for child in self._get_parents(self._get_table_by_table_name(obj_name))\n )\n</code></pre>\n<p>You should also notice you don't need <code>child not in self.visited</code> twice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T21:40:44.467", "Id": "520803", "Score": "0", "body": "While this does make the code way cleaner, it still took the same 1.45 seconds (even after changing `self.visited` to a set). Should I assume this happens for another reason?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T21:48:54.203", "Id": "520806", "Score": "0", "body": "Making a quick perf_counter shows this:\n`Now at patient: Time since start -> 0.0 seconds`\n`Now at appointment: Time since start -> 0.0001 seconds`\n`Now at schedule: Time since start -> 0.3194 seconds`\n`Now at service: Time since start -> 0.5754 seconds`\n`Now at organization: Time since start -> 0.8869 seconds`\n`Now at physiotherapist: Time since start -> 1.312 seconds`\n`Now at address: Time since start -> 1.5363 seconds`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T21:52:30.853", "Id": "520807", "Score": "1", "body": "@ViniciusF. If you've made all the changes I suggested (including removing the duplicate `child not in self.visited` and ensuring both `_get_parents` and `_get_table_by_table_name` do not return lists) then I, or anyone else, can't improve the performance of your code as you have not provided the code which has the performance issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T22:23:44.523", "Id": "520808", "Score": "1", "body": "Yeah, thought so. I'm guessing this is a job for the cProfile then. But much appreciated for your help :D" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-04T19:47:52.377", "Id": "263759", "ParentId": "263758", "Score": "1" } } ]
<p>I have an HL7 MLLP message building class I'd like to refactor. The way HL7 over MLLP works is there are multiple fields, usually delimited by the <code>|</code> character. Within the field, there can be lists, delimited by <code>^</code>, and within those lists there can be lists, delimited by <code>&amp;</code>.</p> <p>So for example, the following structure:</p> <pre><code>message = ['foo', ['bar', 'baz', ['a', 'b', 'c'] ], 'comment'] </code></pre> <p>will be serialized to the message:</p> <p><code>serialized = &quot;foo|bar^baz^a&amp;b&amp;c|comment&quot;</code></p> <p>I've written a simple class whose constructor arguments indicate where in the list of fields you want to place some data, as well as the data itself. The <code>__repr__</code> method is defined for easy use of these objects in f-strings.</p> <p>This is the class:</p> <pre><code>class SegmentBuilder: def __init__(self, segment_type, *args): if not isinstance(segment_type, str): raise ValueError(&quot;Segment type must be a string&quot;) self.state = {0: segment_type} for index, value in args: self.state[index] = value self.fields = [None for _ in range(1 + max(self.state.keys()))] def __repr__(self): # Do a Depth-first string construction # Join first list using ^, second list using &amp; # This is ugly, but will work for now # Could do better with an actual recursive depth-based approach def clean(obj): return str(obj) if obj is not None else '' for index, value in self.state.items(): if not isinstance(value, list): self.fields[index] = value else: subfields = [] for subfield in value: if not isinstance(subfield, list): subfields.append(clean(subfield)) else: subsubfields = [] for subsubfield in subfield: subsubfields.append(clean(subsubfield)) subfields.append('&amp;'.join(subsubfields)) self.fields[index] = '^'.join(subfields) return '|'.join([clean(field) for field in self.fields]) </code></pre> <p>Now, there's clearly a recursive refactoring trying to leap out of this, probably involving some list comprehension as well. I thought it might involve passing an iterator based on the sequence of delimiter characters, eg <code>&quot;|^&amp;&quot;</code>, but the base case had me confused (since you would have to catch <code>StopIteration</code>, and then maybe signal to the caller via returning None?). Any guidance on this recursive refactor would be very helpful!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-07T22:40:39.690", "Id": "521016", "Score": "2", "body": "Is the second `bar` in a serialized message supposed to be `baz`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T02:12:08.167", "Id": "521023", "Score": "0", "body": "It is! That was a typo" } ]
{ "AcceptedAnswerId": "263850", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-07T20:07:10.240", "Id": "263844", "Score": "3", "Tags": [ "python", "recursion" ], "Title": "How to refactor an imperative function recursively?" }
263844
accepted_answer
[ { "body": "<p>I'm not certain I understand all of the rules, but if you have only 3\ndelimiters, one per level in the hierarchy, then the base case is the level\nnumber or a non-list type. Here's a sketch of one recursive implementation:</p>\n<pre><code>DELIMITERS = ['|', '^', '&amp;']\n\ndef serialize(level, xs):\n if isinstance(xs, list) and level &lt; len(DELIMITERS):\n return DELIMITERS[level].join(\n serialize(level + 1, x)\n for x in xs\n )\n else:\n # Base case: adjust as needed.\n return xs\n</code></pre>\n<p>I suspect your messages might have more variety in the leaf-node data types\n(are ints and floats allowed?). If so, you might need to use <code>return str(xs)</code>\ninstead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T02:13:04.500", "Id": "521024", "Score": "0", "body": "Brilliant! I like the exception-free approach, also how you constructed the base case conditions!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T00:40:00.083", "Id": "263850", "ParentId": "263844", "Score": "4" } } ]
<p>I wrote a code that given a string (<code>txt</code>), will print a histogram that contains the number of occurrences of each word in it and the word itself.</p> <p>A word is defined to be a sequence of chars separated by one space or more.</p> <p>The code is working, I just want to see if I can improve it.</p> <pre><code>def PrintWordsOccurence(txt): lst = [x for x in txt.split(' ') if x != ' ' and x != ''] newlst = list(dict.fromkeys(lst)) for item in newlst: print(&quot;[{0}] {1}&quot;.format(lst.count(item),item)) </code></pre> <p>An input-output example:</p> <pre><code>&gt;&gt; PrintWordsOccurence(&quot;hello code review! this is my code&quot;) [1] hello [2] code [1] review! [1] this [1] is [1] my </code></pre> <p>The first line creates a list with all words, there will be duplicates in it, so to remove them, I turn the list into a dictionary and then I turn it back to a list. In the end, for each item in the list, I print the number of its occurrences in the original string and the item itself.</p> <p>The time complexity of the code is <span class="math-container">\$\Theta(n^2)\$</span></p> <p>Any suggestions to improve the code?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T09:23:05.273", "Id": "263856", "Score": "10", "Tags": [ "python", "python-3.x" ], "Title": "Create a words histogram of a given string in python" }
263856
max_votes
[ { "body": "<h3>str.split method without arguments</h3>\n<p>It does the same filtering as you do. Just skip ' ' argument.</p>\n<h3>list(dict.fromkeys(list comprehension))</h3>\n<p>It looks overburdened, right? You can create a set of list comprehension as well:</p>\n<pre><code>newlst = list({x for x in txt.split()})\n</code></pre>\n<p>or just</p>\n<pre><code>newlst = list(set(txt.split()))\n</code></pre>\n<p>but the best way is</p>\n<h3>collections.Counter</h3>\n<p>You're reinventing it with worse time complexity.</p>\n<h3>Format strings</h3>\n<p>f-strings look better (but it depends on your task).</p>\n<h3>Function name</h3>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> advices to use lower case with underscores: print_words_occurence</p>\n<h3>All together</h3>\n<pre><code>from collections import Counter\ndef print_words_occurence(txt):\n for word, count in Counter(txt.split()).items():\n print(f&quot;[{count}] {word}&quot;)\n</code></pre>\n<p>Also consider dividing an algorithmic part and input/output - like yielding a pair (word, count) from the function and outputting it somewhere else.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T10:34:27.770", "Id": "263858", "ParentId": "263856", "Score": "15" } } ]
<p><code>map</code> is a builtin function that takes one function <code>func</code> and one or more iterables, and maps the function to each element in the iterables. I wrote the following function that does the reverse, but it feels like this is such a basic operation that someone must have done this before, and hopefully given a better name to this.</p> <p>This appears to be a related question with a slightly different solution:</p> <ul> <li><a href="https://stackoverflow.com/questions/35858735/apply-multiple-functions-with-map">https://stackoverflow.com/questions/35858735/apply-multiple-functions-with-map</a></li> </ul> <pre><code>from toolz import curry, compose @curry def fmap(funcs, x): return (f(x) for f in funcs) cases = fmap([str.upper, str.lower, str.title]) tuple_of_cases = compose(tuple, cases) strings = ['foo', 'bar', 'baz'] list(map(tuple_of_cases, strings)) </code></pre>
[]
{ "AcceptedAnswerId": "263865", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T14:06:21.773", "Id": "263863", "Score": "2", "Tags": [ "python", "functional-programming" ], "Title": "map multiple functions to a single input" }
263863
accepted_answer
[ { "body": "<p>First and foremost, the code is not working as posted.\nOne has to add <code>from toolz import curry, compose</code>.</p>\n<p>Apart from this I like the solution and striving for more functional programming is probably always better. I also don't know a canonical solution for passing an argument to functions in python</p>\n<p>Things I would definitely change:</p>\n<ol>\n<li>I would not overdo the functional programming syntax. <code>list(map(...))</code> should be IMHO written as list comprehension. Even if one does not cast the result of <code>map</code> to a list, I find a generator comprehension to be more readable.</li>\n</ol>\n<p>Small stuff:</p>\n<ol start=\"2\">\n<li><p><code>fmap</code> could get a docstring.</p>\n</li>\n<li><p>Type information with <code>mypy</code> etc. would be nice.</p>\n</li>\n<li><p>Perhaps <code>through</code> would be a better name for <code>fmap</code>. At least if one peeks to other languages. (<a href=\"https://reference.wolfram.com/language/ref/Through.html\" rel=\"nofollow noreferrer\">https://reference.wolfram.com/language/ref/Through.html</a>)</p>\n</li>\n<li><p>Since <code>strings</code> is a constant, it could become uppercase.</p>\n</li>\n<li><p>Sometimes stuff does not need a separate name if functions are just concatenated and IMHO <code>tuple_of_cases</code> can go.</p>\n</li>\n</ol>\n<pre><code>from toolz import curry, compose\n\n\n@curry\ndef fmap(funcs, x):\n return (f(x) for f in funcs)\n\nSTRINGS = ['foo', 'bar', 'baz']\ncases = compose(tuple, fmap([str.upper, str.lower, str.title]))\n\n[cases(x) for x in STRINGS]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T15:17:04.400", "Id": "521046", "Score": "0", "body": "I fixed the missing import in my question. I couldn't really find a suitable name for the concept, but I like `through`, thanks for pointing me in that direction." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T15:09:41.187", "Id": "263865", "ParentId": "263863", "Score": "1" } } ]
<p>I'm learning and looking for at least &quot;not bad&quot; quality of my code. Please let me know how should I improve.</p> <pre><code>#!/usr/bin/env python3 import subprocess import re battery_status = subprocess.run('upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep percentage:', shell=True, capture_output=True, text=True) b_strip = re.sub(r&quot;\t\n\s\W&quot;, &quot; &quot;, battery_status.stdout) b_join = &quot;&quot;.join([i for i in b_strip if i not in [' ', '%', '\t', '\n']]) b_split = b_join.split(':') b_result = int(b_split[1]) if b_result &gt;= 30: print(&quot;Safe to work. You have&quot;, b_result, &quot;%&quot;, &quot;charge left&quot;) else: print(&quot;Please save. You have&quot;, b_result, &quot;%&quot;, &quot;charge left&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T17:21:29.530", "Id": "521048", "Score": "5", "body": "This is text parsing code. I suspect you'll increase your chance of getting useful feedback if you show people **the text** – ie, an example output of the relevant `upower` command." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T19:03:43.080", "Id": "521055", "Score": "5", "body": "@BansheePrime Welcome to CR! Please pick a title that describes what the script does. We know you're here because you have a request for improvement; if we all used generic titles like that, it'd be impossible to find anything. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T13:16:07.573", "Id": "521119", "Score": "2", "body": "Welcome to the Code Review Community. I think it would be very helpful for you to read our [help section](https://codereview.stackexchange.com/help), especially [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask). As @ggorlen pointed out the title needs some work. If your title followed the guidelines better I think you would have scored some up votes on this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T07:06:21.923", "Id": "521667", "Score": "0", "body": "At this moment, there is still no description in either title or question body as to what this code is supposed to do. Please try to follow the helpful advice you've been provided for your next question." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T17:02:37.987", "Id": "263869", "Score": "-1", "Tags": [ "python" ], "Title": "Request for improvement. Isn't it too much variables?" }
263869
max_votes
[ { "body": "<h2>Security</h2>\n<p>Using <code>shell=True</code> has <strong>security</strong> implications (shell injection) which are mentioned in the Python doc: <a href=\"https://docs.python.org/3/library/subprocess.html#security-considerations\" rel=\"noreferrer\">subprocess — Subprocess management: security considerations</a>. So this parameter should be avoided unless truly needed and third-party input must be sanitized always.</p>\n<p>While it assumed you are running a controlled environment, you have no control over the output format of cli utilities. It could change in the future.</p>\n<p>See also this discussion: <a href=\"https://stackoverflow.com/q/3172470\">Actual meaning of 'shell=True' in subprocess</a> and also <a href=\"https://security.stackexchange.com/q/162938/125626\">Security implications of Suprocess executing with a active shell vs no shell</a></p>\n<h2>Simplify the parsing</h2>\n<p>I think the current implementation of parsing stdout is overkill.</p>\n<p>Indeed, some <strong>error handling</strong> is required. But since you are already doing regexes you could perhaps apply a formula to the whole stdout output and look for the line that contains &quot;percentage&quot;, followed by whitespace and a numeric value and the % sign. You are expecting to find one line.</p>\n<p>Example:</p>\n<pre><code>import re\nmatch = re.search(&quot;percentage:\\s*([0-9]+)%&quot;, stdout, re.MULTILINE)\nif match:\n percentage = match.group(1)\n print(f&quot;Percentage: {percentage}&quot;)\nelse:\n print(&quot;Percentage value not found !&quot;)\n</code></pre>\n<p>There is no need for splitting etc. A regex is sufficient to address your need.</p>\n<p>NB: I don't know if upower returns decimals, then you may have to adjust the regex.</p>\n<h2>Check the return code</h2>\n<p>One bonus: check the return code of your call. The command may fail for various reasons, also when running a command that is not present on the target system. All you need is to add this:</p>\n<pre><code>print(f&quot;returncode: {battery_status.returncode}&quot;)\n</code></pre>\n<p>0 = OK, 1 = failure</p>\n<p>So check the return code before you proceed with the rest of your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T00:49:28.813", "Id": "521091", "Score": "0", "body": "Thank you for your help. I really appreciate your advice and it directs me toward topics I need to learn." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T07:44:48.147", "Id": "521104", "Score": "0", "body": "It's correct to default to `shell=False` as policy, but there are no security implications for `shell=True` when running a literal (hard-coded) command ... am I overlooking something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T18:41:28.527", "Id": "521156", "Score": "0", "body": "@FMc: you are correct, no immediate risk here, the point is to avoid bad habits and be aware of the possible pitfalls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T18:48:13.770", "Id": "521159", "Score": "0", "body": "@Anonymous Makes sense, just wanted to confirm that I understood the underlying issue. Good answer, BTW." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-08T21:18:19.763", "Id": "263875", "ParentId": "263869", "Score": "6" } } ]
<p>The input for price() would be STRINGS, as you see below. If the string starts with &quot;-&quot; I would like what follows to be stored in fiat_name and then retrieve the symbol from _KNOWN_FIAT_SYMBOLS. &quot;--rub&quot; (EXAMPLE) could be at any position in the list passed through price()</p> <p>If the optional fiat_name does not exist in _KNOWN_FIAT_SYMBOLS i would like it to default to USD/$</p> <p>I would like the code optimized and cleaned/minimized. I am trying to practice clean and read-able code.</p> <pre><code>import re _KNOWN_FIAT_SYMBOLS = {&quot;USD&quot;:&quot;$&quot;, &quot;RUB&quot;:&quot;₽&quot;} # this will be populated with more symbols/pairs later def price(*arguments): # default to USD/$ fiat_name = &quot;USD&quot; arguments = list(arguments) cryptos = [] for arg in arguments: arg = arg.strip() if not arg: continue for part in arg.split(&quot;,&quot;): if part.startswith(&quot;-&quot;): fiat_name = part.upper().lstrip(&quot;-&quot;) continue crypto = re.sub(&quot;[^a-z0-9]&quot;, &quot;&quot;, part.lower()) if crypto not in cryptos: cryptos.append(crypto) if not cryptos: cryptos.append(&quot;btc&quot;) fiat_symbol = _KNOWN_FIAT_SYMBOLS.get(fiat_name) if not fiat_symbol: fiat_name = &quot;USD&quot; fiat_symbol = &quot;$&quot; print(f&quot;{cryptos} to: {fiat_name}{fiat_symbol}&quot;) price(&quot;usd&quot;, &quot;usdc&quot;, &quot;--rub&quot;) # ['usd', 'usdc'] to: RUB₽ (becuase of the optional --rub) price(&quot;usd,usdc,eth&quot;, &quot;btc&quot;, &quot;-usd&quot;) # ['usd', 'usdc', 'eth', 'btc'] to: USD$ (becuase of the optional --usd) price(&quot;usd&quot;, &quot;usdc,btc&quot;, &quot;-xxx&quot;) #['usd', 'usdc', 'btc'] to: USD$ (because xxx does not exist in _KNOWN_FIAT_SYMBOLS price(&quot;usd,usdc,eth&quot;, &quot;btc&quot;) # ['usd', 'usdc', 'eth', 'btc'] to: USD$ (becuase no optional fiat_name was given) price(&quot;usd,--rub,eth&quot;, &quot;btc&quot;) # ['usd', 'eth', 'btc'] to: RUB₽ (becuase of the optional --rub) price(&quot;--rub&quot;) # ['btc'] to: RUB₽ (becuase of the optional --rub and the cryptos is empty) price(&quot;&quot;) # ['btc'] to: USD$ (becuase of the default USD and the cryptos is empty) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T13:29:38.683", "Id": "521127", "Score": "1", "body": "Welcome to Code Review! 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": "263894", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T01:26:08.553", "Id": "263887", "Score": "6", "Tags": [ "python", "parsing" ], "Title": "Parsing input and output currency names" }
263887
accepted_answer
[ { "body": "<p><strong>Return data</strong>. Algorithmic code should return data, not print – at least\nwhenever feasible. It's better for testing, debugging, refactoring, and\nprobably other reasons. At a minimum, return a plain tuple or dict. Even better\nwould be a meaningful data object of some kind (e.g., <code>namedtuple</code>,\n<code>dataclass</code>, or <code>attrs</code> class). Print elsewhere, typically in\na function operating at the outer edge of your program.</p>\n<p><strong>Function <code>*args</code> are already independent tuples</strong>. That means you don't need\n<code>arguments = list(arguments)</code>.</p>\n<p><strong>Algorithmic readability</strong>. Your current code is generally fine: I had no\ngreat difficulty figuring out how it was supposed to work. However, the parsing\nrules themselves have a tendency to require an annoying amount of conditional\nlogic: I was not happy with the first draft or two I sketched out. But I did\ncome up with an alternative that I ended up liking better: one function\nfocuses on parsing just the currency names (a fairly narrow, textual task); and\nthe other part deals with the annoyances of missing/unknown data. Note that\nboth functions return meaningful data objects – an important tool in writing\nmore readable code – and the second function handles missing/unknown values\nwith a &quot;declarative&quot; style. Overall, this version strikes me as somewhat more\nreadable. If you need to optimize for raw speed, it's probably slower.</p>\n<pre><code>import re\nfrom collections import namedtuple\n\n_KNOWN_FIAT_SYMBOLS = {&quot;USD&quot;:&quot;$&quot;, &quot;RUB&quot;:&quot;₽&quot;}\n\nFiatCryptos = namedtuple('FiatCryptos', 'name symbol cryptos')\nCurrency = namedtuple('Currency', 'name is_fiat')\n\ndef price(*arguments):\n currencies = list(parse_currencies(arguments))\n cryptos = [c.name for c in currencies if not c.is_fiat] or ['btc']\n fiats = [c.name.upper() for c in currencies if c.is_fiat] or ['USD']\n f = fiats[0]\n syms = _KNOWN_FIAT_SYMBOLS\n name, sym = (f, syms[f]) if f in syms else ('USD', '$')\n return FiatCryptos(name, sym, cryptos)\n\ndef parse_currencies(arguments):\n for arg in arguments:\n for part in arg.strip().split(','):\n if part:\n is_fiat = part.startswith('-')\n name = re.sub('[^a-z0-9]', '', part.lower())\n yield Currency(name, is_fiat)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T07:35:07.527", "Id": "263894", "ParentId": "263887", "Score": "9" } } ]
<p>I solved a Daily Coding Challenge, but i suspect my code could be optimised. The challenge is the following:</p> <p>You are given an N by M matrix of 0s and 1s. Starting from the top left corner, how many ways are there to reach the bottom right corner?<br /> You can only move right and down. 0 represents an empty space while 1 represents a wall you cannot walk through. For example, given the following matrix:</p> <pre><code>[[0, 0, 1], [0, 0, 1], [1, 0, 0]] </code></pre> <p>Return two, as there are only two ways to get to the bottom right:<br /> Right, down, down, right<br /> Down, right, down, right<br /> The top left corner and bottom right corner will always be 0.</p> <p>You can see my solution below. Any tips on how to improve on it are very welcome.</p> <pre><code>def solution(matrix, x=0, y=0): count = 0 right, left = False, False if y == len(matrix) - 1 and x == len(matrix[0]) - 1: # found a way return 1 if x &lt; len(matrix[0]) - 1: if matrix[y][x+1] == 0: count += solution(matrix, x+1, y) # look right right = True if y &lt; len(matrix) - 1: if matrix[y+1][x] == 0: count += solution(matrix, x, y+1) # look down left = True if not right and not left: # dead end return 0 return count if __name__ == &quot;__main__&quot;: print(solution([[0, 0, 0], [0, 0, 0], [0, 1, 0]])) </code></pre>
[]
{ "AcceptedAnswerId": "263898", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T07:29:32.973", "Id": "263893", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "matrix" ], "Title": "Find number of ways to traverse matrix of 0's and 1's" }
263893
accepted_answer
[ { "body": "<p>You don't need <code>right</code> and <code>left</code>: they add nothing that isn't already covered\nby <code>count</code>.</p>\n<p>Compute lengths once rather than repeatedly.</p>\n<p>Check for empty matrix rows and/or columns, or invalid <code>x</code> and <code>y</code>, if your\ncode needs to handle such edge cases.</p>\n<pre><code>def solution(matrix, x=0, y=0):\n count = 0\n y_limit = len(matrix) - 1\n x_limit = len(matrix[0]) - 1\n\n # Success.\n if y == y_limit and x == x_limit:\n return 1\n\n # Look right.\n if x &lt; x_limit and matrix[y][x + 1] == 0:\n count += solution(matrix, x + 1, y)\n\n # Look down.\n if y &lt; y_limit and matrix[y + 1][x] == 0:\n count += solution(matrix, x, y + 1)\n\n return count\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T09:17:22.750", "Id": "521107", "Score": "0", "body": "I don't think edge cases have to be considered in my case. this helped, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T09:04:20.753", "Id": "263898", "ParentId": "263893", "Score": "0" } } ]
<p>I have a dictionary in Python (<code>uglyDict</code>) that has some really un-cool key names. I would like to rename them based on values from another dictionary (<code>keyMapping</code>). Here's an example of the dictionaries:</p> <pre><code>uglyDict = { &quot;ORDER_NUMBER&quot;: &quot;6492&quot;, &quot;Ship To - Name&quot;: &quot;J.B Brawls&quot;, &quot;Ship To - Address 1&quot;: &quot;42 BAN ROAD&quot;, &quot;Ship To - City&quot;: &quot;Jimville&quot;, &quot;Ship To - State&quot;: &quot;VA&quot;, &quot;Ship To - Postal Code&quot;: &quot;42691&quot; } keyMapping = { &quot;Market - Store Name&quot;: &quot;WSCUSTOMERID&quot;, &quot;Ship To - Name&quot;: &quot;ShipToCompany&quot;, &quot;Ship To - Country&quot;: &quot;ShipToCountryCode&quot;, &quot;Ship To - Postal Code&quot;: &quot;ShipToZipcode&quot;, &quot;Ship To - City&quot;: &quot;ShipToCity&quot;, &quot;Date - Order Date&quot;: &quot;OrderDate&quot;, &quot;Gift - Message&quot;: &quot;SpecialInstructions&quot;, &quot;Customer Email&quot;: &quot;ShipToEmail&quot;, &quot;Ship To - Address 2&quot;: &quot;ShipToAddress2&quot;, &quot;Ship To - Address 1&quot;: &quot;ShipToAddress1&quot;, &quot;Ship To - Phone&quot;: &quot;ShipToPhoneNum&quot;, &quot;Order - Number&quot;: &quot;ORDER_NUMBER&quot;, &quot;Ship To - State&quot;: &quot;ShipToState&quot;, &quot;Carrier - Service Selected&quot;: &quot;ShipMethod&quot;, &quot;Item - SKU&quot;: &quot;PRODUCT_NUMBER&quot;, &quot;Item - Qty&quot;: &quot;Quantity&quot; } </code></pre> <p>Here is my code so far to rename <code>uglyDict</code>'s keys:</p> <pre><code>prettyDict = {} for mkey, mval in keyMapping.items(): for ukey in uglyDict.keys(): if mkey == ukey: prettyDict[mval] = uglyDict[mkey] print(prettyDict) </code></pre> <p>The code works as desired, and prints the dictionary with renamed keys as shown below:</p> <pre><code>{'ORDER_NUMBER': '6492', 'ShipToCompany': 'J.B Brawls', 'ShipToAddress1': '42 BAN ROAD', 'ShipToCity': 'Jimville', 'ShipToState': 'VA', 'ShipToZipcode': '42691'} </code></pre> <p>My question is, is there any more efficient/more Pythonic way to do this? Preferably one where I don't have to loop over the keys of both dictionaries. I am using this code with much larger dictionaries and performance is needed.<br /> Any insight is welcome!</p>
[]
{ "AcceptedAnswerId": "263905", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T14:48:38.030", "Id": "263904", "Score": "9", "Tags": [ "python", "performance", "python-3.x", "hash-map" ], "Title": "Efficient renaming of dict keys from another dict's values - Python" }
263904
accepted_answer
[ { "body": "<p>I'd use a dict comprehension:</p>\n<pre><code>pretty_dict = {replacement_keys[k]: v for k, v in ugly_dict.items()}\n</code></pre>\n<p>This throws an error if <code>replacement_keys</code> (<code>keyMapping</code>) is missing any <code>k</code>. You might want to handle that with a default that falls back to the original key:</p>\n<pre><code>pretty_dict = {replacement_keys.get(k, k): v for k, v in ugly_dict.items()}\n</code></pre>\n<p>Time complexity is linear, assuming constant time dict lookups.</p>\n<p>The main point of dicts is fast lookups, not iteration, so alarm bells should sound if you find yourself doing nested loops over multiple dicts.</p>\n<hr />\n<p>Style suggestions:</p>\n<ul>\n<li>Use <code>snake_case</code> rather than <code>camelCase</code> per <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">PEP-8</a>.</li>\n<li>Generally avoid appending the type to every variable, <code>users_count</code>, <code>source_string</code>, <code>names_list</code>, <code>translation_dict</code> and so forth, although I assume this is for illustrative purposes here.</li>\n<li><code>.keys()</code> is superfluous as far as I know, but then again it doesn't hurt. You shouldn't need to loop over keys on a dict often.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T15:12:36.403", "Id": "521143", "Score": "3", "body": "This is a very nice solution, thank you! I love it when Python comprehension can be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T15:13:56.223", "Id": "521144", "Score": "0", "body": "Although when I said more Pythonic I wasn't asking about pothole case " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-10T08:09:24.377", "Id": "521188", "Score": "7", "body": "@NoahBroyles regardless of whether you consider it pothole case and abominable it is the recommended standard for Python code. Style suggestions are important and good on ggorlen for providing them!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-10T17:16:43.000", "Id": "521224", "Score": "0", "body": "I agree -- most coding style decisions are non-decisions. When in Rome, do as the Romans. Otherwise, you raise cognitive load for people reading the code and your linter won't shush. Older libraries like BeautifulSoup have gone so far as to rewrite their camelCased API to pothole_case, so now they have 2 functions per name: legacy `findAll` and idiomatic `find_all`. When I see Python code with camelCase, 99% of the time it's low-quality in other regards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T00:06:36.183", "Id": "521239", "Score": "0", "body": "@NoahBroyles Pythonic means following the idioms of Python. Of which PEP 8 is a large part of the culture for many people. Another notable one is PEP 20 (`import this`). In the future, please be more clear when using terms in non-standard ways." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T15:02:04.443", "Id": "263905", "ParentId": "263904", "Score": "19" } } ]
<p>I have the following code to round a number down to the nearest non zero digit in a string, or if the digit is larger than 1 it would round to the second decimal place. I have yet to find a way to do this without converting the number to a string and then using regex.</p> <p>The end result of the number can be either a string or a digit, I kept it a string because i already converted it to one earlier in the method.</p> <p>I am curious to know what <strong>you</strong> guys would do in this situation. I am working with all kinds of numbers (1 -&gt; 50,000+ (generally)), however I am also working with VERY small numbers (4.42223e-9)</p> <p>As always,</p> <p>Thank you for taking the time to reading and answering this. I look forward to everyone's responses and criticism</p> <pre><code>import re def roundToNearestZero(number): number = abs(number) if number &lt; 1: #number = re.match(&quot;^0\\.0*[1-9][0-9]&quot;, f&quot;{abs(number):.99f}&quot;).group() str_number = f&quot;{number:.99f}&quot; index = re.search('[1-9]', str_number).start() number = f&quot;{str_number[:index + 3]}&quot; else: number = f&quot;{number:,.2f}&quot; return number print( roundToNearestZero(0.0000001232342) )# 0.000000123 print( roundToNearestZero(1.9333) ) # 1.93 print( roundToNearestZero(-0.00333) ) # 0.00333 print( roundToNearestZero(-123.3333) ) # 123.33 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T22:52:23.153", "Id": "521173", "Score": "2", "body": "Why would you do this in the first place? This is _not_ only a rounding function, since there is an `abs` in the mix." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T23:10:05.083", "Id": "521174", "Score": "0", "body": "@Reinderien Hi, thank you for the question. I am creating a price checker and some of the coins/tokens are fractions of pennies. Some could be: 0.000000000012313149 and i am only interested in rounding to the nearest non zero digit: 0.00000000001. the reason i have abs() is because some i am also checking the price change within the last 24 hours and the API I use sends back scientific notation (which is why i have {number.99f}and negative numbers (-0.00000000123 for example) abs(). The abs() is not required in this method. I hope this helps and explains things a little bit more" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-10T03:28:18.377", "Id": "521179", "Score": "0", "body": "I'm afraid that this entire procedure has a bad-idea fragrance. If you're formatting these values for display only, there are better formats. If this is part of an analysis routine you probably shouldn't be rounding at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-10T07:27:06.227", "Id": "521185", "Score": "0", "body": "@Reinderien Yes its for display, could you tell me the better formats you're talking about? Thanks again" } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-09T22:14:30.450", "Id": "263916", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Round number to nearest non zero digit" }
263916
max_votes
[ { "body": "<p><strong>A few stylistic edits to consider</strong>. Your code is generally fine. In the example below, I made some minor stylistic\nedits: shorter variable names (because they are just as clear in context as the\nvisually-heavier longer names); direct returns rather than setting <code>number</code>;\nand taking advantage of the built-in <code>round()</code> function where it applies. I\nwould also add some explanatory comments to the code, as illustrated below.\nIt needs some explanation, for reasons discussed below.</p>\n<pre><code>def roundToNearestZero(number):\n n = abs(number)\n if n &lt; 1:\n # Find the first non-zero digit.\n # We want 3 digits, starting at that location.\n s = f'{n:.99f}'\n index = re.search('[1-9]', s).start()\n return s[:index + 3]\n else:\n # We want 2 digits after decimal point.\n return str(round(n, 2))\n</code></pre>\n<p><strong>The function is unusual</strong>. Less convincing is the function itself. First, it's not a rounding operation:\nit takes the absolute value, converts to string, and then it does some\nrounding-adjacent things. If <code>number</code> is 1 or larger, the function actually\nrounds (to 2 digits past the decimal). Otherwise, the function imposes a floor\noperation (to 3 digits, starting at the first non-zero). The whole thing seems\nlike a conceptual mess, but I understand that you might be operating under some\nodd constraints from your project that you cannot easily change.</p>\n<p><strong>Choose a better function name</strong>. At a minimum you should rename the function. Naming it according to\nmathematical operations makes little sense due to its inconsistent and unusual\nbehavior. Instead you might consider a name oriented toward its purpose: for\nexample, <code>display_price()</code> or whatever makes more sense based on its role in\nthe project.</p>\n<p><strong>Data-centric orchestration</strong>. Finally, I would encourage you to adopt a more data-centric approach to working\non algorithmic code – while writing code, debugging it, and when asking people\nfor help. Here I'm talking about the orchestration code rather than the\nfunction itself. The first thing I did when experimenting with your code its to\nset up better orchestration:</p>\n<pre><code># This is print-centric. As such, it's not very useful.\n\nprint( roundToNearestZero(0.0000001232342) )# 0.000000123\nprint( roundToNearestZero(1.9333) ) # 1.93\nprint( roundToNearestZero(-0.00333) ) # 0.00333\nprint( roundToNearestZero(-123.3333) ) # 123.33\n\n# This is data-centric and thus amenable to efficient testing.\n# Any bad edit I made to the code was quickly revealed, and I\n# could easily add more test cases as I explored.\n\ndef main():\n TESTS = (\n (0.0000001232342, '0.000000123'),\n (1.9333, '1.93'),\n (-0.00333, '0.00333'),\n (-123.3333, '123.33'),\n (0.00000012032342, '0.000000120'),\n (-0.00000012032342, '0.000000120'),\n (-0.000000120999, '0.000000120'),\n (204.947, '204.95'),\n )\n for inp, exp in TESTS:\n got = roundToNearestZero(inp)\n if got == exp:\n print('ok')\n else:\n print('FAIL', (inp, got, exp))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-10T00:07:05.513", "Id": "263918", "ParentId": "263916", "Score": "4" } } ]
<p>I'm reading on how to write proper testing suites <a href="https://martinfowler.com/bliki/PageObject.html" rel="nofollow noreferrer">here</a>. So I'm trying to follow the selenium example in the <a href="https://github.com/SeleniumHQ/selenium/wiki/PageObjects" rel="nofollow noreferrer">docs</a> which is in Java; I'm trying to translate it to Python since my app is written in Python.</p> <p>So I translated the example like so:</p> <pre><code>class LoginPage(unittest.TestCase): FE_URL = os.getenv('FE_URL') SERVER_URL = os.getenv('SERVER_URL') def __init__(self, driver): self.selenium = driver def find_button_by_text(self, text): buttons = self.selenium.find_elements_by_tag_name(&quot;button&quot;) for btn in buttons: if text in btn.get_attribute(&quot;innerHTML&quot;): return btn def login_page(self): self.selenium.get(self.FE_URL) WebDriverWait(self.selenium, MAX_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, &quot;login&quot;)) ) return self.selenium def type_username(self, username): username_locator = self.selenium.find_element_by_name(&quot;user[email]&quot;) username_locator.send_keys(username) return self.selenium def type_password(self, password): password_locator = self.selenium.find_element_by_name(&quot;user[password]&quot;) password_locator.send_keys(password) return self.selenium def submit_login(self): login_locator = self.find_button_by_text(&quot;Continue&quot;) login_locator.click() return self.selenium def submit_login_expecting_failure(self): self.login_page() self.submit_login() return self.selenium def login_as(self, username, password): login_page = self.login_page() self.type_username(username) self.type_password(password) return self.submit_login() </code></pre> <p>and then the actual test is here:</p> <pre><code>class MyTest(unittest.TestCase): USER_NAME = os.getenv('USER_NAME') PASSWORD = os.getenv('PASSWORD') @classmethod def setUpClass(cls): super(MyTest, cls).setUpClass() cls.selenium = WebDriver() # cls.selenium = webdriver.Firefox() cls.wait = WebDriverWait(cls.selenium, MAX_WAIT) @classmethod def tearDownClass(cls): cls.selenium.quit() super(MyTest, cls).tearDownClass() def test_login(self): login_page = LoginPage(self.selenium) main_page = login_page.login_as(self.USER_NAME, self.PASSWORD) WebDriverWait(main_page, MAX_WAIT).until( EC.presence_of_element_located((By.LINK_TEXT, &quot;Create alert&quot;)) ) def test_failed_login(self): login_page = LoginPage(self.selenium) page = login_page.submit_login_expecting_failure() alert = WebDriverWait(page, MAX_WAIT).until( EC.visibility_of_element_located((By.CLASS_NAME, &quot;alert-danger&quot;)) ) self.assertIn(&quot;Invalid Email or Password&quot;, alert.text) if __name__ == &quot;__main__&quot;: unittest.main() </code></pre> <p>The test works. Did I understand this correctly that the driver is setup in the actual test class and not in the <code>LoginPage</code>?</p> <p>Did I hide the actual mechanics of the test correctly? I am using <code>WebDriverWait</code> in the <code>LoginPage</code> class to wait till the page is loaded. I see this as kind of an assert replacement but I am not sure how else to wait for the page to have finished loading.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T13:35:04.967", "Id": "521256", "Score": "1", "body": "Do `FE_URL` and `SERVER_URL` take values that point to a publicly-accessible server you can share with us for the purposes of testing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T16:22:11.103", "Id": "521260", "Score": "0", "body": "those are only localhost values, as in `http://localhost:3000` and `http://localhost:3001` I put them in env variables cause I thought this is how you are supposed to do it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T16:32:33.627", "Id": "521261", "Score": "1", "body": "No that's fine, you've done the right thing. It just means that I can't test your code for you." } ]
{ "AcceptedAnswerId": "263949", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T01:45:19.100", "Id": "263941", "Score": "1", "Tags": [ "python-3.x", "selenium", "integration-testing" ], "Title": "Simple login test, translated from java to python" }
263941
accepted_answer
[ { "body": "<p>I think the biggest miss here is that <code>LoginPage</code>, though it is perhaps fine as a test utility class, is clearly not a <code>TestCase</code> and should not inherit from that.</p>\n<p>This loop:</p>\n<pre><code> buttons = self.selenium.find_elements_by_tag_name(&quot;button&quot;)\n for btn in buttons:\n if text in btn.get_attribute(&quot;innerHTML&quot;):\n return btn\n</code></pre>\n<p>should not be needed, and you should be able to write a single selector that accomplishes the same thing. Without access to your DOM I don't know what that's going to be, precisely.</p>\n<p>Your pattern of <code>return self.selenium</code> isn't particularly useful, since <code>MyTest</code> already has a reference to its own <code>self.selenium</code>; so all of those functions can just be <code>None</code>-returns.</p>\n<p>For Python 3 you should no longer be passing parameters into <code>super()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T14:25:05.593", "Id": "263949", "ParentId": "263941", "Score": "2" } } ]
<p>I have a simple SDK in Python for internal use. It's basically 150~200 lines of code of simple API calls wrapped around nicely that is comfortable for us to use.</p> <p>It holds a few clients with methods (and each method wraps some API calls).</p> <p>So a proper usage would be:</p> <pre><code>from datatube.datatube import Datatube client = Datatube() client.do_stuff(...) </code></pre> <p>Currently it expects 3 environment variables - two for authentication purposes (these are the secret ones) and one for the environment (dev/stg/prod). I want to change the environment variable to be passed on as an argument (seems better). So:</p> <pre><code>from datatube.datatube import Datatube client = Datatube('stg') client.do_stuff(...) </code></pre> <p>Inside <code>Datatube</code> I'll take the correct config based on the environment. Currently I have:</p> <pre><code>class BaseConfig: pass class DevelopmentConfig(BaseConfig): DATATUBE_URL = 'https://..' class StagingConfig(BaseConfig): DATATUBE_URL = 'https://..' class ProductionConfig(BaseConfig): DATATUBE_URL = 'https://..' def get_config(env: str): env = env.lower() if env == 'dev': return DevelopmentConfig() if env == 'stg': return StagingConfig() elif env == 'prod': return ProductionConfig() else: raise KeyError(f&quot;unsupported env: {env}. supported environments: dev/stg/prod&quot;) </code></pre> <p>If I'll use type annotation on <code>get_config</code> like:</p> <p><code>def get_config(env: str) -&gt; BaseConfig</code></p> <p>Then the IDE won't like it (I guess because <code>BaseConfig</code> is empty, but I don't know how to do it nicely - isn't an abstract class kind of an overkill?)</p> <p>Any recommendations would be helpful.</p> <p>Using Python 3.9</p>
[]
{ "AcceptedAnswerId": "263989", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T14:44:30.443", "Id": "263982", "Score": "0", "Tags": [ "python", "python-3.x", "configuration" ], "Title": "Config for each environment (for a simple Python SDK)" }
263982
accepted_answer
[ { "body": "<p>Class inheritance is overkill here. Just use dataclass instances:</p>\n<pre><code>from dataclasses import dataclass\n\n\n@dataclass\nclass Config:\n DATATUBE_URL: str\n\n\nENVIRONMENTS = {\n 'dev': Config(\n DATATUBE_URL='https://..',\n ),\n 'stg': Config(\n DATATUBE_URL='https://..',\n ),\n 'prd': Config(\n DATATUBE_URL='https://..',\n ),\n}\n\n\ndef get_config(env_name: str) -&gt; Config:\n env = ENVIRONMENTS.get(env_name.lower())\n if env is None:\n raise KeyError(\n f&quot;unsupported env: {env_name}. supported environments: &quot; +\n ', '.join(ENVIRONMENTS.keys()))\n return env\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T18:27:51.110", "Id": "263989", "ParentId": "263982", "Score": "3" } } ]
<pre><code># digit containing 9 has to be greater or equal in length mul9 = { str(i): str(9-i) for i in range(10)} print(f&quot;{mul9}\n&quot;) number1 = int(input(&quot;Enter 9s': &quot;)) len1 = len(str(number1)) number2 = int(input(f&quot;Enter (0 - {str(9)*len1}): &quot;)) if len(str(number1)) &lt; len(str(number2)): print(&quot;This trick won't work&quot;) else: res = str(number2 - 1) print(f&quot;{number2} - 1 = {res} &quot;) end = '' for i in res: end += mul9[i] print(f&quot;{i} needs {mul9[i]} to become 9&quot;) res += (len(str(number1)) - len(str(number2))) * &quot;9&quot; + end # This accounts for adding the invisible 0s at the start of 'res' in the video. I've simply added the correct number of 9s and avoided but avoided looping through them in the for loop. print(res) </code></pre> <p>gives</p> <pre><code>{'0': '9', '1': '8', '2': '7', '3': '6', '4': '5', '5': '4', '6': '3', '7': '2', '8': '1', '9': '0'} Enter 9s': 99 Enter (0 - 99): 99 99 - 1 = 98 9 needs 0 to become 9 8 needs 1 to become 9 9801 [Program finished] </code></pre> <p>The objective of the code is to demo students how we can multiply large numbers in smallest amount of time. I am new to python so not that aware of syntax. Works as expected. Can you please point out at lines which can be reduced.</p>
[]
{ "AcceptedAnswerId": "264025", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T15:42:38.720", "Id": "264019", "Score": "4", "Tags": [ "python-3.x", "mathematics" ], "Title": "Multiply by 9 without multiplying by 9, using vedic math" }
264019
accepted_answer
[ { "body": "<ul>\n<li>Introduce some validation loops, rather than just bailing when the trick won't work</li>\n<li>Rephrase your outputs to be real equations - there's no reason not to</li>\n<li>Rearrange your digit storage order so that first things are added to a list first, and at the end call <code>join</code></li>\n<li>Beware your use of parens in your first prompt; this suggests an open interval when I think you want a closed interval. Your original meaning aside, I don't think that your <code>(0 - 99)</code> is actually supported - 0 crashes, so I'll suggest that you instead ask for a minimum of 1.</li>\n<li>Storing <code>mul9</code> as a dictionary is more effort than it's worth. Just calculate the difference for each digit.</li>\n<li>You might as well include a test to verify that your answer is correct.</li>\n<li>Explain how you get to the number of middle-9 digits.</li>\n</ul>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>while True:\n number1 = input('Enter a number whose digits are all 9: ')\n if set(number1) == {'9'}:\n break\nlen1 = len(number1)\nnumber1 = int(number1)\n\nwhile True:\n number2 = input(f'Enter [1-{number1}]: ')\n len2 = len(number2)\n try:\n number2 = int(number2)\n except ValueError:\n continue\n if 0 &lt; number2 &lt;= number1:\n break\n\nres = number2 - 1\ndigits = [str(res), '9'*(len1 - len2)]\nprint(\n f'{number2} - 1 = {res}\\n'\n f'The difference of the input lengths '\n f'{len1}-{len2}={len1-len2} is the number '\n f'of &quot;9&quot; digits to insert in the middle'\n)\n\nfor str_i in str(res):\n i = int(str_i)\n mul9 = 9 - i\n digits += str(mul9)\n print(f'{i} + {mul9} = 9')\n\nans = int(''.join(digits))\nif number1 * number2 != ans:\n raise ValueError('Unexpected algorithm failure')\nprint(f'{number1} * {number2} = {ans}')\n</code></pre>\n<h2 id=\"output\">Output</h2>\n<pre><code>Enter a number whose digits are all 9: 9999\nEnter [1-9999]: 526\n526 - 1 = 525\nThe difference of the input lengths 4-3=1 is the number of &quot;9&quot; digits to insert in the middle\n5 + 4 = 9\n2 + 7 = 9\n5 + 4 = 9\n9999 * 526 = 5259474\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T17:49:52.953", "Id": "521385", "Score": "0", "body": "my code misses how ```9``` becomes part of final answer, so is urs.... i will debug that and thanks for suggestion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T18:04:03.470", "Id": "521387", "Score": "0", "body": "@Subham done, though obviously this one isn't as easy to phrase in the form of an equation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T17:29:33.927", "Id": "264025", "ParentId": "264019", "Score": "3" } } ]
<pre><code>add9 = [] add9.append(int(input(&quot;Enter 1st 4-digit no.: &quot;))) print(f&quot;The answer will be 2 and {str(add9[0])[0 :-1]} and {str(add9[0]-2)[-1]} = 2{add9[0]-2}&quot;) add9.append(int(input(&quot;Enter 2nd 4-digit no.: &quot;))) add9.append(9999-add9[1]) print(f&quot;The 3rd 4-digit is 9999 - {add9[1]}= {add9[2]}&quot;) add9.append(int(input(&quot;Enter 4th 4-digit no.: &quot;))) add9.append(9999-add9[3]) print(f&quot;The 5th 4-digit is 9999 - {add9[2]}= {add9[4]}&quot;) print(f&quot;&quot;&quot; So, {add9[0]}+{add9[1]} = {add9[0]+add9[1]} {add9[0]+add9[1]}+{add9[2]} = {add9[0]+add9[1]+add9[2]} {add9[0]+add9[1]+add9[2]}+{add9[3]} = {add9[0]+add9[1]+add9[2]+add9[3]} {add9[0]+add9[1]+add9[2]+add9[3]}+{add9[4]} = {add9[0]+add9[1]+add9[2]+add9[3]+add9[4]} &quot;&quot;&quot;) </code></pre> <p>gives</p> <pre><code>Enter 1st 4-digit no.: 9999 The answer will be 2 and 999 and 7 = 29997 Enter 2nd 4-digit no.: 2345 The 3rd 4-digit is 9999 - 2345= 7654 Enter 4th 4-digit no.: 6789 The 5th 4-digit is 9999 - 7654= 3210 So, 9999+2345 = 12344 12344+7654 = 19998 19998+6789 = 26787 26787+3210 = 29997 [Program finished] </code></pre> <p>Code works fine. It's for kids to demo how to produce output using 3 inputs from user. The trick is to subtract 9999 from 2nd and 3rd input from user. I have tried to use as small syntax as possible.</p> <p>Edit: 3rd and 5th digit are - 9999</p> <pre><code>Enter 1st 4-digit no.: 9990 The answer will be 2 and 999 and 8 = 29988 Enter 2nd 4-digit no.: 6667 The 3rd 4-digit is 9999 - 6667= 3332 Enter 4th 4-digit no.: 8888 The 5th 4-digit is 9999 - 3332= 1111 So, 9990+6667 = 16657 16657+3332 = 19989 19989+8888 = 28877 28877+1111 = 29988 [Program finished] </code></pre> <p>is working as expected</p> <p>From calculator,</p> <pre><code> Calculation 1 (1/1) 9,990. + (1/2) 6,667. = (1/3) 16,657. + (1/4) 3,332. = (1/5) 19,989. + (1/6) 8,888. = (1/7) 28,877. + (1/8) 1,111. = (1/9) 29,988. </code></pre>
[]
{ "AcceptedAnswerId": "264030", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T17:05:29.960", "Id": "264021", "Score": "1", "Tags": [ "python-3.x", "mathematics" ], "Title": "Game: Predict answer based on 3 user inputs, 2 self created inputs" }
264021
accepted_answer
[ { "body": "<ul>\n<li>To start, I wouldn't put everything in a list. There are benefits to putting all five numbers in a sequence, but that needn't happen until the end</li>\n<li>You can expand your explanation for the &quot;answer&quot;. First, it's unclear what you mean by &quot;answer&quot;; it's actually the fourth sum. Also, you can expand your explanation for each of the terms going into this fourth sum. Some of the notation I've shown is perhaps a little advanced for kids, so simplify it at your discretion.</li>\n<li>You should be replacing your expressions at the bottom with a loop.</li>\n<li>Where possible, you should be phrasing your operations as mathematical (mod, floor division) rather than string-based.</li>\n<li>I think you have an algorithmic problem? When I enter <code>9990</code> for the first number, the predicted and actual fourth sum diverge.</li>\n</ul>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>a = int(input(&quot;Enter 1st 4-digit no.: &quot;))\nsum4 = int(f'2{a//10}{(a - 2)%10}')\nprint(\n f&quot;The fourth sum will be the concatenation of:&quot;\n f&quot;\\n 2&quot;\n f&quot;\\n ⌊{a}/10⌋ = {a//10}&quot;\n f&quot;\\n mod({a} - 2, 10) = {(a - 2)%10}&quot;\n f&quot;\\n= {sum4}&quot;\n f&quot;\\n&quot;\n)\n\nb = int(input(&quot;Enter 2nd 4-digit no.: &quot;))\nc = 9999 - b\nprint(f&quot;The 3rd 4-digit no. is 9999 - {b} = {c}&quot;)\n\nd = int(input(&quot;Enter 4th 4-digit no.: &quot;))\ne = 9999 - d\nprint(f&quot;The 5th 4-digit no. is 9999 - {c} = {e}&quot;)\n\nnums = (a, b, c, d, e)\nprint('\\nSo,')\nfor i in range(4):\n addend = sum(nums[:i+1])\n augend = nums[i+1]\n print(f'{addend} + {augend} = {addend+augend}')\n</code></pre>\n<h2 id=\"output\">Output</h2>\n<pre><code>Enter 1st 4-digit no.: 9999\nThe fourth sum will be the concatenation of:\n 2\n ⌊9999/10⌋ = 999\n mod(9999 - 2, 10) = 7\n= 29997\n\nEnter 2nd 4-digit no.: 2345\nThe 3rd 4-digit no. is 9999 - 2345 = 7654\nEnter 4th 4-digit no.: 6789\nThe 5th 4-digit no. is 9999 - 7654 = 3210\n\nSo,\n9999 + 2345 = 12344\n12344 + 7654 = 19998\n19998 + 6789 = 26787\n26787 + 3210 = 29997\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T20:34:57.493", "Id": "264030", "ParentId": "264021", "Score": "0" } } ]
<p>basically i am new to python lookin for any bad practices done down there in my script, any ways to shrink the code and increase efficiency</p> <pre><code>import json, os, win32crypt, shutil, sqlite3 from Crypto.Cipher import AES tmp = os.getenv('TEMP') usa = os.environ['USERPROFILE'] triple = False both = False edb = usa + os.sep + r'AppData\Local\Microsoft\Edge\User Data\Default\Login Data' cdb = usa + os.sep + r'AppData\Local\Google\Chrome\User Data\Default\Login Data' bdb = usa + os.sep + r'AppData\Local\BraveSoftware\Brave-Browser\User Data\Default\Login Data' if os.path.exists(edb) and os.path.exists(bdb): both = True if both and os.path.exists(bdb): triple = True ckey = usa + os.sep + r'AppData\Local\Google\Chrome\User Data\Local State' ekey = usa + os.sep + r'AppData\Local\Microsoft\Edge\User Data\Local State' bkey = usa + os.sep + r'AppData\Local\BraveSoftware\Brave-Browser\User Data\Local State' def dec(pwd, key): initv = pwd[3:15] block = pwd[15:] cphr = AES.new(key, AES.MODE_GCM, initv) realAssPass = cphr.decrypt(block) realAssPass = realAssPass[:-16].decode() return realAssPass l = [&quot;LOGIN.db&quot;, &quot;LOGIN.txt&quot;, &quot;LOGINe.db&quot;, &quot;LOGINe.txt&quot;, &quot;LOGINb.db&quot;, &quot;LOGINb.txt&quot;] def main(db=cdb, keylocation=ckey, dbName=l[0], fName=l[1]): cp = shutil.copy2(db, tmp + os.sep + fr&quot;{dbName}&quot;) f = open(keylocation, &quot;r&quot;, encoding=&quot;utf-8&quot;) local_state = f.read() local_state = json.loads(local_state) maKey = b64decode(local_state['os_crypt']['encrypted_key']) maKey = maKey[5:] maKey = win32crypt.CryptUnprotectData(maKey)[1] # gotTheKeyHoe, TimeToDeCode conn = sqlite3.connect(tmp + os.sep + fr&quot;{dbName}&quot;) cursor = conn.cursor() cursor.execute(&quot;SELECT action_url, username_value, password_value FROM logins&quot;) f2 = open(tmp + os.sep + fr&quot;{fName}&quot;, &quot;w&quot;) for i in cursor.fetchall(): site = i[0] user = i[1] pas = i[2] final = dec(pas, maKey) x = f&quot;[...] User: {user}, Pass: {final}, URl: {site}&quot; f2.write('\n' + x) f2.close() if triple: main() main(bdb, bkey, l[4], l[5]) main(edb, ekey, l[2], l[3]) elif both: main() main(edb, ekey, l[2], l[3]) else: try: main() except: main(db=edb, keylocation=ekey) </code></pre> <p>FYI i am studyin cybersec and came across a script to recover browser passwords, decided to write one myself</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:42:23.197", "Id": "521534", "Score": "1", "body": "This seems very hardcoded, especially your paths. How would this run on another persons system with a different file structure or even worse Linux? Disregarding the serverstuff I would look into [pathlib](https://docs.python.org/3/library/pathlib.html) and particular `Path`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T15:39:25.570", "Id": "521550", "Score": "0", "body": "@N3buchadnezzar it can never work on linux. thats one reason i posted it for a solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T20:36:35.147", "Id": "521583", "Score": "0", "body": "I [changed the title](https://codereview.stackexchange.com/posts/264094/revisions#rev-body-51d43f6f-0f30-460a-8233-4cf991a04ee8) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:09:10.873", "Id": "264094", "Score": "0", "Tags": [ "python", "beginner", "python-3.x", "security" ], "Title": "script to recover browser passwords" }
264094
max_votes
[ { "body": "<p>There are two things that can greatly improve your code's readability.</p>\n<p>First one is, using better names. Making a variable name short makes it easier to write it. However, code is more often read than written. Hence, its better to give variables a more meaningful name. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>chrome_db_path\nedge_db_path\nbreave_db_path\nchrome_key_path\n...\n</code></pre>\n<p>And also, as @N3buchadnezzar suggested, you could use <code>pathlib</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nfrom pathlib import Path\n\ntmp_dir = Path(os.getenv('TEMP'))\nuser_profile_dir = Path(os.environ['USERPROFILE'])\n\napp_data_local_dir = user_profile_dir / 'AppData/Local'\n\nLOGIN_DATA_PATH = 'User Data/Default/Login Data'\nLOCAL_STATE_PATH = 'User Data/Local State'\n\nchrome_dir = app_data_local_dir / 'Google/Chrome'\nedge_dir = app_data_local_dir / 'Microsoft/Edge'\nbrave_dir = app_data_local_dir / 'BraveSoftware/Brave-Browser'\n\nchrome_db_path = chrome_dir / LOGIN_DATA_PATH\nedge_db_path = edge_dir / LOGIN_DATA_PATH\nbrave_db_path = brave_dir / LOGIN_DATA_PATH\n\nchrome_key_path = chrome_dir / LOCAL_STATE_PATH\n...\n\nchrome_and_edge_exist = chrome_db_path.exists() and edge_db_path.exists()\nchrome_edge_and_brave_exist = chrome_and_edge_exist and brave_db_path.exists()\n...\n</code></pre>\n<p>Also, I would recommend you to use the <code>with</code> statement, to ensure files are always closed:</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n my_file = open(my_file_path)\n ...\nfinally:\n my_file.close()\n</code></pre>\n<p>Would be equivalent to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>with open(my_file_path) as my_file:\n ...\n</code></pre>\n<p>Using <code>pathlib</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>my_file_path = Path('some/path')\nwith my_file_path.open() as my_file:\n ...\n</code></pre>\n<p>Edit:</p>\n<p>After re-reading your code, it seems like a list is not the best data structure for the files used by the different browsers. A dict will be more suitable and readable:</p>\n<pre class=\"lang-py prettyprint-override\"><code>browser_files = {\n 'chrome': {\n 'db_file': 'LOGIN.db',\n 'output_file': 'LOGIN.txt'\n },\n 'edge': {\n 'db_file': 'LOGINe.db',\n 'output_file': 'LOGINe.txt'\n },\n ...\n}\n\nchrome_files = browser_files['chrome']\nmain(chrome_db_path, chrome_key_path, chrome_files['db_file'], chrome_files['db_file'])\n...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T16:16:23.587", "Id": "264096", "ParentId": "264094", "Score": "1" } } ]
<p>I'm currently learning Python for a masters and am trying to improve the best I can, as I'll need to know how to code in my future career.</p> <p>I currently have a function that builds a table from a dictionary, no matter how long the characters of either the keys or values are.</p> <p>However, I'm trying to get better and I'm sure there's a more &quot;Pythonic&quot; way to write this (i.e. a more simple way). This is just what I was able to come to with my limited knowledge.</p> <pre><code>def salaryTable(itemsDict): lengthRight=max( [ len(k) for k,v in itemsDict.items() ] ) lengthLeft=max( [ len(str(v)) for k,v in itemsDict.items() ] ) print( &quot;Major&quot;.ljust(lengthRight+7) + &quot;Salary&quot;.rjust(lengthLeft+7) ) print( '-' * (lengthRight+lengthLeft+14) ) for k,v in itemsDict.items(): print( k.ljust(lengthRight+7,'.') + str(v).rjust(lengthLeft+7) ) </code></pre> <p>And here's the two dictionaries I used to test both left and right:</p> <pre><code># what it produces when keys or values in the dictionary are longer than the parameter's # leftWidth and rightWidth majors={'English Composition':45000, 'Mechanical Engineering with a concentration in Maritime Mechanics':75000, 'Applied Math with a concentration in Computer Science':80000} # testing on a dictionary with a long value majors2={'English Composition':45000, 'Mechanical Engineering':75000, 'Applied Math':&quot;$100,000 thousand dollars per year USD&quot;} <span class="math-container">```</span> </code></pre>
[]
{ "AcceptedAnswerId": "264111", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T20:33:29.183", "Id": "264102", "Score": "6", "Tags": [ "python", "hash-map", "formatting" ], "Title": "Python function to print a two-column table from a dictionary" }
264102
accepted_answer
[ { "body": "<h3 id=\"identifiers-ou1y\">Identifiers</h3>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> recommends using snake_case for variables and functions, not camelCase.</p>\n<p>It should be <code>salary_table</code>, <code>length_right</code> and <code>items_dict</code>. Besides, do you really need <code>_dict</code> in <code>items_dict</code>?</p>\n<h3 id=\"are-you-sure-lengthleft-and-lengthright-are-proper-names-haez\">Are you sure lengthLeft and lengthRight are proper names?</h3>\n<p>It looks strange that lengthRight is the width of the left column; maybe it has something with the content of the column, but width_left looks better to me.</p>\n<h3 id=\"max-works-with-any-iterator-not-only-list-qw85\">Max works with any iterator, not only list</h3>\n<pre><code>width_left = max( len(k) for k,v in items_dict.items() )\n</code></pre>\n<p>works as well, and doesn't create a list.</p>\n<h3 id=\"you-can-iterate-over-keys-of-dict-without-items-1695\">You can iterate over keys of dict without items()</h3>\n<p>width_left = max( len(k) for k in items_dict )</p>\n<p>You can go further and use <code>max(map(len, itemsDict))</code>, but this is pythonic enough for me.</p>\n<h3 id=\"if-the-variable-is-not-used-point-this-out-with-5qlg\">If the variable is not used, point this out with _</h3>\n<pre><code>width_right = max( len(str(v)) for _, v in items_dict.items() )\n</code></pre>\n<p>But it is better to</p>\n<h3 id=\"use.values-if-you-dont-need-keys-5thz\">Use .values(), if you don't need keys</h3>\n<pre><code>width_right = max( len(str(v)) for v in items_dict.values() )\n</code></pre>\n<h3 id=\"avoid-magic-numbers-constants-without-explanation-wpz6\">Avoid &quot;magic numbers&quot; (constants without explanation)</h3>\n<p>Both lengths are added with 7; maybe it is better to add it at once and name it?</p>\n<pre><code>MINIMAL_WIDTH = 7\nwidth_left = max( len(k) for k in items_dict ) + MINIMAL_WIDTH\nwidth_right = max( len(str(v)) for v in items_dict.values() ) + MINIMAL_WIDTH\n</code></pre>\n<h3 id=\"f-strings-are-usually-more-readable-o98w\">F-strings are usually more readable</h3>\n<pre><code>print(f&quot;{k:.&lt;{length_right}}{v:&gt;{length_right}}&quot;)\n</code></pre>\n<h3 id=\"all-together-hke3\">All together</h3>\n<pre><code>def salary_table(items):\n MINIMAL_WIDTH = 7\n width_left = MINIMAL_WIDTH + max( len(k) for k in items )\n width_right = MINIMAL_WIDTH + max( len(str(v)) for v in items.values() )\n\n print( f&quot;{'Major':&lt;{width_left}}{'Salary':&gt;{width_right}}&quot; )\n print( '-' * (width_left + width_right) )\n\n for k, v in items.items():\n print( f&quot;{k:.&lt;{width_left}}{v:&gt;{width_right}}&quot; )\n</code></pre>\n<p>I don't know anything about the nature of keys and values; according to values given it can be better to rename <code>k</code> and <code>v</code> into <code>name</code> and <code>price</code>, and <code>items</code> into <code>books</code>.</p>\n<h3 id=\"alternatives-wpj0\">Alternatives</h3>\n<p>Pay attention to <a href=\"https://github.com/astanin/python-tabulate\" rel=\"nofollow noreferrer\">tabulate</a>. Maybe you better use it instead of inventing the wheel? There are also <a href=\"https://github.com/jazzband/prettytable\" rel=\"nofollow noreferrer\">PrettyTable</a> and <a href=\"https://github.com/foutaise/texttable/\" rel=\"nofollow noreferrer\">texttable</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T14:28:42.220", "Id": "521624", "Score": "1", "body": "You could make `MINIMAL_WIDTH` a defaulted kwarg of `salary_table()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:11:47.537", "Id": "521629", "Score": "0", "body": "Yes. Also the dot - it could be optionated, right? And the max width. And justification. I've thought about it - and the best choice would be to take one of the libraries in the Alternatives section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T19:25:48.097", "Id": "521645", "Score": "0", "body": "Thank you so much! Especially for taking the time to explain each step and directing me to those useful cites. I'm assuming there are pretty useful codes/mods (whatever you call them) there and that's why I can just search there and not have to \"inventing the wheel\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T19:27:41.917", "Id": "521646", "Score": "0", "body": "This was so helpful because I learned how these little improvements can help in a big, besides I'm trying to become a good programmer myself so knowing these things are important." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T05:28:11.697", "Id": "521665", "Score": "0", "body": "Steve McConnel's \"Code Complete\" is still the best. Also Robert Martin's \"Clean Code\"." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T08:49:51.017", "Id": "264111", "ParentId": "264102", "Score": "4" } } ]
<p>I'm trying to learn how to write code well in Python. I've been tinkering with a function that will return a list of all prime numbers between the two parameters. This is the best I could come up with considering my limited experience.</p> <p>Do you have any ideas of how this code can be improved to become more Pythonic? (Which I think means more efficient?) If you do, would you be so kind as to not explain what you would do differently?</p> <p>This would be such a help! Here's what I have so far:</p> <pre><code>def get_primes(start,end): return [num for num in range(start,end+1) if num&gt;1 and all(num%i!=0 for i in range(2,num))] get_primes(-41,41) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T21:08:13.383", "Id": "264130", "Score": "3", "Tags": [ "python", "functional-programming", "primes", "iteration" ], "Title": "Python – return list (or not?) of prime numbers between two numbers" }
264130
max_votes
[ { "body": "<p>If you are already into programming/STEM, you will already know finding prime numbers is a tough problem. Hence, I will not comment on the efficiency of checking whether a number is primer by checking all possible divisors (which is a terrible idea if you are trying to actually find prime numbers, but it is good enough if you are simply trying to learn).</p>\n<p>Now, regarding what pythonic means, it does not refer to efficiency at all. It is about readability and the way the language features are used (it is explained in a bit more depth in <a href=\"https://stackoverflow.com/a/25011492/13688761\">this</a> answer).</p>\n<p>Furthermore, if you are new to python, and want to learn about best practises, I would recommend you giving a read to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP-8</a>. It is a style guide for python code widely followed by the community.</p>\n<p>Edit:</p>\n<p>Still, as a comment on your code, I feel the logic to check whether a number is primer or not is complex enough to be encapsulated in a function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterable\n\ndef is_prime(num: int) -&gt; bool:\n return num&gt;1 and all(num%i!=0 for i in range(2,num))\n\ndef get_primes(start: int, end:int) -&gt; Iterable[int]:\n return [num for num in range(start,end+1) if is_prime(num)]\n\nget_primes(-41,41)\n</code></pre>\n<p>If you are not yet familiar with it, the syntax used above is called type annotations. You can read more about it <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"noreferrer\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T21:26:55.837", "Id": "264132", "ParentId": "264130", "Score": "6" } } ]
<p>How can I improve efficiency/readability of the following code?</p> <blockquote> <p>It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.</p> </blockquote> <p><a href="https://projecteuler.net/problem=52" rel="nofollow noreferrer">https://projecteuler.net/problem=52</a></p> <pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python def sameDigits(a, b): return sorted(str(a)) == sorted(str(b)) def main(): found = False i = 2 while not found: x2 = i * 2 x3 = i * 3 x4 = i * 4 x5 = i * 5 x6 = i * 6 if ( sameDigits(i, x2) and sameDigits(i, x3) and sameDigits(i, x4) and sameDigits(i, x5) and sameDigits(i, x6) ): found = True print(i) i += 1 if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
{ "AcceptedAnswerId": "264139", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T06:28:46.657", "Id": "264138", "Score": "1", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Permuted multiples in python" }
264138
accepted_answer
[ { "body": "<h2 id=\"readablilitypythonization-n2fr\">Readablility/pythonization</h2>\n<h3 id=\"pep8-is-your-friend-2zpr\"><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> is your friend</h3>\n<p>Use recommended practices, like using snake_case instead of camelCase for functions and variables.</p>\n<h3 id=\"short-circuit-evaluation-1rzf\">Short-circuit evaluation</h3>\n<p><code>and</code> and <code>or</code> operators evaluate the second argument only if the first can't tell the value - like <code>False</code> for <code>and</code> and <code>True</code> for <code>or</code>. So, if you move all multiplications in a condition, some of them will not be calculated.</p>\n<pre><code>if same_digits(i, x*2) and same_digits(i,x*3) and ...\n</code></pre>\n<h3 id=\"move-repeating-expressions-into-loops-ai3e\">Move repeating expressions into loops</h3>\n<p>Luckily, Python has functions to check several expressions for <code>True</code> at once: <code>any</code> for at least one <code>True</code> and <code>all</code> for all. They work with a short-circuit and can work with any iterable - like generator expression:</p>\n<pre><code>if all(same_digits(i, x*j) for j in range(1,7)):\n</code></pre>\n<h3 id=\"generating-an-infinite-loop-with-itertools.count-s1xc\">Generating an infinite loop with itertools.count()</h3>\n<p>There's a more pythonic way to have something like unlimited range: itertools.count()</p>\n<pre><code>from itertools import count\nfor i in count(2):\n #no need to increment i\n</code></pre>\n<h3 id=\"using-break-instead-of-found-variable-lkii\">Using <code>break</code> instead of <code>found</code> variable</h3>\n<p>Though not a structured feature, it can be useful</p>\n<pre><code>for ...:\n if ...:\n break\n</code></pre>\n<h3 id=\"separate-algorithm-and-input-output-7fev\">Separate algorithm and input-output</h3>\n<p>Return the value from the function, not output it. <code>return</code> statement works just like break, so we can omit it.</p>\n<h3 id=\"all-together-3bgy\">All together</h3>\n<pre><code>from itertools import count\n\ndef same_digits(a, b):\n return sorted(str(a))==sorted(str(b))\n\ndef main():\n for i in count(2):\n if all(same_digits(i, x*j) for j in range(1,7)):\n return i\n\nif __name__ == &quot;__main__&quot;:\n print(main())\n</code></pre>\n<h2 id=\"optimizations-7ftq\">Optimizations</h2>\n<p>I don't think you can change the complexity of an algorithm, but you can avoid unnecessary actions. Profile the code for everything below - Python is a very high-level programming language, and built-in functions can prove faster then better algorithms for small optimizations .</p>\n<h3 id=\"same_digits-y3y9\">same_digits</h3>\n<p>Instead of using str, divide (with divmod) both numbers and count digits in a list - adding for a and subtracting for b. If at some point you reach negative value or lengths are different - return <code>False</code>. Counting digits is slightly faster than sorting, and you avoid dividing after problem is found.</p>\n<h3 id=\"multiples-of-9-z9i2\">Multiples of 9</h3>\n<p>The number with this property should be a very specific. The sum of its digits remains the same after multiplication (because digits are the same). If the number is a multiple of 3, the sum of its digits also will be the multiple of 3, the same for 9. But <span class=\"math-container\">\\$3i\\$</span> is a multiple of 3 and has the same digits, so <span class=\"math-container\">\\$i\\$</span> will be the multiple of 3, <span class=\"math-container\">\\$i=3k\\$</span>. Once again, <span class=\"math-container\">\\$3i=9k\\$</span> will be the multiple of 9, so i will be the multiple of 9. No sense to check not multiples of 9:</p>\n<pre><code>for i in count(9,9):\n</code></pre>\n<h3 id=\"i-should-have-the-same-number-of-digits-yon3\"><code>6*i</code> should have the same number of digits</h3>\n<p>The second idea is that <code>6*i</code> should have the same number of digits with i. You can refactor the loop into nested loops: outer for the number of digits (name it <code>d</code>) and inner for numbers from 100...08 (<code>d</code> digits) to 100..00 (<code>d+1</code> digits)/6, everything bigger will make <code>6*i</code> have <code>d+1</code> digit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T08:26:23.870", "Id": "264139", "ParentId": "264138", "Score": "3" } } ]
<p>Below is my attempt at the challenge found <a href="https://github.com/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph_build_order/build_order_challenge.ipynb" rel="nofollow noreferrer">here</a>. The challenge is &quot;Find a build order given a list of projects and dependencies.&quot; Already given are the classes Node and Graph (which I can add if anyone needs them to help review my code), and also</p> <pre><code>class Dependency(object): def __init__(self, node_key_before, node_key_after): self.node_key_before = node_key_before self.node_key_after = node_key_after </code></pre> <p>I came up with the below:</p> <pre><code>class BuildOrder(object): def __init__(self, dependencies): self.dependencies = dependencies self.graph = Graph() self._build_graph() def _build_graph(self): for dependency in self.dependencies: self.graph.add_edge(dependency.node_key_before, dependency.node_key_after) def find_build_order(self): processed_nodes = [n for n in self.graph.nodes.values() if n.incoming_edges == 0] if not processed_nodes: return None num_processed = len(processed_nodes) num_nodes = len(self.graph.nodes) while num_processed &lt; num_nodes: for node in [n for n in processed_nodes if n.visit_state == State.unvisited]: node.visit_state = State.visited for neighbor in list(node.adj_nodes.values()): node.remove_neighbor(neighbor) processed_nodes += [n for n in self.graph.nodes.values() if n.incoming_edges == 0 and n.visit_state == State.unvisited] if len(processed_nodes) == num_processed: return None else: num_processed = len(processed_nodes) return processed_nodes </code></pre> <p>When I timed it against the solution given <a href="https://github.com/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph_build_order/build_order_solution.ipynb" rel="nofollow noreferrer">here</a>, mine was ~4.5x faster. This was surprising, as throughout completing the challenges in the repo, I usually have approx same runtime as the given solution, or worse.</p> <p>I'd like to know if the above is pythonic, is it readable and how would you improve it? Also, I have deliberately left out comments - which lines in this should probably have a comment to help others understand it? Thanks!</p>
[]
{ "AcceptedAnswerId": "264148", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T11:03:54.547", "Id": "264145", "Score": "0", "Tags": [ "python-3.x", "graph" ], "Title": "Build order from a dependency graph (Python)" }
264145
accepted_answer
[ { "body": "<p><strong>&quot;Pythonicness&quot;</strong></p>\n<p>The code is easy to read and understandable - a good start.</p>\n<ol>\n<li>Remove <code>(object)</code> when declaring classes, it is not needed :)</li>\n<li>Use type annotations!</li>\n</ol>\n<pre><code>from typing import List\n\ndef __init__(self, node_key_before: Node, node_key_after: Node):\ndef __init__(self, dependencies: List[Dependency]):\ndef find_build_order(self) -&gt; List[Node]:\n</code></pre>\n<ol start=\"3\">\n<li>The statement:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>if len(processed_nodes) == num_processed:\n return None\nelse:\n num_processed = len(processed_nodes)\n</code></pre>\n<p>Can be rewritten as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if len(processed_nodes) == num_processed:\n return None\nnum_processed = len(processed_nodes)\n</code></pre>\n<p>That is it for this section (for now - I might edit later).</p>\n<p><strong>Algorithm and runtime</strong></p>\n<p>Let's talk complexity. This algorithm runs in <code>O(V * V + E)</code>, it can be seen from the example of the following graph:</p>\n<pre><code>a -&gt; b -&gt; c -&gt; d -&gt; ... (V times) \n</code></pre>\n<p>You will iterate over the <code>V</code> nodes and for each of them you will search (twice in fact) over all the <code>V</code> nodes. The reason we add <code>+ E</code> is since you will also delete all edges of the graph.</p>\n<p>Now the correct algorithm can do this in <code>O(V + E)</code>, the analysis a just a little bit more complex but you can do it yourself.</p>\n<p>Why is my algorithm faster in tests than?<br />\nI cannot answer for sure but 2 explanations are possible:</p>\n<ol>\n<li><p>The graph in the test has many many edges and <code>E</code> is close to <code>V * V</code>, therefore the fact that the time complexity is worst is not relevant in practice.</p>\n</li>\n<li><p>After a quick look at the code in the answer you can see it has more functions and more dictionaries, this is probably the reason your code is faster in with smaller graphs, also cache probably plays a factor here.</p>\n</li>\n</ol>\n<hr />\n<p>I might add some more stuff. This is it for now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T17:49:59.220", "Id": "521684", "Score": "0", "body": "Am I right in thinking that I can remove the 'else' since the 'if' results in a return statement? I have seen a lot of code that just does 'if' several times, without returns in the bodies of the 'if's. I guess I am asking, is 'else' (and even 'elif') actually necessary ever?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T17:56:48.170", "Id": "521685", "Score": "0", "body": "Would you be able to give an example of how to do the type annotations please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T18:49:31.390", "Id": "521693", "Score": "0", "body": "Yes you are right, this is also point 3 in the first section. I will edit to add a type annotation, no problem." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T16:54:46.850", "Id": "264148", "ParentId": "264145", "Score": "1" } } ]
<p>I have the python script that creates a sqlite database and fills it with data (originally coming from a json file). At the time I execute the code below, my <code>word</code> table has about 400 000 entries.</p> <pre><code>con = sqlite3.connect(&quot;words.db&quot;) cur = con.cursor() form_of_words_to_add: &quot;list[tuple(int, str)]&quot; = [] # other code fills this list with also about 400 000 entries index = 0 for form_of_entry in form_of_words_to_add: base_word = form_of_entry[1] word_id = form_of_entry[0] unaccented_word = unaccentify(form_of_entry[1]) index += 1 cur.execute(&quot;INSERT INTO form_of_word (word_id, base_word_id) \ SELECT ?, COALESCE ( \ (SELECT w.word_id FROM word w WHERE w.word = ?), \ (SELECT w.word_id FROM word w WHERE w.canonical_form = ?), \ (SELECT w.word_id FROM word w WHERE w.word = ?) \ )&quot;, (word_id, base_word, base_word, unaccented_word)) if index == 1000: print(index) con.commit() index = 0 </code></pre> <p>The code works, but it is very slow and only achieves about 15 insertions per second. I am looking for ideas to optimize it. The bottleneck appears to be the sql query, the rest of the loop takes almost no time in comparison once I comment the SQL out. Is there anything obvious I could do to optimize this very slow process? I am having a hard time thinking of a simpler query. I already tried using PyPy, but this did not increase performance.</p> <p>The relevant entries in the database are as follows:</p> <pre><code>CREATE TABLE word ( word_id INTEGER NOT NULL PRIMARY KEY, pos VARCHAR, --here had been pos_id canonical_form VARCHAR, romanized_form VARCHAR, genitive_form VARCHAR, adjective_form VARCHAR, nominative_plural_form VARCHAR, genitive_plural_form VARCHAR, ipa_pronunciation VARCHAR, lang VARCHAR, word VARCHAR, lang_code VARCHAR ); CREATE TABLE form_of_word ( word_id INTEGER NOT NULL, base_word_id INTEGER, FOREIGN KEY(word_id) REFERENCES word(word_id), FOREIGN KEY(base_word_id) REFERENCES word(word_id) ); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:11:04.710", "Id": "521732", "Score": "6", "body": "Add indexes on word and canonical_form." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:23:23.360", "Id": "521734", "Score": "0", "body": "@PavloSlavynskyy Ooh thank you, that was very much the answer. Now the entire code ran in seven seconds, instead of the seven hours it would have taken at original speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T12:02:59.147", "Id": "521744", "Score": "3", "body": "@PavloSlavynskyy Do you think you could add an explanation of why indexes help and expand your comment into a full answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T12:04:51.917", "Id": "521745", "Score": "0", "body": "Yes, but I don't have time right now. Maybe in 10 hours or so" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T14:44:58.037", "Id": "521759", "Score": "0", "body": "How is `word` populated? You show the population of `form_of_word` but not `word`. Are the contents of `form_of_words_to_add` the same as the `word` table?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:30:36.453", "Id": "521771", "Score": "0", "body": "@Reinderien `word` only shares the ID with the form_of_words entries, so it is probably not very useful for optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T17:40:14.433", "Id": "521805", "Score": "1", "body": "There was an article posted about this topic on Hacker News recently, in case you're curious. [Article](https://avi.im/blag/2021/fast-sqlite-inserts/) and [discussion](https://news.ycombinator.com/item?id=27872575)." } ]
{ "AcceptedAnswerId": "264182", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T10:19:00.067", "Id": "264172", "Score": "4", "Tags": [ "python", "performance", "sql", "sqlite" ], "Title": "Optimizing the insertion of 400 000 records in sqlite" }
264172
accepted_answer
[ { "body": "<p>Other than @PavloSlavynskyy's correct recommendation to add indices:</p>\n<ul>\n<li>Whereas autocommit is <a href=\"https://docs.python.org/3/library/sqlite3.html#sqlite3-controlling-transactions\" rel=\"nofollow noreferrer\">off by default for the Python library</a>, I doubt your code is doing what you think it's doing because as soon as your first <code>commit</code> occurs autocommit is going to be re-enabled. Explicitly start a transaction at the beginning of your 1000-row pages to avoid this issue.</li>\n<li>Rather than manually incrementing your loop index, use <code>enumerate</code></li>\n<li><a href=\"https://docs.python.org/3/library/sqlite3.html#using-the-connection-as-a-context-manager\" rel=\"nofollow noreferrer\">SQLite connection objects are context managers</a> - so use a <code>with</code>.</li>\n<li>Rather than</li>\n</ul>\n<pre><code> base_word = form_of_entry[1]\n word_id = form_of_entry[0]\n</code></pre>\n<p>you should unpack:</p>\n<pre><code>word_id, base_word = form_of_entry\n</code></pre>\n<ul>\n<li>Your code is going to miss a commit for the last segment of words in all cases except the unlikely one that the total number of words is a multiple of 1000. A trailing <code>commit()</code> should fix this.</li>\n<li>Rather than modulating your index, consider just having a nested loop - which also would need neither an outside <code>commit</code> nor <code>enumerate</code>. There are many ways to do this, but basically:</li>\n</ul>\n<pre><code>for index in range(0, len(form_of_words_to_add), 1000):\n cur.execute('begin')\n for word_id, base_word in form_of_words_to_add[index: index+1000]:\n cur.execute('insert ...')\n con.commit()\n</code></pre>\n<ul>\n<li>Rather than doing individual, filtered inserts into the destination table, consider doing your inserts unfiltered into a <a href=\"https://sqlite.org/lang_createtable.html\" rel=\"nofollow noreferrer\">temporary table</a>, keeping them to the &quot;literal&quot; data (no <code>where</code> etc.). After all of the inserts are done, follow it with one single statement using proper <code>join</code>s, roughly looking like</li>\n</ul>\n<pre class=\"lang-sql prettyprint-override\"><code>insert into form_of_word(word_id, base_word_id)\nselect tw.word_id, w.word_id\nfrom word w\njoin temp_words tw on (\n w.canonical_form = tw.base_word\n or w.word = tw.base_word\n or w.word = tw.unaccented_word\n)\n</code></pre>\n<p>This temporary table can be told to <a href=\"https://sqlite.org/pragma.html#pragma_temp_store\" rel=\"nofollow noreferrer\">live in memory via pragma</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:26:26.903", "Id": "521770", "Score": "1", "body": "Thank you very much for the answer! I implemented all of your suggestions except the temporary tables so far and got from 7 seconds (achieved after adding the indexing) to 4 seconds. I think the committing worked fine in my version of sqlite, when I accessed it through another DB navigator it updated exactly in the 1000-intervals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T20:02:15.743", "Id": "521774", "Score": "1", "body": "You could also try enabling wal mode. That can sometimes speed things up significantly. See https://sqlite.org/wal.html" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T13:58:20.170", "Id": "264182", "ParentId": "264172", "Score": "7" } } ]
<p>I'm going to start out by saying this is the 1st python program I have ever written and have no real background in the language so my code is probably pretty rough. Take it easy on me!</p> <p>When I wrote this it works fine for a small number of tickers but when I have a file with 6k+ it is very slow. Now I know there are other ways I can improve performance BUT I want to try and tackle the async thing first.</p> <p>I thought it was as simple as making the read_ticker_file function async and adding await in front of the yfin_options() call but obviously that didn't work.</p> <p>I'm thinking possibly I need to restructure the way things are called but kind of stuck here. Hoping someone can point me in the right direction! Thanks in advance</p> <pre><code>import logging import pyodbc import config import yahoo_fin as yfin from yahoo_fin import options from datetime import datetime, date from selenium import webdriver def main(): read_ticker_file() def init_selenium(): driver = webdriver.Chrome(config.CHROME_DRIVER) return driver def yfin_options(symbol): logging.basicConfig(filename='yfin.log', level=logging.INFO) logging.basicConfig(filename='no_options.log', level=logging.ERROR) try: # get all options dates (in epoch) from dropdown on yahoo finance options page dates = get_exp_dates(symbol) # iterate each date to get all calls and insert into sql db for date in dates: arr = yfin.options.get_calls(symbol, date) arr_length = len(arr.values) i = 0 for x in range(0, arr_length): strike = str(arr.values[i][2]) volume = str(arr.values[i][8]) open_interest = str(arr.values[i][9]) convert_epoch = datetime.fromtimestamp(int(date)) try: sql_insert(symbol, strike, volume, open_interest, convert_epoch) i += 1 except Exception as insert_fail: print(&quot;I failed at sqlinsert {0}&quot;.format(insert_fail)) file_name_dir = &quot;C:\\temp\\rh\\options{0}{1}.xlsx&quot;.format(symbol, date) logging.info(arr.to_excel(file_name_dir)) except Exception as e: bad_tickers_file_dir = config.BAD_TICKERS f = open(bad_tickers_file_dir, &quot;a&quot;) f.write(symbol) f.write('\n') def sql_insert(symbol, strike, volume, open_interest, exp_date): conn_string = ('Driver={SQL Server};' 'Server={0};' 'Database={1};' 'Trusted_Connection=yes;').format(config.SERVER, config.DATABASE) conn = pyodbc.connect(conn_string) cursor = conn.cursor() insert_string = &quot;&quot;&quot;INSERT INTO dbo.options (Ticker, Strike, Volume, OpenInterest, expDate) VALUES (?, ?, ?, ?, ?)&quot;&quot;&quot; cursor.execute(insert_string, symbol, strike, volume, open_interest, str(exp_date)) conn.commit() def get_exp_dates(symbol): url = &quot;https://finance.yahoo.com/quote/&quot; + symbol + &quot;/options?p=&quot; + symbol chromedriver = init_selenium() chromedriver.get(url) # Yahoo Finance options dropdown class name (find better way to do this) select_dropdown = chromedriver.find_element_by_css_selector(&quot;div[class='Fl(start) Pend(18px)'] &gt; select&quot;) options_list = [x for x in select_dropdown.find_elements_by_tag_name(&quot;option&quot;)] dates = [] for element in options_list: dates.append(element.get_attribute(&quot;value&quot;)) return dates def read_ticker_file(): file1 = open(config.TICKER_FILE, 'r') lines = file1.readlines() count = 0 # loop to read each ticker in file for line in lines: count += 1 line = line.strip('\n') line = line.strip() yfin_options(line) if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:09:43.483", "Id": "521767", "Score": "1", "body": "Just to be sure (in addition to your remark), you're aware that, at best, ``async`` will still be single-threaded, right? It's definitely something worth learning, but it's primarily intended to allow a single thread to run multiple tasks where some may be blocked by IO at any given moment. Just want to make sure that's what you want to learn about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:10:57.720", "Id": "521768", "Score": "1", "body": "BTW, this might get closed since your code is technically non-working (it doesn't do what you want it to do, since you want it to be ``async``.) You might get better results asking this over at Stack Overflow, then come back here once you have the code you want and you just want to know how to make it better/cleaner/nicer/more Pythonic/etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T23:33:21.543", "Id": "521779", "Score": "0", "body": "@scnerd I know the concept of how async works and I think I can use that to my advantage in this case. So I am utilizing selenium to initialize chrome driver and load a web page. I was thinking that I could use the async wait functionality to pause the execution while the web page loaded and spin up another one in the background." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T02:23:36.100", "Id": "521780", "Score": "0", "body": "I would encourage you to change you strategy for learning parallelism in Python. Start with the basics: writing programs that use multiple processes or threads (learn both and why you would choose one or the other). The place to start that is the multiprocessing module. Then learn async, which generally applies to a narrower range of real-world situations -- at least in my experience writing programs making many internet requests and/or DB calls." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T14:16:33.607", "Id": "264185", "Score": "3", "Tags": [ "python", "beginner", "asynchronous", "asyncio" ], "Title": "Converting python code to async calls" }
264185
max_votes
[ { "body": "<p>After doing some reading and taking the advice of FMc, I decided against async for what I was doing.</p>\n<p>I ended up with multi-processing</p>\n<pre><code>pool = multiprocessing.Pool()\n\n# input list\ninputs = read_ticker_file()\n# pool object with number of element\npool = multiprocessing.Pool(processes=4)\n\npool.map(yfin_options, inputs)\n\npool.close()\npool.join()\n</code></pre>\n<p>I've noticed some weird behavior but we'll see if it gets the same result more quickly when it's done running.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T11:43:41.510", "Id": "264205", "ParentId": "264185", "Score": "1" } } ]
<p>I am computing pairwise Euclidean distances for 3-D vectors representing particle positions in a periodic system. The minimum image convention is applied for each periodic boundary such that a particle only considers the <em>nearest image</em> of another particle when computing the distance.</p> <p>This code is part of a larger post-processing effort in Python. Here is a working example of what I am implementing:</p> <pre><code>import numpy as np from scipy.spatial.distance import cdist s = np.array([40, 30, 20]) half_s = 0.5*s a = np.transpose(np.random.rand(1000,3) * s) b = np.transpose(np.random.rand(1000,3) * s) dists = np.empty((3, a.shape[1]*b.shape[1])) for i in range(3): dists[i,:] = cdist(a[i,:].reshape(-1,1), b[i,:].reshape(-1,1), 'cityblock').ravel() dists[i,:] = np.where(dists[i,:] &gt; half_s[i], dists[i,:] - s[i], dists[i,:]) dists = np.sqrt(np.einsum(&quot;ij,ij-&gt;j&quot;, dists, dists)) </code></pre> <p>The domain size <code>s</code> and the 3xn particle position arrays <code>a</code> and <code>b</code> are obtained from existing data structures, but this example uses sizes I would typically expect. I should emphasize that <code>a</code> and <code>b</code> can have different lengths, but on average I expect the final <code>dists</code> array to represent around a million distances (+/- an order of magnitude).</p> <p>The <strong>last 5 lines computing the distances</strong> will need to be run many thousands of times, so <strong>this is what I hope to optimize</strong>.</p> <p>The difficulty arises from the need to apply the minimum image convention to each component independently. I haven't been able to find anything which can beat SciPy's cdist for computing the unsigned distance components, and NumPy's einsum function seems to be the most efficient way to reduce the distances for arrays of this size. At this point, the bottleneck in the code is in the NumPy where function. I also tried using NumPy's casting method by replacing the penultimate line with</p> <pre><code>dists[i,:] -= (dists[i,:] * s_r[i] + 0.5).astype(int) * s[i] </code></pre> <p>where <code>s_r = 1/s</code>, but this yielded the same runtime. <a href="https://doi.org/10.1524/zpch.2013.0311" rel="nofollow noreferrer">This paper</a> discusses various techniques to handle this operation in C/C++, but I'm not familiar enough with the underlying CPython implementation in NumPy/SciPy to determine what's best here. I'd love to parallelize this section, but I had little success with the multiprocessing module and cdist is incompatible with Numba. I would also entertain suggestions on writing a C extension, though I've never incorporated one in Python before.</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T02:24:13.987", "Id": "264196", "Score": "2", "Tags": [ "python-3.x", "numpy", "scipy" ], "Title": "Applying Minimum Image Convention in Python" }
264196
max_votes
[ { "body": "<p>I think you could move the <code>where</code> function out of the loop:</p>\n<pre><code>dists = np.empty((3, a.shape[1] * b.shape[1]))\n\nfor i in range(3):\n dists[i, :] = cdist(a[i, :].reshape(-1, 1),\n b[i, :].reshape(-1, 1), 'cityblock').reshape(-1)\n\ndists = np.where(dists &gt; half_s[..., None], dists - s[..., None], dists)\n...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T09:32:05.343", "Id": "268284", "ParentId": "264196", "Score": "1" } } ]
<p>I solved <a href="https://projecteuler.net/problem=58" rel="nofollow noreferrer">problem 58</a> in Project Euler and I am happy with my solution. However, are there any areas where I can improve my code here as I am learning how to write good python code.</p> <p>Prompt:</p> <blockquote> <p>Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.</p> <pre><code>37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 </code></pre> <p>It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.</p> <p>If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?</p> </blockquote> <pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python from funcs import isPrime # Corner values of a square of size s have values: # s^2 - 3s + 3, s^2 - 2s + 2, s^2 - s + 1, s^2 def corner_values(n): &quot;&quot;&quot; returns a tuple of all 4 corners of an nxn square &gt;&gt;&gt; corner_values(3) (3, 5, 7, 9) &quot;&quot;&quot; return (n ** 2 - 3 * n + 3, n ** 2 - 2 * n + 2, n ** 2 - n + 1, n ** 2) def main(): ratio, side_length = 1, 1 primes, total = 0, 0 while ratio &gt;= 0.1: side_length += 2 for n in corner_values(side_length): if isPrime(n): primes += 1 total += 1 else: total += 1 ratio = primes / total return side_length - 2 if __name__ == &quot;__main__&quot;: print(main()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T08:16:06.510", "Id": "521785", "Score": "0", "body": "What is funcs module?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T09:57:13.843", "Id": "521787", "Score": "0", "body": "@PavloSlavynskyy These are some local helper functions I have written." } ]
{ "AcceptedAnswerId": "264214", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T07:13:53.460", "Id": "264201", "Score": "1", "Tags": [ "python-3.x", "programming-challenge" ], "Title": "Ratio of primes in square diagonals | Problem 58 Project Euler" }
264201
accepted_answer
[ { "body": "<h3 id=\"identifiers-consistency-6w7i\">Identifiers consistency</h3>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> recommends snake_case, not camelCase for functions and variables; <code>isPrime</code> breaks this. Moreover, PEP8 recommends consistency over other matters (except for readability). If it's your function - maybe you should rework it one way or another?</p>\n<h3 id=\"main-is-unclear-name-6p0t\"><code>main</code> is unclear name</h3>\n<p>Yes, it makes clear that it makes some &quot;main work&quot; in the file, but <code>find_prime_diagonals_size</code> (ok, bad example) or something like that could be more readable. How about <code>solve_euler58</code>?</p>\n<h3 id=\"dry-in-if-branches-8u0u\">DRY in if branches</h3>\n<p>If the last statement in both <code>if</code> and <code>else</code> branches is the same - it can be moved out and put after <code>if-else</code>:</p>\n<pre><code> if isPrime(n):\n primes += 1\n total += 1\n</code></pre>\n<p>The same applies if you have first statement the same - it could be put before <code>if</code>.</p>\n<h3 id=\"total-and-side_length-are-loop-variables-and-are-defined-by-each-other-w6ey\"><code>total</code> and <code>side_length</code> are loop variables and are defined by each other</h3>\n<p><code>total</code> increases by 4 every <code>while</code> iteration, and <code>side_length</code> increases by 2. Consider using only 1 variable and (arguably) itertools.count, like</p>\n<pre><code>for side_length in itertools.count():\n ...\n if primes/(side_length*2-1)&lt;0.1:\n return side_length\n</code></pre>\n<h3 id=\"corner_values-return-a-progression-so-it-can-be-replaced-with-range-hxb7\"><code>corner_values</code> return a progression, so it can be replaced with range</h3>\n<pre><code>range(n**2 - 3*n + 3, n**2 + 1, n - 1)\n</code></pre>\n<p>returns the same values as <code>corner_values</code>, even probably slightly faster, but I'm not sure if it's more readable. Probably not. Still, you should be aware of possibilities.</p>\n<h3 id=\"divisions-are-slower-than-multiplications-floating-point-operations-are-slower-than-integers-71wh\">Divisions are slower than multiplications, floating point operations are slower than integers</h3>\n<p>It's not really important here; but I think you should know that. You're calculating <code>primes / total &gt;= 0.1</code> every loop; multiply both sides by 10*total, and the expression will be <code>10 * primes &gt;= total</code>, which calculates slightly faster. I don't think it's really needed here, it looks more readable in the first form, just FYI.</p>\n<h3 id=\"complexity-of-isprime-is-unknown-augz\">Complexity of <code>isPrime</code> is unknown</h3>\n<p>I think this is the bottleneck of the code. Does it use any sieve or is just a brute force division check?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T18:12:40.617", "Id": "264214", "ParentId": "264201", "Score": "2" } } ]
<p>Python Noob building an automation irrigation system in Python for Raspberry Pi.</p> <p>Python has two functions in the most basic use case:</p> <ol> <li>on/off the LED (which will in future be a relay-&gt;pump) and</li> <li>Notifies &quot;This is out of water&quot; (which will in future be a HTTP post)</li> </ol> <ul> <li>I have a GPIO switch that working successfully on: <code>water_level_sensor.value </code></li> <li>I obviously don't want the While loop to just spam that its looping, it should <strong>only</strong> print on each change of state</li> </ul> <p>The below code appears to work successfully on both use cases, however, I am unsatisfied/unconfident that this is a very good/clean method to achieve the &quot;print once&quot; per change of state loop.</p> <p>It works by having:</p> <ul> <li>X = &quot;Wet&quot; outside the outer while loop</li> <li>X = &quot;Dry&quot; at the bottom of the nest while</li> <li>X = &quot;NULL&quot; at the bottom of the inner loop</li> </ul> <p>It just seems messy... <strong>How should someone solve this kind of problem neatly/efficiently?</strong> I'm also concerned that I will struggle to pull out of this solution any state data.</p> <pre><code>def water_level(): while True: x = &quot;Wet&quot; while water_level_sensor.value == False: water_level_led.value = False if x == &quot;Wet&quot;: print(&quot;They System has Water&quot;) x = &quot;Dry&quot; while water_level_sensor.value == True: water_level_led.value = True if x == &quot;Dry&quot;: print(&quot;The System is Dry and needs Water&quot;) x = &quot;&quot; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T14:51:54.480", "Id": "521845", "Score": "1", "body": "Welcome to Code Review! 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": "264281", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T14:19:15.263", "Id": "264236", "Score": "4", "Tags": [ "python", "python-3.x", "raspberry-pi", "status-monitoring" ], "Title": "Loop to print changes in irrigation state to turn on and off a pump when water is low" }
264236
accepted_answer
[ { "body": "<p>I agree with @Anonymous that you should not loop continuously like that, or you'll waste energy and CPU time continuously checking the values. To solve this you can just sleep, wake up every minute, check the state and go back to sleep.</p>\n<p>Another more code-style related observation is that you don't need to nest <code>while</code> loops like that, but only keep track of the last value.</p>\n<p>The variable naming is also not ideal, use descriptive naming instead of <code>x</code>. Actually in this case, you do not need the variable at all.</p>\n<p>For instance, you could do:</p>\n<pre><code>import time\n\ndef water_level():\n previous_water_low = None\n while True:\n water_low = water_level_sensor.value\n\n if water_low != previous_water_low:\n on_water_level_change(water_low)\n\n previous_water_low = water_low\n time.sleep(60)\n\n def on_water_level_change(water_low: bool):\n water_level_led.value = water_low\n\n if water_low:\n print(&quot;The System is Dry and needs Water&quot;)\n else:\n print(&quot;They System has Water&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T22:45:15.177", "Id": "521966", "Score": "0", "body": "Thank you for the detail and example code - very helpful. Its slightly confusing to me as my coding is not sufficient to understand what is fully going on here. particularly around \"on_water_level_change\" and \"def on_water_level_change(water_low: bool):\" Its very efficient looking solution though. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T07:37:31.257", "Id": "521987", "Score": "0", "body": "@GlennB This is similar to what @FMc proposed in the other answer. You just keep track of what the last `water_level_sensor` value and if that changes it triggers a `on_water_level_change`, where you can take actions based on the change. I also added an extra sleep to reduce energy use. I just like to factor the real actions into an own function, so that you have a loop doing the triggering and another function defining what happens on water level change. You could also change the trigger condition (multiple sensors? wait for multiple dry minutes?), without changing the action function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-04T14:47:42.543", "Id": "524814", "Score": "0", "body": "Thanks @francesco-pasa; I updated your code and its working perfectly with the following format" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T14:44:02.863", "Id": "264281", "ParentId": "264236", "Score": "4" } } ]
<p>This code was an answer to my own <a href="//stackoverflow.com/questions/68411538">question on SO</a>, however I am looking at the line <code>global X</code> and wondering if there is a better way to do this. I try to minimize the amount of global declarations in my code in order to avoid namespace collisions. I'm considering changing this code to use <a href="https://docs.python.org/3/library/multiprocessing.shared_memory.html" rel="nofollow noreferrer">multiprocessing.shared_memory</a>, but I would like some feedback on the code below 'as is'.</p> <p>The purpose of this code is to compute in parallel the <a href="https://en.wikipedia.org/wiki/Pearson_correlation_coefficient" rel="nofollow noreferrer">Pearson's product-moment correlation coefficient</a> on all pairs of random variables. The columns of NumPy array <code>X</code> index the variables, and the rows index the sample.</p> <p><span class="math-container">$$r_{x,y} = \frac{\sum_{i=1}^{n}(x_i- \bar{x})(y_i- \bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i- \bar{x})^2}\sqrt{\sum_{i=1}^{n}(y_i- \bar{y})^2}}$$</span></p> <p>This is actual code that should run on your machine (ex. <code>python 3.6</code>).</p> <pre class="lang-py prettyprint-override"><code>from itertools import combinations import numpy as np from scipy.stats import pearsonr from multiprocessing import Pool X = np.random.random(100000*10).reshape((100000, 10)) def function(cols): result = X[:, cols] x,y = result[:,0], result[:,1] result = pearsonr(x,y) return result def init(): global X if __name__ == '__main__': with Pool(initializer=init, processes=4) as P: print(P.map(function, combinations(range(X.shape[1]), 2))) </code></pre> <p>In addition to considering <code>global X</code>, any constructive feedback and suggestions are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T15:18:08.480", "Id": "521850", "Score": "2", "body": "Please clarify the purpose of the code. What problem does it solve? Perhaps taking a look at the [help/on-topic] will help in determining whether you posted your question in the right place, especially the part talking about example code might be relevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T15:23:03.327", "Id": "521851", "Score": "2", "body": "\"toy examples\", sadly, are explicitly off-topic for CodeReview. If you show this code in its real context we are more likely able to help you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T15:27:23.137", "Id": "521852", "Score": "0", "body": "@Reinderien Toy examples being off-topic surprises me. I expect they should have clearer and simpler scope and behaviour, and consequently easier to explain and understand. I will have to think on whether to edit or delete this question. Thanks for the feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T15:48:31.927", "Id": "521855", "Score": "1", "body": "To a first approximation, `global` is never needed in Python (the legitimate exceptions are truly rare). Even more strongly, one can say the `global` will never help with any kinds of shared-memory or parallelism problems, because it doesn't address the real issue — namely, what happens when two processes/threads operate on the same data and the same time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-06T03:33:43.760", "Id": "524939", "Score": "1", "body": "The applied edits do not address the close reason. Note that the close reason is essentially saying that there isn't enough code to review. So to address it, you would need to add more code. Of course, since there is an answer, you can't do that. Rather than throwing it into the Reopen queue, a better approach would be to discuss it on meta." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-06T03:58:48.630", "Id": "524941", "Score": "0", "body": "@mdfst13 For future questions, it would be useful to know precisely how much code is required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-06T04:21:26.933", "Id": "524942", "Score": "0", "body": "Sure, which is also better asked on meta if the links in the close reason are not sufficient." } ]
{ "AcceptedAnswerId": "264245", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T14:56:59.287", "Id": "264240", "Score": "-1", "Tags": [ "python", "namespaces" ], "Title": "Compute pairwise Pearson's R in parallel with tasks separated by pairs of columns of an array" }
264240
accepted_answer
[ { "body": "<p>If you are not going to write anything to <code>X</code> (which it seems you are not doing), and just going to read from it, you should be good to just have all processes access the same variable without some locking mechanism.</p>\n<p>Now, <code>global</code> is not necesarily the way to go. Here is different approach:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import combinations\nimport numpy as np\nfrom scipy.stats import pearsonr\nfrom multiprocessing import Pool\n\n\nclass MyCalculator:\n\n def __init__(self, X):\n self.X = X\n\n def function(self, cols):\n result = self.X[:, cols]\n x,y = result[:,0], result[:,1]\n result = pearsonr(x,y)\n return result\n\n\ndef main():\n X = np.random.random(100000*10).reshape((100000, 10))\n myCalculator = MyCalculator(X)\n with Pool(processes=4) as P:\n print(P.map(myCalculator.function, \n combinations(range(X.shape[1]), 2)))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T16:43:34.900", "Id": "521861", "Score": "0", "body": "Yes, good work on inferring that I am interested in the read-only cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T16:44:00.317", "Id": "521862", "Score": "0", "body": "Tried to run the code in this answer and got a traceback: `AttributeError: Can't pickle local object 'main.<locals>.<lambda>'`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T16:58:06.553", "Id": "521864", "Score": "0", "body": "My bad, I'll update the approach. Nested function cannot be pickeld" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T16:39:31.643", "Id": "264245", "ParentId": "264240", "Score": "1" } } ]
<p>I wrote a short function to iterate over a list starting at a given index, then flipping back and forth between left and right values.</p> <pre class="lang-py prettyprint-override"><code>import itertools from typing import Generator def bidirectional_iterate(lst: list, index: int) -&gt; Generator: for left, right in itertools.zip_longest(reversed(lst[:index]), lst[index:]): if right is not None: yield right if left is not None: yield left arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ # 7 5 3 1 0 2 4 6 8 9 &lt;- Expected order of iteration print(list(bidirectional_iterate(arr, 4))) </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>[4, 3, 5, 2, 6, 1, 7, 0, 8, 9] </code></pre> <p>I feel like I've seen an algorithm like this before, but I couldn't find any reference to it.</p> <p>This was the most Pythonic implementation I could come up with. The only improvement I can think to make to this implementation is a way to differentiate <code>None</code> list elements from the <code>None</code> values returned to pad <code>itertools.zip_longest()</code>.</p> <p>Are there any better/faster ways or any libraries that can accomplish this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-24T00:45:33.330", "Id": "522060", "Score": "3", "body": "Why is the expected output and the actual output different?" } ]
{ "AcceptedAnswerId": "264341", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T19:34:43.787", "Id": "264334", "Score": "6", "Tags": [ "python", "iterator", "generator" ], "Title": "Bidirectional iterate over list in Python" }
264334
accepted_answer
[ { "body": "<p>I like your code, but I think the biggest potential issue with it is that in <em>each iteration</em> of the loop, both <code>left</code> and <code>right</code> need to be checked to see if they're not <code>None</code>. As @FMc pointed out, another issue is that your <code>reversed(lst[:index])</code> and <code>lst[index:]</code> lists both have to be built in memory before you even begin iterating. If you're dealing with very large lists, that might not be possible, and certainly won't be efficient.</p>\n<p>Here's another alternative approach, that uses makes use of the <code>roundrobin</code> recipe at the end of the <code>itertools</code> docs. Rather than checking <em>each iteration</em> whether the generator has been exhausted, <code>roundrobin</code> removes an empty generator from the sequence of generators as soon as that generator raises <code>StopIteration</code>. (If you're happy with having a third-party import, you can just import it from <code>more_itertools</code> and it saves you a few lines of code). I also used generator expressions in place of the lists that you built in memory, and tinkered a little with your type hints to make them more expressive of what the code is achieving.</p>\n<pre><code>from itertools import cycle, islice\nfrom typing import Iterator, Iterable, TypeVar, Sequence\n\nT = TypeVar(&quot;T&quot;)\n\ndef roundrobin(*iterables: Iterable[T]) -&gt; Iterator[T]:\n &quot;roundrobin('ABC', 'D', 'EF') --&gt; A D E B F C&quot;\n # Recipe credited to George Sakkis\n num_active = len(iterables)\n nexts = cycle(iter(it).__next__ for it in iterables)\n while num_active:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n # Remove the iterator we just exhausted from the cycle.\n num_active -= 1\n nexts = cycle(islice(nexts, num_active))\n\n\ndef bidirectional_iterate(xs: Sequence[T], index: int) -&gt; Iterator[T]:\n left = (xs[i] for i in range((index - 1), -1, -1))\n right = (xs[i] for i in range(index, len(xs)))\n yield from roundrobin(right, left)\n\narr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(list(bidirectional_iterate(arr, 4)))\n</code></pre>\n<p>Another option is to take away the function call and merge the two functions into one:</p>\n<pre><code>from itertools import cycle, islice\nfrom typing import Iterator, TypeVar, Sequence\n\nT = TypeVar(&quot;T&quot;)\n\ndef bidirectional_iterate(xs: Sequence[T], index: int) -&gt; Iterator[T]:\n &quot;&quot;&quot;Incorporates the 'roundrobin' recipe from the itertools docs, credited to George Sakkis&quot;&quot;&quot;\n left = (xs[i] for i in range((index - 1), -1, -1))\n right = (xs[i] for i in range(index, len(xs)))\n num_active = 2\n nexts = cycle(iter(it).__next__ for it in (right, left))\n while num_active:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n # Remove the iterator we just exhausted from the cycle.\n num_active -= 1\n nexts = cycle(islice(nexts, num_active))\n\narr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint(list(bidirectional_iterate(arr, 4)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-24T17:49:41.440", "Id": "522100", "Score": "1", "body": "This is great! Thanks so much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-24T01:18:22.653", "Id": "264341", "ParentId": "264334", "Score": "7" } } ]
<blockquote> <p>The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.</p> <p>Find the smallest cube for which exactly five permutations of its digits are cube.</p> </blockquote> <p>The following code can find find three permutations under a second, but it's taking very long for finding five permutations.</p> <p>How do I improve runtime?</p> <pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python import itertools def is_cube(n): return round(n ** (1 / 3)) ** 3 == n def main(): found = False n = 100 while not found: n += 1 cube = n ** 3 perms = [ int(&quot;&quot;.join(map(str, a))) for a in itertools.permutations(str(cube)) ] perms = [perm for perm in perms if len(str(perm)) == len(str(cube))] filtered_perms = set(filter(is_cube, perms)) if len(filtered_perms) == 5: found = True print(filtered_perms) if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
{ "AcceptedAnswerId": "264405", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-25T08:19:20.403", "Id": "264370", "Score": "0", "Tags": [ "python-3.x", "programming-challenge" ], "Title": "Cubic Permutations | Project Euler #62" }
264370
accepted_answer
[ { "body": "<h3 id=\"tend-to-use-one-style-opt9\">Tend to use one style</h3>\n<pre><code>perm for perm in perms if len(str(perm)) == len(str(cube))\n</code></pre>\n<p>and</p>\n<pre><code>filter(is_cube, perms)\n</code></pre>\n<p>are almost the same: an iterator that applies some filter. Don't confuse the reader - use the same style for both... or even join them in one expression.</p>\n<h3 id=\"dont-create-collections-until-needed-ong2\">Don't create collections until needed</h3>\n<p><code>perms</code> is a <code>list</code> of permutations. For a 9-digit number there will be roughly 9!=362880 permutations, and they are filtered afterwards. You can use a generator, so all filters will be applied together:</p>\n<pre><code>perms = (int(&quot;&quot;.join(map(str, a)))\n for a in itertools.permutations(str(cube)))\nperms = (perm for perm in perms if len(str(perm)) == len(str(cube)))\nfiltered_perms = set(filter(is_cube, perms))\n</code></pre>\n<p>First two expressions won't actually do anything; the third will run all the actions because set needs to be populated. So you'll save some memory and allocation/deallocation operations.</p>\n<h3 id=\"use-break-keyword-instead-of-found-variable-3b2n\">Use <code>break</code> keyword instead of <code>found</code> variable</h3>\n<p>Yes, it's not structural, but makes code more readable if there's only one break (or several are located together in a long loop). Instead of setting <code>found = True</code> just <code>break</code> the loop.</p>\n<h3 id=\"use-itertools.count-lbtf\">Use <code>itertools.count </code></h3>\n<p>I think <code>for n in itertools.count(100):</code> looks better than <code>while True:</code> and all operations with n.</p>\n<h3 id=\"algorithm-g8ec\">Algorithm</h3>\n<p>As I've said, there's too many permutations. And then you do extra work because you're checking permutations you've checked again on different numbers. Instead of that, just turn every cube into a kind of fingerprint - a string of sorted digits, <code>''.join(sorted(str(n**3)))</code>, and count the times you've met each fingerprint (it a <code>dict</code> or <code>collections.Counter</code>). All permuted numbers will have the same fingerprint. The only possible problem is when you meet some fingerprint 5 times, you should also check if it won't be met the 6th time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T07:37:58.840", "Id": "264405", "ParentId": "264370", "Score": "1" } } ]
<p>My goal is to write code that picks several random numbers from a range without repeating any previously chosen numbers. I figured out a functional solution for my problem but it seems very bulky and there must be a way to do this in fewer lines. Mine feels brute force and not very elegant and becomes super unwieldy if stretched to larger ranges and repetitions. Would love any suggestions for cleaning up what I already have.</p> <pre><code>import random key1 = random.randint(1, 4) while True: key2 = random.randint(1, 4) if key2 != key1: break while True: key3 = random.randint(1, 4) if key3 != key1 and key3 != key2: break while True: key4 = random.randint(1, 4) if key4 != key1 and key4 != key2 and key4 != key3: break key_order = [key1, key2, key3, key4] print(key_order) </code></pre> <p>If it means totally taking my code apart and rebuilding it, that is fine. I am here to learn.</p>
[]
{ "AcceptedAnswerId": "264385", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-25T15:43:50.663", "Id": "264382", "Score": "6", "Tags": [ "python", "python-3.x", "random" ], "Title": "Python code for eliminating options for random intergers as they get picked" }
264382
accepted_answer
[ { "body": "<ul>\n<li>\n<blockquote>\n<p>if key4 != key1 and key4 != key2 and key4 != key3:</p>\n</blockquote>\n<p>If you append to <code>key_order</code> upon picking a non-duplicate value you can just use <code>in</code> instead.</p>\n</li>\n<li><p>You can then more simply use a for loop to select the number of keys to output.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>key_order = []\nfor _ in range(4):\n while True:\n key = random.randint(1, 4)\n if key not in key_order:\n key_order.append(key)\n break\n</code></pre>\n<hr />\n<ul>\n<li>You can just use <a href=\"https://docs.python.org/3/library/random.html#random.sample\" rel=\"noreferrer\"><code>random.sample</code></a> or <a href=\"https://docs.python.org/3/library/random.html#random.shuffle\" rel=\"noreferrer\"><code>random.shuffle</code></a> and follow Python's &quot;batteries included&quot; ethos.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>key_order = random.sample(range(1, 5), 4)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>key_order = random.shuffle(range(1, 5))\n</code></pre>\n<hr />\n<p>Your algorithm is known as the naive shuffle, because the algorithm is very simple but also very slow. If you want to implement the shuffle yourself <a href=\"https://bost.ocks.org/mike/shuffle/\" rel=\"noreferrer\">there's a very clear visual explanation on how the Fisher-Yates shuffle works</a>.</p>\n<p>Whatever you do you should remove the <code>while</code> loop by only picking a random number from the values you have left. You can do so by building a list of options to pick from by <a href=\"https://docs.python.org/3/library/stdtypes.html#typesseq-mutable\" rel=\"noreferrer\"><code>list.pop</code>ing</a> when you <code>key_order.append(key)</code>.</p>\n<p>Whilst <code>pop</code> is less expensive then your while loop when shuffling, <code>pop</code> is still expensive. So we can change <code>append</code> and <code>pop</code> to a swap operation. For the first selection we swap <code>0</code> with <code>random.randrange(0, 4)</code>, then for the second selection <code>1</code> with <code>random.randrange(1, 4)</code>... Getting the Fisher-Yates shuffle.</p>\n<pre class=\"lang-py prettyprint-override\"><code>values = [0, 1, 2, 3]\nfor i in range(len(values)):\n j = random.randrange(i, len(values))\n values[i], values[j] = values[j], values[i]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T00:29:46.760", "Id": "522329", "Score": "0", "body": "This was incredibly informative (and practical). I greatly appreciate your feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-25T16:10:45.663", "Id": "264385", "ParentId": "264382", "Score": "5" } } ]
<p>I have this Python code:</p> <pre class="lang-py prettyprint-override"><code>def main() -&gt; None: print(&quot;Welcome To UltiList!&quot;) lst = [] len_of_list = int(input(&quot;Enter the len of the list: &quot;)) while len(lst) &lt;= len_of_list: print(&quot;&gt;&gt; &quot;, end=&quot;&quot;) args = input().strip().split(&quot; &quot;) if args[0] == &quot;append&quot;: lst.append(int(args[1])) elif args[0] == &quot;insert&quot;: lst.insert(int(args[1]), int(args[2])) elif args[0] == &quot;remove&quot;: lst.remove(int(args[1])) elif args[0] == &quot;pop&quot;: lst.pop() elif args[0] == &quot;sort&quot;: lst.sort() elif args[0] == &quot;reverse&quot;: lst.reverse() elif args[0] == &quot;print&quot;: print(lst) elif args[0] == &quot;exit&quot;: print(&quot;Bye!&quot;) exit() else: print(&quot;That's not a valid command!&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>But I thinks is very repetitive,Eg: In JavaScript I could do something like:</p> <blockquote> <pre class="lang-javascript prettyprint-override"><code> const commands = { append: (arg)=&gt;lst.append(arg), remove: (arg)=&gt;lst.remove(arg), ... } // This would go in the while loop commands[`${args[0]}`](args[1]) </code></pre> </blockquote> <p>And I would no longer have to make any comparison, this will make it more readable and shorter in my opinion.</p> <p>What can be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-27T07:01:32.940", "Id": "522245", "Score": "0", "body": "Please see *[What to do when someone answers](/help/someone-answers)*. I have rolled back Rev 2 → 1." } ]
{ "AcceptedAnswerId": "264386", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-25T16:06:48.483", "Id": "264384", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Python program to manipulate a list based on user input" }
264384
accepted_answer
[ { "body": "<p>Your 'switch statement' is bad because you've chosen to not use the same algorithm as your JavaScript example:</p>\n<blockquote>\n<pre class=\"lang-js prettyprint-override\"><code>const commands = {\n append: (arg)=&gt;lst.append(arg),\n remove: (arg)=&gt;lst.remove(arg),\n ...\n}\n</code></pre>\n</blockquote>\n<p>Converted into Python:</p>\n<pre class=\"lang-py prettyprint-override\"><code>commands = {\n &quot;append&quot;: lambda arg: lst.append(arg),\n &quot;remove&quot;: lambda arg: lst.remove(arg),\n}\n\ncommands[f&quot;{args[0]}&quot;](args[1])\n</code></pre>\n<p>Python has no equivalent to JavaScript's <code>() =&gt; {...}</code> lambdas.\nSo you can abuse class if you need them.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Commands:\n def append(arg):\n lst.append(arg)\n\n def exit(arg):\n print(&quot;bye&quot;)\n exit()\n\ngetattr(Commands, f&quot;{args[0]}&quot;)(args[1])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-25T18:38:03.350", "Id": "522125", "Score": "0", "body": "`lambda arg:lst.append(arg)` is just a closure `lst.append`. F-string is an overkill, non-str aguments would not be found in dict keys. Else/default option can be done with `commands.get(args[0], None)` and adding `None:lambda print(...)` to `commands`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-25T18:54:23.920", "Id": "522127", "Score": "1", "body": "@PavloSlavynskyy 1. The point is to show `lambda` exists in Python, not to cut characters. 2. I'm just copying the JS example in the question. 3. Yes, or you could just do `default = lambda arg: print(...)` `commands.get(args[0], default)(args[1])`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-25T16:46:38.440", "Id": "264386", "ParentId": "264384", "Score": "2" } } ]
<p>Im currently working on a filtering keywords. I have two lists which I called positive and negative.</p> <p>Scenarios:</p> <ol> <li>if <code>POSITIVE</code> matches and <strong>NOT</strong> <code>NEGATIVE</code>matches = <strong>True</strong></li> <li>if <code>POSITIVE</code> matches and <code>NEGATIVE</code>matches = <strong>False</strong></li> <li>if NOT <code>POSITIVE</code>(Then no need to check <code>NEGATIVE</code>) = <strong>False</strong>.</li> </ol> <p>I have done something like this:</p> <pre class="lang-py prettyprint-override"><code>import re from typing import List # In the future it will be a longer list of keywords POSITIVE: List[str] = [ &quot;hello+world&quot;, &quot;python&quot;, &quot;no&quot; ] # In the future it will be a longer list of keywords NEGATIVE: List[str] = [ &quot;java&quot;, &quot;c#&quot;, &quot;ruby+js&quot; ] def filter_keywords(string) -&gt; bool: def check_all(sentence, words): return all(re.search(r'\b{}\b'.format(word), sentence) for word in words) if not any(check_all(string.lower(), word.split(&quot;+&quot;)) for word in POSITIVE) or \ any(check_all(string.lower(), word.split(&quot;+&quot;)) for word in NEGATIVE): filtered = False else: filtered = True print(f&quot;Your text: {string} is filtered as: {filtered}&quot;) return filtered filter_keywords(&quot;Hello %#U&amp;¤AU(1! World ¤!%!java&quot;) filter_keywords(&quot;Hello %#U&amp;¤AU(1! World ¤!%!&quot;) filter_keywords(&quot;I love Python more than ruby and js&quot;) filter_keywords(&quot;I love Python more than myself!&quot;) </code></pre> <p>Regarding the <code>+</code> in the list, that means that if <code>hello</code> and <code>world</code> is in the string then its a positive match</p> <p>It does work of course, but I do believe I am doing too many &quot;calculations&quot; and I believe it could be shorted, I wonder if there is a possibility of it?</p>
[]
{ "AcceptedAnswerId": "264430", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T14:07:41.413", "Id": "264419", "Score": "1", "Tags": [ "python-3.x" ], "Title": "Filtering string by given keywords" }
264419
accepted_answer
[ { "body": "<p>That's a <em>lot</em> of regexes to compute. I'm going to suggest that you only run one regex, to split the string up into words; and from there represent this as a series of set operations.</p>\n<p>If I understand it correctly, you basically have two different cases in your filter words:</p>\n<ul>\n<li>A single word, which produces a match</li>\n<li>Multiple words, which - regardless of the order found - <em>all</em> need to be present to produce a match</li>\n</ul>\n<p>In the second case, I don't think it's a good idea to include a magic plus-sign to indicate string separation in static application data. Just write the separation in yourself, as represented by a multi-element set.</p>\n<p>The single-word match case is going to execute much more quickly than what you have now, because it takes only one set disjoint check for each of the positive and negative terms. If such a match is found, the multi-word case will be short-circuited away and will not be computed. The multi-word case is slower because every sub-set needs to be checked, but I still expect it to be faster than the iterative-regex approach.</p>\n<p>Also note that you should remove your boolean variable and print statement in your function, and simplify your boolean expression by applying <a href=\"https://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"nofollow noreferrer\">De Morgan's Law</a> to switch up your <code>True</code> and <code>False</code> and produce a single return expression.</p>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>import re\nfrom typing import Tuple, Iterable, Set\n\n\n# In the future it will be a longer list of keywords\nSINGLE_POSITIVE: Set[str] = {\n &quot;python&quot;,\n &quot;no&quot;,\n}\nMULTI_POSITIVE: Tuple[Set[str], ...] = (\n {&quot;hello&quot;, &quot;world&quot;},\n)\n\n# In the future it will be a longer list of keywords\nSINGLE_NEGATIVE: Set[str] = {\n &quot;java&quot;,\n &quot;c#&quot;,\n}\nMULTI_NEGATIVE: Tuple[Set[str], ...] = (\n {&quot;ruby&quot;, &quot;js&quot;},\n)\n\n\nfind_words = re.compile(r'\\w+').findall\n\n\ndef filter_keywords(string: str) -&gt; bool:\n words = {word.lower() for word in find_words(string)}\n\n def matches(single: Set[str], multi: Iterable[Set[str]]) -&gt; bool:\n return (\n (not words.isdisjoint(single))\n or any(multi_word &lt;= words for multi_word in multi)\n )\n\n return (\n matches(SINGLE_POSITIVE, MULTI_POSITIVE) and not\n matches(SINGLE_NEGATIVE, MULTI_NEGATIVE)\n )\n\n\ndef test() -&gt; None:\n for string in (\n &quot;Hello %#U&amp;¤AU(1! World ¤!%!java&quot;,\n &quot;Hello %#U&amp;¤AU(1! World ¤!%!&quot;,\n &quot;I love Python more than ruby and js&quot;,\n &quot;I love Python more than myself!&quot;,\n &quot;I love Python more than js&quot;,\n ):\n filtered = filter_keywords(string)\n print(f&quot;Your text: {string} is filtered as: {filtered}&quot;)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<h2 id=\"output\">Output</h2>\n<pre><code>Your text: Hello %#U&amp;¤AU(1! World ¤!%!java is filtered as: False\nYour text: Hello %#U&amp;¤AU(1! World ¤!%! is filtered as: True\nYour text: I love Python more than ruby and js is filtered as: False\nYour text: I love Python more than myself! is filtered as: True\nYour text: I love Python more than js is filtered as: True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T21:51:30.133", "Id": "522219", "Score": "0", "body": "Why do you keep always chock me?! You are awesome dude. The reason I used the `+` is that in the future I would like to use postgresql for storing the keywords in the database and I was not sure if the database would like to store with spaces so I thought it would be better idea to replace space with + but I guess not. What would you suggest if I would like to store it to the database? To have multiple tables, one for multiple words and one for single words?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-27T03:36:40.887", "Id": "522228", "Score": "3", "body": "The approach will be very different. You'll want to run the word matching query entirely in the database rather than doing it on the application side with sets or regexes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-27T10:38:37.163", "Id": "522272", "Score": "0", "body": "Cool! I will have to investigate it abit more, but that is abit off topic for now! Thanks once again!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T20:29:14.717", "Id": "264430", "ParentId": "264419", "Score": "2" } } ]
<pre><code>class RadarChecker: def __init__(self) -&gt; None: self._issues = set() @property def issues(self) -&gt; Set[str]: return self._issues @property def _checkers(self) -&gt; Iterable[Callable]: return ( self._check_1, self._check_2, self._check_3, ) def check(self) -&gt; None: for checker in self._checkers: ok, issue = checker() if not ok: self._issues.add(issue) </code></pre> <p>The current interface of the <code>RadarChecker</code> class consists of two methods: <code>check</code> and <code>issues</code>. The whole purpose of the check method is that it triggers computation of the issues that are returned by the issues method. So, all users of <code>RadarChecker</code> call issues eventually:</p> <pre><code>checker = RadarChecker() checker.check() for issue in checker.issues: # process issue </code></pre> <p>Is it possible to provide the same functionality with a simpler interface?</p> <p>I'm thinking about defining the <code>RadarIssues</code> class that implements the <code>Iterable[str]</code> interface. We provide the same info to <code>RadarIssues</code> that we do to <code>RadarChecker</code> but instead of calling <code>issues</code> to get the issues, the users would simply iterate over the instance of <code>RadarIssues</code>. This would look roughly as follows:</p> <pre><code>radar_issues = RadarIssues() for issue in radar_issues: # process issue </code></pre> <p>Is it better? I will appreciate criticism and other ideas.</p>
[]
{ "AcceptedAnswerId": "264432", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T18:28:35.330", "Id": "264425", "Score": "2", "Tags": [ "python", "object-oriented", "design-patterns" ], "Title": "Simple interface for collecting issues after a list of validations" }
264425
accepted_answer
[ { "body": "<p>What you have is neither crazy nor terrible.</p>\n<p>You've started some type hinting (good!) but it's incomplete. For instance</p>\n<pre><code>self._issues: Set[str] = set()\n</code></pre>\n<p>and</p>\n<pre><code>@property\ndef checkers(self) -&gt; Tuple[\n Callable[\n [], \n Tuple[bool, str],\n ], ...\n]:\n</code></pre>\n<p>Note that it's good practice to add hints accepting the most generic possible type and return the most specific possible type, so <code>Tuple</code> instead of <code>Iterable</code>.</p>\n<p>There's not a whole lot of win in having <code>_issues</code> as a private with a public accessor, because private is only a suggestion in Python and users can still get to that member. You might as well just have a public <code>issues</code> set. However, the better thing to do is make this class stateless - keep your <code>checkers</code> (which can be made public - again, private is kind of a lost cause in Python); do not store <code>issues</code> on the class; and yield issues as a generator from <code>check()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-27T06:44:47.067", "Id": "522242", "Score": "0", "body": "Thanks! Could you please provide an implementation for `check` with generators? Not really sure how it will look like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-27T07:02:03.200", "Id": "522246", "Score": "0", "body": "def check(self) -> Iterable[str]:\n for checker in self._checkers:\n ok, issue = checker()\n if not ok:\n yield issue" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T20:51:43.923", "Id": "264432", "ParentId": "264425", "Score": "2" } } ]
<p>I recently tried to solve the first non-repeating character problem. Please tell me if my solution is valid. I'm aiming for O(n) with a single loop.</p> <p>My thinking is, it would be easy to tell you what the last non repeated character is, just:</p> <pre class="lang-none prettyprint-override"><code>loop each char if map[char] doesn't exist output = char store char in map </code></pre> <p>So if you can get the last non repeated character, wouldn't you be able to run the same algorithm to get the first one, if the loop went through the string backwards? Here's my (python) code:</p> <pre class="lang-py prettyprint-override"><code>def firstNonRepeater(s): smap = {} out = '' for i in range(len(s)-1, -1, -1): if s[i] not in smap: out = s[i] if s[i] in smap: smap[s[i]] += 1 else: smap[s[i]] = 1 if smap[out] &gt; 1: return None return out </code></pre> <p>There is some extra code to catch when there are no unique chars.</p> <p>This seems to work, am I missing something?</p> <h4 id="edit-cxuv">EDIT:</h4> <p>@Alex Waygood has raised that my solution has an oversight, in that it will return None if it encounters a repeating character, where all instances are before the first non-repeater. See his in-depth explanation below.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T22:04:25.507", "Id": "522221", "Score": "0", "body": "Also, what are the constraints here? Are you aiming for a solution that just uses builtin types, or are solutions that use `collections`/`itertools` etc okay?" } ]
{ "AcceptedAnswerId": "264436", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T21:34:33.090", "Id": "264433", "Score": "10", "Tags": [ "python", "algorithm", "programming-challenge", "strings", "array" ], "Title": "First non-repeating Character, with a single loop in Python" }
264433
accepted_answer
[ { "body": "<p>Python has a <code>Counter</code> data structure that is handy whenever you are ...\ncounting things. Since strings are directly iterable, you can easily get a\ndict-like tally for how many times each character occurs in a string. And since\nmodern Python dicts keep track of insertion order, you can just iterate over\nthat tally, returning the first valid character.</p>\n<pre><code>from collections import Counter\n\ndef first_non_repeater(s):\n for char, n in Counter(s).items():\n if n == 1:\n return char\n return None\n\nprint(first_non_repeater(&quot;xxyzz&quot;)) # y\nprint(first_non_repeater(&quot;xxyzzy&quot;)) # None\nprint(first_non_repeater(&quot;xxyzazy&quot;)) # a\n</code></pre>\n<p>And if you don't want to use <code>Counter</code>, just add your\nown counting logic to the function:</p>\n<pre><code>tally = {}\nfor char in s:\n try:\n tally[char] += 1\n except KeyError:\n tally[char] = 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-27T06:32:53.150", "Id": "522239", "Score": "2", "body": "Even shorter: `def first_non_repeater(s): return next((char for char, n in Counter(s).items() if n == 1), None)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-27T07:24:54.863", "Id": "522249", "Score": "2", "body": "This is a great solution, pythons Counter seems very elegant here. I also had no idea that later python versions maintained insertion order in dicts, so I wasn't aware that writing your own tally was an option(since I thought there is no way to check the first occurrence). Thanks for your help. Although your answer doesn't mention that my algorithm is flawed(feel free to update), I'll accept it because I like the solution best." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-26T23:40:14.143", "Id": "264436", "ParentId": "264433", "Score": "16" } } ]
<p>I am trying to find the &quot;Number of trailing zeros of N!&quot; (N factorial). In the python code I am trying to find the factorial first and then the number of trailing zeros. However, I am getting &quot;Execution Timed Out&quot; error.</p> <ol> <li>Why is this code giving the error? Is there anyway to optimize the code to decrease the execution time?</li> <li>Can this code be shortened in terms of lines of code?</li> </ol> <pre><code>def zeros(n): fact=1 if n==1 or n==0: return 1 elif n&lt;0: return 0 else: while n&gt;1: fact=n*fact n=n-1 count = 0 while fact &gt;= 1: if fact%10==0: count+=1 fact=fact//10 else: break return count </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T14:47:52.547", "Id": "524443", "Score": "3", "body": "Coding problems like this are almost always challenging you to find a more clever solution than the obvious iteration/recursion. That's why they have execution time limits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T16:14:51.923", "Id": "524451", "Score": "2", "body": "This is integer sequence [A027868](https://oeis.org/A027868) and you can find a wealth of reading (including two different Python implementations) on its OEIS page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T22:23:46.347", "Id": "524463", "Score": "0", "body": "Skip finding the factorial first, and just find the number of trailing zeroes. The number of trailing zeroes is equal to the number of powers of ten in the factorial, which is equal to the number of the prime factors of ten that appear in the factorial, or rather, whichever of the prime factors is less numerous..." } ]
{ "AcceptedAnswerId": "264471", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T09:48:43.290", "Id": "264470", "Score": "8", "Tags": [ "python", "python-3.x", "time-limit-exceeded" ], "Title": "Find the number of trailing zeros in factorial" }
264470
accepted_answer
[ { "body": "<blockquote>\n<pre><code>if n==1 or n==0:\n return 1\n</code></pre>\n</blockquote>\n<p>That looks incorrect. 0! and 1! are both equal to 1, which has <em>no</em> trailing zeros, so we should be returning 0 there. If we had some unit tests, this would be more apparent.</p>\n<hr />\n<p>We don't need to carry all the trailing zeros with us as we multiply; we can divide by ten whenever we have the opportunity, rather than waiting until the end:</p>\n<pre><code> count = 0\n while n &gt; 1:\n fact *= n\n n -= 1\n while fact % 10 == 0:\n count += 1\n fact = fact // 10\n</code></pre>\n<hr />\n<p>However, this only gets us a small gain. The real problem is that we have chosen <strong>a very inefficient algorithm</strong>. We're multiplying by all the numbers in 2..n, but some mathematical insight helps us find a faster technique.</p>\n<p>Observe that each trailing zero means a factor of 10, so we just need the lesser count of 2s or 5s in the prime factors of the factorial (which is the count of all 2s or 5s in all the numbers 1..n). We know there will be more 2s than 5s, since even numbers are much more common than multiples of 5, so we just need a way to count how many fives are in the factorial.</p>\n<p>At first glance, that would appear to be n÷5, since every 5th number is a multiple of 5. But we would undercount, because 25, 50, 75, ... all have two 5s in their prime factorisation, and 125, 250, 375, ... have three 5s, and so on.</p>\n<p>So a simpler algorithm would be to start with n÷5, then add n÷25, n÷125, n÷625, ... We can do that recursively:</p>\n<pre><code>def zeros(n):\n if n &lt; 5:\n return 0\n return n // 5 + zeros(n // 5)\n</code></pre>\n<p>We can (and should) unit-test our function:</p>\n<pre><code>def zeros(n):\n &quot;&quot;&quot;\n Return the number of trailing zeros in factorial(n)\n &gt;&gt;&gt; zeros(0)\n 0\n &gt;&gt;&gt; zeros(4)\n 0\n &gt;&gt;&gt; zeros(5)\n 1\n &gt;&gt;&gt; zeros(24)\n 4\n &gt;&gt;&gt; zeros(25)\n 6\n &gt;&gt;&gt; zeros(625) - zeros(624)\n 4\n &quot;&quot;&quot;\n if n &lt; 5:\n return 0\n return n // 5 + zeros(n // 5)\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T16:26:55.787", "Id": "522366", "Score": "1", "body": "I express my deep sense of gratitude for writing a detailed answer and explaining it so beautifully." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T18:36:46.520", "Id": "522375", "Score": "1", "body": "Great, except that I think both “infinite set of even numbers” and “infinite set of multiples of 5” are countably infinite and thus technically have the same cardinality :) it seems true, OTOH, that in any given finite set 1..n, the smaller of the two subsets is the multiples of 5" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T19:01:52.850", "Id": "522377", "Score": "0", "body": "@D.BenKnoble If n>1. If n=1 then each subset has zero elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T19:50:30.580", "Id": "522382", "Score": "0", "body": "@D.BenKnoble, you're right, and I saw the smiley too. Just trying to keep the explanation at the right level for the code, rather than mathematically rigorous!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T20:59:42.783", "Id": "522385", "Score": "0", "body": "I ran into exactly the inverse problem: I scripted a factorial calculator (using `awk | dc`) and assumed it was rounding somewhere because of the abundance of trailing zeros. Took me a while to spot the pattern. The corollary, of course, is that the value before the trailing zeros is divisible by the remaining power of two." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T10:16:46.533", "Id": "264471", "ParentId": "264470", "Score": "17" } } ]
<p>The task is:</p> <blockquote> <p>Given an array of integers, return the minimum required increment to make each element unique.</p> <p>Sample Input 1: [3, 4, 2, 2, 6]</p> <p>Sample Output 1: 3 (One of the 2s should be incremented to 5)</p> <p>Sample Input 2: [3, 4, 5]</p> <p>Sample Output 2: 0 (There is no duplicate)</p> </blockquote> <p>My code works by shifting all numbers even if there is only one duplicate in a whole array. I guess this could be written more efficiently (e.g., in each duplicate, looking at the minimum number that does not exist in the array and shifting one of the duplicates to that number), but I couldn't manage it.</p> <pre><code>def getMinimumCoins(arr): sumBefore = sum(arr) arr.sort() previous = arr[0] for i in range(1, len(arr)): if arr[i] &lt;= previous: arr[i] = previous + 1 previous = arr[i] return sum(arr) - sumBefore </code></pre> <p>Besides, in the way I proposed above, decremental operations also could be possible. I mean, in my code, if the input is [3,3,3], the resulting array would be [3,4,5] with total increment equals 3. However, in the new algorithm, it could be possible to obtain a resulting array of [1,2,3] with a total decrement equals to -3.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T11:45:02.727", "Id": "524416", "Score": "5", "body": "\"My code works in the linear time since\". \"`arr.sort()`\" does not run in linear time, so your code is not linear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T11:50:38.877", "Id": "524417", "Score": "0", "body": "Timsort runs in logarithmic time as you have said, but the loop below works in the linear time. Therefore, in the worst case, it is linear. Am I wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T12:35:44.407", "Id": "524419", "Score": "1", "body": "Timsort is \\$O(n\\sqrt{n})\\$ your loop is \\$O(n)\\$. \\$O(n\\sqrt{n} + n) = O(n(\\sqrt{n} + 1)) = O(n\\sqrt{n})\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T12:56:13.290", "Id": "524423", "Score": "1", "body": "Sorry, Timsort is \\$O(n \\log n)\\$ not \\$O(n\\sqrt{n})\\$ however the math and conclusion are roughly the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T13:18:30.783", "Id": "524427", "Score": "1", "body": "What is the expected output for arr `[3, 3, 6]`? You could get there by one increment (`arr[1] += 1 -> 4`) and one decrement (`arr[2] -= 1 -> 5`). Is the expected output `0`, because one increment and one decrement \"cancel each other out\"? Or `2` (1 increment of value `1`, plus 1 decrement of value `1`)? Or perhaps `(1, 1)`, indicating the sum of all required increments is `1`, and the sum of all required decrements is also `1`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T13:22:47.130", "Id": "524428", "Score": "0", "body": "@AlexWaygood For [3,3,6], the output is 1 ([3,4,6]) in my algorithm. I only proposed another idea which includes also decremental operation. My first purpose to ask this question was to optimize my code. Then, I proposed an alternative that includes decremental operations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T13:27:28.980", "Id": "524430", "Score": "0", "body": "@Peilonrayz sorry for my mistake. Yes, the worst-case complexity is O(nlogn), but cannot I change the way of the loop to make it slightly better? I mean, instead of shifting all elements, maybe it can only alter the duplicates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T13:35:42.300", "Id": "524431", "Score": "0", "body": "Understood, but consider a different example. Say `arr = [5, 5, 6, 7, 7]`. The smallest changes required here to achieve an array of unique integers would be to subtract `1` from `arr[0]` and add `1` to `arr[4]`, leading to `[4, 5, 6, 7, 8]`. You *could* add `1` to `arr[1]`, `2` to `arr[2]`, `2` to `arr[3]` and `3` to `arr[4]` -> result of `8`, but this is arguably not the *minimum increment required* if the algorithm is allowed to consider decrements. So for a situation where the algorithm is allowed to consider decrements, how should that result be expressed if the operations cancel out?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T21:21:37.003", "Id": "524460", "Score": "0", "body": "In case of decremental operations are allowed, we can traverse the array one by one, and if we see a duplicate, we can check what is the minimum positive integer that does not exist in the array, and change the current element with that integer. The problem is, how can we do this in an efficient way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T12:37:45.893", "Id": "524489", "Score": "2", "body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T11:22:27.513", "Id": "265504", "Score": "5", "Tags": [ "python", "performance", "algorithm" ], "Title": "Given an array of integers, return the minimum required increment to make each element unique" }
265504
max_votes
[ { "body": "<p>The algorithm is good, but...</p>\n<ul>\n<li>Use a better function name than <code>getMinimumCoins</code>. The task isn't about coins.</li>\n<li>Python prefers <code>snake_case</code> and four-space indentation.</li>\n<li>If the list is empty, you crash instead of returning zero.</li>\n<li>No need to actually perform the increments in the array, and <a href=\"https://docs.python.org/3/library/itertools.html#itertools.accumulate\" rel=\"noreferrer\"><code>itertools.accumulate</code></a> can help:</li>\n</ul>\n<pre><code>from itertools import accumulate\n\ndef minimum_increments(arr):\n arr.sort()\n return sum(accumulate(arr, lambda prev, curr: max(prev + 1, curr))) - sum(arr)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T10:47:11.363", "Id": "524478", "Score": "0", "body": "Hello Kelly, thank you for your valuable input. I have just learned a new concept thanks to you. I could not fully comprehend how this module unpacks elements in the array for the lambda function. The lambda function works on two elements (prev, curr), but the elements in the array are integers, not tuples. I could not find anything about this. My wild guess is: if the function is operator.add, it fetches 0 and the first element at the beginning, and in the rest, previous element and the current element. If the function is mul, it fetches 1 and the first element at the beginning and so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T11:12:49.347", "Id": "524482", "Score": "0", "body": "I don't know why, but the first algorithm works slightly faster (by 40 ms difference on average)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T12:05:00.007", "Id": "524487", "Score": "0", "body": "@bbasaran Not quite. First `prev` is the first element, not 0 or 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T12:56:54.273", "Id": "524490", "Score": "0", "body": "What is the first curr then? It cannot be the first element as well, because when I tried this: accumulate([1,3,5], lambda prev, curr: prev+curr), it returns [1, 4, 9], not [2, 4, 9]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T13:11:33.313", "Id": "524492", "Score": "0", "body": "The second element. Try for example `accumulate([1,3,5], print)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T13:14:21.710", "Id": "524495", "Score": "0", "body": "In such a case, the result should be [4, 9] instead of [1, 4, 9]. Isn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T13:15:00.563", "Id": "524496", "Score": "0", "body": "I don't know why you think so." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T02:13:16.917", "Id": "265529", "ParentId": "265504", "Score": "8" } } ]
<p>I'm trying to create a function to check multiple conditions of data. The function will return a list if the data is errors.</p> <p>Here is my idea:</p> <pre><code>error_lists = [] def check(A, B, C, D, E): check condition 1 for A if there is a error -&gt; error_list.append(1) check condition 2 for B if there is a error -&gt; error_list.append(2) check condition 3 for C if there is a error -&gt; error_list.append(3) check condition 4 for D if there is a error -&gt; error_list.append(4) check condition 5 for E if there is a error -&gt; error_list.append(5) return error_list </code></pre> <p>If A, B, C do not meet the requirement, the function will return the error_list: [1,2,3]. Likewise, the function will return [2,5] if only B or E do not meet the requirement</p> <p>Actually I've already written the code, however I feel that it need to be improved.</p> <pre><code>P_list = [35000, 50000, 80000, 120000, 150000, 180,000] def data_check(Staff_id, A ,B, x, y, z, t, u, D): error_list = [] wh = x + y tot = z + t C = [x, y, z, t, u] &quot;&quot;&quot;First condition&quot;&quot;&quot; if A not in P_list: print(f&quot;Error type 1 in the data of {staff_id} {A} is not True&quot;) error_list.append(1) &quot;&quot;&quot;Second condition&quot;&quot;&quot; if B &gt;= 48: print(f&quot;Error type 2 in the data of {staff_id} {B} is not True&quot;) error_list.append(2) &quot;&quot;&quot;Third condition&quot;&quot;&quot; for k in C: if k &lt; 0: print(f&quot;Error type 3 in the data of {staff_id} {k} is less than 0&quot;) error_list.append(3) &quot;&quot;&quot;Fourth condition&quot;&quot;&quot; if D &gt;= 3000000: print(f&quot;Error type 4 in the data of {staff_id} D is not true&quot;) error_list.append(4) &quot;&quot;&quot;Fifth condition&quot;&quot;&quot; if tot &gt;= wh: print(f&quot;Error type 5 in the data of {staff_id} E is not true&quot;) error_list.append(5) return print(error_list) data_check(&quot;1a88s2s&quot;, 50000 ,71, 23, 28, 3,5, 12, 3500000) </code></pre> <p>Does anybody has any suggestion ?</p> <p>Many thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T18:32:40.357", "Id": "524456", "Score": "1", "body": "Welcome to Code Review! It appears there is a slight flaw with the code: \"_NameError: name 'staff_id' is not defined_\" - it can be fixed by changing the case on the argument." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-29T12:38:58.820", "Id": "265511", "Score": "2", "Tags": [ "python-3.x" ], "Title": "Create a function in Python to check for the data errors" }
265511
max_votes
[ { "body": "<ul>\n<li><code>P_list</code> should be a set, not a list, based on its usage; it's only used for membership checks. You can also pre-bind to the <code>__contains__</code> member to get a function reference you can call, constraining the set to one purpose.</li>\n<li>Add PEP484 type hints</li>\n<li><code>C</code> should be a tuple based on its usage since it's immutable</li>\n<li>Your <code>print</code> statements should not be mixed in with your logic, and should be separated to another method</li>\n<li>Consider representing your errors not as free integers, but as constrained enumeration values</li>\n<li>Use an <code>any</code> generator for your <code>C</code> negative check</li>\n<li><code>180,000</code> is likely incorrect and should be <code>180_000</code></li>\n<li><code>return print</code> is meaningless and will always return <code>None</code>; instead consider returning your error values or yielding them as a generator</li>\n<li><code>staff_id</code> shouldn't be passed into <code>data_check</code> at all; it's only used for formatting error messages which again can exist in a separate method</li>\n<li>Your letter-salad variable names are helping no one. You need to spell out what these actually mean.</li>\n<li>Moving your intermediate error-checking variables <code>C</code>, <code>wh</code> and <code>tot</code> closer to where they're used is, I think, clearer</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import enum\nfrom enum import Enum\nfrom typing import Iterable\n\nin_p_list = frozenset((35_000, 50_000, 80_000, 120_000, 150_000, 180_000)).__contains__\n\n\n@enum.unique\nclass ErrorType(Enum):\n REJECTED_A = 1\n B_TOO_HIGH = 2\n NEGATIVE_C = 3\n D_TOO_HIGH = 4\n TOTAL_TOO_HIGH = 5\n\n\ndef data_check(\n A: int,\n B: int,\n x: int,\n y: int,\n z: int,\n t: int,\n u: int,\n D: int,\n) -&gt; Iterable[ErrorType]:\n if not in_p_list(A):\n yield ErrorType.REJECTED_A\n\n if B &gt;= 48:\n yield ErrorType.B_TOO_HIGH\n\n C = (x, y, z, t, u)\n if any(k &lt; 0 for k in C):\n yield ErrorType.NEGATIVE_C\n\n if D &gt;= 3_000_000:\n yield ErrorType.D_TOO_HIGH\n\n wh = x + y\n tot = z + t\n if tot &gt;= wh:\n yield ErrorType.TOTAL_TOO_HIGH\n\n\ndef print_errors(staff_id: str, errors: Iterable[ErrorType]) -&gt; None:\n for error in errors:\n print(\n f'Error type {error.value} in the data of {staff_id}: {error.name}'\n )\n\n\ndef test() -&gt; None:\n print_errors(&quot;1a88s2s&quot;, data_check(50000, 71, 23, 28, 3, 5, 12, 3500000))\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<h2>Output</h2>\n<pre><code>Error type 2 in the data of 1a88s2s: B_TOO_HIGH\nError type 4 in the data of 1a88s2s: D_TOO_HIGH\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T13:12:00.230", "Id": "524493", "Score": "0", "body": "Thank you so much for your response @Reinderien!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T02:37:12.147", "Id": "265531", "ParentId": "265511", "Score": "3" } } ]
<p>I've created an on-demand class that can be initiated to collected any new data written to file from <code>start_recording</code> call until <code>stop_recording</code> which close the connection and retrieve the collected data so far.</p> <p>It uses in test cases for obtaining relevant logs during the time where a certain operation was performed in order to verify its success.</p> <p>I'm currently using this class for tests in remote machine, but would be happy to hear for any idea for improvements, correctness, etc.</p> <pre><code>import time import paramiko import select from virtual_machine import utils from multiprocessing import Queue import multiprocess class background(): def __init__(self, config_file): self.q = Queue(1000) #this methods implemented elsewhere and read a config file into dictionary self.config = utils.get_params(config_file) @staticmethod def linesplit(socket): buffer_string = socket.recv(4048).decode('utf-8') done = False while not done: if '\n' in buffer_string: (line, buffer_string) = buffer_string.split('\n', 1) yield line + &quot;\n&quot; else: more = socket.recv(4048) if not more: done = True else: buffer_string = buffer_string + more.decode('utf-8') if buffer_string: yield buffer_string def do_tail(self, log_file): data = &quot;&quot; client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) from os.path import expanduser home = expanduser(&quot;~&quot;) client.connect(self.config[&quot;ip&quot;],self.config[&quot;username&quot;],self.config[&quot;password&quot;]) grep_pattern = &quot;grep_filter&quot; remote_command = 'tail -0 -f {} '.format(log_file) print(remote_command) transport = client.get_transport() channel = transport.open_session() channel.exec_command(remote_command) while 1: try: rl, _, _ = select.select([channel], [], [], 0.0) if len(rl) &gt; 0: print(&quot;ready to read&quot;) for line in background.linesplit(channel): self.q.put_nowait(line) except (KeyboardInterrupt, SystemExit): print('got ctrl+c') break client.close() return data def start_recording(self, log_file): q = Queue(100) self.p = multiprocess.Process(target=self.do_tail, args=(log_file,), daemon=True) self.p.start() def stop_recording(self): self.p.terminate() data = &quot;&quot; while not self.q.empty(): data += self.q.get() return data #example if __name__ == '__main__': x = background(&quot;config.conf&quot;) x.start_recording(&quot;/tmp/logfile.log&quot;) # doing some operation data = x.stop_recording() print(data) </code></pre>
[]
{ "AcceptedAnswerId": "265553", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T10:59:18.943", "Id": "265545", "Score": "3", "Tags": [ "python", "python-3.x", "linux", "integration-testing" ], "Title": "remote file follow using python" }
265545
accepted_answer
[ { "body": "<p>Your <code>linesplit</code> repeats a little bit of code; you could phrase it as</p>\n<pre><code>while True:\n buffer_bytes = socket.recv(4096)\n if len(buffer_bytes) == 0:\n break\n buffer_string = buffer_bytes.decode('utf-8')\n *lines, buffer_string = buffer_string.split('\\n')\n yield from lines\n</code></pre>\n<p><code>'tail -0 -f {} '.format(log_file)</code> could be simply <code>'tail -0 -f ' + log_file</code>.</p>\n<p><code>background</code> should be <code>Background</code>.</p>\n<p>Consider adding some PEP484 type hints.</p>\n<p><code>rl, _, _ = select ...</code></p>\n<p>can be</p>\n<p><code>rl, *_ = select ...</code></p>\n<p>The code between <code>paramiko.SSHClient()</code> and <code>client.close()</code> has no close-guarantee protection. There are various options, including a <code>try</code>/<code>finally</code>, or making your current class (or a factored-out tail-specific class) a context manager.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-31T15:44:27.057", "Id": "524567", "Score": "0", "body": "Thanks for your comments. Btw, I've encountered where the log recording was lagging behind, and where it did, the interesting part already finished. I wonder if there's any kind of system wide lock that can block the `start_recording` from returning, until the subprocess reach the `ready to read` line. Can you recommend anything ? thanks !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T15:03:45.273", "Id": "265553", "ParentId": "265545", "Score": "1" } } ]