1

: Write a function, named foldStrings(string1, string2) that takes, as arguments, two strings. If
the two strings are equal in length, the function returns a string that is formed by alternating characters in each of the two strings. If the two strings are not equal in length, the function returns the string “The two strings are not equal in length.”

For example, >>>foldStrings(“abc”, “def”)
should return the string “adbecf” and >>>foldStrings(“a”, “bc”)
should return the string “The two strings are not equal in length.”

This is what I have so far:

def foldStrings(str1, str2):
newStr = ""
counter = 0
if len(str2) == len(str1):
    while counter < len(str2):
        for element in str1:
            for index in str2:
                newStr = newStr + element
                newStr = newStr + index
                counter += 1
    return newStr
else:
    return "The two Strings are not equal in length"

and it prints this: 's1s2s3s4s5s6a1a2a3a4a5a6n1n2n3n4n5n6t1t2t3t4t5t6o1o2o3o4o5o6s1s2s3s4s5s6' instead of this: 's1a2n3t4o5s6'

4
  • Right now, for every element in str1 it looks at all elements in str2. You only want it to look at the next element of str2. You only need 1 for loop over str1, not 2 loops over str1 and str2, because str1 and str2 are the same length. Commented Nov 16, 2017 at 21:52
  • exactly, and I'm not sure what to change as I've tried to change the placement. I've also tried to change the strings to a list but I was unable to do so without fully understanding how to iterate through strings as I need to be able to. Commented Nov 16, 2017 at 21:54
  • by the way this is just a practice assignment question in my intro to comp course. I'm reviewing simple things but for some reasons I get stuck on how to fix them. Commented Nov 16, 2017 at 21:55
  • @C.Helling error. sorry.... Commented Nov 16, 2017 at 22:26

3 Answers 3

1

You have unnecessarily complicated the problem with three nested loops, when a single loop is required.

Replace:

while counter < len(str2):
    for element in str1:
        for index in str2:
            newStr = newStr + element
            newStr = newStr + index
            counter += 1
return newStr

With:

for index in range(len(str1)) :
    newStr = newStr + str1[index] + str2[index]

return newStr

In the original code, if the string length was for example 6, your code says:

 Repeat 6 times:
     for every character in str1
         for every character in str1
             do stuff

so that do stuff is executed 6 x 6 x 6 times! You only want to execute it 6 times suggesting a single loop.

What you were doing wrong was not a python specific issue, but rather an issue with your algorithmic and logical thinking. Mathematically the problem suggests a single iteration, while you had three - nested. In this case you might have manually walked through the code or used a debugger to step through it to demonstrate flaw in thinking here.

Sign up to request clarification or add additional context in comments.

3 Comments

I appreciate the cleaner version. Patrick has also provided similar a similar fix. If you wouldn't mind though, could you aid in helping fix my code in the structure that I was going for? As stated in another comment, I write these down on paper first and logically work it out and this seemed to work out mathematically but didn't translate well into the python language. If you can't come up with a fix to my code in the structure that is ok, now I'm just curious. Best, Santos
@srxprime13 : I have extended the answer, it is not that this is a "cleaner" solution; it is a mathematically consistent solution. Creating a solution of complexity O(n-cubed) for an intrinsically O(n) problem makes no sense. Your attempt makes little sense and cannot be adapted to work; it was just incorrect.
I really appreciate your candor and response. It helps a lot and answers literally weeks and weeks of problems I encountered with my algorithms I've been practicing with. I struggle with complexity in the algorithms and I will study up more about discerning between what's asked and what my mind is thinking lol!
0

You can skip using a counter variable by using range

def foldStrings(str1, str2):
    if len(str1) != len(str2):
        return "The two Strings are not equal in length" 
        # This should really be a raise ValueError("The two Strings are not equal in length")
    newStr = ''
    for i in range(len(str1)):
        newStr += str1[i] + str2[i]
    return newStr

Here's a slightly more compact way to replace the for loop

newStr = ''.join([x for pair in zip(str1, str2) for x in pair])

3 Comments

the for loop you've rewritten is a great replacement and cleaner...I just wonder what I was doing wrong and how I could fix my code in the way I was writing the structure. (When I tackle these small algorithms in my course, I write everything down first. Logically this worked in my head, but it didn't translate well into the Python programming language.)
@srxprime13 Let's say you have two lists l1 with m elements and l2 with n elements. If you do for i in l1: for j in l2: print(), you're going to end up with a total of n*m prints. This is because for each of the m elements in l1, you're going to do n prints. That's why the result you were getting cycles through all the characters of your second string before switching the character from your first string.
ahh, that makes sense now. I'm sorry you guys had to explain at such a basic level for me, but it helped! :) thanks again!
0
#Simple way to do it 
def foldStrings(str1, str2):
    newStr = ""
    counter = 0
    if len(str2) == len(str1):
        while counter < len(str2):
            newStr = newStr + str1[counter] + str2[counter]
            counter += 1
        return newStr
    else:
        return "The two Strings are not equal in length"

2 Comments

The existing answers are already even simpler, and the OP has commented on both that what he is really looking for is an explanation of his flawed thinking rather then just a solution to the problem.
@Pratik Patil : Thanks Pratik, but as Clifford stated above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.