简体   繁体   中英

list.count() says 1 when there are no value in list

I am trying to count the frequency of all elements from 1 to N in a List A". I have to do it within O(1) space that's why I'm appending the count value on the same list. I am new to problem-solving in python.

def printfrequency(A,N):
#Your Code here
lis = []

for i in range(1,N+1):
    if i in A:
        A.append(A.count(i))
    else:
        A.append(0)       
for i in A[-N:]:
    print(i,end=" ")

this code is giving wrong value for input

N = 9

A = [9,2,5,7,9,2,2,1,4]

Output --> 1 3 1 1 1 0 1 0 2

Expected --> 1 3 0 1 1 0 1 0 2

This is working fine for some input like

N = 2

A = 2 3 2 3 5

Output --> 0 2 2 0 1

Expected --> 0 2 2 0 1

To count the values in A you should not append any more value to A . Rather use the lis variable you created there. Fo example, like this

def printfrequency(A,N):
    #Your Code here
    lis = []

    for i in range(1,N+1):
        if i in A:
            lis.append(A.count(i))
        else:
            lis.append(0)       
    for i in lis:
        print(i, end=" ")
  1. What you intend to do is adding 'N' elements to the end of the list which represent the counts of 1 to N. This means you are still allocating N spaces. So this is still O(N) space. Maybe you meant that the space you use has to be independent of the list length. In that case, yes you are right. It really depends on what question you are trying to answer.

  2. Let's assume your current algorithm is right, you just haven't implemented it properly. Let's look at what your code does. Assume the list you get is A = [1, 2, 1, 3] . Then on the first run of the loop you count the number of 1's and it's 2. So you append that to the list.

    So we now have A = [1, 2, 1, 3, 2] . On the second run of the loop, you ask it to count the 2's. And now there are two 2's, 1 from the original list and one from the appended part. A.count will count through the entire list. So what you want to do is count only the 2's from the original part. You can do this by

    i. Don't append the counts to A. Put them in a different list. For example, your lis variable. That way A.count will count things in the original list anyway.

    ii. Tell count to only use the list up till the original part:

length = len(A)

for i in range(1, N+1):
   if i in A[:length]:
       A.append(A[:length].count(i))

(i) is cleaner than (ii), so it should be preferred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM