Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python character match in a string

Write a function repfree(s) that takes as input a string s and checks whether any character appears more than once. The function should return True if there are no repetitions and False otherwise.

I have tried this but I don't feel this is an efficient way of solving it. Can you suggest an efficient code for this, thanks?

def repfree(s):
    newlist = []
    for i in range(0, len(s)):
        newlist.append(s[i])
    newlist2 = set(newlist)
    if len(newlist) == len(newlist2):
        print("True")
   else:
        print("False")
like image 792
Praveen KUMAR Avatar asked Jul 21 '26 11:07

Praveen KUMAR


2 Answers

One easy way to meet this requirement is to use regular expressions. You may not be allowed to use them, but if you can, then consider this:

def repfree(s):
    if re.search(r'^.*(.).*\1.*$', s):
        print("True")
    else:
        print("False")
like image 120
Tim Biegeleisen Avatar answered Jul 24 '26 00:07

Tim Biegeleisen


Believe it or not, this problem can be solved in O(1) time, because every sufficiently large string contains at least one duplicate character. There are only a finite number of different Unicode characters, after all, so a string cannot be arbitrarily long while also using each Unicode character at most once.

For example, if you happen to know that your strings are formed of only lowercase letters, you can do this:

def has_repeated_char(s):
    return len(s) > 26 or len(s) != len(set(s))

Otherwise you can replace the 26 with whatever number of characters your string could possibly contain; e.g. 62 for upper- and lowercase letters and digits.

As of February 2020, the whole of Unicode has 137,994 distinct characters (Wikipedia), so if your string length is 150,000 then you can return True without searching.

like image 27
kaya3 Avatar answered Jul 24 '26 01:07

kaya3