Python Forum
Python find the minimum length of string to differentiate dictionary items
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python find the minimum length of string to differentiate dictionary items
#4
Here is a solution with module itertools
import itertools as it

def index_two(a, b):
    '''return the first index where the two words differ
    If they don't differ, return the length of the smallest'''
    return next(
        it.dropwhile(lambda t: t[0]==t[1], zip(a, b, it.count(0))),
        (None, None, min(len(a), len(b))))[2]

def index_many(words):
    '''return the first index where all the words differ
    identical words are considered to differ on the next character'''
    seq = sorted(words)
    if not seq: return 0
    a, b = it.tee(seq)
    next(b, None)
    return max((index_two(*t) for t in zip(a, b)), default=0)


def shorten_names(dic):
    n = index_many(dic.values())
    return {k: v[:1+n] for k, v in dic.items()}
    
dTeamNames = {'A': 'Man City', 'B': 'Man United', 'C': 'West Brom', 'D': 'West Ham'}
dShortNames = shorten_names(dTeamNames)
print(dShortNames)
Reply


Messages In This Thread
RE: Python find the minimum length of string to differentiate dictionary items - by Gribouillis - Mar-03-2018, 05:23 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to get all items in SharePoint recycle bin by using sharepy library in Python? QuangHuynh 2 349 Apr-10-2024, 03:09 PM
Last Post: SandraYokum
  How to parse and group hierarchical list items from an unindented string in Python? ann23fr 0 199 Mar-27-2024, 01:16 PM
Last Post: ann23fr
  Removal of items in .txt using python nanakochan 8 1,767 Sep-02-2022, 04:58 PM
Last Post: perfringo
  mutable values to string items? fozz 15 2,838 Aug-30-2022, 07:20 PM
Last Post: deanhystad
  Find and Replace numbers in String giddyhead 2 1,244 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Converting '1a2b3c' string to Dictionary PythonNoobLvl1 6 1,879 May-13-2022, 03:44 PM
Last Post: deanhystad
  how to assign items from a list to a dictionary CompleteNewb 3 1,593 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  Why is dictionary length not 20? Mark17 2 1,742 Oct-07-2021, 05:56 PM
Last Post: Mark17
  Find string between two substrings, in a stream of data xbit 1 2,165 May-09-2021, 03:32 PM
Last Post: bowlofred
  Parse String between 2 Delimiters and add as single list items lastyle 5 3,397 Apr-11-2021, 11:03 PM
Last Post: lastyle

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020