
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a String Can Be Repeated to Make Another String in Python
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
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
Advertisements