user11620448
user11620448

Reputation:

How do I iterate over a loop in a circular fashion?

I am trying to encrypt a given number by adding each of its digits with a key number. For example: Suppose the number is 34621 and the key is 9, so the encrypted number will be 13462 (i.e., for the first digit 3 add its index with the key number which will be 9, and thus make 0+9 iterations over all the digits and and replace that digit with the digit in [0+9]th index, and so on).

But for this, I have to iterate over the number multiple times, and I don't know how to do that. Can someone please help me?

My code:

n=input()
k=input()
for i in range(len(n)):
   if(n[i]+int(k)<n[len(n)-1]):
       #don't know how to proceed

Upvotes: 0

Views: 93

Answers (4)

Moshe perez
Moshe perez

Reputation: 1726

The algorithm you are describing is basically shifting the string to the right by k%len(n).

You can achieve this with one line of code:

n = input()
k = int(input())

print(int(n[k % len(n):] + n[:k % len(n)]))

Upvotes: 0

sahasrara62
sahasrara62

Reputation: 11238

for this purpose % operator will help you.

all you need is index in the list when you add the list index with the key value and then get value from the list for the new index.

see example for 0+9 -> new index 9, once you iterate over it you will get that the value associates with it will be on index 4 on orignal list which is (0+9)%le(length of list)

n = int(input()) # 34621
k = int(input()) # 9


l = [int(i) for i in str(n)]

l2=[0 for i in range(len(l))]
for i in range(len(l)):
    l2[i] = l[(i+k)%len(l)]

new_num =int(''.join([str(i) for i in l2]))

print(new_num)

output

13462

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With itertools.cycle and itertools.islice magic:

from itertools import cycle, islice

def enc_shuffle(num, rotate_step=9):
    """Encrypt number (given as string) by rotating step"""
    res = ''
    for i, _ in enumerate(num):
        gen = cycle(num)         # iterator that repeats infinitely
        step = i + rotate_step   # slicing offset
        _, val = islice(gen, 0, step + 1, step)
        res += val
    return res

print(enc_shuffle('34621'))   # 13462

Upvotes: 0

DustyPosa
DustyPosa

Reputation: 463

how about this way that don't use cycle in code. only by string concatenation can get the answer.

n = input()
k = int(input())
number_length = len(n)
real_move = k % number_length
res = int(n[real_move:] + n[:real_move])
print(res)

Upvotes: 1

Related Questions