Skip to content

Instantly share code, notes, and snippets.

@4e1e0603
Last active February 11, 2020 08:50
Show Gist options
  • Save 4e1e0603/f8d25b937ca6d529286dd2595d70f2ae to your computer and use it in GitHub Desktop.
Save 4e1e0603/f8d25b937ca6d529286dd2595d70f2ae to your computer and use it in GitHub Desktop.
Compute Hamming Distance
# -*- coding: utf-8 -*-
"""
Hamming distance between two sequences.
Hamingova vzdálenost je metrika; splňuje předpoklady:
Předpoklad:
a) H(x, y) >= 0 a H(x, y) = 0 právě když x = y;
b) H(x, y) = H(y, x) komutace
c) H(x, z) <= H(x, y) + H(y, z) trojúhelníková nerovnost
"""
from typing import Sequence
class Hamming:
@staticmethod
def v1(cls, s1: Sequence, s2: Sequence) -> int:
if len(s1) != len(s2):
raise ValueError("Sequences hasn't the same length!")
distance = 0
for x, y in zip(s1, s2):
if x != y:
distance += 1
return distance
@staticmethod
def v2(cls, s1, s2 = None) ->:
if s2 = None:
return len(s1)
if len(s1) != len(s2):
raise ValueError("Sequences hasn't the same length!")
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
if __name__ == "__main__":
words = [
("pes", "les"), ("kůl", "hůl"), ("půl", "vůl"), # = 1
("půl", "vůz"), ("sůl", "můj"), # = 2
("ruka", "muka"), ("stát", "hrát"), # = 1
("lhář", "tmář"), ("paruka", "záruka"), # = 2
("záruka", "antuka"), # = 3
]
for w in words:
print(Hamming.v1(w[0], w[1]), w[0], w[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment