DEV Community

Cover image for Python | Isogram Problem!
Banji
Banji

Posted on • Edited on

Python | Isogram Problem!

Hey everone, I wanna share my last challenge that I solved, it took me around 2 days!
I know it could be easy for some of you even for beginners but it doesn't matter for me cause my goal is improving my coding skill and problem solving every single day.
Long story short!
Let's dive to the Isogram Challenge!


Alt Text
SOLVE IT!

Problem:

Determine if a word or phrase is an isogram.

An isogram (also known as a "nonpattern word"),
 is a word or phrase without a repeating letter,
 however spaces and hyphens are allowed to appear
 multiple times.

Examples of isograms:

- lumberjacks
- background
- downstream
- six-year-old

The word **isograms**,
is not an isogram, because the s repeats.
Enter fullscreen mode Exit fullscreen mode

Let's break down the problem to the 3 steps:

  1. Making a function
  2. We need to use if statement to count if there's more than one item in our string!
  3. we need to loop over if statement to check every item in our string!.

1.Making a function:

  def isogram(string):
       pass
Enter fullscreen mode Exit fullscreen mode

2.if statement to count if there's one more item or not:

if string.count(item) > 1 :
            return False
Enter fullscreen mode Exit fullscreen mode

3.for loop over if statement to check every item in given string:

for item in upper_string:
Enter fullscreen mode Exit fullscreen mode

*after this steps we need to combine number 2 and number 3, like this:

for item in upper_string:
        if upper_string.count(item) > 1 :
            return False
Enter fullscreen mode Exit fullscreen mode

So we have a function:

def isogram(string):

    for item in string:
        if string.count(item) > 1 :
            return False
    return True
Enter fullscreen mode Exit fullscreen mode

If we test our program with a string like this:

abc = isogram("A B C")
Enter fullscreen mode Exit fullscreen mode

It will return False !
Cause our program count spaces so we have two spaces in "A B C" string!
If your read the Problem part carefully it says:

spaces and hyphens are allowed to appear
multiple times!
So:

spaces = " "
hyphens = "-"
Enter fullscreen mode Exit fullscreen mode

We need another step to complete our solution which is:
.
.
.
4.writing a __if statement_ for spaces and hyphens to return True if there's more than once_:

spaces = " "
hyphens = "-"
if string.count(spaces)>1 or string.count(hyphens)>1:
      return True
Enter fullscreen mode Exit fullscreen mode

and our string() function will be look like this:

def isogram(string):

    for item in string:
        spaces = " "
        hyphens = "-"
        if  string.count(item) > 1 :
            return False
        elif string.count(spaces) > 1 or string.count(hyphens) > 1:
            return True 
        else:
            pass
    return True

Enter fullscreen mode Exit fullscreen mode

Let's test our program with another string:

abc = isogram("A a B C")
print(abc)
Enter fullscreen mode Exit fullscreen mode

Our program will return True!!!
But we have two letter "A" and "a"!
That's obvious cause there is a difference between Capital letters and small letter in every programming language!
and if you try :

print(A is a)
Enter fullscreen mode Exit fullscreen mode

the answer would be False.
So in our program we can make all letters Upper-Case(upper()) or Lower-Case(lower()), it's totally up to you, I prefer upper!

def is_isogram(string):

    upper_string = string.upper()

    for item in upper_string:
        spaces = " "
        hyphens = "-"
        if upper_string.count(item) > 1 :
            return False

        elif string.count(spaces) > 1 or string.count(hyphens) > 1:
            return True 
        else:
            pass
    return True
Enter fullscreen mode Exit fullscreen mode

I need to say thank you my brother Amir, cause you're helping me a lot in this way.


Finally we completed this challenge, if you have any suggestion to improve this solution and write more Pythonic, cleaner and more readable just let me know and leave a comment below my post, I'll appreciate it.
Thank you so much for reading my post.

Keep Moving Forward

Code with 💛

🅑🅐🅝🅙🅘

Top comments (10)

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

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
 
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

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

Keep Moving Forward

Code with 💛

🅑🅐🅝🅙🅘

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
 
rafaacioly profile image
Rafael Acioly • Edited

Hi Banji, you've done a nice work on this challenge, congratulations :)

Here's my approach:

from collections import Counter
import re

def is_isogram(text: str) -> bool:
  content = re.sub(r"-|\s+", "", text, flags=re.UNICODE)
  letter_counter = Counter(content)

  letter, amount = letter_counter.most_common(1)[0]

  return amount == 1

My considerations:

  • I always use the class Counter when i need to check if something repeats
  • Before starts to work on the input i always normalized it first
  • In this case i prefer to use regex to substitute hypens and spaces at once instead of using the method replace twice, like this: text.replace("-", "").replace("-", "")

A few tips:

Every time i need/want to do a challenge that need loop or repetitive tasks i always ask myself:

Can i use some of the standard libraries of python to solve this?

Then i check the itertools, and the collections packages.

The big brain move on my approach was the use of Counter class, this class have a lot useful methods such as subtract, add, and get the most_common letter form the input.

Collapse
 
banji220 profile image
Banji • Edited

Heyyyyyyyyy Rafael ;)
Thank you for sharing your code and your great approach in my Post.
I appreciate it
But if you test your program with a string like:

abc = is_isogram("A a B C)
print(abc)

the program will

__return : True__

but we need to get False cuz there's to letter (A, a).

Finally your comment was so helpful for me cuz I think I really need to change some of my approach in my coding routine like using standard libraries more and etc.
Thanks for giving a light in my jourrney.

Keep Moving Forward

Code with 💛

🅑🅐🅝🅙🅘

Collapse
 
rafaacioly profile image
Rafael Acioly

I didn't see this case, we can fix this normalizing even more the input with .lower() and it will work just fine.

I'm glad to help.