+ 2
I've been trying the Spy life code coach question. But I just can't seem to get it right. What is wrong with my code?
word = input() rev_word = word[::-1] rev_word = list(rev_word) valid = "a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z" valid = list(valid) for i in rev_word: if not i in valid: rev_word.remove(i) rev_word = "".join(rev_word) print(rev_word)
7 Réponses
+ 8
Umar Muhammad ,
the task description says that we have to remove all "none" alphabet character. as Jayakrishna🇮🇳 already mentioned, iterating and removing elements at the same time can create issues. so we can go for an other strategy and try this (we are going to create a new string that contains only allowed characters):
> input the string and then reverse it
> create an empty list that can hold the characters after "filtering" out not allowed characters
> run a loop over the reversed string, it will give you one character in each iteration cycle
> check if the character is allowed:
this can be done by using the string method isxxxx() that checks for alphabet characters, check also if character is a space
if char is alpha or a space, append this character to the list
> if iteration of the loop is done, the list contains only allowed characters
> finally we have to join the list elements to a string and the output it.
+ 4
Umar Muhammad ,
your solution is perfect 👍😁
+ 3
in loop, for I in rev_word: you are using original list, so removing will reflect on next iteration value.
a1cb => if you remove 1, next element is for i value is b, not c because list str is acb.
+ 3
Lothar thank you. I'll try these
+ 3
As @Lother said, use isalpha() , (isspace() ) instead of 'valid' list. If true add to empty list.
You code works well if you use rev_word.copy() instead of rev_word in loop.
You're welcome...
+ 3
Solved it!
word = input()
rev_word = word[::-1]
rev_word = list(rev_word)
out_word = []
for i in rev_word:
if i.isalpha() or i.isspace():
out_word.append(i)
out_word= "".join(out_word)
print(out_word)
+ 2
Jayakrishna🇮🇳 Thank you so much