Search code examples
pythonstringpandasdataframepalindrome

Create a new column in a dataframe with the values 'bingo' or 'nop' depending on if the row contains all palindromes or not


(Sorry, had to take down my previous post to fix something.)

I recently struggled with this problem in an interview and ran out of time (I had other problems to solve before this one). I went back and solved it later on but I was just wondering how other people would solve this problem. I'm still a bit of a beginner in programming so my answer is most likely not the best.

I was given the following code:

import pandas as pd

input_df = pd.DataFrame(
    [
        'Noon,Feature,Good'.split(','),
        'Radar,Refer,Wow'.split(','),
        'Other,Day,Mouse'.split(',')
    ],
    columns='String_1,String_2,String_3'.split(',')
)

output_df = pd.DataFrame(
    [
        [1,0,0,'nop'],
        [1,1,1,'bingo'],
        [0,0,0,'nop']
    ],
    columns='String_1,String_2,String_3,Bingo'.split(',')
)

So given that input_df, write a function called bingo that will produce the given output_df.

Here is what I came up with:

def is_palindrome(s):
    s = s.lower()

    new_s = ""

    for char in s:
        if char.isalnum():
            new_s += char

    if new_s == new_s[::-1]:
        return 1
    else:
        return 0


def bingo(df):
    df = df.applymap(is_palindrome)

    num_col = len(df.columns)

    sums = df.apply(sum, axis=1)

    values = []
    for item in sums:
        if item == num_col:
            values.append('bingo')
        else:
            values.append('nop')

    df['Bingo'] = values

    return df

output_df.equals(bingo(input_df)) returns True so I believe I've solved the problem in this case. Thanks for any advice, would love to see how other people solve this more efficiently.


Solution

  • You can use applymap to compare each cell with its reversed word and use np.where to determine if it's a bingo or nop.

    output_df = (
        input_df.applymap(lambda x: int(x[::-1].lower()==x.lower()))
        .assign(Bingo=lambda x: np.where(x.all(1), 'bingo', 'nop'))
    )
    
        String_1    String_2    String_3    Bingo
    0   1           0           0           nop
    1   1           1           1           bingo
    2   0           0           0           nop