Saturday 28 February 2015

Skepticism


Almost every Classmate notebook has a page at the end with some interesting facts on it. In my notebook, one of the facts went like this:
Skepticism is the longest word that can be typed with alternate hands.
A list of all valid English words is available in Linux systems. You can get them too, /usr/share/dict/words. So I decided to check the fact and retrieve the largest word that can be typed with alternate hands.
I wrote a Python script to do it.

Flip = lambda X: 0 if X == 1 else 1 
Alibaba = lambda X: 0 if X in left_hand else 1

babloo = str()                # Required string    
babloo_len = 0        

left_hand = 'ASDFGQWERTZXCV'  # Alphabets assigned to Left hand
right_hand = 'LKJHPOIUYMNB'   # Alphabets assigned to Right hand

filename = 'words.txt'        # File with all valid words, 
                              # one on each line  

if __name__ == '__main__':    
    my_file = open(filename, 'r') 
    
    for line in my_file:
        word = line.rstrip().upper()
    
        Clock = Alibaba(word[0])

        sync = True
        for alphabet in word:
            if Alibaba(alphabet) != Clock:  
                sync = False                
                break
            Clock = Flip(Clock)

        if sync:
            print(word, end=',')
            if len(word) > babloo_len:
                babloo = word
                babloo_len = len(word)

    my_file.close()

    print("\n")
    print("Largest word is %s with a length of %d alphabets" 
           % (babloo, babloo_len))

# No offence meant, Babloo

This extracts all the required words and displays the largest of them. They came out to be AUTHENTICITY and ABSORPTIVITY, which have a character length of 12. There are others with a character length of 11. These include DISBANDMENT, ENCHANTMENT, ENTITLEMENT, PROFICIENCY and SHANTYTOWNS. You can modify the script to extract them too.

EDIT: A code golf solution

Written keeping in mind to traverse a word just once.

FILENAME = 'words.txt'
required_words = []

for w in map(lambda s: s.upper(), open(FILENAME, 'r').read().splitlines()):
    prev = None
    for now in map(lambda l: 1 if l in 'ASDFGQWERTZXCV' else 0, w):
        if now == prev: break
        prev = now
    else:
        required_words.append(w)

print(max(required_words, key=len))