무냐의 개발일지

[OSSU] <MITx 6.00.1x_Intro CS> Week3/ tuple, list, map 본문

카테고리 없음

[OSSU] <MITx 6.00.1x_Intro CS> Week3/ tuple, list, map

무냐코드 2024. 4. 18. 00:48

Tuples

슬라이싱 가능한데, 리스트랑 다르게 ('one' , ) 이런 식으로 콤마가 꼭 찍혀나온다

 

#tuples

def get_data(aTuple):
    nums = ()
    words = ()
    for t in aTuple:
        nums = nums + (t[0], )
        if t[1] not in words:
            words = words + (t[1], )
    min_nums = min(nums)
    max_nums = max(nums)
    unique_words = len(words)
    return (min_nums, max_nums, unique_words)


print(get_data(((1,'mine'), (3, 'yours'), (5, 'ours'), (8, 'mine'))))

#결과
(1, 8, 3)

#혹은 끝에를 이렇게 해도 됨
(small, large, words) = get_data((((1,'mine'), (3, 'yours'), (5, 'ours'), (8, 'mine'))))

print(small)
print(large)
print(words)

 

👩‍💻 Odd tuples

ESTIMATED TIME TO COMPLETE: 5 minutes

Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple').

 

💡 풀이

#Ex. Odd Tuples
def oddTuples(aTup):
    res = ()
    for i in range(0,len(aTup),2):
        res = res + (aTup[i], )
    return res


# 혹은
def oddTuples(aTup):
	return aTup[::2]

 


 

문자 자체를 더해줄거면, 그냥 바로 문자로 더해주는 오른쪽이 훨씬 더 깔끔하다 ! 

 

기본 중의 기본인데 되게 많이, 자주 쓰이는 애들이다 ! 

특히 list, string을 왔다갔다 할 수 있다. list(str) 혹은 ''.join(llist) 으로

 

 

| sorted vs sort

 

 

중요하다. print(str.sort())를 하면 None이 나온다. return 하는 값이 없고, 그냥 str 자체를 바꾸기만 하기 때문

 


 

map 은 하나의 funtion을 list에 각각 적용해줄 수 있다 

def applyToEach(L, f):
	for i in range(len(L)):
        L[i] = f(L[i])

testList = [1, -4, 8, -9]

#1>>> print(testList) : [5, -20, 40, -45]
def timesFive(a):
    return a * 5
applyToEach(testList, timesFive)
print(testList)

#2 >>> print(testList) :[1, 4, 8, 9]
applyToEach(testList, abs)
print(testList)

#3 >>> print(testList) : [2, -3, 9, -8]
def plusone(a):
    return a+1
applyToEach(testList, plusone)
print(testList)

#4   >>> print testList : [1, 16, 64, 81]
def square(a):
    return a*a
applyToEach(testList, square)
print(testList)

 

이런 식으로 리스트에 함수를 매핑 가능 !! 

 

 


| Dictionary 

 

 

 

👩‍💻 How many (Dictionary)

 

Consider the following sequence of expressions:

animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')

We want to write some simple procedures that work on dictionaries to return information.

First, write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary. For example:
>>> print(how_many(animals))
6

 

💡 풀이 

def how_many(aDict):
    count = 0
    for i in aDict.values():
        count += len(i)
    return count

print(how_many(animals))

결과 : 6

 

💡 풀이 

def biggest(aDict):
    biggestValue = 0
    for key in aDict.keys():
        if len(aDict[key]) > biggestValue:
            biggestValue = len(aDict[key])
    return key

print(biggest(animals))

결과 : d

 

✍️ 해설

모든 values들에 들어있는 총 동물의 수를 구하는 것이다.

각각 value를 루프로 돌면서, 길이를 더해주면 된다.


 

💡 피보나치 수열

def fib_efficient(n, d):
    if n in d:
        return d[n]
    else:
        ans = fib_efficient(n-1, d) + fib_efficient(n-2, d)
        d[n] = ans
        return ans
    
d={1:1, 2:2}
print(fib_efficient(6,d))  #1 2 3 5 8 13

 

 


💡 리스트 복사