Even parity adds one bit so that the number of 1s in the word is even.
What to build
A program that finds the even parity bit of some data and prints the word to send.
Requirements
- Print
parity P, where P is 0 or 1. - Print
sent W, where W is the data followed by the parity bit.
Input
One line of 1 to 64 characters, each 0 or 1.
Output
Two lines: parity P and sent W.
Constraints
The data has at most 64 bits.
Example
Input:
1011001
Output:
parity 0
sent 10110010
Why it works
Adding the parity bit to the count of 1s must give an even number. If the count is already even the bit is 0, and if it is odd the bit is 1, which is exactly count % 2.
Examples
1011001
parity 0 sent 10110010
1110
parity 1 sent 11101
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Count the 1s with data.count("1").
Hint 2
The parity bit is 1 when the count is odd and 0 when it is even, so count % 2.
Hint 3
The sent word is the data followed by the parity bit.
Solution
Show one correct solution (try it yourself first)
data = input().strip()
p = data.count("1") % 2
print("parity", p)
print("sent", data + str(p))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step