Check any value in a list exist in a sentence - python

I am trying to check whether any value in a list exist in a sentence as below:
rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]
whoAmI = "I am an Engineer"
if rich.*MISSING_HERE* in whoAmI:
print "You are RICH"
else :
print "You are POOR"
If you look at the line with the if statement, I am checking whether any element fron rich is available in whoAmI. How do I check this?

Use any() method -
if any(r in whoAmI for r in rich):
print "You are RICH"
else :
print "You are POOR"

Try for else loop
rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]
whoAmI = "I am an Engineer"
for r in rich:
if r in whoAmI:
print "You are RICH"
break
else:
print "You are POOR"

We can use the re or regex module of Python Library to search for the word in the string. We will be using simple for loop ( Note: Time complexity : O(n))
import re
rich = ["Businessman","Robber","Politician"]
poor = ["Programmer","Engineer","Doctor"]
whoAmI = "I am an Businessman"
for word in rich:
if re.search(i, whoAmI):
print("Rich")
quit()
print("Poor")
We are using Python inbuilt function quit() so as to prevent same outputs from displaying multiple times.

You can use this simplified answer
[any( j in rich for j in whoAmI.split())]
If it satisfies the condition, it will answer True(i.e., 'rich') else it will notify false.

With a list of comprehension:
if len([x for x in rich if x in whoAmI]):
print ("You are RICH")
else :
print ("You are POOR")
You are POOR

Related

Where could the error be in this programme, please?

I am grouped into groups for a project, and I am are expected to come up with as many famous scientists who have the same first letter of their name as I as possible. But I need to know whether i will have to come up with the answers on my own, or is there somebody in my group that I can work with?
The input is a string of my group members' names separated by spaces, and then a string of my name.
Expected Output:
A string that says "Compare notes" if I have a name buddy, or "No such luck" if I have to work on this alone.
group_members = input().split()
my_name = input()
for fellow in group_members:
if fellow[0] is my_name[0]:
print("Compare notes")
break
else:
print("No such luck")
break
My programme worked perfectly for all but one of the test cases. Please, where could the bug be here? Thanks for your support.
Try this
group_members = input().split()
my_name = input()
for fellow in group_members:
if fellow[0] == my_name[0]:
print("Compare notes")
break
else:
print("No such luck")
More on else for the for loop is in the docs.

How to check if any part of an input is part of a list in python

So I want to make a bot that tells jokes but I am having trouble checking if any part of an input is part of a seperate list. So for instance (side note: this is all in a while loop):
punWords = [pun, Puns]
userInput = input('What kind of jokes do you want to hear?')
elif userInput in punWords:
print(random.choice(punJokes))
print(random.choice(jokeResponses))
print(' ')
jokeFunc2()
else:
print('Sorry I dont know any of these jokes')
The problem im having is that if the user inputs something like "I want to hear a pun" Then it goes through and compares every word to punWords and if it doesn't match then it prints the "Sorry I don't know any of these jokes" message so that the output ends up looking something like this:
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Sorry I dont know any of these jokes'
'Insert pun joke'
What I want to happen is that it only prints the error message if the input doesnt match any of the other words. Thanks a lot for any help and sorry if the post isnt done right (this is my first time posting on any kind of forum).
One way you could do it is to count the number of matches. Then if there are zero matches, print the error message. Something like:
if userInput in punWords:
matchedWords += 1
then after the while loop
if matchedWords:
# do your thing
else:
print ("Sorry I don't know any of these jokes")
You are basically looking for the intersection between two lists (the list of pun words and the list of words entered), which can be performed using a Python set:
words = userInput.split()
if (set(words) & set(punWords)):
print(random.choice(punJokes))
or more simply demonstrated:
a = [1,2,3]
b = [3,4,5]
print(list(set(a) & set(b))) #result: [3]

Is there a way to recognize at least one word in the input?

For example
userDay = input("How was you day? ")
The user input "My day was good"
and then the program recognizes that the user said "good", and then chooses the correct response for "good".
Sorry if you don't understand, its hard to explain.
Easy and quick way would be split the response into words using response.split() and then check each word if it equal to good
This way you can avoid searching for ‘ good’ or ‘ good ‘ or ’good ‘ (good word can be starting word, ending word or somewhere in the line)
I'd suggest using python's built-in lexical analysis tool, shlex. It is very useful as it contains functionality that makes it easy to write a (simple) lexical analyzer.
So in your case you can do something like this:
import shlex
user_input = 'My day was good'
li = shlex.split(user_input)
print 'Your day was good' if 'good' in li else 'Your day was bad'
The prints here are for demonstrating purposes only. You have to substitute them with your code that will choose the correct response for "good".
Just check if a substring is in a string:
userDay = input("How was you day? ")
if 'good' in userDay:
print('good')
or you can use:
if userDay.find('good') == 1:
print('good')
Something like this:
response = input("How was you day? ")
if response == 'good':
# do something
Or if you're just looking for 'good' in the response somewhere:
response = input("How was you day? ")
if 'good' in response.lower():
# do something

Basic Python Script If Statement

I am messing around with this basic Magic 8 Ball program and im trying to make it only allow yes or no questions I am thinking that it will only except questions that have the first word "will" or "do" how can I make a that only allows those to words?
Here is the Script:
import random
import time
print "Welcome to Magic Eight Ball !"
while True:
def Magic8(a):
foo = ['Yes', 'No', 'Maybe', 'Doubtful', 'Try Again']
from random import choice
print choice(foo)
a = raw_input("Question: ")
if a == "exit":
exit()
#If Stament here
print "Determining Your Future..."
time.sleep(2)
Magic8(a)
if a.split(None, 1)[0].lower() in {'will', 'do'}:
print "Determining Your Future..."
time.sleep(2)
magic8(a) # function names are usually not capitalized
str.split() splits the sentence on whitespace, str.lower should handle the uppercase.
You can use str.startswith and pass a tuple of accepted words.
if a.lower().startswith(("will ", "do ")):
# Do your magic.
maybe if you have little words you can use elif or or
if a=="exit":
exit()
elif a=="optionOne":
doSomething
else:
print "word not alowed"
Or you can do like this
if a=="exit" or a=="notAllowedWord":
exit()

Identify substrings and return responses based on order of substrings in Python

I am a beginner in Python, I am teaching myself off of Google Code University online. One of the exercises in string manipulation is as follows:
# E. not_bad
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
# So 'This dinner is not that bad!' yields:
# This dinner is good!
def not_bad(s):
# +++your code here+++
return
I'm stuck. I know it could be put into a list using ls = s.split(' ') and then sorted with various elements removed, but I think that is probably just creating extra work for myself. The lesson hasn't covered RegEx yet so the solution doesn't involve re. Help?
Here's what I tried, but it doesn't quite give the output correctly in all cases:
def not_bad(s):
if s.find('not') != -1:
notindex = s.find('not')
if s.find('bad') != -1:
badindex = s.find('bad') + 3
if notindex > badindex:
removetext = s[notindex:badindex]
ns = s.replace(removetext, 'good')
else:
ns = s
else:
ns = s
else:
ns = s
return ns
Here is the output, it worked in 1/4 of the test cases:
not_bad
X got: 'This movie is not so bad' expected: 'This movie is good'
X got: 'This dinner is not that bad!' expected: 'This dinner is good!'
OK got: 'This tea is not hot' expected: 'This tea is not hot'
X got: "goodIgoodtgood'goodsgood goodbgoodagooddgood goodygoodegoodtgood
goodngoodogoodtgood" expected: "It's bad yet not"
Test Cases:
print 'not_bad'
test(not_bad('This movie is not so bad'), 'This movie is good')
test(not_bad('This dinner is not that bad!'), 'This dinner is good!')
test(not_bad('This tea is not hot'), 'This tea is not hot')
test(not_bad("It's bad yet not"), "It's bad yet not")
UPDATE: This code solved the problem:
def not_bad(s):
notindex = s.find('not')
if notindex != -1:
if s.find('bad') != -1:
badindex = s.find('bad') + 3
if notindex < badindex:
removetext = s[notindex:badindex]
return s.replace(removetext, 'good')
return s
Thanks everyone for helping me discover the solution (and not just giving me the answer)! I appreciate it!
Well, I think that it is time to make a small review ;-)
There is an error in your code: notindex > badindex should be changed into notindex < badindex. The changed code seems to work fine.
Also I have some remarks about your code:
It is usual practice to compute the value once, assign it to the variable and use that variable in the code below. And this rule seems to be acceptable for this particular case:
For example, the head of your function could be replaced by
notindex = s.find('not')
if notindex == -1:
You can use return inside of your function several times.
As a result tail of your code could be significantly reduced:
if (*all right*):
return s.replace(removetext, 'good')
return s
Finally i want to indicate that you can solve this problem using split. But it does not seem to be better solution.
def not_bad( s ):
q = s.split( "bad" )
w = q[0].split( "not" )
if len(q) > 1 < len(w):
return w[0] + "good" + "bad".join(q[1:])
return s
Break it down like this:
How would you figure out if the word "not" is in a string?
How would you figure out where the word "not" is in a string, if it is?
How would you combine #1 and #2 in a single operation?
Same as #1-3 except for the word "bad"?
Given that you know the words "not" and "bad" are both in a string, how would you determine whether the word "bad" came after the word "not"?
Given that you know "bad" comes after "not", how would you get every part of the string that comes before the word "not"?
And how would you get every part of the string that comes after the word "bad"?
How would you combine the answers to #6 and #7 to replace everything from the start of the word "not" and the end of the word "bad" with "good"?
Since you are trying to learn, I don't want to hand you the answer, but I would start by looking in the python documentation for some of the string functions including replace and index.
Also, if you have a good IDE it can help by showing you what methods are attached to an object and even automatically displaying the help string for those methods. I tend to use Eclipse for large projects and the lighter weight Spyder for small projects
http://docs.python.org/library/stdtypes.html#string-methods
I suspect that they're wanting you to use string.find to locate the various substrings:
>>> mystr = "abcd"
>>> mystr.find("bc")
1
>>> mystr.find("bce")
-1
Since you're trying to teach yourself (kudos, BTW :) I won't post a complete solution, but also note that you can use indexing to get substrings:
>>> mystr[0:mystr.find("bc")]
'a'
Hope that's enough to get you started! If not, just comment here and I can post more. :)
def not_bad(s):
snot = s.find("not")
sbad = s.find("bad")
if snot < sbad:
s = s.replace(s[snot:(sbad+3)], "good")
return s
else:
return s

Categories

Resources