Today I have solved yet another python problem on codewars which I would like to share it with you all! If you are an intermediate python’s programmer then codewars is where you really need to visit to brush up your python skill. Here is the python problem which takes me a while to solve it.
Given a number, return a string with a dash ‘-‘ marks before and after each odd integer, but do not begin or end the string with a dash mark. If the beginning digit of that number is the odd number then insert a dash mark after it or else if the end digit is the odd number then insert a dash mark in front of it. Only one dash mark is allowed between digits. If the user enters None into that function then return the ‘None’ string. This program also needs to change the negative number to a positive number.
Let say if you enter (-28369) into the function then you will get (28-3-6-9) in return and if you enter (3463) into the function you will get (3-46-3) in return. Before you look at the below solution, create the function by yourself which will return (3-3-3-3-3-3) when you entered this number ( 333333 ) into it.
def dashatize(num): if(num == None): return 'None' # if the user enters a none value the program returns None number_list = list(str(abs(num))) # make sure to turn the number into absolute value number_string = '' for i in range(len(number_list)): # this part will add '-' to the front and the back of odd number if(i==0 or i == ((len(number_list) - 1))): number_string += number_list[i] elif(int(number_list[i]) % 2 != 0): if(int(number_list[i-1]) % 2 != 0 and (i-1) != 0): number_string+= number_list[i] + '-' else: number_string+= '-' + number_list[i] + '-' elif(int(number_list[i+1]) % 2 != 0 and (i+1) == ((len(number_list) - 1))): # if last number is odd '-' is added to it's front number_string += number_list[i] + '-' elif(int(number_list[i-1]) % 2 != 0 and (i-1) == 0): # if the first number is odd '-' is added to the back number_string += '-' + number_list[i] else: number_string += number_list[i] return number_string
Well, hope you have fun with codewars, tomorrow we will visit another website which has the same features as codewars. Lastly, can you solve the above problem by yourself? Let me know your answer in the comment box below!
from Planet Python
via read more
No comments:
Post a Comment