I have a class "PushInfo"
And generate 300 PushInfo object in list
I want remove duplicate userid and ip in the list
Here is my code:
from faker import Faker
import random
def RemovePustListDuplicateData(PushList):
return list(set([(x.userid, x.ip) for x in PushList]))
def FakeData(number):
PushList = []
fake = Faker()
accountList = [('john','127.0.0.1'),('john','127.0.0.1'),('amy','127.0.0.1'),
('lia','140.112.1.9'),('julia','140.112.1.9'),
('asuka','140.112.1.9'),('roy','140.112.1.9'),('stacie','140.112.1.9'),('ben','123.964.123.41'),
('yich','127.0.0.1'),('beef','127.0.0.1'),('aloha','235.151.123.1'),('yamaha','235.151.123.1')]
for i in range(0,number):
user = random.choice(accountList)
PushList.append(PushInfo(fake.name(),
user[0],
fake.text(max_nb_chars=10),
fake.date(pattern="%Y-%m-%d"),
user[1]
))
return PushList
class PushInfo:
def __init__(self, name, userid, content, time,ip=''):
self.name = name
self.userid = userid
self.content = content
self.time = time
self.ip = ip
PushList = FakeData(300)
print("top 10 push in list:")
for push in PushList[:10]:
print("name:"+push.name+" id:"+push.userid+" content:"+push.content+" time:"+push.time+" ip:"+push.ip)
print("\nremove duplicate userid and ip data")
print(RemovePustListDuplicateData(PushList))
https://repl.it/#YichLin/Remove-object-in-list/
The example code is return tuple list
[(userid,ip),(userid,ip)....]
But the result I want is
[PushInfo(some data),PushInfo(some data),.....]
How to achieve this result?
Try this:
from faker import Faker
import random
def RemovePustListDuplicateData(PushList):
return list(set(PushList))
def FakeData(number):
PushList = []
fake = Faker()
accountList = [('john','127.0.0.1'),('john','127.0.0.1'),('amy','127.0.0.1'),
('lia','140.112.1.9'),('julia','140.112.1.9'),
('asuka','140.112.1.9'),('roy','140.112.1.9'),('stacie','140.112.1.9'),('ben','123.964.123.41'),
('yich','127.0.0.1'),('beef','127.0.0.1'),('aloha','235.151.123.1'),('yamaha','235.151.123.1')]
for i in range(0,number):
user = random.choice(accountList)
PushList.append(PushInfo(fake.name(),
user[0],
fake.text(max_nb_chars=10),
fake.date(pattern="%Y-%m-%d"),
user[1]
))
return PushList
class PushInfo:
def __init__(self, name, userid, content, time,ip=''):
self.name = name
self.userid = userid
self.content = content
self.time = time
self.ip = ip
def __eq__(self, other):
return self.userid==other.userid and self.ip==other.ip
def __hash__(self):
return hash(('userid', self.userid, 'ip', self.ip))
def __repr__(self):
return str(self.userid) + ' ' + str(self.ip)
PushList = FakeData(300)
print("top 10 push in list:")
for push in PushList[:10]:
print("name:"+push.name+" id:"+push.userid+" content:"+push.content+" time:"+push.time+" ip:"+push.ip)
print("\nremove duplicate userid and ip data")
print(RemovePustListDuplicateData(PushList))
You need to implement eq and hash methods in order to check whether two objects are same.
Change the RemovePustListDuplicateData(PushList) function as follows:-
def RemovePustListDuplicateData(PushList):
object_memo = set()
final_list = []
for object in PushList:
if (object.userid, object.ip) in object_memo:
continue
else:
final_list.append(object)
object_memo.add((object.userid, object.ip))
return final_list
I hope it helps!
Related
Trying to generate school timetable with lab hours.
Kindly help me to solve this error! Thanks in advance.
Here is my code!
#planning_solution
class TimeTable:
timeslot_list: list[Timeslot]
timeslot_list1: list[Timeslot]
room_list: list[Room]
lesson_list: list[Lesson]
lab_list: list[Lab]
score: HardSoftScore
def __init__(self, timeslot_list, timeslot_list1, room_list, lesson_list,lab_list,
score=None):
self.timeslot_list = timeslot_list
self.timeslot_list1 = timeslot_list1
self.room_list = room_list
self.lesson_list = lesson_list
self.lab_list = lab_list
self.score = score
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLS")
def get_timeslot_list(self):
return self.timeslot_list
#problem_fact_collection_property(Timeslot)
#value_range_provider("timeslotRangeLB")
def get_timeslot_list1(self):
return self.timeslot_list1
#problem_fact_collection_property(Room)
#value_range_provider("roomRange")
def get_room_list(self):
return self.room_list
#planning_entity_collection_property(Lesson)
def get_lesson_list(self):
return self.lesson_list
#planning_entity_collection_property(Lab)
def get_lab_list(self):
return self.Lab_list
#planning_score(HardSoftScore)
def get_score(self):
return self.score
def set_score(self, score):
self.score = score
def __str__(self):
return (
f"TimeTable("
f"timeslot_list={format_list(self.timeslot_list)},\n"
f"timeslot_list1={format_list(self.timeslot_list1)},\n"
f"room_list={format_list(self.room_list)},\n"
f"lesson_list={format_list(self.lesson_list)},\n"
f"lab_list={format_list(self.lab_list)},\n"
f"score={str(self.score.toString()) if self.score is not None else 'None'}"
f")"
)
Trying to get the 2 timeslots one for lesson(1 hour) and one for lab(2 hour).Here is my #planning_solution.
I defined 2 #planning_entity for both lab & lesson with #value_range_provider.
#planning_entity
class Lab(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot1: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot1 = None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot1 = timeslot1
self.room = room
#planning_variable(Base, value_range_provider_refs=['roomRange', 'timeslotRangeLB'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLB"])
def get_timeslot1(self):
return self.timeslot1
#value_range_provider(range_id = "timeslotRangeLB", value_range_type = Timeslot)
def get_possible_timeslot_list1(self):
return self.subject.teacher.student_group.room_list
def set_timeslot1(self, new_timeslot):
self.timeslot1 = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lab("
f"id={self.id}, "
f"timeslot1={self.timeslot1}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
#planning_entity
class Lesson(Base):
id: int
subject: str
teacher: str
student_group: str
timeslot: Timeslot
room: Room
def __init__(self, id, subject, teacher, student_group, timeslot=None, room=None):
self.id = id
self.subject = subject
self.teacher = teacher
self.student_group = student_group
self.timeslot = timeslot
self.room = room
#planning_variable(Base, value_range_provider_refs=['timeslotRangeLS', 'roomRange'],
graph_type=PlanningVariableGraphType.CHAINED)
#planning_id
def get_id(self):
return self.id
#planning_variable(Timeslot, ["timeslotRangeLS"])
def get_timeslot(self):
return self.timeslot
#value_range_provider(range_id = "timeslotRangeLS", value_range_type = Timeslot)
def get_possible_timeslot_list(self):
return self.subject.teacher.student_group.room_list
# return self.course.teacher.department.room_list
def set_timeslot(self, new_timeslot):
self.timeslot = new_timeslot
#planning_variable(Room, ["roomRange"])
def get_room(self):
return self.room
def set_room(self, new_room):
self.room = new_room
def __str__(self):
return (
f"Lesson("
f"id={self.id}, "
f"timeslot={self.timeslot}, "
f"room={self.room}, "
f"teacher={self.teacher}, "
f"subject={self.subject}, "
f"student_group={self.student_group}"
f")"
)
The issue is you defined #value_range_provider(range_id = "timeslotRangeLS") on both your #planning_solution and your #planning_entity. You can only have one; if you want the value range to apply to every entity, do it on the #planning_solution. If you want each planning entity to have it own value range that only applies to it, do it on the #planning_entity. If you want to combine a value range that contains common values for all entities, and a value range that is per entity, use a #value_range_provider on the #planning_solution, and a #value_range_provider on the entity, but give them different ids (ex: #value_range_provider(range_id = "timeslotRangeLSSolution") and #value_range_provider(range_id = "timeslotRangeLSEntity"), and in the #planning_variable, use both range ids in the list (ex: #planning_variable(Room, ["timeslotRangeLSSolution", "timeslotRangeLSEntity"])
I am trying to get one account from some branch but somewhere i am missing something. This line is from method -> but the result is <main.SavingAccount object at 0x000001F2563CEFD0>
class Branch:
def __init__(self, branch_code, city):
self.branch_code = branch_code
self.city = city
self.account_list = []
self.loan_list = []
def getAccount(self, acc_no):
for account in self.account_list:
if account.acc_no == acc_no:
return account
print(f2.getAccount(300005))
try this:
class Branch:
def __init__(self, branch_code, city):
self.branch_code = branch_code
self.city = city
self.account_list = []
self.loan_list = []
def getAccount(self, acc_no):
for account in self.account_list:
if account == acc_no:
return account
f2 = Branch(123,"NY")
f2.account_list=[111,222,300005]
print(f2.getAccount(300005))
I am still learning Python and I have a problem. If my question isn't that clear, please be nice!
Is it possible that while using a list, I can delete an object from the list if only one object matches
So for example:
driver.addDriver(Driver("Ben", "BBB"))
driver.removeDriver("Ben", "123")
Can I remove the driver name and print as None while still showing the vehicle number. Thanks.
class Driver:
def __init__(self, name, vehNo):
self._name = name
self._vehNo = vehNo
#property
def name(self):
return self._name
#property
def vehNo(self):
return self._vehNo
#vehNo.setter
def vehNo(self, newVehNo):
self._vehNo = newVehNo
def __str__(self):
return 'Driver Name: {} Vehicle Number: {}'.format(self._name, self._vehNo)
class TransportServices:
def __init__(self):
self._drivers = []
def searchDriver(self, name = None, vehNo = None):
for d in self._drivers:
if d.name == name and d.vehNo == vehNo:
return d
return None
#############################################################################
def addDriver(self, driver):
d = self.searchDriver(driver.name)
if d is None:
self._drivers.append(driver)
return True
else:
return False
#############################################################################
def removeDriver(self, name = None, vehNo = None):
d = self.searchDriver(name, vehNo)
if d is None:
return False
else:
self._drivers.remove(d)
#############################################################################
def __str__(self):
drivers = [str(d) for d in self._drivers]
return "{} ".format('\n'.join(drivers))
def main():
driver = TransportServices()
driver.addDriver(Driver("Alan", "AAA"))
driver.addDriver(Driver("Ben", "BBB"))
driver.removeDriver("Ben", "123")
print(driver)
main()
Basically what you are looking for is not deleting the object but updating it.
You can update the corresponding object as below:
for driver in self.drivers:
if driver.name == 'Bob': # or driver vehNo == 'BBB'
driver.name = None
Also for your case,
you could rather use a dictionary which is the same
as a hash map in Java.
You can do some thing like below:
self.drivers = {}
self.driver['vehicle Num'] = theDriverObject
so that when you need to access or update you can do it instantly i.e. O(1) without having to loop through all the drivers.
I started learning python. Here is a simple program:
class StudentRepo:
def __init__(self):
self.student_list = []
def add(self, student):
self.student_list.append(student)
def get_list(self):
self.student_list
class Student:
def __init__(self, name, age):
self.age = age
self.name = name
from models.student.Student import Student
from services.student.StudentRepo import StudentRepo
s1 = Student("A", 10)
s2 = Student("B", 11)
# What is the issue here ?
StudentRepo.add(s1)
StudentRepo.add(s2)
studentList = StudentRepo.get_list()
for student in studentList:
print(student.name)
What is the issue with s1 = Student("A", 10) ?
There are two mistakes in your code. First, this:
def get_list(self):
self.student_list
should be:
def get_list(self):
return self.student_list
Second, you're using the class StudentRepo where you should be using an instance of StudentRepo:
s1 = Student("A", 10)
s2 = Student("B", 11)
my_roster = StudentRepo()
my_roster.add(s1)
my_roster.add(s2)
studentList = my_roster.get_list()
for student in studentList:
print(student.name)
Here is my class:
class ManagementReview(object):
"""Class describing ManagementReview Object.
"""
# Class attributes
id = 0
Title = 'New Management Review Object'
fiscal_year = ''
region = ''
review_date = ''
date_completed = ''
prepared_by = ''
__goals = [] # List of <ManagementReviewGoals>.
__objectives = [] # List of <ManagementReviewObjetives>.
__actions = [] # List of <ManagementReviewActions>.
__deliverables = [] # List of <ManagementReviewDeliverable>.
__issues = [] # List of <ManagementReviewIssue>.
__created = ''
__created_by = ''
__modified = ''
__modified_by = ''
def __init__(self,Title='',id=0,fiscal_year='',region='',review_date='',
date_completed='',prepared_by='',created='',created_by='',
modified='',modified_by=''):
"""Instantiate object.
"""
if id:
self.setId(id)
if Title:
self.setTitle(Title)
if fiscal_year:
self.setFiscal_year(fiscal_year)
if region:
self.setRegion(region)
if review_date:
self.setReview_date(review_date)
if date_completed:
# XXX TODO: validation to see if date_completed pattern matches ISO-8601
self.setDate_completed(date_completed)
if prepared_by:
self.setPrepared_by(prepared_by)
if created:
# XXX TODO: validation to see if date_completed pattern matches ISO-8601
self.setCreated(created)
else:
self.setCreated(self.getNow())
if created_by:
self.setCreated_by(created_by)
self.__modified = self.getNow()
if modified_by:
self.__modified_by = modified_by
def __str__(self):
return "<ManagementReview '%s (%s)'>" % (self.Title,self.id)
def __setattr__(self, name, value): # Override built-in setter
# set the value like usual and then update the modified attribute too
object.__setattr__(self, name, value) # Built-in
self.__dict__['__modified'] = datetime.now().isoformat()
def getActions(self):
return self.__actions
def addAction(self,mra):
self.__actions.append(mra)
def removeAction(self,id):
pass # XXX TODO
I have this test:
from datetime import datetime
import random
import unittest
from ManagementReview import ManagementReview, ManagementReviewAction
# Default Values for ManagementReviewAction Object Type
DUMMY_ID = 1
DUMMY_ACTION = 'Action 1'
DUMMY_OWNER = 'Owner 1'
DUMMY_TITLE = 'Test MR'
DUMMY_FISCAL_YEAR = '2011'
DUMMY_REGION = 'WO'
DUMMY_REVIEW_DATE = '2009-01-18T10:50:21.766169',
DUMMY_DATE_COMPLETED = '2008-07-18T10:50:21.766169'
DUMMY_PREPARED_BY = 'test user'
DUMMY_CREATED = '2002-07-18T10:50:21.766169'
DUMMY_CREATED_BY = 'test user 2'
DUMMY_MODIFIED = datetime.now().isoformat()
DUMMY_MODIFIED_BY = 'test user 3'
class TestManagementReviewSetAction(unittest.TestCase):
def setUp(self):
self.mr = ManagementReview(DUMMY_TITLE,DUMMY_ID,fiscal_year=DUMMY_FISCAL_YEAR,region=DUMMY_REGION,
review_date=DUMMY_REVIEW_DATE,date_completed=DUMMY_DATE_COMPLETED,
prepared_by=DUMMY_PREPARED_BY,created=DUMMY_CREATED,
created_by=DUMMY_CREATED_BY,modified=DUMMY_MODIFIED,
modified_by=DUMMY_MODIFIED_BY)
def tearDown(self):
self.mr = None
def test_add_action(self):
for i in range(1,11):
mra = ManagementReviewAction(i,'action '+str(i),'owner '+str(i))
self.mr.addAction(mra)
self.assertEqual(len(self.mr.getActions()),10)
def test_remove_action(self):
print len(self.mr.getActions())
for i in range(1,11):
mra = ManagementReviewAction(i,'action '+str(i),'owner '+str(i))
self.mr.addAction(mra)
self.mr.removeAction(3)
self.assertEqual(len(self.mr.getActions()),9)
if __name__ == '__main__':
unittest.main()
The first test passes. That is, self.mr.getActions() has 10 actions.
However, when I run the 2nd test, test_remove_action, the value for len(self.mr.getActions()) is 10. At this point, though, it should be 0.
Why is this?
Thanks
see if you are keeping track of actions in a class attribute of ManagementReview as opposed to an instance attribute
A class attribute will be something like
class Spam(object):
actions = []
and an instance attribute will look something like
class Spam(object):
def __init__(self):
self.actions = []
What happens is that actions = [] is executed when the class is created and all instances of the class share the same list.
EDIT:
In light of your update, I can see that this is definitely what is going on