body
stringlengths
144
5.53k
comments
list
meta_data
dict
question_id
stringlengths
1
6
yield
stringclasses
2 values
answers
list
<p>I've written a program that finds the difference between data and gives output. Here's the code:</p> <pre class="lang-py prettyprint-override"><code>import json import numpy as np print(&quot;This is a basic machine learning thing.&quot;) baseData = {&quot;collecting&quot;:True,&quot;x&quot;:[],&quot;y&quot;:[]} while baseData[&quot;collecting&quot;]: baseData[&quot;x&quot;].append(float(input(&quot;X:&quot;))) baseData[&quot;y&quot;].append(float(input(&quot;Y:&quot;))) if input(&quot;Do you want to keep feeding data? Press enter for yes, or type anything for no.&quot;) != &quot;&quot;: baseData[&quot;collecting&quot;] = False if len(baseData[&quot;x&quot;]) == len(baseData[&quot;y&quot;]): xdata = baseData[&quot;x&quot;] ydata = baseData[&quot;y&quot;] nums = [] for i in range(len(xdata)): nums.append(xdata[i] - ydata[i]) median = np.median(nums) else: print(&quot;malformed data&quot;) def getY(x): pass while True: data = input(&quot;X/Data:&quot;) print(int(data)-median) </code></pre> <p>To work the program, give it X and Y data, then give it X data and it will predict Y data.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-13T22:16:33.157", "Id": "507776", "Score": "0", "body": "Do you have a particular question or concern with your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-13T22:43:24.350", "Id": "507780", "Score": "0", "body": "@KaPy3141 I want to know some ways I can improve or minify this code." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-13T20:37:41.530", "Id": "257111", "Score": "0", "Tags": [ "python", "python-3.x", "machine-learning" ], "Title": "Machine Learning Program" }
257111
max_votes
[ { "body": "<p><code>baseData</code> should be split into 3 separate variables(<code>collecting</code>, <code>xdata</code>, <code>ydata</code>); there is no reason for it to be a dict.</p>\n<pre><code>nums = []\nfor i in range(len(xdata)):\n nums.append(xdata[i] - ydata[i])\n</code></pre>\n<p>can be written more Pythonically as:</p>\n<pre><code>nums = []\nfor x, y in zip(xdata, ydata):\n nums.append(x - y)\n</code></pre>\n<p>or even just:</p>\n<pre><code>nums = [x - y for x, y in zip(xdata, ydata)]\n</code></pre>\n<p>You don't need to import numpy only for the media; stdlib <code>statistics.median</code> should work just fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-14T00:30:00.837", "Id": "257125", "ParentId": "257111", "Score": "2" } } ]
<p>I have written a fairly simple bot that provides information or additional choice based on the user's query. It runs well and does the job, however, I was wondering how can I optimize my code and use the telebot better?</p> <p>Currently the main action happens in the query handler and something tells me that I am missing possible efficiency gains (when I will attempt to build more choices for example). Below is the code, simplified for demonstration purposes:</p> <pre><code>import telebot from telebot import types token = bottoken bot = telebot.TeleBot(token) @bot.message_handler(commands=['start']) def welcome(message): # here i give the main choice that is always visible to the user markup = types.ReplyKeyboardMarkup(resize_keyboard=False) item1 = types.KeyboardButton(&quot;Button1&quot;) item2 = types.KeyboardButton(&quot;Button2&quot;) markup.add(item1, item2) bot.send_message(message.chat.id, &quot;Welcome message&quot;.format(message.from_user, bot.get_me()), parse_mode='html', reply_markup=markup) @bot.message_handler(content_types=['text']) def main_choice(message): # here i develop each of the main choices and redirect to the callback handler if message.text == 'Button1': # Forward to callback handler markup = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Yes&quot;, callback_data = 'demo_yes') item2 = types.InlineKeyboardButton(&quot;No&quot;, callback_data = 'demo_no') markup.add(item1, item2) bot.send_message(message.chat.id, 'Some text', reply_markup=markup) elif message.text == 'Button2': # some logic else : bot.send_message(message.chat.id, 'Sorry, i dont understand. You can use /help to check how i work') @bot.callback_query_handler(func=lambda call: True) def tempo(call): # here a handle the queries launched both by main buttons and the inline keyboard if call.data == &quot;demo_yes&quot;: keyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text1&quot;, callback_data = 'call1') item2 = types.InlineKeyboardButton(&quot;Text2&quot;, callback_data = 'call2') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) elif call.data == &quot;demo_no&quot;: kkeyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text3&quot;, callback_data = 'call3') item2 = types.InlineKeyboardButton(&quot;Text4&quot;, callback_data = 'call4') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) if call.data == &quot;call1&quot;: keyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text5&quot;, callback_data = 'another_call1') item2 = types.InlineKeyboardButton(&quot;Text6&quot;, callback_data = 'another_call2') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) elif call.data == &quot;call2&quot;: kkeyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text7&quot;, callback_data = 'another_call3') item2 = types.InlineKeyboardButton(&quot;Text8&quot;, callback_data = 'another_call4') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T12:06:21.237", "Id": "513462", "Score": "3", "body": "\"Below is the code, simplified for demonstration purposes\" Next time, please don't simplify the code. We can handle big pieces of code, but we'd be wasting your and our time by providing a review that turns out to be non-applicable to your actual code because that happens to look slightly different." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-14T23:02:52.477", "Id": "257167", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "telegram" ], "Title": "How to optimize my telegram bot written in Python?" }
257167
max_votes
[ { "body": "<p>From my point of view you can use a visitor pattern for this with a simple dictionary, specially for your operations, here is a small example:</p>\n<p>Insead of this</p>\n<pre><code>@bot.callback_query_handler(func=lambda call: True)\ndef tempo(call):\n\n # here a handle the queries launched both by main buttons and the inline keyboard \n\n\n if call.data == &quot;demo_yes&quot;:\n\n keyboard = types.InlineKeyboardMarkup()\n ......\n</code></pre>\n<p>Use the following</p>\n<pre><code>tempo_operations = {&quot;demo_yes&quot; : demo_yes_function,\n &quot;demo_no&quot; : demo_no_function, \n ....}\n\n@bot.callback_query_handler(func=lambda call: True)\ndef tempo(call):\n\n if call.data in tempo_operations:\n tempo_operations[call.data]()\n else:\n print(&quot;Operation not supported&quot;)\n</code></pre>\n<p>Hope you can get the idea :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-15T19:58:53.950", "Id": "507963", "Score": "0", "body": "That's not a visitor pattern, it's a lookup table. Since the OP is looking for efficiency, a call to `dict.get` would be preferable to a call to both `__contains__` and `__getitem__`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T12:49:26.883", "Id": "513469", "Score": "1", "body": "While I agree on the fact that it's not exactly a [visitor pattern](https://sourcemaking.com/design_patterns/visitor), the proposed solution certainly answers OP's concern regarding \"I am missing possible efficiency gains (when I will attempt to build more choices for example)\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-15T11:57:39.713", "Id": "257179", "ParentId": "257167", "Score": "1" } } ]
<p>I have written a fairly simple bot that provides information or additional choice based on the user's query. It runs well and does the job, however, I was wondering how can I optimize my code and use the telebot better?</p> <p>Currently the main action happens in the query handler and something tells me that I am missing possible efficiency gains (when I will attempt to build more choices for example). Below is the code, simplified for demonstration purposes:</p> <pre><code>import telebot from telebot import types token = bottoken bot = telebot.TeleBot(token) @bot.message_handler(commands=['start']) def welcome(message): # here i give the main choice that is always visible to the user markup = types.ReplyKeyboardMarkup(resize_keyboard=False) item1 = types.KeyboardButton(&quot;Button1&quot;) item2 = types.KeyboardButton(&quot;Button2&quot;) markup.add(item1, item2) bot.send_message(message.chat.id, &quot;Welcome message&quot;.format(message.from_user, bot.get_me()), parse_mode='html', reply_markup=markup) @bot.message_handler(content_types=['text']) def main_choice(message): # here i develop each of the main choices and redirect to the callback handler if message.text == 'Button1': # Forward to callback handler markup = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Yes&quot;, callback_data = 'demo_yes') item2 = types.InlineKeyboardButton(&quot;No&quot;, callback_data = 'demo_no') markup.add(item1, item2) bot.send_message(message.chat.id, 'Some text', reply_markup=markup) elif message.text == 'Button2': # some logic else : bot.send_message(message.chat.id, 'Sorry, i dont understand. You can use /help to check how i work') @bot.callback_query_handler(func=lambda call: True) def tempo(call): # here a handle the queries launched both by main buttons and the inline keyboard if call.data == &quot;demo_yes&quot;: keyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text1&quot;, callback_data = 'call1') item2 = types.InlineKeyboardButton(&quot;Text2&quot;, callback_data = 'call2') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) elif call.data == &quot;demo_no&quot;: kkeyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text3&quot;, callback_data = 'call3') item2 = types.InlineKeyboardButton(&quot;Text4&quot;, callback_data = 'call4') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) if call.data == &quot;call1&quot;: keyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text5&quot;, callback_data = 'another_call1') item2 = types.InlineKeyboardButton(&quot;Text6&quot;, callback_data = 'another_call2') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) elif call.data == &quot;call2&quot;: kkeyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text7&quot;, callback_data = 'another_call3') item2 = types.InlineKeyboardButton(&quot;Text8&quot;, callback_data = 'another_call4') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T12:06:21.237", "Id": "513462", "Score": "3", "body": "\"Below is the code, simplified for demonstration purposes\" Next time, please don't simplify the code. We can handle big pieces of code, but we'd be wasting your and our time by providing a review that turns out to be non-applicable to your actual code because that happens to look slightly different." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-14T23:02:52.477", "Id": "257167", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "telegram" ], "Title": "How to optimize my telegram bot written in Python?" }
257167
max_votes
[ { "body": "<p>From my point of view you can use a visitor pattern for this with a simple dictionary, specially for your operations, here is a small example:</p>\n<p>Insead of this</p>\n<pre><code>@bot.callback_query_handler(func=lambda call: True)\ndef tempo(call):\n\n # here a handle the queries launched both by main buttons and the inline keyboard \n\n\n if call.data == &quot;demo_yes&quot;:\n\n keyboard = types.InlineKeyboardMarkup()\n ......\n</code></pre>\n<p>Use the following</p>\n<pre><code>tempo_operations = {&quot;demo_yes&quot; : demo_yes_function,\n &quot;demo_no&quot; : demo_no_function, \n ....}\n\n@bot.callback_query_handler(func=lambda call: True)\ndef tempo(call):\n\n if call.data in tempo_operations:\n tempo_operations[call.data]()\n else:\n print(&quot;Operation not supported&quot;)\n</code></pre>\n<p>Hope you can get the idea :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-15T19:58:53.950", "Id": "507963", "Score": "0", "body": "That's not a visitor pattern, it's a lookup table. Since the OP is looking for efficiency, a call to `dict.get` would be preferable to a call to both `__contains__` and `__getitem__`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T12:49:26.883", "Id": "513469", "Score": "1", "body": "While I agree on the fact that it's not exactly a [visitor pattern](https://sourcemaking.com/design_patterns/visitor), the proposed solution certainly answers OP's concern regarding \"I am missing possible efficiency gains (when I will attempt to build more choices for example)\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-15T11:57:39.713", "Id": "257179", "ParentId": "257167", "Score": "1" } } ]
<p>I have written a fairly simple bot that provides information or additional choice based on the user's query. It runs well and does the job, however, I was wondering how can I optimize my code and use the telebot better?</p> <p>Currently the main action happens in the query handler and something tells me that I am missing possible efficiency gains (when I will attempt to build more choices for example). Below is the code, simplified for demonstration purposes:</p> <pre><code>import telebot from telebot import types token = bottoken bot = telebot.TeleBot(token) @bot.message_handler(commands=['start']) def welcome(message): # here i give the main choice that is always visible to the user markup = types.ReplyKeyboardMarkup(resize_keyboard=False) item1 = types.KeyboardButton(&quot;Button1&quot;) item2 = types.KeyboardButton(&quot;Button2&quot;) markup.add(item1, item2) bot.send_message(message.chat.id, &quot;Welcome message&quot;.format(message.from_user, bot.get_me()), parse_mode='html', reply_markup=markup) @bot.message_handler(content_types=['text']) def main_choice(message): # here i develop each of the main choices and redirect to the callback handler if message.text == 'Button1': # Forward to callback handler markup = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Yes&quot;, callback_data = 'demo_yes') item2 = types.InlineKeyboardButton(&quot;No&quot;, callback_data = 'demo_no') markup.add(item1, item2) bot.send_message(message.chat.id, 'Some text', reply_markup=markup) elif message.text == 'Button2': # some logic else : bot.send_message(message.chat.id, 'Sorry, i dont understand. You can use /help to check how i work') @bot.callback_query_handler(func=lambda call: True) def tempo(call): # here a handle the queries launched both by main buttons and the inline keyboard if call.data == &quot;demo_yes&quot;: keyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text1&quot;, callback_data = 'call1') item2 = types.InlineKeyboardButton(&quot;Text2&quot;, callback_data = 'call2') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) elif call.data == &quot;demo_no&quot;: kkeyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text3&quot;, callback_data = 'call3') item2 = types.InlineKeyboardButton(&quot;Text4&quot;, callback_data = 'call4') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) if call.data == &quot;call1&quot;: keyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text5&quot;, callback_data = 'another_call1') item2 = types.InlineKeyboardButton(&quot;Text6&quot;, callback_data = 'another_call2') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) elif call.data == &quot;call2&quot;: kkeyboard = types.InlineKeyboardMarkup() item1 = types.InlineKeyboardButton(&quot;Text7&quot;, callback_data = 'another_call3') item2 = types.InlineKeyboardButton(&quot;Text8&quot;, callback_data = 'another_call4') keyboard.add(item1,item2) bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T12:06:21.237", "Id": "513462", "Score": "3", "body": "\"Below is the code, simplified for demonstration purposes\" Next time, please don't simplify the code. We can handle big pieces of code, but we'd be wasting your and our time by providing a review that turns out to be non-applicable to your actual code because that happens to look slightly different." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-14T23:02:52.477", "Id": "257167", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "telegram" ], "Title": "How to optimize my telegram bot written in Python?" }
257167
max_votes
[ { "body": "<p>From my point of view you can use a visitor pattern for this with a simple dictionary, specially for your operations, here is a small example:</p>\n<p>Insead of this</p>\n<pre><code>@bot.callback_query_handler(func=lambda call: True)\ndef tempo(call):\n\n # here a handle the queries launched both by main buttons and the inline keyboard \n\n\n if call.data == &quot;demo_yes&quot;:\n\n keyboard = types.InlineKeyboardMarkup()\n ......\n</code></pre>\n<p>Use the following</p>\n<pre><code>tempo_operations = {&quot;demo_yes&quot; : demo_yes_function,\n &quot;demo_no&quot; : demo_no_function, \n ....}\n\n@bot.callback_query_handler(func=lambda call: True)\ndef tempo(call):\n\n if call.data in tempo_operations:\n tempo_operations[call.data]()\n else:\n print(&quot;Operation not supported&quot;)\n</code></pre>\n<p>Hope you can get the idea :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-15T19:58:53.950", "Id": "507963", "Score": "0", "body": "That's not a visitor pattern, it's a lookup table. Since the OP is looking for efficiency, a call to `dict.get` would be preferable to a call to both `__contains__` and `__getitem__`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T12:49:26.883", "Id": "513469", "Score": "1", "body": "While I agree on the fact that it's not exactly a [visitor pattern](https://sourcemaking.com/design_patterns/visitor), the proposed solution certainly answers OP's concern regarding \"I am missing possible efficiency gains (when I will attempt to build more choices for example)\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-15T11:57:39.713", "Id": "257179", "ParentId": "257167", "Score": "1" } } ]
<p>I want to build a barebones system according to the following spec:</p> <p>Given a setup of <code>n</code> computers, if the <code>ith</code> computer receives an operation to update a given key-value pair, it should perform the update, and propagate it to all other nodes. I'd like communication between nodes to be done with RPC.</p> <p>I have the following runnable code that works fine:</p> <pre><code>import aiomas class RpcCall: def __init__(self, port, method): self.port = port self.method = method async def __call__(self, *args, **kwargs): rpc_con = await aiomas.rpc.open_connection((&quot;localhost&quot;, self.port)) rep = await getattr(rpc_con.remote, &quot;redirect&quot;)(*args, **kwargs, method_name=self.method) await rpc_con.close() return rep class Node: def __init__(self, port, neb_ports): self.server = None self.port = port self.table = {} self.neb_ports = neb_ports def start(self): self.server = aiomas.run(aiomas.rpc.start_server((&quot;localhost&quot;, self.port), Server(self))) def close(self): self.server.close() aiomas.run(self.server.wait_closed()) async def update(self, key, value, replicate=True): self.table[key] = value if replicate: for neb in self.neb_ports: await self.replicate(neb, &quot;update&quot;, key=key, value=value, replicate=False) async def replicate(self, node, method_name, *args, **kwargs): rpc_call = RpcCall(node, method_name) await rpc_call(*args, **kwargs) class Server: router = aiomas.rpc.Service() def __init__(self, node: Node): self.node = node @aiomas.expose async def redirect(self, method_name, *args, **kwargs): func = getattr(self.node, method_name) await func(*args, **kwargs) if __name__ == &quot;__main__&quot;: n1 = Node(5555, [5556]) n2 = Node(5556, [5555]) n1.start() n2.start() aiomas.run(n1.update(&quot;foo&quot;, &quot;bar&quot;)) print(n1.table) print(n2.table) </code></pre> <p>As the output should show, the table is replicated onto both nodes, ensuring there's no data loss in case one node dies.</p> <p>I'm looking for a review specifically on the design pattern used in the above.</p> <p>I've coupled the <code>Node</code> and <code>Server</code> classes so that whenever the <code>Server</code> receives an RPC call, it delegates it back to the <code>Node</code>, which then performs the operation on the underlying <code>table </code></p> <p>Good idea/bad idea?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T21:29:28.187", "Id": "508371", "Score": "1", "body": "Could you be more specific on the \"fault-tolerant\" part? What would you expect to happen if two nodes receive the same key at (roughly) the same time? What should happen if a read call for a key arrives at the same time as a write call for the same key? Should the system be tolerant towards loss/rejoining of nodes? What do you expect to happen if a node sends an update call but the receiver dies along the way? What if the sender dies along the way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T23:49:08.143", "Id": "508376", "Score": "0", "body": "@FirefoxMetzger Hi, thanks for the comment :) I'll clarify: what I meant was in the very basic sense: if a node goes down, there's no data loss as the data is preemptively replicated to the other nodes. (Yup, not a very fault-tolerant system by most measures, or even efficient)" } ]
{ "AcceptedAnswerId": "257383", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:32:21.800", "Id": "257298", "Score": "0", "Tags": [ "python" ], "Title": "Python RPC Design Pattern - is bidrectional coupling a good idea?" }
257298
accepted_answer
[ { "body": "<p>On the coding side, every <code>Node</code> has an attribute <code>Server</code> and the <code>Server</code> has a reference to the <code>Node</code> it belongs to. <code>Node</code> calls <code>Server</code>'s methods, and <code>Server</code> reads <code>Node</code>'s attributes, so they currently are inseparable classes. I would suggest refactoring this, and - personally - I would just merge the two classes.</p>\n<p>I'm also not sure why <code>RpcCall</code> needs to be a callable class, other than for the sake of enforcing OOP. It looks like a simple function (or another method in <code>Node</code>) would do just as well. Then again, maybe your real scenario needs it to be a separate class.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for neb in self.neb_ports:\n await self.replicate(...)\n</code></pre>\n<p>This line defeats the purpose of asyncronous IO, because you are waiting for each call to finish before starting the next one. You could look into <code>Asyncio.gather</code> to start and await multiple such calls in parallel instead of sequentially.</p>\n<hr />\n<p>Regarding reliability, you - unfortunately - have none. If one node fails, it will bring peer-nodes down at the next attempt to sync the key-value store. The reason is that you are <code>await</code>ing a function that will timeout and <code>raise</code> and Exception if a connection can't be established. You are not handling this exception anywhere, so the calling node will halt. If keys are updated often enough, your entire cluster will die due to this.</p>\n<p>If a connection can be established, I'm not sure what will happen if either node dies. I briefly searched <code>aiomas</code>, but couldn't find related documentation. My guess is that the call will just hang indefinitely. This is potentially worse than a clean crash because your node will be leaky and silently suffer a death by a thousand cuts. Log messagees (if any) will likely point you into the wrong direction, making this problem hard to debug.</p>\n<p>On the point of fault-tolerant because &quot;there is no data loss because nodes replicate preemptively&quot; it really isn't just that simple.</p>\n<p>The sore point is the hierarchy among nodes, or rather the lack thereof. If the network for one node dies temporarily, it won't receive any further updates. To the node, the faulty network and not getting state changes look alike, so it will continue running happily. To the other nodes of the cluster it looks like the node died, and - assuming you add exception handling - they will continue to change state jointly. After the network issue is resolved, the lost node will reappear in the cluster and continue serving happily. However, it is now out of sync and will serve potentially outdated key-value pairs or report missing values for new ones that were set during the network outage.</p>\n<p>Assume this happens to multiple nodes; you'll end up with a heterogenious cluster and - because you lack hierarchy among your nodes - it is impossible to say what the correct state should be. Currently, you can't differentiate the order in which state-changes occurred, so rebuilding the state is ambiguous. You will need to define merging and conflict resolution mechanisms to re-establish synced state.</p>\n<p>You may also wish to establish a heartbeat for the cluster so that a node can discover connection issues. How it should handle them is context-dependent, but an easy first idea is for the node to simply suicide.</p>\n<p>Instead of creating a homebrew design-pattern for this, it may be easier to follow an established consensus method such as RAFT or PAXOS. This will take care of a lot of edge cases and may make your life considerably easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T11:08:38.537", "Id": "508409", "Score": "0", "body": "thanks for the detailed feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T05:56:02.533", "Id": "257383", "ParentId": "257298", "Score": "1" } } ]
<p>I have been working with where I use watchdogs to be able read whenever I have created a file by the name -&gt; <em>kill_</em>.flag and it contains:</p> <pre><code>*kill_*.flag contains: hello;https://www.google.se/;123 </code></pre> <p>and my script is then going to read the created file, split the &quot;;&quot; between each other and give each a key where I later on print it out which I for now has the text &quot;Deleting&quot; where I will continue my script after I have completed this part.</p> <pre class="lang-py prettyprint-override"><code># !/usr/bin/python3 # -*- coding: utf-8 -*- import os import os.path import time import watchdog.events import watchdog.observers class AutomaticCreate(watchdog.events.PatternMatchingEventHandler): def __init__(self): self.delete_flag = &quot;*kill_*.flag&quot; watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=[os.path.split(self.delete_flag)[1]], case_sensitive=False) def on_created(self, event): while True: try: with open(event.src_path) as f: content = f.read().split(&quot;;&quot;) payload = { &quot;name&quot;: content[0].strip(), &quot;link&quot;: content[1].strip(), &quot;id&quot;: content[2].strip() } break except OSError: print(f&quot;Waiting for file to transfer -&gt; {event.src_path}&quot;) time.sleep(1) continue while True: try: os.remove(event.src_path) break except Exception as err: print(f&quot;Trying to remove file -&gt; {err}&quot;) time.sleep(1) continue print(f'Deleting: {payload[&quot;name&quot;]} - {payload[&quot;link&quot;]} - {payload[&quot;id&quot;]}') def main(self): observer = watchdog.observers.Observer() observer.schedule(AutomaticCreate(), path=os.path.split(self.delete_flag)[0], recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == &quot;__main__&quot;: AutomaticCreate().main() </code></pre> <p>I wonder if there is a smarter or maybe even cleaner way to improve this code both performance and whatever it can be?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:05:24.630", "Id": "508308", "Score": "0", "body": "Are you using Python 2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:15:14.207", "Id": "508314", "Score": "0", "body": "Python 3 :) @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:16:26.930", "Id": "508315", "Score": "2", "body": "Ok. Please file a new question with your updated code. In the meantime I'll need to roll back your edit to this one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:24:32.823", "Id": "508316", "Score": "0", "body": "I have now created a new question in here: https://codereview.stackexchange.com/questions/257341/read-created-json-files-inside-a-given-folder :) @Reinderien" } ]
{ "AcceptedAnswerId": "257329", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T15:18:29.583", "Id": "257303", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Read created files in a folder" }
257303
accepted_answer
[ { "body": "<p>I genuinely hope you don't take offence by this, but this implementation is so insane that it's frankly impressive.</p>\n<p>Since you have <code>delete_flag = &quot;*kill_*.flag&quot;</code>, calling <code>os.path.split</code> on it is pointless. Perhaps you're substituting that with something else that has a path, but if you are, why isn't it parametrized?</p>\n<p>Do a tuple-unpack here:</p>\n<pre><code> content = f.read().split(&quot;;&quot;)\n payload = {\n &quot;name&quot;: content[0].strip(),\n &quot;link&quot;: content[1].strip(),\n &quot;id&quot;: content[2].strip()\n }\n</code></pre>\n<p>should just be</p>\n<pre><code>name, link, id = (part.strip() for part in f.read().split(';'))\n</code></pre>\n<p>Putting these in a <code>payload</code> dict is actively harmful. You only ever use these as variables later. About the most generous I can be here is to guess that there's actually more code in your application that you haven't shown which relies on the payload for some other network or serialized file operation, but if that's the case the whole question is invalid.</p>\n<p><code>AutomaticCreate</code> implements <code>PatternMatchingEventHandler</code> - so then why are you reinstantiating it here?</p>\n<pre><code> observer.schedule(AutomaticCreate()\n</code></pre>\n<p>You already instantiated it here:</p>\n<pre><code>AutomaticCreate().main()\n</code></pre>\n<p>Keep the second instantiation, and replace the first instantiation with a reference to <code>self</code>.</p>\n<p>The following is a strange and non-standard way of calling a base constructor:</p>\n<pre><code> watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=[os.path.split(self.delete_flag)[1]], # ...\n</code></pre>\n<p>Just use <code>super()</code>.</p>\n<p>Rework your class to be a context manager, where <code>__enter__</code> calls <code>self.observer.start()</code>, and <code>__exit__</code> calls <code>self.observer.stop()</code>. Then, use your class instance in a <code>with</code> at the top level and delete your <code>main()</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T06:01:51.283", "Id": "508263", "Score": "0", "body": "`name, link, id = (part.strip() for part in f.read().split(';'))` I think I more elegant way would be `name, link, id = map(str.strip, f.read().split(';'))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T06:59:00.337", "Id": "508264", "Score": "0", "body": "elegant but harder to read ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T08:48:15.320", "Id": "508274", "Score": "0", "body": "I have now created a new (Well updated the thread) with the new code with your guidens! Could you please look at it again and tell me if there is anything im missing? :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T02:51:23.533", "Id": "257329", "ParentId": "257303", "Score": "4" } } ]
<p>I have been working with where I use watchdogs to be able read whenever I have created a file by the name -&gt; <em>kill_</em>.flag and it contains:</p> <pre><code>*kill_*.flag contains: hello;https://www.google.se/;123 </code></pre> <p>and my script is then going to read the created file, split the &quot;;&quot; between each other and give each a key where I later on print it out which I for now has the text &quot;Deleting&quot; where I will continue my script after I have completed this part.</p> <pre class="lang-py prettyprint-override"><code># !/usr/bin/python3 # -*- coding: utf-8 -*- import os import os.path import time import watchdog.events import watchdog.observers class AutomaticCreate(watchdog.events.PatternMatchingEventHandler): def __init__(self): self.delete_flag = &quot;*kill_*.flag&quot; watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=[os.path.split(self.delete_flag)[1]], case_sensitive=False) def on_created(self, event): while True: try: with open(event.src_path) as f: content = f.read().split(&quot;;&quot;) payload = { &quot;name&quot;: content[0].strip(), &quot;link&quot;: content[1].strip(), &quot;id&quot;: content[2].strip() } break except OSError: print(f&quot;Waiting for file to transfer -&gt; {event.src_path}&quot;) time.sleep(1) continue while True: try: os.remove(event.src_path) break except Exception as err: print(f&quot;Trying to remove file -&gt; {err}&quot;) time.sleep(1) continue print(f'Deleting: {payload[&quot;name&quot;]} - {payload[&quot;link&quot;]} - {payload[&quot;id&quot;]}') def main(self): observer = watchdog.observers.Observer() observer.schedule(AutomaticCreate(), path=os.path.split(self.delete_flag)[0], recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == &quot;__main__&quot;: AutomaticCreate().main() </code></pre> <p>I wonder if there is a smarter or maybe even cleaner way to improve this code both performance and whatever it can be?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:05:24.630", "Id": "508308", "Score": "0", "body": "Are you using Python 2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:15:14.207", "Id": "508314", "Score": "0", "body": "Python 3 :) @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:16:26.930", "Id": "508315", "Score": "2", "body": "Ok. Please file a new question with your updated code. In the meantime I'll need to roll back your edit to this one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T13:24:32.823", "Id": "508316", "Score": "0", "body": "I have now created a new question in here: https://codereview.stackexchange.com/questions/257341/read-created-json-files-inside-a-given-folder :) @Reinderien" } ]
{ "AcceptedAnswerId": "257329", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T15:18:29.583", "Id": "257303", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Read created files in a folder" }
257303
accepted_answer
[ { "body": "<p>I genuinely hope you don't take offence by this, but this implementation is so insane that it's frankly impressive.</p>\n<p>Since you have <code>delete_flag = &quot;*kill_*.flag&quot;</code>, calling <code>os.path.split</code> on it is pointless. Perhaps you're substituting that with something else that has a path, but if you are, why isn't it parametrized?</p>\n<p>Do a tuple-unpack here:</p>\n<pre><code> content = f.read().split(&quot;;&quot;)\n payload = {\n &quot;name&quot;: content[0].strip(),\n &quot;link&quot;: content[1].strip(),\n &quot;id&quot;: content[2].strip()\n }\n</code></pre>\n<p>should just be</p>\n<pre><code>name, link, id = (part.strip() for part in f.read().split(';'))\n</code></pre>\n<p>Putting these in a <code>payload</code> dict is actively harmful. You only ever use these as variables later. About the most generous I can be here is to guess that there's actually more code in your application that you haven't shown which relies on the payload for some other network or serialized file operation, but if that's the case the whole question is invalid.</p>\n<p><code>AutomaticCreate</code> implements <code>PatternMatchingEventHandler</code> - so then why are you reinstantiating it here?</p>\n<pre><code> observer.schedule(AutomaticCreate()\n</code></pre>\n<p>You already instantiated it here:</p>\n<pre><code>AutomaticCreate().main()\n</code></pre>\n<p>Keep the second instantiation, and replace the first instantiation with a reference to <code>self</code>.</p>\n<p>The following is a strange and non-standard way of calling a base constructor:</p>\n<pre><code> watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=[os.path.split(self.delete_flag)[1]], # ...\n</code></pre>\n<p>Just use <code>super()</code>.</p>\n<p>Rework your class to be a context manager, where <code>__enter__</code> calls <code>self.observer.start()</code>, and <code>__exit__</code> calls <code>self.observer.stop()</code>. Then, use your class instance in a <code>with</code> at the top level and delete your <code>main()</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T06:01:51.283", "Id": "508263", "Score": "0", "body": "`name, link, id = (part.strip() for part in f.read().split(';'))` I think I more elegant way would be `name, link, id = map(str.strip, f.read().split(';'))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T06:59:00.337", "Id": "508264", "Score": "0", "body": "elegant but harder to read ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T08:48:15.320", "Id": "508274", "Score": "0", "body": "I have now created a new (Well updated the thread) with the new code with your guidens! Could you please look at it again and tell me if there is anything im missing? :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T02:51:23.533", "Id": "257329", "ParentId": "257303", "Score": "4" } } ]
<p>Here is a function for creating sliding windows from a 1D NumPy array:</p> <pre><code>from math import ceil, floor import numpy as np def slide_window(A, win_size, stride, padding = None): '''Collects windows that slides over a one-dimensional array. If padding is None, the last (rightmost) window is dropped if it is incomplete, otherwise it is padded with the padding value. ''' if win_size &lt;= 0: raise ValueError('Window size must be positive.') if not (0 &lt; stride &lt;= win_size): raise ValueError(f'Stride must satisfy 0 &lt; stride &lt;= {win_size}.') if not A.base is None: raise ValueError('Views cannot be slided over!') n_elems = len(A) if padding is not None: n_windows = ceil(n_elems / stride) A = np.pad(A, (0, n_windows * win_size - n_elems), constant_values = padding) else: n_windows = floor(n_elems / stride) shape = n_windows, win_size elem_size = A.strides[-1] return np.lib.stride_tricks.as_strided( A, shape = shape, strides = (elem_size * stride, elem_size), writeable = False) </code></pre> <p>(Code has been updated based on Marc's feedback) Meant to be used like this:</p> <pre><code>&gt;&gt;&gt; slide_window(np.arange(5), 3, 2, -1) array([[ 0, 1, 2], [ 2, 3, 4], [ 4, -1, -1]]) </code></pre> <p>Is my implementation correct? Can the code be made more readable? In NumPy 1.20 there is a function called sliding_window_view, but my code needs to work with older NumPy versions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T21:06:28.773", "Id": "508363", "Score": "0", "body": "`numpy.lib.stride_tricks.sliding_window_view` is written in pure python; if it is not for the sake of a programming exercise, is there any reason why you can't ... faithfully borrow ... their code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T21:18:22.220", "Id": "508367", "Score": "0", "body": "It doesn't support padding the last element. Maybe that can be added but it looks like lots of work." } ]
{ "AcceptedAnswerId": "257330", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T01:33:42.033", "Id": "257325", "Score": "2", "Tags": [ "python", "numpy" ], "Title": "Efficient NumPy sliding window function" }
257325
accepted_answer
[ { "body": "<p>Few suggestions:</p>\n<ul>\n<li><p><strong>Input validation</strong>: there is no input validation for <code>win_size</code> and <code>padding</code>. If <code>win_size</code> is <code>-3</code> the exception says <code>ValueError: Stride must satisfy 0 &lt; stride &lt;= -3.</code>. If <code>padding</code> is a string, numpy throws an exception.</p>\n</li>\n<li><p><strong>Type hints</strong>: consider adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">typing</a> to provide more info to the caller.</p>\n</li>\n<li><p><strong>f-Strings</strong>: depending on the version of Python you use, the exception message can be slightly simplified.</p>\n<p>From:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if not (0 &lt; stride &lt;= win_size):\n fmt = 'Stride must satisfy 0 &lt; stride &lt;= %d.'\n raise ValueError(fmt % win_size)\n</code></pre>\n<p>To:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if not 0 &lt; stride &lt;= win_size:\n raise ValueError(f'Stride must satisfy 0 &lt; stride &lt;= {win_size}.')\n</code></pre>\n</li>\n<li><p><strong>Duplication</strong>: the statement <code>shape = n_windows, win_size</code> seems duplicated and can be simplified.\nFrom:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if padding is not None:\n n_windows = ceil(n_elems / stride)\n shape = n_windows, win_size\n A = np.pad(A, (0, n_windows * win_size - n_elems),\n constant_values = padding)\nelse:\n n_windows = floor(n_elems / stride)\n shape = n_windows, win_size\n</code></pre>\n<p>To:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if padding is not None:\n n_windows = ceil(n_elems / stride)\n A = np.pad(A, (0, n_windows * win_size - n_elems),\n constant_values=padding)\nelse:\n n_windows = floor(n_elems / stride)\nshape = n_windows, win_size\n</code></pre>\n</li>\n<li><p><strong>Warning</strong>: FYI on the doc of <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.as_strided.html#numpy.lib.stride_tricks.as_strided\" rel=\"nofollow noreferrer\">np.lib.stride_tricks.as_strided</a> there is a warning that says <code>This function has to be used with extreme care, see notes.</code>. Not sure if it applies to your use case but consider checking it out.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T03:04:23.260", "Id": "257330", "ParentId": "257325", "Score": "2" } } ]
<p>I have implemented the below <code>_get_schema</code> method to ensure that <code>schema</code> attribute is always present on the <code>Todos</code> instance, and can therefore be used in the mixin.</p> <p>Is it OK to do it like this? As far as I know, mixins usually do not implement constructors.</p> <p>Is there a better way to make sure that someone did not forget to explicitly set the <code>schema</code> attribute in the <code>Todos</code> class, especially that this attribute is also not inherited from <code>View</code>?</p> <pre><code>class Mixin: def __init__(self): self._get_schema() super().__init__() def _get_schema(self): if not hasattr(self, 'schema'): msg = f'No &quot;schema&quot; attribute provided in {self.__class__.__name__} class' raise Exception(msg) class View: def __init__(self): print('view constructor') class Todos(SchemaMixin, MethodView): schema = 'todo schema' todos = Todos() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T17:18:29.867", "Id": "508348", "Score": "0", "body": "Your code looks like it has errors (two Mixin definitions, for example). Also, where does the scheme come from -- passed as argument, read from an external source, etc? How many classes will inherit from the schema-checking mixin(s) in question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T17:35:12.697", "Id": "508349", "Score": "0", "body": "Thanks for pointing that out, duplicate code is now deleted. The scheme will come only from setting it as class attribute like in my example. Rest of the implementation is inherited from my mixin and generic Flask's MethodView. My intention is to have a couple of classes that inherit from the mixin and method view like that, each class representing a specific resource in the database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T00:23:06.613", "Id": "508378", "Score": "0", "body": "Does `SchemaMixin` do anything besides verify the class has a schema attribute? Does the check need to be done at runtime or is a compile time check okay?" } ]
{ "AcceptedAnswerId": "257378", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T15:57:13.573", "Id": "257352", "Score": "0", "Tags": [ "python", "inheritance", "mixins" ], "Title": "Ensuring that attributes referenced by a mixin are present in the children class" }
257352
accepted_answer
[ { "body": "<p>I think the norm is to just try to access the <code>schema</code> attribute and let it fail with an AttributeError if there isn't one. But here are two possibilities to catch it before runtime (at compile time, or using a type checker).</p>\n<h3>Using <code>__init_subclass__()</code></h3>\n<p>This may be a good use case for adding an <a href=\"https://docs.python.org/3.8/reference/datamodel.html?highlight=__init_subclass__#object.__init_subclass__\" rel=\"nofollow noreferrer\"><code>__init_subclass__()</code></a> method to the mixin class. It will get called (at compile time) whenever a class inherits the mixin.</p>\n<pre><code>class SchemaMixin:\n def __init_subclass__(cls):\n if not hasattr(cls, 'schema'):\n raise Exception(f&quot;class {cls.__name__} is missing a 'schema' attribute.&quot;)\n\n def do_something_with_the_schema(self, *args):\n # method can rely on self having a 'schema' attribute.\n print(self.schema)\n \nclass Todo(SchemaMixin):\n schema = &quot;testing&quot;\n \nclass BadTodo(SchemaMixin):\n pass\n</code></pre>\n<p>When Python tries to compile class <code>BadTodo</code>, it will raise the following exception (traceback omitted):</p>\n<pre><code>Exception: class BadTodo is missing a 'schema' attribute.\n</code></pre>\n<h3>Using type hints</h3>\n<p>If you are using type hints, this might be checked using <a href=\"https://www.python.org/dev/peps/pep-0544/\" rel=\"nofollow noreferrer\">PEP 544 Protocols</a> to define structural subtyping.</p>\n<pre><code>from typing import Protocol\n\nclass Schema(Protocol):\n schema: ClassVar[str]\n</code></pre>\n<p>Functions/methods that need a type that has a schema attribute would use Schema as a type hint:</p>\n<pre><code>def use_a_schema(x: Schema) -&gt; some_type_hint:\n print(x.schema)\n</code></pre>\n<p>And a type checker like mypy could verify that it is called with arguments having a <code>schema</code> attribute.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T01:35:20.497", "Id": "257378", "ParentId": "257352", "Score": "1" } } ]
<p>Say I have the following two different states:</p> <pre><code>state1 = [0, 1, 0, 1, 1] state2 = [1, 1, 0, 0, 1] </code></pre> <p>And I want to generate <em>n</em> number of <em>new</em> states by <strong>only</strong> changing the values at where these states <strong>differ</strong>; and I want to do so randomly. So I did the following:</p> <pre><code>state1 = np.array(state1) differ = np.where(state1 != state2)[0] # --&gt; array([0, 3], dtype=int64) rand = [random.choices([1, 0], k=len(differ)) for _ in range(4)] states = [state1.copy() for _ in range(4)] for i in range(len(states)): states[i][differ] = rand[i] # Will replace the values at locations where they are mismatched only </code></pre> <p>Out:</p> <pre><code>[array([1, 1, 0, 0, 1]), array([1, 1, 0, 1, 1]), array([0, 1, 0, 1, 1]), array([0, 1, 0, 1, 1])] </code></pre> <p>This does the job but I was wondering if there is a better way (to avoid 2 <code>for</code> loops), but this was the best I could come up with. Any ideas on how to do the same thing but better/cleaner?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T19:43:11.363", "Id": "508358", "Score": "0", "body": "If you want to create a data set from two others that only changes where the originals differ, XOR is your friend" } ]
{ "AcceptedAnswerId": "257361", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T18:55:21.683", "Id": "257360", "Score": "3", "Tags": [ "python", "python-3.x", "array", "numpy" ], "Title": "Generating multiple new arrays using numpy" }
257360
accepted_answer
[ { "body": "<p>You could use <code>np.random.choice()</code> to generate the states, while using <code>a==b</code> and <code>a!=b</code> as masks.</p>\n<pre><code>def new_states(a,b,n):\n return [\n a*(a==b) + np.random.choice(2,len(a))*(a!=b)\n for _ in range(n)\n ]\n\nstate1 = np.array([0, 1, 0, 1, 1])\nstate2 = np.array([1, 1, 0, 0, 1])\nprint(new_states(state1,state2,4))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-18T19:42:20.200", "Id": "257361", "ParentId": "257360", "Score": "2" } } ]
<p>An attempt to find Mersenne primes using the <a href="https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test" rel="nofollow noreferrer">Lucas-Lehmer primality test</a>:</p> <pre><code>n=int(input(&quot;Enter n to check if 2^n-1 is a prime:&quot;)) a=4 for i in range(0,n-2): b=a**2 a=b-2 if i==n-3: c=(a)%((2**n) - 1) if c==0: print((2**n) - 1 ,&quot;is a prime number&quot;) break if c!=0: print((2**n) - 1 ,&quot;is not a prime number&quot;) </code></pre> <p>Can you critique this code? It is apparent that it needs improvement as it doesnt work for <strong>n&lt;=2</strong> and <em>computing power increases exponentially for increasing n</em>. I have been learning python for less than a year, I am only 15 and would love any feedback on this program.</p> <p>Edit: The confusion with n-2 and n-3 is because we have to check if the <strong>(n-1)th term</strong> in the series is divisible by <strong>l = 2^n - 1</strong> to establish that l is a Mersenne prime. But as you would have noticed the above written code considers the 0th term as 14 which is the 3rd term in the actual series. This means there is a gap of two terms between the actual series and the series procured by the program, therefore to actually study the (n-1)th term in the series , we have to consider the (n-3)th term here. Hence the mess that doesn't allow n to be &lt;=2.</p> <p>Please provide your opinion on this</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:34:22.367", "Id": "508425", "Score": "2", "body": "The solution to the problem with n <= 2 would just be returning `True` for 0 < n <= 2 and `False` for n <= 0?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T14:49:01.427", "Id": "508427", "Score": "1", "body": "For a general review you're in the right place. For a specific solution to the n <= 2 problem you'd unfortunately have to go to another sub-site, though I'm not convinced that it should be SO. Maybe CS." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T15:28:30.347", "Id": "508435", "Score": "0", "body": "Is there any way to make the code more efficient? My computer struggles for any n>25" } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T13:38:28.980", "Id": "257397", "Score": "0", "Tags": [ "python", "performance", "beginner", "mathematics" ], "Title": "Finding Mersenne primes" }
257397
max_votes
[ { "body": "<p>The page you linked to has pseudocode, and it does <code>s = ((s × s) − 2) mod M</code>. And right below the pseudocode it says:</p>\n<blockquote>\n<p>Performing the mod M at each iteration ensures that all intermediate results are at most p bits (otherwise the number of bits would double each iteration).</p>\n</blockquote>\n<p>Do that and it'll be much faster.</p>\n<p>And better use the same variable names as in the page you referenced, don't make up new ones, that just obfuscates the connection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:43:33.137", "Id": "257427", "ParentId": "257397", "Score": "1" } } ]
<p>In the following code I used a <code>while True:</code> loop and implemented <code>break</code>, because I couldn't figure out a cleaner solution than an infinite loop. Is this approach considered bad practice? Here is my code:</p> <pre><code>while True: z = int(input(&quot;Y: &quot;)) if (z &gt;= 0 and z &lt;= 20): break for x in range(z): print(&quot;-&quot; * (z-x) + &quot;*&quot; * x + &quot; &quot; * x + &quot;-&quot; * (z-x)) </code></pre> <p>... which outputs:</p> <pre class="lang-none prettyprint-override"><code>Y: 12 ------------------------ -----------* ----------- ----------** ---------- ---------*** --------- --------**** -------- -------***** ------- ------****** ------ -----******* ----- ----******** ---- ---********* --- --********** -- -*********** - </code></pre>
[]
{ "AcceptedAnswerId": "257426", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-19T22:24:30.930", "Id": "257420", "Score": "3", "Tags": [ "python", "python-3.x", "ascii-art" ], "Title": "Printing dynamic ascii-art shapes based on user input" }
257420
accepted_answer
[ { "body": "<blockquote>\n<p>I couldn't figure out a cleaner solution than an infinite loop. Is this approach considered bad practice?</p>\n</blockquote>\n<p>You can't do much better, since Python doesn't have the equivalent of a C-style <code>do/while</code>.</p>\n<p>This is a trivial program so I doubt it's even worth adding functions (etc.); the one thing that can be improved is</p>\n<pre><code>if (z &gt;= 0 and z &lt;= 20):\n</code></pre>\n<p>can be</p>\n<pre><code>if 0 &lt;= z &lt;= 20:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T03:43:00.427", "Id": "257426", "ParentId": "257420", "Score": "3" } } ]
<p>I am new to python and I had the task to find the US zip code based on latitude and longitude. After messing with arcgis I realized that this was giving me empty values for certain locations. I ended up coding something that accomplishes my task by taking a dataset containing all US codes and using Euclidean distance to determine the closest zip code based on their lat/lon. However, this takes approximately 1.3 seconds on average to compute which for my nearly million records will take a while as a need a zip code for each entry. I looked that vectorization is a thing on python to speed up tasks. But, I cannot find a way to apply it to my code. Here is my code and any feedback would be appreciated:</p> <pre><code>for j in range(len(myFile)): p1=0 p1=0 point1 = np.array((myFile[&quot;Latitude&quot;][j], myFile[&quot;Longitude&quot;][j])) # This is the reference point i = 0 resultZip = str(usZips[&quot;Zip&quot;][0]) dist = np.linalg.norm(point1 - np.array((float(usZips[&quot;Latitude&quot;][0]), float(usZips[&quot;Longitude&quot;][0])))) for i in range(0, len(usZips)): lat = float(usZips[&quot;Latitude&quot;][i]) lon = float(usZips[&quot;Longitude&quot;][i]) point2 = np.array((lat, lon)) # This will serve as the comparison from the dataset temp = np.linalg.norm(point1 - point2) if (temp &lt;= dist): # IF the temp euclidean distance is lower than the alread set it will: dist = temp # set the new distance to temp and... resultZip = str(usZips[&quot;Zip&quot;][i]) # will save the zip that has the same index as the new temp # p1=float(myFile[&quot;Latitude&quot;][58435]) # p2=float(myFile[&quot;Longitude&quot;][58435]) i += 1 </code></pre> <p>I am aware Google also has a reverse geocoder API but it has a request limit per day. The file called <code>myFile</code> is a csv file with the attributes userId, latitude, longitude, timestamp with about a million entries. The file usZips is public dataset with information about the city, lat, lon, zip and timezone with about 43k records of zips across the US.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T07:27:06.180", "Id": "508550", "Score": "3", "body": "Welcome to Code Review. It would be helpful to provide an example of input files and the expected result. Is `resultZip` the result? Why is it not saved/printed? Please include the rest of the code if possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T06:34:51.153", "Id": "508627", "Score": "0", "body": "The input files have the following parameters: myFile(UserID, Latitude, Longitude, Time) and usZips(City, State, Latitude, Longitude, Zip). What I want to accomplish is a quicker way of finding the closest zip code for each record in myFile given the location data. Per say I have latitude x and longitude y; so I need to find the zip code that is closest to the given location using the usZips which contain all zips in the US. What I did in my case is compare each value in myFile to the entire usZips file to find the closest pair. But, this takes a long time so I I need something more optimized" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:33:40.293", "Id": "510474", "Score": "0", "body": "Here's a discussion of 5 ways to do this in MySQL. Note that having an \"index\" (the datatabase type) is critical. http://mysql.rjweb.org/doc.php/find_nearest_in_mysql Meanwhile, what you have described will probably not work well with more than a few thousand points." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T07:07:09.493", "Id": "257465", "Score": "1", "Tags": [ "python", "performance" ], "Title": "Can I optimize two for loops that look for the closest zip code based on lat/lon?" }
257465
max_votes
[ { "body": "<p><code>for j in range(len(some_list))</code> is always a red flag. If you need the index, you can use <code>for j,element in enumerate(some_list)</code>. If you don't need the index (like here), you should just use <code>for element in some_list</code>. (Speaking of which, csv files don't have lengths that you can iterate over. Numpy arrays or Pandas DataFrames do.)</p>\n<p>You have <code>i=0</code>, <code>for i in range</code> and <code>i+=1</code>. You only want the middle of those (and <code>i+=1</code> will cause a bug if it's even executed). But you don't even want the middle, because of the previous paragraph. Also, you need to guard against returning that your closest zip code is yourself.</p>\n<p>You flip around between floats and strings. I find my life is much easier the sooner I convert my data to the appropriate format. This means that you should convert your latitude and longitude to floats as soon as possible (probably when you load the csv file). I don't see a problem leaving the zip code as an int until later. Just be aware that you will need to format it at some point: some zip codes start with 0.</p>\n<p>Instead of pre-seeding dist with the first zip code, it might be clearer to start dist off as <code>float('inf')</code>. But:</p>\n<p>The whole point of the inner for loop is to find the closest point. We can use <code>min</code> to do that, as long as we tell Python what we want to minimize, and remove the inner loop entirely (from the code, not the runtime).</p>\n<p>What is <code>p1</code>? What do you do with <code>resultZip</code>?</p>\n<p>Your distance calculation is assuming a flat earth. That breaks down more with higher latitudes (for example, all longitudes at latitude 89 are fairly close together). Also, calculating the square of the distance is usually faster, since most involve taking a square root at the end. (Also, letting the distance function take rows instead of points will allow us to simplify some other parts.) A good approximation for a spherical earth (instead of ellipsoidal) would be</p>\n<pre><code>def dist_sq(row1,row2):\n if row1==row2:\n return float('inf')\n dx = (row1['longitude']-row2['longitude'])*math.cos((row1['latitude']+row2['latitude'])/2)\n dy = row1['latitude']-row2['latitude']\n return dx*dx+dy*dy\n</code></pre>\n<p>That leaves us with your logic boiled down to:</p>\n<pre><code>import functools\nfor row in myFile:\n resultZip = min(myFile,key=functools.partial(dist_sq,row))['Zip']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T22:08:03.580", "Id": "266277", "ParentId": "257465", "Score": "1" } } ]
<p>I am new to python and I had the task to find the US zip code based on latitude and longitude. After messing with arcgis I realized that this was giving me empty values for certain locations. I ended up coding something that accomplishes my task by taking a dataset containing all US codes and using Euclidean distance to determine the closest zip code based on their lat/lon. However, this takes approximately 1.3 seconds on average to compute which for my nearly million records will take a while as a need a zip code for each entry. I looked that vectorization is a thing on python to speed up tasks. But, I cannot find a way to apply it to my code. Here is my code and any feedback would be appreciated:</p> <pre><code>for j in range(len(myFile)): p1=0 p1=0 point1 = np.array((myFile[&quot;Latitude&quot;][j], myFile[&quot;Longitude&quot;][j])) # This is the reference point i = 0 resultZip = str(usZips[&quot;Zip&quot;][0]) dist = np.linalg.norm(point1 - np.array((float(usZips[&quot;Latitude&quot;][0]), float(usZips[&quot;Longitude&quot;][0])))) for i in range(0, len(usZips)): lat = float(usZips[&quot;Latitude&quot;][i]) lon = float(usZips[&quot;Longitude&quot;][i]) point2 = np.array((lat, lon)) # This will serve as the comparison from the dataset temp = np.linalg.norm(point1 - point2) if (temp &lt;= dist): # IF the temp euclidean distance is lower than the alread set it will: dist = temp # set the new distance to temp and... resultZip = str(usZips[&quot;Zip&quot;][i]) # will save the zip that has the same index as the new temp # p1=float(myFile[&quot;Latitude&quot;][58435]) # p2=float(myFile[&quot;Longitude&quot;][58435]) i += 1 </code></pre> <p>I am aware Google also has a reverse geocoder API but it has a request limit per day. The file called <code>myFile</code> is a csv file with the attributes userId, latitude, longitude, timestamp with about a million entries. The file usZips is public dataset with information about the city, lat, lon, zip and timezone with about 43k records of zips across the US.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T07:27:06.180", "Id": "508550", "Score": "3", "body": "Welcome to Code Review. It would be helpful to provide an example of input files and the expected result. Is `resultZip` the result? Why is it not saved/printed? Please include the rest of the code if possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T06:34:51.153", "Id": "508627", "Score": "0", "body": "The input files have the following parameters: myFile(UserID, Latitude, Longitude, Time) and usZips(City, State, Latitude, Longitude, Zip). What I want to accomplish is a quicker way of finding the closest zip code for each record in myFile given the location data. Per say I have latitude x and longitude y; so I need to find the zip code that is closest to the given location using the usZips which contain all zips in the US. What I did in my case is compare each value in myFile to the entire usZips file to find the closest pair. But, this takes a long time so I I need something more optimized" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:33:40.293", "Id": "510474", "Score": "0", "body": "Here's a discussion of 5 ways to do this in MySQL. Note that having an \"index\" (the datatabase type) is critical. http://mysql.rjweb.org/doc.php/find_nearest_in_mysql Meanwhile, what you have described will probably not work well with more than a few thousand points." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T07:07:09.493", "Id": "257465", "Score": "1", "Tags": [ "python", "performance" ], "Title": "Can I optimize two for loops that look for the closest zip code based on lat/lon?" }
257465
max_votes
[ { "body": "<p><code>for j in range(len(some_list))</code> is always a red flag. If you need the index, you can use <code>for j,element in enumerate(some_list)</code>. If you don't need the index (like here), you should just use <code>for element in some_list</code>. (Speaking of which, csv files don't have lengths that you can iterate over. Numpy arrays or Pandas DataFrames do.)</p>\n<p>You have <code>i=0</code>, <code>for i in range</code> and <code>i+=1</code>. You only want the middle of those (and <code>i+=1</code> will cause a bug if it's even executed). But you don't even want the middle, because of the previous paragraph. Also, you need to guard against returning that your closest zip code is yourself.</p>\n<p>You flip around between floats and strings. I find my life is much easier the sooner I convert my data to the appropriate format. This means that you should convert your latitude and longitude to floats as soon as possible (probably when you load the csv file). I don't see a problem leaving the zip code as an int until later. Just be aware that you will need to format it at some point: some zip codes start with 0.</p>\n<p>Instead of pre-seeding dist with the first zip code, it might be clearer to start dist off as <code>float('inf')</code>. But:</p>\n<p>The whole point of the inner for loop is to find the closest point. We can use <code>min</code> to do that, as long as we tell Python what we want to minimize, and remove the inner loop entirely (from the code, not the runtime).</p>\n<p>What is <code>p1</code>? What do you do with <code>resultZip</code>?</p>\n<p>Your distance calculation is assuming a flat earth. That breaks down more with higher latitudes (for example, all longitudes at latitude 89 are fairly close together). Also, calculating the square of the distance is usually faster, since most involve taking a square root at the end. (Also, letting the distance function take rows instead of points will allow us to simplify some other parts.) A good approximation for a spherical earth (instead of ellipsoidal) would be</p>\n<pre><code>def dist_sq(row1,row2):\n if row1==row2:\n return float('inf')\n dx = (row1['longitude']-row2['longitude'])*math.cos((row1['latitude']+row2['latitude'])/2)\n dy = row1['latitude']-row2['latitude']\n return dx*dx+dy*dy\n</code></pre>\n<p>That leaves us with your logic boiled down to:</p>\n<pre><code>import functools\nfor row in myFile:\n resultZip = min(myFile,key=functools.partial(dist_sq,row))['Zip']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-21T22:08:03.580", "Id": "266277", "ParentId": "257465", "Score": "1" } } ]
<p>I have made a <em>password verification</em> &quot;program&quot; which takes user input and checks whether the password is valid or not. Based on that, a reply is printed.</p> <pre><code>print(&quot;Create a password! Your password must have 8 to 12 digits. Numbers and lower as well as upper case letters must be a part of it!&quot;) password = input(&quot;Enter your password:&quot;) res = any(chr.isdigit() for chr in password) res2 = any(chr.islower() for chr in password) res3 = any(chr.isupper() for chr in password) if len(password) &gt;= 8 and len(password) &lt;13 and res == True and res2 == True and res3 == True : print(&quot;Welcome!&quot;) else: print(&quot;Your password is not valid!&quot;) </code></pre> <p>Is there a more elegant or better way? Maybe you also have some ideas on how to expand the project?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:28:27.183", "Id": "508771", "Score": "8", "body": "Don't worry, I was not planing on using this for anything. It was just a small project so that I have something specific to look into. Otherwise getting into programming seems pretty overwhelming" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T15:38:33.293", "Id": "508962", "Score": "0", "body": "I remember that overwhelming feeling (hell, I still have it sometimes), but don‘t let it discourage you. For me the key was to find projects that steadily increase in complexity. The closer a project is to a real use case, the better." } ]
{ "AcceptedAnswerId": "257478", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T16:23:39.930", "Id": "257476", "Score": "20", "Tags": [ "python", "beginner", "python-3.x", "strings" ], "Title": "Password validator" }
257476
accepted_answer
[ { "body": "<p>Two general points about your code:</p>\n<ol>\n<li><p><strong>Variable naming:</strong> <code>res, res2, res3</code> are not descriptive, so it's harder to understand at first glance what their purpose is. Instead\nI would recommend something similiar to <code>contains_digit, contains_lower_char, contains_upper_char</code>. Variable naming is always up to a bit of personal preference, but explicit names are generally preferable.</p>\n</li>\n<li><p><strong>Conditionals:</strong> The way the condition in your if-statement is set up is suboptimal. Firstly: <code>len(password) &gt;= 8 and len(password) &lt;13</code> can be shortened to <code>8 &lt;= len(password) &lt;= 12</code> or <code>len(password) in range(8, 13)</code>. This is more readable and depicts your intentions in a more concise way. Secondly: You almost never need <code>== True</code> clauses since <code>True == True -&gt; True</code> and <code>False == True -&gt; False</code>. So the second part of your condition can be shortened to <code>res and res2 and res3</code>. This is also where better variable names make the functionality of your program way clearer.</p>\n</li>\n</ol>\n<p>To avoid multiple concatenated <code>and</code>-statements you could probably use something like <code>all([len(password) in range(8, 13), res, res2, res3])</code>, but I find this usually decreases readbility.</p>\n<p>To conclude I would suggest the following if-condition:</p>\n<pre><code>if 8 &lt;= len(password) &lt;= 12 and contains_digit and contains_lower and contains_upper:\n</code></pre>\n<p>On a side note: This is not a password generator, but a password validity checker. You might want to additionally check, that the password only includes ASCII-characters if that is relevant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:03:41.870", "Id": "508575", "Score": "0", "body": "Thank you! That's really helpful, I can see what you mean" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:05:17.137", "Id": "508576", "Score": "0", "body": "Glad to help. Please consider marking the question as answered (i.e. accept an answer) if you requirements are met, so other contributors know the question does not require further attention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:17:06.543", "Id": "508578", "Score": "12", "body": "Please consider upvoting the question as well. If it was worth answering, it should've been worth a vote too. Otherwise, why did you answer it? ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:33:19.590", "Id": "508867", "Score": "0", "body": "@mast is that a thing?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-21T17:01:20.757", "Id": "257478", "ParentId": "257476", "Score": "29" } } ]
<p>I have implemented a radix sort algorithm in Python 3. It first finds the maximum number of digits in the list, then changes them to strings and adds 0's. For example, [7, 23, 107, 1, 53] to ['007', '023', '107', '001', '053']. I then make a new matrix, [[] * 10]. I append the numbers with last digit of 0 in lst[0], numbers with last digit of 1 in lst[1], etc. I then flatten the matrix into a list, and recurse with the lst, and with the position one less than the one before (in this case, the second to last digit). Can I get advice on how to improve it? Here is my code:</p> <pre><code>def radix_sort(lst): '''list -&gt; list''' #finds maximum number of digits in list num_of_digits = max([len(str(x)) for x in lst]) #Adds 0s to the front of the number if necessary and changes it to a string for x in range(len(lst)): lst[x] = '0' * (num_of_digits - len(str(lst[x]))) + str(lst[x]) #helper function to sort based on the position def helper(lst, pos): '''list, int -&gt; list''' #places numbers with 0 in the position in the ans[0], 1 in the position in ans[1], etc. ans = [[] for _ in range(10)] #adding numbers to the position in ans for x in lst: ans[int(x[pos])].append(x) #flattened list, reusing lst to save memory lst = [] for x in ans: for y in x: lst.append(y) #we have sorted the whole list if pos == 0: return lst #recurse again with smaller position return helper(lst, pos - 1) #changing the strings to integers and returning return [int(x) for x in helper(lst, num_of_digits - 1)] </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T19:12:46.070", "Id": "257588", "Score": "4", "Tags": [ "python", "python-3.x", "sorting", "radix-sort" ], "Title": "Radix Sort Speed" }
257588
max_votes
[ { "body": "<pre><code> #flattened list, reusing lst to save memory\n lst = []\n</code></pre>\n<p>That doesn't save memory. The caller of the current <code>helper</code> call still has a reference to the &quot;old&quot; list, so it'll remain in memory in addition to this new one. You'll have one list per call level. To actually save memory, you could do <code>lst.clear()</code> instead, so that all levels use the same single list.</p>\n<p>To further save memory, do <code>del ans, x, y</code> after you rebuilt <code>lst</code> from them before you call <code>helper</code> recursively, otherwise they'll remain in memory as well, again once per call level.</p>\n<p>For example for <code>lst = ['1' * 800] * 1000</code>, these improvements changed the peak memory usage from over 15 MB to less than 0.5 MB in this test of mine:</p>\n<pre><code>import tracemalloc\n\nlst = ['1' * 800] * 1000\ntracemalloc.start()\nradix_sort(lst)\npeak = tracemalloc.get_traced_memory()[1]\nprint(peak)\n</code></pre>\n<p>Or just do it iteratively instead of recursively, then you likely wouldn't have these issues in the first place and you wouldn't have to worry about recursion limit errors due to large numbers.</p>\n<p>Here's an iterative one with a few other changes:</p>\n<pre><code>def radix_sorted(lst):\n '''list -&gt; list'''\n lst = list(map(str, lst))\n width = max(map(len, lst))\n lst = [s.rjust(width, '0') for s in lst]\n for i in range(width)[::-1]:\n buckets = [[] for _ in range(10)]\n for s in lst:\n buckets[int(s[i])].append(s)\n lst = [s for b in buckets for s in b]\n return list(map(int, lst))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T23:04:57.660", "Id": "508790", "Score": "0", "body": "Oh, thanks! I thought it was saving memory, I guess I was completely wrong. This will help my memory usage a lot. By the way, is there really a chance that I'll get a recursion limit error? The recursion depth is 1,000 which means it'll only pass recursion depth for 1000+ digit numbers, am I wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T00:04:31.393", "Id": "508793", "Score": "0", "body": "@SolaSky Yes, roughly at 1000 digits you'd hit the limit. Whether there's a chance that you have such numbers, I don't know, only you do :-). Btw I added an iterative one now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T20:02:25.017", "Id": "257589", "ParentId": "257588", "Score": "1" } } ]
<p>I have:</p> <ul> <li>A dataframe with Identifiers (<code>TermId</code>) and Search Terms (<code>SearchTerm</code>).</li> <li>A list of text strings (<code>MyText</code>). This likely would be a column (series) in a dataframe.</li> </ul> <p>I for every string in <code>MyText</code> I want to get a count of hits for every regex <code>SearchTerm</code>, producing a table of counts. This is a scaled down example. I'd have 10,000 of <code>Mytext</code> and 100s of <code>SearchTerm</code>s. I am newer to Python (from R) and would like to know where can I optimize the code to make it more performant? I'm open to what ever feedback people have to offer on all aspects of the code.</p> <pre><code>## Dependencies import re import pandas as pd ## Data MyText = ['I saw xx.yy and also xx.yyy', 'FireFly* this is xx_yy there', 'I xx$YY', 'I see x.yy now .NET', 'now xx.yyxx.yyxx.yy'] MyDictionary = pd.DataFrame({ 'TermId': ['SK_{}'.format(x) for x in list(range(0, 6))], 'SearchTerm': ['xx[.]yy', '[.]NET', 'A[+]', 'FireFly[*]', 'NetFlix[$]', 'Adobe[*]'] }) ## Convert Search Term to Compiled Regex Object MyDictionary['Regexes'] = [re.compile(s) for s in MyDictionary['SearchTerm']] ## List comprehension to double loop over the regexes &amp; ## elements of MyText to count hits out = {id: [len(regex.findall(s)) for s in MyText] for regex, id in zip(MyDictionary['Regexes'], MyDictionary['TermId'])} out = pd.DataFrame(out) out['MyText'] = MyText ## Results print(out) print(MyDictionary) </code></pre> <p>Which yields:</p> <pre><code> SK_0 SK_1 SK_2 SK_3 SK_4 SK_5 MyText 0 2 0 0 0 0 0 I saw xx.yy and also xx.yyy 1 0 0 0 1 0 0 FireFly* this is xx_yy there 2 0 0 0 0 0 0 I xx$YY 3 0 1 0 0 0 0 I see x.yy now .NET 4 3 0 0 0 0 0 now xx.yyxx.yyxx.yy </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T01:59:00.400", "Id": "257601", "Score": "2", "Tags": [ "python", "beginner", "regex", "pandas" ], "Title": "Martix of Counts of Regex Hits Over a List of Strings" }
257601
max_votes
[ { "body": "<p>An idiomatic approach would be to put <code>MyText</code> in a dataframe (if not already) and <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.assign.html\" rel=\"nofollow noreferrer\"><strong><code>assign()</code></strong></a> the results of <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.Series.str.count.html\" rel=\"nofollow noreferrer\"><strong><code>str.count()</code></strong></a>.</p>\n<p>I'd also suggest using an actual <code>dict</code> for the regex mapping. It's not strictly necessary, but the syntax is just cleaner given that this use case aligns with <code>dict</code>. (Here I created <code>terms</code> from <code>MyDictionary</code> just for continuity with the existing code.)</p>\n<pre class=\"lang-py prettyprint-override\"><code>terms = dict(zip(MyDictionary.TermId, MyDictionary.SearchTerm))\ndf = pd.DataFrame({'MyText': MyText})\n\ndf = df.assign(**{key: df.MyText.str.count(val) for key, val in terms.items()})\n\n# MyText SK_0 SK_1 SK_2 SK_3 SK_4 SK_5\n# 0 I saw xx.yy and also xx.yyy 2 0 0 0 0 0\n# 1 FireFly* this is xx_yy there 0 0 0 1 0 0\n# 2 I xx$YY 0 0 0 0 0 0\n# 3 I see x.yy now .NET 0 1 0 0 0 0\n# 4 now xx.yyxx.yyxx.yy 3 0 0 0 0 0\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:45:28.743", "Id": "258819", "ParentId": "257601", "Score": "2" } } ]
<p>I asked <a href="https://stackoverflow.com/questions/66769861/how-is-my-almostincreasingsequencesequence-code-incorrect-codesignal">this</a> question on Stackoverflow as well, but I think it's best suited here because my code needs optimization instead of error checking (that I previously thought).</p> <p>I've made changes to my code as well. But the logic is pretty much the same:</p> <ul> <li>My code first checks the length of the provided sequence, if it is 2 or less it automatically returns <code>True</code>.</li> <li>Next, it creates a <code>newlist</code> with the first element removed and checks if the rest of the list is in ascending order.</li> <li>If the sequence is not in order, the iteration <code>breaks</code> and a <code>newlist</code> is generated again and this time with the next element removed.</li> <li>This continues until there are no more elements to remove (i.e. <code>i == len(sequence) - 1</code>), which ultimately returns as <code>False</code></li> <li>If in any of the iterations, the list is found to be in ascending order(i.e. <code>in_order</code> remains <code>True</code>), the function returns <code>True</code>.</li> </ul> <pre><code>def almostIncreasingSequence(sequence): # return True for lists with 2 or less elements. if len(sequence) &lt;= 2: return True # Outerloop, removes i-th element from sequence at each iteration for i in range(len(sequence)): newlist = sequence[:i] + sequence[i+1:] # Innerloop, checks if the sequence is in ascending order j = 0 in_order = True while j &lt; len(newlist) - 1: if newlist[j+1] &lt;= newlist[j]: in_order = False break j += 1 if in_order == True: return True elif i == len(sequence)-1: return False </code></pre> <hr /> <p>I received a suggestion that <strong>I should only use one loop</strong>, but I cannot think of a way to implement that. Nested loops seems necessary because of the following assumptions:</p> <ol> <li>I have to remove every next element from the original sequence. (outer loop)</li> <li>I need to check if all the elements are in order. (inner loop)</li> </ol> <p><a href="https://stackoverflow.com/questions/43017251/solve-almostincreasingsequence-codefights">This</a> is a brief on <code>almostIncreasingSequence()</code> my code follows the logic provided in the answer here, it solves almost all of the Tests as well, but it is too slow for larger lists (that are approx 10000+ elements).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:17:58.013", "Id": "510470", "Score": "0", "body": "Please define \"almost\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:18:54.193", "Id": "510471", "Score": "0", "body": "Since full sorting is known to be O(N*logN), you have to do at least that good. Your description sounds like O(N*N)." } ]
{ "AcceptedAnswerId": "257660", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T08:26:16.123", "Id": "257606", "Score": "3", "Tags": [ "performance", "python-3.x" ], "Title": "My 'almostIncreasingSequence(sequence)' code is too slow for lists that have 10000+ elements. [CodeSignal]" }
257606
accepted_answer
[ { "body": "<h2>Checking if a list is strictly increasing</h2>\n<p>The inner loop checks if a list (in this case <code>newList</code>) is strictly increasing:</p>\n<pre class=\"lang-py prettyprint-override\"><code>j = 0\nin_order = True\nwhile j &lt; len(newlist) - 1:\n if newlist[j+1] &lt;= newlist[j]:\n in_order = False\n break\n j += 1\nif in_order == True:\n return True\n</code></pre>\n<ol>\n<li>In general variable names should use underscores, so <code>newlist</code> becomes <code>new_list</code>. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP 8</a>.</li>\n<li>It can be simplified with a <code>for-else</code>:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>for j in range(len(new_list) - 1):\n if new_list[j+1] &lt;= new_list[j]:\n break\nelse:\n return True\n</code></pre>\n<p>Or using <code>all</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if all(new_list[i] &gt; new_list[i - 1] for i in range(1, len(new_list))):\n return True\n</code></pre>\n<h2>Optimization</h2>\n<p>As you said, the solution is too slow for large input due to the inner loop that runs every time, making the overall complexity <span class=\"math-container\">\\$O(n^2)\\$</span>.</p>\n<p>The current solution follows this approach:</p>\n<ol>\n<li>For each element of the input list</li>\n<li>Build a new list without such element and check if strictly increasing</li>\n</ol>\n<p>Consider simplifying the approach like the following:</p>\n<ol>\n<li>Find the first pair that is not strictly increasing</li>\n<li>Build a new list without the first element of the pair and check if it is increasing</li>\n<li>Build a new list without the second element of the pair and check if it is increasing</li>\n</ol>\n<p>For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def almostIncreasingSequence(sequence):\n def is_increasing(l):\n return all(l[i] &gt; l[i - 1] for i in range(1, len(l)))\n\n if is_increasing(sequence):\n return True\n\n # Find non-increasing pair\n left, right = 0, 0\n for i in range(len(sequence) - 1):\n if sequence[i] &gt;= sequence[i + 1]:\n left, right = i, i + 1\n break\n\n # Remove left element and check if it is strictly increasing\n if is_increasing(sequence[:left] + sequence[right:]):\n return True\n\n # Remove right element and check if it is strictly increasing\n if is_increasing(sequence[:right] + sequence[right + 1:]):\n return True\n\n return False\n</code></pre>\n<p>I believe there should be an approach that doesn't build the two additional lists to reduce the space complexity, but I'll leave that to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T05:52:20.457", "Id": "257660", "ParentId": "257606", "Score": "2" } } ]
<p>I'm currently trying to do data quality checks in python primarily using <code>Pandas</code>.</p> <p>The code below is fit for purpose. The idea is to do the checks in Python and export to an Excel file, for audit reasons.</p> <p>I perform checks like the below in 4 different files, sometimes checking if entries in one are also in the other, etc.</p> <p><code>df_symy</code> is just another DataFrame that I imported inside the same class.</p> <br> <p>I'm wondering if there's a <strong>better way</strong> to do this task, for example:</p> <ul> <li>create a function for each check</li> <li>create a more meaningful way to check the data and present the results, etc</li> </ul> <br> <pre><code>def run_sharepoint_check(self) -&gt; pd.DataFrame: &quot;&quot;&quot;Perform checks on data extracted from SharePoint. Check 1: Amount decided is 0 or NaN Check 2: Invalid BUS ID Check 3: Duplicated entries. It also tags the latest entry Check 4: SYMY Special not in SharePoint &quot;&quot;&quot; # Use this function to check the data we have from SharePoint # and return DF with checks in the excel file # Another function will be used to process the data and produce # the final list df = self.sharepoint_data.copy() df_symy = self.symy_data df_symy = df_symy.loc[df_symy['COMMITMENT_TYPE'].str[0] == 'S'] symy_cols = ['BUYER_NUMBER', 'Balloon ID', 'CLD_TOTAL_AMOUNT', 'POLICY_CURRENCY'] df = df.merge(right=df_symy[symy_cols], how='outer', left_on=['Balloon ID', 'BUS ID'], right_on=['Balloon ID', 'BUYER_NUMBER']) check_1 = df['Amount decided'] == 0 | df['Amount decided'].isna() df.loc[check_1, 'check_1'] = 'Amount decided is 0 or NaN' check_2 = df['BUS ID'].isna() df.loc[check_2, 'check_2'] = 'Invalid BUS ID' check_3 = df.duplicated(subset=['Balloon ID', 'BUS ID'], keep=False) df.loc[check_3, 'check_3'] = 'Duplicated entry' check_3_additional = ~df.duplicated( subset=['Balloon ID', 'BUS ID'], keep='first' ) # Filter only the entries that are duplicated # Out of those, the first one is the latest df.loc[(check_3) &amp; (check_3_additional), 'check_3'] = 'Duplicated entry (Latest)' # Match Balloon+BUSID (SYMY) to SharePoint check_4 = (~df.duplicated(subset=['Balloon ID', 'BUS ID'], keep='first')) &amp; (df['BUS ID'].isna()) df.loc[check_4, 'check_4'] = 'SYMY SA not in SharePoint' check_cols = ['check_1', 'check_2', 'check_3', 'check_4'] # .fillna('OK') just for visual purposes in Excel. df[check_cols] = df[check_cols].fillna('OK') # self.data_checks_dfs in the init method is an empty dictionary. self.data_checks_dfs['SharePoint_checks'] = df return df </code></pre> <p>So, how can I improve this?</p> <p>Does anyone have this type of task that has been automated using Python?</p>
[]
{ "AcceptedAnswerId": "258980", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T14:45:01.970", "Id": "257676", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "Function to perform checks on data" }
257676
accepted_answer
[ { "body": "<p>It seems difficult to comment on the <em>meaningfulness</em> of your proposed solution. You are the one to decide on that since you know the context around your problem. With that being said, I'm afraid there is not much to go on here.</p>\n<p>Nevertheless, one observation I make about your code is that the checks use <code>.loc</code> to locate rows that receive a &quot;non-OK&quot;, and finally, after all checks, you use a fill to turn nans into &quot;OK&quot;. To make your code more concise and likely faster, consider using <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.where.html\" rel=\"nofollow noreferrer\"><code>np.where</code></a>. So for instance, your <code>check_1</code> would be turned into:</p>\n<pre><code>df[&quot;check_1&quot;] = np.where(\n (df['Amount decided'] == 0) | (df['Amount decided'].isna()),\n &quot;Amount decided is 0 or NaN&quot;, &quot;OK&quot;)\n</code></pre>\n<p>Also, I would rename <code>check_N</code> into something that actually means a little more, like <code>amount_check</code> for <code>check_1</code> and so on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T20:12:47.440", "Id": "510976", "Score": "0", "body": "Thanks for answering the question. I know it's a little abstract. I guess I doubt myself too much when it comes to writing these codes, and I'm always looking for validation to see if what I'm doing is correct or not, and what I can improve." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T19:31:35.447", "Id": "258980", "ParentId": "257676", "Score": "0" } } ]
<p>I have a <code>.txt</code> file that looks like this:</p> <pre><code>SHT1 E: T1:30.45°C H1:59.14 %RH SHT2 S: T2:29.93°C H2:67.38 %RH SHT1 E: T1:30.49°C H1:58.87 %RH SHT2 S: T2:29.94°C H2:67.22 %RH SHT1 E: T1:30.53°C H1:58.69 %RH SHT2 S: T2:29.95°C H2:67.22 %RH </code></pre> <p>I want to have a <code>DataFrame</code> that looks like this:</p> <pre><code> T1 H1 T2 H2 0 30.45 59.14 29.93 67.38 1 30.49 58.87 29.94 67.22 2 30.53 58.69 29.95 67.22 </code></pre> <p>I parse this by:</p> <ol> <li>Reading up the text file line by line</li> <li>Parsing the lines e.g. matching only the parts with <code>T1, T2, H1, and H2</code>, splitting by <code>:</code>, and removing <code>°C</code> and <code>%RH</code></li> <li>The above produces a list of lists each having <em>two</em> items</li> <li>I flatten the list of lists</li> <li>Just to chop it up into a list of four-item lists</li> <li>Dump that to a <code>df</code></li> <li>Write to an Excel file</li> </ol> <p>Here's the code:</p> <pre class="lang-py prettyprint-override"><code>import itertools import pandas as pd def read_lines(file_object) -&gt; list: return [ parse_line(line) for line in file_object.readlines() if line.strip() ] def parse_line(line: str) -&gt; list: return [ i.split(&quot;:&quot;)[-1].replace(&quot;°C&quot;, &quot;&quot;).replace(&quot;%RH&quot;, &quot;&quot;) for i in line.strip().split() if i.startswith((&quot;T1&quot;, &quot;T2&quot;, &quot;H1&quot;, &quot;H2&quot;)) ] def flatten(parsed_lines: list) -&gt; list: return list(itertools.chain.from_iterable(parsed_lines)) def cut_into_pieces(flattened_lines: list, piece_size: int = 4) -&gt; list: return [ flattened_lines[i:i + piece_size] for i in range(0, len(flattened_lines), piece_size) ] with open(&quot;your_text_data.txt&quot;) as data: df = pd.DataFrame( cut_into_pieces(flatten(read_lines(data))), columns=[&quot;T1&quot;, &quot;H1&quot;, &quot;T2&quot;, &quot;H2&quot;], ) print(df) df.to_excel(&quot;your_table.xlsx&quot;, index=False) </code></pre> <p>This works and I get what I want <em>but</em> I feel like points <code>3, 4, and 5</code> are a bit of redundant work, especially creating a list of list just to flatten it and then chop it up again.</p> <hr /> <h3>Question:</h3> <p><em>How could I simplify the whole parsing process? Or maybe most of the heavy-lifting can be done with <code>pandas</code> alone?</em></p> <p>Also, any other feedback is more than welcomed.</p>
[]
{ "AcceptedAnswerId": "257747", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:43:27.720", "Id": "257729", "Score": "3", "Tags": [ "python", "python-3.x", "parsing", "pandas" ], "Title": "Parsing a text file into a pandas DataFrame" }
257729
accepted_answer
[ { "body": "<p><strong>Disclaimer:</strong> I know this is a very liberal interpretation of a code review since it suggests an entirely different approach. I still thought it might provide a useful perspective when thinking about such problems in the future and reducing coding effort.</p>\n<p>I would suggest the following approach using <a href=\"https://docs.python.org/3/library/re.html\" rel=\"nofollow noreferrer\">regex</a> to extract all the numbers that match the format &quot;12.34&quot;.</p>\n<pre><code>import re\nimport pandas as pd\n\nwith open(&quot;your_text_data.txt&quot;) as data_file:\n data_list = re.findall(r&quot;\\d\\d\\.\\d\\d&quot;, data_file.read())\n\nresult = [data_list[i:i + 4] for i in range(0, len(data_list), 4)]\n\ndf = pd.DataFrame(result, columns=[&quot;T1&quot;, &quot;H1&quot;, &quot;T2&quot;, &quot;H2&quot;])\nprint(df)\ndf.to_excel(&quot;your_table.xlsx&quot;, index=False)\n</code></pre>\n<p>This will of course only work for the current data format you provided. The code will need to be adjusted if the format of your data changes. For example: If relevant numbers may contain a varying number of digits, you might use the regex <code>&quot;\\d+\\.\\d+&quot;</code> to match all numbers that contain at least one digit on either side of the decimal point.</p>\n<p>Also please note the use of the context manager <code>with open(...) as x:</code>. Only code that accesses the object needs to and should be part of the managed context.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T20:36:17.597", "Id": "509112", "Score": "0", "body": "I absolutely don't mind that you've offered a new approach. I totally forgot about regex, I was so much into those lists of lists. This is short, simple, and does the job. Nice! Thank you for your time and insight." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T20:37:48.530", "Id": "509113", "Score": "0", "body": "PS. You've got your imports the other way round. `re` should be first and then `pandas`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T23:01:52.410", "Id": "509120", "Score": "0", "body": "You're right, I fixed the import order!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:47:29.567", "Id": "257747", "ParentId": "257729", "Score": "3" } } ]
<ol> <li>I want to generate a random date of birth [mm/dd/yyyy]which will represent an age equal to less than 18years old</li> <li>My requirement is to dynamically generate test data [date of birth] to negatively test a system which needs a date of birth (age) to be always greater than 18 years old</li> <li>The system which I am trying to test compares the user's input D.O.B. with the current date and calculates the age, if the age is less than 18 years old then throws an error</li> <li>I have tried to create the below python snippet to generate a date of birth [for age less than 18 years old] and kindly need expert opinions to know if this is indeed the correct/best approach?</li> </ol> <pre><code>start_date = date.today() - relativedelta(years=18) end_date = date.today() time_between_dates = end_date - start_date days_between_dates = time_between_dates.days random_number_of_days = random.randrange(days_between_dates) random_date = start_date + datetime.timedelta(days=random_number_of_days) month = random_date.month day = random_date.day year = random_date.year # Once I have the the day, month, year then I can convert it in ISO date format as per my needs </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T09:28:53.830", "Id": "510150", "Score": "0", "body": "Do you really need *random* dates for testing? Usually, good tests focus on the boundary conditions, so you'd want to use dates including exactly 18 years, the same ±1day, and at the other extreme, today and tomorrow. A really good test will allow the \"today\" date to be passed into the code under test, so we can check the right behaviour when the birthday or the present day is 29 February." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T13:43:24.170", "Id": "510168", "Score": "1", "body": "@TobySpeight what you say is true for a generic unit test. For a fuzzer you actually do need random input. It's not clear that the OP appreciates this distinction mind you." } ]
{ "AcceptedAnswerId": "257758", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T21:09:30.250", "Id": "257753", "Score": "0", "Tags": [ "python", "datetime" ], "Title": "Code to generate a random date of birth which will always represent an age less than 18 years from current date" }
257753
accepted_answer
[ { "body": "<p><code>datetime.date</code> has a <code>.replace()</code> method that returns a copy with some values changed. This can be used to get the date 18 years ago.</p>\n<pre><code>end_date = date.today()\nstart_date = end_date.replace(year=end_date.year - 18)\n</code></pre>\n<p><code>datetime.date.toordinal</code> returns an integer corresponding to the date. The ordinals for the start and stop date can be used in <code>random.randint()</code> to pick a random ordinal, which can then be converted back into a date with <code>date.fromordinal()</code>.</p>\n<pre><code>random_date = date.fromordinal(random.randint(start_date.toordinal(), end_date.toordinal()))\n</code></pre>\n<p><code>date.isoformat()</code> returns a date a as YYYY-MM-DD. Or use <code>date.strftime()</code> for more control over the date format. In an f-string, a date is converted to ISO format, or a format string can be used: <code>f&quot;{random_date:%a, %b %d, %Y}&quot;</code> -&gt; <code>'Sat, Dec 14, 2013'</code>.</p>\n<p>If you want to generate a list of dates in the range, use <code>random.sample()</code> with a <code>range</code> object.</p>\n<pre><code>NUMBER_OF_DATES = 10\n\ndate_range = range(start_date.toordinal(), end_date.toordinal())\nrandom_dates = [date.fromordinal(o) for o in random.sample(date_range, NUMBER_OF_DATES)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T01:05:07.060", "Id": "257758", "ParentId": "257753", "Score": "6" } } ]
<p>I have been trying to improve my Python coding and was just wondering if there was a more pythonic way to perform what I have done so far, namely around the date in the <code>main()</code> function.</p> <pre><code>import datetime import sybase account_list = [] def get_date(): # Date -1 day unless Monday then -3 days d = datetime.date.today() if d.weekday() == 0: date = d - datetime.timedelta(days=3) return date else: date = d - datetime.timedelta(days=1) return date def get_unique_accounts(date): conn = sybase.Connection('') c = conn.cursor() c.execute(&quot;SELECT DISTINCT acct from accounts WHERE date = @date&quot;, {&quot;@date&quot;: date}) result = c.fetchall() for row in result: account_list.append(row[0]) c.close() conn.close() def check_balance(date): conn = sybase.Connection('') c = conn.cursor() c.execute(&quot;SELECT TOP 1 name,balance from balance WHERE date = @date&quot;, {&quot;@date&quot;: date}) result = c.fetchone() c.close() conn.close() return result def main(): date = get_date() get_unique_accounts(date) # This will be used for future functions check_balance(date) if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T17:41:05.860", "Id": "510426", "Score": "0", "body": "Sybase, though? Why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T17:43:06.937", "Id": "510428", "Score": "0", "body": "I have no control over the current in place DB solution :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T17:58:57.293", "Id": "510430", "Score": "0", "body": "That's deeply unfortunate. For your own learning purposes, if you have the opportunity I suggest trying out PostgreSQL instead of a museum piece." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T17:59:35.153", "Id": "510431", "Score": "0", "body": "You've tagged this as both Python 2 and 3. What are the constraints? Does the `sybase` package work with 3?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T18:00:35.887", "Id": "510432", "Score": "0", "body": "I will do for sure, as I've used MySQL and variants when I did PHP coding. But as for what I've posted above is there a more 'pythonic' method? Or have I done all I can so far correctly. We have a modified sybase module that we can import for both 2 and 3." } ]
{ "AcceptedAnswerId": "258914", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T17:31:04.640", "Id": "258885", "Score": "2", "Tags": [ "python" ], "Title": "Bank database program" }
258885
accepted_answer
[ { "body": "<p>I will focus on the <code>get_date()</code> method. First of all, what sort of date is it? Currently the name makes me think it will get the current date, but it's sort of a banking date? Something along the lines of <code>get_last_banking_day()</code> would be more descriptive?</p>\n<p>You can move the return to the end of the function as that is the same in both blocks of the if/else:</p>\n<pre><code>def get_last_banking_day(): # Date -1 day unless Monday then -3 days\n d = datetime.date.today()\n\n if d.weekday() == 0:\n date = d - datetime.timedelta(days=3)\n else:\n date = d - datetime.timedelta(days=1)\n \n return date\n</code></pre>\n<p>You could clean up the import and only import the 2 things needed from <code>datetime</code>, <code>date</code> and <code>timedelta</code>.:</p>\n<pre><code>from datetime import date, timedelta\n</code></pre>\n<p>The function would become:</p>\n<pre><code>def get_last_banking_day(): # Date -1 day unless Monday then -3 days\n d = date.today()\n\n if d.weekday() == 0:\n date = d - timedelta(days=3)\n else:\n date = d - timedelta(days=1)\n \n return date\n</code></pre>\n<p>Now we can look at variable names and do some cleanup, especially the <code>d</code> variable. Always try to avoid non-descriptive names:</p>\n<pre><code>def get_last_banking_day(): # Date -1 day unless Monday then -3 days\n today = date.today()\n\n if today.weekday() == 0:\n last_banking_day = today - timedelta(days=3)\n else:\n last_banking_day = today - timedelta(days=1)\n \n return last_banking_day\n</code></pre>\n<p>As the <code>today - timedelta(days=1)</code> is the default we use it as such and set the value to this and only use an if-statement to set the exception:</p>\n<pre><code>def get_last_banking_day(): # Date -1 day unless Monday then -3 days\n today = date.today()\n last_banking_day = today - timedelta(days=1)\n\n if today.weekday() == 0:\n last_banking_day = today - timedelta(days=3)\n\n return last_banking_day\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T06:32:15.620", "Id": "510604", "Score": "0", "body": "AH thanks Korfoo, the if loop where there is already a default is mistake I need to remove from my mindset when coding. Although just for reference you still have 'return date' rather than 'return 'last_banking_day'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T07:03:24.747", "Id": "510608", "Score": "0", "body": "Oops, I edited it to correct the return. Do note that I only looked at the `get_date` method as I do not have experience with `sybase` so I can not give tips about that :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T08:12:35.860", "Id": "510616", "Score": "0", "body": "Appreciate it, I do not think there are improvements that could be made elsewhere in what has been posted." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T09:14:18.397", "Id": "258914", "ParentId": "258885", "Score": "2" } } ]
<p>Here is the problem.</p> <p><em>Repeatedly ask the user to enter game scores in a format like team1 score1 - team2 score2. Store this information in a dictionary where the keys are the team names and the values are tuples of the form (wins, losses).</em></p> <p>Here is my Solution, what can I change for the better in it?</p> <pre><code>number_of_games = int(input(&quot;Enter the total number of Games: &quot;)) team_wins_and_loses = {} for _ in range(number_of_games): team1, score1, __, team2, score2 = input(&quot;Enter the game results(Note that the name of the team must be a single word, without spaces):&quot;).split() team1_result, team2_result = ((1, 0), (0, 1)) if int(score1) &gt; int(score2) else ((0, 1), (1, 0)) if team1 not in team_wins_and_loses: team_wins_and_loses[team1] = team1_result else: updated_result = (team_wins_and_loses[team1][0] + team1_result[0], team_wins_and_loses[team1][1] + team1_result[1]) team_wins_and_loses[team1] = updated_result if team2 not in team_wins_and_loses: team_wins_and_loses[team2] = team2_result else: updated_result = (team_wins_and_loses[team2][0] + team2_result[0], team_wins_and_loses[team2][1] + team2_result[1]) team_wins_and_loses[team2] = updated_result print(team_wins_and_loses) </code></pre>
[]
{ "AcceptedAnswerId": "258939", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T17:02:04.417", "Id": "258926", "Score": "5", "Tags": [ "python" ], "Title": "Count wins and losses for each team in a league" }
258926
accepted_answer
[ { "body": "<ol>\n<li><p>Please always use 4 spaces to indent when using Python.</p>\n</li>\n<li><p>Rather than the verbose name <code>team_wins_and_loses</code> we could use <code>team_results</code>.</p>\n</li>\n<li><p>Rather than adding both values of the tuple we should focus on adding 1 win to the winning team, and 1 lose to the losing team.</p>\n<pre class=\"lang-py prettyprint-override\"><code>winner[0] += 1\nloser[1] += 1\n</code></pre>\n</li>\n<li><p>We can change your turnery to pick the wining or losing team, and then extract the value with the correct default.</p>\n<pre class=\"lang-py prettyprint-override\"><code>winning_team, losing_team = (\n (team1, team2)\n if int(score1) &gt; int(score2) else\n (team2, team1)\n)\nif winning_team not in team_results:\n winner = team_results[winning_team] = [0, 0]\nelse:\n winner = team_results[winning_team]\n# same for losing team\n</code></pre>\n</li>\n<li><p>We can use <code>dict.setdefault</code> to remove the need for the if.</p>\n<pre class=\"lang-py prettyprint-override\"><code>winner = team_results.setdefault(winning_team, [0, 0])\n</code></pre>\n</li>\n<li><p>We can use <code>collections.defaultdict</code> to make interacting with <code>team_results</code> much cleaner, rather than using <code>dict.setdefault</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def default_scores():\n return [0, 0]\n\nteam_results = collections.defaultdict(default_scores)\n# ...\nteam_results[winning_team][0] += 1\n</code></pre>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n\n\ndef default_scores():\n return [0, 0]\n\n\nteam_results = collections.defaultdict(default_scores)\nnumber_of_games = int(input(&quot;Enter the total number of Games: &quot;))\nfor _ in range(number_of_games):\n team1, score1, __, team2, score2 = input(&quot;Enter the game results(Note that the name of the team must be a single word, without spaces):&quot;).split()\n winner, loser = (\n (team1, team2)\n if int(score1) &gt; int(score2) else\n (team2, team1)\n )\n team_results[winner][0] += 1\n team_results[loser][1] += 1\n print(team_results)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T20:35:26.313", "Id": "258939", "ParentId": "258926", "Score": "4" } } ]
<p>My code currently doesn't insert data into MySQL fast enough. However I don't know how to measure the current speed.</p> <pre><code>def insert(): mycursor = mydb.cursor() plik = input(&quot;:::&quot;) agefile = open(&quot;C:/Users/juczi/Desktop/New Folder/&quot; + plik, &quot;r&quot;) sql = &quot;INSERT INTO wyciek (nick, ip) VALUES (%s, %s)&quot; for row in agefile: mydb.commit() data = row.split(':') val = (data[0].replace(&quot;\n&quot;,&quot;&quot;), data[1].replace(&quot;\n&quot;, &quot;&quot;)) mycursor.execute(sql, val) agefile.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T17:14:45.623", "Id": "510526", "Score": "0", "body": "\"I was wondering if there is any faster way ...\" why? Is your code currently not fast enough, or do you just want speed for speed's sake?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T17:17:39.347", "Id": "510527", "Score": "0", "body": "The code is not fast enough, i need it to be faster." } ]
{ "AcceptedAnswerId": "258937", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T17:05:43.370", "Id": "258927", "Score": "1", "Tags": [ "python", "mysql", "time-limit-exceeded" ], "Title": "Inserting data into MySQL" }
258927
accepted_answer
[ { "body": "<p>If you are trying to insert data in bulk to Mysql the best would be to use <a href=\"https://dev.mysql.com/doc/refman/8.0/en/load-data.html\" rel=\"nofollow noreferrer\">LOAD DATA</a> instead of doing it in a loop on top of an interpreted language, which is inevitably slower. However there is less flexibility if you need to transform data but that shouldn't be a problem in your case. All you're doing is get rid of carriage return. This is a plain delimited file without heavy transformation.</p>\n<p>The <code>mydb.commit()</code> is misplaced. It should be called <em>after</em> running an insert/update. On the first iteration there is nothing to be committed.\nBut this is not efficient. I suggest that you take full advantage of <strong>transactions</strong>. Start a transaction at the beginning, do your loop and commit at the end. In case of error, you roll back. The added benefit is <strong>data integrity</strong>. If an error occurs, the data already inserted is &quot;undone&quot; so you don't end up with garbage due to a partial import of data.</p>\n<p>Schema:</p>\n<pre><code>try:\n conn.autocommit = False\n\n # insert loop..\n\n # Commit your changes\n conn.commit()\n\nexcept mysql.connector.Error as error:\n print(&quot;Failed to update record to database rollback: {}&quot;.format(error))\n # reverting changes because of exception\n conn.rollback()\n</code></pre>\n<p>See for example: <a href=\"https://pynative.com/python-mysql-transaction-management-using-commit-rollback/\" rel=\"nofollow noreferrer\">Use Commit and Rollback to Manage MySQL Transactions in Python</a></p>\n<p>This alone should improve performance but you have to test it to measure the gain.</p>\n<p>Not performance-related, but you can also use a <strong>context manager</strong> whenever possible, for instance when opening/writing to a file. So:</p>\n<pre><code>agefile = open(&quot;C:/Users/juczi/Desktop/New Folder/&quot; + plik, &quot;r&quot;)\n</code></pre>\n<p>becomes:</p>\n<pre><code>with open(&quot;C:/Users/juczi/Desktop/New Folder/&quot; + plik, &quot;r&quot;) as agefile:\n # do something\n</code></pre>\n<p>and you don't have to bother closing the file, this is done automatically.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T19:08:45.700", "Id": "258937", "ParentId": "258927", "Score": "1" } } ]
<p>I would like to get some feed back on my code; the goal is to get all agencies address of banks. I wrote a pretty simple brute force algorithm. I was wondering if you would have any advice to improve the code, design it differently (do I need an OOP approach here) etc .</p> <pre><code>import requests from lxml import html groupe = &quot;credit-agricole&quot; dep = '21' groupes =[&quot;credit-agricole&quot;] deps = ['53', '44', '56', '35', '22', '49', '72', '29', '85'] def get_nb_pages(groupe,dep): &quot;&quot;&quot; Return nb_pages ([int]): number of pages containing banks information . Args: groupe ([string]): bank groupe (&quot;credit-agricole&quot;,...) dep ([string]): departement (&quot;01&quot;,...) &quot;&quot;&quot; url =&quot;https://www.moneyvox.fr/pratique/agences/{groupe}/{dep}&quot;.format(groupe=groupe,dep=dep) req = requests.get(url) raw_html = req.text xpath = &quot;/html/body/div[2]/article/div/div/div[3]/div[2]/nav/a&quot; tree = html.fromstring(raw_html) nb_pages = len(tree.xpath(xpath)) +1 return nb_pages def get_agencies(groupe,dep,page_num): &quot;&quot;&quot; Return agencies ([List]): description of agencies scrapped on website target page. Args: groupe ([string]): bank groupe (&quot;credit-agricole&quot;,...) dep ([string]): departement (&quot;01&quot;,...) page_num ([int]): target page &quot;&quot;&quot; url =&quot;https://www.moneyvox.fr/pratique/agences/{groupe}/{dep}/{page_num}&quot;.format(groupe=groupe,dep=dep,page_num=page_num) req = requests.get(url) raw_html = req.text xpath = '//div[@class=&quot;lh-bloc-agence like-text&quot;]' tree = html.fromstring(raw_html) blocs_agencies = tree.xpath(xpath) agencies = [] for bloc in blocs_agencies: agence = bloc.xpath(&quot;div/div[1]/h4&quot;)[0].text rue = bloc.xpath(&quot;div/div[1]/p[1]&quot;)[0].text code_postale = bloc.xpath(&quot;div/div[1]/p[2]&quot;)[0].text agencies.append((agence,rue,code_postale)) return agencies def get_all(groupes,deps): &quot;&quot;&quot;Return all_agencies ([List]): description of agencies scrapped. Args: groupes ([List]): target groups deps ([List]): target departments &quot;&quot;&quot; all_agencies = [] for groupe in groupes: for dep in deps: nb_pages = get_nb_pages(groupe,dep) for p in range(1,nb_pages+1): agencies = get_agencies(groupe,dep,p) all_agencies.extend(agencies) df_agencies = pd.DataFrame(all_agencies,columns=['agence','rue','code_postale']) return df_agencies get_nb_pages(groupe,dep) get_agencies(groupe,dep,1) df_agencies = get_all(groupes,deps) <span class="math-container">```</span> </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T09:11:57.237", "Id": "258961", "Score": "2", "Tags": [ "python", "design-patterns", "web-scraping" ], "Title": "Web scraping and design pattern lifting" }
258961
max_votes
[ { "body": "<p>To emphasize what Reinderien already said, always check the return of your calls to requests. <code>status_code</code> should return 200. If you get anything else you should stop and investigate. It is possible that the website is blocking you and there is no point running blind.</p>\n<p>Also, I recommend that you <strong>spoof the user agent</strong>, otherwise it is obvious to the web server that you are running a <strong>bot</strong> and they may block you, or apply more stringent rate limiting measures than a casual user would experience. By default the user agent would be something like this: python-requests/2.25.1.</p>\n<p>And since you are making repeated calls, you should use a <a href=\"https://docs.python-requests.org/en/master/user/advanced/\" rel=\"nofollow noreferrer\">session</a> instead. Reinderien already refactored your code with session but did not mention this point explicitly. The benefits are persistence (when using cookies for instance) and also more efficient connection pooling at TCP level. And you can use session to set default headers for all your requests.</p>\n<p>Example:</p>\n<pre><code>&gt;&gt;&gt; session = requests.session()\n&gt;&gt;&gt; session.headers\n{'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}\n&gt;&gt;&gt; \n</code></pre>\n<p>Change the user agent for the session, here we spoof Firefox:</p>\n<pre><code>session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0'})\n</code></pre>\n<p>And then you can use session.get to retrieve pages.</p>\n<p>May you could be interested in <strong>prepared queries</strong> too. I strongly recommend that Python developers get acquainted with that section of the documentation.</p>\n<p>To speed up the process you could also add parallel processing, for example using threads. But be gentle, if you have too many open connections at the same time, it is one thing that can get you blocked. Usage patterns have to remain reasonable and human-like.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T21:15:22.143", "Id": "259028", "ParentId": "258961", "Score": "1" } } ]
<p>In my real case I have a set of time series related to different IDs stored in a single <code>DataFrame</code> Some are composed by 400 samples, some by 1000 samples, some by 2000. They are stored in the same df and:</p> <p><em><strong>I would like to drop all the IDs made up of time series shorter than a custom length.</strong></em></p> <p>I wrote the following code, but I think is very ugly and inefficient.</p> <pre><code>import pandas as pd import numpy as np dict={&quot;samples&quot;:[1,2,3,4,5,6,7,8,9],&quot;id&quot;:[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;]} df=pd.DataFrame(dict) df_id=pd.DataFrame() for i in set(df.id): df_filtered=df[df.id==i] len_id=len(df_filtered.samples) if len_id&gt;3: #3 is just a random choice for this example df_id=df_id.append(df_filtered) print(df_id) </code></pre> <p>Output:</p> <pre><code> samples id 2 3 c 6 7 c 7 8 c 8 9 c 1 2 b 3 4 b 4 5 b 5 6 b </code></pre> <p>How to improve it in a more Pythonic way? Thanks</p>
[]
{ "AcceptedAnswerId": "258995", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T16:25:45.057", "Id": "258969", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Pandas Filtering based on the length of the same kind variables in a column" }
258969
accepted_answer
[ { "body": "<p>Good answer by Juho. Another option is a <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.filter.html\" rel=\"nofollow noreferrer\"><strong><code>groupby-filter</code></strong></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df.groupby('id').filter(lambda group: len(group) &gt; 3)\n\n# samples id\n# 1 2 b\n# 2 3 c\n# 3 4 b\n# 4 5 b\n# 5 6 b\n# 6 7 c\n# 7 8 c\n# 8 9 c\n</code></pre>\n<p>To match your output order exactly, add a descending <code>id</code> sort: <code>.sort_values('id', ascending=False)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T06:19:32.027", "Id": "510718", "Score": "1", "body": "This is neat as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T02:52:05.053", "Id": "258995", "ParentId": "258969", "Score": "3" } } ]
<p>In my real case I have a set of time series related to different IDs stored in a single <code>DataFrame</code> Some are composed by 400 samples, some by 1000 samples, some by 2000. They are stored in the same df and:</p> <p><em><strong>I would like to drop all the IDs made up of time series shorter than a custom length.</strong></em></p> <p>I wrote the following code, but I think is very ugly and inefficient.</p> <pre><code>import pandas as pd import numpy as np dict={&quot;samples&quot;:[1,2,3,4,5,6,7,8,9],&quot;id&quot;:[&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;]} df=pd.DataFrame(dict) df_id=pd.DataFrame() for i in set(df.id): df_filtered=df[df.id==i] len_id=len(df_filtered.samples) if len_id&gt;3: #3 is just a random choice for this example df_id=df_id.append(df_filtered) print(df_id) </code></pre> <p>Output:</p> <pre><code> samples id 2 3 c 6 7 c 7 8 c 8 9 c 1 2 b 3 4 b 4 5 b 5 6 b </code></pre> <p>How to improve it in a more Pythonic way? Thanks</p>
[]
{ "AcceptedAnswerId": "258995", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T16:25:45.057", "Id": "258969", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Pandas Filtering based on the length of the same kind variables in a column" }
258969
accepted_answer
[ { "body": "<p>Good answer by Juho. Another option is a <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.filter.html\" rel=\"nofollow noreferrer\"><strong><code>groupby-filter</code></strong></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df.groupby('id').filter(lambda group: len(group) &gt; 3)\n\n# samples id\n# 1 2 b\n# 2 3 c\n# 3 4 b\n# 4 5 b\n# 5 6 b\n# 6 7 c\n# 7 8 c\n# 8 9 c\n</code></pre>\n<p>To match your output order exactly, add a descending <code>id</code> sort: <code>.sort_values('id', ascending=False)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T06:19:32.027", "Id": "510718", "Score": "1", "body": "This is neat as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T02:52:05.053", "Id": "258995", "ParentId": "258969", "Score": "3" } } ]
<p>How could i improve the following code. This part was easy to implement but there is a lot of redondancy and i use pandas to return as dict which seems quite odd.</p> <pre><code>def pipeline_place_details(place_id, fields, lang): &quot;&quot;&quot;Return a dataframe with useful information Args: place_id ([string]): Id retrieved from google api fields ([type]): Field retrieved from json output &quot;&quot;&quot; fields = ['name', 'formatted_address', 'international_phone_number', 'website', 'rating', 'review'] lang = 'fr' # details will give us a dict which is the result of serialized json returned from google api details = get_place_details(place_id, fields, &quot;fr&quot;) try: website = details['result']['website'] except KeyError: website = &quot;&quot; try: address = details['result']['formatted_address'] except KeyError: address = &quot;&quot; try: phone_number = details['result']['international_phone_number'] except KeyError: phone_number = &quot;&quot; try: reviews = details['result']['reviews'] except KeyError: reviews = [] rev_temp = [] for review in reviews: author_name = review['author_name'] user_rating = review['rating'] text = review['text'] time = review['relative_time_description'] rev_temp.append((author_name, user_rating, text, time)) rev_temp_2 = pd.DataFrame(rev_temp, columns = ['author_name', 'rating', 'text', 'relative_time']) rev_temp_2['place_id'] = i rev_temp_2['address'] = address rev_temp_2['phone_number'] = phone_number rev_temp_2['website'] = website review_desc = review_desc.append(rev_temp_2, ignore_index = True) return review_desc.to_dict('records') <span class="math-container">```</span> </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T18:19:23.890", "Id": "259021", "Score": "0", "Tags": [ "python" ], "Title": "Return target informations from nested api json output" }
259021
max_votes
[ { "body": "<p><strong>1. Getting data from dict</strong></p>\n<p>When <code>details</code> is a <code>dict</code>, then instead of writing:</p>\n<pre><code>try:\n address = details['result']['formatted_address']\nexcept KeyError:\n address = &quot;&quot;\n</code></pre>\n<p>you can do:</p>\n<pre><code>address = details.get('result', {}).get('formatted_address', '')\n</code></pre>\n<p>Second parameter of <code>.get</code> represents the default value which is returned when a dictionary doesn't contain a specific element</p>\n<p><strong>2. Modularization</strong></p>\n<p>Function <code>pipeline_place_details</code> is not short, so it might be a good idea to break it up into a smaller functions. Each time when you write a loop, it's worth to consider if moving body of the loop to a separate function will increase the code readability.</p>\n<p>For example that part:</p>\n<pre><code> author_name = review['author_name']\n user_rating = review['rating']\n text = review['text']\n time = review['relative_time_description']\n rev_temp.append((author_name, user_rating, text, time))\n</code></pre>\n<p>can be easiliy extracted to the new function:</p>\n<pre><code>def process_review(review):\n return (\n review['author_name'],\n review['rating'],\n review['text'],\n review['relative_time_description']\n )\n</code></pre>\n<p>and you can use it as below:</p>\n<pre><code>rev_temp = [process_review(review) for review in reviews]\n</code></pre>\n<p><strong>3. Variables naming</strong></p>\n<p>Good code should be not only working and efficient but it should be also easy to read and understand. So it's a good rule to use really meaningful variable names. I belive that you can find better names than for example <code>rev_temp</code> or <code>rev_temp2</code>. ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T18:48:48.137", "Id": "259023", "ParentId": "259021", "Score": "1" } } ]
<p>I am processing an unknown &quot;length&quot; of generator object. I have to keep things &quot;lazy&quot; because of memory management. The processing is compute heavy, so writing it multiproc style is the solution (or at least it seems for me).</p> <p>I have solved this problem of multiproc on generator object with a combination of monkey patch and a bounded Queue.</p> <p>What really itches me is the monkey patch... Do you think this is fine to apply <code>imap()</code> on a generator object? How would you do this?</p> <p>I would like to underline that the focus is to <strong>compute the outputs of a generator in parallel.</strong> From the perspective of this &quot;minimal example&quot; :</p> <pre><code>process_line, process_line_init, process_first_n_line </code></pre> <p>are the functions I am most interested about your opinion.</p> <pre><code>import multiprocessing as mp import psutil import queue from typing import Any, Dict, Iterable, Set def yield_n_line(n: int)-&gt; Iterable[Dict[str, str]]: for i in range(n): yield {'body': &quot;Never try to 'put' without a timeout sec declared&quot;} def get_unique_words(x: Dict[str, str])-&gt; Set[str]: return set(x['body'].split()) def process_line(x:Dict[str, str])-&gt; Set[str]: try: process_line.q.put(x, block=True, timeout=2) except queue.Full: pass return get_unique_words(x) def process_line_init(q: mp.Queue)-&gt; None: process_line.q = q def process_first_n_line(number_of_lines: int)-&gt; Any: n_line = yield_n_line(number_of_lines) if psutil.cpu_count(logical=False) &gt; 4: cpu_count = psutil.cpu_count(logical=False)-2 else: cpu_count = psutil.cpu_count(logical=False) q = mp.Queue(maxsize=8000) p = mp.Pool(cpu_count, process_line_init, [q]) results = p.imap(process_line, n_line) for _ in range(number_of_lines): try: q.get(timeout=2) except queue.Empty: q.close() q.join_thread() yield results.next() p.close() p.terminate() p.join() pass def yield_uniqueword_chunks( n_line: int = 10_000_000, chunksize: int = 1_787_000)-&gt; Iterable[Set[str]]: chunk = set() for result in process_first_n_line(n_line): chunk.update(result) if len(chunk) &gt; chunksize: yield chunk chunk = set() yield chunk def main()-&gt; None: for chunk in yield_uniqueword_chunks( n_line=1000, #Number of total comments to process chunksize=200 #number of unique words in a chunk (around 32MB) ): print(chunk) #export(chunk) if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T01:41:31.093", "Id": "510803", "Score": "0", "body": "The idea behind `multiprocessing.Pool` is that it handles queuing work for the processes. If you want more control, then use Process and Queue." } ]
{ "AcceptedAnswerId": "259034", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T21:18:35.857", "Id": "259029", "Score": "6", "Tags": [ "python", "queue", "generator", "multiprocessing" ], "Title": "Compute the outputs of a generator in parallel" }
259029
accepted_answer
[ { "body": "<p>Here's a condensed illustration of how to achieve your stated purpose, namely\nto <strong>compute the outputs of a generator in parallel</strong>. I offer it because\nI could not understand the purpose of most of the complexity in your current\ncode. I suspect there are issues that you have not explained to us or that I\nfailed to infer (if so, this answer might be off the mark). In any case,\nsometimes it helps to look at a problem in a simplified form to see\nwhether your actual use case might work just fine within those parameters.</p>\n<pre><code>import multiprocessing as mp\n\ndef main():\n for chunk in process_data(1000, 50):\n print()\n print(len(chunk), chunk)\n \ndef process_data(n, chunksize):\n # Set up the Pool using a context manager.\n # This relieves you of the hassle of join/close.\n with mp.Pool() as p:\n s = set()\n # Just iterate over the results as they come in.\n # No need to check for empty queues, etc.\n for res in p.imap(worker, source_gen(n)):\n s.update(res)\n if len(s) &gt;= chunksize:\n yield s\n s = set()\n\ndef source_gen(n):\n # A data source that will yield N values.\n # To get the data in this example:\n # curl 'https://www.gutenberg.org/files/2600/2600-0.txt' -o war-peace.txt\n with open('war-peace.txt') as fh:\n for i, line in enumerate(fh):\n yield line\n if i &gt;= n:\n break\n\ndef worker(line):\n # A single-argument worker function.\n # If you need multiple args, bundle them in tuple/dict/etc.\n return [word.lower() for word in line.split()]\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>This example illustrates a garden-variety type of parallelization:</p>\n<ul>\n<li><p>The data source is running in a single process (the parent).</p>\n</li>\n<li><p>Downstream computation is\nrunning in multiple child processes.</p>\n</li>\n<li><p>And final aggregation/reporting\nis running in a single process (also the parent).</p>\n</li>\n</ul>\n<p>Behind the scenes, <code>Pool.imap()</code> is\nusing pickling and queues to shuttle data between processes. If your real\nuse case requires parallelizing data generation and/or reporting,\na different approach is needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T01:00:13.987", "Id": "510802", "Score": "1", "body": "Thank you, for the fast response, I have checked out your example, and on its own it is working and deserves an up. In a day, I will be able to check / implement it on my specific use case and see, where have I overcomplicated this problem. 'for res in p.imap(worker, source_gen(n))' pattern somehow always errored out for me that is why I went with my solution. Thank you, and will come back bit later!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T11:09:22.500", "Id": "510823", "Score": "0", "body": "Works like a charm, \nEarlier I have used the 'With' pattern for pool, hut just for list.\nI have over-complicated this task." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T00:01:22.887", "Id": "259034", "ParentId": "259029", "Score": "6" } } ]
<p>I'm trying to get a list of unique colors (rgba values) in an image. Here are my attempts:</p> <pre><code># 1 - too ugly and clunky all_colors = [] for i in range(width): for j in range(height): color = pix[i, j] if color not in all_colors: all_colors.append(color) </code></pre> <p>OR</p> <pre><code># 2 - not memory-efficient, as it adds the whole list into memory all_colors = list(set([pix[i, j] for i in range(width) for j in range(height)])) </code></pre> <p>Edit: here is the setup:</p> <pre><code>from PIL import Image img = Image.open(&quot;../Camouflage.png&quot;) pix = img.load() </code></pre> <p>Thank you very much.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T02:51:45.983", "Id": "510806", "Score": "1", "body": "`as it adds the whole list into memory` both options do that. Or you mean something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T09:18:38.183", "Id": "510817", "Score": "0", "body": "@Marc Looks like they mean \"the whole list of all pixels\", not just the list of *different* colors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T09:23:48.137", "Id": "510819", "Score": "0", "body": "Quite possibly there's a way without looping yourself, but we can't tell because you're keeping it secret what `pix` is and not giving us a chance to test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T17:19:38.123", "Id": "510845", "Score": "0", "body": "@Manuel, just updated to show what `pix` is. Thank you for your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T20:07:48.647", "Id": "510856", "Score": "0", "body": "Are any of the downvoters going to bother explaining what's wrong with my question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T20:27:45.533", "Id": "510857", "Score": "2", "body": "The downvotes from before your latest edits were probably because the code was incomplete, lacking context. On Code Review, we require more than just snippets. Feel free to refer to [Simon's guide on asking questions](https://codereview.meta.stackexchange.com/a/6429/52915)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T21:17:08.440", "Id": "510862", "Score": "0", "body": "Why do you want the code to be more memory efficient?" } ]
{ "AcceptedAnswerId": "259071", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T01:33:43.487", "Id": "259036", "Score": "-3", "Tags": [ "python" ], "Title": "memory-efficient & clean set() in python" }
259036
accepted_answer
[ { "body": "<p>How about simply this?</p>\n<pre><code>all_colors = set(img.getdata())\n</code></pre>\n<p>Or let Pillow do the hard work:</p>\n<pre><code>all_colors = [color for _, color in img.getcolors()]\n</code></pre>\n<p>Benchmark results along with the set comprehension solution on a test image of mine (since you didn't provide any):</p>\n<pre><code>113 ms set_comp\n 68 ms set_getdata\n 1 ms getcolors\n\n115 ms set_comp\n 65 ms set_getdata\n 1 ms getcolors\n\n106 ms set_comp\n 62 ms set_getdata\n 1 ms getcolors\n</code></pre>\n<p>With <a href=\"https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.getdata\" rel=\"nofollow noreferrer\"><code>img.getdata()</code></a> you get a &quot;sequence-like object&quot; that seems light-weight:</p>\n<pre><code>&gt;&gt;&gt; img.getdata()\n&lt;ImagingCore object at 0x7f0ebd0f1e50&gt;\n\n&gt;&gt;&gt; import sys\n&gt;&gt;&gt; sys.getsizeof(img.getdata())\n32\n</code></pre>\n<p>Benchmark code:</p>\n<pre><code>from timeit import repeat\nfrom PIL import Image\n\ndef set_comp(img):\n pix = img.load()\n width, height = img.size\n return {pix[i,j] for i in range(width) for j in range(height)}\n\ndef set_getdata(img):\n return set(img.getdata())\n\ndef getcolors(img):\n return [color for _, color in img.getcolors()]\n\nfuncs = set_comp, set_getdata, getcolors\n\ndef main():\n img = Image.open(&quot;test.png&quot;)\n for _ in range(3):\n for func in funcs:\n t = min(repeat(lambda: func(img), number=1))\n print('%3d ms ' % (t * 1e3), func.__name__)\n print()\n\nmain()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-04T19:32:57.193", "Id": "510914", "Score": "0", "body": "hmmm I think part of its speed comes from the fact that you don't need to `img.load()` the whole image. but, I'll need to do that eventually to iterate over the pixels and change them if they're not black." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-04T19:55:32.733", "Id": "510916", "Score": "0", "body": "@tommy2111111111 Have a look at `getdata`'s source code (it's linked to in the documentation), the first thing it does is `self.load()`. Also, see my update, new solution using `getcolors`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-04T21:30:32.000", "Id": "510918", "Score": "0", "body": "thank you, `getcolors` works great. would it still be the best/fastest solution if I still needed to iterate over all the pixels anyways like this? https://pastebin.com/UnAR6kzv" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-04T21:40:49.203", "Id": "510919", "Score": "0", "body": "@tommy2111111111 I don't see what getting the colors has to do with that. Anyway, for efficient manipulation there might be other Pillow methods or you could use NumPy on the image data." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-04T08:29:19.970", "Id": "259071", "ParentId": "259036", "Score": "5" } } ]
<p>A common preprocessing in machine learning consists in replacing rare values in the data by a label stating &quot;rare&quot;. So that subsequent learning algorithms will not try to generalize a value with few occurences.</p> <p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html" rel="nofollow noreferrer">Pipelines</a> enable to describe a sequence of preprocessing and learning algorithms to end up with a single object that takes raw data, treats it, and output a prediction. <a href="https://scikit-learn.org/stable/" rel="nofollow noreferrer">scikit-learn</a> expects the steps to have a specific syntax (fit / transform or fit / predict). I wrote the following class to take care of this task so that it can be run inside a pipeline. (More details about the motivation can be found here: <a href="https://www.thekerneltrip.com/python/pandas-replace-rarely-occuring-values-pipeline/" rel="nofollow noreferrer">pandas replace rare values</a>)</p> <p>Is there a way to improve this code in term of performance or reusability ?</p> <pre><code>class RemoveScarceValuesFeatureEngineer: def __init__(self, min_occurences): self._min_occurences = min_occurences self._column_value_counts = {} def fit(self, X, y): for column in X.columns: self._column_value_counts[column] = X[column].value_counts() return self def transform(self, X): for column in X.columns: X.loc[self._column_value_counts[column][X[column]].values &lt; self._min_occurences, column] = &quot;RARE_VALUE&quot; return X def fit_transform(self, X, y): self.fit(X, y) return self.transform(X) </code></pre> <p>And the following can be appended to the above class to make sure the methods work as expected:</p> <pre><code>if __name__ == &quot;__main__&quot;: import pandas as pd sample_train = pd.DataFrame( [{&quot;a&quot;: 1, &quot;s&quot;: &quot;a&quot;}, {&quot;a&quot;: 1, &quot;s&quot;: &quot;a&quot;}, {&quot;a&quot;: 1, &quot;s&quot;: &quot;b&quot;}]) rssfe = RemoveScarceValuesFeatureEngineer(2) print(sample_train) print(rssfe.fit_transform(sample_train, None)) print(20*&quot;=&quot;) sample_test = pd.DataFrame([{&quot;a&quot;: 1, &quot;s&quot;: &quot;a&quot;}, {&quot;a&quot;: 1, &quot;s&quot;: &quot;b&quot;}]) print(sample_test) print(rssfe.transform(sample_test)) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-04T08:30:16.143", "Id": "259072", "Score": "3", "Tags": [ "python", "pandas", "machine-learning" ], "Title": "Pandas replace rare values in a pipeline" }
259072
max_votes
[ { "body": "<ul>\n<li><p>You could use scikit-learn's <a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.base.TransformerMixin.html\" rel=\"nofollow noreferrer\"><code>TransformerMixin</code></a> which provides an implementation of <code>fit_transform</code> for you (its implementation is available <a href=\"https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/base.py#L683\" rel=\"nofollow noreferrer\">here</a> for interest).</p>\n</li>\n<li><p>I'd consider renaming <code>RemoveScarceValuesFeatureEngineer</code> to something that fits a bit more with other classes in scikit-learn. How about <code>RareValueTransformer</code> instead?</p>\n</li>\n<li><p>What do you want to happen if an unseen value is transformed? Take, for example</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>sample_test = pd.DataFrame([{&quot;a&quot;: 1, &quot;s&quot;: &quot;a&quot;}, {&quot;a&quot;: 2, &quot;s&quot;: &quot;b&quot;}])\nprint(sample_test)\nprint(rssfe.transform(sample_test))\n</code></pre>\n<p>This raises a <code>KeyError</code>, which isn't what I expected. I'd either rework your code to ignore unseen values, or return a nicer error if this is what you want to happen. To me, ignoring seems more reasonable, but it's up to you! Making some unit tests would give you more confidence in cases like this, too.</p>\n<p>A pedantic aside: you have a typo of 'occurrence' in <code>min_occurences</code>, which is easily amended.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-04T15:57:13.697", "Id": "259090", "ParentId": "259072", "Score": "4" } } ]
<p>I've created a little GUI where the text entered in the text-fields is stored in a property of the currently selected button. If a different button is clicked, the contents stored for that button are inserted into the text-fields.</p> <p>For storing the information I'm currently using a class where each text-field's contents represent a separate attribute:</p> <pre><code>from PyQt5.QtWidgets import * class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) v_layout = QVBoxLayout() cent_widget = QWidget() cent_widget.setLayout(v_layout) self.setCentralWidget(cent_widget) # Buttons h_layout = QHBoxLayout() v_layout.addLayout(h_layout) self.btn_group = QButtonGroup() self.btn_group.setExclusive(True) btn_1 = QPushButton('Button 1') btn_2 = QPushButton('Button 2') btn_3 = QPushButton('Button 3') for w in [btn_1, btn_2, btn_3]: w.setProperty('data', Storage()) w.setCheckable(True) w.clicked.connect(self.set_data) self.btn_group.addButton(w) h_layout.addWidget(w) btn_1.setChecked(True) # Text Fields self.tf_1 = QLineEdit() self.tf_2 = QSpinBox() self.tf_3 = QLineEdit() for w in [self.tf_1, self.tf_2, self.tf_3]: w.editingFinished.connect(lambda x=w: self.update_storage(x)) v_layout.addWidget(w) def update_storage(self, widget): active_storage = self.btn_group.checkedButton().property('data') if widget == self.tf_1: active_storage.field1 = self.tf_1.text() elif widget == self.tf_2: active_storage.field2 = self.tf_2.value() elif widget == self.tf_3: active_storage.field3 = self.tf_3.text() def set_data(self): btn = self.btn_group.checkedButton() storage = btn.property('data') self.tf_1.setText(storage.field1) self.tf_2.setValue(storage.field2) self.tf_3.setText(storage.field3) class Storage: def __init__(self): self.field1 = '' self.field2 = -1 self.field3 = '' if __name__ == '__main__': app = QApplication([]) window = MainWindow() window.show() app.exec() </code></pre> <p><a href="https://i.stack.imgur.com/C56hL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C56hL.png" alt="GUI with 3 buttons at the top and 2 QLineEdits and a QSpinbox below" /></a></p> <p>I have a feeling like I'm working <em>against</em> Qt here or I'm at least not using its full potential, because I think Qt <em>could</em> include some tools to make this more efficient and I just did not find them.</p>
[]
{ "AcceptedAnswerId": "259162", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-06T09:55:57.540", "Id": "259149", "Score": "3", "Tags": [ "python", "pyqt" ], "Title": "Storing the contents of text fields and inserting the stored values on button-click" }
259149
accepted_answer
[ { "body": "<p>Your implementation of <code>Storage</code> lends itself nicely to using a <code>dataclass</code>.</p>\n<pre><code>from dataclasses import dataclass\n\n@dataclass\nclass Storage:\n field1: str = &quot;&quot;\n field2: int = -1\n field3: str = &quot;&quot;\n</code></pre>\n<p>This makes your class definition really concise and readable and provides improved scalability and convenient implementations of built-in functions if you ever need them.</p>\n<p>You should also consider giving fields and widgets more meaningful names (maybe even changing button text to match their functionality) to improve readability and usability.</p>\n<p>Further material on dataclasses:</p>\n<ul>\n<li><a href=\"https://realpython.com/python-data-classes/\" rel=\"nofollow noreferrer\">Data Classes in Python 3.7+ (Guide)</a> on RealPython</li>\n<li><a href=\"https://www.youtube.com/watch?v=vBH6GRJ1REM\" rel=\"nofollow noreferrer\">Python dataclasses</a> on Youtube by mCoding</li>\n</ul>\n<hr />\n<p>The way you create the three buttons does not scale well, changing this part will have to be done by hand and is therefore error-prone. I'm talking about this code snippet:</p>\n<pre><code>btn_1 = QPushButton('Button 1')\nbtn_2 = QPushButton('Button 2')\nbtn_3 = QPushButton('Button 3')\n\nfor w in [btn_1, btn_2, btn_3]:\n w.setProperty('data', Storage())\n w.setCheckable(True)\n w.clicked.connect(self.set_data)\n self.btn_group.addButton(w)\n h_layout.addWidget(w)\n</code></pre>\n<p>I find the following approach to be a lot cleaner, while producing the same result. You basically only need to change the <code>stop</code> argument in <code>range(start, stop)</code> if you want to change the amount of buttons:</p>\n<pre><code>for i in range(start=1, stop=4):\n btn = QPushButton(f&quot;Button {i}&quot;)\n btn.setProperty('data', Storage())\n btn.setCheckable(True)\n btn.clicked.connect(self.set_data)\n\n self.btn_group.addButton(btn)\n h_layout.addWidget(btn)\n\n setattr(self, f&quot;btn_{i}&quot;, btn)\n</code></pre>\n<hr />\n<p>I'm sure there's a better way to set up <code>update_storage</code> and <code>set_data</code> without hardcoding the widgets, but I didn't think of a satisfactory approach yet.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-06T12:41:11.577", "Id": "259162", "ParentId": "259149", "Score": "2" } } ]
<p>Here is the problem:</p> <blockquote> <p>Given a numpy array 'a' that contains n elements, denote by b the set of its unique values ​​in ascending order, denote by m the size of array b. You need to create a numpy array with dimensions n×m , in each row of which there must be a value of 1 in case it is equal to the value of the given index of array b, in other places it must be 0.</p> </blockquote> <pre><code>import numpy as np def convert(a): b = np.unique(sorted(a)) result = [] for i in a: result.append((b == i) * 1) return np.array(result) a = np.array([1, 1, 2, 3, 2, 4, 5, 2, 3, 4, 5, 1, 1]) b = np.unique(sorted(a)) print(convert(a)) </code></pre> <p>This is my solution. is there some improvments that I can make? I'm not sure about declaring regular list to the result and then converting it into np.array.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-07T18:29:43.493", "Id": "511195", "Score": "0", "body": "Please do not edit the question with suggestions from answers. If you want a new round of feedback with updated code, you can post a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-07T18:41:15.557", "Id": "511196", "Score": "1", "body": "I've mistaken, when copied the code from my editor, that line was unnecessary." } ]
{ "AcceptedAnswerId": "259209", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-07T15:29:29.543", "Id": "259207", "Score": "4", "Tags": [ "python", "array", "numpy" ], "Title": "Creating nxm index list of array a" }
259207
accepted_answer
[ { "body": "<p><strong>Remove <code>sorted</code></strong></p>\n<p>From the docs: <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.unique.html\" rel=\"nofollow noreferrer\"><code>numpy.unique</code></a> returns the sorted unique elements of an array.</p>\n<p>You can simply remove the call to <code>sorted</code>:</p>\n<pre><code>b = np.unique(sorted(a))\n\n# produces the same result as\n\nb = np.unique(a)\n</code></pre>\n<hr />\n<p><strong>List comprehension</strong></p>\n<p>In most cases you can and should avoid this pattern of list creation:</p>\n<pre><code>result = []\nfor i in a:\n result.append((b == i) * 1)\n</code></pre>\n<p>It can be replaced by a concise list comprehension and directly passed to <code>np.array</code>:</p>\n<pre><code>result = np.array([(b == i) * 1 for i in a])\n\n# or directly return it (if applicable)\nreturn np.array([(b == i) * 1 for i in a])\n</code></pre>\n<p>List comprehensions are more pythonic and often faster. Generally, not mutating the <code>list</code> object is also less error-prone.</p>\n<hr />\n<p>There might be a better way to map <code>lambda x: (uniques == x) * 1</code> over the input array <code>a</code>. Here's a discussion on the topic on StackOverflow: <a href=\"https://stackoverflow.com/questions/35215161/most-efficient-way-to-map-function-over-numpy-array\">Most efficient way to map function over numpy array</a>. Seems like using <code>np.vectorize</code> should be avoided for performance reasons.</p>\n<p>Using <code>map</code> might be similiar to the list comprehension performance-wise (I did <strong>not</strong> properly test performance here):</p>\n<pre><code>def convert_listcomp(a):\n uniques = np.unique(a)\n return np.array([(b == i) * 1 for i in a])\n\ndef convert_map(a):\n uniques = np.unique(a)\n return np.array(list(map(lambda x: (uniques == x) * 1, a)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-07T17:10:16.573", "Id": "259209", "ParentId": "259207", "Score": "4" } } ]
<p>I build this simple function, <a href="https://www.python.org/dev/peps/pep-0008/#introduction" rel="noreferrer">trying to use PEP 8 Style</a>, something that I discovered recently thanks <a href="https://codereview.stackexchange.com/questions/255805/filtering-a-list-based-on-a-suffix-and-avoid-duplicates">to this previous question</a>.</p> <p>The function works, but I was wondering if there is a better way to do it.</p> <pre><code>import datetime def quarter_values_builder(): &quot;&quot;&quot;A function that returns an array with all the actual year quarters &quot;&quot;&quot; now = datetime.datetime.now() year = now.year year_str = str(year) quarter_values = [&quot;31/03/&quot;,&quot;30/06/&quot;,&quot;30/09/&quot;,&quot;31/12/&quot;] quarter_values_now = [x+year_str for x in quarter_values] return quarter_values_now current_quarters_string = quarter_values_builder() print(current_quarters_string) </code></pre>
[]
{ "AcceptedAnswerId": "259234", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T09:06:30.533", "Id": "259231", "Score": "10", "Tags": [ "python", "python-3.x", "datetime" ], "Title": "Return quarters of current year" }
259231
accepted_answer
[ { "body": "<p>Overall, it looks fine. I probably would've written it a little differently, and I'll explain the differences.</p>\n<pre><code>import datetime\n\ndef get_current_quarters():\n &quot;&quot;&quot;A function that returns an array\n with all the actual year quarters\n &quot;&quot;&quot;\n current_year = datetime.date.today().year\n quarter_values = [&quot;31/03/&quot;,&quot;30/06/&quot;,&quot;30/09/&quot;,&quot;31/12/&quot;] \n current_quarter_values = [\n &quot;{0}{1}&quot;.format(x, current_year)\n for x in quarter_values]\n\n return current_quarter_values\n\n\ncurrent_quarters = get_current_quarters()\nprint(current_quarters)\n</code></pre>\n<p>The function name <code>quarter_values_builder()</code> sounds too complicated to me. Is it really a builder if all it does is take a known list and append the year to it? It's basically a glorified string formatter. A builder reminds me of the <a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">Builder pattern</a>, something that doesn't apply here.</p>\n<p>Getting the current year can be simplified too. We're not interested in the intermediary variables, so no need to create them. It's still perfectly readable if we do it all in one go.</p>\n<p><code>x+year_str</code> should at least have a little whitespace, <code>x + year_str</code>, to increase readability. While we're at it, we might as well use proper string formatting. This is how we did save us a <code>str()</code> <a href=\"https://en.wikipedia.org/wiki/Type_conversion\" rel=\"nofollow noreferrer\">cast</a> earlier too. The formatting takes care of this for us. Because the line got a bit long, I cut it up a bit per function. This isn't required under 79 characters, but I think it looks better.</p>\n<p>At the end, we don't need to call the storage variable a <code>string</code>. We don't need to store it at all, the last 2 lines could easily become 1 line. But if we store it, putting the type of the variable in the name is more of a distraction than a help. After all, it's Python. The type might easily change in the next version. If you really want to use type-hints in Python, use <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">actual type hints</a>.</p>\n<p>Having a <code>now</code> in a variable while you're actually talking about quarters is somewhat confusing as well, in my opinion. So I've completely eliminated that from the used variables.</p>\n<p>Addendum:<br>\nWe don't need to use <code>datetime.datetime.now()</code> at all. The <a href=\"https://docs.python.org/3/library/datetime.html\" rel=\"nofollow noreferrer\"><code>datetime</code></a> module has a <code>date</code>, <code>time</code> and <code>datetime</code> type. Considering we're only interested in the <code>year</code> attribute, a <code>datetime</code> is overkill. <code>date</code> is enough to extract the <code>year</code> from.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T17:32:35.957", "Id": "511285", "Score": "1", "body": "Mostly sensible, though I would replace `datetime.datetime.now` with `datetime.date.today` which captures your intent better" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T17:38:12.370", "Id": "511287", "Score": "0", "body": "@Reinderien Great catch, you're absolutely right." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T10:59:51.253", "Id": "259234", "ParentId": "259231", "Score": "8" } } ]
<p>I have a list of key:</p> <pre><code>list_date = [&quot;MON&quot;, &quot;TUE&quot;, &quot;WED&quot;, &quot;THU&quot;,&quot;FRI&quot;] </code></pre> <p>I have many lists of values that created by codes below:</p> <pre><code>list_value = list() for i in list(range(5, 70, 14)): list_value.append(list(range(i, i+10, 3))) </code></pre> <p>Rules created that:</p> <ul> <li><p>first number is 5, a list contains 4 items has value equal x = x + 3, and so on [5, 8, 11, 14]</p> </li> <li><p>the first number of the second list equal: x = 5 + 14, and value inside still as above x = x +3</p> <p>[[5, 8, 11, 14], [19, 22, 25, 28], [33, 36, 39, 42], [47, 50, 53, 56], [61, 64, 67, 70]]</p> </li> </ul> <p>I expect to obtain a dict like this:</p> <pre><code>collections = {&quot;MON&quot;:[5, 8, 11, 14], &quot;TUE&quot; :[19, 22, 25, 28], &quot;WED&quot;:[33, 36, 39, 42], &quot;THU&quot;:[47, 50, 53, 56], &quot;FRI&quot;:[61, 64, 67, 70]} </code></pre> <p>Then, I used:</p> <pre><code>zip_iterator = zip(list_date, list_value) collections = dict(zip_iterator) </code></pre> <p>To get my expected result.</p> <p>I tried another way, like using the <code>lambda</code> function.</p> <pre><code>for i in list(range(5, 70, 14)): list_value.append(list(range(i,i+10,3))) couple_start_end[lambda x: x in list_date] = list(range(i, i + 10, 3)) </code></pre> <p>And the output is:</p> <pre><code>{&lt;function &lt;lambda&gt; at 0x000001BF7F0711F0&gt;: [5, 8, 11, 14], &lt;function &lt;lambda&gt; at 0x000001BF7F071310&gt;: [19, 22, 25, 28], &lt;function &lt;lambda&gt; at 0x000001BF7F071280&gt;: [33, 36, 39, 42], &lt;function &lt;lambda&gt; at 0x000001BF7F0710D0&gt;: [47, 50, 53, 56], &lt;function &lt;lambda&gt; at 0x000001BF7F0890D0&gt;: [61, 64, 67, 70]} </code></pre> <p>I want to ask there is any better solution to create lists of values with the rules above? and create the dictionary <code>collections</code> without using the <code>zip</code> method?</p>
[]
{ "AcceptedAnswerId": "259249", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T15:13:32.127", "Id": "259246", "Score": "3", "Tags": [ "python", "hash-map" ], "Title": "Create a dictionary from a list of key and multi list of values in Python" }
259246
accepted_answer
[ { "body": "<p>One alternative approach is to take advantage of <code>enumerate()</code> -- which allows\nyou to iterate over what could be thought of as a <code>zip()</code> of a list's indexes and\nvalues. To my eye, this version seems a bit clearer and simpler.</p>\n<pre><code>days = ['MON', 'TUE', 'WED', 'THU', 'FRI']\n\nd = {\n day : [\n (5 + i * 14) + (j * 3)\n for j in range(4)\n ]\n for i, day in enumerate(days)\n}\n\nprint(d)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T17:17:37.753", "Id": "511283", "Score": "0", "body": "Personally, I always use ```itertools.product``` whenever there is a cartesian product involved: ```d = {day: (5 + i * 14) + (j * 3) for i,(j,day) in it.product(range(4), enumerate(days))}```." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T17:19:14.273", "Id": "511284", "Score": "0", "body": "Just noticed the answers do not match. I retract my statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T23:45:54.463", "Id": "511329", "Score": "0", "body": "@Kevin: excuse me! but what is \"it\" in \"it.product()\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-09T01:07:35.070", "Id": "511332", "Score": "0", "body": "@Scorpisces `import itertools as it`. But `product()` doesn't really help here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-09T11:55:32.760", "Id": "511380", "Score": "0", "body": "One reason it's simpler/clearer is that it doesn't need the OP's limit `70`, as it simply goes as far as the days. And `range(4)` is also a lot clearer for the intention \"4 items\" than the limit `i+10`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T04:10:39.383", "Id": "511432", "Score": "0", "body": "Overall agree, though you could drop the parens in `(5 + i * 14) + (j * 3)`; `5 + 14*i + 3*j` is clear enough" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T04:14:24.293", "Id": "511433", "Score": "1", "body": "Also you needn't write `3*j` at all - you can instead move that to `j in range(0, 12, 3)` to avoid the multiplication." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T17:07:22.837", "Id": "511478", "Score": "0", "body": "@Reinderien Both of your suggestions are reasonable enough. I don't have a strong opinion one way or another, but I do suspect that readability is helped a small increment by keeping the not-required parens, keeping the looping mechanism simpler, and consolidating all math in a single location. But that's just a hunch." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T16:36:40.600", "Id": "259249", "ParentId": "259246", "Score": "5" } } ]
<p>I just started doing preparation for interviews, but im having trouble recognizing the optimal solution</p> <p><strong>Problem:</strong> For a given IP Address, replace every &quot;.&quot; with &quot;[.]&quot;</p> <p><strong>Example:</strong></p> <pre><code>Input: address = &quot;1.1.1.1&quot; Output: &quot;1[.]1[.]1[.]1&quot; </code></pre> <p><strong>My solutions:</strong></p> <p><strong>First:</strong></p> <pre><code>def defang(x): lst = [] for i in x: if i == &quot;.&quot;: lst.append(&quot;[&quot; + i + &quot;]&quot;) else: lst.append(i) return lst adress = &quot;255.100.50.0&quot; tmp = defrang(adress) x='' for i in tmp: x+=i print(x) </code></pre> <p><strong>Second:</strong></p> <pre><code>adress = &quot;255.100.50.0&quot; print(&quot;[.]&quot;.join(adress.split('.'))) </code></pre> <p>Which one you think is better? The first doesnt rely on built-in methods but it creates a new list (more memory wasted?)</p> <p>The second seems better but is it a problem that it relies on built-in methods?</p> <p>In general idk what level of abstraction is requested by the interviewers, so any advice is welcome (regarding this specific solution or whatever else)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T16:08:26.803", "Id": "511471", "Score": "2", "body": "Using built-in functions is generally good practice and it's really (!) hard to beat their performance with self-written Python code (since they are implemented in C, not Python)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T16:10:05.567", "Id": "511472", "Score": "1", "body": "I'd definitely always create a function and not use the `print` statement from the function, as I/O should be separated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T18:59:34.787", "Id": "511483", "Score": "5", "body": "Both are bad. You should just use `address.replace('.', '[.]')`." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T16:03:39.223", "Id": "259316", "Score": "2", "Tags": [ "python", "comparative-review" ], "Title": "Which solution of the two is the most efficient? Is there a better one? (IP Address Defang)" }
259316
max_votes
[ { "body": "<p>If you are in an interview using Python, assume that the interviewer is\nreasonable and wants you to write fluent Python code. That means, among\nother things, taking advantage of the language's built-in powers:</p>\n<pre><code>def defrang(ip):\n return ip.replace('.', '[.]')\n</code></pre>\n<p>But let's suppose that the interviewer explicitly directs you to ignore\nbuilt-ins and write your own implementation that does the work\ncharacter-by-character. Your current implementation is reasonable, but I would\nsuggest a few things. (1) Especially at interface points (for example, a\nfunction's signature) use substantive variable names when they make sense. (2)\nDon't make the caller re-assemble the IP address. (3) There is no need to\nuse concatenation to create a literal: just use <code>'[.]'</code> directly. (4) The logic is\nsimple enough for a compact if-else expression (this is a stylistic judgment, not a firm opinion).</p>\n<pre><code>def defang(ip_address):\n chars = []\n for c in ip_address:\n chars.append('[.]' if c == '.' else c)\n return ''.join(chars)\n</code></pre>\n<p>A final possibility is to distill further and just use a comprehension.</p>\n<pre><code>def defang(ip_address):\n return ''.join(\n '[.]' if c == '.' else c \n for c in ip_address\n )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-11T00:30:37.033", "Id": "259337", "ParentId": "259316", "Score": "2" } } ]
<p>I just started doing preparation for interviews, but im having trouble recognizing the optimal solution</p> <p><strong>Problem:</strong> For a given IP Address, replace every &quot;.&quot; with &quot;[.]&quot;</p> <p><strong>Example:</strong></p> <pre><code>Input: address = &quot;1.1.1.1&quot; Output: &quot;1[.]1[.]1[.]1&quot; </code></pre> <p><strong>My solutions:</strong></p> <p><strong>First:</strong></p> <pre><code>def defang(x): lst = [] for i in x: if i == &quot;.&quot;: lst.append(&quot;[&quot; + i + &quot;]&quot;) else: lst.append(i) return lst adress = &quot;255.100.50.0&quot; tmp = defrang(adress) x='' for i in tmp: x+=i print(x) </code></pre> <p><strong>Second:</strong></p> <pre><code>adress = &quot;255.100.50.0&quot; print(&quot;[.]&quot;.join(adress.split('.'))) </code></pre> <p>Which one you think is better? The first doesnt rely on built-in methods but it creates a new list (more memory wasted?)</p> <p>The second seems better but is it a problem that it relies on built-in methods?</p> <p>In general idk what level of abstraction is requested by the interviewers, so any advice is welcome (regarding this specific solution or whatever else)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T16:08:26.803", "Id": "511471", "Score": "2", "body": "Using built-in functions is generally good practice and it's really (!) hard to beat their performance with self-written Python code (since they are implemented in C, not Python)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T16:10:05.567", "Id": "511472", "Score": "1", "body": "I'd definitely always create a function and not use the `print` statement from the function, as I/O should be separated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T18:59:34.787", "Id": "511483", "Score": "5", "body": "Both are bad. You should just use `address.replace('.', '[.]')`." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T16:03:39.223", "Id": "259316", "Score": "2", "Tags": [ "python", "comparative-review" ], "Title": "Which solution of the two is the most efficient? Is there a better one? (IP Address Defang)" }
259316
max_votes
[ { "body": "<p>If you are in an interview using Python, assume that the interviewer is\nreasonable and wants you to write fluent Python code. That means, among\nother things, taking advantage of the language's built-in powers:</p>\n<pre><code>def defrang(ip):\n return ip.replace('.', '[.]')\n</code></pre>\n<p>But let's suppose that the interviewer explicitly directs you to ignore\nbuilt-ins and write your own implementation that does the work\ncharacter-by-character. Your current implementation is reasonable, but I would\nsuggest a few things. (1) Especially at interface points (for example, a\nfunction's signature) use substantive variable names when they make sense. (2)\nDon't make the caller re-assemble the IP address. (3) There is no need to\nuse concatenation to create a literal: just use <code>'[.]'</code> directly. (4) The logic is\nsimple enough for a compact if-else expression (this is a stylistic judgment, not a firm opinion).</p>\n<pre><code>def defang(ip_address):\n chars = []\n for c in ip_address:\n chars.append('[.]' if c == '.' else c)\n return ''.join(chars)\n</code></pre>\n<p>A final possibility is to distill further and just use a comprehension.</p>\n<pre><code>def defang(ip_address):\n return ''.join(\n '[.]' if c == '.' else c \n for c in ip_address\n )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-11T00:30:37.033", "Id": "259337", "ParentId": "259316", "Score": "2" } } ]
<p>This is based on this <a href="https://leetcode.com/problems/unique-paths-ii/" rel="nofollow noreferrer">leetcode question</a>. I get the correct answer, but I know it could be much, much cleaner. I also know there is supposed to be an O(n) space solution, but I'm not sure how to implement cleanly.</p> <p>It is a dynamic programming problem, I tried to add some helpful code comments, I know it's pretty messy so thank you for your review.</p> <pre class="lang-py prettyprint-override"><code>class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -&gt; int: #initialize memoization array memo = [[-1 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))] #add known values before any calculation (last row and last column) memo[len(memo)-1][len(memo[0])-1] = 1 for i in range(len(memo[0])-2,-1,-1): if obstacleGrid[len(memo)-1][i] != 1: memo[len(memo)-1][i] = memo[len(memo)-1][i+1] else: memo[len(memo)-1][i] = 0 for j in range(len(memo)-2,-1,-1): if obstacleGrid[j][len(memo[0])-1] != 1: memo[j][len(memo[0])-1] = memo[j+1][len(memo[0])-1] else: memo[j][len(memo[0])-1] = 0 if obstacleGrid[len(memo)-1][len(memo[0])-1] == 1: return 0 #does calculations def helper(row,col): nonlocal memo if obstacleGrid[row][col] == 1: return 0 if memo[row][col] == -1: memo[row][col] = helper(row+1,col) + helper(row,col+1) return memo[row][col] return helper(0,0) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T20:12:01.793", "Id": "259326", "Score": "4", "Tags": [ "python", "algorithm", "dynamic-programming" ], "Title": "Unique Paths II, dynamic programming problem, O(n^2) time, O(n^2) space" }
259326
max_votes
[ { "body": "<p>Nice solution, few suggestions:</p>\n<ul>\n<li><p><strong>Duplicated code</strong>: the functions <code>len(memo)</code> and <code>len(memo[0])</code> are called several times. When working with a matrix is common to call <code>m</code> the number of rows (<code>len(memo)</code>) and <code>n</code> the number of columns (<code>len(memo[0])</code>). This can help to reduce the duplicated code. As @Manuel mentioned in the comments, <code>m</code> and <code>n</code> are also defined in the problem description.</p>\n</li>\n<li><p><strong>Last element of a list</strong>: instead of <code>memo[len(memo)-1]</code> you can use <code>memo[-1]</code>.</p>\n</li>\n<li><p><strong>Input validation</strong>: this input validation:</p>\n<pre><code>if obstacleGrid[len(memo)-1][len(memo[0])-1] == 1:\n return 0 \n</code></pre>\n<p>is done too late in the code, after the <code>memo</code> matrix is fully built. Better to move it up at the beginning of the function. BTW, with the previous suggestion, it can be shortened to:</p>\n<pre><code>if obstacleGrid[-1][-1] == 1:\n return 0\n</code></pre>\n</li>\n<li><p><strong>Naming</strong>: the row is called <code>row</code> in the helper function and <code>j</code> in the rest of the code. Same for the column. Use the same name to be consistent.</p>\n</li>\n<li><p><strong>Throwaway variables</strong>: in the initialization of memo:</p>\n<pre><code>memo = [[-1 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))]\n</code></pre>\n<p>the variables <code>i</code> and <code>j</code> are not used. They can be replaced with <code>_</code>.</p>\n</li>\n<li><p><strong>Type hints</strong>: the <code>helper</code> function is missing the type hints.</p>\n</li>\n<li><p><strong>LRU cache</strong>: there is a handy annotation that does the memoization automatically, <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\">@lru_cache</a>. Or the unbounded <code>@cache</code> in Python 3.9.</p>\n</li>\n</ul>\n<p>An example using <code>@lru_cache</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -&gt; int:\n m = len(obstacleGrid)\n n = len(obstacleGrid[0])\n\n if obstacleGrid[-1][-1] == 1:\n return 0\n\n @lru_cache(maxsize=None)\n def helper(row: int, col: int) -&gt; int:\n if row == m - 1 and col == n - 1:\n return 1\n if row &lt; m and col &lt; n:\n if obstacleGrid[row][col] == 1:\n return 0\n return helper(row + 1, col) + helper(row, col + 1)\n return 0\n\n return helper(0, 0)\n</code></pre>\n<p>For dynamic programming solutions, you can have a look at the &quot;Solution&quot; <a href=\"https://leetcode.com/problems/unique-paths-ii/solution/\" rel=\"nofollow noreferrer\">section</a> or &quot;Discussion&quot; <a href=\"https://leetcode.com/problems/unique-paths-ii/discuss/?currentPage=1&amp;orderBy=hot&amp;query=&amp;tag=python&amp;tag=dynamic-programming\" rel=\"nofollow noreferrer\">section</a> using tags <code>python</code> and <code>dynamic programming</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-11T16:19:41.407", "Id": "511561", "Score": "1", "body": "This is exactly what I was looking for I always struggle with these 2-D DP problems, this will make it a lot easier, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-11T04:18:04.153", "Id": "259341", "ParentId": "259326", "Score": "3" } } ]
<p>I worked on a problem from Automate the Boring Stuff Chapter 7:</p> <blockquote> <p>Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero.</p> <p>The regular expression doesn’t have to detect correct days for each month or for leap years; it will accept nonexistent dates like 31/02/2020 or 31/04/2021. Then store these strings into variables named month, day, and year, and write additional code that can detect if it is a valid date. April, June, September, and November have 30 days, February has 28 days, and the rest of the months have 31 days. February has 29 days in leap years. Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400. Note how this calculation makes it impossible to make a reasonably sized regular expression that can detect a valid date.</p> </blockquote> <p>Here's my code:</p> <pre><code>#Program that detects dates in text and copies and prints them import pyperclip, re #DD/MM/YEAR format dateRegex = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)') #text = str(pyperclip.paste()) text = 'Hello. Your birthday is on 29/02/1990. His birthday is on 40/09/1992 and her birthday is on 09/09/2000.' matches = [] for groups in dateRegex.findall(text): day = groups[0] month = groups[1] year = groups[2] #convert to int for comparisons dayNum = int(day) monthNum = int(month) yearNum = int(year) #check if date and month values are valid if dayNum &lt;= 31 and monthNum &gt; 0 and monthNum &lt;= 12: #months with 30 days if month in ('04', '06', '09', '11'): if not (dayNum &gt; 0 and dayNum &lt;= 30): continue #February only if month == '02': #February doesn't have more than 29 days if dayNum &gt; 29: continue if yearNum % 4 == 0: #leap years have 29 days in February if yearNum % 100 == 0 and yearNum % 400 != 0: #not a leap year even if divisible by 4 if dayNum &gt; 28: continue else: if dayNum &gt; 28: continue #all other months have up to 31 days if month not in ('02', '04', '06', '09', '11'): if dayNum &lt;= 0 and dayNum &gt; 31: continue else: continue date = '/'.join([groups[0],groups[1],groups[2]]) matches.append(date) if len(matches) &gt; 0: pyperclip.copy('\n'.join(matches)) print('Copied to clipboard:') print('\n'.join(matches)) else: print('No dates found.') </code></pre> <p>I've tested it out with various different date strings and it works as far as I can tell. I wanted to know about better ways of doing this though. As a beginner and an amateur, I understand there might be methods of writing the above code that are better and I don't mind being guided in the right direction and learning more about them. What is a better way of doing all of the above without using so many if statements?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-11T21:56:14.847", "Id": "259377", "Score": "5", "Tags": [ "python", "beginner", "regex" ], "Title": "Date Detection Regex in Python" }
259377
max_votes
[ { "body": "<p>Reading into the question somewhat, there is emphasis on not only matching to a date pattern where the digits and separators are in the right places, such as</p>\n<pre><code>98/76/5432\n</code></pre>\n<p>which your pattern would accept; but to narrow this - with the <em>pattern itself</em> - knowing what digits are allowable in which positions. One basic improvement is to constrain the range of the leading digits:</p>\n<pre><code>date_regex = re.compile(\n r'([0-3]\\d)'\n r'/([01]\\d)'\n r'/([12]\\d{3})'\n)\n</code></pre>\n<p>This is not perfect but certainly gets you to &quot;within the neighbourhood&quot; of a pattern that will skip invalid dates.</p>\n<p>As an exercise to you: how do you think you would extend the above to disallow dates like</p>\n<pre><code>00/09/1980\n38/10/2021\n</code></pre>\n<p>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T13:34:39.580", "Id": "511638", "Score": "1", "body": "`(0[1-9]|[1-2]\\d|3[01])/(0[1-9]|1[012])/([12]\\d{3})` would match the given requirements more precisely." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T03:47:48.063", "Id": "259386", "ParentId": "259377", "Score": "3" } } ]
<p>For my current job, I've been told that soon I'm going to be porting our Python code to Cython, with the intent of performance upgrades. In preparation of that, I've been learning as much about Cython as I can. I've decided that tackling the Fibonacci sequence would be a good start. I've implemented a Cython + Iterative version of the Fibonacci sequence. Are there any more performance upgrades I can squeeze out of this? Thanks!</p> <p><strong>fibonacci.pyx</strong></p> <pre><code>cpdef fib(int n): return fib_c(n) cdef int fib_c(int n): cdef int a = 0 cdef int b = 1 cdef int c = n while n &gt; 1: c = a + b a = b b = c n -= 1 return c </code></pre> <p>And how I test this code:</p> <p><strong>testing.py</strong></p> <pre><code>import pyximport ; pyximport.install() # So I can run .pyx without needing a setup.py file # import time from fibonacci import fib start = time.time() for i in range(100_000): fib(i) end = time.time() print(f&quot;Finonacci Sequence: {(end - start):0.10f}s (i=100,000)&quot;) # ~2.2s for 100k iterations </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T03:31:44.800", "Id": "511601", "Score": "5", "body": "Yes you can; there is a \\$O(\\log n)\\$ algorithm, but it has nothing to do with Cython." } ]
{ "AcceptedAnswerId": "259390", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T01:35:05.957", "Id": "259384", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "fibonacci-sequence", "cython" ], "Title": "Cython Fibonacci Sequence" }
259384
accepted_answer
[ { "body": "<p>Using one less variable seems faster:</p>\n<pre class=\"lang-py prettyprint-override\"><code>cdef int fib_c(int n):\n if n == 0:\n return 0\n cdef int a = 0\n cdef int b = 1\n for _ in range(n - 1):\n a, b = b, a + b\n return b\n</code></pre>\n<p>Running your test on my machine:</p>\n<pre><code>Original = 2.934 s\nImproved = 1.522 s\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T11:12:35.940", "Id": "511628", "Score": "0", "body": "I wonder whether it's because of the multi-assignment or because of the loop-kind..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T06:11:00.267", "Id": "259390", "ParentId": "259384", "Score": "2" } } ]
<p>For my current job, I've been told that soon I'm going to be porting our Python code to Cython, with the intent of performance upgrades. In preparation of that, I've been learning as much about Cython as I can. I've decided that tackling the Fibonacci sequence would be a good start. I've implemented a Cython + Iterative version of the Fibonacci sequence. Are there any more performance upgrades I can squeeze out of this? Thanks!</p> <p><strong>fibonacci.pyx</strong></p> <pre><code>cpdef fib(int n): return fib_c(n) cdef int fib_c(int n): cdef int a = 0 cdef int b = 1 cdef int c = n while n &gt; 1: c = a + b a = b b = c n -= 1 return c </code></pre> <p>And how I test this code:</p> <p><strong>testing.py</strong></p> <pre><code>import pyximport ; pyximport.install() # So I can run .pyx without needing a setup.py file # import time from fibonacci import fib start = time.time() for i in range(100_000): fib(i) end = time.time() print(f&quot;Finonacci Sequence: {(end - start):0.10f}s (i=100,000)&quot;) # ~2.2s for 100k iterations </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T03:31:44.800", "Id": "511601", "Score": "5", "body": "Yes you can; there is a \\$O(\\log n)\\$ algorithm, but it has nothing to do with Cython." } ]
{ "AcceptedAnswerId": "259390", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T01:35:05.957", "Id": "259384", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "fibonacci-sequence", "cython" ], "Title": "Cython Fibonacci Sequence" }
259384
accepted_answer
[ { "body": "<p>Using one less variable seems faster:</p>\n<pre class=\"lang-py prettyprint-override\"><code>cdef int fib_c(int n):\n if n == 0:\n return 0\n cdef int a = 0\n cdef int b = 1\n for _ in range(n - 1):\n a, b = b, a + b\n return b\n</code></pre>\n<p>Running your test on my machine:</p>\n<pre><code>Original = 2.934 s\nImproved = 1.522 s\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T11:12:35.940", "Id": "511628", "Score": "0", "body": "I wonder whether it's because of the multi-assignment or because of the loop-kind..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T06:11:00.267", "Id": "259390", "ParentId": "259384", "Score": "2" } } ]
<p>So the problem is</p> <blockquote> <p>Find the duplicate entries (2nd occurrence onwards) in the given numpy array and mark them as True. First time occurrences should be False.</p> </blockquote> <p>And my solution is:</p> <pre><code>import numpy as np def duplicates(a): uniques = np.unique(a) result = [] for i in a: if i not in uniques: result.append(True) else: result.append(False) uniques = np.delete(uniques, np.where(uniques == i)) return result np.random.seed(100) a = np.random.randint(0, 5, 10) print('Array: ', a) print(duplicates(a)) </code></pre> <p>What improvments can i make in this program?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T17:06:27.593", "Id": "511787", "Score": "1", "body": "Hey, thanks for your question. I answered it but I edited it a bunch of times, so be sure to check the final version of the answer now. Let me know in the comments if you have questions." } ]
{ "AcceptedAnswerId": "259469", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T16:40:45.723", "Id": "259467", "Score": "6", "Tags": [ "python", "array", "numpy" ], "Title": "Marking duplicate entries in a numpy array as True" }
259467
accepted_answer
[ { "body": "<p>Your code is good code, I'd say. There's nothing wrong with it. The only thing is that you can write more or less the same algorithm in a much shorter way, and that essentially means you would refactor all of your code down to a single line.</p>\n<p>So, before taking a look at the boiled down version of what you wrote, let me just point out that variable names should be descriptive and if you are using abbreviations or one-letter names, you should stick to the <strong>most</strong> used conventions. Why am I saying this? Well, <code>i</code> is typically the name for an unimportant <em>index</em> variable, but in your loop you have <code>for i in a</code>, and <code>i</code> is an element of the array... So, believe it or not, people looking at the\nrest of your code might be thrown off by the fact that <code>i</code> is not an index.</p>\n<p><strong>Intermediate step</strong></p>\n<p>So before jumping to the one-liner that is actually <em>readable</em> (i.e. it is good Python code) let's take a look at a more tractable intermediate step. Instead of computing all the unique values and then deleting from there (deleting from the middle of a list is typically &quot;slow), you could go the other way around and have a list that saves all the unique values you have found:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def duplicates(arr):\n result, uniques = [], []\n for elem in arr:\n if elem in uniques:\n result.append(True)\n else:\n result.append(False)\n uniques.append(elem)\n \n return result\n</code></pre>\n<p><strong>Next intermediate step</strong></p>\n<p>Now take another look at what I wrote.\nNotice that both in the <code>if</code> and the <code>else</code> I am appending to the <code>result</code> variable. The only thing that is really &quot;special&quot; is the appending to the <code>uniques</code>, which only happens on the <code>else</code>, so we could write the <code>.append</code> unconditionally and append to <code>uniques</code> only if needed:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def duplicates(arr):\n result, uniques = [], []\n for elem in arr:\n result.append(elem in uniques)\n if elem in not uniques:\n uniques.append(elem)\n \n return result\n</code></pre>\n<p><strong>Final solution (after rethinking algorithm)</strong></p>\n<p>Let me know if you can understand my suggested solution and I'll expand on it if you need :)</p>\n<pre class=\"lang-py prettyprint-override\"><code>def duplicates(arr):\n return [elem in arr[:i] for i, elem in enumerate(arr)]\n</code></pre>\n<p>Notice that this list comprehension reads &quot;return a list that says if the i-th element can be found in the first i-1 elements&quot;.</p>\n<p>The key here is in phrasing the result in the correct way. If you reason Python code in the correct way, English and the code become one and the same.</p>\n<p>When you have a relatively simple <code>for</code> loop that is building a list with successive <code>.append</code>, that's a sign to try and see if you can use a list comprehension.</p>\n<p>I am also making use of the <code>enumerate</code> built-in (<a href=\"https://mathspp.com/blog/pydonts/enumerate-me\" rel=\"nofollow noreferrer\">learn about it here</a>) to traverse the array while looking at the values and indices at the same time.</p>\n<p><strong>EDIT</strong>:</p>\n<p>As other answers have noted (and also, see comments on this answer), this one-liner runs in time complexity O(n^2), which is not the best you can do.\nHowever, that single line of Python shows you how far you can go with just a simple idea/naive algorithm, and optimised usage of the core features of Python :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T17:06:24.350", "Id": "511786", "Score": "1", "body": "In that case it should be False, True, True. The False value is given only to the first appearance of the value in the array. Thank you for your explanation and advices, I really appreciate being in this community :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T17:07:25.617", "Id": "511788", "Score": "0", "body": "@LevonAvetisyan yup, I looked more calmly at your code and understood that, of course!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T18:03:08.897", "Id": "511797", "Score": "2", "body": "Better make `uniques` a `set`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T18:12:35.770", "Id": "511798", "Score": "0", "body": "@Manuel better performance in checking if the element is already there? (Won't the performance to _add_ a new element be worse?) Or why would you suggest that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T18:15:30.030", "Id": "511799", "Score": "2", "body": "Yes, making the whole thing O(n) instead of O(n^2). Plus you can remove your extra check then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T18:18:18.860", "Id": "511800", "Score": "0", "body": "@Manuel interesting suggestion. Still doesn't beat the list comprehension in simplicity..." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T16:45:39.147", "Id": "259469", "ParentId": "259467", "Score": "2" } } ]
<p>I am making a video editor with tkinter, and seriously need to clean it up and make it nicer to read / more efficient. Can anybody help me clean up my code (I was sent here from stackoverflow)</p> <p>Here it is: <a href="https://github.com/MiniMinnoww/moviepy-video-editor" rel="nofollow noreferrer">https://github.com/MiniMinnoww/moviepy-video-editor</a></p> <p>The parts I kinda need to figure out are:</p> <ul> <li>Buttons and popup windows. I need 2 functions to run 1 video editor function. For example, if I want to add text, I have to call a function to make a popup window for the details of the text, then call <strong>another</strong> function when the button is pressed to actually edit the video clip.</li> </ul> <p>Here is what I tried to do (in simple terms):</p> <pre><code>def addText(self, x=0): if x == 0: button = Button(root, command=functools.partial(self.addText, 1)) else: # run other stuff for function </code></pre> <p>Here you can see I am re-executing the function using an argument. Although this is effective, it is messy and I was wondering whether there's a better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T17:35:54.443", "Id": "511790", "Score": "3", "body": "Welcome to Code Review! \" Questions must [include the code to be reviewed](https://codereview.meta.stackexchange.com/a/3653/120114). Links to code hosted on third-party sites are permissible, but the most relevant excerpts must be embedded in the question itself. And is the code working fully to the best of your knowledge? if not then it is not [on-topic](https://codereview.stackexchange.com/help/on-topic)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T17:20:31.917", "Id": "259471", "Score": "0", "Tags": [ "python" ], "Title": "Video Editor Clean up" }
259471
max_votes
[ { "body": "<p><strong>Deferring command execution with a simple lambda</strong></p>\n<p>It is very similar to what you did, but no need to bring in heavier artillery like <code>functools.partial</code>, especially because you have no idea who is going to read your code and they may not understand it :(</p>\n<p>I'd go with</p>\n<pre class=\"lang-py prettyprint-override\"><code>def addText(self, x=0):\n if x == 0:\n button = Button(root, command=lambda: self.addText(1))\n else:\n # run other stuff for function\n\n</code></pre>\n<p>If this still annoys you because of the recursive call, then consider:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def auxiliaryStuff(self, x):\n # run other stuff for function\n\ndef addText(self, x=0):\n if x == 0:\n button = Button(root, command=lambda: self.auxiliaryStuff(1))\n else:\n self.auxiliaryStuff(x)\n</code></pre>\n<p>I'm assuming <code>x</code> can take values other than <code>1</code> or <code>0</code> from other places in your code. If they are always either <code>1</code> or <code>0</code> and they just represent a flag, consider using <code>True</code> and <code>False</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-13T17:37:38.053", "Id": "259473", "ParentId": "259471", "Score": "1" } } ]
<p>I wrote this code for a fibonacci sequence generator. Can anyone tell me whether my code is designed well? if not, why?</p> <pre><code>import logging def fibonacci_calc(current_val, current_pos=0, max_seq_length=5, sequence_list=[]): try: if(current_pos != 0 and len(sequence_list) == 0): raise Exception(&quot;Please initalize {} argument: {} with 0&quot;.format(fibonacci_calc.__name__, fibonacci_calc.__code__.co_varnames[1])) else: if(len(sequence_list) == 0): print(&quot;Initialization, added 0 and starting number {} to sequence list&quot;.format(current_val)) sequence_list.append(0) sequence_list.append(current_val) current_pos = 1 print(sequence_list) fibonacci_calc(current_val, current_pos, max_seq_length, sequence_list) elif(len(sequence_list) == max_seq_length): print('{} values in the sequence'.format(max_seq_length)) return else: print(&quot;Current position: {}, Total values: {} calculating next value&quot;.format(current_pos, current_pos+1)) next_val = sequence_list[current_pos] + sequence_list[current_pos-1] sequence_list.append(next_val) print(&quot;Current sequence list {}&quot;.format(sequence_list)) fibonacci_calc(next_val, current_pos+1, max_seq_length, sequence_list) except Exception: logging.exception('ERROR') fibonacci_calc(19,0, 7) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T12:00:43.920", "Id": "511909", "Score": "1", "body": "What is it supposed to do? At the very very least, show the result of the `fibonacci_calc(19,0, 7)` call you already do." } ]
{ "AcceptedAnswerId": "259490", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T00:44:47.680", "Id": "259486", "Score": "0", "Tags": [ "python", "python-3.x", "fibonacci-sequence" ], "Title": "Fibonacci generator python implementation" }
259486
accepted_answer
[ { "body": "<p>tldr; I'd say that this function is too complicated.</p>\n<p>Recursion should be avoided when possible as an iterative method is usually more readable and could be faster. Here's some other things to consider when making a recursive function: <a href=\"https://gist.github.com/abinoda/5593052#when-to-use-recursion-vs-iteration\" rel=\"nofollow noreferrer\">https://gist.github.com/abinoda/5593052#when-to-use-recursion-vs-iteration</a>.</p>\n<p>I think that some of the naming is not as clear as it could be, although that could just be an effect of the function being recursive. Consider changing parameter <code>max_seq_length</code> to <code>seq_length</code>. I couldn't quite see any scenario where you would give less results than the value passed in to <code>max_seq_length</code>.</p>\n<p>Another item that could use some thought is your use of raising an exception when validating your input:</p>\n<pre><code>if(current_pos != 0 and len(sequence_list) == 0):\n raise Exception(&quot;Please initalize {} argument: {} with 0&quot;.format(fibonacci_calc.__name__, fibonacci_calc.__code__.co_varnames[1]))\n</code></pre>\n<p>Here, you would likely be better off just logging a message instead of introducing more overhead by using an exception.</p>\n<p>Here's an example of a function that addresses my concerns:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_fibonacci_sequence(start_num, seq_length):\n if (seq_length &lt; 1):\n return []\n elif (seq_length == 1):\n return [start_num]\n elif (seq_length == 2):\n return [start_num, start_num]\n\n fibonacci_seq = [start_num, start_num]\n\n for i in range(2, seq_length):\n fibonacci_seq.append(fibonacci_seq[i - 1] + fibonacci_seq[i - 2])\n\n return fibonacci_seq\n\nprint(get_fibonacci_sequence(19, 7))\n</code></pre>\n<p>PS. I'm assuming all the print statements are just debugging aids and wouldn't be included in the final version. Those messages are likely superfluous for other purposes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T03:22:51.570", "Id": "511854", "Score": "0", "body": "Interesting implementation thank you, are there any advantages to uses multiple if's instead of if-elif-else statements apart from less characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T06:44:58.573", "Id": "511865", "Score": "1", "body": "@Malemna its not just multiple ifs; it's the early returns" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T13:24:36.927", "Id": "511924", "Score": "0", "body": "No, no advantages to multiple ifs, that was just an oversight on my part, sorry! Fixed it.\n@hjpotter92 The early returns are shortcircuits for cases where we automatically know the answer. I agree, multiple return statements hidden throughout a large function is bad, but they are usually fine if they are at the beginning or at the end of a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T13:30:03.777", "Id": "511925", "Score": "0", "body": "Hey thanks dude, learned alot! Do you have any recommendations on any books that covers alot of these bad practices?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T13:36:34.717", "Id": "511926", "Score": "0", "body": "Clean code is a very good book that should help: https://www.amazon.ca/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T16:00:51.963", "Id": "511940", "Score": "0", "body": "Thannks dude, ill upvote this answer :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T16:17:44.663", "Id": "511941", "Score": "1", "body": "I would argue using `elif` here is not necessary better than multiple `if` statements, since only one can be true and the subsequent `if`s will not be evaluated anyways, if one of the conditions is met. I personally find multiple `if`s clearer as they mark different, mutually exclusive exit conditions, but that's just personal preference. =)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T02:49:51.803", "Id": "259490", "ParentId": "259486", "Score": "2" } } ]
<p>So here is the problem:</p> <blockquote> <p>Given 2D numpy arrays 'a' and 'b' of sizes n×m and k×m respectively and one natural number 'p'. You need to find the distance(Euclidean) of the rows of the matrices 'a' and 'b'. Fill the results in the k×n matrix. Calculate the distance with the following formula <span class="math-container">$$ D(x, y) = \left( \sum _{i=1} ^{m} \left| x_i - y_i \right|^p \right) ^{1/p} ; x,y \in R^m $$</span> (try to prove that this is a distance). Extra points for writing without a loop.</p> </blockquote> <p>And here is my solution:</p> <pre><code>import numpy as np def dist_mat(a, b, p): result = [] print(result) for vector in b: matrix = a - vector print(matrix) result.append(list(((matrix ** p).sum(axis=1))**(1/p))) return np.array(result) a = np.array([[1, 1], [0, 1], [1, 3], [4, 5]]) b = np.array([[1, 1], [-1, 0]]) p = 2 print(dist_mat(a, b, p)) </code></pre> <p>I'm not sure about using Python <code>list</code> and then converting it into <code>np.array</code>, is there a better way?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T17:36:42.787", "Id": "511949", "Score": "2", "body": "Does this code pass all the testcases? It seems to me that you would want `matrix = abs(a - vector)` according to the provided formula. Doesn't matter for an even value `p`, but does for odd values. Might be wrong though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T17:41:12.263", "Id": "511951", "Score": "0", "body": "Yeah, that part was incorrect, thank you for the correction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-16T05:17:48.050", "Id": "512108", "Score": "0", "body": "I know you want your own solution from scratch, but you might have a look at `scipy.spatial.distance_matrix()` for testing. https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance_matrix.html" } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T17:23:44.783", "Id": "259526", "Score": "2", "Tags": [ "python", "array", "numpy", "matrix", "mathematics" ], "Title": "Finding distance between vectors of matrices" }
259526
max_votes
[ { "body": "<p>This is an old enough question that shooting for the extra points is hopefully not going to step on anyone's toes. So let me be the broadcast guy, i.e. this is a loop-free version.</p>\n<p>It is perhaps better to first read either the numpy documentation on broadcasting, or a related <a href=\"https://codereview.stackexchange.com/questions/259207/creating-nxm-index-list-of-array-a/259261#259261\">answer of mine</a>.</p>\n<h2>We start with solving the one-column case.</h2>\n<p>In this case the matrices are of size <code>n x 1</code> and <code>k x 1</code>. We need to turn these into a matrix of size <code>k x n</code>.</p>\n<p>Well, to get there by broadcasting, we need to take the transpose of one of the vectors. The problem calls for the first one to be transposed. Thus we have the matrix <code>a.T</code> of size <code>1 x n</code> and <code>b</code> of size <code>k x 1</code>.</p>\n<p>Then the solution is just</p>\n<pre class=\"lang-py prettyprint-override\"><code> # shape is (k, n)\n (np.abs(a.T - b) ** p) ** (1/p).\n</code></pre>\n<h2>The case with multiple columns</h2>\n<p>The matrices are of size <code>n x m</code> and <code>k x m</code>. To be able to reuse the previous idea, we have to turn these into arrays of shape <code>1 x n x m</code> and <code>k x 1 x m</code>. This can be done using <code>np.expand_dims</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code> # shape is (k, n, m)\n np.expand_dims(a, 0) - np.expand_dims(b, 1)\n</code></pre>\n<p>Looks good. All that remains is to take the absolute value, then the <code>p</code>th power, then sum up along the last dimension, lastly take <code>p</code>th root.</p>\n<pre class=\"lang-py prettyprint-override\"><code> # shape is (k, n)\n (np.abs(np.expand_dims(a, 0) - np.expand_dims(b, 1))**p).sum(axis=-1)**(1/p)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-16T12:35:30.723", "Id": "514712", "Score": "1", "body": "All insights are welcome here on CR - there's no need to worry about \"stepping on toes\"! This is certainly a good way to simplify the code, and shows the reasoning as to how it works and why it's better - exactly what we want from a good answer. Keep them coming!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-16T17:04:29.153", "Id": "514726", "Score": "0", "body": "@TobySpeight right, thank you. I never seem to know when is a complete rewrite appropriate as a review. Especially when the question smells like homework." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-16T10:29:29.073", "Id": "260801", "ParentId": "259526", "Score": "1" } } ]
<p>I've implemented my own insertion sort algorithm, and here's the code.</p> <pre><code>def insertion(lst): for i in range(1, len(lst)): for j in range(i): if lst[i] &lt; lst[j]: val = lst[i] del lst[i] lst.insert(j, val) break return lst </code></pre> <p>Typical insertion sort algorithms seem to compare values from the immediate left of the current index and make swaps as you continue left in the sorted values.</p> <p>I implemented my algorithm such that it will compare values from left to right (the second <code>for</code> loop). Do you see any issues with my code, or do you have any feedback on this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-15T03:09:21.650", "Id": "511989", "Score": "0", "body": "Just a style comment - if you mutate the original list, I would recommend returning `None`. I personally find it confusing when a function both modifies the input and then returns the reference back to me." } ]
{ "AcceptedAnswerId": "259553", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-15T02:01:14.440", "Id": "259545", "Score": "1", "Tags": [ "python", "algorithm", "sorting", "insertion-sort" ], "Title": "Insertion Sort- inserting from the left" }
259545
accepted_answer
[ { "body": "<ul>\n<li>The typical insertion sort is O(n) for already sorted input, and &quot;almost O(n)&quot; for &quot;almost sorted&quot; input. Which is somewhat common in real world data. Your way you don't have that, you're <span class=\"math-container\">\\$\\Theta(n^2)\\$</span>. Someone not familiar with how lists work internally might think your code is O(n) for <em>reverse</em>-sorted input, but since <code>del lst[i]</code> takes O(n - i) and <code>lst.insert(j, val)</code> takes O(n - j), that's not the case.</li>\n<li>As Ted points out, better don't both modify and return. Choose one or the other. Just like Python's own sorting functions do: <code>list.sort</code> only modifies, and <code>sorted</code> only returns (well, it necessarily &quot;modifies&quot; a given iterator by consuming it).</li>\n<li>&quot;Insertion a list&quot;... huh? <code>insertion</code> seems like an incomplete name for insertion <em>sort</em>. You can't really tell from the function signature what it does (and there's no doc string, either).</li>\n<li>I'd go with <code>enumerate</code>, then you have <code>val</code> already, which is nicer and faster.</li>\n</ul>\n<p>Improved version sticking with search-from-left but incorporating the other points:</p>\n<pre><code>def insertion_sort(lst):\n for i, val in enumerate(lst):\n for j in range(i):\n if val &lt; lst[j]:\n del lst[i]\n lst.insert(j, val)\n break\n</code></pre>\n<p>A benchmark sorting 10000 random numbers:</p>\n<pre><code>2.17 seconds insertion\n1.69 seconds insertion_sort\n\n2.15 seconds insertion\n1.66 seconds insertion_sort\n\n2.17 seconds insertion\n1.69 seconds insertion_sort\n</code></pre>\n<p>Benchmark code:</p>\n<pre><code>from timeit import timeit\nfrom random import random\n\ndef insertion(lst):\n for i in range(1, len(lst)):\n for j in range(i):\n if lst[i] &lt; lst[j]:\n val = lst[i]\n del lst[i]\n lst.insert(j, val)\n break\n # return lst\n\ndef insertion_sort(lst):\n for i, val in enumerate(lst):\n for j in range(i):\n if val &lt; lst[j]:\n del lst[i]\n lst.insert(j, val)\n break\n\nfor _ in range(3):\n lst = [random() for _ in range(10000)]\n for func in insertion, insertion_sort:\n copy = lst * 1\n t = timeit(lambda: func(copy), number=1)\n assert copy == sorted(lst)\n print('%.2f seconds ' % t, func.__name__)\n print()\n</code></pre>\n<p><a href=\"https://tio.run/##rVJBboMwELzzipWqKKZCqDSXKioviRAysLROsI2MqZTXU69NISWK1EP3YuyZHe@M6a/2U6vDW2@mqTVaghUShQUhe23svIs8Yrhq3DIjYRdFDbYg1IDGCq1YN9j4GIGrVhsQDiHiB7IsgQ4DPhN@SOeVJG4gKtGCaziJAt79x7n4jVN98Q7ymXYHNtg9gtxxGuZm54RU4jtKZZBf/OkTGLSjUdS1sVwOLo2tby9IvlCNEg23eMP4m3ESeOz6P4xFNES5DnGYh3ACLtFTeGAWw4aWvbiKi8VsO6qa0CWRZBPOOn2t@2t4LHiGbDmm68KPxjouq4YfvSgjepyAi7BCk2erDz6Q/iyXA12CjU94ofRGKMv2u/S1hQFrrZoB9rADm3jttCwVl1iWoSOw42n6Bg\" rel=\"nofollow noreferrer\" title=\"Python 3.8 (pre-release) – Try It Online\">Try it online!</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-15T08:15:50.533", "Id": "259553", "ParentId": "259545", "Score": "1" } } ]
<p>I created a &quot;2-player&quot; rock-paper-scissors game in Python mainly using if statements and a single while loop. The program is really simple, but I was wondering if using switch statements or perhaps another format would make it less cluttered/quicker/etc.</p> <pre><code>again = 'y' while (again == 'y'): p1 = input(&quot;Player 1 --&gt; Rock, Paper, or Scissors? &quot;) p1 = p1.lower() print() p2 = input(&quot;Player 2 --&gt; Rock, Paper, or Scissors? &quot;) p2 = p2.lower() print() if (p1 == &quot;rock&quot;): if (p2 == &quot;rock&quot;): print(&quot;The game is a draw&quot;) elif (p2 == &quot;paper&quot;): print(&quot;Player 2 wins!&quot;) elif (p2 == &quot;scissors&quot;): print(&quot;Player 1 wins!&quot;) elif (p1 == &quot;paper&quot;): if (p2 == &quot;rock&quot;): print(&quot;Player 1 wins!&quot;) elif (p2 == &quot;paper&quot;): print(&quot;The game is a draw&quot;) elif (p2 == &quot;scissors&quot;): print(&quot;Player 2 wins!&quot;) elif (p1 == &quot;scissors&quot;): if (p2 == &quot;rock&quot;): print(&quot;Player 2 wins!&quot;) elif (p2 == &quot;paper&quot;): print(&quot;Player 1 wins!&quot;) elif (p2 == &quot;scissors&quot;): print(&quot;The game is a draw&quot;) else: print(&quot;Invalid input, try again&quot;) again = input(&quot;Type y to play again, anything else to stop: &quot;) print() </code></pre>
[]
{ "AcceptedAnswerId": "259672", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-16T20:54:52.860", "Id": "259635", "Score": "4", "Tags": [ "python", "rock-paper-scissors" ], "Title": "2 Player Rock Paper Scissors (Python)" }
259635
accepted_answer
[ { "body": "<h3>Remove Redundant Parenthesis</h3>\n<p>In this line:</p>\n<pre><code>while (again == 'y'):\n</code></pre>\n<p>The parenthesis are unneeded and can (should) be removed.</p>\n<h3>Use a dict to drive the stacked if/else</h3>\n<p>Whenever I see a stacked if/else I look to restructure the code using a dict (mapping) instead.\nThe net results of the if/else structure in your code can be put into a dict like so:</p>\n<pre><code>results = {\n &quot;rock&quot;: {\n &quot;rock&quot;: &quot;The game is a draw&quot;,\n &quot;paper&quot;: &quot;Player 2 wins!&quot;,\n &quot;scissors&quot;: &quot;Player 1 wins!&quot;,\n },\n &quot;paper&quot;: {\n &quot;rock&quot;: &quot;Player 1 wins!&quot;,\n &quot;paper&quot;: &quot;The game is a draw&quot;,\n &quot;scissors&quot;: &quot;Player 2 wins!&quot;,\n },\n &quot;scissors&quot;: {\n &quot;rock&quot;: &quot;Player 2 wins!&quot;,\n &quot;paper&quot;: &quot;Player 1 wins!&quot;,\n &quot;scissors&quot;: &quot;The game is a draw&quot;,\n },\n}\n</code></pre>\n<p>If the <code>results</code> are mapped this way, then the interactions with the user becomes more clear and\nyour loop can simply become:</p>\n<pre><code>while again == 'y':\n\n p1 = input(&quot;Player 1 --&gt; Rock, Paper, or Scissors? &quot;).lower()\n print()\n\n p2 = input(&quot;Player 2 --&gt; Rock, Paper, or Scissors? &quot;).lower()\n print()\n\n result = results.get(p1, {}).get(p2, &quot;Invalid input, try again&quot;)\n print(result)\n\n again = input(&quot;Type y to play again, anything else to stop: &quot;)\n print() \n</code></pre>\n<p>This is an example of separating the UI (User Interface) from the <a href=\"https://en.wikipedia.org/wiki/Business_logic\" rel=\"nofollow noreferrer\">Business Logic</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-17T20:11:54.423", "Id": "512237", "Score": "0", "body": "Interesting, I didn't even think about using a dict in this way. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-17T19:34:26.053", "Id": "259672", "ParentId": "259635", "Score": "3" } } ]
<p>Here is the problem:</p> <blockquote> <p>Given an array of a non-continuous sequence of dates. Make it a continuous sequence of dates, by filling in the missing dates.</p> </blockquote> <pre><code># Input dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-25'), 2) print(dates) #&gt; ['2018-02-01' '2018-02-03' '2018-02-05' '2018-02-07' '2018-02-09' #&gt; '2018-02-11' '2018-02-13' '2018-02-15' '2018-02-17' '2018-02-19' #&gt; '2018-02-21' '2018-02-23'] </code></pre> <p>And here is my solution:</p> <pre><code>import numpy as n dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-25'), 2) stride = (dates[1] - dates[0]) result = np.arange(np.datetime64(dates[0]), np.datetime64(dates[-1] + stride)) print(dates) print(result) </code></pre> <p>Is there a better way to do this task?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T04:03:50.340", "Id": "512394", "Score": "0", "body": "What's the last `2` supposed to indicate in `dates`, the amount of entries? The gap?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T10:20:17.837", "Id": "512435", "Score": "1", "body": "@Mast That's the `step` argument to [numpy.arange](https://numpy.org/doc/stable/reference/generated/numpy.arange.html), I agree that using keyword arguments would be beneficial here." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-17T12:04:53.830", "Id": "259661", "Score": "0", "Tags": [ "python", "array", "datetime", "numpy" ], "Title": "Fill missing dates into array of np.datetime" }
259661
max_votes
[ { "body": "<p>As you will be able to see from your provided sample input, your code does not produce the intended result. Here is a minimal example:</p>\n<pre><code>dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-05'), 2)\nstride = (dates[1] - dates[0])\nresult = np.arange(np.datetime64(dates[0]), np.datetime64(dates[-1] + stride))\n\nprint(dates) # &gt; ['2018-02-01' '2018-02-03']\nprint(result) # &gt; ['2018-02-01' '2018-02-02' '2018-02-03' '2018-02-04']\n</code></pre>\n<p><code>result</code> includes <code>2018-02-04</code>, which is outside of the range of <code>dates</code>. This is only the simplest case for which this code fails, it will also fail for input arrays that are not sorted in ascending order. The only case your code would cover correctly is an input array of continuous dates (sorted in ascending order). There are two central errors in your code:</p>\n<hr />\n<p><strong>We do not need <code>stride</code></strong></p>\n<p>We want the output range to include everything up until and including the maximum value of our input array. Since the <code>stop</code> argument to <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.arange.html\" rel=\"nofollow noreferrer\"><code>numpy.arange</code></a> is exclusive, we need the following:</p>\n<pre><code>stop:\nmaximum of input array + 1\n\nlast element of output array:\n(maximum of input array + 1) - 1\n= maximum of input array\n</code></pre>\n<p>Your current implementation does the following:</p>\n<pre><code>stop:\nmaximum of input array + stride\n\nlast element of output array:\n(maximum of input array + stride) - 1\n</code></pre>\n<p>The larger the difference between <code>dates[0]</code> and <code>dates[1]</code> (= <code>stride</code>), the more undesired values will be contained at the end of our output array.</p>\n<hr />\n<p><strong>The maximum is not always the last element</strong></p>\n<p>So we need to access the input array's maximum value to get the correct <code>stop</code> argument for <code>numpy.arange</code>. This will only be the last element if the input array is sorted in ascending order or if we get rather lucky, both cases are not specified by the problem statement.</p>\n<hr />\n<p>Correcting these two errors will give us this simple implementation:</p>\n<pre><code>def make_continuous_sorted(np_array):\n return np.arange(np.min(np_array), np.max(np_array) + 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T14:18:30.857", "Id": "512331", "Score": "2", "body": "Very good answer, quite educational +1." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T13:43:06.023", "Id": "259723", "ParentId": "259661", "Score": "4" } } ]
<p>I'm really new to both Python, data analysis and Panda and for gathering a bit of familiarity with this components and trying to replicate a trading strategy I'm creating a function that give me the Wiliam Fractal technical indicator, which by nature is a lagging indicator to apply at the currently analysed row of the dataframe, rather than where it actually happen, but without look ahead bias to not have unrealistic backtesting results ( but also avoiding to go back and always looking for the signal 2 rows before when it actually occurs )</p> <p>the indicator is defined with this constrains <a href="https://www.investopedia.com/terms/f/fractal.asp" rel="nofollow noreferrer">source</a> <span class="math-container">\begin{aligned} \text{Bearish Fractal} =\ &amp;\text{High} ( N ) &gt; \text{High} ( N - 2 ) \text{ and} \\ &amp;\text{High} ( N ) &gt; \text{High} ( N - 1 ) \text{ and} \\ &amp;\text{High} ( N ) &gt; \text{High} ( N + 1 ) \text{ and} \\ &amp;\text{High} ( N ) &gt; \text{High} ( N + 2 ) \\ \end{aligned}</span></p> <p><span class="math-container">\begin{aligned} \text{Bullish Fractal} =\ &amp;\text{Low} ( N ) &lt; \text{Low} ( N - 2 ) \text{ and} \\ &amp;\text{Low} ( N ) &lt; \text{Low} ( N - 1 ) \text{ and} \\ &amp;\text{Low} ( N ) &lt; \text{Low} ( N + 1 ) \text{ and} \\ &amp;\text{Low} ( N ) &lt; \text{Low} ( N + 2 ) \\ \end{aligned}</span> ​<br /> which I implemented with the following code:</p> <pre><code>def wilFractal(dataframe): df = dataframe.copy() df['bear_fractal'] = ( dataframe['high'].shift(4).lt(dataframe['high'].shift(2)) &amp; dataframe['high'].shift(3).lt(dataframe['high'].shift(2)) &amp; dataframe['high'].shift(1).lt(dataframe['high'].shift(2)) &amp; dataframe['high'].lt(dataframe['high'].shift(2)) ) df['bull_fractal'] = ( dataframe['low'].shift(4).gt(dataframe['low'].shift(2)) &amp; dataframe['low'].shift(3).gt(dataframe['low'].shift(2)) &amp; dataframe['low'].shift(1).gt(dataframe['low'].shift(2)) &amp; dataframe['low'].gt(dataframe['high'].shift(2)) ) return df['bear_fractal'], df['bull_fractal'] </code></pre> <p>any suggestions?</p> <p>usage edit: The code in this case is used to signal buy signal for a crypto trading bot in this manner:</p> <pre><code>def populate_buy_trend(self, dataframe, metadata) dataframe.loc[ dataframe['bull_fractal'], 'buy'] = 1 return dataframe </code></pre>
[]
{ "AcceptedAnswerId": "259718", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-18T20:37:51.627", "Id": "259703", "Score": "1", "Tags": [ "python", "beginner", "pandas" ], "Title": "William Fractal technical indicator implementation" }
259703
accepted_answer
[ { "body": "<p>Looks good, just a few ideas:</p>\n<ol>\n<li><p>Since the function only returns two Series, you can save some overhead by removing the <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.copy.html\" rel=\"nofollow noreferrer\"><code>copy()</code></a> and just working with Series.</p>\n</li>\n<li><p>Combining <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.logical_and.html\" rel=\"nofollow noreferrer\"><code>logical_and()</code></a> with <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.reduce.html\" rel=\"nofollow noreferrer\"><code>reduce()</code></a> allows you to build the shifted Series in a comprehension (and also seems slightly faster than chaining <code>&amp; &amp; &amp;</code>, based on some rough testing).</p>\n</li>\n<li><p>Instead of comparing <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.shift.html\" rel=\"nofollow noreferrer\"><code>shift(2)</code></a> against <code>4,3,1,0</code>, I find it more intuitive to compare the unshifted Series against <code>-2,-1,1,2</code>.</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def wilFractal(df):\n periods = (-2, -1, 1, 2)\n \n bear_fractal = pd.Series(np.logical_and.reduce([\n df['high'] &gt; df['high'].shift(period) for period in periods\n ]), index=df.index)\n\n bull_fractal = pd.Series(np.logical_and.reduce([\n df['low'] &lt; df['low'].shift(period) for period in periods\n ]), index=df.index)\n\n return bear_fractal, bull_fractal\n</code></pre>\n<p>An alternative idea is to use <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.Series.rolling.html\" rel=\"nofollow noreferrer\"><code>rolling()</code></a> with a window size of 5 and check if the center value in each window is the <code>max</code> (bear) or <code>min</code> (bull):</p>\n<pre class=\"lang-py prettyprint-override\"><code>def roll(df):\n bear_fractal = df['high'].rolling(5, center=True).apply(lambda x: x[2] == max(x), raw=True)\n bull_fractal = df['low'].rolling(5, center=True).apply(lambda x: x[2] == min(x), raw=True)\n return bear_fractal, bull_fractal\n</code></pre>\n<p>The <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.Series.rolling.html\" rel=\"nofollow noreferrer\"><code>rolling()</code></a> code is more concise, but it turns out your <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.shift.html\" rel=\"nofollow noreferrer\"><code>shift()</code></a> version scales better (memory permitting)!</p>\n<p><a href=\"https://i.stack.imgur.com/O8tmC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O8tmC.png\" alt=\"timing rolling() vs shift()\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T10:16:22.983", "Id": "259718", "ParentId": "259703", "Score": "9" } } ]
<p>I have a text adventure game and I need to use OOP so I've chosen to use it when getting the player's name and age. I need to keep the OOP; but was wondering if there are any ways to clean up the code or simplify it while still getting the overall output.</p> <pre><code> class Player: def __init__(self): self.get_name() self.verify_age() def get_name(self): print(&quot;If you are ready lets begin!&quot;) while True: print(&quot;What is your name?&quot;) name = input(&quot;:&gt; &quot;) if not name.istitle(): print(&quot;Please enter a name starting with a capital letter; try again.&quot;) else: self.name = name print(&quot;Hello &quot; + name + &quot; prepare for battle.&quot;) break def verify_age(self): while True: print(&quot;Before we begin please verify your age. \nWhat is your age?&quot;) age = input(&quot;:&gt; &quot;) try: if 8 &lt; int(age) &lt;= 110: self.age = age break elif int(age) &lt;= 8: print(&quot;You are not old enough to play the game! Try again.&quot;) else: print(&quot;You can't be that old, come on! Try again.&quot;) except: print(&quot;That is not a valid number! Try again.&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T16:57:26.253", "Id": "512461", "Score": "2", "body": "This is just the class. How will you be actually using this in your game?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T16:37:56.453", "Id": "259765", "Score": "1", "Tags": [ "object-oriented", "pygame" ], "Title": "Asking for player name and age using OOP" }
259765
max_votes
[ { "body": "<p>The methods in this class are not really Player methods. They are a combination of game flow, user input and value verification methods. I'd organize it more like this.</p>\n<pre><code>class Game:\n def __init__(self):\n io.show(&quot;If ready, let's begin&quot;)\n name = self.get_valid_name()\n age = self.get_valid_age()\n self.player = Player(name, age)\n io.show(&quot;Hello {}, prepare for battle&quot;.format(self.player.get_name()))\n</code></pre>\n<p>The <code>Game</code> object owns the flow of control. The I/O is encapsulated in an object which can be a simple stdio wrapper for now, but may eventually include non-blocking input or html output or whatever - don't tie the game logic to the display method. The <code>Player</code> object contains player state.</p>\n<p>The <code>get_valid_x</code> methods can basically be what you have now. If you are using that pattern over and over, you could get fancy and write a parameterized validator:</p>\n<pre><code>def get_valid_input(prompt, validation_func):\n while True:\n input = io.prompt(prompt)\n guidance = validation_func(input)\n if not guidance:\n return input\n io.show(guidance)\n\ndef validate_name(str):\n if not str.istitle():\n return &quot;Please enter name beginning with capital Letter&quot; \n return None\n\n ...\n \n name = get_valid_input(&quot;What is your name?&quot;, validate_name)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T18:41:37.053", "Id": "259769", "ParentId": "259765", "Score": "1" } } ]
<p>For example, given <code>[10, 15, 3, 7]</code> and a number <code>k</code> of <code>17</code>, return <code>True</code> since <code>10 + 7</code> is <code>17</code>.</p> <p>How can I improve the below solution?</p> <pre><code>from itertools import combinations def add_up_to(numbers, k): c_k_2 = list(combinations(numbers, 2)) return any([True for pair in c_k_2 if sum(pair) == k]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T19:03:47.947", "Id": "512470", "Score": "0", "body": "consider sorting and using two pointers for quick performance" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T19:17:16.707", "Id": "512478", "Score": "2", "body": "@HereToRelax Consider writing an answer and providing some more explanation for contributors that are looking to learn and improve" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T19:25:12.570", "Id": "512480", "Score": "0", "body": "I have an answer on two pointers here https://codereview.stackexchange.com/a/219139/62030" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T20:17:53.927", "Id": "512489", "Score": "0", "body": "Thanks for sharing. I implemented your proposed approach (my interpretation of course, as there's not a lot of information provided), sorted the list and used two pointers to run across the array. I used a numpy array to get good sorting performance. While there was a sweet spot (list length around 1.000) where this approach slightly outperformed my proposed algortihm using a `set`, it was significantly slower for long lists. If you actually know of a faster approach, I'd be interested to learn, so please do share!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T20:33:54.413", "Id": "512491", "Score": "0", "body": "How do you get a list of 10^10 elements and how long does it take once the list is loaded?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T20:43:52.210", "Id": "512492", "Score": "0", "body": "it takes me considerably longer to generate a suitable list or read one for the sizes that fit on my ram." } ]
{ "AcceptedAnswerId": "259790", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-20T16:38:58.630", "Id": "259766", "Score": "7", "Tags": [ "python" ], "Title": "Given a list of numbers and a number, return whether any two numbers from the list add up to" }
259766
accepted_answer
[ { "body": "<p>We can take your approach even further than riskypenguin did by pushing the work pretty much entirely into C-code:</p>\n<pre><code>def add_up_to(numbers, k):\n return k in map(sum, combinations(numbers, 2))\n</code></pre>\n<p>Takes <span class=\"math-container\">\\$O(1)\\$</span> space instead of your <span class=\"math-container\">\\$O(n^2)\\$</span>, and best case time is <span class=\"math-container\">\\$O(1)\\$</span> instead of your <span class=\"math-container\">\\$O(n^2)\\$</span>. And it's nice and short. Plus the C code is faster.</p>\n<p>Benchmark with a worst case, <code>numbers, k = [0] * 1000, 1</code>:</p>\n<pre><code>546.63 ms original\n386.11 ms riskypenguin\n229.90 ms Manuel\n</code></pre>\n<p>Benchmark with a &quot;best case&quot;, <code>numbers, k = [0] * 1000, 1</code>:</p>\n<pre><code>594.35 ms original\n 0.02 ms riskypenguin\n 0.02 ms Manuel\n</code></pre>\n<p>Why did I put quotes around &quot;best case&quot;? Because for you it's a worst case. Note your increased time. You treat all pairs in any case, and you do the most work when they all have the desired sum: then you build the longest possible list, full of <code>True</code> values. The other solutions see the first pair and right away stop, hence their tiny times.</p>\n<p>Those are of course all <a href=\"https://www.youtube.com/watch?v=62necDwQb5E\" rel=\"nofollow noreferrer\">moo points</a>, as this problem should be solved in <span class=\"math-container\">\\$O(n)\\$</span> time (as riskypenguin did later) or at most <span class=\"math-container\">\\$O(n \\log n)\\$</span> time. Unless you're only allowed <span class=\"math-container\">\\$O(1)\\$</span> space and forbidden to modify the given list, which is rather unrealistic.</p>\n<p>Benchmark code:</p>\n<pre><code>from timeit import repeat\nfrom functools import partial\nfrom itertools import combinations\n\ndef original(numbers, k):\n c_k_2 = list(combinations(numbers, 2))\n return any([True for pair in c_k_2 if sum(pair) == k])\n\ndef riskypenguin(numbers, k):\n return any(sum(pair) == k for pair in combinations(numbers, 2))\n\ndef Manuel(numbers, k):\n return k in map(sum, combinations(numbers, 2))\n\ndef benchmark(numbers, k, reps):\n print(f'{len(numbers)=} {k=} {reps=}')\n funcs = original, riskypenguin, Manuel\n for _ in range(3):\n for func in funcs:\n t = min(repeat(partial(func, numbers, k), number=reps))\n print('%6.2f ms ' % (t * 1e3), func.__name__)\n print()\n\n# benchmark([10, 15, 3, 7], 17, 10**5)\nbenchmark([0] * 1000, 1, 5)\nbenchmark([0] * 1000, 0, 5)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T11:37:30.990", "Id": "512537", "Score": "0", "body": "That's a really clean solution compared to my first version, +1! Could you include my proposed approach using a `set` in your benchmarks? I would hope it performs pretty well, especially in worst case scenarios" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T12:07:48.900", "Id": "512539", "Score": "0", "body": "@riskypenguin Hmm, I left it out intentionally, as I don't find it interesting to confirm the obvious :-P. I really just wanted to compare the `combinations`+`sum` versions, didn't even include another O(1) space non-modifying solution of mine that's about four times faster. But I ran your set solution now, takes about 0.4 to 0.5 ms for that \"worst case\", although that's not quite fair as it additionally unrealistically benefits from its set remaining a single element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T12:13:57.923", "Id": "512541", "Score": "0", "body": "I see your point, no worries. Do you have an idea where your performance improvement comes from exactly? Is it just the replacement of `==` by `in` or the presumably reduced overhead of not calling `any`? Or does `map` simply outperform user-written generator expressions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T12:29:16.817", "Id": "512544", "Score": "1", "body": "@riskypenguin I think it's the `map` vs the generator expression. With the latter, you're still interpreting Python code all the time. And maybe all the \"context switches\" between `any` and the generator also hurt. I'm kinda disappointed the speed difference isn't bigger :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T12:45:06.897", "Id": "512548", "Score": "1", "body": "@TobySpeight Bah, [that was intentional](https://www.youtube.com/watch?v=62necDwQb5E) :-(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T14:33:12.693", "Id": "512559", "Score": "1", "body": "\"Bah\" - or \"Baa\"? ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T07:38:35.840", "Id": "512652", "Score": "0", "body": "I tried to edit it myself, but turns out there's a minimum number of characters you can edit; the best case scenario should have `k == 0`, not `k == 1`, there's a typo in the benchmark example!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T10:56:15.720", "Id": "259790", "ParentId": "259766", "Score": "3" } } ]
<p>I am creating a metaclass which ensures that instances of an actual class <code>A</code> are kind of singletons. But rather than having only single instance of <code>A</code>, I would like to have one instance per argument set given to <code>A</code>.</p> <p>That is</p> <pre><code>class A(metaclass=ArgumentSingleton): pass r = A() s = A() t = A(1) u = A(1) v = A('hi') print(r is s) # True print(r is t) # False print(t is u) # True print(v is u) # False print(v is r) # False </code></pre> <p>Moreover, the property of 'being a singleton' must survive pickling.</p> <p>That is</p> <pre><code>a = A() with open('tmp.pkl', 'wb') as f: pkl.dump(a, f) with open('tmp.pkl', 'rb') as f: b = pkl.load(f) print(a is b) # True </code></pre> <p>For example Sympy is capable of doing that with their constants (such as <code>pi</code>) and I tried similar approach.</p> <pre><code>class ArgumentSingleton(type): _instances = {} def __new__(cls, name, bases, class_dict): def __init__(self, *args): self._args = args print('Here in __init__') def __reduce_ex__(self, protocol): return type(self), (*self._args,) init = '__init__' reduce = '__reduce_ex__' method_absence = [ init not in class_dict, reduce not in class_dict ] if all(method_absence): class_dict[init] = __init__ class_dict[reduce] = __reduce_ex__ elif any(method_absence): raise ArgumentSingletonException( f&quot;Either both methods '{init}', '{reduce}' are defined or &quot; f&quot;none of them in class: {name}&quot; ) new_class = super().__new__(cls, name, bases, class_dict) return new_class def __call__(cls, *args, **kwargs): key = (cls, *args, *kwargs.items()) if key not in ArgumentSingleton._instances: ArgumentSingleton._instances[key] = super().__call__(*args, **kwargs) return cls._instances[key] </code></pre> <p>The code depends quite deeply (at least to my standards) on inner workings of Python and I am afraid of any hidden bugs and hidden problems.</p> <p>The purpose of controling presence of <code>__init__</code> and <code>__reduce_ex__</code> is to explicitly move responsibility for <code>__reduce_ex__</code> to the creators of the class <code>A</code> in case they decide to provide their <code>__init__</code>.</p> <p>Any comments or suggestions appreciated!</p> <p>So far, I am aware of the fact that the arguments must be hashable. That is not problem for me, as this construction is meant to speed up comparison of my complex hashable objects.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T12:19:17.240", "Id": "512542", "Score": "1", "body": "Hey, welcome to the community! The 2nd code snippet, where you show the pickling and unpickling, makes use of a variable `b` that is not defined! For the sake of clarity and correctness you might want to add it there :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T12:21:44.147", "Id": "512543", "Score": "1", "body": "Hi, thank you for welcome and pointing out the error. Fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T14:34:02.147", "Id": "512560", "Score": "1", "body": "Welcome to Code Review. I have rolled back your edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
{ "AcceptedAnswerId": "259797", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T12:10:39.877", "Id": "259793", "Score": "6", "Tags": [ "python", "singleton" ], "Title": "Singleton metaclass for each argument set compatible with Pickle" }
259793
accepted_answer
[ { "body": "<p>The point of having to define either neither or both of <code>__init__</code> and <code>__reduce_ex__</code> is to set <code>_args</code>.\nHowever you can just set <code>_args</code> in <code>__call__</code> and then use the one you've set in your <code>__reduce_ex__</code>.<br />\n<sub><strong>Note</strong>: untested</sub></p>\n<pre class=\"lang-py prettyprint-override\"><code>class ArgumentSingleton(type):\n __INSTANCES = {}\n\n def __new__(cls, name, bases, class_dict):\n def __reduce_ex__(self, protocol):\n return partial(type(self), *self.__args, **self.__kwargs), ()\n\n def __init__(self, *args, **kwargs):\n pass\n\n class_dict.setdefault('__init__', __init__)\n class_dict.setdefault('__reduce_ex__', __reduce_ex__)\n return super().__new__(cls, name, bases, class_dict)\n\n def __call__(cls, *args, **kwargs):\n key = (cls, args, frozendict(kwargs))\n if None is (self := cls.__INSTANCES.get(key)):\n self = cls.__INSTANCES[key] = super().__call__(cls, *args, **kwargs)\n self.__args, self.__kwargs = key[1:]\n return self\n</code></pre>\n<p>Now we should be able to see we can just stop defining a metaclass by;</p>\n<ol>\n<li>changing <code>__call__</code> to <code>__new__</code>, and</li>\n<li>defining a default <code>__reduce_ex__</code> on the base class.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>from frozendict import frozendict\nfrom functools import partial\n\nclass Singleton:\n __INSTANCES = {}\n\n def __new__(cls, *args, **kwargs):\n key = (cls, args, frozendict(kwargs))\n if None is (self := cls.__INSTANCES.get(key)):\n self = cls.__INSTANCES[key] = super().__new__(cls)\n self.__args, self.__kwargs = key[1:]\n return self\n\n def __reduce_ex__(self, protocol: int):\n return partial(type(self), *self.__args, **self.__kwargs), ()\n\nclass A(Singleton):\n pass\n\n\n# passes all your tests and the following one\na = A(&quot;hi&quot;)\nb = pickle.loads(pickle.dumps(a))\nassert a is b\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T14:21:46.707", "Id": "512554", "Score": "0", "body": "Thanks for your answer. However it gets little problematic when allowing keyword arguments. Please, see my edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T14:26:22.033", "Id": "512556", "Score": "1", "body": "@TomášHons My aim is to simplify your code not change how your code functions. Since your code didn't correctly handle kwargs my changes don't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T14:39:11.847", "Id": "512566", "Score": "0", "body": "Well, I my solution explicitly forbid them, which I see as better than allow them and silently introduce weird behavior. I pointed that out for anyone who wants to use the solution (me and you included). My intention was not to complain but to raise awareness of the possible problem. Your solution has +1 from me, as it helped me a lot and probably will be accepted (I want let the question open for others for some time)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T14:43:33.333", "Id": "512568", "Score": "0", "body": "@TomášHons Yeah using `frozendict` would be better here as you know. Additionally you are unlikely to have weird gotchas. For example if a subclass change the `__init__` in your code to include `**kwargs` your code has the same issue, without changing to use `frozendict`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T15:22:22.640", "Id": "512574", "Score": "0", "body": "Right, that is true, it's not bullet proof (maybe forbid `__init__` completely). Similarly, I still ponder whether use the `Singleton` should be a class or metaclass. With metaclass it is possible to avoid invoking `__init__` completely when re-using an instance which is probably desirable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T15:40:05.783", "Id": "512579", "Score": "0", "body": "@TomášHons My 2c with the code you've provided I currently see no benefits to using a metaclass that a normal class doesn't allow. However, ensuring `__init__` is only ever called once could be a benefit of using a metaclass, with different/more code. You could just move `__new__` to the metaclass and have like a mix between my two examples above. Additionally I'm confident you can make the right decision, worst case you can ask for another review :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T15:49:46.720", "Id": "512581", "Score": "0", "body": "Right, I agree :) I will just add the `frozendict` to your solution, in order to mark it as accepted with a clear conscience (in case someone will use it in future). Thank you for your work!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T15:18:25.710", "Id": "512715", "Score": "0", "body": "The edit intended to fix the error in the call `super().__call__(cls, *args, **kwargs)`. However, too short edits are forbidden, so I added a note there to fulfill the 'requirements' on edit. Also, the note itself makes sense for anyone who wants to use the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T15:19:16.783", "Id": "512716", "Score": "0", "body": "@TomášHons The note is better served as a comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T15:21:56.513", "Id": "512717", "Score": "0", "body": "Yet, still the original intent to fix the code is valid. So please, remove the `cls` argument, as I do not have the ability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T15:29:06.117", "Id": "512720", "Score": "0", "body": "@TomášHons You're not following the etiquette of Stack Exchange sites. Everyone thinks their edits and opinions are right. And whilst you may be right, the proper course of action is to comment. Two people rejected your edit for misusing the edit button. Please leave your note as a comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T15:44:16.363", "Id": "512730", "Score": "0", "body": "Now I am concerned about fixing the call on the line `self = cls.__INSTANCES[key] = super().__call__(cls, *args, **kwargs)`. I wrote the note **only** because I was not allow post such short edit (though I believe in the message of the note in itself). Now I send another edit to mark my point." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T13:02:09.577", "Id": "259797", "ParentId": "259793", "Score": "5" } } ]
<p>A couple of weeks ago I had to do a coding challenge for a job interview. I did the challenge using Python, the code was working and I got the job. But I would like to know how (if possible) I can improve/refactor the code I've written. The reviewer told my future employer there were too many if statements and that I could have written better code. I guess this is an example of too many if statements:</p> <pre class="lang-py prettyprint-override"><code>def get_row_tax_percentage(product_name: str): exempt = is_exempt(product_name) imported = is_imported(product_name) if exempt and imported: return Decimal(&quot;.05&quot;) elif exempt and not imported: return Decimal(&quot;0&quot;) elif imported: return Decimal(&quot;.15&quot;) else: return Decimal(&quot;.1&quot;) </code></pre> <p>Link to the task description: <a href="https://github.com/xpeppers/sales-taxes-problem" rel="noreferrer">https://github.com/xpeppers/sales-taxes-problem</a></p> <p>Link to my solution: <a href="https://github.com/soulpaul/sales-taxes-solution" rel="noreferrer">https://github.com/soulpaul/sales-taxes-solution</a></p> <p>I think this could be a chance to learn something new. I don't need you guys to write code for me, but please point me to the right direction. Thanks to anyone who is going to spend some time on this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T07:59:57.137", "Id": "512657", "Score": "2", "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)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T11:34:09.447", "Id": "512679", "Score": "2", "body": "Welcome to the Code Review Community and congrats on the new job. In the future please copy the programming challenge into the question so that we understand the requirements. The full code that you want reviewed needs to be embedded in the question, we can use repositories for references, but we can't review code in them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T11:55:47.340", "Id": "512849", "Score": "0", "body": "Just curious: Why `f\"{word.lower()}\"` instead of `word.lower()` [here](https://github.com/soulpaul/sales-taxes-solution/blob/bdb6f8f4ace0168224e1e402f86591492508b327/src/printer.py#L29)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T19:10:48.440", "Id": "512881", "Score": "1", "body": "There's 2 things I don't like about the task, that would probably require it to be different in production code. First I wouldn't want to hard code the values into the code, they should be external to the code. Secondly the production code should probably be able to handle additional taxes (which is what I assume they are). That is their mistake and not your mistake. But if they expected you to ask about it, or they thought it was common sense, it could explain why they complained about the amount of ifs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T15:32:03.850", "Id": "512953", "Score": "0", "body": "@Manuel honestly... it doesn't make sense to me as well. It's probably something due to some kind of refactoring. It's just bad code." } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T13:58:40.217", "Id": "259801", "Score": "15", "Tags": [ "python", "python-3.x" ], "Title": "Having a string representing items in a cart, elaborate taxes and totals. Interview task in Python" }
259801
max_votes
[ { "body": "<p>That really depends on how the task is stated. If it's stated like your code, just in English, with four different (and possibly independent) values, then I'd say your way is actually ok. Because then if one of them changes, you only need to change the value, not rewrite logic.</p>\n<p>But the task description says:</p>\n<blockquote>\n<p><strong>Basic sales tax</strong> is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt. <strong>Import duty</strong> is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions.</p>\n</blockquote>\n<p>So it is in fact stated as two separate taxes that should be determined separately and just added. Make the code's logic reflect the real logic.</p>\n<p>For extra clarity, use the proper names as well. For example:</p>\n<pre><code>def get_row_tax_percentage(product_name: str):\n basic_sales_tax = 10 if not is_exempt(product_name) else 0\n import_duty = 5 if is_imported(product_name) else 0\n return Decimal(basic_sales_tax + import_duty) / 100\n</code></pre>\n<p>Or maybe with <code>0 if is_exempt(product_name) else 10</code>, I can't decide which I find clearer and/or closer to how the task says it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T07:33:52.477", "Id": "512651", "Score": "1", "body": "I omitted to write the task description because it was way too long to include. I should have added a reference, you are right, especially since I was looking for more feedback on the other part of the code as well. Thanks for your time and your precious answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T15:04:08.633", "Id": "259805", "ParentId": "259801", "Score": "21" } } ]
<p>I am trying to write a python script that can search through Fortran code ignoring comments. I didn't find a simple way of doing this using grep. So I startwed writing my own.</p> <p>The rules for comments that I am following are:</p> <ol> <li>the first character is not a space or a number. It is usually a c, C but I've seen * and other variations</li> <li>the above condition can be violated if its a fortran90/95 code in that case, its complicated so I am not treating that case for now.</li> <li>the first non-space character is a &quot;!&quot;</li> </ol> <p>I could not find a simple solution that ignores all types of fortran comments in text so I started writing my own in python 2.x. It looks dirty but works in many cases.</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/python import sys def fgrep(file_name, cond): first_valid_chars=tuple(range(0,10 )) + (' ',) with open(file_name, 'r') as f: for line in f: if line[0] in first_valid_chars: line1 = line.strip() if line1: # ignore empty lines if line1[0] != '!': # fortran is case insensitive so comparing lower to lower if cond.lower() in line1.lower(): print(line1) if __name__ == &quot;__main__&quot;: print(sys.argv[1]) file_name = sys.argv[1] cond = sys.argv[2] fgrep(file_name, cond) </code></pre> <p>It's drty, not clean and too many indents. How do I clean this up? Because I copy-pasted from editor, there could be errors due to indentation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T18:19:30.680", "Id": "512590", "Score": "0", "body": "@Peilonrayz, probably resulting from copy-pasting from my editor. Can you try now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T18:30:39.623", "Id": "512591", "Score": "0", "body": "Looks runnable now, thank you." } ]
{ "AcceptedAnswerId": "259822", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T17:55:22.080", "Id": "259815", "Score": "1", "Tags": [ "python", "fortran" ], "Title": "Search through fortran source for a string ignoring comments" }
259815
accepted_answer
[ { "body": "<h1>Shebang</h1>\n<p><code>#!/usr/bin/python</code> is not portable, <code>#!/usr/bin/env python</code> is preferred.</p>\n<h1>White Space</h1>\n<p>There should be a blank line between your imports and your function declarations.</p>\n<h1>Efficiency</h1>\n<p>You are constantly converting your <code>cond</code> to lowercase. You don't need to repeatedly do this; just do it once, before the loop.</p>\n<h1>Right Leaning Code</h1>\n<p>As you've mention, the code is way-too right leaning.</p>\n<p>You could fix this with <code>continue</code> type statements ...</p>\n<pre class=\"lang-py prettyprint-override\"><code>def fgrep(file_name, cond):\n first_valid_chars=tuple(range(0,10 )) + (' ',)\n\n # Fortran is case insensitive so comparing lower to lower\n cond = cond.lower()\n with open(file_name, 'r') as f:\n for line in f: \n if line[0] not in first_valid_chars:\n continue\n\n line1 = line.strip()\n if not line1: # ignore empty lines\n continue\n\n if line1[0] == '!':\n continue\n\n if cond in line1.lower():\n print(line1)\n</code></pre>\n<h1>RegEx</h1>\n<p>You could use a Regular Expression to identify comment lines.</p>\n<ul>\n<li><code>\\s*!</code> would find an exclamation mark after any number of spaces.</li>\n<li><code>[^\\d\\s]</code> would match anything but a digit or a white-space character.</li>\n</ul>\n<p>Combined these with the <code>|</code> or-operator, and use <code>.match()</code> to search from the start of the string, and you get an easy comment-line predicate:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def fgrep(file_name, cond):\n # A comment line starts with an exclamation mark as the first non-blank character,\n # or any non-blank character other than a digit as the first character. \n comment = re.compile(r'\\s*!|[^\\d\\s]')\n\n # Fortran is case insensitive so comparing lower to lower\n cond = cond.lower()\n\n with open(file_name, 'r') as f:\n for line in f: \n if not comment.match(line) and cond in line.lower():\n print(line)\n</code></pre>\n<h1>Line numbers</h1>\n<p>You might want to print out the line number of the matching line, to make it easier to find the lines in the file. <code>enumerate</code> would help:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def fgrep(file_name, cond):\n # A comment line starts with an exclamation mark as the first non-blank character,\n # or any non-blank character other than a digit as the first character. \n comment = re.compile(r'\\s*!|[^\\d\\s]')\n\n # Fortran is case insensitive so comparing lower to lower\n cond = cond.lower()\n\n with open(file_name, 'r') as f:\n for line_no, line in enumerate(f, 1): \n if not comment.match(line) and cond in line.lower():\n print(line_no, line, sep=&quot;: &quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T20:38:24.293", "Id": "259822", "ParentId": "259815", "Score": "2" } } ]
<p>I made this super basic autoclicker using Python (v3.7) and the pynput (v1.7.3) library.</p> <p>Are there any changes that you could recommend to make the code more efficient, faster, and overall better?</p> <p>Here's the code:</p> <pre><code>from pynput.keyboard import Controller import time # Autoclicker Functionality def AutoClick(inputClickKey, inputClickAmount, inputClickDelay): keyboard = Controller(); clickAmount = 1; while clickAmount &lt;= inputClickAmount: clickAmount += 1; keyboard.press(inputClickKey) keyboard.release(inputClickKey) time.sleep(inputClickDelay) # User Input KeyInput = input(&quot;Key to be autoclicked: &quot;); ClickAmountInput = int(input(&quot;Number of autoclicks (integer): &quot;)) ClickDelayInput = int(input(&quot;Delay between each autoclick in seconds (integer): &quot;)) # Code Execution AutoClick(KeyInput, ClickAmountInput, ClickDelayInput); </code></pre> <p>and Here's the GitHub repository:</p> <p><a href="https://github.com/SannanOfficial/AutoClickPython" rel="nofollow noreferrer">https://github.com/SannanOfficial/AutoClickPython</a></p> <p>Any sort of critique or suggestion would be appreciated. :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T22:57:57.763", "Id": "512620", "Score": "3", "body": "\"Are there any changes that you could recommend to make the code more efficient, faster\" conflicts with `time.sleep`." } ]
{ "AcceptedAnswerId": "259858", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T22:29:13.400", "Id": "259824", "Score": "1", "Tags": [ "python", "python-3.x", "automation" ], "Title": "Python Autoclicker" }
259824
accepted_answer
[ { "body": "<p>Your code is fairly simple (which is good) and there isn't much to make it &quot;more efficient&quot; or &quot;faster&quot;. There's only a couple of suggestions I have to clean it up and you'll end up with a textbook example of a nice and short Python script that does something useful :)</p>\n<h1>Replace the loop</h1>\n<p>You are using a <code>while</code> loop to control your iterations, but you know beforehand how many times you want to run your code <strong>and</strong> you don't care about the iteration you are at, so you can replace that loop by a more idiomatic one:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(inputClickAmount):\n # ...\n</code></pre>\n<p>People reading this code understand that you want something to run for <code>inputClickAmount</code> times and that you don't care about the number of your iteration.</p>\n<h1>PEP 8 naming conventions</h1>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> is the style guide for Python that recommends that you use <code>snake_case</code> for your variables:</p>\n<ul>\n<li><code>input_click_amount</code> instead of <code>inputClickAmount</code>;</li>\n<li><code>auto_click</code> instead of <code>AutoClick</code>;</li>\n<li>etc.</li>\n</ul>\n<p>Of course being consistent within your code is better than following PEP 8 in some places and not following it in other places, so if your code is part of a larger library, for example, you would want to follow the conventions of that library.\nOtherwise, for your personal projects I can recommend that you use this convention, as it will help your code fit in within the community.</p>\n<h1>Basic error handling</h1>\n<p>This is a possible direction of improvement, and depends on how robust you want your code to become.</p>\n<p>At the end of your script you have a couple of <code>int(input())</code> usages, which raise <code>ValueError</code>s if the user (which I think is you?) types something other than a number. To make a more robust application you would probably want to do some input validation/error handling.\nI suggest you follow a &quot;EAFP&quot; coding style – Easier to Ask Forgiveness than Permition – that is, try to do the conversion with <code>int(input())</code> and only if it fails, handle that, for example by saying something to the user:</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n click_amount_input = int(input(&quot; ... &quot;))\nexcept ValueError:\n print(&quot;The number of clicks should be an integer, defaulting to 1&quot;)\n click_amount_input = 1\n</code></pre>\n<p>(You can read more about the EAFP coding style, and its counterpart LBYL (Look Before You Leap) in <a href=\"https://mathspp.com/blog/pydonts/eafp-and-lbyl-coding-styles?utm_source=codereview\" rel=\"nofollow noreferrer\">this article</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T14:45:10.383", "Id": "512709", "Score": "1", "body": "Thank you very much for the suggestions mate. They were useful and I will most certainly implement them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T15:10:30.937", "Id": "512713", "Score": "2", "body": "+1 This is implicit in the suggested refactoring, but to make it more explicit: while you're refactoring the input, you may want to encapsulate them inside a method like `read_number(question, by_default=1)` so you avoid duplication." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T15:12:30.303", "Id": "512714", "Score": "0", "body": "@fabiofili2pi I see, that as well is a good suggestion and I'll try to implement it as well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T13:32:27.340", "Id": "259858", "ParentId": "259824", "Score": "4" } } ]
<p>I am trying to find a N number of leading zeros from the output of the sha1 hash function. I would like N to go up to 10 or 9. Currently I can get to 7 in about 7 minutes (even though is not always that fast), but already 8 takes forever. The input to the sha1 must be a combination between an input_str and a random generated string.</p> <p>Here is my code:</p> <pre><code>import os import base64 import hashlib import time def gen_keys_06(_urandom=os.urandom, _encode=base64.b64encode): while True: yield _encode(_urandom(4)).decode('ascii') def search_matching_random_str(input_str, zeroes, _sha1=hashlib.sha1): leading_zeros = &quot;0&quot;*zeroes for my_random_str in gen_keys_06(): input_str_my_random_str = &quot;&quot;.join([input_str, my_random_str]) hashval = _sha1(input_str_my_random_str.encode('utf-8')).hexdigest() if hashval[:zeroes] == leading_zeros: return hashval, my_random_str def get_time(input_data, zeroes): start = time.perf_counter() val, random_str = search_matching_random_str(input_data, zeroes) print(f'hash: {val}') print(f'random_str: {random_str}') finish = time.perf_counter() print(f'Finished in {round(finish-start, 2)} seconds(s)') if __name__ == '__main__': first_str = &quot;eTSlASZYlLNgKJuYeIQvGVbiAcLEEOVgAQPzSrtCOIwQxQHyFHcfjgRQJBJDlojx&quot; get_time(first_str, 4) </code></pre> <p>On what should I work to make it faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T09:44:01.087", "Id": "512664", "Score": "0", "body": "@Manuel see the EDIT, try to change the value in `get_time` function up to 10. How long does it take?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T09:52:54.400", "Id": "512665", "Score": "0", "body": "Have you tried [profiling](https://docs.python.org/3/library/profile.html)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T09:54:07.580", "Id": "512666", "Score": "0", "body": "Are you trying to mine crypto? Thought the point of mining was to be slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T09:58:03.703", "Id": "512667", "Score": "0", "body": "Your random string doesn't look fully random to me. It seems to always end with `==`. Is that a requirement somehow? And does it really need to be a random *string*, not random *bytes*? And does it really need to be *random*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T10:03:57.890", "Id": "512668", "Score": "0", "body": "No it is not a requirement. Can also be random bytes. The point is to find a random bytes/string that has more entropy (for that I try to include upper, lower, digits and punctuation). The `==` can be cut by slicing, no improvement though" } ]
{ "AcceptedAnswerId": "259857", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T08:53:40.383", "Id": "259848", "Score": "1", "Tags": [ "python-3.x", "random" ], "Title": "find leading zeros: performance" }
259848
accepted_answer
[ { "body": "<ul>\n<li><code>zeros</code> or <code>zeroes</code>? Better make up your mind and stick with one.</li>\n<li><code>str.join</code> is good when you want to join an iterable. For two strings, just use <code>+</code>.</li>\n<li>Instead of always reencoding and rehashing the input string, you can do it <em>once</em> and then <em>copy</em> the resulting hasher (state) for different extensions.</li>\n<li>Instead of creating random bytes and then elaborately turning them into a string and back to bytes, just use the bytes. Since that's also just a single function call, you can ditch your <code>gen_keys_06</code> and its overhead.</li>\n<li><code>str.startswith</code> is at least simpler, don't know about speed.</li>\n<li>For measuring performance, create a benchmark that runs the function much more than just once, as a single time is rather random. Or change the function so it tries a fixed number of random extensions (let's say a million) instead of stopping at the first successful one.</li>\n<li>You ask us <em>&quot;On what should I work to make it faster?&quot;</em>. That's a question to ask a <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\">profiler</a>.</li>\n<li>Producing random values takes time. Check the profiler's results (or leave out the randomness when doing the million-extensions thing) to see whether it's significant here. If it is, maybe try a different randomness source (I think I've seen someone say that <code>os.urandom</code> is slow on Linux). Or if you don't actually need randomness, try increasing bytes instead.</li>\n<li>Do you really want zero-<em>nibbles</em>? Or would zero-<em>bytes</em> work as well, i.e., are you maybe really only interested in even numbers of zero-nibbles? Then you could use <code>digest</code> instead of <code>hexdigest</code>, which is probably faster because bytes are probably what the hasher actually works with and because it makes digests half as large and you'd check for fewer zeros.</li>\n</ul>\n<p>A version incorporating some of those points:</p>\n<pre><code>def search_matching_random_str(input_str, zeros, _sha1=hashlib.sha1, _urandom=os.urandom):\n leading_zeros = &quot;0&quot; * zeros\n hasher_copy = _sha1(input_str.encode()).copy\n while True:\n my_random_bytes = _urandom(4)\n hasher = hasher_copy()\n hasher.update(my_random_bytes)\n hashval = hasher.hexdigest()\n if hashval.startswith(leading_zeros):\n return hashval, my_random_bytes\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T13:25:13.333", "Id": "512698", "Score": "0", "body": "Thanks a lot for you comments. I think the last is a very good point. Working with bytes, end so `digest` would make it faster. So I will go that way" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T12:55:20.210", "Id": "259857", "ParentId": "259848", "Score": "3" } } ]
<p>I have this code:</p> <pre><code>Sorted=False while not Sorted: Sorted=True for x,y in enumerate(List[:-1]): if List[x]&gt;List[x+1]: List[x],List[x+1]=List[x+1],List[x] Sorted=False </code></pre> <p>However the use of</p> <pre><code>Sorted=True/False </code></pre> <p>being repeated is quite ugly and it would be much nicer to write the code is something similar to:</p> <pre><code>while True: for x,y in enumerate(List[:-1]): if List[x]&gt;List[x+1]: List[x],List[x+1]=List[x+1],List[x] break else:break </code></pre> <p>The only problem is that breaking from the loop this early causes the loop to be repeated many more times taking up more time overall. Are there any ways around this to make the code more pythonic or do I just need to leave it as ugly as it is?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T21:18:24.480", "Id": "512786", "Score": "3", "body": "Hi and welcome to CodeReview. Unfortunately, `List` is missing. While its name indicates that it's a usual Python list, several other collections in Python also provide an iterator interface as well as (range-based) indexing. Also, keep in mind that while reviewers *might* answer additional questions, it's not mandatory. Asking for other ways is inherently off-topic, so you might want to remove your question or rephrase it into a concern. Last but not least, you probably want to tag your question with [tag:reinventing-the-wheel] and [tag:comparative-review]. I hope you get nice reviews :)." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T20:48:19.787", "Id": "259877", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "How would I make this bubble sort more pythonic?" }
259877
max_votes
[ { "body": "<p>One approach is to move most of the logic into a helper function that does the\nswapping and returns the N of swaps. The outer part of the algorithm then\nreduces to almost nothing.</p>\n<p>While you're at it: (1) use conventional names for Python variables (lowercase\nfor variables, capitalized for classes, uppercase for constants); (2) let your\noperators breathe for readability, (3) take full advantage of <code>enumerate()</code>,\nwhich gives both index and value (<code>x1</code>), (4) use convenience variables to make\ncode more readable (<code>x2</code> rather that repeated uses of <code>xs[i + 1]</code>); (5)\nlook for ways to pick simple variable names that help the reader understand the\nalgorithm (<code>i</code> for an index; <code>xs</code> for a list of values; <code>x1</code> and <code>x2</code> for\nindividual values that are being swapped) rather than purely abstract variable\nnames that convey nothing substantive to the reader (<code>List</code>, <code>x</code> for an\nindex, and <code>y</code> for a value); and (6) put your sort in a proper function.</p>\n<pre><code>def bubble_sort(xs):\n while bubble(xs):\n pass\n\ndef bubble(xs):\n n_swaps = 0\n for i, x1 in enumerate(xs[:-1]):\n x2 = xs[i + 1]\n if x1 &gt; x2:\n xs[i] , xs[i + 1] = x2, x1\n n_swaps += 1\n return n_swaps\n\nvals = [9, 3, 4, 2, 6, 8, 10, 1]\nbubble_sort(vals)\nprint(vals)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T01:12:16.047", "Id": "512803", "Score": "0", "body": "Nice review. But how `xs` would help the reader to understand that it's a list of values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T02:05:38.110", "Id": "512808", "Score": "1", "body": "Also, counting the swaps is unnecessary, a flag would be enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T02:43:30.567", "Id": "512812", "Score": "0", "body": "@Marc Yes, adjust as needed. The truth evaluation is the same and bubble() could be used for something else in our bUbBle-SoRt library. More seriously, `xs` is a conventional name for exactly this purpose: one `x`, many `xs` (especially in contexts where the values are generic in some sense). It's ubiquitous in functional programming, for example, and works great in Python -- if applied with good sense." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-22T21:54:06.623", "Id": "259879", "ParentId": "259877", "Score": "2" } } ]
<p>I have a set of Italian words in a <code>txt</code> file hosted on GitHub. I use it as stopwords vocabulary for further NLP tasks.</p> <p>When I dump from GitHub it returns me, obviously, also <code>\n</code></p> <p>Better or more efficient way to replace the special character compared with my working code?</p> <pre><code>import urllib.request stopwords_link = &quot;https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt&quot; file_name = urllib.request.urlopen(stopwords_link) list_nowords = [x.decode(&quot;utf-8&quot;) for x in file_name] splitted = [x.split('\n')[0] for x in list_nowords] </code></pre> <p>As usual I am a self-taught and this is the best place where I can learn, discover new ways and aspects on how to code efficiently with Python</p>
[]
{ "AcceptedAnswerId": "259896", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T09:04:30.750", "Id": "259895", "Score": "4", "Tags": [ "python", "performance" ], "Title": "Remove \\n newline from a list of string dumped from github used for a Italian stopwords vocabulary" }
259895
accepted_answer
[ { "body": "<p>Code is very readable, and that's a good start.</p>\n<p><code>file_name</code> is in fact the file_content; <code>splitted</code> (split) should be just <code>stop_words</code>; <code>stopwords_list</code> is a constant, so by PEP 8, should be uppercase <code>STOPWORDS_LIST</code>.</p>\n<p>The problem I see here is that you are decoding each word, when in fact you should decode the whole file, just once.</p>\n<p>This is just personal preference, but I tend to always use the <code>requests</code> library, because, in my experience, is always a step ahead of what I need. <code>requests</code> tries to understand the encoding, based on the response, so there should be no need to decode.</p>\n<p>A bit of data validation is also needed. The file could have been moved, the network or Github could be down, so it always better to be prepared for the worse. In this case, if the network is down (Connection Timeout) or the file is not there (404) there isn't a big difference: your application should handle the exception and the execution should not proceed.\nWhile a connection timeout would normally raise an exception, a 404 (or any other HTTP error) would still be considered a valid HTTP response, that's why <code>requests</code> has a handy method when you just want 2** responses: <code>raise_for_status</code>.</p>\n<p>Then, to remove the <code>\\n</code> there is actually the method <code>splitlines()</code> which is exactly what you need.</p>\n<pre><code>import requests\n\nSTOPWORDS_LIST= &quot;https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt&quot;\n\ntry:\n response = requests.get(STOPWORDS_LIST)\n response.raise_for_status() \n file_content = response.text\n words = file_content.splitlines()\nexcept Exception as e:\n print(f&quot;There was an error: {str(e)}&quot;)\n\n\n\n</code></pre>\n<p>This piece of code should put inside a function, so it is clearer what it does and restrict its scope. I'm also adding a type to the function, that can be useful to avoid errors at compile time. Maybe some day you will have stopwords in other languages, so I'm just writing a main as example.</p>\n<pre><code>from typing import List\n\nimport requests\n\n\ndef download_stop_words(url: str) -&gt; List[str]:\n try:\n response = requests.get(url)\n response.raise_for_status()\n return response.text.splitlines()\n except Exception as e:\n print(f&quot;There was an error: {str(e)}&quot;)\n\nif __name__ == '__main__': # this avoids the program being executed when the module is imported \n STOP_WORDS = {\n &quot;it&quot;: &quot;https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt&quot;\n }\n for lang, url in STOP_WORDS.items():\n stop_words = download_stop_words(url)\n print(f&quot;In '{lang}' there are {len(stop_words)} stop words&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T07:58:01.747", "Id": "512925", "Score": "0", "body": "no, it wasn't part of a biggere piece of code :D It was just a basic Colab Notebook for practice with Natural Language Processing. What should be \"main scope check\" (I don't have testing knowledge and I started a course about it)? Thank you for your time and energy :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T12:26:53.403", "Id": "513016", "Score": "0", "body": "Hi @AndreaCiufo I've updated the answer, putting the code in a function and with a main as example." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T09:37:05.307", "Id": "259896", "ParentId": "259895", "Score": "6" } } ]
<p>I have a set of Italian words in a <code>txt</code> file hosted on GitHub. I use it as stopwords vocabulary for further NLP tasks.</p> <p>When I dump from GitHub it returns me, obviously, also <code>\n</code></p> <p>Better or more efficient way to replace the special character compared with my working code?</p> <pre><code>import urllib.request stopwords_link = &quot;https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt&quot; file_name = urllib.request.urlopen(stopwords_link) list_nowords = [x.decode(&quot;utf-8&quot;) for x in file_name] splitted = [x.split('\n')[0] for x in list_nowords] </code></pre> <p>As usual I am a self-taught and this is the best place where I can learn, discover new ways and aspects on how to code efficiently with Python</p>
[]
{ "AcceptedAnswerId": "259896", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T09:04:30.750", "Id": "259895", "Score": "4", "Tags": [ "python", "performance" ], "Title": "Remove \\n newline from a list of string dumped from github used for a Italian stopwords vocabulary" }
259895
accepted_answer
[ { "body": "<p>Code is very readable, and that's a good start.</p>\n<p><code>file_name</code> is in fact the file_content; <code>splitted</code> (split) should be just <code>stop_words</code>; <code>stopwords_list</code> is a constant, so by PEP 8, should be uppercase <code>STOPWORDS_LIST</code>.</p>\n<p>The problem I see here is that you are decoding each word, when in fact you should decode the whole file, just once.</p>\n<p>This is just personal preference, but I tend to always use the <code>requests</code> library, because, in my experience, is always a step ahead of what I need. <code>requests</code> tries to understand the encoding, based on the response, so there should be no need to decode.</p>\n<p>A bit of data validation is also needed. The file could have been moved, the network or Github could be down, so it always better to be prepared for the worse. In this case, if the network is down (Connection Timeout) or the file is not there (404) there isn't a big difference: your application should handle the exception and the execution should not proceed.\nWhile a connection timeout would normally raise an exception, a 404 (or any other HTTP error) would still be considered a valid HTTP response, that's why <code>requests</code> has a handy method when you just want 2** responses: <code>raise_for_status</code>.</p>\n<p>Then, to remove the <code>\\n</code> there is actually the method <code>splitlines()</code> which is exactly what you need.</p>\n<pre><code>import requests\n\nSTOPWORDS_LIST= &quot;https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt&quot;\n\ntry:\n response = requests.get(STOPWORDS_LIST)\n response.raise_for_status() \n file_content = response.text\n words = file_content.splitlines()\nexcept Exception as e:\n print(f&quot;There was an error: {str(e)}&quot;)\n\n\n\n</code></pre>\n<p>This piece of code should put inside a function, so it is clearer what it does and restrict its scope. I'm also adding a type to the function, that can be useful to avoid errors at compile time. Maybe some day you will have stopwords in other languages, so I'm just writing a main as example.</p>\n<pre><code>from typing import List\n\nimport requests\n\n\ndef download_stop_words(url: str) -&gt; List[str]:\n try:\n response = requests.get(url)\n response.raise_for_status()\n return response.text.splitlines()\n except Exception as e:\n print(f&quot;There was an error: {str(e)}&quot;)\n\nif __name__ == '__main__': # this avoids the program being executed when the module is imported \n STOP_WORDS = {\n &quot;it&quot;: &quot;https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt&quot;\n }\n for lang, url in STOP_WORDS.items():\n stop_words = download_stop_words(url)\n print(f&quot;In '{lang}' there are {len(stop_words)} stop words&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T07:58:01.747", "Id": "512925", "Score": "0", "body": "no, it wasn't part of a biggere piece of code :D It was just a basic Colab Notebook for practice with Natural Language Processing. What should be \"main scope check\" (I don't have testing knowledge and I started a course about it)? Thank you for your time and energy :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T12:26:53.403", "Id": "513016", "Score": "0", "body": "Hi @AndreaCiufo I've updated the answer, putting the code in a function and with a main as example." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T09:37:05.307", "Id": "259896", "ParentId": "259895", "Score": "6" } } ]
<p>I am trying to calculate some values using numpy. Here is my code,</p> <pre><code>x= np.zeros([nums]) for i in range (nums): x[i] = np.mean((Zs[i :] - Zs[:len(Zs)-i]) ** 2) </code></pre> <p>The code runs perfectly and give desired result. But it takes very long time for a large number <code>nums</code> value. Because the <code>Zs</code> and <code>nums</code>value having same length. Is it possible to use some other method or multiprocessing to increase the speed of calculation?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T13:27:42.777", "Id": "513601", "Score": "2", "body": "How are you sure that this is where the code is slow? Have you profiled the entire program? For us to help you optimize the code we need to understand more about what the code does." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T08:04:01.983", "Id": "259927", "Score": "-1", "Tags": [ "python", "numpy" ], "Title": "Speed up calculation time of for loop in numpy" }
259927
max_votes
[ { "body": "<h1>Minor style edits</h1>\n<p>Like you said, the code seems to be perfectly fine and I don't see a very obvious way to make it faster or more efficient, as the consecutive computations you are making in your <code>for</code> loop don't seem to be easy to relate to one another.</p>\n<p>Of course this is just my input after thinking for some time, other people may have clever suggestions I can't come up with.</p>\n<p>However, I would make <em>minor</em> edits to your code, for the sake of homogenisation:</p>\n<pre class=\"lang-py prettyprint-override\"><code>x = np.zeros(Zs.shape)\nfor i in range(len(Zs)): \n x[i] = np.mean((Zs[i:] - Zs[:-i])**2)\n</code></pre>\n<p>For the snippet of code we have, it is not clear the relationship between <code>nums</code> and <code>Zs</code> and so it makes more sense to have the loop in terms of <code>Zs</code>.</p>\n<p>Also, notice that the right term of the subtraction I replaced <code>Zs[:len(Zs)-i]</code> with <code>Zs[:-i]</code>, which is a nice feature of Python that is worth getting used to, you can learn about <a href=\"https://mathspp.com/blog/pydonts/sequence-indexing#negative-indices?utm_source=codereview\" rel=\"nofollow noreferrer\">using negative indices in Python</a>.</p>\n<p>Other minor things were just fixing spacing. If you want, take a look at the <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">PEP 8</a> style guide for Python :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T08:59:49.397", "Id": "512927", "Score": "0", "body": "thank you for your comment. Zs and nums having the same length so using that range in for loop are perfectly fine." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T08:49:28.127", "Id": "259930", "ParentId": "259927", "Score": "4" } } ]
<p>I've been assigned the following Python homework:</p> <blockquote> <p>Implement myrange that acts like <code>range</code> using iterators. Define a function <code>myrange</code>and define a class <code>MyRange</code>.</p> </blockquote> <p>We've just seen iterators, so I think I'm asked to use them. I am not required to write a sophisticated code, but only something that allows the range-for loop syntax.</p> <p>Professor said that, roughly, an iterator is an object for which the dunder method <code>__next__</code> is provided. I've seen there are similar questions here. However, none of them is defining the <code>__next__</code> method in a class.</p> <hr /> <p>So, here's what I did: first I implemented <code>MyRange</code> class and then <code>my range</code>. After that, I did two tests.</p> <p><strong>Question:</strong> It works, but I'd like to be sure from you if I solved correctly the question, I mean, if this is what I was supposed to do :-) As I said, I've just seen what is an iterator.</p> <pre><code>class MyRange(): def __init__(self,data): self.data = data self.check() self.index = -1 def check(self): assert len(self.data)&gt;0, &quot;Not enough data&quot; def __iter__(self): return self def __next__(self): if self.index == len(self.data)-1: raise StopIteration self.index= self.index+1 return self.data[self.index] def my_range(*args): return MyRange((args)) print(&quot;Tests using MyRange class \n&quot;) for i in MyRange((1,2,3,4)): print(i) print(&quot;Tests with range for loop \n&quot;) for i in my_range(1,2,3,4,5,&quot;Hello&quot;): print(i) r = MyRange((1,2,3,4,&quot;Last Value&quot;)) print(next(r)) print(next(r)) print(next(r)) print(next(r)) print(next(r)) print(next(r)) </code></pre> <p>I'll show here the output, which seems the correct one:</p> <pre><code>1 2 3 4 Tests with range for loop 1 2 3 4 5 Hello 1 2 3 4 Last Value Traceback (most recent call last): File &quot;Untitled3.py&quot;, line 45, in &lt;module&gt; print(next(r)) #&lt;-- Raises StopIteration File &quot;Untitled3.py&quot;, line 16, in __next__ raise StopIteration StopIteration </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T17:25:04.010", "Id": "513042", "Score": "3", "body": "If `myrange()` is supposed to act like `range()`, shouldn't it take similar arguments: `start`, `stop`, and `step`? It doesn't seem like your implementation is following the instructions, but you obviously have more context than I do. A range is a device to generate integers (integers often used to index into a data collection), but you have implemented `myrange()` to take the data collection itself as an argument. Perhaps you can edit your question to clarify." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T18:37:33.997", "Id": "513047", "Score": "0", "body": "@FMc Unfortunately the text of the assignment was the short one I wrote at the beginning of my post. So far what we know is only that we need to use `__next__` in our class. I think I can fix this point. For the moment, assuming that the class `MyRange` is correct, do you think that `my_range` is implemented correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T19:36:38.603", "Id": "513053", "Score": "0", "body": "The assignment seems to be asking to implement `range` two different ways (1) as a function (e.g. using `yield` in a loop), and (2) as a class (e.g. having `__iter__` and `__next__` methods)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T19:36:42.403", "Id": "513054", "Score": "0", "body": "No, based on my reading of the assignment, I think both `MyRange` and `my_range()` are incorrect. You have successfully implemented an iterable object (`MyRange`), but it is **not** an iterable object that behaves at all like `range()`." } ]
{ "AcceptedAnswerId": "259993", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T16:07:05.100", "Id": "259987", "Score": "2", "Tags": [ "python", "python-3.x", "object-oriented", "iterator", "interval" ], "Title": "Implement a range behaviour in Python using iterators" }
259987
accepted_answer
[ { "body": "<h1>You have an iterator</h1>\n<p>Your code implements an iterator, you are right. You have defined a <code>__next__</code> method and it works well.</p>\n<p>I would tweak your code slightly, though:</p>\n<ul>\n<li>remove the <code>check</code> because iterators can be empty and that is okay;</li>\n<li>fix minor spacing issues around operators, etc;</li>\n<li>use augmented assignment to increment;</li>\n<li>change order of statements in <code>__next__</code> to be more idiomatic.</li>\n</ul>\n<p>All in all, <code>MyRange</code> would end up looking like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class MyRange():\n def __init__(self,data):\n self.data = data\n self.index = -1\n \n def __iter__(self):\n return self\n \n def __next__(self):\n self.index += 1\n if self.index == len(self.data):\n raise StopIteration\n return self.data[self.index]\n</code></pre>\n<p>In particular, the changes to <code>__next__</code> are because you start by setting <code>self.index</code> to the value of the index <em>you would like to read</em>. Then, just before reading the value from <code>data</code>, you ensure you can actually use that index and raise <code>StopIteration</code> if you can't.</p>\n<h1><code>range</code> is not any iterator</h1>\n<p>However, the &quot;problem statement&quot; says to implement an iterator <em>that behaves like <code>range</code></em>, and as brought to your attention in the comments, <code>range</code> is a very specific iterator that can take up to 3 arguments: <code>start</code>, <code>stop</code>, and <code>step</code>.</p>\n<p>Take a look at the docs for the range function <a href=\"https://docs.python.org/3/library/functions.html#func-range\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Having said that, solving this &quot;issue&quot; does not need to be very difficult.\nYou could do something as simple as having <code>my_range</code> take the three arguments,\ngenerate the <code>data</code> you need, and then feed it into <code>MyRange</code> to iterate, but that seems like a waste.</p>\n<p>What <em>I think</em> is more or less the intended approach, is to define <code>MyRange</code> to expect the <code>start</code>, <code>stop</code>, and <code>step</code> values, and the <code>my_range</code> function is what the user calls, which then fills in the <code>start</code>, <code>stop</code>, and <code>step</code> values that are used by default and calls <code>MyRange</code>.</p>\n<p>E.g.,</p>\n<ul>\n<li><code>my_range(10)</code> would call <code>MyRange(0, 10, 1)</code>;</li>\n<li><code>my_range(4, 12)</code> would call <code>MyRange(4, 12, 1)</code>;</li>\n<li><code>my_range(0, 13, -3)</code> would call <code>MyRange(0, 13, -3)</code>.</li>\n</ul>\n<p>(In the examples above, I assumed you changed <code>MyRange</code> to do what I described.)</p>\n<p>Therefore, just for the sake of clarity: what would be happening is that the <code>__next__</code> method would use the three arguments <code>start</code>, <code>stop</code>, and <code>step</code> (and possibly other auxiliary variables you create) to <em>compute</em> the successive values, instead of generating all of them at once and then returning one by one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T06:35:31.073", "Id": "513087", "Score": "0", "body": "Thanks for your answer, I got the point! So the signature of `my_range` should be `my_range(start, stop,step)` too, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T06:37:03.880", "Id": "513088", "Score": "0", "body": "@bobinthebox yes, that is _my interpretation_ of the problem statement :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T06:37:53.003", "Id": "513089", "Score": "0", "body": "Thanks, I'll try to fix this :-) @RGS" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T06:39:46.717", "Id": "513090", "Score": "0", "body": "@bobinthebox good luck! But sorry, just to be clear, probably your `my_range` function also has to work with a single argument, `my_range(stop)` and two arguments, `my_range(start, stop)`, just like `range` does, yeah?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T07:34:42.917", "Id": "513107", "Score": "0", "body": "I agree, I should use default arguments to achieve this behaviour, right? @RGS" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T08:31:50.973", "Id": "513112", "Score": "0", "body": "Yes @bobinthebox , default arguments are probably the way to go here. Just be careful with what values you choose as the default arguments ;)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T19:15:51.563", "Id": "259993", "ParentId": "259987", "Score": "2" } } ]
<p>This small programme is an exercise that my teacher gave us.</p> <p><code>n</code> is an alphabetic input that its length must be between 5 and 10. You have to insert the characters of the input one by one to a list called <code>T</code>. Then, add the reverse case of letters to another list called <code>V</code>. So if there is a capital letter in <code>T</code> it would be lower in list <code>V</code> and you have to only print <code>V</code> at the end.</p> <p>This is my code, is there any better solution or cleaner one perhaps?</p> <pre><code>T = [] V = [] n = input(&quot;Enter a character&quot;) while len(n) not in range(5, 11) or n.isalpha() == False: n = input(&quot;Enter a characters between 5 and 11, and only characters &quot;) print(n) for i in range(len(n)): T.append(n[i]) for i in range(len(T)): if T[i].isupper(): V.append(T[i].lower()) else: V.append(T[i].upper()) print(V) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T21:54:09.800", "Id": "513060", "Score": "0", "body": "Welcome to Code Review! The current question title 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." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T22:20:23.943", "Id": "513062", "Score": "2", "body": "Your \"*N is a alphabetic input that is between 5 and 10*\" does not really make sense. Are you sure you copied your task correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T23:02:32.217", "Id": "513065", "Score": "0", "body": "N is basically a string input that have 5 characters atleast and doesn't go beyond 10 characters, it should not be numbers or symbols." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T23:02:47.703", "Id": "513066", "Score": "0", "body": "There is no `N` in your code snippet, and it is unclear what \"between 5 and 10\" means." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T23:04:02.630", "Id": "513067", "Score": "0", "body": "i'm sorry if i couldn't explain more clearly, im not a native english speaker." } ]
{ "AcceptedAnswerId": "259999", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T21:45:24.660", "Id": "259996", "Score": "3", "Tags": [ "python" ], "Title": "Get 5 to 10 characters and flip their case" }
259996
accepted_answer
[ { "body": "<p>A flexible approach to getting user input is to use a while-true loop, breaking\nwhen conditions are met. The structure is easy to remember and allows you to\nhandle user mistakes without awkward setup or code repetition:</p>\n<pre><code>while True:\n x = input('...')\n if x is OK:\n break\n</code></pre>\n<p>I realize the variable names are coming from your teacher's instructions, but\nboth of you should strive for better variable names. Better does not always\nmean longer (brevity and clarity are both worthy goals and they are at odds\nsometimes); but it does mean using variable names that are <em>meaningful\nin context</em>. For example, <code>letters</code> is a better name for a string of letters\nthan <code>n</code>, which is a purely abstract name (even worse, it adds confusion\nbecause <code>n</code> is often/conventionally used for numeric values).</p>\n<p>There is no need to build <code>T</code> character by character. Python strings are\niterable and therefore directly convertible to lists.</p>\n<p>Python strings, lists, and tuples are directly iterable: just iterate over the\nvalues and don't bother with the soul-crushing tedium imposed by many less-cool\nprogramming languages where you must iterate over indexes. And for cases when\nyou need both values and indexes, use <code>enumerate()</code>.</p>\n<p>Use simple comments as sign-posts and organizational devices to make\nyour code more readable. This habit will serve you well as you try\nto write bigger, more complex programs.</p>\n<pre><code># Get user input.\nwhile True:\n prompt = 'Enter 5 to 10 letters, without spaces or punctuation: '\n letters = input(prompt)\n if len(letters) in range(5, 11) and letters.isalpha():\n break\n\n# List of the original letters.\nT = list(letters)\n\n# List of letters with case flipped.\nV = []\nfor c in letters:\n c2 = c.lower() if c.isupper() else c.upper()\n V.append(c2)\n\n# Same thing, in one shot.\nV = [\n c.lower() if c.isupper() else c.upper()\n for c in letters\n]\n\n# Check.\nprint(T) \nprint(V) \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T23:00:01.080", "Id": "513064", "Score": "0", "body": "Writing comments really came in handy, I am working on this keylogger, i end up giving up because its a 110 line and its literally a mess. I truly appreciate your help, you deserve to be a teacher." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-25T22:55:28.447", "Id": "259999", "ParentId": "259996", "Score": "5" } } ]
<p>I am trying to filter the events table to get ongoing events and complete events, but pycharm keeps underlining my code because of duplicated code. How do I prevent for loop code duplicates on the two functions below? Better yet, how do I optimally refactor these two functions? Thanks</p> <pre><code> def get_ongoing_events(): ongoing_events = Events.objects.filter( Q(event_begin_datetime__lte=current_time), Q(event_end_datetime__gt=current_time), ) for event in ongoing_events: event.event_status = 'ongoing' event.save() event.venue.status = 'booked' event.venue.save() reserve_data = dict() reserve_data[&quot;sensor_id&quot;] = event.venue.sensor_id reserve_data[&quot;status&quot;] = event.venue.status return reserve_data def get_complete_reservation(): &quot;&quot;&quot; Update reservations and sensors :return: &quot;&quot;&quot; completed_events = Events.objects.filter( Q(reservation_begin_datetime__lt=current_time), Q(reservation_end_datetime__lte=current_time), ) for event in completed_events: event.reservation_status ='complete' event.save() event.venue.status = 'free' event.venue.save() reserve_data = dict() reserve_data[&quot;sensor_id&quot;] = event.venue.sensor_id reserve_data[&quot;status&quot;] = event.venue.status return reserve_data <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T07:30:44.427", "Id": "513100", "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)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T07:30:56.687", "Id": "513101", "Score": "6", "body": "Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." } ]
{ "AcceptedAnswerId": "260014", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T06:42:13.970", "Id": "260012", "Score": "1", "Tags": [ "python-3.x" ], "Title": "I am trying to filter a queryset based on dates, I keep getting a duplicate error on the for loops,How do I refactor these code to remove duplicates?" }
260012
accepted_answer
[ { "body": "<h1>Factoring duplication out</h1>\n<p>Whenever I have (near-)duplicate code, what I do is take a look at the repeated code. The parts that change ever so slightly are going to be controlled with arguments to functions and etc, whereas the parts that remain the same will just be left more-or-less as-is.</p>\n<p>Having said that, here is what I see:</p>\n<ul>\n<li>the queries being used change, so those are function arguments;</li>\n<li>the attributes of the event being updated change, so those are function arguments;</li>\n<li>the final dict being generated is the same, so we leave it the same.</li>\n</ul>\n<p>From your code alone, here is a suggested modification:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def filter_and_update_events(Qs, event_changes, venue_changes):\n for event in Events.objects.filter(*Qs)\n for attr, new_value in event_changes.items():\n setattr(event, attr, new_value)\n event.save()\n for attr, new_value in venue_changes.items():\n setattr(event.venue, attr, new_value)\n event.venue.save()\n\n reserve_data = dict()\n reserve_data[&quot;sensor_id&quot;] = event.venue.sensor_id\n reserve_data[&quot;status&quot;] = event.venue.status\n return reserve_data\n\ndef get_ongoing_events():\n return filter_and_update_events(\n [\n Q(event_begin_datetime__lte=current_time),\n Q(event_end_datetime__gt=current_time),\n ],\n {&quot;event_status&quot;: &quot;ongoing&quot;},\n {&quot;status&quot;: &quot;booked&quot;},\n )\n\ndef get_complete_reservation():\n &quot;&quot;&quot;\n Update reservations and sensors\n :return:\n &quot;&quot;&quot;\n return filter_and_update_events(\n [\n Q(reservation_begin_datetime__lt=current_time),\n Q(reservation_end_datetime__lte=current_time),\n ],\n {&quot;reservation_status&quot;: &quot;complete&quot;},\n {&quot;status&quot;: &quot;free&quot;},\n )\n</code></pre>\n<p>Notice that I used <code>setattr</code> <a href=\"https://docs.python.org/3/library/functions.html#setattr\" rel=\"nofollow noreferrer\">docs</a> to set the attributes of the event and the venue.\nAlso notice that my new function has a bit of duplication in the loops, but that is the easiest way to deal with the fact that <code>venue</code> is inside <code>event</code> and there is no obvious way to use <code>setattr</code> to deal with the nesting.\nIf you need to expand your function to update even more things inside <code>event</code>, then I would also recommend creating a helper function that takes an <code>event</code> and a &quot;setting name&quot; and sets it, so that <code>filter_and_update_events</code> doesn't need to take one dictionary per object inside <code>event</code>.</p>\n<p>Does this make sense?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T12:18:11.877", "Id": "513132", "Score": "0", "body": "If there is already an answer, it might be better not to edit the question, especially the code in the question since everyone needs to be able to see the code as the first reviewer saw it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T08:04:12.620", "Id": "513229", "Score": "0", "body": "This makes sense and works like a charm, thankyou @RGS, just add .index() during filter so as to avoid the unpacking elements error. `for attr, new_value in event_changes.index():`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T08:37:08.707", "Id": "513231", "Score": "1", "body": "@pythonista woops that slipped, I meant `for attr, new_value in event_changes.items():`, and similarly for the venues, sorry for that. Answer has been fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T11:30:43.663", "Id": "513459", "Score": "1", "body": "oops meant .items(), thanks for the fix" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T07:10:21.620", "Id": "260014", "ParentId": "260012", "Score": "1" } } ]
<p>Any suggestions on improving the speed of below code. My dictionary is rather large in fold of * 100000 and expected to grow larger every day.</p> <p>I am open to completely new ideas or approaches to do the below operation.</p> <pre><code>from pyxdameraulevenshtein import damerau_levenshtein_distance, normalized_damerau_levenshtein_distance name = 'john doe' word_dict = { 'john' : ['ID1','ID2', 'AB2' ,'AS1'] ,'doe' : ['ID1','ID4', 'AB2' ,'AS6'] ,'jahn' : ['ID3','ID2', 'AB2' ,'AS5'] } # perform iteration on dictionary keys . compute and filter if damerau edit distance is less than 2 all_matches = [] for nWord in set(name.split()): match = [] match += [(word,list(word_dict[word]), int((1-normalized_damerau_levenshtein_distance(nWord,word))* 100))\ for word in word_dict if damerau_levenshtein_distance(nWord,word) in [0,1,2]] all_matches.append(match) </code></pre>
[]
{ "AcceptedAnswerId": "260151", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T10:38:10.910", "Id": "260023", "Score": "0", "Tags": [ "performance", "python-3.x" ], "Title": "perform fuzzy matching on a large set of dictionary keys" }
260023
accepted_answer
[ { "body": "<p>Take a look at <a href=\"https://en.wikipedia.org/wiki/BK-tree\" rel=\"nofollow noreferrer\">BKTrees</a>. <a href=\"http://nullwords.wordpress.com/2013/03/13/the-bk-tree-a-data-structure-for-spell-checking/\" rel=\"nofollow noreferrer\">Here</a> is a less technical description. There is a Python library on PyPI: <a href=\"https://pypi.org/project/pybktree/\" rel=\"nofollow noreferrer\">pybktree</a>.</p>\n<p>You create the BKTree once (once a day?) from the keys in the dictionary. Then run all the queries against the BKTree.</p>\n<p>It would look something like this untested code:</p>\n<pre><code>import pybktree\nfrom pyxdameraulevenshtein import damerau_levenshtein_distance\n\ntree = pybktree.BKTree(damerau_levenshtein_distance, word_dict.keys())\n\nall_matches = []\n\nfor target in set(name.split()):\n all_matches.extend(tree.find(target, MAX_DISTANCE))]\n</code></pre>\n<p><code>all_matches</code> would be a list of (distance, word) tuples.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T06:21:34.560", "Id": "513784", "Score": "0", "body": "Thank you. This has helped me a lot . Any suggestions on how to store the tree structure ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T06:35:41.243", "Id": "513862", "Score": "0", "body": "@abhilashDasari, you can use the `pickle` module from the standard library to save it to orload it from a file." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T07:01:51.837", "Id": "260151", "ParentId": "260023", "Score": "1" } } ]
<p>I want to implement a function <code>take_upto_n(A, n)</code> such that for e.g.</p> <pre><code>take_upto_n([1,2,3,4], 8) returns [1,2,3,2] take_upto_n([1,2,4,3], 8) returns [1,2,4,1] take_upto_n([1,2,3,4], 100) returns [1,2,3,4] take_upto_n([1,2,3,4], 3) returns [1,2,0,0] </code></pre> <p>Assume <code>A</code> contains non-negative values only. n is also non-negative</p> <p>This is straightforward with a loop</p> <pre><code>def take_upto_n(A, n): out = [] for x in A: out += [min(n, x)] n -= min(n, x) return out </code></pre> <p>We can also do this with numpy, but this I.M.O. is fairly unreadable:</p> <pre><code>def take_upto_n(A, n): A = np.array(A) return np.clip(n + A - np.cumsum(A), 0, A) </code></pre> <p>Is there some standard function that does this - couldn't find it myself (or didn't know how to search)?</p> <p>If there isn't any such function, any advice on how to make it not look like &quot;what is this?&quot; (the <code>n + A - np.cumsum(A)</code> is the real killer)?</p>
[]
{ "AcceptedAnswerId": "260061", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-26T20:39:30.807", "Id": "260048", "Score": "3", "Tags": [ "python", "numpy" ], "Title": "Selecting a quantity from a list" }
260048
accepted_answer
[ { "body": "<p>Your regular Python implementation generally looks reasonable, and unless numpy\noffers a performance boost that you really need, I would not recommend it for\nthis use case: the brevity/clarity tradeoff seems bad.</p>\n<p>My biggest suggestion is to consider clearer names. A function with signature\nof <code>take_upto_n(A, n)</code> makes me think the function takes an iterable and\nreturns a sequence of <code>n</code> values. Something like <code>take_upto_sum(A, total)</code>\nseems more communicative to me. And even &quot;take&quot; isn't quite right: take\nimplies a filtering process (we'll take some and leave some). But we\nare limiting or capping. Perhaps you can think of something even better.</p>\n<p>This example presents a classic Python dilemma: you want to do a simple map\nover a list to generate a new list, so of course you would like to knock it out\nin a comprehension or something equally cool. But while iterating,\nyou also need to modify some other variable to keep track of state, and Python\nmostly lacks the assignments-as-expression idiom that allows such trickery in\nother languages (for example, old-school Perl map/grep one-liners and their\nilk). If you are using a sufficiently modern Python, you can use the walrus\noperator to compress the code a bit, but it doesn't get you all the way there.\nHonestly, I wouldn't even bother with the walrus (but I would assign <code>min()</code> to\na convenience variable to avoid repetition and thus help readability). In any\ncase, the walrus approach:</p>\n<pre><code>def take_upto_sum(A, total):\n out = []\n for x in A:\n out.append(y := min(total, x))\n total -= y\n return out\n</code></pre>\n<p>I suppose it is possible to express this as a single list comprehension if we\ntake advantage of the built-in <code>itertools</code> and <code>operator</code> modules. Like the\nnumpy solution, this approach reminds me of the Spinal Tap quote: <em>It's such a\nfine line between stupid, and uh ... clever</em>.</p>\n<pre><code>from itertools import accumulate\nfrom operator import sub\n\ndef take_upto_sum(A, total):\n return [\n max(min(x, acc), 0)\n for x, acc in zip(A, accumulate(A, sub, initial=total))\n ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T05:27:43.303", "Id": "260061", "ParentId": "260048", "Score": "3" } } ]
<p>I've been practising trying to write my code neater, so decided to build a practice GUI, the code works, However, how could I tidy this up in terms of separating out the different parts of the GUI, such as a separate defs for labels, Combobox etc? or using a function for the 'with open' section.</p> <pre class="lang-py prettyprint-override"><code>from tkinter import* from tkinter.ttk import * root = Tk() class GUI: def __init__(self, master): self.master = master master.title('PATM Generator') master.geometry('+600+300') #Label1 master.label1 = Label(root, text = 'Select test bed:') master.label1.grid(row = 0, column = 0, padx = 10, pady = 5) #Combobox master.combo = Combobox(root) master.combo.grid(row =1, column = 0) master.combo['values'] = (TB) #Label2 master.label2 = Label(root, text = 'Enter TRD index:') master.label2.grid(row = 2, column = 0, padx = 10, pady = 5) #Entry master.entry = Entry(root) master.entry.grid(row = 3, column = 0, padx = 10, pady = 0) #Button master.button = Button(root, text = 'Append to txt') master.button.grid(row = 4, padx = 10, pady = 5) with open('TB.txt') as inFile: TB = [line for line in inFile] def main(): GUI(root) root.mainloop() main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T10:09:10.107", "Id": "513239", "Score": "0", "body": "the comments do not add additional information, I would just remove them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T06:19:54.523", "Id": "513425", "Score": "1", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". e.g. _PATM generator_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T17:32:15.030", "Id": "513746", "Score": "0", "body": "[I edited the title](https://codereview.stackexchange.com/revisions/260066/3) so it describes the code. Feel free to [edit] it if you feel there is a more appropriate title." } ]
{ "AcceptedAnswerId": "260283", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T09:43:09.407", "Id": "260066", "Score": "4", "Tags": [ "python", "tkinter", "gui", "user-interface" ], "Title": "PATM Generator GUI" }
260066
accepted_answer
[ { "body": "<p>You didn't give an example of your text file, maybe that would shed some light on the use of a combo box instead of a text widget.\nYou started out with using self in your class but soon used master.</p>\n<blockquote>\n<p>master.combo = Combobox(root)</p>\n</blockquote>\n<p>Using self. prefix allows you to access the objects, widgets and any other data in other functions.</p>\n<pre><code>apple\norange\nbanana\ngrape\ngrapefruit\ntangerine\n</code></pre>\n<p>combo_stuff.txt</p>\n<p>So I'm guessing that you want to add whatever is typed into the entry widget to your text file- Here's one way to accomplish it.</p>\n<pre><code>from tkinter import*\nfrom tkinter.ttk import *\n\n\n\nclass GUI:\n def __init__(self, master):\n self.master = master\n self.master.title('PATM Generator')\n self.master.geometry('+600+300')\n\n #Label1\n self.label1 = Label(root, text = 'Select test bed') \n self.label1.grid(row = 0, column = 0, padx = 10, pady = 5)\n\n #Combobox\n self.combo = Combobox(root)\n self.combo.grid(row =1, column = 0)\n self.combo['values'] = (TB)\n\n #Label2\n self.label2 = Label(root, text = 'Enter TRD index:')\n self.label2.grid(row = 2, column = 0, padx = 10, pady = 5)\n\n #Entry\n self.entry = Entry(root)\n self.entry.grid(row = 3, column = 0, padx = 10, pady = 0)\n\n #Button\n self.button = Button(root, text = 'Append to txt',\n command=self.append_text)\n self.button.grid(row = 4, padx = 10, pady = 5)\n def append_text(self):\n item= self.entry.get()\n if item: # insure there's text in the entry\n print(item)\n \n with open('combo_stuff.txt', mode='a',) as write_file:\n write_file.write('\\n' + item)\n write_file.close()\n self.entry.delete(0,'end')\n \n\nwith open('combo_stuff.txt') as inFile:\n TB = [line for line in inFile]\n\nif __name__ == '__main__':\n root = Tk()\n GUI(root)\n root.mainloop()\n</code></pre>\n<p>The easiest way to open a file is with the pre-made dialog.\nhere's a link to some examples :\n<a href=\"https://pythonbasics.org/tkinter-filedialog/\" rel=\"nofollow noreferrer\">tkinter file dialog</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T05:09:41.870", "Id": "260283", "ParentId": "260066", "Score": "1" } } ]
<p>I have a start and end date. I would like to return a list of tuples, which have the start and end dates of each month.</p> <pre><code>Input start_date = '2020-10-14' end_date = '2021-03-26' Output [('2020-10-14', '2020-10-31'), ('2020-11-01', '2020-11-30'), ('2020-12-01', '2020-12-31'), ('2021-01-01', '2021-01-31'), ('2021-02-01', '2021-02-28'), ('2021-03-01', '2021-03-26')] </code></pre> <p>My code</p> <pre><code>from datetime import datetime, timedelta, date import calendar def get_first_day(year, month): return f'{year}-{str(month).zfill(2)}-01' def get_last_day(year, month): # https://stackoverflow.com/a/23447523/5675288 dt = datetime.strptime(f'{year}-{month}', '%Y-%m') dt = (dt.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1) return dt.strftime('%Y-%m-%d') def diff_month(d1, d2): # https://stackoverflow.com/a/4040338/5675288 return abs((d1.year - d2.year) * 12 + d1.month - d2.month) def add_months(sourcedate, months): # https://stackoverflow.com/a/4131114/5675288 month = sourcedate.month - 1 + months year = sourcedate.year + month // 12 month = month % 12 + 1 day = min(sourcedate.day, calendar.monthrange(year,month)[1]) return date(year, month, day) def get_dates(start_date, end_date): &quot;&quot;&quot;get list of tuples of dates [ (start_date, end-of-month), (start-of-next-month, end-of-next-month), (start-of-next-next-month, end-of-next-next-month), ... (start-of-last-month, end_date) ] &quot;&quot;&quot; sd = datetime.strptime(f'{start_date}', '%Y-%m-%d') ed = datetime.strptime(f'{end_date}', '%Y-%m-%d') diff_months = diff_month(sd, ed) first_days = [] last_days = [] for month in range(diff_months+1): d = add_months(sd, month) first_days.append(get_first_day(d.year, d.month)) last_days.append(get_last_day(d.year, d.month)) first_days = [start_date] + first_days[1:] last_days = last_days[:-1] + [end_date] return list(zip(first_days, last_days)) start_date = '2020-10-14' end_date = '2021-03-26' print(get_dates(start_date, end_date)) </code></pre> <p>Is there a cleaner / better approach for this?</p>
[]
{ "AcceptedAnswerId": "260075", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T14:59:02.023", "Id": "260070", "Score": "2", "Tags": [ "python" ], "Title": "Return list of tuples of date ranges" }
260070
accepted_answer
[ { "body": "<p>None of this code should deal in strings, except <em>maybe</em> the final output stage. It can all be thrown away in favour of a single generator function that uses the highly-useful <code>dateutil</code> library. Also type hints will help:</p>\n<pre><code>from datetime import date\nfrom typing import Iterable, Tuple\nfrom dateutil.relativedelta import relativedelta\n\n\ndef get_dates(start: date, end: date) -&gt; Iterable[Tuple[date, date]]:\n\n while True:\n next_start = start + relativedelta(months=1, day=1)\n this_end = next_start - relativedelta(days=1)\n\n if end &lt;= this_end:\n yield start, end\n break\n\n yield start, this_end\n start = next_start\n\n\ndef main() -&gt; None:\n start = date.fromisoformat(input('Enter start date: '))\n end = date.fromisoformat(input('Enter end date: '))\n for range_start, range_end in get_dates(start, end):\n print(f'{range_start.isoformat()} - {range_end.isoformat()}')\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Output:</p>\n<pre><code>Enter start date: 2020-10-14\nEnter end date: 2021-03-26\n2020-10-14 - 2020-10-31\n2020-11-01 - 2020-11-30\n2020-12-01 - 2020-12-31\n2021-01-01 - 2021-01-31\n2021-02-01 - 2021-02-28\n2021-03-01 - 2021-03-26\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T15:38:07.967", "Id": "513261", "Score": "0", "body": "Thank you for the answer. Although it makes sense that I should not be doing this with strings, my use case is that I will be getting the start and end dates as strings from the user, and the date tuples will be used as parameters to request from an API. That's why I was returning them as strings as well. I do like your solution though, maybe I can make slight modifications to get it as strings" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T15:38:48.417", "Id": "513262", "Score": "1", "body": "Just wrap the solution with parse calls beforehand, and formatting calls after." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-27T15:28:56.730", "Id": "260075", "ParentId": "260070", "Score": "4" } } ]
<p>This a small project for a beginner, it basically generate symbols digits letters depending on the user input I want to make the code better and learn from my mistakes.</p> <pre><code>import string import random asklenght = 0 asku = int(input(&quot;Please choose a method:\n 1)Digits \n 2)Letters \n 3) Symbols \n 4) All \n &quot;)) asklenght = int(input(&quot;How long do you want your password to be ? &quot;)) digits = string.digits letters = string.ascii_letters symbols = string.punctuation if asku == 1: outputpass = random.choice(digits) elif asku == 2: outputpass = random.choice(letters) elif asku == 3: outputpass = random.choice(symbols) else: outputpass = random.choice(digits) outputpass = random.choice(letters) outputpass = random.choice(symbols) for i in range(asklenght - 1 ): if asku == 1: outputpass += random.choice(digits) elif asku == 2: outputpass += random.choice(letters) elif asku == 3: outputpass += random.choice(symbols) else: outputpass += random.choice(digits) outputpass += random.choice(letters) outputpass += random.choice(symbols) print(outputpass) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T15:32:20.503", "Id": "513613", "Score": "0", "body": "I don't have any feedback beyond what FMC already said. I built a password generator, if you want something else to reference to https://github.com/adholmgren/password_gen. It's not super polished, was just going for something personal/functional, but just to see some other ideas." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-01T05:27:13.560", "Id": "513642", "Score": "0", "body": "Hello! but this doesn't give me required length of password\nI entered 10 in the digits but it gave me 27 length of password! need to fix that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T02:18:21.197", "Id": "513691", "Score": "0", "body": "@Pear Yeah, i thought it did comment again if you want the final code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T05:40:09.717", "Id": "513706", "Score": "0", "body": "what do you mean by Comment again if you want the final code?\ndoes that mean Now i commented and You will update your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T14:57:34.340", "Id": "513731", "Score": "0", "body": "Do i need to update it if someone else posted the correct code ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T18:45:11.310", "Id": "513823", "Score": "1", "body": "No, it's better not to touch the code after reviews start coming in. It gets really confusing on who reviewed what code otherwise, even if you clearly mark it as such. If you've updated your code significantly and want a new review on the new code, post a new question." } ]
{ "AcceptedAnswerId": "260176", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T23:30:10.493", "Id": "260173", "Score": "9", "Tags": [ "python", "beginner" ], "Title": "A password generator" }
260173
accepted_answer
[ { "body": "<p>One of the easiest ways to improve code is to reduce repetition. The\nmost-repeated elements in your code are <code>random.choice</code> and <code>outputpass</code>. You\ncan reduce bulk by importing what you need rather than importing a module containing\nwhat you need.</p>\n<pre><code>from random import choice\nfrom string import digits, ascii_letters, punctuation\n</code></pre>\n<p>Another bulk-reducer is to choose more practical variable names. By practical,\nI mean names that are are more\ncompact but no less informative to the reader. For example, in a script that\ngenerates a password, the context is quite clear, so you can get away with a\nvery short variable name: <code>pw</code> is one sensible option. Similarly, a simple name\nlike <code>n</code> is just as clear as <code>asklenght</code>, because <em>in context</em> everybody\nunderstands what <code>n</code> means.</p>\n<p>On the subject of naming, what does <code>asku</code> mean? Not very much to me. But\nyour input prompt text is very clear. A better name might be be <code>method</code>\n(which your text uses)\nor perhaps even <code>chartype</code>, which is more specific.</p>\n<p>Your code has a bug for <code>All</code>: it creates a password 3x as long as it should be.</p>\n<p>You don't need any special logic for <code>n</code> of 1, 2, or 3. Just set up\nthe loop and let it handle everything. The key is to use <code>n</code> rather\nthan <code>n - 1</code>.</p>\n<pre><code>for i in range(n):\n ...\n</code></pre>\n<p>The conditional logic inside the loop has only one purpose: selecting\nthe relevant characters to include in the password. Anytime you have\na situation like that, logic can often be greatly simplified by\ncreating a data structure.</p>\n<pre><code>characters = {\n 1: digits,\n 2: ascii_letters,\n 3: punctuation,\n 4: digits + ascii_letters + punctuation,\n}\n</code></pre>\n<p>That change drastically reduces the code inside the loop:</p>\n<pre><code>pw = ''\nfor i in range(n):\n pw += choice(characters[chartype])\n</code></pre>\n<p>If you want to impress your friends, you can even write it\nin one shot by using a comprehension:</p>\n<pre><code>pw = ''.join(choice(characters[chartype]) for i in range(n))\n</code></pre>\n<p>For usability, you might also consider changing the way that <code>chartype</code>\nworks: instead of asking users to type a number, which requires a small\nmental translation from a meaningful thing (letters, numbers, symbols, all)\nto an abstract thing (1, 2, 3, 4), you could just let them type the\nfirst letter of the actual thing.</p>\n<p>Also for usability, if the context is already clear, shorter messages\nare easier on users, because they can scan them very quickly.</p>\n<p>A final change to consider is whether to subject your user to interrogation by a\ncomputer. I come from the school of thought that says humans tell computers what to\ndo, not the other way around. In addition to being pro-human, that policy has many practical benefits.\nFor example, isn't it annoying that everything time you edit the code and\nre-run it, you have to answer <em>the same damn questions</em>. A different approach\nis to take those instructions directly from the command line. Python\nships with a module called <code>argparse</code> that would work well for a script\nlike this, but you can skip that if you want and just use <code>sys.argv</code> directly.</p>\n<p>You probably should do some input validation, but I'll leave that\nfor you to pursue or for some other reviewer to comment on. Here's\nthe code with those suggested changes.</p>\n<pre><code>from string import digits, ascii_letters, punctuation\nfrom random import choice\nfrom sys import argv\n\nif len(argv) == 3:\n chartype = args[1]\n n = int(args[2])\nelse:\n prompt = 'Password characters:\\n (D)igits\\n (L)etters\\n (S)ymbols\\n (A)ll\\n'\n chartype = input(prompt)\n n = int(input(&quot;Length? &quot;))\n chartype = chartype.lower()[0]\n\ncharacters = {\n 'd': digits,\n 'l': ascii_letters,\n 's': punctuation,\n 'a': digits + ascii_letters + punctuation,\n}\n\npw = ''.join(choice(characters[chartype]) for i in range(n))\n\nprint(pw)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T01:47:01.323", "Id": "513546", "Score": "0", "body": "You are the same guy that helped me the other time, Thanks for all these tips, but i tried the programme in the terminal whenever i try to pass arguments it gives me an error in the terminal \n\"Traceback (most recent call last):\n File \".../Password generator/propass.py\", line 8, in <module>\n n = int(args[1])\nIndexError: list index out of range\n\"\nyou don't need to help me with this, its a little bit advanced for me but i'm curios if you have time, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T01:47:27.440", "Id": "513547", "Score": "0", "body": "the programme work fine in my IDE by the way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T01:55:05.153", "Id": "513548", "Score": "0", "body": "ah, sorry i didn't know i should put all the arguments, i appreciate your help i truly do <3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T02:14:15.693", "Id": "513549", "Score": "1", "body": "@BackpainYT Probably better to use `if len(argv) == 3` than my initial code. I edited that. And yes, you can put arguments on the command line when you run a script. That's the standard way to interact with these kinds of programs and a useful technique in many situations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T02:32:31.570", "Id": "513550", "Score": "0", "body": "alright, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T08:25:58.163", "Id": "513569", "Score": "0", "body": "We could be nicer to the user when invalid inputs are supplied." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T01:17:44.160", "Id": "260176", "ParentId": "260173", "Score": "15" } } ]
<p>This code returns a string of binary in 4-digit forms for a given hex in the form of string</p> <pre><code>def str_bin_in_4digits(aString): retStr = '' for i in aString: retStr = retStr+&quot;{0:04b}&quot;.format(int(i, 16))+&quot; &quot; return retStr.strip() </code></pre> <p>for example,</p> <pre><code>&gt;&gt;&gt; str_bin_in_4digits(&quot;20AC&quot;) 0010 0000 1010 1100 </code></pre> <p>The code works as expected and my concern is could it be more elegant, like faster or less memory consumption?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-01T06:39:41.683", "Id": "513644", "Score": "0", "body": "this question better fit to portal [stackoverflow.com](https://stackoverflow.com/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-01T15:00:44.277", "Id": "513669", "Score": "0", "body": "You should probably be using the inbuilt `binascii` module for this. (https://stackoverflow.com/a/1425500/10534470)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T04:16:10.100", "Id": "513700", "Score": "1", "body": "@furas what makes you say that? The code is as complete as can be expected, and works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T04:49:51.900", "Id": "513703", "Score": "0", "body": "@Reinderien I send a lot of time on Stackoverflow and I see many questions which shows only part of code - like in question - and for me it fit to Stackoverflow." } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-01T04:17:54.807", "Id": "260215", "Score": "4", "Tags": [ "python" ], "Title": "Converting hex to binary in the form of string" }
260215
max_votes
[ { "body": "<h1>Review</h1>\n<p>You don't have a lot of code here to review, so this will necessarily be short.</p>\n<ul>\n<li><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP-8</a>: The Style Guide for Python Code recommends:\n<ul>\n<li><code>snake_case</code> for functions, variables, and parameters. So <code>aString</code> should be <code>a_string</code>, and <code>retVal</code> should be <code>ret_val</code>.</li>\n</ul>\n</li>\n<li>Better parameter names\n<ul>\n<li>What is <code>aString</code>? <code>&quot;Hello World&quot;</code> is a string, but we can't use it, because you are actually expecting a hexadecimal string. Perhaps <code>hex_string</code> would be a better parameter name.</li>\n<li>Similarly, <code>binary_string</code> would be more descriptive than <code>retStr</code>.</li>\n</ul>\n</li>\n<li>A <code>'''docstring'''</code> would be useful for the function.</li>\n<li>Type hints would also be useful.</li>\n</ul>\n<h1>Alternate Implementation</h1>\n<p>Doing things character-by-character is inefficient. It is usually much faster to let Python do the work itself with its efficient, optimized, native code functions.</p>\n<p>Python strings formatting supports adding a comma separator between thousand groups.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; f&quot;{123456789:,d}&quot;\n'123,456,789'\n</code></pre>\n<p>It also supports adding underscores between groups of 4 digits when using the binary or hexadecimal format codes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; f&quot;{548151468:_x}&quot;\n'20ac_20ac'\n&gt;&gt;&gt; f&quot;{0x20AC:_b}&quot;\n'10_0000_1010_1100'\n</code></pre>\n<p>That is most of the way to what you're looking for. Just need to turn underscores to spaces, with <code>.replace(...)</code> and fill with leading zeros by adding the width and 0-fill flag to the format string.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; f&quot;{0x20AC:019_b}&quot;.replace('_', ' ')\n'0010 0000 1010 1100'\n</code></pre>\n<p>A function using this technique could look like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def str_bin_in_4digits(hex_string: str) -&gt; str:\n &quot;&quot;&quot;\n Turn a hex string into a binary string.\n In the output string, binary digits are space separated in groups of 4.\n\n &gt;&gt;&gt; str_bin_in_4digits('20AC')\n '0010 0000 1010 1100'\n &quot;&quot;&quot;\n\n value = int(hex_string, 16)\n width = len(hex_string) * 5 - 1\n bin_string = f&quot;{value:0{width}_b}&quot;\n return bin_string.replace('_', ' ')\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod(verbose=True)\n</code></pre>\n<p>Depending on your definition of elegant, you can one-line this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def str_bin_in_4digits(hex_string: str) -&gt; str:\n &quot;&quot;&quot;\n Turn a hex string into a binary string.\n In the output string, binary digits are space separated in groups of 4.\n\n &gt;&gt;&gt; str_bin_in_4digits('20AC')\n '0010 0000 1010 1100'\n &quot;&quot;&quot;\n\n return f&quot;{int(hex_string,16):0{len(hex_string)*5-1}_b}&quot;.replace('_', ' ')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T00:03:08.493", "Id": "513957", "Score": "0", "body": "Nice review. Is there a reason to mix double and single quotes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T00:58:58.150", "Id": "513959", "Score": "1", "body": "Python makes no distinction between single and double quotes, or triple-quoted single/double quote strings, once they've been created. Single quotes don't need to be escaped in double quote strings, and double quotes don't need to be escaped in single quote string; newlines and quotes don't need escaping in triple-quoted strings. My habit of using single quotes for single characters and double quotes for strings comes from C/C++/Java, and has no other significance. @Marc" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T23:01:04.343", "Id": "260276", "ParentId": "260215", "Score": "5" } } ]
<p>I have these 2 version of code. Both are looking for all primes under a certain ceiling value.</p> <p>The first is testing against the set of all odd numbers. The second in testing against the set of all 6k-1 and 6k+1.</p> <p>In theory, the second version should be faster than the first. However the result states otherwise.</p> <p>For under 1 million, the first perform for 1.477835 seconds, while the second perform for 1.521462 seconds.</p> <p>For under 10 million, the first perform for 30.929565 seconds, while the second perform for 32.825142 seconds.</p> <p>I have not test these under a different machine.</p> <p>I could not figure out why I'm getting these results. Because, the second version is suppose to eliminate more composite numbers than the first. However, it perform worse, quite significantly.</p> <p>I suspect this might be caused by my method of implementation. But even if that were the case, I still wouldn't have the slightest idea of why.</p> <p>Could it be because of I'm having more nested loops? Or is it to do with memory access? Is it maybe a python's quirk where the implementation details matters? Maybe in some way the first version is simpler and therefore can be easily better optimized by python compared to the second?</p> <p>If someone could provide some explanations, suggestions, even solutions or alternatives, that would be much appreciated.</p> <pre><code>#!/usr/bin/env python3.8 import sys import time import math if len(sys.argv) != 2: print('usage:') print(' (ceiling)') print(' Find primes less than ceiling.') sys.exit(-1) try: ceiling = int(sys.argv[1]) except: print('Fail to parse ceiling ({}) as integer.'.format(sys.argv[1])) sys.exit(-2) if ceiling &lt; 3: print('Minimum ceiling value is 3.') sys.exit(-3) prime = [3] # start benchmark bench_start = time.perf_counter() # range(start, end, step) does not include end # step = 2 to avoid checking even numbers for i in range(5, ceiling + 1, 2): # test only against factors less than the square root root = math.sqrt(i) for j in prime: if j &gt; root: prime.append(i) break if i % j == 0: break # end of benchmark bench_end = time.perf_counter() # prepend 2 to the prime list since it was skipped prime.insert(0, 2) print(prime) print('Number of, primes less than {0}, found: {1}'.format(ceiling, len(prime))) # benchmark report print('Time elapsed: {:f}s'.format(bench_end - bench_start)) sys.exit(0) </code></pre> <hr /> <pre><code>#!/usr/bin/env python3.8 import sys import time import math if len(sys.argv) != 2: print('usage:') print(' (ceiling)') print(' Find primes less than or equal to ceiling.') sys.exit(-1) try: ceiling = int(sys.argv[1]) except: print('Fail to parse ceiling ({}) as integer.'.format(sys.argv[1])) sys.exit(-2) if ceiling &lt; 3: print('Minimum ceiling value is 3.') sys.exit(-3) prime = [3] # start benchmark bench_start = time.perf_counter() # range(start, end, step) does not include end # test only for 6k-1 and 6k+1 # use (ceiling+1)+1 in case of ceiling = 6k-1 for h in range(6, ceiling+2, 6): for i in [h-1, h+1]: # test only against factors less than the square root root = math.sqrt(i) for j in prime: if j &gt; root: prime.append(i) break if i % j == 0: break # end of benchmark bench_end = time.perf_counter() # when ceiling = {6k-1, 6k}, remove 6k+1 if prime[-1] &gt; ceiling: prime.pop() # prepend 2 to the prime list since it was skipped prime.insert(0, 2) print(prime) print('Number of, primes less than or equal to {0}, found: {1}'.format(ceiling, len(prime))) # benchmark report print('Time elapsed: {:f}s'.format(bench_end-bench_start)) sys.exit(0) <span class="math-container">```</span> </code></pre>
[]
{ "AcceptedAnswerId": "260239", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-01T06:40:25.040", "Id": "260218", "Score": "1", "Tags": [ "python", "algorithm", "python-3.x", "primes", "search" ], "Title": "Python Prime Search Slower Optimization" }
260218
accepted_answer
[ { "body": "<p>The difference averages to .2 microseconds per number checked.</p>\n<p>To see if its the inner loop, try unrolling it in the second program:</p>\n<pre><code>...\nfor i in range(5, ceiling+1, 6):\n # test only against factors less than the square root\n # just use the sqrt of the bigger number to avoid another call to sqrt\n root = math.sqrt(i + 2)\n\n # tests 6k - 1\n for j in prime:\n if j &gt; root:\n prime.append(i)\n break\n if i % j == 0:\n break\n\n # tests 6k + 1\n i += 2\n for j in prime:\n if j &gt; root:\n prime.append(i)\n break\n if i % j == 0:\n break\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T03:44:02.227", "Id": "513694", "Score": "0", "body": "I tried unwinding the inner-loop. Although it did makes it faster, it still was slower than the first version. However, by taking the root calculation out of the inner-loop and only calculating for the larger number, as you had suggested, it has made the performance quite considerably faster than the first version. So in conclusion, the square root calculation seems to have a more significant performance importance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-01T23:28:51.317", "Id": "260239", "ParentId": "260218", "Score": "2" } } ]
<p>Is there any room for improvements in this code. I am new to programming (python3), learning and practicing functions related to arguments recently.</p> <pre><code>def make_pizza(*toppings, **pizza_info): &quot;&quot;&quot;Creating a dictionary for pizza information&quot;&quot;&quot; pizza = {} pizza_toppings = [topping for topping in toppings] pizza['toppings'] = pizza_toppings for key, value in pizza_info.items(): pizza[key] = value return pizza def show_pizza(pizza): &quot;&quot;&quot;Showing the order with the information provided by make_pizza() function.&quot;&quot;&quot; print(&quot;You've ordered &quot; + str(pizza['size']) + &quot; inches size &quot; + pizza[ 'crust'].title() + &quot; crust pizza with the toppings of:&quot;) for topping in pizza['toppings']: print(&quot;-&quot; + topping.title()) # Taking order in a form of dictionary structure order = make_pizza('cheese', 'mushroom', size=12, crust='thin') # Show the order message show_pizza(order) </code></pre>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T14:27:43.980", "Id": "260258", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Pizza ordering system" }
260258
max_votes
[ { "body": "<p>You can use standard copy functions instead of manually copying:</p>\n<pre><code>from copy import copy\n\ndef make_pizza(*toppings, **pizza_info):\n pizza = pizza_info.copy()\n pizza['toppings'] = copy(toppings) \n return pizza\n</code></pre>\n<p>And maybe use a dict-comprehension for merging information, instead of mutating the pizza:</p>\n<pre><code>def make_pizza(*toppings, **pizza_info):\n return {\n **pizza_info,\n 'toppings': copy(toppings) \n }\n</code></pre>\n<p>For printing, use f-strings for easier formatting:</p>\n<pre><code>print(f&quot;You've ordered {pizza['size']} inches size {pizza[\n 'crust'].title()} crust pizza with the toppings of:&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T07:06:20.843", "Id": "513786", "Score": "0", "body": "Thank you for your guidance. I gained a lot of insight from this. Gotta apply those practise real quick. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T05:16:12.463", "Id": "513853", "Score": "1", "body": "Maybe I answered too fast. Please note that:\n\n- the copy function will give you the same type as the input you give it, so you will end up with a tuple for toppings, not a list (which might be as fine)\n- the copies here are actually not needed, as *args and **kwargs are already created anew when the function is called\n- the copies are only shallow. It makes no difference when the contents are only strings, as these are immutable, but if you had anything mutable it could cause trouble\n- but if you avoid mutating anything in your programs, this will not be a problem" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T10:38:17.087", "Id": "514056", "Score": "0", "body": "Thank you so much for giving me such efforts and being considerate about my codes. I will keep on working on your suggestions. Big thanks to you. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T15:15:26.447", "Id": "260260", "ParentId": "260258", "Score": "2" } } ]
<p>I have some python scripts to run on different computers. To avoid struggles with different paths and filenames I made specific config-files (DConfig, AConfig and MConfig) and another script that decides which config to use. It works, but I guess, there are better ways to do this. Any ideas?</p> <pre><code>import os import socket hostname_K = 'DESKTOP-K' hostname_A = 'A' hostname_M = '' # hostname not known for sure print(&quot;start config&quot;) print(&quot;cwd: &quot;, os.getcwd()) print(&quot;os: &quot;, os.name) # print(os.getlogin()) # Doesn't work on non-posix hostname = socket.gethostname() if hostname == hostname_K: import DConfig as Conf elif hostname == hostname_A: import AConfig as Conf else: print(&quot;Hostname: {}, guess we are on M&quot;.format(hostname)) import MConfig as Conf dirData = Conf.dirData dirScript = Conf.dirScript pathDB = Conf.pathDB print(&quot;config done.&quot;) </code></pre> <p>How it is used by other scripts:</p> <pre><code>import config XMLFILE = config.dirData + 'Tags.xml' DATABASE = config.pathDB </code></pre> <p>Here is an example script for one of the config-files.</p> <pre><code>dirData = '/home/username/path/to/data/' dirScript = '/home/username/path/to/scripts/' pathDB = '/home/username/path/to/database.db' </code></pre> <p>The other scripts are similar.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T21:56:05.590", "Id": "513757", "Score": "0", "body": "`dirData` etc. are used by other scripts importing this config files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T02:15:19.093", "Id": "513774", "Score": "0", "body": "It might be helpful if you include the 3 config files in the question as well." } ]
{ "AcceptedAnswerId": "260275", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T19:58:34.833", "Id": "260270", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Managing configs to use scripts on different computers" }
260270
accepted_answer
[ { "body": "<p>You have a value (<code>hostname</code> in this case) that you want to use to select among\nvarious data choices (config modules in this case). When you have situations\nlike this, use a data structure. <strong>Sensible\ndata is always simpler than logic</strong>. For example, see <a href=\"https://users.ece.utexas.edu/%7Eadnan/pike.html\" rel=\"nofollow noreferrer\">Rule 5</a> from Rob\nPike.</p>\n<p>An illustration based on your code:</p>\n<pre><code>import socket\nimport DConfig\nimport AConfig\nimport MConfig\n\nconfigs = {\n 'host-D': DConfig,\n 'host-A': AConfig,\n 'host-M': MConfig,\n}\n\nhostname = socket.gethostname()\nConf = configs.get(hostname, MConfig)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T22:07:50.113", "Id": "513758", "Score": "0", "body": "Thanks, that looks a lot better!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-02T21:35:31.157", "Id": "260275", "ParentId": "260270", "Score": "1" } } ]
<pre><code>from itertools import permutations def next_bigger(n): nlist = list(str(n)) perm = permutations(nlist,len(str(n))) perm = set(perm) listofperm = [] nlist = int(&quot;&quot;.join(nlist)) for x in perm: form = int(&quot;&quot;.join(x)) if form &lt; nlist: continue else: listofperm.append(form) listofperm = sorted(listofperm) if (listofperm.index(n) + 1) == len(listofperm): indexofn = listofperm.index(n) else: indexofn = listofperm.index(n) + 1 return listofperm[indexofn] </code></pre> <p>I'm trying to get the next bigger number by rearranging the digits of <code>n</code> but my code is very inefficient can you suggest ways to make my code more efficient and faster?</p> <p>Inputs would be any integer.</p>
[]
{ "AcceptedAnswerId": "260307", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T12:21:28.260", "Id": "260299", "Score": "0", "Tags": [ "python", "algorithm", "time-limit-exceeded", "combinatorics" ], "Title": "Get the next bigger number by rearranging the digits of the input integer" }
260299
accepted_answer
[ { "body": "<p>Since this is asking for a new algorithm, I will try to provide some hints. Look at the output of</p>\n<pre><code>from itertools import permutations\nsorted([a*1000 + x*100 + y*10 + z for a,x,y,z in permutations([1,2,3,4])])\n</code></pre>\n<p>Which digits are most likely to be different between consecutive members of this list?</p>\n<p>Look at the elements that start with <code>4</code>. Can you see a pattern in the rest of their digits? If so, how do the rest of the digits have to change when the first changes?</p>\n<p>Does the same pattern hold for digits <code>a,b,c,d</code> in place of <code>1,2,3,4</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T23:31:03.190", "Id": "513842", "Score": "1", "body": "I see, thanks it gave me a new idea to implement this" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T15:54:53.857", "Id": "260307", "ParentId": "260299", "Score": "0" } } ]
<ol> <li>Given an array of unique numbers find the combinations</li> <li>Doing a shallow copy in the code to avoid changes to the passed obj by reference</li> <li>This has a run time of <span class="math-container">\$O(n \times \text{#ofcombinations})\$</span> - can this be done better -- iteratively and easy to understand</li> </ol> <pre><code>import copy def gen_combinations(arr): # res = [[]] for ele in arr: temp_res = [] for combination in res: temp_res.append(combination) new_combination = copy.copy(combination) new_combination.append(ele) temp_res.append(new_combination) res = copy.copy(temp_res) return res </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T16:35:36.103", "Id": "514200", "Score": "0", "body": "Step 2 says \"Doing a deep copy...\", but `copy.copy()` does a shallow copy, which is fine in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T21:06:13.317", "Id": "514214", "Score": "0", "body": "thanks for catching that @RootTwo, edited the description" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T22:29:56.697", "Id": "260318", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "Generate combinations of a given sequence without recursion" }
260318
max_votes
[ { "body": "<p>First, a side note. What you call <code>combination</code> is usually called <code>subset</code>.</p>\n<p>In a set of <span class=\"math-container\">\\$n\\$</span> elements an average length of a subset is <span class=\"math-container\">\\$\\dfrac{n}{2}\\$</span>. That is, generating a single subset takes <span class=\"math-container\">\\$O(n)\\$</span> time. You cannot get a time complexity better than <span class=\"math-container\">\\$O(n2^n)\\$</span>.</p>\n<p>The space complexity is a different matter. If you indeed need all the subset at the same time, then again the space complexity cannot be better than <span class=\"math-container\">\\$O(n2^n)\\$</span>. On the other hand, if you want one subset at a time, consider converting your function to a generator, which would <code>yield</code> subsets one at a time.</p>\n<p>A more or less canonical way of generating subsets uses the 1:1 mapping of subsets and numbers. Each number <code>a</code> in the <span class=\"math-container\">\\$[0, 2^n)\\$</span> range uniquely identifies subset of <span class=\"math-container\">\\$n\\$</span> elements (and vice versa). Just pick the elements at the position where <code>a</code> has a bit set.</p>\n<p>All that said, consider</p>\n<pre><code>def generate_subsets(arr):\n n = len(arr)\n for a in range(2 ** n):\n yield [arr[i] for i in range(n) if (a &amp; (1 &lt;&lt; i)) != 0]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T10:41:27.647", "Id": "513882", "Score": "1", "body": "Just a note, one can always iterate a finite generator and fill an array with all the results. So it actually feels more flexible to do that way even if now, you need them all at once." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T02:40:10.503", "Id": "260323", "ParentId": "260318", "Score": "12" } } ]
<p>I have ~40,000 JPEG images from the <a href="https://www.kaggle.com/c/siim-isic-melanoma-classification" rel="nofollow noreferrer">Kaggle</a> melanoma classification competition. I created the following functions to denoise the images:</p> <pre><code># Denoising functions def denoise_single_image(img_path): img = cv2.imread(f'../data/jpeg/{img_path}') dst = cv2.fastNlMeansDenoising(img, 10,10,7,21) cv2.imwrite(f'../processed_data/jpeg/{img_path}', dst) print(f'{img_path} denoised.') def denoise(data): img_list = os.listdir(f'../data/jpeg/{data}') with concurrent.futures.ProcessPoolExecutor() as executor: tqdm.tqdm(executor.map(denoise_single_image, (f'{data}/{img_path}' for img_path in img_list))) </code></pre> <p>The <code>denoise</code> function uses <code>concurrent.futures</code> to map the <code>denoise_single_image()</code> function over the full list of images.</p> <p><code>ProcessPoolExecutor()</code> was used based on the assumption of denoising as a CPU-heavy task, rather than an I/O-intensitve task.</p> <p>As it stands now, this function takes hours to run. With a CUDA-configured Nvidia GPU and 6 GB VRAM, I'd like to optimize this further.</p> <p>Is there any way to improve the speed of this function?</p> <p><a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow noreferrer">Multi-core processing documentation</a><br/> <a href="https://docs.opencv.org/4.5.2/" rel="nofollow noreferrer">OpenCV documentation</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T07:25:27.630", "Id": "513978", "Score": "1", "body": "Welcome to Code Review. What Python version are you using?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T03:18:59.100", "Id": "260355", "Score": "2", "Tags": [ "python", "image", "opencv", "multiprocessing" ], "Title": "Multi-core OpenCV denoising" }
260355
max_votes
[ { "body": "<p>You may look at opencv <a href=\"https://learnopencv.com/opencv-transparent-api/\" rel=\"nofollow noreferrer\">Transparent API</a></p>\n<pre><code>#\nimgUMat = cv2.UMat(img)\ndst = cv2.fastNlMeansDenoising(imgUMat, 10,10,7,21)\n#\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T10:49:17.910", "Id": "260365", "ParentId": "260355", "Score": "1" } } ]
<p>The problem is to ask the user to guess a number between 1 to 100 and compare it with a random number of that range. If user guessed number is lesser/greater than the random number print &quot;too low&quot; or &quot;too high&quot; accordingly. Take new input asking the user to guess the correct number again. When the guessed number matches with the random number print &quot;you win&quot; and the number of attempts the user required to guess it.</p> <pre><code>import random u_num = int(input(&quot;guess a number between 1 to 100: &quot;)) w_num = random.randint(1,100) i = 1 while u_num != w_num: if u_num &lt; w_num: print(&quot;too low&quot;) else: print(&quot;too high&quot;) u_num = int(input(&quot;guess again: &quot;)) i += 1 print(f&quot;you win, and you guessed this number in {i} times!&quot;) </code></pre>
[]
{ "AcceptedAnswerId": "260410", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T17:14:30.343", "Id": "260385", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "number-guessing-game" ], "Title": "Simple number guessing game in python" }
260385
accepted_answer
[ { "body": "<p>Your variable names are a little impenetrable - best to use whole words.</p>\n<p>Consider adding input validation as a next step to enhancing this program's functionality - what if a user guesses &quot;banana&quot;?</p>\n<p>Pythonic code generally discourages the maintenance of your own loop variables (<code>i</code>). I would move your termination condition into the loop body - where you're already checking the guess anyway - and count in your loop declaration.</p>\n<p>This example code does the above, minus input validation:</p>\n<pre><code>import random\nfrom itertools import count\n\nguess = int(input(&quot;Guess a number between 1 to 100: &quot;))\nsecret = random.randint(1, 100)\n\nfor guesses in count(1):\n if guess &lt; secret:\n print(&quot;Too low&quot;)\n elif guess &gt; secret:\n print(&quot;Too high&quot;)\n else:\n break\n\n guess = int(input(&quot;Guess again: &quot;))\n\nprint(f&quot;You win, and you guessed this number in {guesses} times!&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T10:20:25.903", "Id": "260410", "ParentId": "260385", "Score": "2" } } ]
<p>Standard code review, tell me what's good, what's bad, and how to improve. Critical suggestions welcomed. This is a content aggregator using bs4 and requests. I did not use any tutorials or help.</p> <pre><code>import requests from bs4 import BeautifulSoup as bs topic = input('Enter the topic: ').lower() print() def getdata(url, headers): r = requests.get(url, headers=headers) return r.text def linesplit(): print('-~'*16, 'COLIN IS MOOCH', '-~'*16, '\n') headers = { 'User-agent': &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582&quot; } google = getdata(f'https://www.google.com/search?q={topic}&amp;oq={topic}&amp;aqs=chrome..69i59j69i57j69i59j69i60l3j69i65j69i60.2666j0j7&amp;sourceid=chrome&amp;ie=UTF-8', headers) soup = bs(google, 'html.parser') links = str(soup.find_all('div', class_='TbwUpd NJjxre')) links = links.replace('&lt;div class=&quot;TbwUpd NJjxre&quot;&gt;&lt;cite class=&quot;iUh30 Zu0yb qLRx3b tjvcx&quot;&gt;', '') links = links.replace('&lt;span class=&quot;dyjrff qzEoUe&quot;&gt;', '') links = links.replace('&lt;/span&gt;&lt;/cite&gt;&lt; /div&gt;', '') links = links.replace('&lt;div class=&quot;TbwUpd NJjxre&quot;&gt;&lt;cite class=&quot;iUh30 Zu0yb tjvcx&quot;&gt;', '') links = links.replace('&lt;/cite&gt;&lt;/div&gt;', '') links = links.replace('&lt;/span&gt;', '') links = links.replace(' › ', '/') links = links.split(', ') links[-1] = links[-1].replace(']', '') links[0] = links[0].replace('[', '') info = [] counter = 0 for x in range(len(links)): try: htmldata = getdata(links[x], headers) newsoup = bs(htmldata, 'html.parser') website = '' for i in newsoup.find_all('p'): website = website + ' ' + i.text info.append(links[x]) info.append(website) counter += 1 except Exception: continue try: for x in range(0, (counter * 2) + 2, 2): if info[x+1] != '': linesplit() print() print('From ', info[x], ':') print() print(info[x+1]) linesplit() except IndexError: pass </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T21:54:33.720", "Id": "514103", "Score": "0", "body": "Why not use the API?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T22:54:45.113", "Id": "514107", "Score": "0", "body": "Which API? I didn't know there was one." } ]
{ "AcceptedAnswerId": "260441", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-06T21:12:47.280", "Id": "260437", "Score": "0", "Tags": [ "beginner", "python-3.x", "beautifulsoup" ], "Title": "Content aggregator using bs4 and requests" }
260437
accepted_answer
[ { "body": "<p>Your <code>linesplit</code> is... strange? I'm going to ignore that message and pretend it makes sense.</p>\n<p>Whenever there's an API, prefer it. In this case Google has a Custom Search API that allows you to skip past all of the scraping insanity. You'll need to get an API key and configure an engine instance to search the whole web. The front-end of such an application, without including your second &quot;scrape all of the paragraphs&quot; step, looks like:</p>\n<pre><code>from typing import Iterable\nfrom requests import Session\n\n\n# To set a custom search engine to search the entire web, read\n# https://support.google.com/programmable-search/answer/4513886\nAPI_KEY = '...'\nENGINE_ID = '...'\n\n\ndef api_get(session: Session, query: str) -&gt; Iterable[str]:\n with session.get(\n 'https://customsearch.googleapis.com/customsearch/v1',\n headers={'Accept': 'application/json'},\n params={\n 'key': API_KEY,\n 'cx': ENGINE_ID,\n 'q': query,\n }\n ) as resp:\n resp.raise_for_status()\n body = resp.json()\n\n for item in body['items']:\n yield item['link']\n\n\ndef main():\n topic = input('Enter the topic: ').lower()\n\n with Session() as session:\n urls = api_get(session, topic)\n\n print('\\n'.join(urls))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T01:01:39.863", "Id": "260441", "ParentId": "260437", "Score": "2" } } ]
<p>I have this function called error, which estimates value based on previous value and rewards in trials. The difference between the estimated value and true value is then calculated, giving the error. I need to run this code 1000 times with different lists of trials, but currently it runs too slowly. How would I optimize this code?</p> <p>Additional information: alpha is a parameter. Reward and true_value are lists. Value always starts at 0.5, but I remove this starting number before calculating error</p> <pre><code>def loopfunction(alpha, reward, true_value): difference = [] value = [0.5] for index, lr in enumerate(reward): value.append(lever_update(alpha, value[-1], reward[index])) value.pop(0) zip_object = zip(value, true_value) for value_i, true_value_i in zip_object: difference.append(value_i-true_value) absdiff = [abs(number) for number in difference] return absdiff </code></pre> <p>The lever_update function, which calculates value is here:</p> <pre><code>def lever_update(alpha, value, reward): value += alpha * (reward - value) return(value) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T10:26:19.727", "Id": "514184", "Score": "1", "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." } ]
{ "AcceptedAnswerId": "260490", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T10:11:36.320", "Id": "260488", "Score": "3", "Tags": [ "python", "performance", "functional-programming" ], "Title": "Finding the difference between the estimated value and the true value in a reward task" }
260488
accepted_answer
[ { "body": "<ol>\n<li><p>Using list comprehensions instead of numerous <code>.append</code> calls is\noften times faster and more readable.</p>\n</li>\n<li><p>A list of rewards should be called <code>rewards</code> instead of <code>reward</code>. Same goes for <code>values</code> and <code>true_values</code>.</p>\n</li>\n<li><p>We don't need to <code>enumerate</code> rewards, since we don't need the index itself. We can simply iterate over <code>rewards</code>.</p>\n<pre><code>def loopfunction(alpha, rewards, true_values):\n\n values = [0.5]\n for reward in rewards:\n values.append(lever_update(alpha, values[-1], reward))\n\n values.pop(0)\n\n return [abs(value - true_value) for value, true_value in zip(values, true_values)]\n</code></pre>\n</li>\n</ol>\n<p>I sadly can't test performance right now, but I would assume the first <code>for</code> loop takes up most of your runtime. This is what I'd focus on for further improvements. In general, making code more concise and readable also allows for easier refactoring / performance improvements in the future.</p>\n<hr />\n<p>We can also make <code>lever_update</code> more concise:</p>\n<pre><code>def lever_update(alpha, value, reward):\n return value + alpha * (reward - value)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T10:40:59.090", "Id": "260490", "ParentId": "260488", "Score": "1" } } ]
<p>I have a <code>dataframe</code> with a column composed by <code>date</code> object and a column composed by <code>time</code> object. I have to merge the two columns.</p> <p>Personally, I think it is so ugly the following solution. Why I have to cast to <code>str</code>? I crafted my solution based <a href="https://stackoverflow.com/a/49668702/6290211">on this answer</a></p> <pre><code>#importing all the necessary libraries import pandas as pd import datetime #I have only to create a Minimal Reproducible Example time1 = datetime.time(3,45,12) time2 = datetime.time(3,49,12) date1 = datetime.datetime(2020, 5, 17) date2 = datetime.datetime(2021, 5, 17) date_dict= {&quot;time1&quot;:[time1,time2],&quot;date1&quot;:[date1,date2]} df=pd.DataFrame(date_dict) df[&quot;TimeMerge&quot;] = pd.to_datetime(df.date1.astype(str)+' '+df.time1.astype(str)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T03:32:39.717", "Id": "514442", "Score": "1", "body": "i agree it would be nice if they overloaded `+` for `date` and `time`, but your current `str`/`to_datetime()` code is the fastest way to do it (even if it looks uglier)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T03:38:49.850", "Id": "514443", "Score": "1", "body": "if your real data is coming from a csv, [`pd.read_csv(..., parse_dates=[['date1','time1']])`](https://stackoverflow.com/a/44920602/13138364) would probably be the \"prettiest\" and fastest option" } ]
{ "AcceptedAnswerId": "260504", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:19:09.717", "Id": "260503", "Score": "1", "Tags": [ "python", "datetime", "pandas" ], "Title": "Pandas merge a \"%Y%M%D\" date column with a \"%H:%M:%S\" time column" }
260503
accepted_answer
[ { "body": "<p>We can let pandas handle this for us and use <code>DataFrame.apply</code> and <code>datetime.datetime.combine</code> like this:</p>\n<pre><code>df[&quot;TimeMerge&quot;] = df.apply(lambda row: datetime.datetime.combine(row.date1, row.time1), axis=1)\n</code></pre>\n<hr />\n<p>Although the following approach is more explicit and might therefore be more readable if you're not familiar with <code>DataFrame.apply</code>, I would strongly recommend the first approach.</p>\n<p>You could also manually map <code>datetime.datetime.combine</code> over a zip object of <code>date1</code> and <code>time1</code>:</p>\n<pre><code>def combine_date_time(d_t: tuple) -&gt; datetime.datetime:\n return datetime.datetime.combine(*d_t)\n\ndf[&quot;TimeMerge&quot;] = pd.Series(map(combine_date_time, zip(df.date1, df.time1)))\n</code></pre>\n<p>You can also inline it as an anonymous lambda function:</p>\n<pre><code>df[&quot;TimeMerge&quot;] = pd.Series(map(lambda d_t: datetime.datetime.combine(*d_t), zip(df.date1, df.time1)))\n</code></pre>\n<p>This is handy for simple operations, but I would advise against this one-liner in this case.</p>\n<hr />\n<p>By the way, <a href=\"https://stackoverflow.com/a/39474812/9173379\">the answer your were looking for</a> can also be found under <a href=\"https://stackoverflow.com/q/17978092/9173379\">the question you linked</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T03:28:49.800", "Id": "514441", "Score": "1", "body": "\"can and should\" seems too conclusive though. `apply(axis=1)` is usually the slowest option. in this case, it's 2x slower than `pd.to_datetime()` at 200 rows, 3x slower at 2K rows, 3.5x slower at 2M rows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T10:21:20.890", "Id": "514452", "Score": "0", "body": "Thank you for the input, I was expecting `df.apply` to be faster than that. I reduced it to *\"can\"*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T06:40:12.827", "Id": "514816", "Score": "0", "body": "Thank you @riskypenguin I missed the specific answer :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T17:48:17.013", "Id": "260504", "ParentId": "260503", "Score": "2" } } ]
<p>I previously posted a question for codereview:</p> <p><a href="https://codereview.stackexchange.com/questions/259824/python-autoclicker">Python Autoclicker</a></p> <p>And I received some great feedback and changes to do in the code.</p> <p>I have done many of the changes mentioned in the answers and here is the final code:</p> <pre><code>from pynput.keyboard import Controller from time import sleep def auto_click(key: str, n_clicks: int, delay: float): keyboard = Controller() for _ in range(n_clicks): keyboard.tap(key) sleep(delay) def main(): key = input(&quot;Key to be autopressed: &quot;) try: n_clicks = int(input(&quot;Number of autopresses (integer): &quot;)) except ValueError: print(&quot;\n The number of autopresses should be an integer value, defaulting to 1. \n&quot;) n_clicks = 1 try: delay = float(input(&quot;Delay between each autopress in seconds (integer/float): &quot;)) except ValueError: print(&quot;\n The delay between each autoclick should be an integer or a decimal value, defaulting to 1 (second). \n&quot;) delay = 1 auto_click(key, n_clicks, delay) if __name__ == '__main__': main() </code></pre> <p>What is it that you think should be made better in this code? Any feedback and suggestions would be much appreciated.</p> <p>Here's the github repo:</p> <p><a href="https://github.com/SannanOfficial/AutoKeyPython" rel="nofollow noreferrer">https://github.com/SannanOfficial/AutoKeyPython</a></p>
[]
{ "AcceptedAnswerId": "260514", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T18:32:36.063", "Id": "260505", "Score": "4", "Tags": [ "python", "python-3.x", "automation" ], "Title": "\"Python AutoClicker\" Part 2" }
260505
accepted_answer
[ { "body": "<p>Your code is generally fine. I suspect you are not doing enough validation (for\nexample, to forbid negative values or multi-character keys). Also, if you want\nto expand your toolkit, you can think about eliminating the duplication in your\ncode by generalizing the input collection process.</p>\n<p>Collecting user input involves a few common elements: an input prompt, a\nfunction to convert the string to a value, a function to validate that value,\nan error message in the event of bad input, and possibly some other stuff (max\nallowed attempts, fallback/default value in the event of bad input). If we\nfocus on just the basics, we end up with a function along the lines of this\nsketch:</p>\n<pre><code>def get_input(convert, validate, prompt, errmsg):\n while True:\n try:\n x = convert(input(prompt + ': '))\n if validate(x):\n return x\n else:\n print(errmsg)\n except ValueError:\n print(errmsg)\n</code></pre>\n<p>With that in hand, all of the algorithmic detail will reside in that single\nfunction, and your <code>main()</code> will be little more than straightforward,\nstep-by-step orchestration code.</p>\n<pre><code>def main():\n key = get_input(\n str.strip,\n lambda s: len(s) == 1,\n 'Key to be autopressed',\n 'Invalid, must be single character',\n )\n n_clicks = get_input(\n int,\n lambda n: n &gt; 0,\n 'Number of autopresses',\n 'Invalid, must be positive integer',\n )\n delay = get_input(\n float,\n lambda n: n &gt; 0,\n 'Delay between autopresses',\n 'Invalid, must be positive float',\n )\n auto_click(key, n_clicks, delay)\n</code></pre>\n<p>As shown in that sketch, I would also encourage you to favor a more compact\nstyle in messages to users. Brevity usually scales better across a variety of\ncontexts than verbosity: it's easier to maintain; it's easier to make\nconsistent across an entire application; and most people don't appreciate\nhaving to slog through long messages when an equally clear short one\nis possible.</p>\n<p>Finally, you might also consider whether <code>input()</code> is the best\nmechanism to get this information from the user. In my experience,\nit is almost always preferable to take such values from the\ncommand-line, either from <code>sys.argv</code> directly or, more commonly,\nusing a library like <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a>. The advantages\nto this approach are numerous.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T15:00:57.117", "Id": "514258", "Score": "0", "body": "Thank you so much for the answer, mate. All of your suggestions make sense to me and I'll try to implement all of them If I can." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T21:33:06.157", "Id": "260514", "ParentId": "260505", "Score": "4" } } ]
<p>I previously posted a question for codereview:</p> <p><a href="https://codereview.stackexchange.com/questions/259824/python-autoclicker">Python Autoclicker</a></p> <p>And I received some great feedback and changes to do in the code.</p> <p>I have done many of the changes mentioned in the answers and here is the final code:</p> <pre><code>from pynput.keyboard import Controller from time import sleep def auto_click(key: str, n_clicks: int, delay: float): keyboard = Controller() for _ in range(n_clicks): keyboard.tap(key) sleep(delay) def main(): key = input(&quot;Key to be autopressed: &quot;) try: n_clicks = int(input(&quot;Number of autopresses (integer): &quot;)) except ValueError: print(&quot;\n The number of autopresses should be an integer value, defaulting to 1. \n&quot;) n_clicks = 1 try: delay = float(input(&quot;Delay between each autopress in seconds (integer/float): &quot;)) except ValueError: print(&quot;\n The delay between each autoclick should be an integer or a decimal value, defaulting to 1 (second). \n&quot;) delay = 1 auto_click(key, n_clicks, delay) if __name__ == '__main__': main() </code></pre> <p>What is it that you think should be made better in this code? Any feedback and suggestions would be much appreciated.</p> <p>Here's the github repo:</p> <p><a href="https://github.com/SannanOfficial/AutoKeyPython" rel="nofollow noreferrer">https://github.com/SannanOfficial/AutoKeyPython</a></p>
[]
{ "AcceptedAnswerId": "260514", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T18:32:36.063", "Id": "260505", "Score": "4", "Tags": [ "python", "python-3.x", "automation" ], "Title": "\"Python AutoClicker\" Part 2" }
260505
accepted_answer
[ { "body": "<p>Your code is generally fine. I suspect you are not doing enough validation (for\nexample, to forbid negative values or multi-character keys). Also, if you want\nto expand your toolkit, you can think about eliminating the duplication in your\ncode by generalizing the input collection process.</p>\n<p>Collecting user input involves a few common elements: an input prompt, a\nfunction to convert the string to a value, a function to validate that value,\nan error message in the event of bad input, and possibly some other stuff (max\nallowed attempts, fallback/default value in the event of bad input). If we\nfocus on just the basics, we end up with a function along the lines of this\nsketch:</p>\n<pre><code>def get_input(convert, validate, prompt, errmsg):\n while True:\n try:\n x = convert(input(prompt + ': '))\n if validate(x):\n return x\n else:\n print(errmsg)\n except ValueError:\n print(errmsg)\n</code></pre>\n<p>With that in hand, all of the algorithmic detail will reside in that single\nfunction, and your <code>main()</code> will be little more than straightforward,\nstep-by-step orchestration code.</p>\n<pre><code>def main():\n key = get_input(\n str.strip,\n lambda s: len(s) == 1,\n 'Key to be autopressed',\n 'Invalid, must be single character',\n )\n n_clicks = get_input(\n int,\n lambda n: n &gt; 0,\n 'Number of autopresses',\n 'Invalid, must be positive integer',\n )\n delay = get_input(\n float,\n lambda n: n &gt; 0,\n 'Delay between autopresses',\n 'Invalid, must be positive float',\n )\n auto_click(key, n_clicks, delay)\n</code></pre>\n<p>As shown in that sketch, I would also encourage you to favor a more compact\nstyle in messages to users. Brevity usually scales better across a variety of\ncontexts than verbosity: it's easier to maintain; it's easier to make\nconsistent across an entire application; and most people don't appreciate\nhaving to slog through long messages when an equally clear short one\nis possible.</p>\n<p>Finally, you might also consider whether <code>input()</code> is the best\nmechanism to get this information from the user. In my experience,\nit is almost always preferable to take such values from the\ncommand-line, either from <code>sys.argv</code> directly or, more commonly,\nusing a library like <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a>. The advantages\nto this approach are numerous.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T15:00:57.117", "Id": "514258", "Score": "0", "body": "Thank you so much for the answer, mate. All of your suggestions make sense to me and I'll try to implement all of them If I can." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T21:33:06.157", "Id": "260514", "ParentId": "260505", "Score": "4" } } ]
<p>I'm trying to design a chain of responsibility pattern.</p> <p>It slightly differ from traditional way when handler does only one action on a request, f.e. handles http response considering status code.</p> <p>But my handlers have to do two actions. Below is an (dummy) example where handler asks a question first and then writes the user response to some store:</p> <pre><code># some object where we keep surname and name class Request: pass # some outer storage store = {} # chain of responsibility implementation class PersonIdentifier: def __init__(self) -&gt; None: self.handlers = [] def add_handler(self, handler): if self.handlers: self.handlers[-1].set_next_handler(handler) self.handlers.append(handler) def handle(self, request): return self.handlers[0].handle_request(request) # handlers for chain of responsibility class BaseHandler: handler_name = None def __init__(self) -&gt; None: self.next_handler = None def set_next_handler(self, handler): self.next_handler = handler class SurnameHandler(BaseHandler): handler_name = 'surname' handler_name_answer = 'surname-answer' question = 'Type your surname: ' def handle_request(self, request): if request.handler_name == self.handler_name: return self.question elif request.handler_name == self.handler_name_answer: global store store['surname'] = request.surname del request.surname request.handler_name = 'name' return self.next_handler.handle_request(request) else: return self.next_handler.handle_request(request) class NameHandler(BaseHandler): handler_name = 'name' handler_name_answer = 'name-answer' question = 'Type your name: ' def handle_request(self, request): if request.handler_name == self.handler_name: return self.question elif request.handler_name == self.handler_name_answer: global store store['name'] = request.name user_request = Request() chain = PersonIdentifier() chain.add_handler(SurnameHandler()) chain.add_handler(NameHandler()) # first ask for surname user_request.handler_name = 'surname' surname = input(chain.handle(user_request)) user_request.handler_name = 'surname-answer' user_request.surname = surname # then ask for name name = input(chain.handle(user_request)) user_request.name = name user_request.handler_name = 'name-answer' chain.handle(user_request) print(store) </code></pre> <p>It looks ugly for me. What do I dislike more is using <strong>handler_name</strong> and <strong>handler_name_answer</strong>.</p> <p>May be you could offer nicer way to solve my task?</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T19:20:28.323", "Id": "260624", "Score": "2", "Tags": [ "python" ], "Title": "Chain of Responsibility design" }
260624
max_votes
[ { "body": "<p><em>Chain of Responsibility</em> pattern (hereby &quot;CORP&quot;) includes two things: iteration and &quot;handling&quot;.</p>\n<p>IMO, the iteration part, at least in modern programming languages such as Python and Java, can be easily &quot;extracted&quot; to an external iteration. So eventually the code could look like:</p>\n<pre><code>result = None\nfor handler in handlers:\n temp_result = handler.handle(request)\n if temp_result is not None:\n result = temp_result\n break\nif result is not None:\n # handled!\n</code></pre>\n<p>I think this approach is simpler than maintaining the inner chain, and it has the same impact.</p>\n<p>In CORP, once a handler was found, and it can handle the input, no additional handlers should be executed. It's quite similar to filtering.</p>\n<p>However, I think that the code we have in your question tries to execute <strong>as many handlers as it can</strong> (as it tries to enrich a wider context). So maybe CORP is not really needed here.</p>\n<p>Perhaps you can have enriching classes, that have a method <code>enrich</code> that accepts a request and a context, so that every enriching class could either change the state of the context object, or leave it as is:</p>\n<pre><code>class BaseEnricher:\n def enrich(request, store):\n pass\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T21:10:28.477", "Id": "260626", "ParentId": "260624", "Score": "1" } } ]
<p>I have a function that sums two arrays element-wise and stops if the sum at a certain index is greater strictly than 1. This function is called lot of times (15817145 times for a small simulation and expects to grow a lot more as the simulation size grows). Profiling my code shows that it is among the five most consuming functions of my code and I believe can be optimized further.</p> <pre><code>def add_lis(lis1, lis2): res = [] for i, j in zip(lis1, lis2): if i + j &gt; 1: return res.append(i + j) return array('H', res) </code></pre> <p><code>lis1</code> and <code>lis2</code> are both of type <code>array.array('H',..)</code>. The two lists have the same length which can be up to 100 and they are both filled with zeroes and ones only. I tried with <code>numpy</code> arrays but there is too much overhead that it is not beneficial to use it.</p> <p>My question is can this function be optimized? Maybe in a sort of list comprehension ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T18:38:28.590", "Id": "514486", "Score": "2", "body": "You have framed this as a question of speed. But you also say the lists have 100 or fewer elements (ie, tiny) and the function is called several times (meaning unclear, but it also sounds small-scale). Have you benchmarked the code? How much time is this function costing you and is it worth the effort to optimize? Alternatively, perhaps this isn't really a speed issue and you are curious about different ways someone might write this code more clearly or compactly. Perhaps you can edit your question to clarify your goal or at least explain how a substantive speed issue is at play." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T19:03:10.877", "Id": "514487", "Score": "0", "body": "If `lis1` and `lis2` are long, finding the index of the first above-one sum will be fast with numpy, and this function can be vectorized. But you need to show typical calls to this function, and what `lis1` and `lis2` really contain, along with expected lengths." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T06:10:10.303", "Id": "514598", "Score": "1", "body": "hope my edits clear up your questions @FMc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T14:59:35.337", "Id": "514616", "Score": "0", "body": "@sos Yes, indeed, that clears things up. I think the suggestion to try numpy is a good one. It's a library designed to do such things more quickly at a large scale like that -- at least that's my rough understanding of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T23:03:53.980", "Id": "530731", "Score": "0", "body": "What's the probability that two lists have a sum larger than 1? What's the probability at each position?" } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-12T17:44:45.610", "Id": "260663", "Score": "0", "Tags": [ "python" ], "Title": "addition of two list elementwise with abortion if condition satisfied python" }
260663
max_votes
[ { "body": "<p>You're operating on individual &quot;bits&quot; with Python code. Can be faster to use data types that do the operations in C. One way is to go <code>array</code>→<code>bytes</code>→<code>int</code>→<code>bytes</code>→<code>array</code>, doing the operations at the <code>int</code> level:</p>\n<pre><code>def dont_talk_just_code(lis1, lis2):\n b1 = lis1.tobytes()\n b2 = lis2.tobytes()\n i1 = int.from_bytes(b1, 'big')\n i2 = int.from_bytes(b2, 'big')\n if i1 &amp; i2:\n return\n b = (i1 | i2).to_bytes(len(b1), 'big')\n return array('H', b)\n</code></pre>\n<p>Benchmark results when there is <em>no</em> sum larger than 1:</p>\n<pre><code>18.77 μs 18.97 μs 19.23 μs original\n19.24 μs 19.39 μs 19.57 μs _8349697\n 1.74 μs 1.74 μs 1.78 μs dont_talk_just_code\n</code></pre>\n<p>Benchmark results where there's a sum larger than 1 at index 50:</p>\n<pre><code> 7.94 μs 7.98 μs 8.02 μs original\n 2.48 μs 2.48 μs 2.52 μs _8349697\n 1.10 μs 1.11 μs 1.11 μs dont_talk_just_code\n</code></pre>\n<p>Maybe <code>array</code>→<code>bytes</code>→<code>numpy</code>→<code>bytes</code>→<code>array</code> would be even faster, I didn't try.</p>\n<p>Benchmark code (<a href=\"https://tio.run/##fVRtjpswEP3PKUZabbFTRIF0t7srpb97hyiyTDBZ74KNjFMpVY/WM/RK6dgmEEq0/gF45vHmzYfdneyrVuunzpzPtdEtWNkKaUG2nTYWjOgEt9Flx1Wl28jjuDH8dIH5TbDXR7W3Wjf9xddxYyVvoqgSNWgjD1LxhjSyzxPAZ0FfIsBlRA8b2O78ptYGZAJvIBX8kt0S7ZasQcJnBH2HfLIGLns0Kpq2fcq7TqiK@B9oNIGCdBL/iBOHo0Eme1p/fX58/rYMjEEJWnL6obQrAcswQcRHOdJBRqWVZZY37@zt2Fu215VYxitzrJuzplaXJyt6EvIri2Av/rNLh5fKpq5dLHhKpIxLeYgHSHEDUswhtSP6hNCbWZdIQBDwGwEUBQwkjVAYi86YlgUqMX03Rm4gLgOTjD1JbpUl1GtvcFgF@8kbWZGhPLyqRIVEYXbT/auWe1SyJVkCGSpxb6fIdTWjuwTeN3mWBWlTrZHA9Wjl2SYnmq90O8voKxa@YpbvxI3J4igwNwco8iDIepA@Cz/PzfvvPGL7kO2GTg@f@XiGXBUdr6/m1Kg76Ay2lzjzbO5GhDq2pTCOK8M1mt3l4LrS48EWFQm3AxlOuKdLrlRjVQPPJrwo3b6sdyNZ0LAi8f1DWtTw908PMdwDsfDlEn8FuXikPhXr8vDxkdZFShlTvBWMBdWBjZ7P/wA\" rel=\"nofollow noreferrer\" title=\"Python 3.8 (pre-release) – Try It Online\">Try it online!</a>):</p>\n<pre><code>from timeit import repeat\nimport random\nfrom array import array\nfrom functools import partial\n\ndef original(lis1, lis2):\n res = []\n for i, j in zip(lis1, lis2):\n if i + j &gt; 1:\n return\n res.append(i + j)\n return array('H', res)\n\ndef _8349697(lis1, lis2):\n if (1, 1) in zip(lis1, lis2):\n return\n return array('H', (i + j for i, j in zip(lis1, lis2)))\n\ndef dont_talk_just_code(lis1, lis2):\n b1 = lis1.tobytes()\n b2 = lis2.tobytes()\n i1 = int.from_bytes(b1, 'big')\n i2 = int.from_bytes(b2, 'big')\n if i1 &amp; i2:\n return\n b = (i1 | i2).to_bytes(len(b1), 'big')\n return array('H', b)\n\nfuncs = original, _8349697, dont_talk_just_code\n\ndef create_valid():\n added = random.choices([(0, 0), (0, 1), (1, 0)], k=100)\n lis1, lis2 = zip(*added)\n lis1 = array('H', lis1)\n lis2 = array('H', lis2)\n return lis1, lis2\n\nfor _ in range(3):\n lis1, lis2 = create_valid()\n # lis1[50] = lis2[50] = 1\n for func in funcs:\n # print(func(lis1, lis2))\n number = 10000\n times = sorted(repeat(partial(func, lis1, lis2), number=number))[:3]\n print(*('%5.2f μs ' % (t / number * 1e6) for t in times), func.__name__)\n print()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T23:28:42.853", "Id": "530732", "Score": "1", "body": "Ugh, just realized this is an old question, only got \"bumped\" by the stupid \"Community Bot\". Oh well..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T23:25:55.267", "Id": "269051", "ParentId": "260663", "Score": "1" } } ]
<p>This is my first post here. I seek to improve my way of writing Python and C++ code. I hope I can also contribute to others when I have increased my skill.</p> <p>Here is a python function I have for a neural network I have implemented. I feel it become a bit cumbersome. The intention is to weight positive labels in channels <code>1:end</code> higher than background pixels. Hence the distinction between foreground and background.</p> <pre><code>def loss_function( self, x: torch.tensor, groundtruth: torch.tensor, weight: float ) -&gt; torch.tensor: delta = 0.00001 groundtruth_pos = groundtruth[:, 1:, :, :] == 1 groundtruth_neg = groundtruth[:, 1:, :, :] == 0 foreground_gt = groundtruth[:, 1:, :, :] background_gt = groundtruth[:, 0, :, :] foreground_x = x[:, 1:, :, :] background_x = x[:, 0, :, :] loss_foreground_pos = -(torch.sum(foreground_gt[groundtruth_pos] * torch.log(foreground_x[groundtruth_pos] + delta)) + torch.sum((1 - foreground_gt[groundtruth_pos]) * torch.log(1 - foreground_x[groundtruth_pos] + delta))) loss_foreground_neg = -(torch.sum(foreground_gt[groundtruth_neg] * torch.log(foreground_x[groundtruth_neg] + delta)) + torch.sum((1 - foreground_gt[groundtruth_neg]) * torch.log(1 - foreground_x[groundtruth_neg] + delta))) loss_background = -(torch.sum(background_gt * torch.log(background_x + delta)) + torch.sum((1 - background_gt) * torch.log(1 - background_x + delta))) return weight * loss_foreground_pos + loss_foreground_neg + loss_background </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T12:47:11.243", "Id": "514607", "Score": "0", "body": "The code does not compile since it is missing the `import` statements. Here at Code Review we prefer self-contained compilable code snippets that allow us reviewers to run the code with some example data. (This is just a remark for your future questions. Since this question already has an answer, leave the question as it is now.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T13:04:50.633", "Id": "514665", "Score": "0", "body": "Thanks, then I know!" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T07:33:20.150", "Id": "260693", "Score": "2", "Tags": [ "python", "neural-network", "pytorch" ], "Title": "Loss function in python is a bit cumbersome" }
260693
max_votes
[ { "body": "<p>It looks like you need to calculate the same thing over and over again. Instead of doing this separately for the positive, the negative and all labels (not sure that is the correct word), you could do it once and then use that once you need to calculate the sums:</p>\n<pre><code>def loss_function(\n self,\n x: torch.tensor,\n groundtruth: torch.tensor,\n weight: float\n) -&gt; torch.tensor:\n\n delta = 0.00001\n foreground_gt = groundtruth[:, 1:, :, :]\n background_gt = groundtruth[:, 0, :, :]\n groundtruth_pos = foreground_gt == 1\n groundtruth_neg = foreground_gt == 0\n\n foreground_x = x[:, 1:, :, :] + delta\n background_x = x[:, 0, :, :] + delta\n\n a = foreground_gt * torch.log(foreground_x)\n b = (1 - foreground_gt) * torch.log(1 - foreground_x)\n c = a + b\n\n loss_foreground_pos = -torch.sum(c[groundtruth_pos])\n loss_foreground_neg = -torch.sum(c[groundtruth_neg])\n\n loss_background = -torch.sum(background_gt * torch.log(background_x))\n + (1 - background_gt) * torch.log(1 - background_x))\n return weight * loss_foreground_pos + loss_foreground_neg + loss_background\n</code></pre>\n<p>Note that <code>sum(a) + sum(b)</code> is the same as <code>sum(a + b) = sum(c)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T12:05:36.717", "Id": "260735", "ParentId": "260693", "Score": "1" } } ]
<p>This is my first post here. I seek to improve my way of writing Python and C++ code. I hope I can also contribute to others when I have increased my skill.</p> <p>Here is a python function I have for a neural network I have implemented. I feel it become a bit cumbersome. The intention is to weight positive labels in channels <code>1:end</code> higher than background pixels. Hence the distinction between foreground and background.</p> <pre><code>def loss_function( self, x: torch.tensor, groundtruth: torch.tensor, weight: float ) -&gt; torch.tensor: delta = 0.00001 groundtruth_pos = groundtruth[:, 1:, :, :] == 1 groundtruth_neg = groundtruth[:, 1:, :, :] == 0 foreground_gt = groundtruth[:, 1:, :, :] background_gt = groundtruth[:, 0, :, :] foreground_x = x[:, 1:, :, :] background_x = x[:, 0, :, :] loss_foreground_pos = -(torch.sum(foreground_gt[groundtruth_pos] * torch.log(foreground_x[groundtruth_pos] + delta)) + torch.sum((1 - foreground_gt[groundtruth_pos]) * torch.log(1 - foreground_x[groundtruth_pos] + delta))) loss_foreground_neg = -(torch.sum(foreground_gt[groundtruth_neg] * torch.log(foreground_x[groundtruth_neg] + delta)) + torch.sum((1 - foreground_gt[groundtruth_neg]) * torch.log(1 - foreground_x[groundtruth_neg] + delta))) loss_background = -(torch.sum(background_gt * torch.log(background_x + delta)) + torch.sum((1 - background_gt) * torch.log(1 - background_x + delta))) return weight * loss_foreground_pos + loss_foreground_neg + loss_background </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T12:47:11.243", "Id": "514607", "Score": "0", "body": "The code does not compile since it is missing the `import` statements. Here at Code Review we prefer self-contained compilable code snippets that allow us reviewers to run the code with some example data. (This is just a remark for your future questions. Since this question already has an answer, leave the question as it is now.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T13:04:50.633", "Id": "514665", "Score": "0", "body": "Thanks, then I know!" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-13T07:33:20.150", "Id": "260693", "Score": "2", "Tags": [ "python", "neural-network", "pytorch" ], "Title": "Loss function in python is a bit cumbersome" }
260693
max_votes
[ { "body": "<p>It looks like you need to calculate the same thing over and over again. Instead of doing this separately for the positive, the negative and all labels (not sure that is the correct word), you could do it once and then use that once you need to calculate the sums:</p>\n<pre><code>def loss_function(\n self,\n x: torch.tensor,\n groundtruth: torch.tensor,\n weight: float\n) -&gt; torch.tensor:\n\n delta = 0.00001\n foreground_gt = groundtruth[:, 1:, :, :]\n background_gt = groundtruth[:, 0, :, :]\n groundtruth_pos = foreground_gt == 1\n groundtruth_neg = foreground_gt == 0\n\n foreground_x = x[:, 1:, :, :] + delta\n background_x = x[:, 0, :, :] + delta\n\n a = foreground_gt * torch.log(foreground_x)\n b = (1 - foreground_gt) * torch.log(1 - foreground_x)\n c = a + b\n\n loss_foreground_pos = -torch.sum(c[groundtruth_pos])\n loss_foreground_neg = -torch.sum(c[groundtruth_neg])\n\n loss_background = -torch.sum(background_gt * torch.log(background_x))\n + (1 - background_gt) * torch.log(1 - background_x))\n return weight * loss_foreground_pos + loss_foreground_neg + loss_background\n</code></pre>\n<p>Note that <code>sum(a) + sum(b)</code> is the same as <code>sum(a + b) = sum(c)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T12:05:36.717", "Id": "260735", "ParentId": "260693", "Score": "1" } } ]
<p>I am trying to solve a set of differential equations in x,y,z, I have made simple kutta 2 code in python before but not with 3 variables. I am not sure if what i have done is an acceptable way to adjust for 3. Here is what i have so far: (i have not entered the exact solution as i do not know it)</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Define function to compute velocity field A = 0.2 B = 1.0 C = 0.20 def velfun(x,y,z,t): xvelocity = (A*np.sin(z) + C*np.cos(x)) yvelocity = (B*np.sin(x) + A*np.cos(z)) zvelocity = (C*np.sin(y) + B*np.cos(x)) return xvelocity, yvelocity, zvelocity # Set stopping time # and the step length Nstep = 10000 h = 0.01 # Create arrays to store x and t values x = np.zeros(Nstep); y = np.zeros(Nstep); z = np.zeros(Nstep); # Set the initial condition x[0] = 1 y[0] = 0 z[0] = 0 # Carry out steps in a loop for k in range(1,Nstep): # Provisional Euler step xx = x[k-1] yy = y[k-1] zz = z[k-1] ux,uy,uz = velfun(xx,yy,zz) xp = x[k-1] + h*ux yp = y[k-1] + h*uy zp = z[k-1] + h*uz # Compute velocity at provisional point uxp,uyp,uzp = velfun(xp,yp,zp) # Compute average velocity uxa = 0.5*(ux + uxp) uya = 0.5*(uy + uyp) uza = 0.5*(uz + uzp) # Make final Euler step # using average velocity x[k] = x[k-1] + h*uxa y[k] = y[k-1] + h*uya z[k] = z[k-1] + h*uza # Exact solution # Plot results fig = plt.figure() ax = plt.axes(projection='3d') ax = plt.axes(projection='3d') ax.scatter3D(x,y,z,'b',label='x (with RK2)') plt.show() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T14:23:32.227", "Id": "514613", "Score": "1", "body": "Anyway, this will not run: your `velfun` expects four parameters but you only ever pass three." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T06:59:26.713", "Id": "514654", "Score": "0", "body": "its not a typo and i have adjusted the velfun, the code runs i am just unsure if the solution is in any way accurate" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-23T07:08:37.933", "Id": "515222", "Score": "0", "body": "Cross-posted from https://math.stackexchange.com/questions/4137970/runge-kutta-2-in-python. The system should probably be the Arnold-Beltrami-Childress ABC dynamic, with variables and constants cyclic in all positions." } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T11:56:51.200", "Id": "260734", "Score": "3", "Tags": [ "python", "mathematics" ], "Title": "Runge Kutta 2 Python ODE fluid flow" }
260734
max_votes
[ { "body": "<p>This is an interesting problem but I'm afraid that my feedback will be somewhat limited:</p>\n<ul>\n<li>Consider vectorizing your <code>velfun</code> to be represented with matrix multiplications</li>\n<li>Your <code>x</code>/<code>y</code>/<code>z</code> should be combined into one matrix</li>\n<li>You should add axis labels, and some form of colour indicator to make your graph more legible - here I've added an arbitrary &quot;start-to-finish progress&quot; colour</li>\n<li>Rather than <code>label</code>, you likely meant to use <code>title</code></li>\n</ul>\n<p>The code I'm suggesting produces exactly the same results as yours. The problem is that I have no idea whether those are correct. I suggest that you re-post on <a href=\"https://physics.stackexchange.com/\">https://physics.stackexchange.com/</a> with more details on your physics problem to get confirmation as to whether your RK is implemented correctly. You should include a picture of your graph.</p>\n<h2>Suggested</h2>\n<pre><code>from typing import Tuple\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nA = 0.2\nB = 1.0\nC = 0.20\n\nN_STEP = 10_000 # stopping time\nH = 0.01 # step length\n\n\ndef new() -&gt; np.ndarray:\n M = np.array([\n [0, 0, A],\n [B, 0, 0],\n [0, C, 0],\n ])\n N = np.array([\n [C, 0, 0],\n [0, 0, A],\n [B, 0, 0],\n ])\n\n # Define function to compute velocity field\n def velfun(p: np.ndarray) -&gt; np.ndarray:\n return M@np.sin(p) + N@np.cos(p)\n\n X = np.empty((3, N_STEP))\n a = np.array((1, 0, 0), dtype=np.float64)\n X[:, 0] = a\n\n for k in range(1, N_STEP):\n # Provisional Euler step\n u = velfun(a)\n p = a + H*u\n\n # Compute velocity at provisional point\n up = velfun(p)\n\n # Compute average velocity\n ua = 0.5*(u + up)\n\n # Make final Euler step\n # using average velocity\n a += H*ua\n X[:, k] = a\n\n return X\n\n\ndef plot(x, y, z):\n # Plot results\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n ax.set_title('x (with RK2)')\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n colour = np.linspace(0, 1, len(x))\n\n ax.scatter3D(x, y, z, s=0.5, c=colour)\n\n\ndef main():\n # plot(*old())\n plot(*new())\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Be warned: I have very little understanding of what this code is actually doing, so my variable names are bad.</p>\n<p><a href=\"https://i.stack.imgur.com/KOYfT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KOYfT.png\" alt=\"plot\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T20:38:04.173", "Id": "514644", "Score": "1", "body": "Very nice code especially if you haven't ever done something similar. `a` is some point in space. `velfun(a)` is the velocity at that point. `H` is the step size, i.e. length of time between two successive numerical approximations. I would use `h` for the latter. `x` instead of `a` for a point in space. If you are interested, a possible next step is writing code that takes the [Butcher tableau](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods) of an explicit method (the tableau is then strictly lower triangular), and yields the method itself as a function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T18:48:50.183", "Id": "260750", "ParentId": "260734", "Score": "2" } } ]
<p>My code does a DFS on the given graph and prints all possible paths for a given start and end node. My question is how can this be improved?</p> <ol> <li>Can some form of memoization be used here? There are cases where a path from a certain source - destination is already found and will be an intermediate path for a different source - destination but it is still computed again.</li> <li>As it is a generator will that make memoization different?</li> <li>Is there an already existing text book algorithm that I am missing? Does not have to be specifically DFS.</li> <li>Pythonic / Idiomatic code suggestions are also welcome.</li> </ol> <p>This is my code</p> <pre><code>from itertools import product def find_path(g, src, dst): &quot;&quot;&quot;Prints all possible path for a graph `g` for all pairs in `src` and `dst` Args: g (list): 2d list, graph src (list): list of nodes that will be the source dst (list): list of nodes that will be the destination &quot;&quot;&quot; graph = {} # constructing a graph for from_, to_ in g: graph.setdefault(from_, set()).add(to_) graph.setdefault(to_, set()).add(from_) # undirected def dfs(src, dst, path, seen): &quot;&quot;&quot;Recursive generator that yields all paths from `src` to `dst` Args: src (int): source node dst (int): destination node path (list): path so far seen (set): set of visited nodes Yields: list: all paths from `src` to `dst` &quot;&quot;&quot; if src in seen: return if src == dst: yield path + [src] return seen.add(src) for i in graph.get(src, []): yield from dfs(i, dst, path + [src], seen) seen.remove(src) # start finding path for all `src` `dst` pairs for source, destination in product(src, dst): print(source, destination, list(dfs(source, destination, [], set()))) g = list(product(range(1, 5), repeat=2)) # a graph for testing purpose src = dst = range(1, 5) # source and destination, in actual code this will be a list find_path(g, src, dst) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T10:46:37.457", "Id": "514659", "Score": "0", "body": "Is there any additional details needed?" } ]
{ "AcceptedAnswerId": "260856", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T13:54:11.470", "Id": "260737", "Score": "8", "Tags": [ "python", "performance", "recursion", "graph", "memoization" ], "Title": "Find all paths in a graph" }
260737
accepted_answer
[ { "body": "<ol>\n<li>I don't think memoization will be useful here. Any correct algorithm is going to be <em>O(n!)</em>, nothing you do can reduce that fundamentally because you still have to <em>output</em> all the paths.<br />\nTrying to cache stuff you already output is just going to make the space-costs worse, it won't make the processing-time any better.</li>\n<li>The advantages of using a generator are that the caller doesn't have to wait for the whole computation to finish before handling the early outputs, and that we never have to <em>store</em> the results of the whole computation at once. This is a good choice for the task at hand!<br />\nIt doesn't affect the point in (1.) though.</li>\n<li><a href=\"https://www.baeldung.com/cs/simple-paths-between-two-vertices\" rel=\"noreferrer\">You seem to have already found the textbook algorithm.</a></li>\n<li>There are various things to make the code prettier, but you'd have to do some testing to see if they make it work better.\n<ul>\n<li>Types are nice. They do nothing at runtime, but they let <a href=\"http://mypy-lang.org/\" rel=\"noreferrer\">MyPy</a> check for many kinds of mistakes.</li>\n<li>I don't like the redundancy of <code>path</code> and <code>seen</code>, and I don't like that you're mutating <code>seen</code> the way you are, but I suspect the way you've written it is actually the most efficient for larger graphs.</li>\n<li>The expression <code>path + [src]</code> makes two calls to the <code>list</code> constructor, and it's happening inside the <code>for</code> loop. That can be improved!</li>\n<li>Since you never mutate a value of <code>path</code>, it can be a tuple instead of a list.</li>\n<li>The way you have it set up now, your adjacencies dict will always contain <code>src</code>, so you don't need to use <code>get</code>.</li>\n</ul>\n</li>\n</ol>\n<p>I'm ignoring your outer wrapper, and I've made no effort to test this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterable, Mapping, MutableSet, Sequence, TypeVar\nN = TypeVar('N')\ndef dfs(source: N, # The current node\n destination: N, # The destination node\n path: Sequence[N], # The path taken to the current node\n seen: MutableSet[N], # The nodes visited on the path\n graph: Mapping[N, Iterable[N]] # The graph being explored, as an adjacency dict\n) -&gt; Iterable[Sequence[N]]:\n new_path = (*path, source)\n if source == destination:\n yield new_path\n else:\n seen.add(source)\n for n in graph[source]:\n if n not in seen:\n yield from dfs(n, destination, new_path, seen, graph)\n seen.remove(source)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T00:33:41.023", "Id": "514810", "Score": "0", "body": "thank you for answering this, *\"don't like that you're mutating seen the way you are\"*, can you suggest any other ways this can be done?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T20:12:30.160", "Id": "514871", "Score": "0", "body": "The other options would be to make a new set for the recursive `seen`, like you you're doing with `path`. Mutating values is often efficient, but opens up its own class of bugs. But as I understand it's somewhat expensive to spin up a new `set` instance (relative to other basic structures), so for this purpose your way is probably better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T01:01:29.817", "Id": "514884", "Score": "0", "body": "I have one other question, assume a path exists like so `'1 -> 2 -> 3 -> 4 -> 5 -> 6'` and before that computation, I have already computed `'2 -> 3 -> 4 -> 5'`, that was what I meant when I said how memoization can be used, as you can see, the second path is part of the result of the first path, can I not take advantage of this? I will clarify if you need more details" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T01:01:47.043", "Id": "514885", "Score": "0", "body": "also, I will give the bounty to you if I dont get any other even more well written answer, just want to clarify things before :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T02:13:56.723", "Id": "514887", "Score": "0", "body": "I understand what you mean by memoization, and I don't think it's going to help here. Suppose you've cached (memoized) the `2...5` path. Probably you've also cached all the other paths from 2. Great, but three problems: 1) You still have to iterate over all those `2...` paths and output them; I don't think you can do that _fundamentally_ faster than just rebuilding them all as-needed. 2) You have to store them all somewhere; that could be costly and/or slow. 3) You can't just iterate over _all_ of them; any containing a `1` must be excluded, so there's still extra computation to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T03:27:06.720", "Id": "514891", "Score": "0", "body": "I understand it now, thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-22T02:15:18.153", "Id": "515143", "Score": "0", "body": "thank you @ShapeOfMatter" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-17T15:59:12.010", "Id": "260856", "ParentId": "260737", "Score": "8" } } ]
<p>I want to create a COM server to expose scipy to VBA code, as performing integration is kinda difficult and I don't know of any good VBA/COM libraries for this. My objectives are:</p> <ul> <li>As portable as possible</li> <li>Fast</li> <li>Maintainable</li> </ul> <p>Here's the python:</p> <pre class="lang-py prettyprint-override"><code># Requires C:\Users\...\anaconda3\Library\bin on the PATH from scipy import integrate from win32com.client import Dispatch from typing import Callable import comtypes class ScipyWrapper: # pythoncom.CreateGuid() _reg_clsid_ = &quot;{A621AB64-9378-4B54-A7D3-20711C0B72DB}&quot; _reg_desc_ = &quot;Python Scipy COM Server&quot; _reg_progid_ = &quot;PythonCOM.ScipyWrapper&quot; _reg_clsctx_ = comtypes.CLSCTX_LOCAL_SERVER # don't want inproc because conda not supported on 64 bit # see https://stackoverflow.com/q/67462529/6609896 _public_methods_ = [&quot;quad&quot;,] # _public_attrs_ = [] # _readonly_attrs_ = [] def quad(self, vbFunc, a: float, b: float) -&gt; float: vb_dispatch = Dispatch(vbFunc) func: Callable[[float], float] = vb_dispatch.Evaluate # Callable[..., float]? return integrate.quad(func, a, b)[0] # only return val, not uncertainty if __name__ == &quot;__main__&quot;: import win32com.server.register win32com.server.register.UseCommandLine(ScipyWrapper) </code></pre> <p>Called from VBA (twinBasic) like:</p> <pre class="lang-vb prettyprint-override"><code>Module Main Public Sub doStuff() Dim integrator as Object = CreateObject(&quot;PythonCOM.ScipyWrapper&quot;) Dim func as IOneDimensionalFunction = New XSquared 'this is what we'll integrate Debug.Print integrator.quad(func, 0., 1.) 'integrate x^2 from 0-&gt;1, returns 0.333333... End Sub End Module '@Description(&quot;Interface for a f(x) -&gt; y function, with optional parameters&quot;) Class IOneDimensionalFunction Public Function Evaluate(ByVal x As Double, ParamArray parameters() as Variant) As Double End Function End Class Class XSquared Implements IOneDimensionalFunction Private Function IOneDimensionalFunction_Evaluate(ByVal x As Double, ParamArray parameters() as Variant) As Double Return x^2 End Function End Class </code></pre> <h3>Questions:</h3> <ul> <li>Not sure how to Type the python, <code>vbFunc</code> is a PyIDispatch instance but not sure what that means for typing/mypy.</li> <li>I'd like to use strong typing to protect my python, right now it's duck typed and I could easily pass an Interface without the Evaluate method, or anything else for that matter.</li> <li>No idea how to handle python errors and turn them into COM errors.</li> <li>Is this ref-count safe?</li> </ul> <p>OFC any other tips on general style, use of comments and naming etc. are welcome :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T19:15:54.507", "Id": "514637", "Score": "0", "body": "What problem did you intend to solve with this? Python can do a lot of direct communication with Office software, ignoring VBA altogether." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T19:24:26.880", "Id": "514639", "Score": "1", "body": "@Mast I need the integration to do convolution of probability distributions, which I'm after for a code profiling library in VBA. I could do post processing of data in a python script but I think it's cleaner if I can import a VBA library without any kind of file IO to communicate with python, going through COM is smoother" } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T18:02:07.003", "Id": "260749", "Score": "5", "Tags": [ "python", "beginner", "vba", "com" ], "Title": "Simple python COM server to expose scipy integration to VBA" }
260749
max_votes
[ { "body": "<h2>Deferred Imports</h2>\n<p>Why is <code>import win32com.server.register</code> only imported during <code>__main__</code>? It should be inexpensive and clean to just leave it at the top with everything else. I'd also de-namespace <code>from win32com.server.register import UseCommandLine</code> but that's mostly a matter of taste.</p>\n<h2>Stubbing</h2>\n<p>You ask:</p>\n<blockquote>\n<p>vbFunc is a PyIDispatch instance but not sure what that means for typing/mypy</p>\n</blockquote>\n<p>If <code>PyIDispatch</code> is an importable type, then simply</p>\n<pre><code>def quad(self, vbFunc: PyIDispatch, a: float, b: float) -&gt; float:\n</code></pre>\n<p>If it's not importable at all (this can happen for some libraries that are aggressively dynamic), then you basically have two options:</p>\n<ul>\n<li>Declare an opaque, named <a href=\"https://docs.python.org/3/library/typing.html#newtype\" rel=\"nofollow noreferrer\"><code>NewType</code></a> to make it clear to callers that this is not just &quot;anything&quot;</li>\n<li>Do the work that the library should have done for you, and <a href=\"https://www.python.org/dev/peps/pep-0484/#stub-files\" rel=\"nofollow noreferrer\">stub it yourself</a> using a custom <code>.pyi</code></li>\n</ul>\n<h2>Call protocols</h2>\n<pre><code># Callable[..., float]?\n</code></pre>\n<p>You're right to be confused, and mypy is still fairly terrible at annotating variadic callables. Here you should consider using <a href=\"https://docs.python.org/3/library/typing.html#typing.Protocol\" rel=\"nofollow noreferrer\"><code>Protocol</code></a>:</p>\n<pre><code>class DispatchCall(typing.Protocol):\n def __call__(self, x: float, *parameters: COMCompatibleTypes) -&gt; float:\n ... # literally an ellipsis\n\n# Later:\n\nfunc: DispatchCall = vb_dispatch.Evaluate\n</code></pre>\n<h2>Unpacking</h2>\n<p>Re.</p>\n<pre><code>return integrate.quad(func, a, b)[0] # only return val, not uncertainty\n</code></pre>\n<p>it's worth noting that uncertainty is not the only thing <code>quad</code> <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html\" rel=\"nofollow noreferrer\">returns</a>; there's actually <code>y</code>, <code>abserr</code>, <code>infodict</code>, <code>message</code> and <code>explain</code>.</p>\n<p>It's minor, but I typically prefer to do at least a partial unpack to make it a little more clear what's happening:</p>\n<pre><code>y, *_ = integrate.quad(func, a, b)\n</code></pre>\n<p>Given the tuple length I don't think I'd do this, but you can if you think it adds clarity:</p>\n<pre><code>y, abserr, infodict, message, explain = integrate.quad(func, a, b)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T18:05:06.117", "Id": "514947", "Score": "0", "body": "I'm still not entirely sure how to typehint `func` inside `quad`. if quad is `quad(func, a:float, b:float, args:Tuple)` then func *must* accept a Tuple arg (`Callable[[float,Tuple],float]`. If a tuple is not passed to quad then func *may* accept a Tuple arg `Callable[[float,Tuple],float] | Callable[[float],float] | Callable [[float, *args],float]`. There may be some @overload I can do... Moreover Evaluate really looks like`__call__(self, x: float, *args: COMCompatibleTypes) -> float:` where `COMCompatibleTypes` does not include Tuple..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T18:07:20.883", "Id": "514948", "Score": "0", "body": "... Since the `*args` can be left out, the function sig is compatible with `Callable[[float],float]` for func, but not `Callable[[float, Tuple],float]`. This means when I pass a tuple to quad(), I want mypy to warn me that func is expected to be `Callable[[float, Tuple],float]` which is not compatible with `__call__(self, x: float, *args: COMCompatibleTypes) -> float` even though that *is* compatible with the signature of func when a Tuple is not passed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T18:25:19.817", "Id": "514950", "Score": "0", "body": "Where does the `Tuple` come from? Does that correspond to `ParamArray parameters() as Variant` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T19:17:53.620", "Id": "514959", "Score": "0", "body": "No, `ParamArray parameters() As Variant => *args: COMCompatibleTypes`, `Tuple` comes from `scipy.integrate.quad(func, a: float, b:float, args: Tuple=(), ...)` (see [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html?highlight=scipy%20integrate%20romb)). Sorry yeah that was sort of confusing, hope this makes sense. FWIW COMCompatibleTypes is not something that exists yet, but COMCompatibleTypes does contain `float` which can be coerced to a COM double, whereas it does not contain `Tuple` as there is not a COM equivalent (currently) - it would error in pywin32" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T23:10:58.127", "Id": "514967", "Score": "0", "body": "I'm really confused now. Is `COMCompatibleTypes` a sequence type or an element type? For it to be used with `*` it needs to be an element type. Are you actually going to be passing in a tuple, as in `func(1.0, (2.0, 3.0))`? Or are you going to be passing in variadic arguments like `func(1.0, 2.0, 3.0)`? If the latter, your hint should not be `Tuple`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T23:58:39.090", "Id": "514969", "Score": "1", "body": "Scipy quad accepts (optional) arguments and forwards them onto func as a tuple. However my func implementation is defined in VBA to accept arguments in the variadic form with ParamArray. Consequently, as these two definitions for arguments are incompatible, I want mypy to enforce that *no additional arguments* are passed, as the variadic signature cannot be invoked with a tuple so the only way to make the 2 signatures compatible is to remove any optional arguments. COMCompatibleTypes is a Union type of a few things, for the sake of this, let's say it is `typing.Any except Tuple` (pseudo code)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T14:39:47.660", "Id": "515030", "Score": "2", "body": "Crucially, whereas [scipy quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html) accepts extra arguments as a tuple, it does not _pass them on_ as a tuple. It unpacks them. This calls for a plain `*args: float`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T12:54:58.387", "Id": "515303", "Score": "1", "body": "This is what I was hoping for with the type hinting https://stackoverflow.com/q/67649533/6609896. I think it may require the new PEP 612 -- Parameter Specification Variables but not sure. The problem with Protocol is that it doesn't seem to play nicely with Callable, so I can't pass a custom callable that matches the protocol - e.g. a python function or lambda, and must manually typehint callables to match the protocol which is a bit weird. It's maybe fine here since the Evaluate function needs to be typehinted in python anyway, however it arbitrarily restricts the sig of my scipy stub method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T00:07:53.440", "Id": "515572", "Score": "0", "body": "Thanks for the bounty. Procedurally I toyed with the idea of copying my answer in https://stackoverflow.com/questions/67649533/how-to-typehint-a-function-which-takes-a-callable-and-its-args-as-parameters-e/67674066#67674066 to here but decided against it." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T11:20:15.260", "Id": "260932", "ParentId": "260749", "Score": "2" } } ]
<p>I have come with such a code for checking IP addresses. But would like to know how clean and good it is from 1 to 10. What I care about are readability and simplicity. Please give me any feedback.</p> <p>Should I go here with unittests?</p> <pre class="lang-py prettyprint-override"><code>import re import logging logging.basicConfig(level=logging.ERROR) pattern = re.compile(r'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$') def is_in_bounds(s): return int(s) &gt;= 0 and int(s) &lt;= 255 def is_leading_zeros(s): if s is not '0': return s[0] is not '0' return True def validate_ipv4(ipv4: str, expectFail: bool = False) -&gt; bool: logging.info(f&quot;Validating IP '{ipv4}' START.&quot;) try: match = pattern.match(ipv4) assert(match) groups = match.groups() assert(len(groups)==4) for s in match.groups(): assert(is_leading_zeros(s)) assert(is_in_bounds(s)) logging.info(f&quot;Validating IP '{ipv4}' SUCCESS.&quot;) except AssertionError: logging.info(f&quot;Validating IP '{ipv4}' FAILED.&quot;, exc_info=True) if not expectFail: raise if __name__ == '__main__': octets = [] octets.extend(range(0,3)) octets.extend(range(9,12)) octets.extend(range(98,102)) octets.extend(range(198,202)) octets.extend(range(250,256)) for i in octets: for j in octets: for k in octets: for l in octets: validate_ipv4(f'{i}.{j}.{k}.{l}') octets = [] octets.extend(range(-3,0)) octets.extend(range(256, 260)) exceptions = [] for i in octets: for j in octets: for k in octets: for l in octets: validate_ipv4(f'{i}.{j}.{k}.{l}', True) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T13:32:42.860", "Id": "514666", "Score": "0", "body": "Where and how is this going to be used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-17T21:02:54.230", "Id": "514785", "Score": "0", "body": "It's my attempt to learn how to avoid doing complex regex everywhere. I'm devops currently, so maybe will have some use for networking setup scripts." } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T09:26:12.993", "Id": "260761", "Score": "7", "Tags": [ "python", "regex", "validation" ], "Title": "readable validation with python regex and simple logic" }
260761
max_votes
[ { "body": "<h1>When to use <code>is not</code></h1>\n<p>Your usage of <code>is not</code> is incorrect. You want to use <code>==</code> when you're testing <strong>equality</strong>, like when you check if <code>s</code> doesn't equal a <code>'0'</code>. You want to use <code>is not</code> when checking for <strong>identity</strong>, like when you're ensuring two variables are of the same object.</p>\n<pre><code>def is_leading_zeros(s: str) -&gt; bool:\n if s != '0':\n return s[0] != '0'\n return True\n</code></pre>\n<h1>Clearer comparisons</h1>\n<p>Python has a syntax that allows you to do this:</p>\n<pre><code>def is_in_bounds(s: str) -&gt; int:\n return 0 &lt;= int(s) &lt;= 255\n</code></pre>\n<h1>Type Hints</h1>\n<p>You should add types hints to your functions, which display what types are accepted and returned from your functions. See above for an example of this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T12:12:03.797", "Id": "260766", "ParentId": "260761", "Score": "5" } } ]
<pre><code># get rank which takes the users rank as an argument and determines # if it is valid input def getRank(x): # make a list of the acceptable choices choices = ['l','m','h'] # convert the users rank to lowercase x = x.lower() # create a while True loop that only runs if x is not in the choices while True: if x not in choices: # remind the user of the valid choices print('Only enter a valid choices') print(choices[0:3]) x = input('Please enter a rank: ') x = x.lower() # add an if statement to continue the loop if the users new input is still incorrect if x not in choices: continue # if everything is all good break from the loop else: break return x def main(): print('Please enter a ranking for the items') print('l for low,m for medium,h for high') print('') print('Please enter a rank for milk') # prompt the user to enter their rate userRate = input('Please enter a rank: ') # validate their input validRank = getRank(userRate) # assign the users rating to validRank as it will only hold a valid choice # continue doing this for each item milkRate = validRank print('Please enter a rank for cheese') userRate = input('Please enter a rank: ') validRank = getRank(userRate) cheeseRank = validRank print('Please enter a rank for eggs') userRate = input('Please enter a rank: ') validRank = getRank(userRate) eggRank = validRank print('') #output the users ratings for the items print('Your overall ratings are:') print('Milk:',milkRate) print('Cheese:',cheeseRank) print('Eggs:',eggRank) main() </code></pre> <p>Hi everyone! I'm a first year student and I would really love some tips to better my logic here. The above program does exactly what I want it to do: Display an item to the user, ask the user for their rank, validate that their rank is one of 3 choices case insensitive. If its invalid it requests reinput until it is. While this code works, I know there are oppurtunities for me to write better logic here.</p> <p>I am open to all critiques here! Would just love feedback from the community</p>
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-16T22:17:50.443", "Id": "260823", "Score": "3", "Tags": [ "python" ], "Title": "This program asks users to rank an item and validates the rank" }
260823
max_votes
[ { "body": "<p>For printing multiple lines, instead of multiple print statements, you can use triple quotes.</p>\n<pre><code>&quot;&quot;&quot;Please enter a ranking for the items\nl for low, m for medium, h for high\n&quot;&quot;&quot;\n</code></pre>\n<p>This is equivalent to the first three lines in <code>main()</code></p>\n<p>Also, merging the input prompt and print statement above for all the 3 items might simplify the code.</p>\n<p>For example for milk,</p>\n<pre><code>userRate = input('Please enter a rank for milk: ')\nmilkRate = getRank(userRate)\n</code></pre>\n<p>Instead of</p>\n<pre><code>print('Please enter a rank for milk')\nuserRate = input('Please enter a rank: ')\nvalidRank = getRank(userRate)\nmilkRate = validRank\n</code></pre>\n<p>You may also use dictionaries to store the data of items and print them out (if possible), so that repetitive code parts (boilerplate) can be replaced with loops.</p>\n<p>The suggestions are simple ones but might simplify your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T12:36:17.017", "Id": "261420", "ParentId": "260823", "Score": "1" } } ]
<p>Recently, I made this gif opener using tkinter:</p> <pre><code>import tkinter as tk from tkinter import filedialog as fd import time import threading def getfile(): file = fd.askopenfilename() window = tk.Toplevel() def run_gif(): i = 0 while True: try: photo = tk.PhotoImage(file = file,format=&quot;gif -index&quot; +' '+ str(i)) gif = tk.Label(window, image=photo) gif.grid(row=0,column=0) i += 1 time.sleep(0.0001) except: i = 0 gif_thread=threading.Thread(target=run_gif) gif_thread.start() window.mainloop() def display(): root = tk.Tk() root.title(&quot;.gif opener&quot;) root.geometry('50x100') root.configure(bg = &quot;lightgreen&quot;) label = tk.Label(root, text = &quot;.gif opener&quot;) label.pack() button = tk.Button(root, text = &quot;File&quot;, command = getfile) button.place(x = &quot;50&quot;, y= &quot;50&quot;) root.mainloop() display() </code></pre> <p>However, every time I open a gif, the animation is really laggy.</p> <p>Is there any way to make the gifs flow smoother? Any help will be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-17T16:39:06.650", "Id": "514767", "Score": "0", "body": "Why is there a `sleep()`?" } ]
{ "AcceptedAnswerId": "260918", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-16T22:52:59.167", "Id": "260826", "Score": "2", "Tags": [ "python", "performance", "tkinter" ], "Title": "Is there any way to stop the lag in this Gif opener?" }
260826
accepted_answer
[ { "body": "<p>Your problem may be similar to this one:</p>\n<p><a href=\"https://stackoverflow.com/questions/50904093/gif-animation-in-tkinter-with-pill-flickering-on-every-other-frame\">https://stackoverflow.com/questions/50904093/gif-animation-in-tkinter-with-pill-flickering-on-every-other-frame</a></p>\n<p>I tried your code on gif which has a 2nd disposal method.\nWorks, but loops over frames too quickly. GIFs with the 1st disposal method fail.</p>\n<p>Also pay attention to the frame delay/frame rate. Different GIFs can have different values.\nYou can use third party libraries like <a href=\"https://pypi.org/project/Pillow/\" rel=\"nofollow noreferrer\">Pillow</a> to get file information.</p>\n<pre class=\"lang-py prettyprint-override\"><code>\nfrom PIL import Image\n\nf = Image.open(&quot;tenor.gif&quot;)\nprint(f.info) # duration in ms\nprint(f.disposal_method)\nprint(f.n_frames) # number of frames\n\n</code></pre>\n<p>Output example:</p>\n<pre><code>{'version': b'GIF89a', 'background': 140, 'transparency': 140, 'duration': 160, 'extension': (b'NETSCAPE2.0', 795), 'loop': 0}\n2\n12\n</code></pre>\n<p>You can use some custom label classes.\n<a href=\"https://stackoverflow.com/a/43770948/8349697\">https://stackoverflow.com/a/43770948/8349697</a></p>\n<p>Consider using the <a href=\"https://pypi.org/project/PyQt5/\" rel=\"nofollow noreferrer\">PyQt5</a> library. I tried some test gifs with QtWidgets, and it works much better than tkinter. PyQt can display animated gifs using QMovie.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T18:17:30.580", "Id": "260918", "ParentId": "260826", "Score": "1" } } ]
<p>This function should take in a string and a number as parameters and 'rotate' the string to the equivalent alphabet letter that is located at the letter position + 'rotation' parameter.</p> <p>E.g.: <code>&quot;stackoverflow&quot; --- &quot;fgnpxbiresybj&quot;</code></p> <pre><code>def caesar(inputString, rotation = 1): zNum = ord('z') alphaLen = 26 result = [] for c in inputString: charNum = ord(c) + rotation if charNum &gt; zNum: result.append(chr(charNum - alphaLen)) else: result.append(chr(charNum)) return ''.join(result) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T06:57:40.497", "Id": "514901", "Score": "1", "body": "Not really a programming issue, but Ceasar's Cipher has the property that when it is applied twice, you get the original results back. In other words, the rotation is always 13 and it must wrap around (modulo operation)." } ]
{ "AcceptedAnswerId": "260870", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-17T10:40:08.230", "Id": "260846", "Score": "8", "Tags": [ "python", "caesar-cipher" ], "Title": "Caesar cipher using ASCII character codes" }
260846
accepted_answer
[ { "body": "<h1>PEP 8</h1>\n<p>The <a href=\"https://pep8.org/\" rel=\"noreferrer\">Style Guide for Python Code</a> has many guidelines all Python programs should follow. Marc mentioned one (parameters and variables should be <code>snake_case</code> not <code>bumpyWords</code>.</p>\n<p>Another is with regard to keyword parameters: the <code>=</code> should not be surrounded with spaces when used for keywords. Instead of declaring the function like:</p>\n<pre><code>def caesar(inputString, rotation = 1):\n ...\n</code></pre>\n<p>it should be:</p>\n<pre><code>def caesar(input_string, rotation=1):\n ...\n</code></pre>\n<h1>Type hints</h1>\n<p>Although Python is a not a strongly typed language, it is useful to pretend it is, and provide the expected types for the function parameters and return values. I’ll repeat that: <strong>expected</strong> types. The declarations actually don’t enforce anything, and are mostly ignored by the Python interpreter, but other tools (pylint, pyflakes, pychecker, mypy, ...) can read in the code and look for inconsistencies based on the declared types.</p>\n<p>When using type hints, you do end up putting a space around the <code>=</code> sign for the function’s keyword parameters:</p>\n<pre><code>def caesar(input_string: str, rotation: int = 1) -&gt; str:\n ...\n</code></pre>\n<h1>Docstrings</h1>\n<p>Python allows the author to include built-in documentation for functions using a <code>&quot;&quot;&quot;docstrings&quot;&quot;&quot;</code> immediately after the function declaration.</p>\n<pre><code>def caesar(input_string: str, rotation: int = 1) -&gt; str:\n &quot;&quot;&quot;\n Encrypt an input string using a “Caesar Cipher”, where each\n alphabetic character is replaced by the alphabetic character\n `rotation` characters after it, wrapping around from `z` back\n to `a`.\n &quot;&quot;&quot;\n ...\n</code></pre>\n<h1>Bugs</h1>\n<p>As others have noted, the program has bugs which happen when a rotation larger than 25 is used, or non-lowercase letters is given as input.</p>\n<h1>Efficiency</h1>\n<p>When translating longer texts, the method used is inefficient. For instance, when translating <code>&quot;stackoverflow&quot;</code>, the translation for the letter “o” is computed more than once.</p>\n<p>For translation of longer blocks of text, it would be more efficient to determine the translation key once, ahead of time, and then simply looking up the correct translation for each character.</p>\n<pre><code>def caesar(input_string: str, rotation: int = 1) -&gt; str:\n &quot;&quot;&quot;\n Encrypt an input string using a “Caesar Cipher”, where each\n alphabetic character is replaced by the alphabetic character\n `rotation` characters after it, wrapping around from `z` back\n to `a`.\n &quot;&quot;&quot;\n\n key = {}\n for ch in string.ascii_lowercase:\n key[ch] = chr((ord(ch) - ord('a') + rotation) % 26 + ord('a')\n\n return ''.join(key.get(ch, ch) for ch in input_string)\n</code></pre>\n<p>Python actually has a built-in translation function for this purpose. Once the <code>key</code> has been created, a translation table may be generated, and used.</p>\n<pre><code>def caesar(input_string: str, rotation: int = 1) -&gt; str:\n &quot;&quot;&quot;\n Encrypt an input string using a “Caesar Cipher”, where each\n alphabetic character is replaced by the alphabetic character\n `rotation` characters after it, wrapping around from `z` back\n to `a`.\n &quot;&quot;&quot;\n\n key = {}\n for ch in string.ascii_lowercase:\n key[ch] = chr((ord(ch) - ord('a') + rotation) % 26 + ord('a')\n\n translation_table = str.maketrans(key)\n\n return input_string.translate(translation_table)\n</code></pre>\n<p>Ideally, this <code>translation_table</code> would only be created once, and could be reused for other translations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T00:13:02.963", "Id": "514807", "Score": "1", "body": "[Pylint](https://en.wikipedia.org/wiki/Pylint) can check/enforce some of these." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T21:29:51.777", "Id": "514876", "Score": "0", "body": "*it would be more efficient to determine the translation key once, ahead of time, and then simply looking up the correct translation for each character.* - That's mostly because the Python interpreter is so slow, and `.translate` could be a compiled C function. If you were writing this in C, it would probably be faster to just use arithmetic, after turning the rotation into a number from 0..25 that allows you to do `c += c<thresh ? rotation : rotation - 26;`. A good C compiler could even vectorize that to do 16 ASCII bytes at once. (Handle upper/lower with `c+= (c|0x20)<thresh ? ...`)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-17T20:56:14.103", "Id": "260870", "ParentId": "260846", "Score": "7" } } ]
<p>I wrote a function to return the first <strong>n</strong> length sequence which occurs twice in the digits of pi. Along with the repeated sequence, I want the indices of the first and second occurrences. For example, if <strong>n</strong> is <code>1</code>, code returns <code>(1, 0, 2)</code> and if <strong>n</strong> is <code>2</code>, <code>(26, 5, 20)</code>.</p> <p>For reference, here are the first digits of pi:</p> <pre><code>3.141592653589793238462643383279502884197169399375105820974944592... </code></pre> <p>The code uses a breadth-first search (as opposed to a depth-first search, which I coded up to be faster, but isn't what I'm looking for). I realize code below is convoluted and inefficient because it checks same digits multiple times.</p> <p>How do I make it simpler and faster?</p> <h3>code</h3> <pre><code>from mpmath import mp mp.dps = 1000 pi = mp.pi def repeats(n): pi_list = [int(x) for x in str(pi)[2:]] breadth = range(n + n, len(pi_list)) for breadth_level in breadth: pattern_starts = range(breadth_level - 2 * n + 1) for p_s in pattern_starts: test_starts = range(n, breadth_level - n + 1) for t_s in test_starts: candidate = pi_list[p_s:p_s + n] test_start = max(p_s + n, t_s) test = pi_list[test_start:test_start + n] if candidate == test: return candidate, p_s, t_s print(repeats(1)) print(repeats(2)) print(repeats(3)) </code></pre> <h3>output</h3> <pre><code>([1], 0, 2) ([2, 6], 5, 20) ([5, 9, 2], 3, 60) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T02:25:32.483", "Id": "514889", "Score": "3", "body": "If you expect to call `repeat` many times, it might be worth building a `suffix tree` once, and the running the queries on the tree. A suffix tree can also let you answer similar questions like: are there any that repeat more the 2 times, what's the most repeats, which pair has the earliest repeat, find all repeats, etc." } ]
{ "AcceptedAnswerId": "260879", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-17T20:20:02.397", "Id": "260869", "Score": "7", "Tags": [ "python", "performance", "algorithm", "breadth-first-search" ], "Title": "Find the first repeating sequence in digits of pi" }
260869
accepted_answer
[ { "body": "<blockquote>\n<p>How do I make it simpler and faster?</p>\n</blockquote>\n<p>A more efficient approach:</p>\n<ul>\n<li>Iterate on <code>pi</code> with a sliding window of size <code>n</code>.</li>\n<li>Save each sequence (and the starting position) in a lookup map</li>\n<li>Return as soon as you find a match in the lookup map</li>\n</ul>\n<p>Something like this:</p>\n<pre><code>def repeats(n):\n lookup = {}\n pi_s = str(pi)[2:]\n for i in range(n, len(pi_s)):\n start = i - n\n seq = pi_s[start:i]\n if seq in lookup:\n return list(map(int, seq)), lookup[seq], start\n lookup[seq] = start\n</code></pre>\n<p>For <code>n=5</code> this runs in 0.001 seconds, while your approach takes ~40 seconds.</p>\n<p>For <code>n=10</code> and 1 million digits, this approach finds <code>([4, 3, 9, 2, 3, 6, 6, 4, 8, 4], 182104, 240478)</code> in ~50 seconds. The slowest part now seems to be <code>str(pi)</code>, which generates the digits. Once the digits are generated, searching for the sequence takes less than a second.</p>\n<h2>Review</h2>\n<ul>\n<li><strong>Naming</strong>: the function name <code>repeats</code> is a bit ambiguous, it sounds like how many times <code>n</code> appears in the sequence. A better name could be <code>first_repeating_sequence_of</code>.</li>\n<li><strong>Edge case</strong>: for bigger <code>n</code>, more digits of pi are required, otherwise no matches are found. Consider passing the max number of digits of pi as an argument so the caller is aware of this limit.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T03:10:52.217", "Id": "514812", "Score": "1", "body": "This solution is really beautiful and simple. I didn't realize that dictionary lookups are so fast and nested loops so slow. Thanks for the other feedback too!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T03:24:38.350", "Id": "514813", "Score": "2", "body": "@cona I am glad I could help. To get more answers, consider accepting after one day, so reviewers in different timezone have the time to answer. Generally, answers on Code Review come slower compared to Stack Overflow." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T02:23:07.647", "Id": "260879", "ParentId": "260869", "Score": "8" } } ]
<p>I wrote this code that takes the vessel coordinates and checks them against every possible port coordinates. If the distance between the vessel and the port coordinates is within x meters (in this example, it has to be less than 3 km), then add that <em>port</em> and the <em>distance_to_the_port</em> to the data frame.</p> <p>Example dataframes:</p> <pre><code>df_ports = pd.DataFrame({'Ports':['Port_A','Port_B','Port_C'], 'latitude': [1,5,3], 'longitude':[1,10,5]}) latitude_and_longitude_columns = df_ports.iloc[:, [1,2]] df_ports['coordinates_tuple'] = latitude_and_longitude_columns.apply(tuple, axis=1) df_vessel = pd.DataFrame({'latitude': [1,5,7], 'longitude':[1,10,20]}) latitude_and_longitude_columns = df_vessel.iloc[:, [0,1]] df_vessel['coordinates_tuple'] = latitude_and_longitude_columns.apply(tuple, axis=1) df_vessel['distance_to_port_in_meters'] = -1 df_vessel['port'] = -1 </code></pre> <p>The function that checks the distance:</p> <pre><code>def get_distance_between_two_points(tuple1, tuple2): from geopy import distance radius = 3000 dist = distance.distance(tuple1, tuple2).m if dist &lt; radius: return dist return -1 </code></pre> <p>The logic:</p> <pre><code>for _, port_row in df_ports.iterrows(): port = port_row['Ports'] result = df_vessel.apply(lambda vessel_row : get_distance_between_two_points(vessel_row['coordinates_tuple'], port_row['coordinates_tuple']), axis=1) for index, value in result[result != -1].items(): df_vessel.loc[index, 'distance_to_port_in_meters'] = int(value) df_vessel.loc[index, 'port'] = port </code></pre> <p>Result:</p> <pre><code> latitude longitude coordinates_tuple distance_to_port_in_meters port 0 1 1 (1, 1) 0 Port_A 1 5 10 (5, 10) 0 Port_B 2 7 20 (7, 20) -1 -1 </code></pre> <p>The result is correct and it works with my bigger data sample.</p> <p>How can I improve this?</p> <p>In my current code, I have 4800 vessel coordinates and 137 ports. It takes just above 2 minutes to go through the code. How can I make my code better and possibly faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T13:51:54.583", "Id": "514845", "Score": "2", "body": "_In my real code, I use a different one_ - so show your real code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T13:53:57.117", "Id": "514846", "Score": "0", "body": "Based only on latitude and longitude, great-circle distance is a somewhat involved calculation. Are you calculating great circles?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T06:52:01.323", "Id": "514899", "Score": "0", "body": "I have edited the function. I have been reading that the last thing to do in pandas is to loop over a data frame. Is it possible to avoid the for loop in my code?" } ]
{ "AcceptedAnswerId": "260950", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T11:58:31.480", "Id": "260893", "Score": "1", "Tags": [ "python", "pandas" ], "Title": "Check if any of the coordinates are within a certain distance using apply in Python pandas with two data frames" }
260893
accepted_answer
[ { "body": "<p>You need to drop your use of <code>geopy</code>. So far as I can see it does not support vectorised inverse geodesics. Instead use <code>cartopy</code> which inherently supports this.</p>\n<p>The following example code uses random instead of real data, but with the same size as your real data, and completes in about one second. <code>distances</code> and <code>close</code> are both matrices whose rows correspond to vessels and columns correspond to ports. <code>close</code> is a matrix of booleans for vessel-port pairs that are proximate.</p>\n<pre><code>import numpy as np\nfrom cartopy.geodesic import Geodesic\nfrom numpy.random import default_rng\n\nN_VESSELS = 4_800\nN_PORTS = 137\n\nrand = default_rng(seed=0)\n\nvessels = rand.random((N_VESSELS, 2)) + (1, -51)\nports = rand.random((N_PORTS, 2)) + (1, -51)\nsource = vessels.repeat(N_PORTS, axis=0)\ndest = np.tile(ports, (N_VESSELS, 1))\n\ngeo = Geodesic()\ndistances = geo.inverse(source, dest).base[:, 0].reshape((N_VESSELS, N_PORTS))\nclose = distances &lt; 3_000\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T09:37:52.010", "Id": "514996", "Score": "1", "body": "Brilliant! Thank you for teaching me this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T19:46:52.700", "Id": "260950", "ParentId": "260893", "Score": "1" } } ]
<p>What I need to do is to return the prime numbers that are dividers of a some numbers in a list, so if</p> <pre><code>I = [12, 15] # result = [[2, 12], [3, 27], [5, 15]] </code></pre> <p>and this is the code that I used for that:</p> <pre><code>def sum_for_list(lst): r = [] for num in lst: for i in range(2, abs(num)+1): if num%i == 0 and i%2 != 0 and all(i%x != 0 for x in r) and i not in r: r.append(i) elif i == 2 and num%i == 0 and 2 not in r: r.append(i) newList = [] for r in r: z = 0 for y in lst: if y%r == 0: z += y newList.append([r,z]) return sorted(newList) </code></pre> <p>BTW, if you know about good resources to study efficient algorithms, I would really appreciate that too :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T13:48:38.807", "Id": "514844", "Score": "1", "body": "Welcome to Code Review! 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": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T13:28:07.487", "Id": "260897", "Score": "0", "Tags": [ "python", "programming-challenge", "time-limit-exceeded" ], "Title": "Return the prime numbers that are dividers of a some numbers in a list" }
260897
max_votes
[ { "body": "<p>Here are some suggestions for improving readability of your code. The more readable / easily understandable your code is, the easier it is to properly review regarding performance.</p>\n<hr />\n<p><strong>Naming</strong></p>\n<p>This is probably the most important point regarding your code. More or less none of the variables have meaningful names. This makes it that much harder to understand your algorithm.</p>\n<p>Single letter variable names (<code>r</code>, <code>z</code>, <code>y</code>) are only a good idea when following well-known conventions like iterating over an index (<code>for i in range(...)</code>). The same goes for <code>lst</code> and <code>newList</code>, these names say nothing about content and function of the variables. Without fully understanding your algorithm I would presume some names like <code>divisor</code>, <code>numbers</code>, <code>candidate_primes</code>, <code>results</code>, etc. might be useful.</p>\n<p>Variables should be named in <code>snake_case</code> instead of <code>camelCase</code>. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP 8</a></p>\n<p><code>for r in r:</code>: Using the same variable name for different variables (in this case: the single elements of an iterable and the iterable itself) is confusing to the reader and might lead to some unexpected behaviour in some cases.</p>\n<hr />\n<p><strong>Conditions</strong></p>\n<p>Line 5: After checking <code>all(i%x != 0 for x in r)</code>, you don't need to additionally check if <code>i not in r</code>. Since <code>i % i == 0</code>, the first condition would already fail if <code>i in r</code>.</p>\n<hr />\n<p><strong>Comments &amp; docstrings</strong></p>\n<p>You should include comments and docstrings in your code to explain at least the key functionality / algorithmic approach.</p>\n<hr />\n<p>You can remove the entire <code>elif</code> case from this for loop:</p>\n<pre><code>for num in lst:\n for i in range(2, abs(num)+1):\n if num%i == 0 and i%2 != 0 and all(i%x != 0 for x in r) and i not in r:\n r.append(i)\n elif i == 2 and num%i == 0 and 2 not in r:\n r.append(i)\n</code></pre>\n<p>like this:</p>\n<pre><code>for num in lst:\n if num % 2 == 0 and 2 not in r:\n r.append(2)\n\n for i in range(3, abs(num) + 1):\n if num % i == 0 and i % 2 != 0 and all(i % x != 0 for x in r) and i not in r:\n r.append(i)\n</code></pre>\n<p>This will save you some unnecessary checks for each <code>i in range(3, abs(num) + 1)</code> for each <code>num</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T14:14:54.983", "Id": "260900", "ParentId": "260897", "Score": "3" } } ]
<p>I have a Python function like so:</p> <pre><code>def get_values(n: int) -&gt; list: &quot;&quot;&quot; :param n: the maximum absolute value :return: sorted list of all the positive and negative permutations up to size n &quot;&quot;&quot; if n &lt; 0: return [] if n == 0: return [(0, 0)] out = set() for i in range(0, n + 1): for j in range(0, i + 1): out.add((i, j)) out.add((-i, j)) out.add((i, -j)) out.add((-i, -j)) return sorted(out, key=lambda t: abs(t[0])) </code></pre> <p>The <code>sorted</code> at the end is important for my use case.</p> <p>The issue is this uses a large amount of memory, presumably because it appends 4 values for every j. So as n becomes large, this set becomes very large.</p> <p>I used a set rather than a list since I gathered it should take less memory by avoiding duplicates (I may be wrong :))</p> <p>I would like to reduce the memory of this so can be large, up to 10,000 would be ideal but the bigger the better. Speed isn't really an issue here but faster is better!</p>
[]
{ "AcceptedAnswerId": "260912", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T15:06:17.900", "Id": "260902", "Score": "9", "Tags": [ "python" ], "Title": "Python algorithm to return all two-tuple permutations of numbers up to n" }
260902
accepted_answer
[ { "body": "<p>I'd say your code is well-structured and easy to read. The approach however can be simplified using the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a> module from the standard library. <code>itertools</code> provides useful implementations for things like <code>combinations</code>, <code>permutations</code>, cartesian <code>product</code> and a lot more.</p>\n<p>Here's the simplest and fastest approach I could come up with, that is equivalent to your implementation:</p>\n<pre><code>from itertools import product\n\ndef valid_tuple(number_pair: tuple) -&gt; bool:\n a, b = number_pair\n return abs(b) &lt;= abs(a)\n\n\ndef get_values_product(n: int) -&gt; list:\n out = product(range(-n, n + 1), repeat=2)\n out = filter(valid_tuple, out)\n return sorted(out, key=lambda t: abs(t[0]))\n</code></pre>\n<p>It's usually faster to use functions that are built-in or included in standard library modules. <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\"><code>itertools.product</code></a> returns the cartesian product of input iterables, which is exactly what we want here. On my machine, this takes about half the time of your original implementation.</p>\n<hr />\n<p><s>As you need sorted output I don't think there's a way to significantly reduce the space complexity. If you didn't need the output to be sorted, you could turn it into a <a href=\"https://realpython.com/introduction-to-python-generators/\" rel=\"nofollow noreferrer\">generator</a>, which is really memory-efficient.</s></p>\n<p><strong>Edit:</strong></p>\n<p>Here's how you can get the same desired sorted output while optimising space complexity:</p>\n<pre><code>from itertools import product, chain\nfrom typing import Generator\n\ndef get_values_generator(n: int) -&gt; Generator:\n if n &lt; 0:\n return\n\n numbers = chain(*zip(range(n + 1), range(-1, -n - 1, -1)), [n])\n\n pairs = product(numbers, repeat=2)\n\n yield from filter(valid_tuple, pairs)\n</code></pre>\n<p>This works because we already <em>pre-sort</em> the list of numbers before calculating the cartesian product. This implementation returns a <code>generator object</code>, i.e. an iterator instead of a list. This means you might have to make some slight adjustments to the code that uses the return value of <code>get_values</code>.</p>\n<p>Here's a comparison of the memory used by the return values of both approaches:</p>\n<pre><code>num = 50\n\nsorted_list = get_values(num)\ngenerator_obj = get_values_generator(num)\n\nprint(sys.getsizeof(sorted_list))\nprint(sys.getsizeof(generator_obj))\n</code></pre>\n<p>prints</p>\n<pre><code>&gt; 85176\n&gt; 112\n</code></pre>\n<p>When changing <code>num = 500</code>, we get:</p>\n<pre><code>&gt; 8448728\n&gt; 112\n</code></pre>\n<p>As you can see, the memory used by the <code>generator object</code> is constant at 112 bytes.</p>\n<p>Here's some validation regarding the correctness of our result:</p>\n<pre><code>print(&quot;Same elements:\\t&quot;, set(sorted_list) == set(generated_list))\nprint(&quot;Same length:\\t&quot;, len(sorted_list) == len(generated_list))\nprint(&quot;No duplicates:\\t&quot;, len(generated_list) == len(set(generated_list)))\n\nprint(&quot;Sorted:\\t\\t\\t&quot;, all(abs(x[0]) &lt;= abs(y[0]) for x, y in zip(generated_list, generated_list[1:])))\n</code></pre>\n<p>We get the same output for negative and positive numbers, as well as zero:</p>\n<pre><code>&gt; Same elements: True\n&gt; Same length: True\n&gt; No duplicates: True\n&gt; Sorted: True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T16:42:52.577", "Id": "514859", "Score": "1", "body": "I guess it doesn't have to be sorted, the reason it is sorted is it finds an equation for a multivariable function using a saddle point, local maxima and local minima and returns Ax^2+Bx+Cx^2+Dy+k. This function is used for values A,B,C and D so clearly you want to return the smallest values hence why it will go 0,1,-1,2,-2.... Check here (https://pastebin.com/gr2KbvQb) if you want to see the full code. This isn't really the place to talk about this so if you think it's better I can open a new question and link it here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T16:46:46.407", "Id": "514860", "Score": "0", "body": "I see. I think there should be an approach that produces already sorted output, which could then be returned element-by-element without the need to sort first. That should significantly reduce space-complexity. I will have a look at that later tonight!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T00:47:18.560", "Id": "514882", "Score": "0", "body": "@GAP2002 I provided an additional approach, that will reduce the memory usage of the return value to a constant 112 bytes. Intermediate objects inside the function are even smaller (`numbers` takes up 48 bytes of memory, while `product(numbers, repeat=2)` takes up 80 bytes)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T01:07:00.457", "Id": "514886", "Score": "0", "body": "@riskypenguin nice review, you can use `yield from product(numbers, repeat=2)` to save one line of code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T03:54:58.433", "Id": "514893", "Score": "0", "body": "In the original code, `j` only went up to `i`. In this code it goes up to `n`. That is, the second element in the tuple is always <= the first element. Don't know if that's important or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T10:38:19.117", "Id": "514907", "Score": "0", "body": "@Marc Thanks, I implemented your suggestion!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T10:50:15.127", "Id": "514909", "Score": "0", "body": "@RootTwo You're absolutely right, thanks for spotting that! I fixed it for both my approaches, by checking for valid tuples. `get_values_product` still takes about half the time of OP's approach, and `get_values_generator` is the fastest in my testing, even when consuming the entire iterator." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-18T16:24:51.843", "Id": "260912", "ParentId": "260902", "Score": "15" } } ]
<p>Assume a multi-line file (<code>myInput.txt</code>) with lines comprising one or more words.</p> <pre><code>echo -e &quot;Foo\nFoo bar\nFoo baz\nFoo bar baz\nBar\nBaz\nBaz qux\nBaz qux quux\nQux quux&quot; &gt; myInput.txt </code></pre> <p>I wish to remove all one-word lines that are identical with the first word of any multi-word lines <strong>using Python</strong>.</p> <pre><code>echo -e &quot;Foo bar\nFoo baz\nFoo bar baz\nBar\nBaz qux\nBaz qux quux\nQux quux&quot; &gt; myGoal.txt </code></pre> <p>The following code satisfies my goal but does not appear overtly Pythonic to me.</p> <pre><code>from itertools import compress myList = list() with open(&quot;myInput.txt&quot;, &quot;r&quot;) as myInput: for line in [l.strip() for l in myInput.readlines()]: if not line.startswith(&quot;#&quot;): myList.append(line) # Get all lines with more than one word more_than_one = list(compress(myList, [len(e.strip().split(&quot; &quot;))&gt;1 for e in myList])) # Get all lines with only one word only_one_word = list(compress(myList, [len(e.strip().split(&quot; &quot;))==1 for e in myList])) # Keep only unique set of initial words of more_than_one unique_first_words = list(set([e.split(&quot; &quot;)[0] for e in more_than_one])) # Remove all union set words from only_one_word only_one_word_reduced = [e for e in only_one_word if e not in unique_first_words] # Combine more_than_one and only_one_word_reduced combined_list = only_one_word_reduced + more_than_one </code></pre> <p>Do you have any suggestions on making the Python code slimmer and more straightforward?</p>
[]
{ "AcceptedAnswerId": "260928", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T00:35:32.167", "Id": "260924", "Score": "4", "Tags": [ "python", "strings" ], "Title": "Pythonic way of removing one word entries from compound list" }
260924
accepted_answer
[ { "body": "<p>Based on your code, the lines don't need to be kept in order.</p>\n<p>This code reads each line of the file once. If there are multiple words on a line, it is appended to <code>combined_lines</code> and the first words is added to a set of first words. Another set is used for single words. At the end, any single words that aren't a first word (using set subtraction) are added to <code>combined_lines</code>.</p>\n<p>With revisions suggested in the comments:</p>\n<pre><code>combined_lines = list()\nsingle_words = set()\nfirst_words = set()\n\nwith open(&quot;myInput.txt&quot;, &quot;r&quot;) as sourcefile:\n for line in sourcefile:\n line = line.strip()\n if line == '' or line.startswith(&quot;#&quot;):\n continue\n\n first, rest = line.split(maxsplit=1)\n\n if rest:\n combined_lines.append(line)\n first_words.add(first)\n\n else:\n single_words.add(first)\n\n combined_lines.extend(single_words - first_words)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T10:11:30.390", "Id": "514905", "Score": "1", "body": "FYI `lines` is not defined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T10:46:13.360", "Id": "514908", "Score": "0", "body": "Also, you're going to want to pass `maxsplit` since you only care about the first token. Doing so will avoid your need for a `*` so will be marginally faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T13:03:01.183", "Id": "514918", "Score": "0", "body": "@RootTwo Thanks for the explanations. Understanding that the last line should rather be `combined_lines.extend(single_words - first_words)`, this is indeed a much more Pythonic way of approaching the problem than I had." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T03:08:23.817", "Id": "260928", "ParentId": "260924", "Score": "1" } } ]
<p><strong>Hello everyone!</strong></p> <p>In today's assignment I had to complete a rather unusual translator, take a look at my solution, tell me what I can do to make it better and show off yours!</p> <p>Write a function that translates some text into New Polish and vice versa. Polish is translated into New Polish by taking the last letter of each word, moving it to the beginning of the word and adding <code>ano</code> at the beginning. <code>Tom has a cat'</code> becomes <code>['Anomto anosha anoa anotca']</code>.</p> <pre><code>def new_polish_translator(input): result = '' content = input.replace(',', '').replace('.', '').replace('?', '').replace('-', '') #Dzieli na linie bez wchodzenia do nowej linii (\n) lines = [line.rstrip() for line in content.split(&quot;\n&quot;)] lines = [line for line in lines if len(line) &gt; 0] #sprawdza czy nie jest przetlumaczony if all(line[-3::] == 'ano' for line in lines for word in line.split(' ')): result = ' '.join(lines) #sprawdza czy nie jest else: result = ' '.join('ano' + word[-1] + word[0:-1] for line in lines for word in line.split(' ')) result = result.capitalize() return result new_polish_translator(&quot;Tom has a cat&quot;) </code></pre> <p>result:</p> <pre><code>'Anomto anosha anoa anotca' </code></pre> <p><strong>Have a great day!</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T23:11:48.703", "Id": "514968", "Score": "1", "body": "Not super important, but I'll just note that this is basically just a variation of \"Pig Latin\"." } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T19:07:24.253", "Id": "260949", "Score": "3", "Tags": [ "python", "algorithm" ], "Title": "NewPolish - unconventional translator in Python" }
260949
max_votes
[ { "body": "<p>Your code is reasonable, but it does get tripped up if the text (<code>input</code>)\ncontains multiple adjacent spaces or the cleaned text (<code>content</code>) ends up\ncontaining multiple adjacent spaces. It also could be simplified here and\nthere. Some suggestions to consider: (1) parameterize the function so the user\ncan control which punctuation characters to remove; (2) since the algorithm is\nfundamentally a word-based translation, it makes sense to convert the text to\nwords early; (3) the check for already-translated text is not robust to\ncapitalization; and (4) use the no-argument form of <code>split()</code> to avoid the bug\nnoted above. Here's one way to make those changes:</p>\n<pre><code>def new_polish_translator(text, replace = ',.?-'):\n # Remove unwanted punctuation.\n for char in replace:\n text = text.replace(char, '')\n\n # Convert to words.\n words = text.split()\n\n # Translate, unless the text is already New Polish.\n prefix = 'ano'\n if all(w.lower().startswith(prefix) for w in words):\n np_words = words\n else:\n np_words = [prefix + w[-1] + w[0:-1] for w in words]\n\n # Return new text.\n return ' '.join(np_words).capitalize()\n</code></pre>\n<p>As you know already, this problem raises some tricky questions related to how\nthe algorithm defines a &quot;word&quot;. Simply splitting on whitespace and removing a\nfew common punctuation markers will fail to handle a variety of human language\ninputs reasonably. There are other types of punctation (colon, semicolon, dash,\nand some weird ones), some words have internal punctuation (apostrophe), some\nwords contain or even start with digits, some words convey additional meaning\nwith capitalization, and some texts care about internal whitespace. Consider\nthis specimen from Ogden Nash, and notice the details of spacing and\npunctuation lost during translation:</p>\n<pre class=\"lang-none prettyprint-override\"><code># English.\n\nThe camel has a single hump;\nThe dromedary, two;\nOr else the other way around.\nI'm never sure. Are you?\n\n# New Polish.\n\nAnoeth anolcame anosha anoa anoesingl ano;hump anoeth anoydromedar ano;two anoro anoeels anoeth anorothe anoywa anodaroun anomi' anorneve anoesur anoear anouyo\n</code></pre>\n<p>Is there a a <strong>practical</strong> way to make a translator that preserves more of\nthose details? One approach is to use a basic tokenizing technique to decompose\nthe input text into various tokens, some of which will be preserved as-is and\nsome of which will be word-translated. These tokenizers are easy to build\nbecause they follow a simple pattern: try to match a sequence of regular\nexpressions; stop on the first match; emit a <code>Token</code>; then re-enter the loop.\nIn these situations, it helps to define some simple data-objects to represent\nsearch patterns and tokens. A sketch is shown below. It is purposely unfinished\nin the sense that it is missing some error handling (eg, checking that the\npatterns exhaust the text) and\nit doesn't try to preserve the original word capitalization. But those\nimprovements are fairly easy to add if you are so inclined.</p>\n<pre><code>from collections import namedtuple\nimport re\n\nPattern = namedtuple('Pattern', 'kind regex')\nToken = namedtuple('Token', 'kind text')\n\ndef new_polish_translator(text):\n # Define the search patterns.\n patterns = [\n Pattern('whitespace', re.compile('\\s+')),\n Pattern('word', re.compile('[A-Za-z]+')),\n Pattern('other', re.compile('\\S+')),\n ]\n\n # Translate only Token(kind=word). Preserve the rest.\n words = []\n for tok in tokenize(text, patterns):\n if tok.kind == 'word':\n w = tok.text\n words.append('ano' + w[-1] + w[0:-1])\n else:\n words.append(tok.text)\n\n # Return joined text.\n return ''.join(words)\n\ndef tokenize(text, patterns):\n pos = 0\n limit = len(text)\n while pos &lt; limit:\n for p in patterns:\n m = p.regex.match(text, pos = pos)\n if m:\n txt = m.group(0)\n pos += len(txt)\n yield Token(p.kind, txt)\n break\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>anoeTh anolcame anosha anoa anoesingl anophum;\nanoeTh anoydromedar, anootw;\nanorO anoeels anoeth anorothe anoywa anodaroun.\nanoI'm anorneve anoesur. anoeAr anouyo?\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T22:21:37.323", "Id": "260955", "ParentId": "260949", "Score": "2" } } ]
<p>I have been playing around with numpy and matplotlib.</p> <p>My little project was to create a scatter plot ranging from -1 to 1 on both X and Y, but where the shading is done with the XOR scheme.</p> <p>The following is the code that I have implemented (it is in a cell of a jupyter notebook, hence the trailing <code>;</code> after <code>plt.scatter</code>):</p> <pre class="lang-py prettyprint-override"><code>arr_size = 2000 X = np.random.uniform(low=-1.0, high=1.0, size=(arr_size, arr_size)) colour = np.zeros(arr_size) for i in range(arr_size): if X[0, i] &gt; 0 and X[1, i] &lt; 0: colour[i] = 1 elif X[0, i] &lt; 0 and X[1, i] &gt; 0: colour[i] = 1 plt.scatter(X[0], X[1], c=colour); </code></pre> <p>The output that I generated was:</p> <p><a href="https://i.stack.imgur.com/9P3r7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9P3r7.png" alt="enter image description here" /></a></p> <p>Which is the desired output.</p> <p>However, I am on a bit of a campaign to make my numpy code run faster (I am on an ML course and we have been taught to remove for loops wherever possible). Can anyone show me how to make this code more efficient?</p> <p>Cheers</p>
[]
{ "AcceptedAnswerId": "260972", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T08:55:35.157", "Id": "260971", "Score": "1", "Tags": [ "python", "performance", "numpy", "matplotlib" ], "Title": "Removing Loop from Numpy XOR" }
260971
accepted_answer
[ { "body": "<p>Since <code>(a &lt; 0 and b &gt; 0) or (a &gt; 0 and b &lt; 0)</code> can be summarized as <code>a*b &lt; 0</code>, moreover <code>*</code> and <code>&lt;</code> work on vectors, we get the one-liner:</p>\n<pre><code>plt.scatter(X[0], X[1], c=X[0]*X[1] &lt; 0)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-20T09:17:04.227", "Id": "260972", "ParentId": "260971", "Score": "2" } } ]
<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" } } ]