Shahzaib Shuz Bari
Shahzaib Shuz Bari

Reputation: 75

How can I get an alphabetic input to match another alphabetic input in length?

I need to get a user-input keyword to be the same length as a user-input message, for example:

keyword = "gcse"  # the keyword input
message = "python" # the message input
newkeywordshouldbe = "gcsegc"

This seems simple, but I have been unable to figure out how to accomplish it. Ideas?

Upvotes: 1

Views: 98

Answers (4)

sathyz
sathyz

Reputation: 1441

Use the modulo operation (%) and array indexing.

keyword = 'gcse'
message = 'python'
n, m = len(keyword), len(message)
print ''.join( [ keyword[ i % n ]  for i in range(m) ] )

The following interactive Python session (with keyword, message, n, and m already declared and initialized) explains:

>>> range(m)
[0, 1, 2, 3, 4, 5]
>>> [i % n for i in range(m)]
[0, 1, 2, 3, 0, 1]
>>> [keyword[i % n] for i in range(m)]
['g', 's', 'c', 'e', 'g', 's']

Upvotes: 1

acushner
acushner

Reputation: 9946

another way to approach it is:

import math
new_word = (math.ceil(len(message) / len(keyword)) * keyword)[:len(message)]

Upvotes: 0

J0e3gan
J0e3gan

Reputation: 8938

Try the following:

keyword = "gcse"
message = "python"
newkeywordshouldbe = "gcsegc"

keywordLen = len(keyword)
messageLen = len(message)

if keywordLen == messageLen:
    newkeyword = keyword
elif keywordLen > messageLen:
    newkeyword = keyword[:messageLen]
elif keywordLen < messageLen:
    # Use keyword in its entirety as many times as possible to match
    # message's length; then match the rest of message's length with
    # as many of keyword's characters as needed.
    newkeyword = ''.join(keyword * (messageLen / keywordLen)) + \
        keyword[:messageLen - keywordLen]

print newkeyword

You can run the code above in a related Ideone demo.

Also, you could squeeze more from less and make the solution more Pythonic (e.g. like mpcabd's); but this super clearly conveys the logic given the three logical possibilities:

  • keyword and message are the same length.
  • keyword is shorter than message.
  • keyword is longer than message.

Even employing a more Pythonic solution, it is important to understand the underlying logic of course.

Upvotes: 0

mpcabd
mpcabd

Reputation: 1807

Another solution would be to use the cycle function like this:

from itertools import cycle

keyword = "gcse"
message = "python"
iterator = cycle(keyword)

newkeywordshouldbe = ''.join(iterator.next() for i in range(len(message)))

Upvotes: 2

Related Questions