A problem from python crash course by google - python

The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, … For example, group_list("g", ["a","b","c"]) returns "g: a, b, c". Fill in the gaps in this function to do that.
def group_list(group, users):
members = ___
return ___
print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha"
print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom"
print(group_list("Users", "")) # Should be "Users:"
I have tried sth like this:
members = " "
for i in users:
members += ",".join(i)
return ("{}:{}".format(group, members))
output comes:
Marketing: M,i,k,eK,a,r,e,nJ,a,k,eT,a,s,h,a
Engineering: K,i,mJ,a,yT,o,m
Users:
but it didn't give the expected answer. Can anyone solve it with filling the blanks please ?

You need to join users, not each user separately.
members = ', '.join(users)
return "{}: {}".format(group, members)

def group_list(group, users):
members =", ".join(users)
return(" {}: {}".format(group, members))
print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha"
print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom"
print(group_list("Users", "")) # Should be "Users:"

Try this:
return group + ": " + (", ".join(users))

Check out a more shorter way to achieve same result using the format 'f' method.
def group_list(group, users):
members = ", ".join(users)
return f"{group}: {members}"

Try this one
def group_list(group, users):
members = " "
for i in users:`
members+=",".join(users)
break
return "{}:{}".format(group,members)**
print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha"
print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom"
print(group_list("Users", "")) # Should be "Users:"

Check this out:
def group_list(group, users):
members = ", ".join(users)
return "{}: {}".format(group,members)

This should give desired results:
def group_list(group, users):
members = ""
for user in users:
members += user + ", "
return "{}: ".format(group) + members

Related

Creating emails while accounting for two first names when using input()

My code below works as long as all of the student's name consists of only two names - ex. Julie Andrews. But, when generating the student's emails, I'm trying to account for the students who have two first names - ex. Mary Jane Stewart. I want it to output something like MJStewart123#gmail.org, vs. what my current code will print, which is MJane123#gmail.com - totally ignoring the student's last name.
After hours of researching Google, I have tried updating my create_emails fx to change my original variable first_last = name.split(" ") to something like first, middle, last = name.split(" ") or first_last = name.split(" ", 2) while also, respectively, updating the line utilizing the attribute .append from its original to student_emails.append(first_last[0][0] + first_last1 + first_last[2]+ last_three_sid + "#gmail.com") or student_emails.append(first[0] + middle[0] + last + last_three_sid + "#gmail.com"). All attempts have obviously returned some form of an error...
The attached Stack Overflow article is the closest thing I could find whose logic might be applicable to what I'm trying to accomplish here, specifically the comment by Manfred, but in reading it, I don't know how to apply what they've done to my program... because I don't quite understand what it is that I'm reading... since I'm such a newbie at all this. I'd appreciate any help you can offer.
student_names = []
def create_names():
count = 1
while count <= 5:
name = input("Enter student name, please. ")
student_names.append(name)
count += 1
create_names()
import random
student_ids = []
def create_ids():
student_id = random.randint(111111,999999)
return student_id
def create_id_list():
for name in student_names:
student_ids.append(create_ids())
create_id_list()
student_emails = []
def create_emails():
for name in student_names:
first_last = name.split(" ")
sid = str(student_ids[student_names.index(name)])
len_sid = len(sid)
last_three_sid = sid[len_sid-3:len_sid]
student_emails.append(first_last[0][0] + first_last[1] + last_three_sid + "#gmail.com") #ignores last index if one is provided.
create_emails()
def student_info():
for name in student_names:
name_pos = student_names.index(name)
print("\n" + "name: " + name)
print("id: " + str(student_ids[name_pos]))
print("email: " + student_emails[name_pos])
student_info()
Finding and first and middle initials in a list of names in python
You could do it like this I guess:
student_names = []
def create_names():
count = 1
while count <= 5:
name = input("Enter student name, please. ")
student_names.append(name)
count += 1
create_names()
import random
student_ids = []
def create_ids():
student_id = random.randint(111111,999999)
return student_id
def create_id_list():
for name in student_names:
student_ids.append(create_ids())
create_id_list()
student_emails = []
def create_emails():
for name in student_names:
email_name = ""
first_last = name.split(" ")
for i, v in enumerate(first_last):
if i > len(first_last)-2:
break
email_name+=v[0]
email_name = email_name+first_last[-1]
sid = str(student_ids[student_names.index(name)])
len_sid = len(sid)
last_three_sid = sid[len_sid-3:len_sid]
student_emails.append(email_name + last_three_sid + "#gmail.com") #ignores last index if one is provided.
create_emails()
def student_info():
for name in student_names:
name_pos = student_names.index(name)
print("\n" + "name: " + name)
print("id: " + str(student_ids[name_pos]))
print("email: " + student_emails[name_pos])
student_info()
Result:
Enter student name, please. Julie Andrews
Enter student name, please. Mary Jane Stewart
Enter student name, please. Jack Hendricks
Enter student name, please. Maria Basset Juliett
Enter student name, please. Marco Hansen
name: Julie Andrews
id: 742536
email: JAndrews536#gmail.com
name: Mary Jane Stewart
id: 823274
email: MJStewart274#gmail.com
name: Jack Hendricks
id: 590875
email: JHendricks875#gmail.com
name: Maria Basset Juliett
id: 982168
email: MBJuliett168#gmail.com
name: Marco Hansen
id: 671240
email: MHansen240#gmail.com
The code is too redundant and could be implemented with some simpler structures.
name construction can use split combined with join function
storage can also use dictionaries to store multiple information about the same object, compared to multiple lists so more concise and efficient
The code itself is not a big problem, mainly the syntax structure requires more skilled,let's encourage each other in our endeavours
try this:
import random
info = []
# You can use for loop if you already know how many times it will loop
for i in range(5):
name = input("Enter student name, please:") # get name
student_id = random.randint(111111, 999999) # get id
name_structure = name.split()
email = "{name_abbr}{last_name}{sid}#gmail.com".format(
name_abbr="".join([item[0] for item in name_structure[:-1]]), # Generate initials
last_name=name_structure[-1], # Generate the last part of the name
sid=str(student_id)[-3:] # Generate the id in the mailbox
)
info.append({"name": name, "id": student_id, "email": email}) # Store to the list, or print directly
# Print Information
for item in info:
print("name:", item["name"])
print("id:", item["id"])
print("email:", item["email"])
print()

Is there a way to find a string in a list and print just the list element associated with that string?

I am working on an Employee Management System and would like my user to search for an employee by SSN. Once the employee is found, I'd like to print the list associated with that SSN. Eventually, I'd like to search for an employee by SSN and allow the user to edit the data in the fields as well. Right now, I can't figure out how to associate the SSN search to the list. I can find the SSN, but I don't know how to display it. How do I do that?
employee_info = [ ]
while True: # While loop created to make the script constantly run
counter = len(employee_info) # Counter created so that the user will know how many entries there are
print('There are', '(', (int(counter)), ')', 'employees in the system.\n')
add_new = input('Would you like to add a new employee to the system, find an employee\'s record by SSN, change an employee\'s information or view all employee entries in the system?\
To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL." To find an employee, type: "FIND." To change employee info, type: "CHANGE."\n'\
) #Added option to add an employee, find an employee by SSN, change information or to view all employees currently the system
if add_new == 'ADD':
while True: # Loop created to input employees with option to quit
employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')]
employee_info.append(employee_index)
more_employees = input('Would you like to add another employee? Y or N.\n')
if more_employees == 'Y':
continue
elif more_employees == 'N':
break
elif add_new == 'VIEW ALL':
for employee_index in employee_info:
print(' -----------------', employee_index[0], '-----------------\n')
print('SSN:', employee_index[1], '\n')
print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
print('Email:', employee_index[3], '\n')
print('Salary:', '$' + str(employee_index[4]), '\n')
print(' ----------------------------------------------------')
elif add_new == "FIND":
find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
if find_emp in employee_index:
You can parse through every employee in the list, and if employee[1] == find_emp i.e. if the serial number matches, you can print the employee's details.
elif add_new == "FIND":
find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
found = False
for employee in employee_info:
if employee[1] == find_emp:
print(' -----------------', employee_index[0], '-----------------\n')
print('SSN:', employee_index[1], '\n')
print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
print('Email:', employee_index[3], '\n')
print('Salary:', '$' + str(employee_index[4]), '\n')
print(' ----------------------------------------------------')
found = True
if found == False:
print("Employee not found!")
If the employee is not found, you print the appropriate error message.
Instead of a dict try using key pair values like this
mydict = {"SSN": 465736283, "Name": 'Some Dude'}
But have it like this
{
"employee": {
"SSN": "1574083",
"username": "gustog",
"full_name": "Don Won",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
"bio": "This is my bio",
"website": "http://donwon.gov",
"counts": {
"media": 1320,
"follows": 420,
"followed_by": 3410
}
}
This might let you store the info better and then retrieved it faster instead of looping over a array
Looks like you're reading in a list of employee indexes, and each employee index is a list of five elements, with the second of five being the SSN. So you could run through the list of 5-item-lists, checking the 2nd of the 5 for a match to the SSN. So...
def match_the_ssn(list_of_lists, ssn):
for item in list_of_lists:
try:
if item[1] == ssn:
print(item)
return item
except:
pass
return
Something along these lines.... Run through the list, looking at each sublist. For each sublist, check if sublist[1] is the ssn you want. If so, you've got the sublist right there to do with what you want.

Creating a subject and grading system in Python

I am trying to create a gradingsystem for a UNI project.
we are told to have 3 global lists:
Emner = ["INFO100","INFO104","INFO110","INFO150","INFO125"]
FagKoder = [["Informasjonsvitenskap","INF"],["Kognitiv vitenskap","KVT"]
Karakterer=[["INFO100","C"],["INFO104","B"],["INFO110","E"]]
With these lists we are suppost to create a way to view the subjects(Emner), with grades from Karakterer, but we should also be able to view subjects without grades. It should be displayed like this:
We should also be able to add new subjects in (Emner) and add new Grades in (Karakterer). All of this should be displayed as in the picture above.
I have been trying all different kind of ways of doing this, but i keep returning to one of two problems. Either im not able to print a subject without a grade, or if i add a new subject(Emne), and want to add a grade(Karakter) i am not able to place it to the right Subject, as it just saves at the first one without a grade.
hope anyone can help me with this, going crazy here!
Code i have so far:
def emneliste():
global Emner
global Karakterer
emne,kar = zip(*Karakterer)
ans = [list(filter(None, i)) for i in itertools.zip_longest(Emner,kar)]
def LeggTilEmne():
global Karakterer
global Emner
nyttEmne = input("Skriv ny emnekode (4Bokstaver + 3 tall): ")
if nyttEmne not in Emner:
while re.match('^[A-Å]{3,4}[0-9]{3}$',nyttEmne):
Emner.append(nyttEmne)
print(nyttEmne + " Er lagt til!")
start()
print("Feil format")
LeggTilEmne()
else:
print("Dette Emnet er allerede i listen din")
start()
def SettKarakter():
global Karakterer
global Emner
VelgEmne = input("Hvilke emne? ")
Emne,Karakter = zip(*Karakterer)
if str(VelgEmne) not in str(Emner):
print("Dette faget er ikke i din liste")
feil = input("om du heller ønsket å opprette fag trykk 2, ellers trykk enter ")
if feil == str(2):
LeggTilEmne()
else:
start()
else:
if str(VelgEmne) in str(Karakterer):
index = Karakterer.index([VelgEmne,"C"])
Karakterer.pop(index)
SettKar = input("Karakter? ")
Emner.append([VelgEmne,SettKar])
print("Karakter " + SettKar + " Er Lagt til i " + VelgEmne)
start()
else:
SettKar = input("Karakter? ")
if str(VelgEmne) in str(Emner):
index = Emner.index(VelgEmne)
print(index)
Emner.pop(index)
Emner.insert(index,[VelgEmne,SettKar])
print("Karakter " + SettKar + " Er Lagt til i " + VelgEmne)
start()
else:
print("Virker Ikke")
start()
You can make Karakterer a dict instead so that you can iterate through the subjects in Emner and efficiently look up if a subject is in Karakterer with the in operator:
Karakterer = dict(Karakterer)
for subject in Emner:
print(*([subject] + ([Karakterer[subject]] if subject in Karakterer else [])))
This outputs:
INFO100 C
INFO104 B
INFO110 E
INFO150
INFO125
Here's an updated GradeHandler class demo. I tried to allow for updating grades, removing subjects, etc.:
__name__ = 'DEMO'
class GradeHandler(object):
EMNER = ["INFO100","INFO104","INFO110","INFO150","INFO125"]
FAGKODER= [["Informasjonsvitenskap","INF"],["Kognitiv vitenskap","KVT"]]
KARAKTERER = [["INFO100","C"],["INFO104","B"],["INFO110","E"]]
def __init__(self):
self.Emner = self.EMNER
self.FagKoder = self.FAGKODER
self.Karakterer = self.KARAKTERER
self.__create_grade_dict()
def remove_subject(self, subject_name):
"""
Remove a subject ot the classes class list variable.
"""
try:
self.Emner = [i for i in self.EMNER if i != subject_name]
self.__create_grade_dict()
except ValueError:
pass
def add_subject(self, subject_name):
"""
Append a subject ot the classes class list variable.
"""
if not subject_name in Emner:
self.Emner.append(subject_name)
self.__create_grade_dict()
def __create_grade_dict(self, grade_dict=None):
"""
Split grades matrix into separate parts; Create and set a dictionary of values.
"""
if grade_dict is None:
self.grade_dict = dict()
sub, grade = zip(*self.Karakterer)
karakterer_dict = {k:v for k, v in list(zip(sub, grade))}
for i in self.Emner:
if i in karakterer_dict.keys():
self.grade_dict[i] = karakterer_dict[i]
else:
self.grade_dict[i] = ''
def update_grade(self, subject_name, grade='A'):
"""
Update a grade in the grade dictionary.
Will also add a subject if not alrady in the dictionary.
"""
try:
self.grade_dict[subject_name] = grade
except (KeyError, ValueError):
pass
def print_grades(self, subject_name=None):
"""
Print dictionary results.
"""
if subject_name is None:
for k, v in self.grade_dict.items():
print('{} {}'.format(k, v))
else:
if subject_name in self.grade_dict.keys():
print('{} {}'.format(subject_name, self.grade_dict[subject_name]))
if __name__ == 'DEMO':
### Create an instance of the GradeHandler and print initial grades.
gh = GradeHandler()
gh.print_grades()
### Append a class
gh.add_subject('GE0124')
gh.print_grades()
### Add grade
gh.update_grade('GE0124', 'B+')
gh.print_grades()
### Update grades
gh.update_grade('GE0124', 'A-')
gh.print_grades()
### Remove subject (will also remove grade.
gh.remove_subject('GE0124')
gh.print_grades()

python program to overload ‘==’ operator to print the details of students having same marks

Here I have to create a class student with following member attributes: roll no, name, age and total marks. Create suitable methods for reading and printing member variables also to overload ‘==’ operator to print the details of students having same marks. Here I can't find way how to overload == operator for marks. Here I have got error.
class Student():
def __init__(self,r_no,name,age,marks):
self.r_no = r_no
self.name = name
self.age = age
self.marks = marks
def displayStudent(self):
print ("Roll no : ", self.r_no, "Name : ", self.name, ", Age: ", self.age, ", Marks: ", self.marks)
def __str__(self):
return "({0},{1},{3},{4})".format(self.r_no,self.name,self.age,self.marks)
def __eq__(self,other):
if(self.marks==other.marks):
return self.marks==other.marks
stu = []
for i in range (1,3):
print("Enter Details for Students %d" % (i))
r_no = int(input("Enter Roll no:"))
name = input("Enter Name:")
age = int(input("Enter Age:"))
marks = input("Enter Marks:")
stu.append(Student(r_no,name,age,marks))
for s in stu:
s.displayStudent()
To report that two students are equal given that they have the same marks the __eq__ function should look like this:
def __eq__(self, other):
return self.marks == other.marks
It returns True if the marks are the same and False otherwise
Then this code returns True and False respectively.
print(Student(1, 'test1', 20, 4) == Student(2, 'test2', 30, 4)) # True
print(Student(3, 'test3', 0, 1) == Student(3, 'test3', 0, 2)) # False
Code screenshot
Instead of def __eq__, you need to use an if condition, like
if(stu[0].marks==stu[1].marks):
print("marks of ",stu[0].name,"&",stu[1].name," is same")
else:
print("not same")
Or, if you have more data than just two students, you can use a for loop as well. For more details, check out the image I've linked at the top here.

"None" given when attempting to return the value of dict in Python

I'm trying to return the values of a dict when creating an instance of a class in Python, but I keep getting "None" returned instead.
I'm very new to Python, so I'm sure there is an easy answer to this one.
After running the below:
class TestTwo(object):
def __init__(self):
self.attributes = {
'age': "",
'name' : "",
'location': ""
}
def your_age(self):
self.attributes['age'] = raw_input("What is your age? > ")
self.your_name()
def your_name(self):
self.attributes['name'] = raw_input("What is your name? > ")
self.your_location()
def your_location(self):
self.attributes['location'] = raw_input("Where do you live? > ")
self.results()
def results(self):
print "You live in %s" % self.attributes['location']
print "Your number is %s" % self.attributes['age']
print "Your name is %s" % self.attributes['name']
d = self.attributes
return d
output = TestTwo().your_age()
print output
I end up with this:
MacBook-Pro-2:python johnrougeux$ python class_test.py
What is your age? > 30
What is your name? > John
Where do you live? > KY
You live in KY
Your number is 30
Your name is John
None
Instead of "None", I was expecting "{'age': '30', 'name': 'John', 'location': 'KY'}"
What am I missing?
Only results() returns something. You need to pass its return value along the call chain by returning it in the other functions if you want them to return something, too:
def your_age(self):
self.attributes['age'] = raw_input("What is your age? > ")
return self.your_name()
def your_name(self):
self.attributes['name'] = raw_input("What is your name? > ")
return self.your_location()
def your_location(self):
self.attributes['location'] = raw_input("Where do you live? > ")
return self.results()
Of course this kind of chaining is extremely ugly; but I'm sure you already know that. If not, rewrite your code like this:
in each of those functions, just set the value and do not call one of your other functions. Then add a function such as this:
def prompt_data(self):
self.your_age()
self.your_name()
self.your_location()
In the code using the class, do this:
t2 = TestTwo()
t2.prompt_data()
output = t2.results()
the function your_age() doesn't return any values, of course output is None

Categories