Program to find out the XOR values of specific elements from a generated list in Python

PythonServer Side ProgrammingProgramming

Suppose we are given a list that contains natural numbers. Now from that list, we remove all the numbers that contain two consecutive 1s in its binary representation and generate another list called Z. Now we are given another list 'input_list' that contains some integer values. We have to find out the XOR value of the specified elements from Z whose indexes are specified in input_list.

So, if the input is like input_list = [3, 4, 5], then the output will be 9.

In indexes 3, 4, and 5 of Z; the values are 4, 5, and 8. So, 4 XOR 5 XOR 8 = 9.

To solve this, we will follow these steps −

  • Define a function zeck_num() . This will take k, f_list
    • res := 0
    • for i in range (size of f_list -1) to -1, decrease by 1, do
      • if k >= f_list[i], then
        • res := res + 2^i
        • k := k - f_list[i]
    • return res
  • MOD := 10^9 + 7
  • max_val := 10^18
  • f_list := a new list containing values 1 and 2
  • while last element of f_list <= max_val, do
    • insert last element of f_list + second last element of f_list at the end of f_list
  • res := 0
  • for each index in input_list, do
    • res := res XOR zeck_num(index, f_list)
  • return res mod MOD

Example

Let us see the following implementation to get better understanding −

def zeck_num(k, f_list):
   res = 0
   for i in range(len(f_list)-1,-1,-1):
      if k >= f_list[i]:
         res += 2**i
         k -= f_list[i]
   return res

def solve(input_list):
   MOD = 10**9+7
   max_val = 10**18
   f_list = [1,2]
   while f_list[-1] <= max_val:
      f_list.append(f_list[-1] + f_list[-2])
   res = 0
   for index in input_list:
      res ^= zeck_num(index, f_list)
   return res % MOD

print(solve([3, 4, 5]))

Input

[3, 4, 5]

Output

9
raja
Updated on 20-Oct-2021 08:09:12

Advertisements