WeightsAndMeasures/신재동

~cpp 
class Turtle:
    def __init__(self, weight, strength):
        self.weight = weight
        self.strength = strength
        self.canAmount = strength - weight
        
def inputATurtle():
    numsStr = raw_input().split(' ')
    if(numsStr == ['']):
        return (0,0)
    weight = int(numsStr[0])
    strength = int(numsStr[1])
    return (weight, strength)

def inputTurtles(turtles):
    while(True):
        (weight, strength) = inputATurtle()
        if(weight == 0 or strength == 0):
            break
        turtles.append(Turtle(weight, strength))

def turtlesCompare(t1, t2):
    result = 0
    if(t1.canAmount > t2.canAmount):
        result = -1
    elif(t1.canAmount < t2.canAmount):
        result = 1
    return result

def pileUpTurtles(turtles):
    totalWeight = turtles[0].weight
    canAmount = turtles[0].canAmount
    pile = [turtles[0]]
    for t in turtles[1:]:
        if(canAmount >= t.weight):
            canAmount -= t.weight
            if(canAmount > t.canAmount):
                canAmount = t.canAmount
            pile.append(t)
    #showTurtles(pile)
    return len(pile)

def showTurtles(turtles):
    for t in turtles:
        print t.weight, t.strength, t.canAmount
    
if __name__=='__main__':
    turtles = []
    inputTurtles(turtles)
    turtles.sort(cmp = turtlesCompare)
    numOfTurtle = pileUpTurtles(turtles)
    print numOfTurtle

sort()에 비교 함수(turtlesCompare) 넣는데 은근히 힘들었음. 처음에는 C++의 STL에서 vector에 비교 함수 넣는 것과 같으리라고 생각하고 비교 함수를 만들었는데 안되서 확인해보니 파이썬의 리스트에서는 결과를 {-1, 0, 1}로 해야지 제대로 돌아간다는 것을 알았음. --재동

소팅 방식을 바꾸는 데에는 여러가지 방법이 있다.

~cpp 
>>> class A:
...     pass
...
>>> a1=A();a1.foo=30
>>> a2=A();a2.foo=-1
>>> l=[a1,a2]
>>> l.sort(key=lambda x:x.foo)
>>> l[0].foo
-1
>>> l.reverse()
>>> l[0].foo
30
>>> import operator
>>> l.sort(key=operator.attrgetter('foo'))
>>> l[0].foo
-1
>>> l.reverse()
>>> l.sort(cmp=lambda a,b:cmp(a.foo,b.foo))
>>> l[0].foo
-1
>>>

클래스를 사용한다면 스스로 어떻게 정렬될지 아는 놈으로 만드는 것도 좋겠다.

~cpp 
>>> class A:
	def __init__(self,foo):
		self.foo=foo
	def __cmp__(self,anA):
		return cmp(self.foo,anA.foo)
	def __repr__(self):
		return '<A : %d>'%self.foo

	
>>> l=[A(i) for i in xrange(5,0,-1)]
>>> l
[<A : 5>, <A : 4>, <A : 3>, <A : 2>, <A : 1>]
>>> l.sort()
>>> l
[<A : 1>, <A : 2>, <A : 3>, <A : 4>, <A : 5>]

--JuNe
Retrieved from http://wiki.zeropage.org/wiki.php/WeightsAndMeasures/신재동
last modified 2021-02-07 05:28:24