0

So I have this piece of code:

def check_if_mirror(ch_1, ch_2):
    if len(ch_1) != len(ch_2):
        return False
    nb_car = len(ch_1)
    i = 0
    while i < nb_car:
        if ch_1[i] != ch_2[nb_car-1-i]:
            return False
        i = i+1
    return True

What I want to do is make this same function (which checks if two pieces of string are mirrored) with a for loop instead of a while loop. I made this code:

def check_if_mirror(ch_1, ch_2):
    if len(ch_1) != len(ch_2):
        return False
    ch_1 = ch_1[::-1]
    for i in ch_1:
        if ch_1 == ch_2:
            return True
        return False

But the problem with this one is that it works completely fine without the for loop.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
AstroDog
  • 3
  • 1
  • 1
    Do you have to use a `for` loop? Otherwise you could juse use `ch_1 == ch_2[::-1]` – Barmar Dec 17 '20 at 22:49
  • You're comparing a single character in `ch_1` with the entire string `ch_2`. You need to compare with just the character at the same index. Also, you can't return `True` immediately, only if you make it through the entire loop without a failing comparison. – Barmar Dec 17 '20 at 22:52
  • You can return `False` immediately if the characters don't match. Then return `True` at the end. – Barmar Dec 17 '20 at 22:53
  • Yes I need to use a for loop – AstroDog Dec 17 '20 at 23:28
  • Start with `for index, char in enumerate(ch_1):` – Barmar Dec 17 '20 at 23:31
  • Sorry I'm lost. What does enumerate() do and why are there 2 variables created of index and char. – AstroDog Dec 17 '20 at 23:37
  • `enumerate()` returns a sequence of indexes and contents. So you can then check `if char != ch_2[index]:` – Barmar Dec 17 '20 at 23:39
  • 1
    If you don't know what a function does, read the documentation to find out. – Barmar Dec 17 '20 at 23:40

0 Answers0