为什么我的python代码中的array值在使用array一次后变为0?

2024-05-13 18:00:41 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在编写一个python代码,其中我有一个元素数组,并对其使用计数排序!因此,我创建了一个count数组,其中第一个值包含[1200]中的值,第二个值计算数组中出现的次数。我创建了一个函数SortedArray(count\u array,d)d是排序数组包含的元素数

def sortedarray(array,d):
    a=[0]*d
    i=0
    for j in range(d):
        if array[j][1]>0:
            while array[j][1]>0:
                a[i]=array[j][0]
                array[j][1]-=1
                i+=1
    return a

这是我剩余的代码,它试图创建一个count数组并使用它

def activityNotifications(expenditure, d):
    L = queue.Queue(maxsize=d)
    for i in range(d):
        L.put(expenditure[i])
    count_array=[[i+1,0] for i in range(200)]

    for a in L.queue:
        j=0
        while(j<200):
            if a==count_array[j][0]:
                count_array[j][1]+=1
                break
            j+=1
    #1 print(list(sortedarray(count_array,d)))        
    medi=median(sortedarray(count_array,d),d)

    #2 print(medi,list(L.queue),list(sortedarray(count_array,d)),expenditure[d])
    notifications=0
    if expenditure[d]>=2*medi:
        notifications=1

    for x in range(d,len(expenditure)):
        L.get()
        L.put(expenditure[x])
        j=0
        while(j<200):
            if count_array[j][0]==expenditure[d-x]:
                count_array[j][1]-=1
            if L.queue[d-1]==count_array[j][0]:
                count_array[j][1]+=1
                break
            j+=1
        medi=median(sortedarray(count_array,d),d)
        if expenditure[d]>=2*medi:
            notifications+=1
        print(list(L.queue),sortedarray(count_array,d),expenditure[d])
    return notifications

所以我用#1和#2标记了上面的两个print语句。因为我得到了错误的值,所以我想看看我到底在哪里得到了错误的值,我在countŠ数组上使用sortedarray()函数时注意到了这一点。它在第一次调用时返回正确的输出,但如果我再次调用它,则返回的值都是零,即第二次print语句中的值!为什么会发生这种情况,因为我没有在这些print语句之间更改count\u数组,只是使用了sortedarray()函数两次,但它不应该正确地更改count\u数组


Tags: 函数inforifqueuecountrange数组