Incrementing Slice in Python?

chopnhack

Apr 28, 2014
1,576
Joined
Apr 28, 2014
Messages
1,576
Hello again, I need assistance on a question - no spoilers, just a direction if you will:

I thought I could increment a slice function --> s1[i+1] but Python doesn't allow that operation.
Code:
def laceStrings(s1, s2):
"""

s1 and s2 are strings.



Returns a new str with elements of s1 and s2 interlaced,

beginning with s1. If strings are not of same length,

then the extra elements should appear at the end.

"""

length=max(len(s1),len(s2))

i=0

last=0



if len(s1)>len(s2):

     last = s1[-1]

     length-=1

elif len(s2)>len(s1):

     last = s2[-1]

     length-=1

else:

     length=length



while length >0:

     print s1[i]+s2[i]

     length-=1

     i+=1

if len(s1)>len(s2):

    print s1[-1]

elif len(s2)>len(s1):

    print s2[-1]

else:

    return



s1='abcd'

s2='efg'

laceStrings(s1,s2)

the output is :
ae
bf
cg
d

How can I get that all on one line? Am I approaching this problem incorrectly?
Thanks in advance.
 

Merlin3189

Aug 4, 2011
250
Joined
Aug 4, 2011
Messages
250
Yes, I think you are approaching it wrongly. You are not creating a new string, simply printing out the elements of that new string. (Though having looked at the Python documentation, it may be that you do create a string when you use print, but it is not accessible to the rest of the program.)

Now if that were all you wanted to do, you need to look at something like this
http://stackoverflow.com/questions/11266068/python-avoid-new-line-with-print-command

But if you really want to obtain a new string for further processing, then you need to make a new string! :)
while length >0:
print s1{i}+s2{i}
length-=1
i+=1

So instead of "print s1{i}+s2{i}"
you need something like " newstr = newstr + s1{i} + s2{i} "
which will create a new string by concatenating the previous newstr with the next two letters.
and eventually you can print newstr , if that is what you want to do, or you can use it to do something useful with. NB I am using {} because the sq brackets are not displaying.

Now, I don't know one end of Python from the other, just basing this on what applies in most programming languages and the Python documentation I've just looked at. Amazingly (to me) I haven't been able to find a single example where a string variable is assigned a simple concatenation of other string variables, but it does seem to be allowed by the syntax of Python.

I hope this is not too much help. I suspect all he really wants is the bit I just gave a link for.
If he really needed what he asked, then I haven't completed the code, just showed what sort of thing is needed. I think this degree of help is justified - it is similar to the documentation eg.s in Python.org etc.
As a fairly experienced programmer (though totally ignorant of Python) I have spent a couple of hours reading Python.org and other online tutorials and failed to find any clear description of this issue. I think OP would need at least this amount of help.
 
Last edited:

chopnhack

Apr 28, 2014
1,576
Joined
Apr 28, 2014
Messages
1,576
I think OP would need at least this amount of help.

Thank you Merlin! I need more than that!! LOL
Creating the new string and being able to concantenate back to it worked beautifully. The problem became apparent when I only accounted for two scenarios: base test case of both strings equal in length and then, either string being 1 character longer. The question threw me a curve when the strings became of variable lengths.

I now need to construct some code to:
  1. Compare length of each string.
  2. Longer string gets sliced first
  3. When shorter string ends, the balance of the longer string needs to be sliced
Does this sound like a logical approach to the problem? I intend to use len() to get length of the strings, max() to determine the larger of the two, variable to be counted down on the smaller string with conditional of when it reaches zero, to slice balance of longer string.

Easier said than done! :eek::D
 

chopnhack

Apr 28, 2014
1,576
Joined
Apr 28, 2014
Messages
1,576
Ok, I got it - its ugly but functional and satisfied the various cases thrown at it via the automatic checker.

Code:
     def laceStrings(s1, s2):
     """
     s1 and s2 are strings.
     Returns a new str with elements of s1 and s2 interlaced, 
     beginning with s1. If strings are not of same length,
     then the extra elements should appear at the end.
     """

     i=0
     it=0
     length=0
     strng=''

     if s1==s2 and len(s1)==0 and len(s2)==0 :
          return ''

     if len(s1)>len(s2):
          length=len(s2)
     while length>0:
          strng=strng+s1[i]+s2[it]
          length-=1
          i+=1
          it+=1
          strng=strng+s1[i:]



     if len(s1)<len(s2):
          length=len(s1)
     while length>0:
          strng=strng+s1[i]+s2[it]
          length-=1
          i+=1
          it+=1
          strng=strng+s2[i:]



     if len(s1)==len(s2) and len(s1)>0 and len(s2)>0:
          length=len(s1)
     while length>0:
          strng=strng+s1[i]+s2[it]
          length-=1
          i+=1
          it+=1




     return strng



s1='aaa'
s2='vvv'
laceStrings(s1,s2)

If you try to test this, replace 'return' with 'print'
 

Merlin3189

Aug 4, 2011
250
Joined
Aug 4, 2011
Messages
250
Have you tested it?
I haven't, but I don't think it should work when s1 is shorter than s2.
if len(s1)>len(s2):
length=len(s2)
while length>0:
strng=strng+s1+s2[it]
length-=1
i+=1
it+=1
strng=strng+s1[i:]
Is there an indentation error here? Isn't the 'while' loop to be executed only if the "if" is true? If so, the other while loop is also wrong.

Apart from that, it looks as if it should work. There are some stylistic inefficiencies, like
using i and it when both always seem to have the same value.

using 3 tests for 2 conditions (if both are "" then they must be the same)
if s1==s2 and len(s1)==0 and len(s2)==0 :
return ''

Both are ok and work correctly, just a bit unnecessary.


On another tack, I was on another thread about recursion recently. It struck me that recursion would be a good method here. I didn't mention it at first, because I didn't know whether you would be familiar with the idea. But then I noticed you were the OP on that thread as well! So when you've sorted out this method to your satisfaction, maybe you could think about doing it by recursion? I tried it and did it in 7 lines as long as you don't care which order the strings are used. (Unfortunately it nearly doubled the length when I tried to put that in quickly!)
I'll have another look when I've got time. But I'm still struggling to understand working with the Python interpreter. I have to type in the whole program every time, because I can't find any way of editing what I've already put in. (Which is why I haven't tested your program: copy & paste ruins the indents, but retyping guaruntees errors!)
 

chopnhack

Apr 28, 2014
1,576
Joined
Apr 28, 2014
Messages
1,576
Have you tested it?
I haven't, but I don't think it should work when s1 is shorter than s2.

Hi Merlin, I really hate how the site software kills the white space! This picture should help abit. The code did indeed work, even when s1 was shorter than s2 - it was handled by line 26. I separated the incrementing of s1 and s2 to two different variables 'i' and 'it' because they would vary with the lengths of the their respective strings.

upload_2015-2-10_14-41-19.png


On another tack, I was on another thread about recursion recently. It struck me that recursion would be a good method here. I didn't mention it at first, because I didn't know whether you would be familiar with the idea. But then I noticed you were the OP on that thread as well! So when you've sorted out this method to your satisfaction, maybe you could think about doing it by recursion? I tried it and did it in 7 lines as long as you don't care which order the strings are used. (Unfortunately it nearly doubled the length when I tried to put that in quickly!)
I'll have another look when I've got time. But I'm still struggling to understand working with the Python interpreter. I have to type in the whole program every time, because I can't find any way of editing what I've already put in. (Which is why I haven't tested your program: copy & paste ruins the indents, but retyping guaruntees errors!)

Yes, the recursive method would be much cleaner. I don't think I have quite got the ability to code with it yet. I understand the theory, just not the application yet. If you want a free Python IDE - this is the one I have been using. Thanks for the input again :)
 

Merlin3189

Aug 4, 2011
250
Joined
Aug 4, 2011
Messages
250
Right. Now I have it with correct indentation, I've run it myself and it's ok.

Thanks for the link. I'll try it.
I've been thinking about doing a bit of coding for fun, but had no particular ideas to try. Your questions have at least got me to fire up an interpreter and have a go again. I hadn't written any code for several years.
Python hasn't really grabbed me yet, but new languages never seem as comfortable as ones you're used to. It takes a while to work out how to go with the grain. It's very nice to be working with an interactive interpreter again. It makes learning easier, just being able to try out little snippets without writing a whole lot of setup. It looks as if it may have some interesting libraries and be able to do the sort of things that interest me.
 

chopnhack

Apr 28, 2014
1,576
Joined
Apr 28, 2014
Messages
1,576
Right. Now I have it with correct indentation, I've run it myself and it's ok.

Thanks for the link. I'll try it.
I've been thinking about doing a bit of coding for fun, but had no particular ideas to try. Your questions have at least got me to fire up an interpreter and have a go again. I hadn't written any code for several years.
Python hasn't really grabbed me yet, but new languages never seem as comfortable as ones you're used to. It takes a while to work out how to go with the grain. It's very nice to be working with an interactive interpreter again. It makes learning easier, just being able to try out little snippets without writing a whole lot of setup. It looks as if it may have some interesting libraries and be able to do the sort of things that interest me.
Cool, I am glad that it has brought interest to you. I think its a great language. When I first started the course, I thought there were some similarities with C, but Python seems more advanced and intuitive than C ever was. I feel this way because of the method by which it processes code - its interpretive vs compiled, so its easier on the coder at first, not having to remember which libs to call, etc.
 
Top