Split Word function- bothersome
the objective is as follows:
Write a function splitWord(word, numOfChar) that takes in a word and a number as arguments. The function will split the word into smaller segments with each segment containing the number of letter specified in the numOfChar argument. These segments are stored and returned in a list.
Examples
>>> splitWord('google', 2)
['go', 'og', 'le']
>>> splitWord('google', 3)
['goo', 'gle']
>>> splitWord('apple', 1)
['a', 'p', 'p', 'l', 'e']
>>> splitWord('apple', 4)
['appl', 'e']
I spent ages messing around try to find ways, eventually i got it working and started testing it, however, for some reason it doesn't accept duplicate values?!
def splitWord(word, numOfChar):
r = []
h = len(word)/numOfChar
while True:
if len(word) == 0:
break
else:
r.append(word[0:numOfChar:1])
word = word.replace(word[0:numOfChar:1], '')
return r
Help would be appreciated, after spending so much time up all night trying to learn and getting stuck on this...
Anyway, thanks for any help.
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
def splitWord(word, length):
r = []
for count in range(0, len(word), length):
r.append(word[count:count+length])
return r
Your capitalization is idiosyncratic (probably due the site not following the PEP8
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
def splitWord(word, numOfChar):
r = []
for count in range(0, len(word), numOfChar):
r.append(word[count:count+numOfChar])
return r
Your capitalization is idiosyncratic (probably due the site not following the PEP8
Thanks for the help! i wish i could have thought that up. Im too now anyway, i have been trying to learn for the past 16 hours or so.
Could you explain exactly how your code works?
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
Advance counter in length steps and take length long pieces from that index forward, stop when counter is equal or greater than length of word to split. The appending to result bit you did yourself already.
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
You use "replace" so it replaces all text that is equal (duplicates), when you should slice off the word.
def split_word(word, numOfChar):
r = []
# h = len(word)/numOfChar ## not used
while True:
if len(word) == 0:
return r
else:
r.append(word[0:numOfChar])
word = word[numOfChar:] ## changed
return r
print split_word("Asentencewithduplicateduplicatewords", 5)
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
Thanks for the help everyone, much appreciated.
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0