如何理解这个表达?

huangapple go评论68阅读模式
英文:

How to understand this expression?

问题

error = (parityList.mapIndexed { i, parity -> parity.toInt() * (2.0.pow(i)).toInt() }).sum()

例如:我输入数字101

变量的值如下所示:

parityList = [1, 0]
i = 1
error = 2

error = 2 是如何计算的呢?可以使用以下示例来解释执行顺序:

程序代码:

val input = "101"
val data = input.map { it.toString().toInt() }.toMutableList()
val cList = mutableListOf<Int>()
var c = 0
val h = mutableListOf<Int>()
val parityList = mutableListOf<Int>()

for (k in data.indices) {
    val p = 2.0.pow(c).toInt()
    h.add(data[k])
    if (p == (k + 1)) {
        c++
    }
}

for (parity in h.indices) {
    val ph = 2.0.pow(parity.toDouble()).toInt()
    if (ph == (parity + 1)) {
        val startIndex = ph - 1
        var i = startIndex
        val toXor = mutableListOf<Int>()

        while (i < h.size) {
            val block = h.subList(i, i + ph)
            toXor.addAll(block)
            i += 2 * ph
        }

        for (z in 1 until toXor.size) {
            h[startIndex] = h[startIndex] xor toXor[z]
        }
        parityList.add(h[parity])
    }
}
parityList.reverse()

val error = parityList.mapIndexed { i, parity -> parity * (2.0.pow(i)).toInt() }.sum()
println("parityList = $parityList")
println("parityList = ${parityList.reversed()}")
println("i = $i")
println("error = $error")
   
if (error == 0) {
    println("在收到的Hamming码中没有错误")
} else if (error >= data.size) {
    println("错误无法检测到")
} else {
    println("错误位于第 $error 位")

    if (data[error - 1] == 0) {
        data[error - 1] = 1
    } else if (data[error - 1] == 1) {
        data[error - 1] = 0
        println("修正Hamming码后: - ")
    }
    data.reverse()
    val correctedData = data.joinToString("").toInt()
    println(correctedData)
}

我明白 for i, parityList in enumerate(parityList[::-1]) 函数是如何工作的,但是如何添加 int(parityList) * (2 ** i)


<details>
<summary>英文:</summary>

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&lt;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]==&#39;0&#39;):
        h_copy[error-1]=&#39;1&#39;

    elif(h_copy[error-1]==&#39;1&#39;):
        h_copy[error-1]=&#39;0&#39;
        print(&#39;После исправления код Хэмминга: - &#39;)
    h_copy.reverse()
    print(int(&#39;&#39;.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)`?

</details>


# 答案1
**得分**: 0

```python
# 定义列表
parity_list = [1, 0]
# 反转列表
reveresed_parity_list = parity_list[::-1]
# 将错误输出定义为0
error = 0
# 遍历每个元素,获取索引和值,其中i是索引,parity_list_value是值
for i, parity_list_value in enumerate(reveresed_parity_list):
    # 如果i = 0,那么2^0 = 1,按照任何值的0次方的规则
    error += int(parity_list_value) * (2 ** i)
英文:
# 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)

huangapple
  • 本文由 发表于 2023年2月27日 01:32:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定