This is a working program that finds whether the random byte given (with last bit always being 0) has an odd or even number of zeros (including the last bit), if the number of zeros is odd then it returns True and prints "This sequence is correct." and if its even it returns false and prints "This sequence is incorrect and must be corrected.".
import random
def random_binary_sequence(n):
bit = ""
for i in range(0, n, 1):
random_bit = str(random.randint(0, 1))
bit = random_bit
return bit
test_byte = random_binary_sequence(7) " | 0"
def OddParity(Byte):
result = Byte.count('0')
#The line above is using count(), I would like to find a way to replace it using a for loop even tho that might be inefficient
if result % 2 == 0:
print("\n" "This sequence is incorrect and must be corrected.", "\n")
return False
elif result % 2 != 0:
print("\n" "This sequence is correct." "\n")
return True
#else can be used instead of elif above
print("Random test byte given: " test_byte)
print(OddParity(test_byte))
Output:
Random test byte given: 1011010 | 0
This sequence is incorrect and must be corrected.
False
How can I count the zeros using a for loop in this case?
CodePudding user response:
You can do it this way:
Assuming byte = '1010...
, then result = sum([bit == '0' for bit in byte])
CodePudding user response:
To check your number of zero in your input string by for-loop:
inp = "1100100101" # assign your input value here
zero_count = 0
for c in inp: # iterate over your input charcater by character
if c == "0": # check against your condition
zero_count = 1 # if condition is met, your counter increases by 1