I have to use nested loops for this exercise.
I have two class lists and need to determine which students are in both classes. I have written the code and it works but now my for loop is iterating over all the students again and prints the results the same as the iteration instead of just the actual students (in both classes). It does work if I put the for students in cs_students in line with the for students in maths_students but then it's not nested.
My code is as follows:
math_students = ["Audrey", "Ben", "Julia", "Paul", "Gerry", "Sue",
"Helena", "Harry", "Marco", "Rachel", "Tina", "Mark", "Jackson"]
cs_students = ["William", "Aroha", "Melissa", "Sue", "Ben", "Audrey", "Susan", "Mark", "Hemi", "Brendan", "Paul", "Barry", "Julia"]
for student in math_students:
count = 0
for student in cs_students:
if student in math_students:
count +=1
print("Student:", student, "is enrolled in both classes")
print(count, "Students are enrolled in Computer Science and Maths")
My output is:
Student: Sue is enrolled in both classes
Student: Ben is enrolled in both classes
Student: Audrey is enrolled in both classes
Student: Mark is enrolled in both classes
Student: Paul is enrolled in both classes
Student: Julia is enrolled in both classes
Student: Sue is enrolled in both classes
Student: Ben is enrolled in both classes
Student: Audrey is enrolled in both classes
Student: Mark is enrolled in both classes
Student: Paul is enrolled in both classes
Student: Julia is enrolled in both classes and so on.......
6 Students are enrolled in Computer Science and Maths
I think you're looking for something like this:
in_both_classes = []
for math_student in math_students:
for cs_student in cs_students:
if math_student == cs_student:
in_both_classes.append(math_student)
print "There are {} students in both classes: {}".format(
len(in_both_classes),
", ".join(in_both_classes),
)
You used the same variable, student, in both for-loops. Doing that prevents you from comparing the list values with each other.
That, and simple if-statement would do the trick :
math_students = ["Audrey", "Ben", "Julia", "Paul", "Gerry", "Sue",
"Helena", "Harry", "Marco", "Rachel", "Tina", "Mark", "Jackson"]
cs_students = ["William", "Aroha", "Melissa", "Sue", "Ben",
"Audrey","Susan", "Mark", "Hemi", "Brendan", "Paul", "Barry", "Julia"]
count = 0
for student1 in math_students: #change this to student1
for student2 in cs_students: #change this to student2
if student1 ==student2: #check if student1 is equal to student 2
count +=1
print("Student:", student2, "is enrolled in both classes") #print student2
print(count, "Students are enrolled in Computer Science and Maths")
Now this would output:
>>>
('Student:', 'Audrey', 'is enrolled in both classes')
('Student:', 'Ben', 'is enrolled in both classes')
('Student:', 'Julia', 'is enrolled in both classes')
('Student:', 'Paul', 'is enrolled in both classes')
('Student:', 'Sue', 'is enrolled in both classes')
('Student:', 'Mark', 'is enrolled in both classes')
(6, 'Students are enrolled in Computer Science and Maths')
when you retrieve the two lists, you use the same variable name studnet, you should rename any of them, for instance s1 and s2 and increase count only when s1 equal to s2.
BTW, I have another suggestion, you can use Sets Intersection
math_students = ["Audrey", "Ben", "Julia", "Paul", "Gerry", "Sue",
"Helena", "Harry", "Marco", "Rachel", "Tina", "Mark", "Jackson"]
cs_students = ["William", "Aroha", "Melissa", "Sue", "Ben", "Audrey", "Susan", "Mark", "Hemi", "Brendan", "Paul", "Barry", "Julia"]
math_set = set(math_students)
cs_set = set(cs_students)
# students in both cs and math
common_set = math_set & cs_set
#the studnets only in cs
only_cs = cs_set - math_set
# the students only in math
only_math = math_set - cs_set
print common_set
print "----"
print only_cs
print "----"
print only_math
Use a list comprehension to filter people that are in both math class and computer science class:
# contains only the students in both original lists
both = [i for i in math_students if i in cs_students]
for student in both:
# interpolating the name of each student in both list
print '{} is enrolled in both classes'.format(student)
# interpolating the number of students in the both list
print '{} students are in both classes'.format(len(both))
Related
i want to run this code
listf = [
{"name":"akram"}
]
for i in listf:
print(listf["name"])
and this eroor happend
line 5, in <module>
print(listf["name"])
TypeError: list indices must be integers or slices, not str
but in another code from another user :
students = [
{"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
{"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
{"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
{"name": "Draco", "house": "Slytherin", "patronus": None},
]
for student in students:
print(student["name"], student["house"], student["patronus"], sep=", ")
and it run normal with the output :
Hermione, Gryffindor, Otter
Harry, Gryffindor, Stag
Ron, Gryffindor, Jack Russell terrier
Draco, Slytherin, None
If you take a look at the second example they accessed students dictionaries via student not students. Let me show it to you differently:
for st in students: # Here I changed student by st
print(st["name"], st["house"], st["patronus"], sep=", ")
Try this will help you make the distinction in your code:
listf = [
{"name":"akram"}
]
for i in listf:
print(i)
Output:
{"name":"akram"}
See? Here i is the dictionary. Here's how you should access it:
listf = [
{"name":"akram"}
]
for i in listf:
print(i["name"])
Need help, a follow up question from one of my previous but a little over my head. I have a list of tuples (s) and a dictionary (dct). For each one of the keys in (s), I need to return a list of tuples containing the matching group key in (dct) and matching key in (s) if the condition below is met:
Condition:
All elements in at least 1 list within a specific group in (dct) is present in the string in (s). if True, return a list of tuples containing the associated group in (dct) and key in (s)
s = [('[0]',
'good morning i live in the city same day deliveries my wille at salmon today will be there today i have an easy ride'),
('[0, 1]',
"christmas is upon us and my father is the greatest of all time and i will celebrate his greatness sad to hear she left"),
('[0]',
'excited to be here i am a boy. thanks man my name is joe", "i live in a city'),
('[0]',
'greetings, today is a good day i go to the village and learn i receive a scholarship')]
dct = {
"group1": [
["i am a boy", "my name is joe", "i live in a city"],
["my name is sam", "i go to school"],
],
"group2": [
["i a stranger", "my present sister", "i love people"],
["my father is here"],
["i go to the village", "i receive a scholarship"],
],
"group3": [
[
"i live in the city",
"my wille at salmon today",
"i have an easy ride",
],
["my father is the greatest", "sad to hear she left"],
[
"today is her birth day",
"i will eat the rice",
"tomorrow is her day",
],
],
}
Expected Results:
[('[0]': 'group3'), ('[0, 1]': 'group3'), ('[0]': 'group1'), ('[0]': 'group2')]
My attempt:
# function to return key for any value
def get_key(val):
for key, value in s.items():
if val == value:
return key
return "key doesn't exist"
out = []
for k, v in dct.items():
for lst in v:
if all(item in s.get('[0,1]') for item in lst):
out[k] = get_key(s.get('[0,1]'))
print(out)
I figured out a solution that works:
out_lst = []
for groupId, lst_lst in dct.items():
for (Id, parag) in s:
for lst in lst_lst:
if all(item in parag for item in lst):
if ((Id, groupId) not in out_lst):
out_lst.append((Id, groupId))
print(out_lst)
This is the code I'm stuck on. For example, if I input in Horror, Action then the output would be
Anabelle=["Horror", "Triller"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Spider_Man=["Action", "Fantasy"]
basically, printing the variable and the list that contains the user input. also if possible, I need to use lists, also don't change the code too much and add comments for each section
my_list= ["Horror, Action, Comedy, Thriller, Mystery, Fantasy, Sci-fi, Romance,
Drama, Dystopian"]
print("All Available Genres " + str(my_list))
Anabelle=["Horror", "Triller"]
Criminal_Minds=["Mystery", "Drama"]
Avengers=["Action", "Fantasy", "Sci-fi"]
Scooby_doo=["Comedy", "Horror"]
Brooklyn_99=["Action", "Comedy" ]
The_fault_in_our_stars=["Romance", "Drama"]
The_tomorrow_war=["Drama", "Sci-Fi"]
Maze_Runner=["Drama", "Dystopian", "Thriller"]
Hunger_Game=["Dystopian", "Sci-Fi", "Thriller"]
Harry_Potter=["Mystery", "Fantasy"]
Fast_Furious=["Action"]
Conjuring=["Horror"]
Fantastic_Beast=["Fantasy"]
Parasite=["Comedy", "Thriller"]
Space_between_us=["Romance"]
Murder_Mystery=["Romance", "Mystery"]
The_Purge=["Dystopian", "Thriller"]
Spider_Man=["Action", "Fantasy"]
variable_strings=['Anabelle', 'Criminal_Minds', 'Avengers', 'Scooby_doo', 'Brooklyn_99', 'The_fault_in_our_stars', 'The_tomorrow_war', 'Maze_Runner', 'Hunger_Game', 'Harry_Potter', 'Fast_Furious', 'Conjuring', 'Fantastic_Beast', 'Parasite', 'Space_between_us', 'Murder_Mystery', 'The_Purge', 'Spider_Man']
newlist = [Anabelle, Criminal_Minds, Avengers, Scooby_doo, Brooklyn_99, The_fault_in_our_stars, The_tomorrow_war, Maze_Runner, Hunger_Game, Harry_Potter, Fast_Furious, Conjuring, Fantastic_Beast, Parasite, Space_between_us, Murder_Mystery, The_Purge, Spider_Man]
user_genre = (input("What movie/show genre do you like to watch?: "))
user_genre = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")
This is quite ugly, but I've tried not to change it too much:
my_list= ["Horror", "Action", "Comedy", "Thriller", "Mystery", "Fantasy", "Sci-fi", "Romance", "Drama", "Dystopian"]
print("All Available Genres " + str(my_list))
movies = {
"Anabelle": ["Horror", "Triller"],
"Criminal_Minds": ["Mystery", "Drama"],
"Avengers": ["Action", "Fantasy", "Sci-fi"],
"Scooby_doo": ["Comedy", "Horror"],
"Brooklyn_99": ["Action", "Comedy" ],
"The_fault_in_our_stars": ["Romance", "Drama"],
"The_tomorrow_war": ["Drama", "Sci-Fi"],
"Maze_Runner": ["Drama", "Dystopian", "Thriller"],
"Hunger_Game": ["Dystopian", "Sci-Fi", "Thriller"],
"Harry_Potter": ["Mystery", "Fantasy"],
"Fast_Furious": ["Action"],
"Conjuring": ["Horror"],
"Fantastic_Beast": ["Fantasy"],
"Parasite": ["Comedy", "Thriller"],
"Space_between_us": ["Romance"],
"Murder_Mystery": ["Romance", "Mystery"],
"The_Purge": ["Dystopian", "Thriller"],
"Spider_Man": ["Action", "Fantasy"],
}
user_genres = (input("What movie/show genre do you like to watch?: "))
user_genres = user_genres.split(", ") if ", " in user_genres else user_genres.split(",")
for (movie, genres) in movies.items():
toPrint = False
for genre in genres:
if genre in user_genres:
toPrint = True
if toPrint:
print(movie + " [" + ", ".join(genres) + "]")
I'm not 100% sure if this is what you are asking for but here is some code that
-iterates through movies
-checks if genre is in each movie''
if it is, prints movie name.
Simply add this to the end of your code
#Splitting user request
user_genre_s = user_genre.split(", ") if ", " in user_genre else user_genre.split(",")
movies_found = 0
print(f"The following movies were found for genres {user_genre}:")
for movie in newlist:
#testing if value was found in each movie's list
for genre in user_genre_s:
if genre in movie:
print(variable_strings[newlist.index(movie)].replace("_"," "))#printing movie name if found, replacing underscores with spaces to make it look nicer
movies_found += 1
if movies_found == 0:
print(":( no match was found")#Telling user if none are found.
However you may want to lower() all of the genres as users may not enter capitals
I'm trying to write a function, where given names (which are always just First name, Last Name), and the function collects names with the same first name. So far I got this, but I don't know how to proceed to get back the full names in the end.
def same_first_name(people):
for i in range(len(people)):
b=people[i].split()
print(b)
if b[0] == b[0]:
for example :
same_first_name(["Anna Smith", "Barbara Wia", "Anna Brien"])
returns
["Anna Smith", "Anna Brien"]
I'm not 100% clear what you're trying to achieve, but here is a function which accepts a list of names, and makes a dictionary, where the keys are first names, and the values are lists of surnames of people who have the key as their first name:
def same_first_name(people):
split_names = [p.split() for p in people]
first_names_set = set(p[0] for p in split_names)
first_names_dict = {
first_name: [p[1] for p in split_names if p[0] == first_name]
for first_name in first_names_set
}
return first_names_dict
people = ["John Smith", "John Rogers", "Jack Jones", "Jack Smith", "Bill Bong"]
print(same_first_name(people))
Console output:
{'Jack': ['Jones', 'Smith'], 'Bill': ['Bong'], 'John': ['Smith', 'Rogers']}
Given the clarification in your comment, here is a list, where every person is added, who share the same first name with at least one other person in the list:
def same_first_name(people):
split_names = [p.split() for p in people]
first_names_list = [p[0] for p in split_names]
first_names_set = set(first_names_list)
first_name_counts_dict = {
first_name: first_names_list.count(first_name)
for first_name in first_names_set
}
duplicated_first_names = [
p for p in people if first_name_counts_dict[p.split()[0]] >= 2
]
return duplicated_first_names
people = ["John Smith", "John Rogers", "Jack Jones", "Jack Smith", "Bill Bong"]
print(same_first_name(people))
Console output:
['John Smith', 'John Rogers', 'Jack Jones', 'Jack Smith']
initially i had to create a function that receives the person's attributes and returns a structure that looks like that:
Team:
Name: Real Madrid
President:
Name: Florentino Perez
Age: 70
Country: Spain
Office: 001
Coach:
Name: Carlo Ancelotti
Age: 55
Country: Italy
Office: 006
Coach License: 456789545678
Players:
- Name: Cristiano Ronaldo
Age: 30
Country: Portugal
Number: 7
Position: Forward
Golden Balls: 1
- Name: Chicharito
Age: 28
Country: Mexico
Number: 14
Position: Forward
- Name: James Rodriguez
Age: 22
Country: Colombia
Number: 10
Position: Midfielder
- Name: Lucas Modric
Age: 28
Country: Croatia
Number: 19
Position: Midfielder
This structure also contains info about other clubs . I managed to do this with the following function:
def create_person(name, age, country, **kwargs):
info={"Name": name, "Age": age, "Country": country}
for k,v in kwargs.iteritems():
info[k]=v
return info
I used this function to create a list of nested dictionaries and display the right structure for each team. Example:
teams = [
{
"Club Name": "Real Madrid",
"Club President": create_person("Florentino Perez", 70, "Spain", Office="001"),
"Club's Coach": create_person("Carlo Angelotii", 60, "Italy", Office="006", CoachLicense="456789545678"),
"Players": {
"Real_Player1": create_person("Cristiani Ronaldo", 30, "Portugal", Number="7", Position="Forward", GoldenBalls="1"),
"Real_Player2": create_person("Chicharito", 28, "Mexic", Number="14", Position="Forward"),
"Real_Player3": create_person("James Rodriguez", 22, "Columbia", Number="10", Position="Midfilder"),
"Real_Player4": create_person("Lucas Modric", 28, "Croatia", Number="19", Position="Midfilder")
}
},
{
"Club Name": "Barcelona",
"Club President": create_person("Josep Maria Bartolomeu", 60, "Spain", Office="B123"),
"Club's Coach": create_person("Luis Enrique Martinez", 43, "Spain", Office="B405", CoachLicense="22282321231"),
"Players": {
"Barcelona_Player1": create_person("Lionel Messi", 28, "Argentina", Number="10", Position="Forward", GoldenBalls="3"),
"Barcelona_Player2": create_person("Xavi Hernandez", 34, "Spain", Number="6", Position="Midfilder"),
"Barcelona_Player3": create_person("Dani Alvez", 28, "Brasil", Number="22", Position="Defender"),
"Barcelona_Player4": create_person("Gerard Pique", 29, "Spain", Number="22", Position="Defender")
}
}
]
Everything fine so far.
The part where I got stuck is this: Create a function print_president that receives the team name prints the following output:
Team: Real Madrid
President: Florentino Perez
Age: 70
Country: Spain
Office: 001
I could use a variable to display this but i need a function and I don't know how to work around this. Please help!
When you're trying to solve a problem (or ask a question) first simplify as much as you can. Your print_president() function takes a team name and then prints various pieces of information about the team. Each team is a dictionary with various attributes. So a simplified version of the problem might look like this:
teams = [
{
'name': 'Real Madrid',
'pres': 'Florentino',
},
{
'name': 'Barcelona',
'pres': 'Josep',
},
]
def print_president(team_name):
for t in teams:
# Now, you finish the rest. What should we check here?
...
print_president('Barcelona')
I can't think of a way to do this with just a team name, as you will have to know which dict to look at. I think something like this:
def print_president(team):
print 'Team: {team} President: {president} Age: {age} Country: {country} Office: {office}'.format(
team=team['Club Name'],
president=team['Club President']['Name'],
age=team['Club President']['Age'],
country=team['Club President']['Country'],
office=team['Club President']['Office']
)
If you are thinking of looking through all the teams in the list, then pass in two arguments: teams_list and team_name:
def print_president(teams_list,team_name):
for team in teams_list:
if team_name in team.values():
print 'Team: {team} President: {president} Age: {age} Country: {country} Office: {office}'.format(
team=team['Club Name'],
president=team['Club President']['Name'],
age=team['Club President']['Age'],
country=team['Club President']['Country'],
office=team['Club President']['Office']
)