Given two strings, determine if they share a common substring. A substring may be as small as one character.
Example:
s1 = "and"
s2 = "art"
They share the character "a". Then return a string: either YES or NO
def twoStrings(s1, s2):
UniqueChar_S1 = (char for char in s1)
UniqueChar_S2 = (char for char in s2)
SubStringExists = False
for i in set(UniqueChar_S1):
if i in set(UniqueChar_S2):
SubStringExists = True
break
else:
continue
return "YES"*int(SubStringExists) + "NO"*(1 - int(SubStringExists))
def main():
q = int(input())
for q_itr in range(q):
s1 = input()
s2 = input()
result = twoStrings(s1, s2)
if __name__ == "__main__":
main()
Example input:
4
wouldyoulikefries
abcabcabcabcabcabc
hackerrankcommunity
cdecdecdecde
jackandjill
wentupthehill
writetoyourparents
fghmqzldbc
Expected Output:
NO
YES
YES
NO
Example Input that Fails:
2
aardvark
apple
beetroot
sandals
Im not getting thrown an error and so im unsure what is the issue with my code, I cannot see any issues with the code and so Im wondering if anyone can point anything out for me. Also any improvements will be appreciated.
In its simplest form: "NO" if set(s1).isdisjoint(s2) else "YES"
Well you need to modify your code as following as it is more optimised:
def twoStrings(s1, s2):
UniqueChar_S1 = set(s1)
UniqueChar_S2 = set(s2)
for i in UniqueChar_S1:
if i in UniqueChar_S2:
return "YES"
return "NO"
def two_strings(s1, s2):
return "YES" if set(s1).intersection(set(s2)) else "NO"
def main():
q = int(input("Numbers: "))
for q_itr in range(q):
s1 = input("String 1: ")
s2 = input("String 2: ")
result = two_strings(s1, s2)
print(result)
if __name__ == "__main__":
main()
UniqueChar_S1 = (char for char in s1) is a generator.
for i in set(UniqueChar_S1):
if i in set(UniqueChar_S2):
So after checking the 'if' condition once the value of set(UniqueChar_S2) would be empty for second iteration.
So i suggest you the following code:
def twoStrings(s1, s2):
SubStringExists = set(s1)&set(s2)
return "YES" if SubStringExists else "NO"
Related
I was expecting this code to print "new string" between each row in my dataframe...
def isASCII(input_string):
print(input_string)
if isinstance(input_string, str):
orig_length = len(input_string)
print('new String!')
listThing = [letter for letter in input_string if ord(letter) < 127]
print(listThing)
new_length = len(listThing)
return (orig_length == new_length)
else:
return False
#isASCII('test') true
#isASCII('一些文字') false
#isASCII('sometext字') false
english_ga = dupe_free_ga.loc[isASCII(dupe_free_ga['App'].to_string())]
Instead 'new string!' appears once. Am I just not understanding how loc works here?
Let's try to split this line
english_ga = dupe_free_ga.loc[isASCII(dupe_free_ga['App'].to_string())]
to illustrate how Python evaluates it:
tmp = isASCII(dupe_free_ga['App'].to_string())
english_ga = dupe_free_ga.loc[tmp]
So, what would you expect dupe_free_ga.loc[True] or dupe_free_ga.loc[False] to return? Isn't that exactly what you get there?
I'm getting same output of "Nodding" in first if else condition instead of "Smiling". Could anyone tell me what can I do to fix it?
mood = ('happy', 'sad', 'neutral', 'angry', 'joy', 'calm')
content = ('positive', 'negative', 'unsure')
i = input('Enter sentence: ')
str = i.split(' ')
for m in str:
for c in str:
if m == mood[0] and c == content[0]:
print("Smiling")
exit()
elif m == mood[0] and c == content[2]:
print("Nodding")
exit()
elif m == mood[1]:
print("Frowning")
exit()
elif m == mood[2] and content[0] or content[1]:
print("Nodding")
exit()
elif m == mood[2] and content[2]:
print("Blinking")
else:
exit()
Output:
Enter sentence: i am happy and positive
Nodding
I should be getting "Smiling" for the above output instead of "Nodding".
The condition m == mood[2] and content[0] or content[1] doesn't do what you want, you forgot the c comparison, it should be
elif m == mood[2] and c in (content[0], content[1])
elif m == mood[2] and c == content[2]
But instead of iterating on the content with 2 for loops, you could store the data in a dict where
the key is a tuple of the keywords to find
the value is what to print
Then if all keywords of a pair are found in the given sentence, then print the value
humors = {
('happy', 'positive'): 'Smiling',
('happy', 'unsure'): 'Nodding',
('sad',): 'Frowning',
('neutral', 'positive'): 'Nodding',
('neutral', 'negative'): 'Nodding',
('neutral', 'unsure'): 'Blinking',
}
content = input('Enter sentence: ')
for keywords, action in humors.items():
if all(keyword in content for keyword in keywords):
print(action)
break
I am trying to implement a function in python that given two strings it checks if the first string is smaller than the second string in the lexicographic order. This is what I managed to write, I do not claim that it is elegant code
import string
#first make a dictionary that gives the value of a letter, eg "C":3
d = dict.fromkeys(string.ascii_uppercase, 0)
i=1
for c in d.keys():
d[c] = i
i+=1
def lexico(str1,str2):#returns true if str1<=str2 in lexicographic order
print(str1,str2) #printing for debugging purpose
if str1 == '' and str2 == '':
return True
elif str1 != '' and str2 == '':
return False
elif str1 == '' and str2 != '':
return True
elif d[str1[0]] > d[str2[0]]:
return False
elif d[str1[0]] < d[str2[0]]:
return True
elif str1 == str2:
return True
else:
print(str1,str2) #printing for debugging purpose
lexico(str1[1:],str2[1:])
str1 = 'ANGELA'
str2 = 'AMY'
print(lexico(str1,str2))
I have really no idea what goes wrong here, but the output is as follows
ANGELA AMY
ANGELA AMY
NGELA MY
None
The function does not return anything, and I dont know why.
You are missing a return on this line: lexico(str1[1:],str2[1:]). It should be return lexico(str1[1:],str2[1:]).
Using Spyder Python 3.6 this code does not execute, says that the method ispal is not defined. However when I run it and put in an integer first (say my string input = 0), then it will run after and recognize the method. It seems like I have to go through a branch other than the call to the method first. Thanks for the critique.
s = input('enter a string: ')
s1 = s
s1 = s1.lower()
s1 = s1.replace(',', '')
s1 = s1.replace(' ', '')
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[1:])
First, as pointed out by TGKL you're calling ispal before it's defined. So define it before calling, i.e:
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[1:])
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')
Second your palindrome recursive function is right except when you call ispal inside itself. Instead of ispal(s1[1:]) you should do ispal(s1[1:-1]) which will remove both the first and the last character, which has been just tested.
You have to define your method first, then call it:
s = raw_input('enter a string: ') #use raw_input so the text it takes will give to you directly a string without ""
s1 = s
s1 = s1.lower()
s1 = s1.replace(',', '')
s1 = s1.replace(' ', '')
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[2:]) # here you put ispal(s1[1:]) it doesn't work properly :/
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')
I am trying to write a program that accepts a phone number in the format XXX-XXX-XXXX and translates any letters in the entry to their corresponding numbers.
Now I have this, and it will allow you to reenter the correct number if its not correct to start, but then it translates the original number entered. how do i fix this?
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
validNumber(phone_number)
translateNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
phone_number=input('Please enter a valid phone number: ')
return phone_number
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return phone_number
return phone_number
def translateNumber(phone_number):
s=""
for char in phone_number:
if char is '1':
x1='1'
s= s + x1
elif char is '-':
x2='-'
s= s + x2
elif char in 'ABCabc':
x3='2'
s= s + x3
elif char in 'DEFdef':
x4='3'
s= s + x4
elif char in 'GHIghi':
x5='4'
s= s + x5
elif char in 'JKLjkl':
x6='5'
s= s + x6
elif char in 'MNOmno':
x7='6'
s= s + x7
elif char in 'PQRSpqrs':
x8='7'
s= s + x8
elif char in 'TUVtuv':
x9='8'
s= s + x9
elif char in 'WXYZwxyz':
x10='9'
s= s + x10
print(s)
import re
def validNumber(phone_nuber):
pattern = re.compile("^[\dA-Z]{3}-[\dA-Z]{3}-[\dA-Z]{4}$", re.IGNORECASE)
return pattern.match(phone_nuber) is not None
If you don't want to use regular expressions: You can use isalnum to check if something is a number or letter. You can access the nth character in a string using mystr[n] so, you could try:
def validNumber(phone_number):
if len(phone_number) != 12:
return False
for i in range(12):
if i in [3,7]:
if phone_number[i] != '-':
return False
elif not phone_number[i].isalnum():
return False
return True
To see what phone_number[i] is doing, try this:
for i in range(len(phone_number)):
print i, phone_number[i]
Using enumerate:
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
return False
elif not c.isalnum():
return False
return True
Once you have it working, you should use it later (inside of main) like:
def main():
phone_number = '' # an invalid number to initiate while loop
while not validNumber(phone_number):
phone_number = input('Please enter a phone number in the format XXX-XXX-XXXX: ')
translated_number = translateNumber(phone_number)
You should use a regex to match the text.
the string module has a translate function that will replace most of your logic
code example below. note how i cast everything into lowercase to simplify the regex and translation.
import string
import re
RE_phone = re.compile("^[a-z0-9]{3}-[a-z0-9]{3}-[a-z0-9]{4}$")
map_in = 'abcdefghijklmnprstuvwxyz'
map_out = '222333444555667778889999'
mapped = string.maketrans( map_in , map_out )
def main():
while True:
phone_number= raw_input('Please enter a phone number in the format XXX-XXX-XXXX: ')
phone_number = phone_number.lower()
if RE_phone.match(phone_number):
break
print "Error. Please try again"
print translateNumber(phone_number)
def translateNumber(phone_number):
return phone_number.translate( mapped )
main()
you can go for:-
def contact_validate(s):
try:
int(s)
return True
except ValueError:
return False
>>> print contact_validate("+12345")
True
>>> print contact_validate("75.0")
False
>>> print contact_validate("hello")
False
I think this can be helpful
def checkvalidNumber(phone_number):
T={"-":0,"+":0,"_":0}
for i in str(phone_number):
if i in list(T.keys()):
if (i=="_" or i=="-") and (T["-"]>=1 or T['_']>=1):
return False
elif i=="+" and T[i]>=1:
return False
else:
T[i]+=1
elif not i.isdigit():
return False
return True
This is a fairly pythonic way to do it in my opinion
def validNumber(phone_number):
return all([x.isdigit() for x in phone_number.split("-")])
It splits the input at "-", checks that each remaining item is a number and returns a single True or False value.
all() - returns True if bool(x) is True for all x in iterable