QUESTION
WRITE A code to check if a list of 'N' English words can be written using only one row of the keyboard. If that's the case, make a list containing 'True' or 'False' options.
Input :
First line must read the value of 'N'. Second line onwards read 'N' Words
Example : if the value of N = 3 then the list of English words are [POTTER, EQUITY, LIRIL] then the output is [True, True, False]
MY CODE
N=int(input("enter number of elements: "))
words=input("enter the words separated by a space: ")
wl=words.split()
print("list of words is" , wl)
l2=[]
final=[]
a=['q','w','e','r','t','y','u','i','o','p']
if N<0:
print("Invalid Input")
else:
for i in range(0,N):
ele=wl[i]
l2.append(ele)
new=ele.split()
if new <=a:
re1='True'
final.append(re1)
else:
re2='False'
final.append(re2)
print(final)
final list shows true even letters from other rows of the keyboard are used. can anyone point out where my mistake is and help me out in fixing this code?
CodePudding user response:
There are 3 rows of letters on your keyboard
row1="QWERTYUIOP"
row2="ASDFGHJKL"
row3="ZXCVBNM"
Granted that the 3rd row won't produce any words because it hase no vowels but you would still need to check the second row for words such as GLAD, FLAG, HALL, etc.
For each individual word, it will be possible to write it on one row, if all its letters are on the same row:
if all(letter in row1 for letter in word) \
or all(letter in row1 for letter in word):
With this you should be able to populate your final result by looping over the word list (no need to bother with indexes).
for word in wl:
if all(letter in row1 for letter in word.upper()) \
or all(letter in row2 for letter in word.upper()):
final.append(True)
else:
final.append(False)