using for loop in python to convert two strings into one string -
for example:
mangle('hello','people')->'hpeelolpole'
it meant combine these 2 strings, character character. function:
def mangle(s1,s2): s1=list(s1) s2=list(s2) a=" " in range(0,min(len(s1),len(s2))): c in s1: d in s2: a=a+c+d if len(s1)>len(s2): return a+''.join(s1)[min(len(s1),len(s2)): ] elif len(s1)<len(s2): return a+''.join(s2)[min(len(s1),len(s2)): ] else: return but produces:
hphehohphlhee i know problem is:
for c in s1: for d in s2: a=a+c+d but don't know how fix it
you correct. don't need iterate on both strings. can this:
def mangle(s1, s2): = "" in range(min(len(s1), len(s2))): += s1[i] + s2[i] if len(s1) > len(s2): return + s1[min(len(s1), len(s2)):] elif len(s1) < len(s2): return + s2[min(len(s1), len(s2)):] return assert(mangle('hello','people') == "hpeelolpole") this program can written itertools.izip_longest this:
try: itertools import izip_longest zip # python 2 except importerror: itertools import zip_longest zip # python 3 def mangle(s1, s2): return "".join(c1 + c2 c1, c2 in zip(s1, s2, fillvalue='')) assert(mangle('hello','people') == "hpeelolpole")
Comments
Post a Comment