DEV Community

loading...

Discussion on: Python | Isogram Problem!

Collapse
vidit1999 profile image
Vidit Sarkar
def is_isogram(str):
    cleaned = str.replace('-', '').replace(' ', '').lower()
    return len(set(cleaned)) == len(cleaned)

print(is_isogram("lumberjacks")) # output -> True
print(is_isogram("background")) # output -> True
print(is_isogram("downstream")) # output -> True
print(is_isogram("six-year-old")) # output -> True
print(is_isogram("isograms")) # output -> False
print(is_isogram("A B C")) # output -> True
print(is_isogram("A a B C")) # output -> False
Collapse
banji220 profile image
Banji Author

Hey Vidit Sarkar, tnx for sharing your amazing solution with us, I have problem to understand :

return len(set(cleaned)) == len(cleaned)

could ya explaing me why we need to write return with

len(set()) == len()

?
actually let me know what's happening behind the scene.
Happy Coding ;)

Collapse
thinkverse profile image
Kim Hallberg

As I understand that code, sets only accept unique characters, and since he cleaned out the hyphens and spaces if the len of the set(cleaned) isn't the len of cleaned that means we have a duplicate character, hence it's not an isogram. 🤔

Please correct me if I'm wrong. 🙂

Thread Thread
vidit1999 profile image
Vidit Sarkar

Yes, you are right!

Thread Thread
thinkverse profile image
Kim Hallberg • Edited

Fun thing, the same code works in Javascript too with some small modifications.

function is_isogram (str) {
    const cleaned = str.replace('-', '').replace(' ', '').toLowerCase();
    return new Set(cleaned).size == cleaned.length;
}

console.log(is_isogram("lumberjacks")) // Returns true
console.log(is_isogram("background")) // Returns true
console.log(is_isogram("downstream")) // Returns true
console.log(is_isogram("six-year-old")) // Returns true
console.log(is_isogram("isograms")) // Returns false
console.log(is_isogram("\u0041\u0042\u0043"))  // Returns true
console.log(is_isogram("\u0041\u0061\u0042\u0043")) // Returns false
Collapse
vidit1999 profile image
Vidit Sarkar

Let's take the example , s = "Six-Year- Old".
replace('-', '') , replace(' ', '') will going to replace all -'s and spaces with empty character respectively. lower() will lowercase all charecters.
So, cleaned will be, cleaned = 'sixyearold'.

Now, set(cleaned) stores all unique characters of cleaned. So, if count of all unique characters is same as length of cleaned then all characters of cleaned are unique.

len(set(cleaned)) == len(cleaned) will be True if all characters of cleaned are unique, else False.

Thread Thread
banji220 profile image
Banji Author

Tnx Vidit Sarkar for your amazing explanation .
I appreciate that.

Keep Moving Forward

Code with 💛

🅑🅐🅝🅙🅘