2

I want to do a function in python that takes 2 strings, and compare the positions. In case they are equal ('a' == 'a') it appends to a list True, and if it's not False. Also if there are more positions in a list, it should return False too.

def g22(S1, S2):
    new = []
    if len(S1) > len(S2):
        for i in range(len(S1)):
            if S1[i] == S2[i]:
                new.append(True)
            elif S1[i] != S2[i]:
                new.append(False)
            else:
                new.append(False)
    elif len(S1) < len(S2):
         for i in range(len(S1)):
            if S1[i] == S2[i]:
                new.append(True)
            elif S1[i] != S2[i]:
                new.append(False)
            else:
                new.append(False)

    return new

This is what i've came up with, but besides thinking it's wrong it's also sloppy.. ideas? Thanks

4
  • First what happens if both length matches?, you can solve this by adding "=" to one of both if. Commented Jan 4, 2017 at 18:04
  • do you mean compare the character at each position ? your wording is unclear Commented Jan 4, 2017 at 18:14
  • like this S1 = 'house', S2 = 'hose' would return [True, True, False, False, False] @amphibient Commented Jan 4, 2017 at 18:16
  • @RafaelAguilar you're right! thanks :) Commented Jan 4, 2017 at 18:16

6 Answers 6

6

You can use itertools.zip_longest:

from itertools import zip_longest

def agrees(s,t):
    return [x == y for x,y in zip_longest(s,t)]

For example,

>>> agrees("mathematical", "mythical")
[True, False, True, True, False, False, True, False, False, False, False, False]

Note that zip_longest is izip_longest in Python 2.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply, but unfortunately i'm studying for an exam on python and zip wasn't taught so I can't really use it
@stasisOo Hopefully one of the other answers will be of better immediate use to you. If you go on in Python -- master itertools if you haven't already. It is often astonishing when a seemingly complicated question on Stack Overflow is easily solved in just a few lines using itertools. Good luck with your exam.
3

Two basic suggestions:

  1. The whole

        if S1[i] == S2[i]:
            new.append(True)
        elif S1[i] != S2[i]:
            new.append(False)
        else:
            new.append(False)
    

can be replaced with

        new.append(S1[i] == S2[i])
  1. Instead of comparing the two lengths with an if, you could use min(len(S1), len(S2)). This will also fix your current problem of not handling the case when the two lengths match.

Two more advanced suggestions:

  1. You could use a list comprehension instead of an explicit loop.

  2. You could use zip() or map() to simultaneously iterate over the two lists.

2 Comments

map would be something like map(g22, S1, S2) where S1 and S2 are the strings ? I'm studying for a python exam i'm going to have, and wasn't taught zip() so i wont be able to use it. The problem for me with these exercices is mostly dealing with the False for the positions that don't have a match
however, do not forget that S1[i] == S2[i] will throw an IndexError in case of two strings of unequal length.
2

Try this:

def compare(a, b):
    eq = [(x == y) for x, y in zip(a, b)]
    rest = [False] * abs(len(a) - len(b))
    return eq + rest

Comments

1

Answer without using zip (as per OP's request):

def g22(S1, S2):

    str_max = S1 if len(S1) >= len(S2) else S2
    str_min = S1 if len(S1) < len(S2) else S2

    new = [False]*(len(str_max) - len(str_min))
    new = [str_min[i] == str_max[i] for i in range(len(str_min))] + new
    return new

Hopefully range can be used!

4 Comments

You're the best, i'ma try it out!
@stasisOo made a minor change, should be bug free now!
Just used this format on another exercise with similar objective and it worked out great, kinda hard to do it without looking at your example though :p
@stasisOo Looking is not bad as long as you understand it and can adapt it to solve another problem. It is a natural learning process, so do not worry too much. Check also the other answers as well - there is a lot to learn from them!
1

While I do like the compactness of John Coleman's answer, you might be wanting to do it without using external libraries (for whatever reason or limitations), in core Python.

If so, one way to approach it is to write a generic function that compares the elements from the same index position in two lists, catching IndexError (when iterating through characters of two strings of unequal length) and assigning that comparison as False in that case:

def compareLists(argListA, argListB):

    size = max(len(argListA), len(argListB))

    result = []

    for i in range(size):

        try:
            comp = argListA[i] == argListB[i]
        except IndexError:
            comp = False

        result.append(comp)

    return result

Then your usage could be something like:

aStr = "Color"
bStr = "Colour"

#convert the strings into lists of chars

aList = []
aList.extend(aStr)

bList = []
bList.extend(bStr)

comp = compareLists(aList, bList)

print(comp)

prints:

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

Comments

1

So this is the code i've came up with using parts of all the answers

def g22(S1, S2):
    new = []
    if len(S1) >= len(S2):
        rest = [False] * (len(S1) - len(S2))
        for i in range(len(S2)):
            new.append(S1[i] == S2[i])
    elif len(S1) < len(S2):
        rest = [False] * (len(S2) - len(S1))
        for i in range(len(S1)):
            new.append(S1[i] == S2[i])
    return new + rest

Returns:

g22('casa', 'passa')
[False, True, True, False, False]

Thanks everyone :)

Edit: I find kinda dumb we can't use simple built in tools that would reduce this to 4 or 5 lines but oh well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.