Python problem:
write a main function that ask user for 2 file name, open files and read the 1st line of each and compare them using hamming function(below is the hamming function I wrote). Just assume the fist line of each file only contains 0s and 1s, such as 0100111101.
The main function may have to do some extra work to remove newline characters or other whitespace from the text read from each file.
This is hamming function that need to be used in the main function:
def hamming(str1, str2):
diffs = 0
smaller_length = len(str1) if len(str1) < len(str2) else
len(str2)
for i in range(smaller_length):
if str1[i] != str2[i]:
diffs += 1
diffs += abs(len(str1) - len(str2))
return diffs
Python Code:
def hamming(str1, str2):
diffs = 0
smaller_length = len(str1) if len(str1) < len(str2) else len(str2)
for i in range(smaller_length):
if str1[i] != str2[i]:
diffs += 1
diffs += abs(len(str1) - len(str2))
return diffs
def main():
inp1=input("Enter the name of 1st file ")
inp2=input("Enter the name of 2nd file ")
with open(inp1) as file1, open(inp2) as file2:
file1line=file1.readline().strip()
file2line=file2.readline().strip()
ans=hamming(file1line,file2line)
print(ans)
if __name__=="__main__":
main()
Get Answers For Free
Most questions answered within 1 hours.