โจทย์ #2

จาก http://www.codenone.com/node60

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
 
def solve_1(persons):
    def print_if_less_than(p,n=28):
        if (p.age < n):
            print 'Name: %s, Age: %d' % (p.name,p.age)
    map(print_if_less_than,persons)
 
persons = [Person('John',30),
           Person('Mary',25)]
 
solve_1(persons)

เลียนแบบมาเห็นๆ (เขียนด้วย Emacs ล้วนๆ) พยายามใช้ lambda แต่ใช้ if ใน lambda ไม่ได้จนปัญญาต้องทำแบบนี้ไปก่อน

omni_kh's picture

ลองอีกแบบ (ที่คล้ายๆ กัน) ดูบ้าง

class Person:
    all_persons = []
    def __init__(self, name):
        self.name = name
        Person.all_persons.append(self)
    def __repr__(self): 
        return self.name
 
john = Person("John")
john.age = 30
marry = Person("Marry")
marry.age = 25
solve = [p for p in Person.all_persons if p.age > 28]
print solve
sugree's picture
def solve_2(persons):
    def print_if_less_than(arg,n=28):
        name,age = arg
        if age < n:
            print 'Name: %s, Age: %d' % (name,age)
    map(print_if_less_than,persons.items())
 
persons = {'John': 30,
           'Mary': 25}
 
solve_2(persons)
veer's picture

Python 2.5 :-P

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
 
def cnex2(persons, age):
    return reduce(lambda ans, person: ans + [person] if person.age > age else an
s, persons, [])
 
cnex2([Person('John',30), Person('Mary',25)], 28)
class Person:
	def __init__(self,name,age):
		self.name = name
		self.age = age
 
	def isOlderThan(self, age):
		return self.age > age
 
	def __repr__(self):
		return self.name
 
persons = [Person('John',30),
	   Person('Mary',25)]
 
[ person for person in persons if person.isOlderThan(28) ]
persons = {'John': 30, 'Mary': 25}
dict([p for p in persons.items if p[1] > 28])

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น