Determine if a string has all unique characters: Difference between revisions
Determine if a string has all unique characters (view source)
Revision as of 23:23, 30 December 2019
, 4 years ago→Python :: Functional: Inserted a variant fusion of filtering and min to one fold.
m (→Python :: Functional: Inserted a variant fusion of filtering and min to one fold.) |
|||
Line 1,333:
min(duplicates, key=compose(head, snd))
) if duplicates else Nothing()
# And another alternative here would be to fuse the 1 < len(v)
# filtering, and the min() search for the earliest duplicate,
# down to a single `earliestDuplication` fold:
# duplicatedCharIndices_ :: String -> Maybe (Char, [Int])
def duplicatedCharIndices_(s):
'''Just the first duplicated character, and
the indices of its occurrence, or
Nothing if there are no duplications.
'''
def positionRecord(dct, ic):
i, c = ic
return dict(
dct,
**{c: dct[c] + [i] if c in dct else [i]}
)
def earliestDuplication(sofar, charPosns):
c, indices = charPosns
return (
Just((c, indices)) if sofar['Nothing'] else (
# Earlier ?
Just((c, indices)) if (
indices[0] < sofar['Just'][1][0]
) else sofar
)
) if 1 < len(indices) else sofar
return reduce(
earliestDuplication,
reduce(
positionRecord,
enumerate(s), {}
).items(),
Nothing()
)
Line 1,352 ⟶ 1,390:
fTable('First duplicated character, if any:')(
showSample
)(maybe('None')(showDuplicate))(
'', '.', 'abcABC', 'XYZ ZYX',
'1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'
|