Python Forum
Aligning values in arrays - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Aligning values in arrays (/thread-28003.html)



Aligning values in arrays - pav1983 - Jun-30-2020

Let's say I want to see if the first item in one string is the same first item as the second string in the array. Or, I want to check if the last item of the first string aligns with the last item of the second string in the array. See below of the example.

"[A2], [A8]" would equal True because 'A' and 'A' align. "[B7], [C7]" would equal True because the 7's align.

This ended up being the solution:

def can_capture(rooks):
    if rooks[0][0] == rooks[1][0] or rooks[0][1] == rooks[1][1]:
        return True
    else
        return False
I'm just curious how this code works. It is meant to see if the first item in the first string is the same as the first item in the second string. Likewise, it also checks if the second item in the first string is the same item in the second item in the second string? I'm just curious how this code works. How does it find what I just told you about? Coming up with the solution is one thing, but understanding it is also important.


RE: Aligning values in arrays - bowlofred - Jun-30-2020

It looks like rooks is a list of strings. If so rooks[0] is the first string and rooks[0][0] is the first letter of the first string. From there you should be able to understand the comparison.

Even though there are only 2 letters in the strings, whenever I hear "comparing each position in multiple iterators", I think zip(). I would zip the two strings, (which hands back the characters from each string at the same position) and compare them. Something like:

def is_orthogonally_aligned(pieces):
    for (position_1, position_2) in zip(*pieces):
        if position_1 == position_2:
            return True
    return False

print(is_orthogonally_aligned(['A2', 'A8']))
print(is_orthogonally_aligned(['B7', 'C7']))
print(is_orthogonally_aligned(['C4', 'D5']))
Output:
True True False



RE: Aligning values in arrays - ndc85430 - Jul-01-2020

You wrote code but don't know how it works?

Also the if and else are unnecessary. On line 2, you have an expression that evaluates to True or False, i.e.rooks[0][0] == rooks[1][0] or rooks[0][1] == rooks[1][1]. Why not just return its value?