Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string has the same characters? Python

I need to be able to discern if a string of an arbitrary length, greater than 1 (and only lowercase), has the same set of characters within a base or template string.

For example, take the string "aabc": "azbc" and "aaabc" would be false while "acba" would be true.

Is there a fast way to do this in python without keeping track of all the permutations of the first string and then comparing it to the test string?

like image 386
Monte Carlo Avatar asked Aug 20 '13 00:08

Monte Carlo


People also ask

How do you check if a string contains the same character?

To find whether a string has all the same characters. Traverse the whole string from index 1 and check whether that character matches the first character of the string or not. If yes, then match until string size. If no, then break the loop.

How do I check if two characters are the same in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.

Can you == strings in Python?

Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.

Can I use == to compare strings in Python?

Python comparison operators can be used to compare strings in Python. These operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).


2 Answers

Sort the two strings and then compare them:

sorted(str1) == sorted(str2)

If the strings might not be the same length, you might want to make sure of that first to save time:

len(str1) == len(str2) and sorted(str1) == sorted(str2)
like image 105
David Robinson Avatar answered Sep 28 '22 03:09

David Robinson


This is the O(n) solution

from collections import Counter
Counter(str1) == Counter(str2)

But the O(n * log n) solution using sorted is likely faster for sensible values of n

like image 29
John La Rooy Avatar answered Sep 28 '22 03:09

John La Rooy