Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a few ways you could increase the efficiency of this search by minimising additional memory use (particularly when your data is BIG).</p> <ul> <li>you can operate directly on the list you are passing in, and don't need to make copies of it, in this way you won't need: <code>original = list</code>, or <code>copy = original[count:]</code></li> <li>you can use slices of the original list to test against, and <code>enumerate(p)</code> to iterate through these slices. You won't need the extra variable <code>count</code> and, <code>enumerate(p)</code> is efficient in Python</li> </ul> <p>Re-implemented, this would become:</p> <pre><code>def search(p): # iterate over p for i, value in enumerate(p): # if value occurs more than once, print locations # do not re-test values that have already been tested (if value not in p[:i]) if value not in p[:i] and value in p[(i + 1):]: print(e, ':', i, p[(i + 1):].index(e)) v = [1,2,3,1,2,3,4] search(v) 1 : 0 2 2 : 1 2 3 : 2 2 </code></pre> <p>Implementing it this way will only print out the values / locations where a value is repeated (which I think is what you intended in your original implementation). </p> <p>Other considerations:</p> <ul> <li><p><em>More than 2 occurrences of value:</em> If the value repeats many times in the list, then you might want to implement a function to walk recursively through the list. As it is, the question doesn't address this - and it may be that it doesn't need to in your situation.</p></li> <li><p><em>using a dictionary:</em> I completely agree with Akavall above, dictionary's are a great way of looking up values in Python - especially if you need to lookup values again later in the program. This will work best if you construct a dictionary instead of a list when you originally create the list. But if you are only doing this once, it is going to cost you more time to construct the dictionary and query over it than simply iterating over the list as described above.</p></li> </ul> <p>Hope this helps! </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload