Fix the Fletcher checksum check for packets
Your task
Your packets end with a 2-byte checksum. The first verifier summed the body bytes, so a packet with two bytes swapped, or one byte up and another down by the same amount, still passed. The fix uses Fletcher-16, which also weighs each byte by its position.
An assistant wrote verify_packet(packet). It is in the editor. It has a bug. Find it and fix it.
Input and output:
packet: the packet's bytes, as integers from 0 to 255. The last 2 are the checksum, high byte first. The rest is the body.- Return
truewhen the checksum matches the body, elsefalse.
Rules the tests check:
- A packet shorter than 2 bytes has no checksum: return
false. - The claimed checksum is the first checksum byte times 256, plus the second.
- Fletcher-16: start with
sum1 = 0andsum2 = 0. For each body byte in order, setsum1 = (sum1 + byte) mod 255, thensum2 = (sum2 + sum1) mod 255. - The computed checksum is
sum2times 256, plussum1. The packet is valid when it equals the claimed checksum.
Examples
verify_packet(packet: list[int]) -> boolExample 1
Input
verify_packet([1, 2, 3, 10, 6])Output
TrueExample 2
Input
verify_packet([3, 2, 1, 10, 6])Output
FalseExample 3
Input
verify_packet([0, 0])Output
True