In: Computer Science
Python(please take a screen shot!):
1. hamming distance: write a function distance that take two bits strings, you can assume each strings only contains 0's and 1's. (Note: the two strings might have the same length or not!)
for example:
hamming('010001001111', '01010100') should return 5(1 bit changed plus 4 bits "lost" from the end).
2. write a main function that ask user for two file names, open files and read the 1st line of each, and compares them using Hamming Distance. Just assume each of the 1st line only contains 0's and 1's.
The main function may have to do some extra work to remove newline characters or other whitespace from the text read from each file.
(when create two files to test the main function, make sure the file saved as (.txt) !)
Thanks so much !!!
Python Code:
IDE: repl online python editor
def hamming(x, y):
"""Calculate the Hamming distance between two bit strings"""
count, z = 0, int(x,2)^int(y,2)
while z:
if z&1:
count += 1
z >>= 1
return count
def main():
# Open files
with open('file1.txt') as f1: # Opening file 1
with open('file2.txt') as f2: # Opening file 2
# read files line by line
line_f1 = f1.readline()
line_f2 = f2.readline()
while True:
if line_f1 == '': # break loop if file1 is at eof (end of file)
break
# Hamming distance
print('Hamming distance between', line_f1, 'and', line_f2, 'is:', hamming(line_f1, line_f2))
line_f1 = f1.readline()
line_f2 = f2.readline()
if __name__ == '__main__':
main()
file1.txt:
010001001111
100101010101
1001010110
10101010111111
file2.txt:
01010100
0011010101100101
100101001110
1010110111
Output:
Code Screenshot: