# Check if a string can be repeated to make another string in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have two strings s and t, we have to find how many times the string s can be concatenated to generate t. If we cannot generate t using s, then return -1.

So, if the input is like s = "tom" t = "tomtomtom", then the output will be 3 as we can concatenate "tom" 3 times to get "tomtomtom".

To solve this, we will follow these steps −

• if size of t is not divisible by size of s, then
• return -1
• cnt := quotient of (size of t / size of s)
• s := concatenate s cnt number of times
• if s is same as t, then
• return cnt
• return -1

Let us see the following implementation to get better understanding −

## Example

Live Demo

def solve(s, t):
if(len(t) % len(s) != 0):
return -1;
cnt = int(len(t) / len(s))
s = s * cnt
if(s == t):
return cnt
return -1
s = "tom"
t = "tomtomtom"
print(solve(s, t))

## Input

"tom", "tomtomtom"

## Output

3