Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Aligning values in arrays
#1
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.
Reply
#2
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
Reply
#3
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?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,732 Dec-27-2021, 03:43 AM
Last Post: noahverner1995

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020