I receive a String. For example in here I have :
Mystring= ‘alohrefllluqoo’
I can see all the letter of 'Hello' word, in the correct sequence, in Mystring string
is it possible to use Booleans?
in that string the final output would be 'YES', cause when I remove extra letter I can see the 'Hello' word (in correct sequence) in string.
and if the sequence is not correct and the word can not be found, the output will be 'NO'
This is one approach.
Ex:
Mystring= 'alohrefllluqoo'
to_find = "hello"
def check_string(Mystring, to_find):
c = 0
for i in Mystring:
if i == to_find[c]:
c += 1
if c == len(to_find):
return "YES"
return "NO"
print(check_string(Mystring, to_find))
You can use something like this:
mystring = 'alohreflllouq'
wordtofind = "hello"
i=0
word=''
for char in mystring:
if char == wordtofind[i]:
word = word + char
i+= 1
if word == wordtofind:
break
result = "YES" if word == wordtofind else "NO"
print(result)
making a function, and passing your string, and the thing you search for:
def IsItHere(some_string, sub_string)
try:
some_string.index(sub_string)
return 'YES'
except:
return 'NO'
Related
a = input()
b = input()
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
else:
if (len(match) > len(answer)): answer = match
match = ""
if answer == '':
return 'No overlapping'
else:
return answer
print(longestSubstringFinder(a, b))
in the above code, not getting the expected outcome for the input
correct
wrong
My output: e
expected output: No overlapping
Some issues:
the else block should not allow the inner loop to continue: when you have a mismatch, you should not try matches with higher values of j, but you should exit that loop and try with the next value for i. So there needs to be a break in the else block
the condition len(match) > len(answer) is not enough to identify a solution. The reason for getting into the else block might have been that the characters didn't match, so in that case you should never update answer.
On the other hand, the update of answer is not happening now when the inner loop ends normally, i.e. when all compared characters were equal and i + j < len1 was always true. This case happens when the second input string is a suffix of the first. So you must make the update to answer somewhere else, so you also catch this case.
Here is the correction to your code, dealing with these issues:
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
# Move the assignment to answer here, and add condition that
# this was the last character of string1:
if i + j == len1 - 1 and len(match) > len(answer): answer = match
else:
break # Necessary!
if answer == '':
return 'No overlapping'
else:
return answer
With the use of string slicing, and comparing those slices instead of individual characters, you can make your code shorter and run faster.
Using RegEX, you can do it with lesser lines of code. I'm assuming you're a beginner in Python. If you are, then please learn RegEx and List Comprehension for this type of code.
import re
str1, str2 = input(), input()
def longestSubstringFinder(string1, string2):
list_of_subsets = [str1.replace(str1[:i], '') for i in range(len(str1))]
intersect = [re.search('^'+slc, str2).group() for slc in list_of_subsets if re.search('^'+slc, str2)]
if len(intersect) == 0:
return 'No overlapping'
else:
return intersect[0]
print(longestSubstringFinder(str1, str2))
a = str(input())
b = str(input())
g=len(a)-1
prefix = "No overlapping"
for i in range(len(a)):
if a[(g-i):] == b[:i+1]:
prefix = b[:i+1]
print(prefix)
I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?
VOWELS = ('a','e','i','o','u','A','E','I','O','U')
ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel
def is_vowel(c):
return c in VOWELS
def mod3(ad):
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
print(modAd)
mod3(ad)
my output for this code:
Otherwise, when I modify my code to look like this:
But my output is:
I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?
You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.
def mod3(ad):
result = ""
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
result += modAd + " "
print(result)
Second option: This is my take on it:
def mod4(ad):
result = ""
testAd =ad.split()
for word in testAd:
for i, char in enumerate(word):
if i == 0:
result += char
if i > 0 and char not in VOWELS:
result += char
result += " "
print(result)
program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t'
here's my code
def change(string):
string_len = len(string)
t = string[0]
for each in range(1, string_len):
if each is t:
each == '$'
else:
continue
return string
print(change("restart"))
output
restart
i'using Pycharm. Line no 6 (each == '$')says this statement has no effect. i don't want to use replace method. just want to know what is the problem.
Your code commented:
def change(string):
string_len = len(string)
t = string[0]
for each in range(1, string_len):
if each is t: # To compara strings you should use the == operator not the 'is' operator.
each == '$' # This will not have any effect because is a temporal variable visible just inside the 'for' loop and you are not using it.
else:
continue
return string
print(change("restart"))
A solution could be:
def change(s):
result = ''
for character in s:
result += '$' if character == s[0] else character
return result
print(change('restart'))
Python strings are immutable objects, so you can't do 'aaa'[1] = 'b' to get aba.
each is set to an integer and you are comparing it to a string.
My teacher wants me to use a reverse loop instead of the reverse function I am using right now. I can't seem to get one that works.
def palindrome():
myInput = input("Enter a Word: ")
word = myInput[::-1]
if myInput == word:
print("That is a palindrome")
return True
else:
print("That is not a palindrome")
return False
palindrome()
def palindrome():
string = input("Enter a Word: ")
for i,char in enumerate(string):
if char != string[-i-1]:
return False
return True
Edited for below comment:
the enumerate() function adds a counter to an iterable.
>>> string = "PARAM"
>>> for count, elem in enumerate(string):
... print count, elem
...
0 P
1 A
2 R
3 A
4 M
so line if char != string[-i-1] will try to match one character from front and one character from end.
You could try the code below, but I really recommend you to try it yourself first. (Because, if you're able to write a recursive call, you should be able to write an iterative one yourself too.)
def reverse(text):
rev = ""
final = ""
for a in range(0,len(text)):
rev = text[len(text)-a-1]
final = final + rev
return final
Problem
How can I stop the loop from asking "Input string" again without using break? Thanks.
Code
# Remove Break
def main():
inp = 0
while inp <= 0:
inp = int(input("Enter Number: "))
if inp > 0:
string = ""
while string != "you" or string != "me":
string = input("Input string: ")
if string == "you":
stringYou(inp)
break
elif string == "me":
stringMe(inp)
break
def stringYou(inp):
sentence = "I love You"
print(sentence * inp)
def stringMe(inp):
sentence = "You love Me"
print(sentence * inp)
main()
while string != "you" or string != "me":
The condition here is a tautology meaning it will always be true.
There are three interesting cases for your variable string here:
string is equal to "you". The first condition string != "you" is obviously false. The second however isn’t: string != "me". string is "you" which is not equal to "me". So false or true gives you true.
string is equal to "me". With the same reasoning, except in the opposite order, we get true or false which is also true.
string is something else. Both the subconditions are true, so true or true gives true.
So the condition is always true, and the while condition never stops on its own. So you have to break in order to get out of it.
The fix is to simply fix your conditions so that they make sense and the loop properly ends on its own:
while string != "you" and string != "me":
Note the and: Now, the loop only continues when string is neither "you" nor "me". This is equivalent to your break logic where you stopped the iteration when the string became either of those strings.
So it now looks like this:
string = ''
while string != "you" and string != "me":
string = input("Input string: ")
if string == "you":
stringYou(inp)
elif string == "me":
stringMe(inp)