Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

python - Iam looping through one array and printing frequency as in the second arrary, for loop works fine, however when same code in function not work

arr1 = [6,12,8,10,20,16]
arr2 = [5,4,3,2,1,5]

arrn=[]
for i in range(len(arr1)):
    for j in range((arr2[i])):
        arrn.append(arr1[i])
print(arrn)


output [6, 6, 6, 6, 6, 12, 12, 12, 12, 8, 8, 8, 10, 10, 20, 16, 16, 16, 16, 16]

Above code works fine, but when put in function it doesn't work Please advise where iam going wrong Here iam try to distribute arr1 as per frequency in arr2 respective elements, it prints fine, but function is return improper result


x = [6,12,8,10,20,16]
y = [5,4,3,2,1,5]
n = len(x)


def defreq(a,b):
    arrn = []
    for i in range(n):
        print(i,[a[i]],b[i])
        arrn += [a[i]] * b[i]
        return arrn

print(defreq(x,y))

[6, 6, 6, 6, 6]
question from:https://stackoverflow.com/questions/65938039/iam-looping-through-one-array-and-printing-frequency-as-in-the-second-arrary-fo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your return is within the for loop, and your logic in the function is different to your earlier code outside the function.
Here is the corrected code:

x = [6,12,8,10,20,16]
y = [5,4,3,2,1,5]
n = len(x)

def defreq(a,b):
    arrn = []
    for i in range(len(a)):
        for j in range((b[i])):
            arrn.append(a[i])
    return arrn

print(defreq(x,y))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...