-3

Here's my code so far.

def encryptMessage():
msg = "I came, I saw, I conquered"
i = 0
numChar = len(msg)
while i < numChar:
  print msg[i:i+5]
  i=i+5

It returns this;

I cam
e, I 
saw, 
I con
quere
d

The next part is having the program print the first letter in each line, then the second, then the third and so on. That should look something like this.

"IesIqd ,a u c wce aI,or m ne"

I honestly can't think of a way to do this. Any help would be appreciated.

jjaderberg
  • 9,844
  • 34
  • 34

3 Answers3

1

I imagine the point of this exercise is to teach you about the "stride" (aka step) option when slicing.

msg = 'I came, I saw, I conquered'

msg[::5]
Out[22]: 'IesIqd'

msg[1::5]
Out[23]: ' ,a u'

More explanation of the syntax here. I'll leave the rest to you.

Community
  • 1
  • 1
roippi
  • 25,533
  • 4
  • 48
  • 73
  • @JackVanoudenaren I did not provide you with "code", I provided you with a tool to solve your problem. There is no issue with the above, I assure you. – roippi Oct 17 '13 at 05:25
0
>>> from itertools import izip_longest
>>> ciphermap = izip_longest(*[msg[i:i+5] for i in range(0,len(msg),5)],fillvalue="")
>>> encoded = "".join(["".join(x) for x in ciphermap])
>>> print encoded
IesIqd ,a uc wceaI,orm  ne

I think would work

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
-1
def encryptMessage():
    result = []
    msg = "I came, I saw, I conquered"
    result = "".join([msg[k::5] for k in range(5)])

You will get output -:

"IesIqd ,a u c wce aI,or m ne"

You don't need to import any packages, Just do it simple.

Nilesh
  • 2,407
  • 1
  • 12
  • 20
  • Why explicitly force float division by using 5.0 instead of 5 only to truncate with `int` immediately? – abarnert Oct 16 '13 at 05:57
  • In fact, what are you even calculating that for in the first place? You want `range(5)` here; it only happens to work because 25<=len<30. – abarnert Oct 16 '13 at 05:59
  • Also, if you run this code, you don't get that output, you get extra spaces in the middle, because you used " ".join instead of "".join. – abarnert Oct 16 '13 at 06:01
  • First, it's almost never true in Python that one line is faster than two. Python doesn't interpret a line at a time like AppleSoft BASIC. Second, the performance here is unlikely to ever matter. But most importantly, if you care about performance, doing a float division and then truncating to int will always be slower than just doing an int division. No code at all is always fastest. – abarnert Oct 16 '13 at 06:17
  • It still only works for messages that are 25-30 characters long, and it still has the extra spaces. And the function returns `None`. Why don't you actually run your code instead of guessing at the output? – abarnert Oct 16 '13 at 18:02
  • I made correction in my code. Now code is more sophisticated than previous. – Nilesh Oct 17 '13 at 04:30