How to understand this expression?

Question:

I am converting Hamming code from python to kotlin. And I almost did everything, but there is one expression that I do not understand.

error=sum(int(parity_list) * (2 ** i) for i, parity_list in enumerate(parity_list[::-1]))

For example: I enter the number 101

The value of the variables are obtained:

parity_list = [1,0]

i = 5

error = 2

How come error = 2? Can you explain the execution sequence with an example?

Program code:

# coding=windows-1251
 
from traceback import print_tb
 
 
print('Введите полученный код Хэмминга')
d=input()
data=list(d)
data.reverse()
c,ch,j,r,error,h,parity_list,h_copy=0,0,0,0,0,[],[],[]
 
for k in range(0,len(data)):
        p=(2**c)
        h.append(int(data[k]))
        h_copy.append(data[k])
        if(p==(k+1)):
            c=c+1
            
for parity in range(0,(len(h))):
        ph=(2**ch)
        if(ph==(parity+1)):
 
            startIndex=ph-1
            i=startIndex
            toXor=[]
 
            while(i<len(h)):
                block=h[i:i+ph]
                toXor.extend(block)
                i+=2*ph
 
            for z in range(1,len(toXor)):
                h[startIndex]=h[startIndex]^toXor[z]
            parity_list.append(h[parity])
            ch+=1
parity_list.reverse()
 
print('parity_list = ', parity_list)
print('parity_list = ', parity_list[::-1])
print('i = ', i)
error=sum(int(parity_list) * (2 ** i) for i, parity_list in enumerate(parity_list[::-1]))
print("error =  ", error)
   
if((error)==0):
        print('В полученном коде Хэмминга нет ошибок')
 
elif((error)>=len(h_copy)):
        print('Ошибка не может быть обнаружена')
 
else:
        print('Error is in',error,'bit')
 
        if(h_copy[error-1]=='0'):
            h_copy[error-1]='1'
 
        elif(h_copy[error-1]=='1'):
            h_copy[error-1]='0'
            print('После исправления код Хэмминга: - ')
        h_copy.reverse()
        print(int(''.join(map(str, h_copy))))

I understand how the function for i, parity_list in enumerate(parity_list[::-1]) works, but how to add this int(parity_list) * (2 ** i)?

Asked By: PROSTO ilya

||

Answers:

# Define the list
parity_list = [1, 0];
# reverse the list
reveresed_parity_list = parity_list[::-1]
# define error output as 0
error = 0
# loop through each element, getting the index and the value where i is the index and parity_list_value is the value
for i, parity_list_value in enumerate(reveresed_parity_list):
    # if i = 0 then 2^0 = 1 as the rule for any value to the exponent of 0
    error += int(parity_list_value) * (2 ** i)
Answered By: Dean Van Greunen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.