There's a dictionary of abbreviations, the key being the abbreviation and the value being its definition ("TTYL","Talk To You Later"). When user inputs something with more than 1 abbreviation , I want a program to replace the abbreviations with the definition as an addition to the original input. I got the program to work, but only for 1 abbreviation. I want it to be able to handle more than 1 abbreviation in a string. I believe the solution has something to do with the nested for loop, however I'm uncertain and need some help.
Python Code:
abbreviationsDictionary = {
"ADBA":"As Directed By Arborist",
"CRTS":"Crown Reduced To Shape",
"NWIC":"Noob Will Improve Company"
}
note = input("Enter note: ")
listOfWordsInNote = note.split()
updatedNote = ""
for key in abbreviationsDictionary:
for word in listOfWordsInNote:
if (key==word):
updatedNote = note.replace(key,abbreviationsDictionary[key])
print(updatedNote)
Current Output (only works for 1 abbreviation):
Enter note: mike is going to do whatever ADBA because he knows NWIC
mike is going to do whatever ADBA because he knows Noob Will Improve Company
Desired Output
Enter note: mike is going to do whatever ADBA because he knows NWIC
mike is going to do whatever As Directed By Arborist because he knows Noob Will Improve Company
Your error is that you use
updatedNote = note.replace(key,abbreviationsDictionary[key])
So, each time a new key is found, you restart with note (which has not changed )
just replace by :
note = note.replace(key,abbreviationsDictionary[key])
and print (note) :
mike is going to do whatever As Directed By Arborist because he knows Noob Will Improve Company
Rather than replacing in the input string, get the [whitespace delimited] tokens from the user input then use a simple generator to reconstruct:
abbreviationsDictionary = {
"ADBA": "As Directed By Arborist",
"CRTS": "Crown Reduced To Shape",
"NWIC": "Noob Will Improve Company"
}
note = input("Enter note: ")
print(' '.join(abbreviationsDictionary.get(loin, loin) for loin in note.split()))
Related
My code is not printing the correct result for the test case
2 6
1 alex
1 Alex
2 sam
1 alix
1 Alix
2 caM
properly as it should result in "alex, sam", yet it results in "alex, Alex" (After reading the following instructions youll understand why). Was hoping I can get some insight as to what is wrong with my code.
Exercise: Dan’s recently announced that he’s teaching n top-secret courses next semester.
Instead of enrolling in them through ACORN, students need to email Dan to
express their interests. These courses are numbered from 1 to n in some arbitrary
order.
In particular, if a student named s is interested in taking a course c, they need to
send an email to Dan containing the message c s. Note that if a student is
interested in taking multiple courses, they need to send multiple emails, one per
course.
Upon receiving a message c s, Dan looks at the list of students already enrolled in
course c. If there’s already a student on the list whose name is too similar to s,
Dan assumes s is the same student and ignores the message. Otherwise, he
enrolls s in the course.
Dan considers two names too similar if and only if they have the same length and
differ in at most one letter(note that “a” and “A” are considered the same letter).
For example, “Josh” and “Josh” are too similar. “Sam” and “CaM” are too similar
as well. However, neither “Max” and “Cat” nor “Ann” and “Anne” are too similar.
Dan has a lot of students and teaches a lot of courses. Consequently, it would take
him forever to process the messages sent by the students one-by-one manually.
Instead, he’s asking you to help him out by writing a program that takes in the
messages as the input and outputs, for every course, the list of the students
enrolled in that course in the order of their enrolments.
My code thus far: `
u = input()
u, w = u.split()
courses = int(u)
students = int(w)
names = []
classes = []
for i in range(students):
names_input = input()
selection = names_input.split()
course_num = selection[0]
student_name = selection[1]
if course_num not in classes:
classes.append(course_num)
names.append(student_name)
else:
if student_name not in names:
names.append(student_name)
print(classes)
print(names)
for i in range(0, len(classes)):
print(names[i])
`Image of the question
image of the question here as well Question in a screenshot, if its easier to read feel free to see it here as well.
I made a dictionary in IDE and made a function to take input from user and it takes the input but when I rerun that program and try to print the output It don`t show anything.
Here is the code, help if anyone want to.
# Created dictionary.
list = {}
# Made a Function to save data.
def up():
v = int(input(f"How many inputs you want to give : "))
for i in range(v):
a = input(f"Give words you want to put : ")
b = input(f"Assign : ")
list.update({a:b})
print(f"Saved",{a:b})
value = input(f"What you want to do ? \nSee List or update it. \nIf you want to update type 'u' , If you want to see list type 's' ")
if value == "s":
print(list)
elif value == "u":
up()
Information in your variables is stored during the execution of your script. It is not automatically carried across to different executions of your script. Each one is a blank slate. Even if it weren't, the first line of your program sets list to an empty dictionary.
At the moment, you're putting salt on your broccoli, eating it, then expecting the broccoli you eat tomorrow to also have salt on it.
You could serialise the dictionary to a file, that can be read back in on next execution, rather than starting with an empty dictionary each time.
I need a program that would let a person enter a person's name and his birth year (5 people only).
The information is written into two lists - one with names and the other with years.
Then the program needs to remove the youngest person (or youngest people).
The final result needs to be printed out in a .txt file.
This is what I have so far:
names = []
ages = []
def names_ages():
while True:
name_age = input("Enter your name and birth year: ")
name_age.split()
print(name_age)
I don't know if I'm going into the right direction or not, could somebody suggest something?
I am going to assume that you are expecting first name and the year to be separated by a space like so.
"andrew 1996"
if so, you are going to want to split the input on space (to have the first entry correspond to "andrew" and the second to correspond to "1996"
response = name_age.split(" ")
Now you can add these values to the arrays that you defined up above (or you could use a python dictionary which I think would be better suited for this problem) https://docs.python.org/2/tutorial/datastructures.html#dictionaries
names.append(response[0])
ages.append(int(response[1]))
You are going to have to decide when to stop accepting names, which you would put in your while loop condition(right now it is running forever) Perhaps wait until the user input is "stop" or something of that nature.
That should get you in the correct direction, comment if you have any questions
name = []
year = []
x=0
while x <3:
x += 1
user = name.append(raw_input("enter name"))
user_year = year.append(raw_input("enter DOB"))
o = []
for i in zip(year,name):
o.append(i)
o.sort()
o.remove(o[0])
print o
This might one from of the solutions from many possible.
I am trying to create a questionnaire where it asks multiple yes/no questions, and after receiving all of the responses a different output is shown depending on the combination of answers provided.
For example, if there were three questions and someone answered no, no, then yes, they would see one output (just a simple sentence that I will create), but if someone else answered yes, no, yes, they would see a different response at the end. I don't want to provide feedback after each individual question, only when all questions have been answered.
I was trying to use if/else, but that didn't seem to be working for my purposes (at least the way I was doing it, but I am very new to Python!). I'm sorry that I don't have much to work with, but I am trying to learn and have been doing Google search after Google search to no avail. Thank you!!
EDIT: Here's what I've been trying. Is there any way to extend on this? What I've done is based on my limited knowledge of Python.
female = raw_input("Are you female?")
over18 = raw_input("Are you over 18?")
shopping = raw_input("Do you like to go shopping?")
And then I know how to do something like
if female=="yes":
print "blahblah"
else:
print "something else"
But I don't know how to use all three responses to contribute to what will print. I also can't figure out how to restrict each question to just a yes/no answer.
EDIT 2:
Can I use multiple if statements as shown below? I know how to use just one response to change the output, but having three influence just one output is just throwing me for a loop.
female = raw_input("Are you female?")
over18 = raw_input("Are you over 18?")
shopping = raw_input("Do you like to go shopping?")
if (female=="yes" and over18=="yes" and shopping=="yes"):
print "1"
if (female=="yes" and over18=="yes" and shopping=="no"):
print "2"
if (female=="yes" and over18=="no" and shopping=="no"):
print "3"
if (female=="yes" and over18=="no" and shopping=="yes"):
print "4"
if (female=="no" and over18=="yes" and shopping=="yes"):
print "5"
if (female=="no" and over18=="yes" and shopping=="no"):
print "6"
if (female=="no" and over18=="no" and shopping=="yes"):
print "7"
if (female=="no" and over18=="no" and shopping=="no"):
print "8"
else:
print "invalid"
It looks like that is functioning relatively well, but no matter what combination of "yes" and "no" I use it will give me the correct number output but then also say "invalid." However, if I take out the else, it won't restrict the answers to "yes" or "no," will it?
One way that occurs to me is to make a dictionary keyed by a tuple of yes/no responses - one for each question. So if you have, say, 2 questions - 1 and 2, you'd have 4 possible outcomes. YY, YN, NY, and NN. You can create a dictionary with keys that correspond to these. So something like
def ask_question(qn):
resp = raw_input(qn)
if resp.lower() in ["yes", "y"]: # Handles Yes, yes etc.
return True
else:
return False
responses = {(True, True) : "Old Male",
(True, False) : "Young Male",
(False, True) : "Old Female",
(False, False) : "Young Female"}
answers = []
questions = ["Are you male?", "Are you over 18?"]
for q in questions:
answers.append(ask_question(q))
print responses[tuple(answers)]
Since the actual answers are in data (rather than code), you can read these out from a file which you can edit/generate easily. It's a much more conventient way of mananging than a huge and hairy if/elif/else block.
I am working on a quiz game and when I get asked any question, i type in the right answer, which I defined in the a variable that holds that correct answer but it says it is wrong if it isn't the first word for that variable (In this case, Metallica). Here is what my code looks like.
q1answer = "Metallica" or "metallica" or "Slayer" or "slayer" or "Anthrax" or "anthrax" or "Megadeth" or "megadeth"
answerinput = str(input("name one of the 'Big Four' metal bands'"))
if answerinput == q1answer:
print ("You got the right answer!")
else:
print ("That is the wrong answer...")
Now, if I was to type in 'Metallica' it would be correct because it is the first word for the q1answer variable. But, if I type metallica, Slayer, slayer, Anthrax, anthrax, megadeth or Megadeth, I would get the wrong answer text. Is there a way for all of these strings to be working for this one variable if i was to type anything but the first word in that variable? I'm a rookie in python so any help would be great.
Put them in a set and test for a correct answer using in instead:
q1answer = {"Metallica", "metallica", "Slayer", "slayer", "Anthrax", "anthrax", "Megadeth", "megadeth"}
...
if answerinput in q1answer:
Right now, your series of ors is just resulting in the first one - "Metallica". You can also stop duplicating every name for case-insensitivity and instead use lower:
if answerinput.lower() in q1answer:
Change your code like this:
q1answer = ("metallica", "slayer", "anthrax", "megadeth")
...
if answerinput.lower() in q1answer:
...