Determine if a string has all unique characters: Difference between revisions
Content added Content deleted
(added Lua version) |
(Add Python version using regular expression (re) library) |
||
Line 2,399: | Line 2,399: | ||
'XYZ ZYX' (7) -> 'X' (0x58) at [0, 6] |
'XYZ ZYX' (7) -> 'X' (0x58) at [0, 6] |
||
'1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ' (36) -> '0' (0x30) at [9, 24]</pre> |
'1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ' (36) -> '0' (0x30) at [9, 24]</pre> |
||
=== Using regular expression === |
|||
<lang python>import re |
|||
pattern = '(.)' + '.*?' + r'\1' |
|||
def find_dup_char(subject): |
|||
match = re.search(pattern, subject) |
|||
if match: |
|||
return match.groups(0)[0], match.start(0), match.end(0) |
|||
def report_dup_char(subject): |
|||
dup = find_dup_char(subject) |
|||
prefix = f'"{subject}" ({len(subject)})' |
|||
if dup: |
|||
ch, pos1, pos2 = dup |
|||
print(f"{prefix}: '{ch}' (0x{ord(ch):02x}) duplicates at {pos1}, {pos2-1}") |
|||
else: |
|||
print(f"{prefix}: no duplicate characters") |
|||
show = report_dup_char |
|||
show('coccyx') |
|||
show('') |
|||
show('.') |
|||
show('abcABC') |
|||
show('XYZ ZYX') |
|||
show('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ') |
|||
</lang> |
|||
{{out}} |
|||
<pre>"coccyx" (6): 'c' (0x63) duplicates at 0, 2 |
|||
"" (0): no duplicate characters |
|||
"." (1): no duplicate characters |
|||
"abcABC" (6): no duplicate characters |
|||
"XYZ ZYX" (7): 'X' (0x58) duplicates at 0, 6 |
|||
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" (36): '0' (0x30) duplicates at 9, 24 |
|||
</pre> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |