You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
8-1 ) Triple Step : A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.
# 피보나치 수열과 비슷# n이 0일떄를 1로 보느냐 0으로 보느냐에 따라 코드가 달라질 듯# n = 0일때 방법을 1으로 가정defgetPosWayCnt(n):
way_cnts= [1, 1, 2]
ifn<3:
returnway_cnts[n]
foriinrange(3, n+1):
way_cnts.append(sum(way_cnts[i-3:i]))
returnway_cnts[n]
8-2 ) Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.
# 참고 : 가짓수를 찾는 문제 https://velog.io/@tjdud0123/%EB%93%B1%EA%B5%A3%EA%B8%B8# off limits(금지구역)가 2차 배열로 주어진다 가정 [x, y] ex) [[2, 2], [3, 2]]# ? parameter가 많아져 global로 선언 => 오염문제 (어떻게 해야 가장 좋은가 ?)defsolution(r, c, limits):
globalr, c, limitslimits=set([(y, x) forx, yinlimits])
cur_y, cur_x=0, 0path= []
returngetPath(cur_y, cur_x, path)
defgetPath(cur_y, cur_x, path):
globalr, c, limitspath.append((cur_y, cur_x))
ifcur_y==r-1andcur_x==c-1:
returnpath# 아래 또는 오른쪽 이동DELTAS= {'D': (1, 0), 'R': (0, 1)}
fordy, dxinDELTAS.values():
nxt_y, nxt_x=cur_y+dy, cur_x+dxifvisitable(nxt_y, nxt_x):
getPath(nxt_y, nxt_x, path)
#이동 불가ifpath:
path.pop()
else:
returnNonedefvisitable(nxt_y, nxt_x):
globalr, c, limitsisOffLimit= (nxt_y, nxt_x) inlimitsreturn0<=nxt_y<rand0<=nxt_x<candnotisOffLimit
8-3 ) Magic Index: A magic index in an array A[e... n-1] is defined to be an index such that A[ i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A.
# 정렬되어있고 같은원소가 아니라는 것이 관건# 포인터를 두고 arr를 복사하지 않는것이 효율적!defsolution(n, arr):
returngetMagicIdx(arr)
defgetMagicIdx(arr):
ifnotarr:
returnNonemid=len(arr) //2ifarr[mid] ==mid:
returnmidelifarr[mid] >mid:
returngetMagicIdx(arr[:mid])
else:
returngetMagicIdx(arr[mid+1:])
# 같은 원소가 있을때는 brute force한 방법밖엔 모르겠음defgetMagicIdx(n, arr):
foriinrange(n):
ifarr[i] ==i:
returnireturnNone
8-4 ) Power Set: Write a method to return all subsets of a set.
8-6 ) Towers of Hanoi: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (Le., each disk sits on top of an even larger one). You have the following constraints:
defhanoi(num, fr, to, temp, moves):
ifnum==1:
moves.append([fr,to])
else:
hanoi(num-1, fr, temp, to, moves)
moves.append([fr,to])
hanoi(num-1, temp, to, fr, moves)
defsolution(n):
moves= []
hanoi(n, 1, 3, 2, moves)
returnmoves
8-7 )Permutations without Dups: Write a method to compute all permutations of a string of unique characters.
8-10 )Paint Fill: Implement the "paint nil" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, nil in the surrounding area until the color changes from the original color.
# point = (x, y)fromcollectionsimportdequedeffillPaint(screen, point, new_color):
r, c=len(screen), len(screen[0])
y, x=pointold_color=screen[y][x]
ifnotvisitable(y, x, r, c):
returnFalseDELTAS= [(0, 1), (0, -1), (-1, 0), (1, 0)]
que, visited=deque([point]), set([point])
whileque:
cur_y, cur_x=que.popleft()
screen[cur_y][cur_x] =new_colorvisited.add((y, x))
fordy, dxinDELTAS:
nxt_y, nxt_x=cur_y+dy, cur_x+dx# 방문 불가ifnotvisitable(nxt_y, nxt_x, r, c) or (nxt_y, nxt_x) invisited:
continue# 방문 가능하지만 같은컬러만 색칠ifscreen[nxt_y][nxt_x] ==old_color:
que.append((nxt_y, nxt_x))
defvisitable(nxt_y, nxt_x, r, c):
return0<=nxt_y<rand0<=nxt_x<c
8-11 ) Coins: Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent), write code to calculate the number of ways of representing n cents.
8-12 ) Eight Queens: Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them share the same row, column, or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board.