Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Iterating through the columns in a list of list to find the palindromes

Here I have a word list as:

[['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]

And I have to display all the palindromes in this list which are in rows as well as columns. I have coded to find all the palindromes in the rows. But cannot implement a method to find the palindromes in the columns.

Here is my code so far:

result_1=""
if len(palindrome)==len_line_str:
    for row in range(len(palindrome)):
        for horizontal_line in range(len(palindrome[row])):
            if ''.join(palindrome[row])==''.join(reversed(palindrome[row])):
                result_1=''.join(palindrome[row])+" is a palindrome starting at ["+str(row)+"]["+str(row)+"] and is a row in the table"
    print(result_1)

Which will display the output:

rotor is a palindrome starting at [0][0] and is a row in the table

Where "rotor" is a palindrome.

I need a method to get the palindromes in the columns which are: "refer", "tenet", "radar"

Any help is much appreciated. Thanks in advance!

like image 937
eye Avatar asked Jan 30 '23 22:01

eye


1 Answers

You can use zip to transpose your lists:

>>> t = [['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]
[['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]
>>> list(zip(*t))
[('r', 'e', 'f', 'e', 'r'), ('o', 'v', 'i', 'n', 'a'), ('t', 'e', 'n', 'e', 't'), ('o', 'i', 'e', 't', 'e'), ('r', 'a', 'd', 'a', 'r')]

Your columns are now rows, and you can apply the same method than before. If you just need the words, you can use list comprehensions:

>>> rows = [['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]
>>> [''.join(row) for row in rows if row[::-1] == row ]
['rotor']
>>> [''.join(column) for column in zip(*rows) if column[::-1] == column ]
['refer', 'tenet', 'radar']
like image 191
Eric Duminil Avatar answered Feb 02 '23 09:02

Eric Duminil