Find if a string has all unique characters in Python 3
return len(set(s))==len(s)
tl = []
for i in range(len(s)):
ts = s[i]
if ts in tl:
return False
tl.append(ts)
return True
679 ns per loop
%timeit unique_or_not2('abcdef')
1.75 ยตs per loop
Set Method
def unique_or_not(s):return len(set(s))==len(s)
Iteration Method
def unique_or_not2(s):tl = []
for i in range(len(s)):
ts = s[i]
if ts in tl:
return False
tl.append(ts)
return True
Test
%timeit unique_or_not('abcdef')679 ns per loop
%timeit unique_or_not2('abcdef')
1.75 ยตs per loop
Comments
Post a Comment