简体   繁体   中英

Wrong Answer python3.6

You are given a set S and Q queries. Initially, S is empty. In each query:

You are given a positive integer X.
You should insert X into S.
For each y∈S before this query such that y≠X, you should also insert y⊕X into S (⊕ denotes the XOR operation). Then, you should find two values E and O: the number of elements of S with an even number of 1's and with an odd number of 1's in the binary representation, respectively.

I have tried splitting the problem into smaller subproblems but it seems to exceed time because of large input size and large list size. Any suggestion into the code and further optimization will be very helpful.I have mow used set but the expected output is not as same as my output. Any suggestions as where I am going wrong in the solution code..?

s=set()
def fun(n,q):
    c=0
    cc=0
    s.add(n)
    for k in range(len(list(s))):
        if list(s)[k]!=n:
            s.add((list(s)[k])^n)

    for k in s:
        if bin(k)[2::].count('1')%2==0:
            c+=1
        else:
            cc+=1
    print(c,cc)


for _ in range(int(input())):
    q=int(input())
    for j in range(q):
        n=int(input())
        fun(n,q)

Example Input:

1
3
4
2
7

Example Output:

0 1
1 2
3 4

The first thing i see wrong on your code is that S should be a set of numbers. A list can have duplicates, so you need to work with sets

And to optimize your script, you can start by improving how you count the amount of enabled bits in your number expressed in binary. Such count is called the hamming weight of a string.

Search it on the web. For instance you have this article

I think you are inserting duplicate value in your List. fix it you will be good to go.

Solution And Reference :- https://whitefox-89ea6.firebaseapp.com/

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