While I tried to execute the following code, I faced some problem in loop iterations and couldn't figure out what's the problem might be.
def string_splosion(s):
"""Takes a non-empty string s like "Code" and
returns a string like "CCoCodCode"
"""
for i in range(len(s)):
return s[i] * (i+1)
print(string_splosion('Code'))
you leave the function after the first return. I think this would be the right solution
def string_splosion(s):
result = ''
for i in range(len(s)):
result += s[:i]
result += s
return result
if you have return inside in a loop the loop is raning only for one time.
def string_splosion(s):
"""Takes a non-empty string s like "Code" and
returns a string like "CCoCodCode"
"""
a='' ## empty String
for i in range(len(s)):
a += s[0:i] +s[i] ## this is beter way to do this "CCoCodCode"
return a ## out of the "for" loop
print(string_splosion('Code'))
Try something like:
def string_splosion(s):
return ''.join(s[:i+1] for i in range(len(s)))
print(string_splosion('Code'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.