Where could the error be in this programme, please? - python

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.

Related

How do I display each element or alphabet as dash after it matches the input for Hangman?

I have been on and off programming but recently I have been more active and done some basic projects. However I have been stuck on this particular problem for the past 3 weeks and still cannot seems to solve it. Looked through some codes and tried and only could improve some parts. The bottom is my full code.
The problems that I faced is the one that I have stated in my title, I need to display the mystery word as dashes and when I guess the unknown word, it was suppose to appear as the only word. One issue is when I guess the word correctly, it only display the single alphabet and reset immediately.
import random
word_list =[
"SAXOPHONE",
"THEREMIN",
"XYLOPHONE",
"TROMBONE",
"RECORDER",
"OCARINA",
"HANG",
"GUITAR",
"PIANO",
"DIDGERIDOO",
"CELLO",
"CLARINET",
"BONGO",
"DRUM",
"FLUTE",
"ERHU",
"DIZI",
"HARMONICA",
"GONG",
"GUZHENG"
]
pick_word = random.choice(word_list)
pick_letter = list(pick_word)
print(pick_letter)
print("Welcome to Hangman Instrumental")
turns = 10
while turns > 0:
# input of players(input to accept both lower and upper case)
player_in = input(str("\nEnter a Character: ")).upper()
# check if input is the same as the pick letter
if player_in in pick_letter:
if player_in in pick_letter:
print(player_in)
elif len(player_in) != 1:
print("Invalid input please try again")
else:
turns -= 1
print("You have ",turns, " turns left")
if turns == 0:
print("You Lose !")
Keep a list of all the player's guesses. When you start a new game, set all_guesses to [] and then, reading the letter from the console set:
all_guesses.append(player_in)
Now you can display just letters from that list in the secret word with:
display_word = ''
for c in pick_word:
if c in all_guesses:
display_word += c
else:
display_word += '-'
Then print out display_word however you like. You can combine all of that into a single Python expression:
display_word = ''.join(c if c in all_guesses else '-' for c in pick_word)
That uses three ideas that you may not have seen yet (if-else expressions, generator expressions and the .join() string member function) so if it looks like Martian to you, that's okay. Think of it as a peek ahead into cool things you'll learn later.

Check any value in a list exist in a sentence

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

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

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