Index
1
2
3
4
5
| 1. Intro => 문제해결 프로그래밍, 알고리즘 문제
2. DataBase => SQL 문제
3. The Core
4. Python => Python 문법 문제
5. Graphs
|
CenturyFromYear
연도를 입력 받으면 몇 세기인지 출력하는 함수 만들기
Example
1
2
3
4
5
| For year = 1905, the output should be
centuryFromYear(year) = 20
For year = 1700, the output should be
centuryFromYear(year) = 17
|
My Answer
1
2
3
4
5
6
7
| def centuryFromYear(year):
if year % 100 != 0:
year = year / 100
return int(year + 1)
else:
year = year / 100
return int(year)
|
Another Answer (Python)
1
2
| def centuryFromYear(year):
return (year + 99) // 100
|
Another Answer (JS)
1
2
3
| function checkPalindrome(inputString) {
return inputString == inputString.split('').reverse().join('');
}
|
CheckPalindrome
회문인지 체크하는 함수, 앞으로 읽어도 뒤로 읽어도 똑같은 문자열이면 True 반환, 아니면 False 반환
Example
1
2
3
4
5
| For inputString = "aabbaa", the output should be checkPalindrome(inputString) = ture
For inputString = "abac", the output should be checkPalindrome(inputString) = false
For inputString = "a", the output should be checkPalindrome(inputString) = true
|
My Answer
1
2
3
4
5
| def checkPalindrome(inputString):
if inputString == inputString[::-1]:
return True
else:
return False
|
Another Answer (Python)
1
2
| def checkPalindrome(inputString):
return inputString == inputString[::-1]
|
Another Answer (C++)
1
2
3
| bool checkPalindrome(string is) {
return is == string(is.rbegin(),is.rend());
}
|
AdjacentElementsProduct
인접한 요소의 곱이 가장 큰 값 반환
Example
1
2
| For inputArray = [3, 6, -2, -5, 7, 3], the output should be
adjacentElementsProduct(inputArray) = 21
|
My Answer
1
2
3
4
5
6
7
| def adjacentElementsProduct(inputArray):
temp = -99999999999
for i in range(len(inputArray)-1):
result = inputArray[i] * inputArray[i+1]
if temp < result:
temp = result
return temp
|
Another Answer (Python)
1
2
| def adjacentElementsProduct(inputArray):
return max([inputArray[i] * inputArray[i+1] for i in range(len(inputArray)-1)])
|
Another Answer (JS)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| # 1
function adjacentElementsProduct(inputArray) {
var prod = inputArray[0] * inputArray[1];
for (var i = 1; i<inputArray.length - 1;i++) {
prod = Math.max(prod, inputArray[i] * inputArray[i+1]);
}
return prod
}
# 2
function adjacentElementsProduct(arr) {
return Math.max(...arr.slice(1).map((x,i)=>[x*arr[i]]))
}
|
Another Answer (Java)
1
2
| int adjacentElementsProduct(int[] inputArray) {
return IntStream.range(1, inputArray.length).map(i->inputArray[i]*inputArray[i-1]).max().getAsInt();}
|
ShapeArea

My Answer
1
2
3
| import math
def shapeArea(n):
return 2 * math.pow(n - 1, 2) + 2 * (n - 1) + 1
|
Another Answer (Python)
1
2
| def shapeArea(n):
return n**2 + (n-1)**2
|
Another Answer (JS)
1
2
3
| function shapeArea(n) {
return n*n + (n-1)*(n-1);
}
|
Another Answer (C++)
1
2
3
| int shapeArea(int n) {
return 1 + 2 * n * (n-1);
}
|
# DataBase (MySQL 문법)MonthlyScholarships
1년치 장학금이 기제되어 있는 DB에서 각 id별로 매달 장학금을 계산해서 id와 scholarship을 조회하라
Example
Table

Result

My Answer
1
2
3
4
| CREATE PROCEDURE monthlyScholarships()
BEGIN
SELECT id, scholarship/12 as scholarship FROM scholarships;
END
|
ProjectsTeam
중복되는 이름은 제거하고 이름을 오름차순으로 정렬하여 조회하라
Example
Table

Result

My Answer
1
2
3
4
| CREATE PROCEDURE projectsTeam()
BEGIN
SELECT DISTINCT name FROM projectLog ORDER BY name;
END
|
AutomaticNotifications
role 칼럼의 admin, premium을 제외한 행의 email을 조회하라
Example
Table

Result

MyAnswer
1
2
3
4
5
| CREATE PROCEDURE automaticNotifications()
SELECT email
FROM users
WHERE role NOT IN ("admin", "premium")
ORDER BY email;
|
# The Core
# PythonCollections Truthness
Python에서 True와 False의 의미를 알 수 있는 문제
Example
1
2
3
4
5
6
| xs = [()]
res = [False] * 2
if xs:
res[0] = True
if xs[0]:
res[1] = True
|
My Answer
1
2
3
4
5
6
| xs = [()]
res = [False] * 2
if xs:
res[0] = True
if xs[0]:
res[1] = False
|
xs 리스트는 첫번째 요소로 tuple을 갖기 때문에 존재론적 관점에서 True, 리스트의 첫번째 요소인 tuple의 첫번째 요소는 아무것도 없기 때문에 존재론적 관점에서 False이다
Efficient Comparison
효과적인 비교 방법을 찾는 문제
Example
1
2
3
| 1. if L < x**y <=R:
2. if x**y > L and x**y <=R:
3. if x**y in range(L+1, R+1):
|
My 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
| def func1(x,y,L,R):
if L < x**y <=R:
return True
else:
return False
def func2(x,y,L,R):
if x**y > L and x**y <=R:
return True
else:
return False
def func3(x,y,L,R):
if x**y in range(L+1, R+1):
return True
else:
return False
%%timeit
func1(2,3, 0,10)
: 480 ns ± 34.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
func2(2,3, 0,10)
: 763 ns ± 23.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
func3(2,3, 0,10)
: 806 ns ± 45.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
|
func1이 가장 빠르다
Count Bits
숫자 n을 입력하면 bit수를 출력하는 함수
Example
1
2
3
| n = 50
countBits(n) = 6
50(10진수) = 110010(2진수) => 6개 비트로 구성
|
My Answer
1
2
3
4
5
6
7
8
9
| def countBits(n):
cnt = 1
rest = 0
while(n!=1):
rest = n/2
n = int(rest)
cnt +=1
return cnt
|
함수가 잘 작동하고 정답처리가 되긴 했지만 자꾸 return문만 써서 간결하게 하라고 해서 다음 단계로 넘어가지 못했음..
Another Answer (Python)
1
2
| def countBits(n):
return n.bit_length()
|
저런 내장 함수가 있는지 몰랐네…
Modulus
숫자 n이 정수형이면 return 1 아니면 return -1
Example
1
2
3
4
5
| n = 15
modulus(n) = 1
n = 23.12
modulus(n) = -1
|
My Answer
1
2
3
4
5
| def modulus(n):
if isinstance(n, int):
return n % 2
else:
return -1
|
Another Answer (Python)
1
2
3
4
5
| def modulus(n):
if n==int(n) :
return n % 2
else:
return -1
|
Base Conversion
n진법으로 표기된 String을 16진수로 변환하기
Example
1
2
3
4
5
6
| n = '1302'
x = 5
1302(5) => 202(10) => ca
baseConversion('1302',5) = 'ca'
|
My Answer
1
2
3
4
5
6
7
8
| def baseConversion(n:str, x:int)->int:
result = 0
for i, n in enumerate(n[::-1]):
result += int(n) * pow(x, i)
return hex(result)[2:]
def baseConversion(n, x):
return hex(int(n,x))[2:]
|
int 함수는 숫자를 넣었을 때 정수형으로 변환하지만, 문자열 형태의 숫자와 변환하고자 하는 진법의 수를 입력하면 원하는 진법을 변환해주기도 한다
Another Answer (Python)
1
2
| def baseConversion(n, x):
return format(int(n, x), 'x')
|
ListBeautifier
어떠한 리스트가 들어와도 리스트의 맨 앞 요소와 맨 뒤 요소가 같거나 빈 리스트를 반환하도록 하는 함수
Example
1
2
3
4
5
6
7
| a = [3, 4, 2, 4, 38, 4, 5, 3, 2]
b = [1,4,-5]
c = [1,2]
listBeautifier(a) = [4, 28, 4]
listBeatuifier(b) = [4]
listBeatuifier(c) = []
|
My Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| def listBeautifier1(a):
res = a[:]
while res and res[0] != res[-1]:
res = res[1:-1]
return res
def listBeautifier2(a):
res = a[:]
while res and res[0] != res[-1]:
a, *res, b = res
return res
%%timeit
listBeautifier1(a)
: 2.32 µs ± 193 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
listBeautifier2(a)
: 3.05 µs ± 237 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# slicing이 아주 살짝 더 빠르다
|
Slicing과 Unpacking으로 쉽게 풀 수 있다!
Fix Message
대소문자 고쳐주는 함수 (가장 앞 단어의 첫번째 철자를 대문자로 그리고 나머지는 소문자로)
Example
1
2
3
| message = "you'll NEVER believe what that 'FrIeNd' of mine did!!1"
fixMessage(message) = "You'll never believe what that 'friend' of mine did!!1"
|
My Answer
1
2
| def fixMessage(message):
return message.lower().capitalize()
|
Another Answer
1
2
| def fixMessage(message):
return message.upper()[0] + message[1:].lower()
|
Cat Walk
내가 자리를 비운 사이 고양이가 내 키보드 위에 올라가 스페이스바를 마구 눌러서 띄어쓰기 간격이
너무 많이 벌어졌다. 늘어난 띄어쓰기 공간을 하나로 줄여라 (이런 말도 안되는..ㅎ)
Example
1
2
3
| line = "def m e gaDifficu ltFun ction(x):"
catwalk(line) = "def m e gaDifficu ltFun ction(x):"
|
My Answer
1
2
3
4
5
6
7
8
9
10
11
| 1번
def catWalk(code):
a = ''
for i in code.rsplit():
a += i + ' '
return a.rstrip() # rstrip 함수는 원래 값은 변하지 않고 함수 호출시에만 결과값 리턴
2번
from functools import reduce
def catWalk(code):
return reduce(lambda x,y:x+' '+y, [i for i in code.rsplit()])
|
내 머리속에서 이런 코드가 나오다니..ㅎ 근데 제출이 안되네 ㅠ
Another Answer
1
2
3
| 3번
def catWalk(code):
return " ".join(code.split())
|
이런 쉬운 함수가 있었다니..ㅎ
속도 차이
1
2
3
4
5
6
7
8
9
10
11
12
13
| %%timeit
catWalk(line)
# 1번
3.13 µs ± 205 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 2번
4.51 µs ± 233 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 3번
1.2 µs ± 39.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# 결론: 이미 만들어져 있는게 젤 빠르다..
|
Convert Tabs
문자열 안에 Tab(\t)이 들어 있다면 n번의 space로 변환하는 함수
Example
1
2
3
4
5
6
7
8
| code = "\t\t\t\t\t"
convertTabs(code, 1) = " "
code = "def add(x, y)\f\treturn x + y"
convertTabs(code, 4) = "def add(x, y)\f return x + y"
code = " for x in range(20)"
convertTabs(code, 100) = " for x in range(20)"
|
My Answer
1
2
| def convertTabs(code, x):
return code.replace('\t', ' '*x)
|
Feedback Review
원하는 크기 이하의 문자열 단위로 쪼개주는 함수
Example
1
2
3
4
5
6
7
| feedback = "This is an example feedback"
size = 8
feedbackReview(feedback, size) = ["This is",
"an",
"example",
"feedback"]
|
Another Answer
1
2
3
4
5
6
7
8
9
| import textwrap
def feedbackReview(feedback, size):
return textwrap.wrap(feedback, size)
import re
def feedbackReview(feedback, size):
return re.findall('(?:\s|^)(\S(?:.{0,%d}\S)?)(?=\s|$)' % (size-2),feedback)
|
Is Word Palindrome
회문인지 확인하는 함수, 앞으로 읽어도 뒤로 읽어도 같은지 확인하는 함수
Example
1
2
3
4
5
| word = "aibohphobia"
isWordPalindrome(word) = true;
word = "hehehehehe"
isWordPalindrome(word) = false
|
My Answer
1
2
| def isWordPalindrome(word):
return word == word[::-1]
|
Permutation Cipher
이름은 순열암호화 인데 사실상 시저 암화랑 같음. 평문하고 키를 넘겨주면 시저암호 처럼 암호화 해주는 함수
Example
1
2
3
4
5
6
7
8
9
| password = "iamthebest"
key = "zabcdefghijklmnopqrstuvwxy"
permutationCipher(password, key) = "hzlsgdadrs"
abcdefghijklmnopqrstuvwxyz
|| | || | ||
vv v vv v vv
zabcdefghijklmnopqrstuvwxy
|
My Answer
1
2
3
| def permutationCipher(password, key):
table = str.maketrans("abcdefghijklmnopqrstuvwxyz", key)
return password.translate(table)
|
Another Answer
1
2
3
4
5
6
7
8
9
10
11
| def permutationCipher(password, key):
table = {ord('a') + i : ord(k) for i, k in enumerate(key)}
return password.translate(table)
def permutationCipher(password, key):
table = ' '*97+key
return str(password).translate(table)
def permutationCipher(password, key):
table = string.maketrans(string.lowercase, key)
return str(password).translate(table)
|
Competitive Eating
설명 못하겠음… 예시 확인 ㄱㄱ
Example
1
2
3
| t = 3.1415, width = 10, precision = 2,
competitiveEating(t, width, precision) = " 3.14 "
|
Another Answer
1
2
3
4
5
6
7
8
| def competitiveEating(t, width, precision):
return '{:^{}.{}f}'.format(t,width,precision)
def competitiveEating(t, width, precision):
return "{0:.{1}f}".format(t,precision).center(width)
def competitiveEating(t, width, precision):
return ('{:^{w}.{p}f}').format(t,w=width,p=precision)
|
Get Commit
유저 이름과 0, ?, +, !가 포함된 암호화 commit 문자중 4가지 symbol을 제거한 문자열을 추출하라
Example
1
2
3
| commit = "0??+0+!!someCommIdhsSt"
getCommit(commit) = "someCommIdhsSt"
|
My Answer
1
2
| def getCommit(commit):
return commit.replace('0','').replace('?','').replace('!','').replace('+','')
|
너무 일차원적인 답변이지만 잘 된다..ㅎ
Another Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| def getCommit(commit):
return commit.lstrip('0?+!')
def getCommit(commit):
return commit.strip('0?+!')
def getCommit(commit):
return "".join(filter(lambda x: x not in "0?+!", commit))
def getCommit(commit):
return re.sub('[0?+!]', '', commit)
def getCommit(commit):
return "".join([c for c in commit if c.islower() or c.isupper()])
def getCommit(commit):
return re.match(r"^[0\?\+!]*(.*)$", commit).group(1)
|
Lists Concatenation
두 리스트를 연결하는 함수.
Example
1
2
3
4
| lst1 = [2, 2, 1]
lst2 = [10, 11]
listsConcatenation(lst1, lst2) = [2, 2, 1, 10, 11]
|
My Answer
1
2
3
4
5
6
7
8
9
| def listsConcatenation(lst1, lst2):
res = lst1
res.extend(lst2)
return res
def listsConcatenation(lst1, lst2):
res = lst1
[res.append(i) for i in lst2]
return res
|
Another Answer
1
2
3
4
| def listsConcatenation(lst1, lst2):
res = lst1
res += lst2
return res
|
Two Teams
리스트에 있는 요소에서 [홀수번째 요소 합 - 짝수번째 요소 합 구하는] 함수
Example
1
2
3
4
| students = [1, 11, 13, 6,14]
twoTeams(students) = 11
(1 + 13 + 14) - (11 + 6) = 11
|
My Answer
1
2
| def twoTeams(students):
return sum(students[::2]) - sum(students[1::2])
|
Another Answer
1
2
| def twoTeams(students):
return sum( (-1)**i*I for i,I in enumerate(students))
|
Remove Tasks
리스트에서 n번째 요소 제거한 리스트 반환하는 함수
Example
1
2
3
4
| k = 3
toDo = [1237, 2847, 27485, 2947, 1, 247, 374827, 22]
removeTasks(k, toDo) = [1237, 2847, 2947, 1, 374827, 22]
|
My Answer
1
2
3
| def removeTasks(k, toDo):
del toDo[k-1::k]
return toDo
|
Print List
설명은 패스 ~ 예시를 참고해주세요~
Example
1
2
3
| lst = [1, 2, 3, 4, 5]
printList(lst) = "This is your list: [1, 2, 3, 4, 5]"
|
My Answer
1
2
| def printList(lst):
return 'This is your list: ' + str(lst)
|
Another Answer
1
2
3
4
5
| def printList(lst):
return f'This is your list: {lst}'
def printList(lst):
return "This is your list: {}".format(lst)
|
Repeat Char
문자열과 숫자를 입력받아 입력받은 숫자만큼 반복하는 문자열을 반환하는 람다
Example
1
2
3
4
| ch = '*'
n = 10
repeatChar(ch, n) = '**********'
|
My Answer
1
| repeatChar = lambda ch, n : ch *n
|
Get Points
채점 해주는 함수. n번째 문제가 맞으면 n점 획득, 틀리면 패널티 점수 차감.
Example
1
2
3
4
| answer = [True, False, True, False, True, True]
p = 3
getPoints(answer, p) = 12 => 1 -3 + 3 -3 + 5 + 6
|
My Answer
1
2
3
4
5
6
7
| def getPoints(answers, p):
questionPoints = lambda x,y : x+1 if(y==True) else -p
res = 0
for i, ans in enumerate(answers):
res += questionPoints(i, ans)
return res
|
Another Answer
1
2
3
4
5
6
7
| def getPoints(answers, p):
questionPoints = lambda i,ans: [-p,i+1][ans]
res = 0
for i, ans in enumerate(answers):
res += questionPoints(i, ans)
return res
|
Sort Students
성씨를 기준으로 오름차순 정렬하는 함수. (단, 성이 같으면 이름으로)
Example
1
2
3
| name = ["John Smith", "Jacky Mon Simonoff", "Lucy Smith", "Angela Zimonova"]
sortStudents(name) = ['Jacky Mon Simonoff', 'John Smith', 'Lucy Smith', 'Angela Zimonova']
|
Another Answer
1
2
3
4
5
6
7
8
| def sortStudents(students):
# 특정한 데이터를 기준으로 정렬할 수 있도록 함수를 지정할 수 있다
students.sort(key=lambda name: name.split(" ")[-1])
return students
def sortStudents(students):
students.sort(key= lambda s : s[len(s)-(s[::-1]).find(" "):] )
return students
|
Is Test Solvable
리스트에 있는 숫자들을 다 더하는데, 각 숫자는 각 자리수의 합을 구한 후 더한다.
그리고 그 총합이 n으로 나누어지는지 확인해주는 함수를 만든다.
Example
1
2
3
4
5
6
| ids = [529665, 909767, 644200]
k = 3
(5+2+9+6+6+5) + (9+0+9+7+6+7) + (6+4+4+2+0+0) = 87
87/3 = 0
=> True
|
My Answer
1
2
3
4
5
6
7
| def isTestSolvable(ids, k):
digitSum = lambda x : sum([int(i) for i in list(str(x))])
sm = 0
for questionId in ids:
sm += digitSum(questionId)
return sm % k == 0
|
Another Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| def isTestSolvable(ids, k):
digitSum = lambda x: x%10+digitSum(x//10) if x else 0
sm = 0
for questionId in ids:
sm += digitSum(questionId)
return sm % k == 0
def isTestSolvable(ids, k):
digitSum = lambda r: sum(map(int,str(r)))
sm = 0
for questionId in ids:
sm += digitSum(questionId)
return sm % k == 0
|
Create Spiral Matrix
나선형 행렬을 구하는 함수. (맨 오른쪽 아래부터 시작)

Example
1
2
3
4
5
| n = 3
createSpiralMatrix(n) = [[5, 4, 3],
[6, 9, 2],
[7, 8, 1]]
|
My 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
| # 1번
def createSpiralMatrix(n):
dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
curDir = 0
curPos = (n - 1, n - 1)
res = [[0 for j in range(n)] for i in range(n)]
for i in range(1, n * n + 1):
res[curPos[0]][curPos[1]] = i
nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
if not (0 <= nextPos[0] < n and
0 <= nextPos[1] < n and
res[nextPos[0]][nextPos[1]] == 0):
curDir = (curDir + 1) % 4
nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
curPos = nextPos
return res
# 2번
import numpy as np
def createSpiralMatrix(n):
dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
curDir = 0
curPos = (n - 1, n - 1)
res = np.zeros([n,n])
for i in range(1, n * n + 1):
res[curPos[0]][curPos[1]] = i
nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
if not (0 <= nextPos[0] < n and
0 <= nextPos[1] < n and
res[nextPos[0]][nextPos[1]] == 0):
curDir = (curDir + 1) % 4
nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
curPos = nextPos
return res
|
2번도 가능. 그러나 해당 문제에서 numpy 사용 금지.
1번에서 처음에 [[j for j in range(n)] for i in range(n)]를 했지만 계속 인덱스 오류가 남. (이유는 모르겠음..)
Another Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| def createSpiralMatrix(n):
dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
curDir = 0
curPos = (n - 1, n - 1)
res = [[0]*n for x in range(n)]
for i in range(1, n * n + 1):
res[curPos[0]][curPos[1]] = i
nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
if not (0 <= nextPos[0] < n and
0 <= nextPos[1] < n and
res[nextPos[0]][nextPos[1]] == 0):
curDir = (curDir + 1) % 4
nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
curPos = nextPos
return res
|
Construct Shell
오른쪽으로 90도 회전한 산 모양 리스트를 반환하는 함수
Example
1
2
3
4
5
6
7
| n = 3
constructShell(n) = [[0],
[0, 0],
[0, 0, 0],
[0, 0],
[0]]
|
My Answer
1
2
| def constructShell(n):
return [[0 for j in range(2*n-i)] if i > n else [0]*i for i in range(1, 2*n)]
|
Another Answer
1
2
3
4
5
6
7
8
| def constructShell(n):
return [[0]*min(i,2*n-i) for i in range(1,2*n)]
def constructShell(n):
return [[0] * (i - 2 * max(0, i-n) ) for i in range(1, 2 * n)]
def constructShell(n):
return [[0] * (n-abs(i)) for i in range(-n+1, n)]
|
Word Power
단어를 넣으면 알파벳 순서에 맞게 숫자로 치환하여 각각의 철자의 합을 구하는 함수.
Example
1
2
3
4
| word = 'hello'
h => 8 e => 5 l => 12 o => 15
wordPower(word) = 8 + 5 + 12 + 12 + 15 = 52
|
My Answer
1
2
3
| def wordPower(word):
num = {b: a+1 for a, b in enumerate('abcdefghijklmnopqrstuvwxyz')}
return sum([num[ch] for ch in word])
|
Another Answer
1
2
3
4
5
6
7
| def wordPower(word):
num = {c: ord(c) - 96 for c in word}
return sum([num[ch] for ch in word])
def wordPower(word):
num = dict(zip('abcdefghijklmnopqrstuvwxyz', range(1, 27)))
return sum([num[ch] for ch in word])
|
Cool Pairs
두 리스트의 요소간 결합으로 만들어지는 숫자 쌍이 (x,y)라 했을 때 (x*y)%(x+y)==0 인 쌍의 갯수를 반환하는 함수
단, 숫자 쌍의 합이 같은 경우가 2개 이상일 때는 하나로 취급한다.
Example
1
2
3
4
5
6
7
| a = [4, 5, 6, 7, 8]
b = [8, 9, 10, 11, 12]
# (4,12), (6,12), (8,8)의 경우가 발생
# 그러나 합으로 봤을 때는 16, 18인 경우 두 가지!
coolPairs(a,b) = 2
|
My Answer
1
2
3
| def coolPairs(a, b):
uniqueSums = {(x+y) for x in a for y in b if (x*y)%(x+y)==0}
return len(uniqueSums)
|
Multiplication Table
숫자 n을 입력하면 NxN 행렬을 반환한다. (단, 1행은 1단 2행은 2단 …n행은 n단의 숫자로 구성)
Example
1
2
3
4
5
6
7
| n = 5
multiplicationTable(5) = [[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
[4, 8, 12, 16, 20],
[5, 10, 15, 20, 25]]
|
My Answer
1
2
| def multiplicationTable(n):
return [[a for a in range(b,b*n+1,b)] for b in range(1,n+1)]
|
Another Answer
1
2
3
4
5
| def multiplicationTable(n):
return [range(i, n*i + 1, i) for i in xrange(1,1+n) ]
def multiplicationTable(n):
return [[x*y for x in range(1,n+1)] for y in range(1,n+1)]
|
Chess Teams
두 개의 리스트를 입력값으로 받으면 각각의 리스트에서 요소 하나씩 뽑아 리스트로 짝지어 리턴해주는 함수
Example
1
2
3
4
| smarties = ["Jane", "Bob", "Peter"]
cleveries = ["Oscar", "Lidia", "Ann"]
chessTeams(smarties, cleveries) = [['Jane', 'Oscar'], ['Bob', 'Lidia'], ['Peter', 'Ann']]
|
My Answer
1
2
| def chessTeams(smarties, cleveries):
return list(map(lambda x, y : [x,y], smarties, cleveries))
|
Another Answer
1
2
| def chessTeams(smarties, cleveries):
return list(zip(smarties,cleveries))
|
College Courses
수강한 과목중에 빼야 하는 과목 이름의 길이만 알때 그 과목을 빼는 함수
Example
1
2
3
4
| n = 7
courses = ["Art", "Finance", "Business", "Speech", "History", "Writing", "Statistics"]
collegeCourses(x, courses) = ["Art", "Business", "Speech", "Statistics"]
|
My Answer
1
2
3
4
5
| def collegeCourses(x, courses):
def shouldConsider(course):
return len(course) != x
return list(filter(shouldConsider, courses))
|
Create Histograme
요일마다 과제 수행정도를 보여주는 히스토그램을 만드는 함수.. (사실 그냥 별찍기)
Example
1
2
3
4
5
6
7
8
9
10
| ch = '*'
assignments = [12, 12, 14, 3, 12, 15, 14]
createHistogram(ch, assignments) = ["************",
"************",
"**************",
"***",
"************",
"***************",
"**************"]
|
My Answer
1
2
3
4
5
| def createHistogram(ch, assignments):
return list(map(lambda x: ch*x, assignments))
def createHistogram(ch, assignments):
return [ch * x for x in assignments]
|
Least Common Denominator
최소공통분모 구하는 함수
Example
1
2
3
4
5
6
7
8
9
| denominators = [2, 3, 4, 5, 6]
leastCommonDenominator(denominators) = 60
# 풀이
2 x 3 4 5 6
----- x ----- x ----- x -----
1 2 1 6 => (2와 3의 최대공약수, 2x3과 4의 최대 공약수.....)
|
Graphs