[Tutor] help find out error

Alan Gauld alan.gauld at yahoo.co.uk
Mon Apr 17 10:37:23 EDT 2023


On 17/04/2023 11:23, Iven Eret wrote:

It would hep if you tell us what the problem is.
If you get any error messages include them in your email.
Meantime I include a few comments below...

>    def  decrypt(encrypted_text:str, n:int):
>        if  n<=0:
>            return  encrypted_text
>        if  len(encrypted_text)%2:
>            encrypted_text += "_"
>        even = encrypted_text[:int(len(encrypted_text)/2) + 1] #including last
>        odd= encrypted_text[int(len(encrypted_text)/2):]#not including last
>        text= ""
>        shorter_length = min(len(even), len(odd))
> 
>        j=0
>        while  j<n:
>            for  i  in  range(shorter_length):
>                text=text + odd[i] + even[i]
>            print(text)  
>            j+=1    

Note that this only prints the string. it would be more
helpful if you returned it so that it could be stored
somewhere.
As a general programming rule we try to avoid having functions
print results, it's much better to return them.

>    def  encrypt(text:str, n:int):
>        if  n<=0:
>            return  text
>        j=0
>        while  j<n:
>            odd= ''
>            even= ''    
>            for  i  in  range(0, len(text)):
>                if  i%2:
>                    odd+=text[i]
>                else :
>                    even+=text[i]
>            text= odd + even
>            j+=1

You can do this in a single line using slicing.

text = text[::2] + text[1::2]

Also since you are always starting at zero and incrementing
by 1 you don't need the while loop. You can use

for _ in range(n):
  for i in range(len(text)):
    text = text[::2] + text[1::2]

For loops tend to be more reliable than using while
loops - no index to maintain.

>        return  text

Interestingly you do return the text in this case.

>    the goal was to encrypt to mplement a pseudo-encryption algorithm which
>    given a string S and an integer N concatenates all the odd-indexed
>    characters of S with all the even-indexed characters of S, this process
>    should be repeated N times.
> 
>    Examples:
> 
>  encrypt("012345", 1)  =>  "135024"
>  encrypt("012345", 2)  =>  "135024"  ->  "304152"
>  encrypt("012345", 3)  =>  "135024"  ->  "304152"  ->  "012345"



>    Help me find out where I’m going wrong

I can't see any obvious bugs but if you are getting an error either
send the error message or if its a data error show us the input and
output that you get. It saves us guessing and potentially solving
the wrong problem.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos





More information about the Tutor mailing list