Error in a function that returns an AND of two variables in python

Asked

Viewed 73 times

1

I made a function in Python that in theory should return a and of each element of two variables, however the result is not being expected.

The answer would be [0, 1, 0, 0, 1, 1, 0, 0], but is returning [0, 1, 1, 0, 1, 1, 0, 0], which is the value of b

a = "11001100"
b = "01101100"

def p_and(a,b):
  aux=[]
  for i in range(8):
    aux.append(int(a[i] and b[i]))
  return aux
  • map(int, format(int(a, 2) & int(b, 2), 'b'))

2 answers

3


It’s the same problem as your previous question, so you didn’t learn from the solution there. , you have to convert the values individually to apply the operator, you are applying the operator to the unconverted value and then you do the result conversion which is already wrong.

a = "11001100"
b = "01101100"
def p_and(a,b):
    aux=[]
    for i in range(8):
        aux.append(int(a[i]) and int(b[i]))
    return aux

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

0

a = "11001100"
b = "01101100"

def p_and(a,b):
  aux=[]
  for i in range(8):
    aux.append(int(int(a[i]) and int(b[i])))
  return aux

print (p_and(a,b))
  • 1

    It’s the same code as the other answer, except for print. What does this answer add to users? If you have any questions about how to respond, read [Answer]. If you have questions about how the page works do our [tour].

  • There was no other answer when I sent mine. If so, coincidence. I didn’t have time to comment on the code because I had to leave the computer. I would return and edit the answer. But ok.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.