Explanation:
I wrote the following function to shorten the hostnames of machines used in production. Here the names have been changed, but the same structure and format have been preserved. The code below is inconvenient, and I would like to make DRY (Do not Repeat Yourself) code . Readability is also important, as it is code that you may need to save or understand not only by yourself.
Code:
def shorten_hostnames(machines):
d = {k: v.split('.') for k, v in machines.items()}
while all(d.values()):
if not len(set([v[-1] for v in d.values()])) == 1:
break
if not all(len(v) > 1 for v in d.values()):
break
d = {k: v[:-1] for k, v in d.items()}
while all(d.values()):
if not len(set([v[0] for v in d.values()])) == 1:
break
if not all(len(v) > 1 for v in d.values()):
break
d = {k: v[1:] for k, v in d.items()}
d = {k: '.'.join(v) for k, v in d.items()}
return d
Input Example:
machines = {'a.ace.site.info': 'a.ace.site.info',
'b.ace.site.info': 'b.ace.site.info',
'a.bob.site.info': 'a.bob.site.info',
'b.bob.site.info': 'b.bob.site.info',}
Output:
>>> for k, v in shorten_hostnames(machines).items():
print k, '-->', v
b.ace.site.info --> b.ace
a.ace.site.info --> a.ace
b.bob.site.info --> b.bob
a.bob.site.info --> a.bob
Where and why do I need your help:
, , , , . , , , , - .
:
, "Gotcha". ( machines = {'a.ace.site.info': 'a.ace.site.info'}
), ( a
). - . - ( )
:
, , , . , ( ), , , , , .
:
machines = {'ace.a.site.info': 'ace.a.site.info',
'ace.b.site.info': 'ace.b.site.info',}
ace.b.site.info --> b
ace.a.site.info --> a
machines = {'a.ace.site.info': 'a.ace.site.info',}
a.ace.site.info --> a
machines = {'ace.a.site.info': 'ace.a.site.info',
'ace.b.site.com': 'ace.b.site.com',}
ace.b.site.com --> b.site.com
ace.a.site.info --> a.site.info