Skip to content

Instantly share code, notes, and snippets.

@technocake
Created September 4, 2019 14:44
Show Gist options
  • Save technocake/a7c2f509d0032542f577983d77afd571 to your computer and use it in GitHub Desktop.
Save technocake/a7c2f509d0032542f577983d77afd571 to your computer and use it in GitHub Desktop.
Kalkuler kontrollsifre på norske personnumre
# coding: utf-8
def kk(ssn9):
"""
Calculates control decimals for norwegian national identity numbers
see: https://no.wikipedia.org/wiki/F%C3%B8dselsnummer#Oppbygning
D nummer: https://no.wikipedia.org/wiki/F%C3%B8dselsnummer#D-nummer
k1 = 11 - ((3 × d1 + 7 × d2 + 6 × m1 + 1 × m2 + 8 × å1 + 9 × å2 + 4 × i1 + 5 × i2 + 2 × i3) mod 11), # noqa
k2 = 11 - ((5 × d1 + 4 × d2 + 3 × m1 + 2 × m2 + 7 × å1 + 6 × å2 + 5 × i1 + 4 × i2 + 3 × i3 + 2 × k1) mod 11).
"""
dd = ssn9[:2]
mm = ssn9[2:4]
yy = ssn9[4:6]
ii = ssn9[6:]
k1 = 11 - (
3 * int(dd[0]) +
7 * int(dd[1]) +
6 * int(mm[0]) +
1 * int(mm[1]) +
8 * int(yy[0]) +
9 * int(yy[1]) +
4 * int(ii[0]) +
5 * int(ii[1]) +
2 * int(ii[2])
) % 11
k2 = 11 - (
5 * int(dd[0]) +
4 * int(dd[1]) +
3 * int(mm[0]) +
2 * int(mm[1]) +
7 * int(yy[0]) +
6 * int(yy[1]) +
5 * int(ii[0]) +
4 * int(ii[1]) +
3 * int(ii[2]) +
2 * int(k1)
) % 11
k1 = 0 if k1 == 11 else k1
k2 = 0 if k2 == 11 else k2
if k1 == 1 and k2 == 0:
raise ValueError(
'Kontrollsiffrene kan ikke bli 10, ugyldig personnummer')
return "{}{}".format(k1, k2)
if __name__ == '__main__':
print(u"410180222", kk(u"410180222"))
ssn9 = input("Enter the nine first siffer in personnummer")
k = kk(ssn9)
print("personnummer is: {}{}".format(ssn9, k))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment