简体   繁体   English

两个字符串的不同异或值

[英]Distinct xor values of two strings

You are given two strings of length n, you have to find distinct xor values by rearranging the elements in an arbitrary way of the two strings.给定两个长度为 n 的字符串,您必须通过以任意方式重新排列两个字符串的元素来找到不同的 xor 值。

Here is what I tried:这是我尝试过的:

String1 = input()
String2 = input()
s1_ones = String1.count('1')  #Number of 1's in string1
s2_ones = String2.count('1')  #Number of 1's in string2

minimum_overlap = s1_ones+s2_ones-n  #minimum overlapping 1's when performing xor
maximum_overlap = min(s1_ones,s2_ones) #maximum overlapping 1's when performing xor

if(minimum_overlap<0):
    minimum_overlap = 0
ans = 0
for x in range(minimum_overlap,maximum_overlap+1):
    resulting_ones = s1_ones + s2_ones - 2*x   #number of ones in resulting string
    ans+=(nCr(n,resulting_ones)) #nCr is a function which returns number of possible values of resulting String.
print(ans)

I would like to explain nCr(n,r) funtion a little more.我想再解释一下 nCr(n,r) 函数。 Given that you have string of length 5 in which number of ones are say 3. Here, N = 5 String = '11100' nCr(5,3) will give all the possible values of the provided string which is (5!/3!*2!) = 10.鉴于您有长度为 5 的字符串,其中的个数为 3。这里, N = 5 String = '11100' nCr(5,3) 将给出所提供字符串的所有可能值,即 (5!/3 !*2!) = 10。
What is wrong with this approach?这种方法有什么问题?

Here is the nCr(n,k):这是 nCr(n,k):

def nCr(n, k): 
    if(k > n - k): 
        k = n - k 
    res = 1
    for i in range(k): 
        res = res * (n - i) 
        res = res / (i + 1) 
    return (res)

I hope, This answers all your questions我希望,这能回答你所有的问题

import operator as op
from functools import reduce

import operator as op
from functools import reduce

def nCr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer / denom

String1 = input()
String2 = input()
n=len(String1)
s1_ones = String1.count('1')
s2_ones = String2.count('1') 

minimum_overlap = max(s1_ones,s2_ones)-min(s1_ones,s2_ones)
zero=n-max(s1_ones,s2_ones)
x=min(s1_ones,s2_ones)
ans = 0
while zero>-1 and x>-1:
    zero-=1
    x-=1
    ans+=nCr(n,minimum_overlap)%1000000007
    minimum_overlap+=2
print(int(ans))

now this nCr function is faster than factorial version, but if it still take time to execute, you can use fermat's theorem for nCr%p (also precompute factorial array) which you can find on internet现在这个 nCr 函数比阶乘版本快,但是如果执行仍然需要时间,您可以使用费马定理来计算 nCr%p(也可以预先计算阶乘数组),您可以在互联网上找到它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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