Unique Characters
문장에서 사용된 Characters type 문자를 중복없이 순서대로 리스트에 나열하는 함수
Example 1 2 3 4 5 6 7 document = "Todd told Tom to trot to the timber" uniqueCharacters(document) = [' ' , 'T' , 'b' , 'd' , 'e' , 'h' , 'i' , 'l' , 'm' , 'o' , 'r' , 't' ] ' ' < 'T' => True 'T' < 't' => True
My Answer 1 2 3 4 5 6 7 def uniqueCharacters (document) : return sorted(list(set(document))) def uniqueCharacters (document) : return sorted(list(set(document)), reverse=True )
Correct Scholarships
예시 설명을 참고 해주세요.
Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 bestStudents = [3 , 5 ] scholarships = [3 , 5 , 7 ] allStudents = [1 , 2 , 3 , 4 , 5 , 6 , 7 ] correctScholarships(bestStudents, scholarships, allStudents) = True bestStudents = [3 ] scholarships = [1 , 3 , 5 ] allStudents = [1 , 2 , 3 ] correctScholarships(bestStudents, scholarships, allStudents) = False bestStudents = [3 , 5 ] scholarships = [3 , 5 ] allStudents = [3 , 5 ] correctScholarships(bestStudents, scholarships, allStudents) = False
My Answer 1 2 3 def correctScholarships (bestStudents, scholarships, allStudents) : return set(bestStudents) | set(scholarships) != set(allStudents) and not ((set(bestStudents) | set(scholarships)) - set(allStudents))
Another Answer 1 2 3 4 5 def correctScholarships (bestStudents, scholarships, allStudents) : return len(scholarships) < len(allStudents) and sum([x in allStudents for x in scholarships]) == len(scholarships) and sum([x in scholarships for x in bestStudents])==min(len(bestStudents), len(scholarships)) def correctScholarships (bestStudents, scholarships, allStudents) : return set(bestStudents) <= set(scholarships) < set(allStudents)
Startup Name
스타트업 회사를 차린다고 가정할 때 인기있는 경쟁사의 회사 이름 3개 중 중요한 철자를 골라내는 함수 결국 3개 집합 전체에서 3개 집합의 대칭차집합을 뺀 부분을 골라내는 함수
Example 1 2 3 4 5 companies = ["coolcompany" , "nicecompany" , "legendarycompany" ] startupName(companies) = ['e' , 'l' ] companies = ["nameone" , "nametwo" , "namethree" ] startupName(companies) = ['o' , 't' ]
Another Answer 1 2 3 4 5 6 def startupName (companies) : cmp1 = set(companies[0 ]) cmp2 = set(companies[1 ]) cmp3 = set(companies[2 ]) res = (set(companies[0 ]) | set(companies[1 ]) | set(companies[2 ])) - (set(companies[0 ])^set(companies[1 ])^set(companies[2 ])) return list(sorted(list(res)))
Words Recognition
두 단어에서 공통적인 알파벳을 뺀 나머지 부분을 추출하는 함수
Example 1 2 3 4 word1 = "program" word2 = "develop" wordsRecognition(word1, word2) = ['agmr' , 'delv' ]
My Answer 1 2 3 4 5 def wordsRecognition (word1, word2) : def getIdentifier (w1, w2) : return '' .join(sorted((set(w1) ^ set(w2)) - set(w2))) return [getIdentifier(word1, word2), getIdentifier(word2, word1)]
Another Answer 1 2 3 4 5 6 7 8 9 10 11 def wordsRecognition (word1, word2) : def getIdentifier (w1, w2) : return '' .join(sorted(set(w1) - set(w2))) return [getIdentifier(word1, word2), getIdentifier(word2, word1)] def wordsRecognition (word1, word2) : def getIdentifier (w1, w2) : return "" .join(sorted(frozenset(w1)-frozenset(w2))) return [getIdentifier(word1, word2), getIdentifier(word2, word1)]
Tip list or set to string => join {: .notice}
Transpose Dictionary
Dictionary형태의 데이터 타입의 키, 값이 “설명”, “확장자 명”으로 되어 있는데 이를 “확장자 명”, “설명”으로 구성된 리스트로 바꿔주는 함수
Example 1 2 3 4 5 6 7 8 9 scriptByExtension = { "validate" : "py" , "getLimits" : "md" , "generateOutputs" : "json" } transposeDictionary(scriptByExtension) = [["json" ,"generateOutputs" ], ["md" ,"getLimits" ], ["py" ,"validate" ]]
My Answer 1 2 def transposeDictionary (scriptByExtension) : return sorted([[y, x] for x, y in scriptByExtension.items()])
Another Answer 1 2 def transposeDictionary (scriptByExtension) : return sorted(zip(scriptByExtension.values(), scriptByExtension.keys()))
Doodled Password
비밀번호 낙서? / queue의 FIFO 특성을 deque로 구현하는 함수. / 인덱스 수 만큼 First out Last in(맨 앞 요소)를 반복한다 설명 잘 못하겠으니 밑에 예시를 참고해 주세요
Example 1 2 3 4 5 6 7 digits = [1 , 2 , 3 , 4 , 5 ] doodledPassword(digits) = [[1 , 2 , 3 , 4 , 5 ], [2 , 3 , 4 , 5 , 1 ], [3 , 4 , 5 , 1 , 2 ], [4 , 5 , 1 , 2 , 3 ], [5 , 1 , 2 , 3 , 4 ]]
My Answer 1 2 3 4 5 6 7 from collections import dequedef doodledPassword (digits) : n = len(digits) res = [deque(digits) for _ in range(n)] [[res[x].insert(len(res)-1 , res[x].popleft()) for y in range(x)] for x in range(1 , len(res))] return [list(d) for d in res]
Another Answer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from collections import dequedef doodledPassword (digits) : n = len(digits) res = [deque(digits) for _ in range(n)] map(lambda i: res[i].rotate(-i), range(n)) return [list(d) for d in res] from collections import dequedef doodledPassword (digits) : n = len(digits) res = [deque(digits) for _ in range(n)] deque(map(lambda x,y: x.rotate(y), res, range(n,0 ,-1 )), 0 ) return [list(d) for d in res] from collections import dequedef doodledPassword (digits) : n = len(digits) res = [deque(digits) for _ in range(n)] deque(map(lambda x: x[1 ].rotate(-x[0 ]), enumerate(res)), 0 ) return [list(d) for d in res]
Frequency Analysis
암호문으로 변경하는 encrypt 함수. 평문에서 가장 빈도수가 높은 문자로 치환한다.
Example 1 2 3 encryptedText = "$~NmiNmim$/NVeirp@dlzrCCCCfFfQQQ" frequencyAnalysis(encryptedText) = 'C'
My Answer 1 2 3 4 5 6 7 from collections import Counterdef frequencyAnalysis (encryptedText) : return Counter(encryptedText).most_common(1 )[0 ][0 ] def frequencyAnalysis (encryptedText) : return list(set(encryptedText))[[encryptedText.count(x) for x in list(set(encryptedText))].index(max([encryptedText.count(x) for x in list(set(encryptedText))]))]
Another Answer 1 2 3 4 from collections import Counterdef frequencyAnalysis (encryptedText) : return sorted(encryptedText, key=encryptedText.count, reverse=True )[0 ]
Cyclic Name
문자열이 주어지면 원하는 길이로 문자열이 순환하는 문자열 반환하는 함수
Example 1 2 3 4 name = 'jihyuk' n = 12 cyclicName(name, n) = 'jihyukjihyuk'
My Answer 1 2 3 4 5 6 7 8 9 10 11 from itertools import cycledef cyclicName (name, n) : gen = (x for x in cycle(name)) res = [next(gen) for _ in range(n)] return '' .join(res) def cyclicName (name, n) : gen = cycle(name) res = [next(gen) for _ in range(n)] return '' .join(res)
cycle 함수로 만든 객체는 generator 이다
Memory Pills
리스트의 요소중 길이가 짝수인 요소 다음부터 3개 요소를 추출하는 함수. 단, 추출된 요소가 3개 미만일 때 부족한 요소는 “”로 채운다.
Example 1 2 3 4 5 6 7 pills = ["Notforgetan" , "Antimoron" , "Rememberin" , "Bestmedicen" , "Superpillsus" ] => 11 , 9 , 10 , 11 , 12 memoryPills(pills) = ["Bestmedicen" , "Superpillsus" , "" ]
Another Answer 1 2 3 4 5 6 7 8 9 10 11 12 13 from itertools import dropwhiledef memoryPills (pills) : gen = dropwhile(lambda x: len(x)%2 !=0 , pills + ["" ]*3 ) next(gen) return [next(gen) for _ in range(3 )] from itertools import dropwhile, cycle, chaindef memoryPills (pills) : gen = chain(dropwhile(lambda x: len(x)%2 > 0 ,pills),cycle(["" ])) next(gen) return [next(gen) for _ in range(3 )]
Float Range
시작, 끝, 간격을 입력값으로 주면(정수, 실수 둘다 가능) 시작부터 끝이전까지 간격을 순회로 하는 리스트를 반환하는 함수
Example 1 floatRange(-0.9 , 0.45 , 0.2 ) = [-0.9 , -0.7 , -0.5 , -0.3 , -0.1 , 0.1 , 0.3 ]
My Answer 1 2 3 4 5 from itertools import takewhile, countdef floatRange (start, stop, step) : gen = takewhile(lambda x: x < stop, count(start, step)) return list(gen)
Another Answer 1 2 3 4 5 from itertools import islicedef floatRange (start, stop, step) : gen =islice(map(lambda x:float(x)/100000.0 ,list(range(int(start*100000 ),int(stop*100000 ),int(step*100000 )))),int((stop-start)/step)+1 ) return list(gen)
Rock Paper Scissors
N명의 사람이 있다고 했을 때 모든 사람이 모든 사람들과 2번씩 경기를 할 수 있도록 명단을 짜주는 함수
Example 1 2 3 players = ["trainee" , "warrior" , "ninja" ] rockPaperScissors(players) =
My Answer 1 2 3 4 from itertools import permutationsdef rockPaperScissors (players) : return sorted(list(permutations(players, 2 ))
Kth Permutation
n개의 순열 조합 중 n번째 순열을 뽑는 함수
Example 1 2 3 4 numbers = [1 , 2 , 3 , 4 , 5 ] k = 4 kthPermutation(numbers, k) = [1 , 2 , 4 , 5 , 3 ]
My Answer 1 2 3 4 from itertools import permutationsdef kthPermutation (numbers, k) : return list(permutations(numbers, len(numbers)))[k-1 ]
Another Answer 1 2 3 4 from itertools import islice, permutationsdef kthPermutation (numbers, k) : return next(islice(permutations(numbers), k - 1 , None ))
Crazyball
n개의 리스트에서 k개를 뽑아 조합하는 함수. (combination)
Example 1 2 3 4 5 6 7 players = ["Ninja" , "Warrior" , "Trainee" , "Newbie" ] k = 3 crazyball(players, k) = [['Ninja' , 'Warrior' , 'Trainee' ], ['Ninja' , 'Warrior' , 'Newbie' ], ['Ninja' , 'Trainee' , 'Newbie' ], ['Warrior' , 'Trainee' , 'Newbie' ]]
My Answer 1 2 3 4 from itertools import combinationsdef crazyball (players, k) : return list(combinations(sorted(players), k))
Twins Score
두 개의 리스트를 입력값으로 받아 같은 인덱스끼리 합하여 하나의 리스트로 반환하는 함수
Example 1 2 3 4 b = [22 , 13 , 45 , 32 ] m = [28 , 41 , 13 , 32 ] twinsScore(b, m) = [50 , 54 , 58 , 64 ]
My Answer 1 2 3 4 5 6 import numpy as npdef twinsScore (b, m) : return list(np.array(b)+np.array(m)) def twinsScoer (b,m) : return [x[0 ]+x[1 ] for x in list(zip(b,m))]
Another Answer 1 2 3 4 5 def twinsScore (b, m) : return map(sum, zip(b,m)) def twinsScore (b, m) : return [u + v for u, v in zip(b, m)]
Pressure Gauges
두 개의 리스트를 입력 받으면 각각의 인덱스에 맞게 짝지어 작은 값을 1행 리스트에 큰 값을 2행 리스트에 묶어 반환하는 함수
Example 1 2 3 4 5 morning = [3 , 5 , 2 , 6 ] evening = [1 , 6 , 6 , 6 ] pressureGauges(morning, evening) = [[1 , 5 , 2 , 6 ], [3 , 6 , 6 , 6 ]]
My Answer 1 2 3 4 5 def pressureGauges (morning, evening) : return [list(map(min, zip(morning,evening))), list(map(max, zip(morning,evening)))] def pressureGauges (morning, evening) : return [[min(x) for x in zip(morning, evening)], [max(x) for x in zip(morning, evening)]]
Another Answer 1 2 3 4 5 def pressureGauges (morning, evening) : return list(zip(*map(sorted, zip(morning, evening)))) def pressureGauges (morning, evening) : return [list(map(op, zip(morning, evening))) for op in [min, max]]
zip과 *의 조합으로 여러개 리스트를 받을 때 각각의 인덱스에 해당하는 요소끼리 합칠 수 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 a = [1 ,2 ,3 ,4 ] b = [1 ,2 ,3 ,4 ] c = [[1 ,2 ],[3 ,4 ],[5 ,6 ]] d = [[1 ,2 ,10 ],[3 ,4 ,11 ],[5 ,6 ,12 ]] list(zip(a,b)) => [(1, 1), (2, 2), (3, 3), (4, 4)] list(zip(*c)) => [(1, 3, 5), (2, 4, 6)] list(zip(*d)) => [(1, 3, 5), (2, 4, 6), (10, 11, 12)]
Correct Lineup
짝수인 리스트를 입력 받으면 앞에서 부터 두 요소씩 짝을 지어 순서를 뒤 바꾸는 함수
Example 1 2 3 athletes = [1 , 2 , 3 , 4 , 5 , 6 ] correctLineup(athletes) = [2 , 1 , 4 , 3 , 6 , 5 ]
My Answer 1 2 def correctLineup (athletes) : return [a[b] for a in [[y,x] for x, y in zip(athletes[::2 ], athletes[1 ::2 ])] for b in range(2 )]
Another Answer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 def correctLineup (athletes) : return [athletes[i^1 ] for i in range(len(athletes))] def correctLineup (athletes) : return [athletes[i+(-1 )**i] for i in range(len(athletes))] def correctLineup (athletes) : return [athletes[i+1 ] if i%2 == 0 else athletes[i-1 ] for i in range(0 ,len(athletes)) ] def correctLineup (athletes) : return list(sum(zip(athletes[1 ::2 ], athletes[0 ::2 ]), ())) def correctLineup (athletes) : return reduce(lambda x,y: x+y, zip(athletes[1 ::2 ], athletes[::2 ]))
Group Dating
입력 받은 두 리스트에서 같은 인덱스의 값이 다를 경우 짝을 지어주는 함수
Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 male = [5 , 28 , 14 , 99 , 17 ] female = [5 , 14 , 28 , 99 , 16 ] groupDating(male, female) = [[28 , 14 , 17 ], [14 , 28 , 16 ]] male = [1 ,2 ,3 ,4 ] female = [1 ,2 ,3 ,4 ] groupDating(male, female) = [[],[]] male = [12 ] female = [43 ] groupDating(male, female) = [[12 ], [43 ]]
My Answer 1 2 def groupDating (male, female) : return [[],[]] if male==female else list(zip(*[[x[0 ],x[1 ]] for x in list(zip(male, female)) if x[0 ]!=x[1 ]]))
Another Answer 1 2 3 4 5 6 7 8 def groupDating (male, female) : return [[x for x, y in zip(male, female) if x!=y], [y for x, y in zip(male, female) if x!=y]] def groupDating (male, female) : return zip(*[[m, f] for (m, f) in zip(male, female) if m != f]) def groupDating (male, female) : return list(zip(*[x for x in list(zip(male,female)) if x[0 ]!=x[1 ]]))
Fix Tree
리스트를 입력 받으면 제대로된 트리 모양으로 바꿔주는 함수
Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 tree = [" * " , " * " , "*** " , " *****" , " *******" , "*********" , " *** " ] fixTree(tree) = [" * " , " * " , " *** " , " ***** " , " ******* " , "*********" , " *** " ]
My Answer 1 2 def fixTree (tree) : return [" " *int((len(x) - len(x.strip()))/2 ) + x.strip() + " " *int((len(x) - len(x.strip()))/2 ) for x in tree]
Another Answer 1 2 3 4 5 6 7 8 def fixTree (tree) : return [x.strip().center(len(x))for x in tree] def fixTree (tree) : return list(map(lambda s: s.strip().center(len(s)), tree)) def fixTree (tree) : return map(lambda x: ' ' * (x.count(' ' ) / 2 ) + '*' * x.count('*' ) + ' ' * (x.count(' ' ) / 2 ), tree)
center라는 좋은 함수가 있었구만!
Pref Sum
리스트를 하나의 수열이라고 했을 때, 즉 점화식 또는 일반항 이라고 보고 이에대한 부분합을 구하는 함수
Example 1 2 3 4 5 a = [1 , 2 , 3 ] b = [1 , 5 , 10 , -5 ] prefSum(a) = [1 , 3 , 6 ] prefSum(a) = [1 , 6 , 16 , 11 ]
My Answer 1 2 3 4 5 6 7 def prefSum (a) : return [sum([a[x] for x in range(y+1 )]) for y in range(len(a))] from functools import reducedef prefSum (a) : return [reduce(lambda x,y:x+y,a[:i]) for i in range(1 ,len(a)+1 )]
Another Answer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 from itertools import accumulatedef prefSum (a) : return list(accumulate(a)) from functools import reducedef prefSum (a) : return reduce(lambda x,y:x+[sum([y]+x[-1 :])],a,[]) from functools import reducedef prefSum (a) : return reduce(lambda p, n: p + [p[-1 ] + n], a, [0 ])[1 :] import numpydef prefSum (a) : return numpy.cumsum(a) def prefSum (a) : return list(__import__('itertools' ).accumulate(a))
새로 알게된 것들: numpy의 cumsum , itertools의 accumlate
Math Practice
리스트를 입력값으로 받으면 더하고 곱하고를 반복하면서 하나의 값으로 만드는 함수. (자세한건 예시 확인)
Example 1 2 3 4 5 6 7 numbers = [1 ,2 ,3 ,4 ,5 ,6 ] mathPractice(numbers) = ((1 + 2 )*3 + 4 )*5 + 6 = 71 numbers2 = [9 , 19 , 2 , 2 , 7 , 3 , 0 , 0 , 6 , 11 , 14 , 18 , 11 , 7 , 9 , 6 , 8 , 4 , 13 , 11 ] mathPractice(numbers2) = 1778151
My Answer 1 2 3 test5에서 통과하지 못함.. 이유는 리스트 인덱스 15 번째에서 더해야 하는데 곱해서 중간에 값이 뻥튀기 됨.. def mathPractice (numbers) : return reduce(lambda x,y: x*y if numbers.index(y)%2 ==0 else x+y, numbers)
Another Answer 1 2 3 4 5 6 7 8 def mathPractice (numbers) : return reduce(lambda x, (i,y): x+y if i%2 else x*y, enumerate(numbers), 1 ) def mathPractice (numbers) : return reduce(lambda z,(x,y):z*x+y, zip(numbers[::2 ],numbers[1 ::2 ]+[0 ]), 1 ) def mathPractice (numbers) : return functools.reduce(lambda s, a: s+numbers[a] if a%2 ==1 else s*numbers[a], range(1 , len(numbers)), numbers[0 ])
Fibonacci List
피보나치 수열 응용 함수
Example 1 2 3 4 5 6 7 8 n = 6 fibonacciList(n) = [[], [0 ], [0 ], [0 , 0 ], [0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ]]
Another Answer 1 2 3 def fibonacciList (n) : return [[0 ] * x for x in reduce(lambda a, b: a+[a[-2 ]+a[-1 ]], range(n-2 ), [0 ,1 ])]
Fibonacci 관련 문제는 여러번 다양한 문제로 연습 해보자
Primes Sum
범위 안의 숫자 중에서 소수만 뽑아 더하는 함수
Example 1 2 3 4 a = 10 b = 20 primesSum(a,b) = 11 + 13 + 17 + 19 = 60
My Answer 1 2 def primesSum (a, b) : return sum([sum([0 if y == 1 or 0 in [0 if y%x==0 else x for x in range(2 , y-1 )] else y]) for y in range(a,b+1 )])
Another Answer 1 2 3 4 5 6 7 8 9 10 11 12 def primesSum (a, b) : return sum(filter(lambda x: all(x % i for i in range(2 , int(x**0.5 ) + 1 )), range(max(2 , a), b+1 ))) import mathdef primesSum (a, b) : return sum([n for n in range(a, b+1 ) if n > 1 and all([n % b for b in range(2 , int(math.sqrt(n))+ 1 )])]) def primesSum (a, b) : return sum([x for x in range(max(a,2 ),b+1 ) if not 0 in [x%z for z in range(2 , int(x**0.5 +1 ))]]) def primesSum (a, b) : return sum([a for a in range(a, b+1 ) if not (a < 2 or any(a % x == 0 for x in range(2 , int(a ** 0.5 ) + 1 ))) ])
Fibonacci Generator
숫자 n을 입력하면 피보나치 수열에서 n번째 항까지 출력하는 함수
Example 1 2 3 n = 7 fibonacciGenerator(n) = [0 , 1 , 1 , 2 , 3 , 5 , 8 ]
My Answer 1 2 3 4 5 6 7 8 9 def fibonacciGenerator (n) : def fib () : last = (0 , 1 ) while True : yield last[0 ] last = last[0 ] + last[1 ], last[0 ] gen = fib() return [next(gen) for _ in range(n)]
Check Password
비밀번호를 몇번째 만에 성공하는지 확인하는 함수
Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 attempts = ["hello" , "world" , "I" , "like" , "coding" ] password = "like" checkPassword(attempts, password) = 4 attempts = ["hello" , "world" , "I" , "like" , "coding" ] password = "qwerty123" checkPassword(attempts, password) = -1 attempts = ["codesignal" ] password = "codesignal" checkPassword(attempts, password) = 1
Another Answer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 def checkPassword (attempts, password) : def check () : while True : x = yield yield x == password checker = check() for i, attempt in enumerate(attempts): next(checker) if checker.send(attempt): return i + 1 return -1 def checkPassword (attempts, password) : def check () : while True : yield (yield ) == password checker = check() for i, attempt in enumerate(attempts): next(checker) if checker.send(attempt): return i + 1 return -1 def checkPassword (attempts, password) : def check () : while True : yield True if attempt==password else False checker = check() for i, attempt in enumerate(attempts): next(checker) if checker.send(attempt): return i + 1 return -1
Super Prize
n의 배수 번째 손님의 구매금액을 d로 나누었을 때 나누어 떨어지면 상금을 주는 알고리즘을 갖는 객체를 생성하시오
Example 1 2 3 4 5 6 7 8 9 10 11 12 13 purchases: [41 , 51 , 91 , 72 , 71 , 30 , 28 , 35 , 55 , 62 , 65 , 45 , 100 , 54 , 83 , 69 , 66 , 43 ] n: 2 d: 5 superPrize(purchases, n, d): [6 , 8 , 12 ] purchases[1 ::2 ] = [51 , 72 , 30 , 35 , 62 , 45 , 54 , 69 , 43 ] [x % 5 for x in purchases[1 ::2 ]] = [1 , 2 , 0 , 0 , 2 , 0 , 4 , 4 , 3 ] 3 , 4 , 6 번째가 나누어 떨어지고 인덱스가 절반으로 줄었으니까6 , 8 , 12 번째의 손님이 상금을 차지하게 된다.
My Answer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Prizes (object) : def __init__ (self, purchases, n ,d) : self.purchases = purchases self.n = n self.d = d self.i = n - 1 def __iter__ (self) : return self def __next__ (self) : while self.i < len(self.purchases): i = self.i self.i += self.n if self.purchases[i] % self.d == 0 : return i + 1 else : raise StopIteration def superPrize (purchases, n, d) : return list(Prizes(purchases, n, d))
Another Answer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 class Prizes (object) : def __init__ (self, p, n, d) : self.p = p self.n = n self.d = d def __iter__ (self) : for i, x in enumerate(self.p): if i%self.n == self.n-1 and x%self.d == 0 : yield i+1 def superPrize (purchases, n, d) : return list(Prizes(purchases, n, d)) class Prizes (object) : def __init__ (self,purchases,n,d) : self.winners = [(i+1 )*n for i,x in enumerate(purchases[n-1 ::n]) if x%d == 0 ] def __iter__ (self) : return iter(self.winners) def superPrize (purchases, n, d) : return list(Prizes(purchases, n, d)) class Prizes (object) : def __new__ (_, p, n, d) : return [(i+1 )*n for i, v in enumerate(p[n-1 ::n]) if v%d == 0 ] def superPrize (purchases, n, d) : return list(Prizes(purchases, n, d))
Try Functions
하나의 값을 여러가지 함수로 평가한 결과 리스트를 반환하는 함수
Example 1 2 3 4 functions = ["math.sin" , "math.cos" , "lambda x: x * 2" , "lambda x: x ** 2" ] x = 1 tryFunctions(x, functions) = [(0.8414709848078965 , 0.5403023058681398 , 2 , 1 )]
My Answer 1 2 def tryFunctions (x, functions) : return list(zip(*[map(x, list([1 ])) for x in func]))
*내가 만든 함수의 문제: * 입력값으로 받는 함수리스트가 문자열로 구성되어 있으면 사용할 수 없다. 리스트 안에 있는 문자열을 함수 타입으로 만들고 싶었으나 함수 타입으로 만들어주는 최상위 클래스같은건 없기에 실패.. {: .notice}
Another Answer 1 2 def tryFunctions (x, functions) : return [eval(f)(x) for f in functions)]
eval 함수 언젠간 요긴하게 쓸거같았는데..! eval을 exec로 착각하는 바람에 결국 답을 봐버렸다..
Simple Composition & Functions Composition
단일 합성함수의 연산 결과를 반환하는 함수 n개 중첩 합성함수의 연산 결과를 반환하는 함수
Example 1 2 3 4 5 6 7 8 9 10 11 12 f = "math.log10" , g = "abs" , x = -100 simpleComposition(f, g, x) = math.log10(abs(-100 )) = 2 functions = ["abs" , "math.sin" , "lambda x: 3 * x / 2" ] x = 3.1415 functionsComposition(functions, x) = abs(math.sin(3 *3.1415 /2 )) = 1
My Answer 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def compose (f, g) : return lambda x : f(g(x)) def simpleComposition (f, g, x) : return compose(eval(f), eval(g))(x) def simpleComposition2 (f, g, x) : return eval(f)(eval(g)(x)) from functools import reducedef compose (functions) : return reduce(lambda f,g : lambda x: f(g(x)), functions) def functionsComposition (functions, x) : return compose(map(eval, functions))(x)
Another Answer 1 2 3 4 5 6 def compose (functions) : return functions[0 ] if len(functions) == 1 else compose([lambda x: functions[0 ](functions[1 ](x))] + functions[2 :]) def functionsComposition (functions, x) : return compose(map(eval, functions))(x)
Graphs