- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 two-character string can be made using given words in Python
Suppose we have a string s of length 2, and also have a list of words w where all words are of length 2. We have to check whether we can concatenate words from w and that concatenated string contains s as substring or not.
So, if the input is like s = "no", w = ["ol", "on", "ni", "to"], then the output will be True as we can concatenate strings like "onol", that contains "no"
To solve this, we will follow these steps −
- n := the number of words in w
- char_0 := False, char_1 := False
- for i in range 0 to n - 1, do
- if w[i] is same as s, then
- return True
- if s[0] is same as w[i, 1], then
- char_0 := True
- if s[1] is same as w[i, 0], then
- char_1 := True
- if char_0 and char_1 both are true, then
- return True
- if w[i] is same as s, then
- return False
Let us see the following implementation to get better understanding −
Example
def solve(s, w): n = len(w) char_0 = False char_1 = False for i in range(n): if w[i] == s: return True if s[0] == w[i][1]: char_0 = True if s[1] == w[i][0]: char_1 = True if char_0 and char_1: return True return False s = "no" w = ["ol", "on", "ni", "to"] print(solve(s, w))
Input
"no", ["ol", "on", "ni", "to"]
Output
True
Advertisements