After I have visited codewars yesterday I continue to visit that site today and solve one more problem. We will stick to codewars site for a while and solve some problems in the incoming few articles before we move on to visit another website. If you have not yet joined codewars then you should really give it a try. The problem I have solved a few moments ago looks like this:-
Move the first character of the word to the back of that word, if the first character is a member of the punctuation mark group then just leave that character alone. Finally, add in ‘ay’ to the end of every word except the one with its first character is a punctuation mark. Below is the entire solution.
import string def pig_it(words): word_list = words.strip().split(' ') # strip empty spaces then turn words into a list new_word = '' # the new string which will return by this function for i in range(len(word_list)): word = list(word_list[i]) # turn word into a character list if(word[0] not in string.punctuation): # if the first character in the list is not a punctuation mark # then extract out that first character from that entire word front = word[0] del word[0] new_word += ''.join(word) + front + 'ay' + ' ' # finally add in that original front character and 'ay' to the back of the new word else: new_word += ''.join(word) + ' ' # or else just concatenate two words together return new_word.strip()
Now if we enter these words into the above function ‘ Hello world !my man ‘ we will get this in return
I have purposely leaved empty spaces in the front and back of the above words just to demonstrate to you that this program will remove those spaces when it needs to. This program is the modified version of the one which I have submitted to codewars which requires two loops to get the job done. Maybe you have a better suggestion to make this program even shorter, do let me know by leaving your comment at the bottom of this post.
Do you like this website? If so then click on the bell button at the bottom right corner of this post to subscribe to the new article notification. The articles of this website include programming (Java, Javascript, Python) as well as the introduction to the free to use software for windows os and android.
from Planet Python
via read more
No comments:
Post a Comment