w3resource

Python: Find two indices making a given string unhappy

Python Programming Puzzles: Exercise-83 with Solution

A string is happy if every three consecutive characters are distinct. Write a Python program to find two indices associated with a given string being unhappy.

Input: 
Python
Output:
None

Input: 
Unhappy
Output:
[4, 5]

Input:
Find
Output:
None

Input:
Street
Output:
[3, 4]

Visual Presentation:

Python: Find two indices making a given string unhappy.
Python: Find two indices making a given string unhappy.

Sample Solution:

Python Code:

# License: https://bit.ly/3oLErEI

# Define a function named 'test' that takes a string 's' as input
def test(s):
    # Iterate through the characters of the string up to the second-to-last character
    for i in range(len(s) - 2):
        # Check if consecutive characters are the same, return the indices if true
        if s[i] == s[i + 1]:
            return [i, i + 1]
        # Check if characters with one character in between are the same, return the indices if true
        if s[i] == s[i + 2]:
            return [i, i + 2]

# Example 1
strs1 = "Python"
print("Original string:", strs1)
print("Find two indices making the string unhappy:")
print(test(strs1))

# Example 2
strs2 = "Unhappy"
print("\nOriginal string:", strs2)
print("Find two indices making the string unhappy:")
print(test(strs2))

# Example 3
strs3 = "Find"
print("\nOriginal string:", strs3)
print("Find two indices making the string unhappy:")
print(test(strs3))

# Example 4
strs4 = "Street"
print("\nOriginal string:", strs4)
print("Find two indices making the string unhappy:")
print(test(strs4))

Sample Output:

Original string: Python
Find two indices making the said string unhappy!
None

Original string: Unhappy
Find two indices making the said string unhappy!
[4, 5]

Original string: Find
Find two indices making the said string unhappy!
None

Original string: Street
Find two indices making the said string unhappy!
[3, 4]

Flowchart:

Flowchart: Python - Find two indices making a given string unhappy.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Find the sublist of numbers with only odd digits in increasing order.
Next: Find the index of the matching parentheses for each character in a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/puzzles/python-programming-puzzles-83.php