OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to make this Python function even faster, lists processing

  • Thread starter Thread starter Andres Masis
  • Start date Start date
A

Andres Masis

Guest
I was doing a Hackerrank question (I already finished that test, I am just asking because I am curious). Most of test cases were successful but a few said that it took too long, so I had to optimize my code. I assume it means that my solution works properly but it is too slow.

The idea is that you take 2 lists.

  • One original items (positive integers), items = [2, 1, 1, 4, 3]
  • A second query list (positive and negative integers), query = [-1, 2, -3, 1]

You have to process each query. If the current query is a positive integer, you just add it in the end of the items list. If the current query is a negative integer, it means that you have to remove the first apparition of that absolute value in the items list.

This is my code:

Code:
def process_orders(query, items):
    for q in query:
        if q > 0:
            items.append(q)
        else:
            q *= -1
            items.remove(q)

    return items

How can I make it faster?

Thanks

I removed some unnecessary extra loops. I even tried dictionaries, but it got worse.
<p>I was doing a Hackerrank question (I already finished that test, I am just asking because I am curious).
Most of test cases were successful but a few said that it took too long, so I had to optimize my code. I assume it means that my solution works properly but it is too slow.</p>
<p>The idea is that you take 2 lists.</p>
<ul>
<li>One original items (positive integers), items = [2, 1, 1, 4, 3]</li>
<li>A second query list (positive and negative integers), query = [-1, 2, -3, 1]</li>
</ul>
<p>You have to process each query. If the current query is a positive integer, you just add it in the end of the items list. If the current query is a negative integer, it means that you have to remove the first apparition of that absolute value in the items list.</p>
<p>This is my code:</p>
<pre><code>def process_orders(query, items):
for q in query:
if q > 0:
items.append(q)
else:
q *= -1
items.remove(q)

return items
</code></pre>
<p>How can I make it faster?</p>
<p>Thanks</p>
<p>I removed some unnecessary extra loops. I even tried dictionaries, but it got worse.</p>
 

Latest posts

Top