1

Say I have a binary number message of 0100110101100101 and a binary key of 001.

How can I repeat the key to be the same length as the message? As in take the length of the message and then repeat the pattern of the key till the length of the message is reached?

In the example the output should be 0010010010010010

Thanks.

1 Answer 1

1

You can use python's list slicing:

In [1599]: a = '0100110101100101'
In [1602]: key = '001'

In [1608]: factor = len(a) // len(key)
In [1606]: remainder = len(a) % len(key)

In [1625]: if factor == 0:
      ...:     print("pattern greater than the string")
      ...: else:
      ...:     answer = (key * factor) + key[:remainder]
      ...: 

In [1614]: answer
Out[1614]: '0010010010010010'
Sign up to request clarification or add additional context in comments.

2 Comments

Mayank, this solution prints the string even when the pattern is smaller than the string. Maybe it will be good to add a condition if needed by @Sulhan!
@Ananth Updated my solution to handle key is greater than message case. Thanks.

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.