Skip to content

Instantly share code, notes, and snippets.

@dfch
Last active May 16, 2026 07:25
Show Gist options
  • Select an option

  • Save dfch/e8034494c550999179a6623c28517772 to your computer and use it in GitHub Desktop.

Select an option

Save dfch/e8034494c550999179a6623c28517772 to your computer and use it in GitHub Desktop.
Community Health Index (CHI) Generator, United Kingdom, Scotland
# This is free and unencumbered software released into the public domain.
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# For more information, please refer to <https://unlicense.org>
import random
def generate_chi(dob: str, is_odd: bool) -> str:
"""
Generate a valid CHI (Community Health Index) number.
Parameters:
dob (str): Date of birth in DDMMYY format (e.g., '010203')
is_odd (bool): True: Male, or False: Female
Returns:
str: A valid 10-digit CHI number, or raises ValueError if invalid.
"""
if len(dob) != 6 or not dob.isdigit():
raise ValueError("Date of birth must be a 6-digit string in DDMMYY format.")
# Generate a 3-digit sequence number based on is_odd.
# Odd = Male, Even = Female.
while True:
seq = random.randint(0, 999)
if seq % 2 == (1 if is_odd else 0):
break
seq_str = f"{seq:03d}"
first_nine = dob + seq_str
# Calculate check digit using Modulus 11.
weights = [10, 9, 8, 7, 6, 5, 4, 3, 2]
total = sum(int(d) * w for d, w in zip(first_nine, weights))
remainder = total % 11
check_digit = 11 - remainder
if check_digit == 11:
check_digit = 0
elif check_digit == 10:
# Invalid combination — regenerate sequence number.
return generate_chi(dob, is_odd)
return first_nine + str(check_digit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment