Skip to content

Instantly share code, notes, and snippets.

@jrha
Last active June 2, 2017 15:27
Show Gist options
  • Save jrha/533a7f1215d699804ba385221ff56f0b to your computer and use it in GitHub Desktop.
Save jrha/533a7f1215d699804ba385221ff56f0b to your computer and use it in GitHub Desktop.
Convert any positive integer into a DNS like name and vice-versa
#!/usr/bin/env python2
#
# Copyright 2017 Science & Technology Facilities Council
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Convert any positive integer into a DNS style name and vice-versa.
A text file named 'elements' with a single unique word per line must be supplied, census birth name data works well.
"""
import argparse
SEPERATOR = '.'
# From https://stackoverflow.com/questions/2267362/how-to-convert-an-integer-in-any-base-to-a-string
def number_to_base(n, b):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1]
def get_elements():
result = open('elements').readlines()
result = [s.strip().lower() for s in result]
return result
def number_to_name(num, elements):
result = []
for val in number_to_base(num, len(elements)):
result.append(elements[val])
result.reverse()
return SEPERATOR.join(result)
def name_to_number(name, elements):
numbers = []
words = name.strip().lower().split(SEPERATOR)
for word in words:
numbers.append(elements.index(word))
result = 0
for power, number in enumerate(numbers):
result += number * (len(elements) ** power)
return result
def int_positive(s):
i = int(s)
if i < 0:
raise argparse.ArgumentTypeError("must be a positive integer")
return i
def main():
parser = argparse.ArgumentParser(description='Namji')
parser.add_argument('-n', type=int_positive, help='Number to convert to text')
parser.add_argument('-t', type=str, help='Text to convert to number')
args = parser.parse_args()
if args.n is not None or args.t is not None:
elements = get_elements()
if args.n is not None:
print '%d\t%s' % (args.n, number_to_name(args.n, elements))
if args.t is not None:
print '%s\t%d' % (args.t, name_to_number(args.t, elements))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment