开发者

How to debug in this simple Python homework?

I need a little bit of help with a homework problem for school using python. The prompt is pretty simple, but I can't seem to figure it out.

'''
rem(A,B) returns the list 
              [A[0]%B[0], A[1]%B[1], ...]  etc

>>> rem( (10,20,30), (7,8,9) )
[3, 4, 3]
>>> X = [ i for i in range(10,18) ] 
>>> Y = [ j+3 for j in range(8) ]
>>> rem(X,Y)+["?"]
[1, 3, 2, 1, 0, 7, 7, 7, '?']
>>> rem( [5,3], [3,2] )
[2, 1]
>>> rem( [10,9], [5,4] )
[0, 1]
'''

I have created this snippet of code which sort of works but not quite:

def rem(A,B):
    return [A[0] % b for b in B]

Right now the definition is working, but only for the first value in each sequence. I think this is due to the A[0] - I need some way to make it do A[x+1], but I'm not s开发者_Python百科ure. Also I'm pretty sure that I have to use range() somewhere in the definition as well.


You need to pair up each element of A with its corresponding element in B, and then mod them.

[x % y for (x, y) in zip(A, B)]


Ignacio's answer is correct and the most pythonic, this is the more basic way:

def rem(a,b):
    l = []
    for x in range(len(a)):
         l.append(a[x]%b[x])
    return l

See comments too!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜