Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm new to Python and I'm wondering is there a way to streamline this clunky code I've written. Maybe a built-in function I've never come across before?

I run through two lists of binary numbers and if the same number appears at the same index in list one and two, do x.

So in the example below the number 1 appears at index 2 in both lists.

list1 = [0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
list2 = [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]


for position, binary in enumerate(list1):
    for placement, number in enumerate(list2):
            if position == placement and binary == 1 and binary == number:
                do x
share|improve this question

3 Answers 3

up vote 7 down vote accepted

Your solution's time complexity is O(n2), which is far from optimal. Your lists contain 19 elements - so your solution performs an order of 361 operations. In order to get a linear solution, you can simulate a "-style" for loop using range:

for i in range(len(list1)): # assuming the lists are of the same length
    if list1[i]==list2[i]:
                do x

Now the loop runs exactly 19 times - much better!

Another thing: your code checks if binary==1. Is it what you want? If so, Python's equal operator can operate on three arguments, making it more readable:

for i in range(len(list1)): # assuming the lists are of the same length
    if list1[i]==list2[i]==1:
                do x

Lastly, you may want to represent a binary number using the most natural way - as a number. Aside from space consideration, most languages (including Python) have standard binary (often called bitwise) operations.

share|improve this answer
    
It probably is what he wants.. Looks like he's ANDing everything. –  Millie Smith Mar 12 at 17:07
    
Yeah, but the description says "same number". –  Benesh Mar 12 at 17:10
    
Good point. I missed that. –  Millie Smith Mar 12 at 17:11
    
Thanks for the great explanation! –  Tara Mar 12 at 21:12

Python has a neat built in called 'zip' which creates a pairwise list from multiple iterables. So you could do:

pairwise = zip (list1, list2)
matched_digits = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]

Which zips up the list and returns the indices of all the pairs which match

share|improve this answer
    
I love zip, thanks for bringing it forth –  Claudiordgz Mar 12 at 20:56
    
Thanks for your answer! –  Tara Mar 12 at 21:11

I would do it like this

for i,j in zip (list1, list2):
    if i == 1 and i == j:
        do(x)
share|improve this answer
    
Thanks a million! –  Tara Mar 12 at 21:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.