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.
Related
Problem:
Once upon a day, Mary bought a one-way ticket from somewhere to somewhere with some flight transfers.
For example: SFO->DFW DFW->JFK JFK->MIA MIA->ORD.
Obviously, transfer flights at a city twice or more doesn't make any sense. So Mary will not do that.
Unfortunately, after she received the tickets, she messed up the tickets and she forgot the order of the ticket.
Help Mary rearrange the tickets to make the tickets in correct order.
Input:
The first line contains the number of test cases T, after which T cases follow.
For each case, it starts with an integer N. There are N flight tickets follow.
Each of the next 2 lines contains the source and destination of a flight ticket.
Output:
For each test case, output one line containing "Case #x: itinerary", where x is the test case number (starting from 1) and the itinerary is a sorted list of flight tickets that represent the actual itinerary.
Each flight segment in the itinerary should be outputted as pair of source-destination airport codes.
Sample Input: Sample Output:
2 Case #1: SFO-DFW
1 Case #2: SFO-DFW DFW-JFK JFK-MIA MIA-ORD
SFO
DFW
4
MIA
ORD
DFW
JFK
SFO
DFW
JFK
MIA
My question:
I am a beginner in the field of competitive programming. My question is how to interpret the given input in this case. How did Googlers program this input? When I write a function with a Python array as its argument, will this argument be in a ready-to-use array format or will I need to deal with the above mentioned T and N numbers in the input and then arrange airport strings in an array format to make it ready to be passed in the function's argument?
I have looked up at the following Google Kickstart's official Python solution to this problem and was confused how they simply pass the ticket_list argument in the function. Don't they need to clear the input from the numbers T and N and then arrange the airport strings into an array, as I have explained above?
Also, I could not understand how could the methods first and second simply appear if no Class has been initialized? But I think this should be another question...
def print_itinerary(ticket_list):
arrival_map = {}
destination_map = {}
for ticket in ticket_list:
arrival_map[ticket.second] += 1
destination_map[ticket.first] += 1
current = FindStart(arrival_map)
while current in destination_map:
next = destination_map[current]
print current + "-" + next
current = next
You need to implement it yourself to read data from standard input and write results to standard output.
Sample code for reading from standard input and writing to standard output can be found in the coding section of the FAQ on the KickStart Web site.
If you write the solution to this problem in python, you can get T and N as follows.
T = int(input())
for t in range(1, T + 1):
N = int(input())
...
Then if you want to get the source and destination of the flight ticket as a list, you can use the same input method to get them in the list.
ticket_list = [[input(), input()] for _ in range(N)]
# [['MIA', 'ORD'], ['DFW', 'JFK'], ['SFO', 'DFW'], ['JFK', 'MIA']]
If you want to use first and second, try a namedtuple.
Pair = namedtuple('Pair', ['first', 'second'])
ticket_list = [Pair(input(), input()) for _ in range(N)]
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()))
I need to make 3 political parties like in an election. The program should ask "for which will you vote?" (showing the 3 political options), after 10 the user randomly inserts 10 votes, the program should count the votes and print the results.
I'm new to programming, I really don't know what I'm doing
print("today is election day! for who will u vote?")
polls=print("PLD","PRM","PRD")
1) In your question, you stated "after 10...", after 10 what?
Im assuming that if was just a typo.
Here's the code for the program. All you need to do is figure out how to stop asking once it the vote count is greater than or equal to 10. You learn and retain information best when you struggle, trust me.
If you have any questions about the syntax used, feel free to drop a comment.
parties = ['PLD', 'PRM', 'PRD']
max_votes = 10
num_votes = 0
print('~'*40)
print(f'\n~ Today is election day!\n~ You have {vote_count} votes to use\n~ Use them wisely!\n')
print('~'*40)
print(f' Polical Parties: {parties[:]}')
print('~'*40,'\n')
"""
As declared above, "num_votes" is the variable that is being used to keep
track of how many votes the user has used so far.
The += operator adds the value of the variable on the right to the existing
value of the variable on the left. It would be the same as saying:
>>> num_votes = num_votes + PLD_votes
So, its just saving the number of votes used to the varible "num_votes".
"""
PLD_votes = int(input(f'\nHow many votes for "{parties[0]}": '))
num_votes += PLD_votes
num_votes = input(f'\nHow many votes for "{parties[1]}": ')
num_votes += PRM_votes
PRD_votes = input(f'\nHow many votes for "{parties[2]}": ')
vote_count += PRD_votes
print('Here are the results...\n')
print(f'{parties[0]}: {PLD_votes}\n{parties[1]}: {PRM_votes}\n{parties[2]}: {PLD_votes}')
"""
The use of "f" and "{}" within strings is a way of formating the string to return letters with variables in them.
Example: print(f'Number of votes: {num_votes}') *mind the 'f'*
Here, typing 'f' before the quotations tells the program that you are going to be using "{}" within the string. What goes inside of the curlies "{}" are variables that you want to print along with the string. I prefer this
There are many different ways of accomplishing this:
Concatenation:
>>> print('Number of votes' + num_votes)
Using %d ('d' for numbers; for variable which contain strings you would use '%s'):
>>> print('Number of votes %d')
There are more ways of doing it, I just prefer using {} because to me it seems more straightforward to read.
"""
Let's say i have a file containing data on users and their favourite movies.
Ace: FANTASTIC FOUR, IRONMAN
Jane: EXOTIC WILDLIFE, TRANSFORMERS, NARNIA
Jack: IRONMAN, FANTASTIC FOUR
and based of that, the program I'm about to write returns me the name of the users that likes the same movies.
Since Ace and Jack likes the same movie, they will be partners hence the program would output:
Movies: FANTASTIC FOUR, IRONMAN
Partners: Ace, Jack
Jane would be exempted since she doesn't have anyone who shares the same interest in movies as her.
The problem I'm having now is figuring out on how Radix Sort would help me achieve this as I've been thinking whole day long. I don't have much knowledge on radix sort but i know that it compares elements one by one but I'm terribly confused in cases such as FANTASTIC FOUR being arranged first in Ace's data and second in Jack's data.
Would anyone kindly explain some algorithms that i could understand to achieve the output?
Can you show us how you sort your lists ? The quick and dirty code below give me the same output for sorted Ace and Jack.
Ace = ["FANTASTIC FOUR", "IRONMAN"]
Jane = ["EXOTIC WILDLIFE", "TRANSFORMERS", "NARNIA"]
Jack = ["IRONMAN", "FANTASTIC FOUR"]
sorted_Ace = sorted(Ace)
print (sorted_Ace)
sorted_Jack = sorted(Jack)
print (sorted_Jack)
You could start comparing elements one by one from here.
I made you a quick solution, it can show you how you can proceed as it's not optimized at all and not generalized.
Ace = ["FANTASTIC FOUR", "IRONMAN"]
Jane = ["EXOTIC WILDLIFE", "TRANSFORMERS", "NARNIA"]
Jack = ["IRONMAN", "FANTASTIC FOUR"]
Movies = []
Partners = []
sorted_Ace = sorted(Ace)
sorted_Jane = sorted(Jane)
sorted_Jack = sorted(Jack)
for i in range(len(sorted_Ace)):
if sorted_Ace[i] == sorted_Jack[i]:
Movies.append(sorted_Ace[i])
if len(Movies) == len(sorted_Ace):
Partners.append("Ace")
Partners.append("Jack")
print(Movies)
print(Partners)
I make my first MLM software and I think I managed to code how to get the points from the downline even though it is a recursive problem I didn't use recursion and I might refactor to a recursive version if that seems better. With our system, the level of a distributor is measured i number of silvers and for each product that gets sold the promotion/bonus/score/points works upline so if Bob is the sponsor of Alice and Alice makes a purchase then Bob will get points measured in number of silvers for that purchase. I added a business function to my user class:
def this_month_non_manager_silver(self):
silver = 0
today = date.today()
timeline = date(today.year, today.month, 1)
downline = User.query(User.sponsor
== self._key).fetch()
distributor = self
while distributor.has_downline():
downline = User.query(User.sponsor == distributor.key).fetch()
for person in downline:
orders = model.Order.all().filter('buyer_id =' , person.key.id()).filter('created >' , timeline).filter('status =', 'PAID').fetch(999999)
for order in orders:
for idx,item in enumerate(order.items):
purchase = model.Item.get_by_id(long(item.id()))
amount = int(order.amounts[idx])
silver = silver + amount*purchase.silver/1000.000
distributor = person
return silver
What might be to do is now just a % on the silver according to the depth of the order.
The code actually output the correct result for an order downline but I didn't yet test it extensively and I wonder if you think the code looks strange and if I have thought of everything since the models are somewhat complicated / advanced. The user class is from webapp2 and I could use a subclass but I didn't have time to do that so I just put in the method to the user class that's there and now I can call it from Jinja2 like {{user.this_month_non_manager_silver}}
Recursion might to be right way to do this but isn't my solution still OK and I can move on and keep this code for now or do you think it is not acceptable?
Thanks for any constructive criticism.
The main problem I see here is that you're essentially trying to do a breadth-first search (you look at all the users who are below the distributor, then look at all of the users below those distributors, etc etc), but each time the while loop loops you're only looking at the users below the last distributor.
If we break down the important parts into something python-ish, you get this:
distributor=self
while distributor.has_downline():
for person in distributor.downline:
distributor = person
As you can see, the value of distributor after the first set of downlines are accessed is the last distributor in the user's downline. Then the next time the for loop is run, you're only looking at the last distributor's downline.
Traditionally a tree-walking algorithm is either recursive or loop-based with a stack. Generally you will choose one or the other based on memory constraints. To keep the solution iterative, you'd need to rewrite the above python-ish code like this:
downlinestack = []
distributor=self
downlinestack += distributor.downline
while downlinestack:
downline = downlinestack.pop()
for person in downline:
downlinestack.append(person.downline)