
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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
- Related Articles
- Check if a string can be formed from another string using given constraints in Python
- Program to check a string can be broken into given list of words or not in python
- Check if given string can be split into four distinct strings in Python
- Check if a given string is made up of two alternating characters in C++
- Check if given string can be formed by concatenating string elements of list in Python
- Check if elements of array can be made equal by multiplying given prime numbers in Python
- Program to check words can be found in matrix character board or not in Python
- Check if characters of a given string can be rearranged to form a palindrome in Python
- Check if a string can be repeated to make another string in Python
- Checking if a string can be made palindrome in JavaScript
- Check whether given string can be generated after concatenating given strings in Python
- Check if the array can be sorted using swaps between given indices only in Python
- Check if a string can be obtained by rotating another string 2 places in Python
- Check if a string can become empty by recursively deleting a given sub-string in Python
- How to check if a string can be converted to float in Python?

Advertisements