0

I am writing an for loop comparing the character in list and string, then return False if the character is not same. But I keep receiving True. Can someone explain what is wrong with my code?

def compare (sofar, orig):
    if len(sofar) == len(orig):
        for i in range(len(orig)+1):
            if orig[i] == sofar[i]:
                return True
            else:
                return False
            
    return False

here is the result i got:

In [29]: compare (['a','v','c','c','s'], 'abccs')
Out[29]: True

But it suppose to be False

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
mozzie
  • 11
  • 1

3 Answers3

0

You could just join the characters back into a string

def compare (sofar, orig):
    return ''.join(sofar) == orig

Otherwise, if you wanted a loop, you need to compare all characters before you return True. You can return False when the first does not match

Here's another one liner using all() over a loop of zipped characters.

You will need the length check before this statement

return all(x == y for x, y in zip(sofar, orig))

Or going back to the original code, invert your logic

def compare (sofar, orig):
    if len(sofar) != len(orig):
        return False
    for i in range(len(orig)):
        if orig[i] != sofar[i]:
            return False

    return True
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

If your function reaches a return statement, that's it. Your function has returned a value and it will not continue running.

You can use a generator to implement your logic. The below solution allows you to iterate lazily; retrieve a Boolean list with a letterwise comparison via list; or check if all letters align via all.

def compare(sofar, orig):
    if len(sofar) == len(orig):
        for i in range(len(orig)):
            if orig[i] == sofar[i]:
                yield True
            else:
                yield False

res = list(compare(['a','v','c','c','s'], 'abccs'))

# [True, False, True, True, True]

res = all(compare(['a','v','c','c','s'], 'abccs'))

# False

Another way of writing your logic without explicit iteration:

lst = ['a','v','c','c','s']
mystr = 'abccs'

res = ''.join(lst) == mystr
jpp
  • 159,742
  • 34
  • 281
  • 339
0

The statement return is exit from your function. So your prog only compares the first element.

 if orig[i] != sofar[i]:
            return False

would do it