Python program to repeat M characters of a string N times
Last Updated :
21 Mar, 2023
In this article, the task is to write a Python program to repeat M characters of string N times.
Method 1:
- Define a function that will take a word, m, and n values as arguments.
- If M is greater than the length of the word. Set m value equal to the length of the word
- Now store the characters needed to be repeated into a string named repeat_string using slicing.
- Initialize an empty string named as a result
- Concatenate the repeat_string to result for n times.
- Now print the string.
Below is the implementation:
Python3
def repeat(word, m, n):
if (m > len (word)):
m = len (word)
repeat_word = word[:m]
result = ""
for i in range (n):
result = result + repeat_word
print (result)
repeat( "geeks" , 2 , 3 )
|
Output:
gegege
Time Complexity : O(n)
Auxiliary Space : O(n)
Method 2:
- Define a function that will take a word, m, n values as arguments.
- if M is greater than length of word. set m value equal to the length of word.
- Now store the characters needed to be repeated into a string named repeat_string using slicing.
- Multiply the repeat_string with n.
- Now print the string.
Python3
def repeat(word, m, n):
if (m > len (word)):
m = len (word)
repeat_word = word[:m]
print (repeat_word * n)
repeat( "geeks" , 2 , 3 )
|
Output:
gegege
The time and space complexity for both methods are the same:
Time Complexity : O(n)
Auxiliary Space : O(n)
Method 3: Using itertools
Here’s another method that can be used to repeat M characters of a string N times using the itertools module in Python:
Python3
import itertools
def repeat(word, m, n):
if m > len (word):
m = len (word)
repeat_word = word[:m]
result = "".join(itertools.islice(itertools.repeat(repeat_word), n))
print (result)
repeat( "geeks" , 2 , 3 )
|
Time Complexity : O(n)
Auxiliary Space : O(n)
Method 4: Using operator.mul()+slicing
Approach
- Define a function that will take a word, m, n values as arguments.
- if M is greater than length of word. set m value equal to length of word.
- Now store the characters needed to be repeated into a string named repeat_string using slicing.
- Multiply the repeat_string with n.(using operator.mul())
- Now print the string.
Python3
def repeat(word, m, n):
if (m > len (word)):
m = len (word)
repeat_word = word[:m]
import operator
print (operator.mul(repeat_word,n))
repeat( "geeks" , 2 , 3 )
|
The time and space complexity for both methods is the same:
Time Complexity : O(n)
Auxiliary Space : O(n)
Share your thoughts in the comments
Please Login to comment...