(출처) https://www.testdome.com/question/python

 

 

 

 

(1) Path

(문제)

Write a function that provides change directory (cd) function for an abstract file system.

추상 파일시스템을 위한 디렉토리 변경 기능을 제공하는 cd 함수를 작성하시오.

 

Notes:

 

Root path is '/'.

Path separator is '/'.

Parent directory is addressable as '..'.

Directory names consist only of English alphabet letters (A-Z and a-z).

The function should support both relative and absolute paths.

The function will not be passed any invalid paths.

Do not use built-in path-related functions.

루트 경로는 / 이다.

경로 구분 기호는 / 이다.

상위디렉토리는 ..으로 주소 지정이 가능하다.

디렉토리 이름은 영어 알파벳 문자(A-Z, a-z)로만 구성된다.

함수는 상대경로와 절대경로를 모두 지원해야 한다.

이 함수는 잘못된 경로를 전달하지 않는다.

경로와 관련된 내장 함수 기능을 사용하지 않는다.

 

For example:

 

path = Path('/a/b/c/d')

path.cd('../x')

print(path.current_path)

 

should display

 

'/a/b/c/x'.

 

(예시)

class Path:

def __init__(self, path):

self.current_path = path

 

def cd(self, new_path):

pass

 

 

path = Path('/a/b/c/d')

path.cd('../x')

print(path.current_path)

    (풀이)
class Path:
    pathes = []         # current_path에 대한 list

    def __init__(self, basic_path):
        if basic_path.isalpha():     # No space & No digit
            return
        self.current_path = basic_path
        Path.pathes = self.current_path.split('/')

    def cd(self, new_path):
        if new_path.isalpha():       # No space & No digit
            return
        new_path_list = new_path.split('/')
        # 절대 경로를 지정한 경우는 입력된 내용을 그대로 표시
        if new_path_list[0] == "":
            self.current_path = new_path
            Path.pathes = self.current_path.split('/')
        # 상대경로를 지정한 경우 ..이면 하나를 지우고, 나머지이면 하나를 더하도록 한다.
        elif '..' in new_path_list:
            for i in new_path_list:
                if i == '..' :
                    Path.pathes.pop()
                else:
                    Path.pathes.append(i)
            self.current_path = "/".join(Path.pathes)
        else:
            print("Wrong Path")


path = Path('/a/b/c/d/e/f')
path.cd('../x')
print(path.current_path)
path.cd('/a/b/c')
print(path.current_path)
path.cd('../..')
print(path.current_path)


or


isalpha()
https://www.tutorialspoint.com/python/string_isalpha.htm

PEP8 규칙
PEP에 따라서 __init__ 함수의 인자인 path를 basic_path 변경하였다. 
하단의 코드에 보면 Path class의 object 이름으로 path를 사용하였으므로, 
이름이 같기 때문에 코드 분석에 문제가 생길 수 있는 부분을 방지한 것.

class Path:
    def __init__(self, path):
        self.current_path = path

    def cd(self, new_path):
        if new_path[0] == "/":
            self.current_path = new_path
        else:
            current_path_list = self.current_path.split('/')[1:]
            new_path_list = new_path.split('/')
            for i in new_path_list:
                if i == "..": current_path_list.pop()
                else: current_path_list.append(i)
            self.current_path = "/" + "/".join(current_path_list)

path = Path('/a/b/c/d')
path.cd('../x') 
print(path.current_path)

 

 

 

 

 

 

아직 못 품

 

(2) Ice Cream Machine

 

Implement the IceCreamMachine's scoops method so that it returns all combinations of one ingredient and one topping. If there are no ingredients or toppings, the method should return an empty list.

IceCreamMachine의 scoops method를 구현하여 하나의 성분과 하나의 토핑의 모든 조합을 반환한다. 성분이나 토핑이 없는 경우 method는 빈 목록을 반환해야 한다.

 

For example, IceCreamMachine

(["vanilla", "chocolate"], ["chocolate sauce"]).scoops()

should return

[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']].

 

 

(예시)

class IceCreamMachine:

def __init__(self, ingredients, toppings):

self.ingredients = ingredients

self.toppings = toppings

 

def scoops(self):

pass

 

machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"])

print(machine.scoops()) #should print[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]

 

 

(3) Playlist

(문제)

A playlist is considered a repeating playlist if any of the songs contain a reference to a previous song in the playlist. Otherwise, the playlist will end with the last song which points to None.

재생목록은 재생목록의 이전 노래에 대한 참조가가 포함된 노래가 있다면, 반복 재생 목록으로 간주한다. 그렇지 않으면 재생목록은 마지막 노래가 없는 경우 끝난다.

Implement a function is_repeating_playlist that, efficiently with respect to time used, returns true if a playlist is repeating or false if it is not.

is_repeating_playlist 함수를 구현한다. 이 함수는 효율적으로 재생목록이 반복 될 경우 true를 return 하고 그렇지 않으며 false를 return한다.

 

For example, the following code prints "True" as both songs point to each other.

 

first = Song("Hello")

second = Song("Eye of the tiger")

first.next_song(second);

second.next_song(first);

print(first.is_repeating_playlist())


(예시)

class Song:

def __init__(self, name):

self.name = name

self.next = None

 

def next_song(self, song):

self.next = song

def is_repeating_playlist(self):

"""

:returns: (bool) True if the playlist is repeating, False if not.

"""

return None

first = Song("Hello")

second = Song("Eye of the tiger")

first.next_song(second);

second.next_song(first);

print(first.is_repeating_playlist())

 

 

(풀이)

직접 문제를 풀어보자



 

(4) Binary Search Tree

 

(문제)

Binary search tree (BST) is a binary tree where the value of each node is larger or equal to the values in all the nodes in that node's left subtree and is smaller than the values in all the nodes in that node's right subtree.

BST는 각 노드의 값이 해당 노드의 왼쪽 하위 트리에 있는 모든 노드의 값보다 크거나 같고, 해당 노드의 오른쪽 하위 트리에 있는 모든 노드의 값보다 작은 2진 트리이다.

 

Write a function that, efficiently with respect to time used, checks if a given binary search tree contains a given value.

사용된 시간과 관련하여 효율적으로 주어진 BST(이진 검색 트리)에 주어진 값이 포함되어 있는지 확인하는 함수를 작성하시오.

 

For example, for the following tree:

 

n1 (Value: 1, Left: null, Right: null)

n2 (Value: 2, Left: n1, Right: n3)

n3 (Value: 3, Left: null, Right: null)

 

Call to contains(n2, 3) should return True since a tree with root at n2 contains number 3.

contains(n2,3) 호출하면 n2에 루트가 있는 트리에 3이 있으므로 True를 반환해야 한다.

 

 

■ BST 트리 구조에 대해서(기본 구조)

10

5 12

 

■ 새로운 값으로 6이 들어오는 경우(기본 구조 + 6)

10

5 12

6

 

■ 새로운 값으로 3이 들어오는 경우(기본 구조 + 6 + 3)

10

5 12

3 6

 

■ 새로운 값으로 15이 들어오는 경우(기본 구조 + 6 + 3 + 15)

10

5 12

3 6 15

 

■ (Binary Search Tree) 주어진 조건에 맞는 그림을 그려보면,

 

n2(2, L:n1, R:n3)

|

|

+---------+---------+

| |

n1(1, L:N, R:N) n3(3, L:N, R:N)

 

 

 

(예시)

import collections

 

class BinarySearchTree:

 

Node = collections.namedtuple('Node', ['left', 'right', 'value'])

@staticmethod

def contains(root, value):

pass

 

n1 = BinarySearchTree.Node(value=1, left=None, right=None)

n3 = BinarySearchTree.Node(value=3, left=None, right=None)

n2 = BinarySearchTree.Node(value=2, left=n1, right=n3)

 

print(BinarySearchTree.contains(n2, 3))


(풀이)

직접 풀어 보시오.



 

 

(5) Two Sum

(문제)

Write a function that, when passed a list and a target sum, returns, efficiently with respect to time used, two distinct zero-based indices of any two of the numbers, whose sum is equal to the target sum. If there are no two numbers, the function should return None.

목록과 대상 합계를 전달할 때, 사용된 시간과 관련하여 효율적으로 반환하는 함수를 작성한다. 이 함수의 대상 합계와 같다. 2개의 숫자가 없으면 함수는 None을 반환해야 한다.

 

For example, find_two_sum([3, 1, 5, 7, 5, 9], 10) should return a single tuple containing any of the following pairs of indices:

 

0 and 3 (or 3 and 0) as 3 + 7 = 10

1 and 5 (or 5 and 1) as 1 + 9 = 10

2 and 4 (or 4 and 2) as 5 + 5 = 10

 

 

(예시)

class TwoSum:

 

@staticmethod

def find_two_sum(numbers, target_sum):

"""

:param numbers: (list of ints) The list of numbers.

:param target_sum: (int) The required target sum.

:returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum

"""

return None

 

print(TwoSum.find_two_sum([3, 1, 5, 7, 5, 9], 10))

 

 

(풀이)

직접 풀어 보시오.



 

(6) File Owners

(문제)

Implement a group_by_owners function that:

다음과 같이 group_by_owners 함수를 구현한다.

 

Accepts a dictionary containing the file owner name for each file name.

Returns a dictionary containing a list of file names for each owner name, in any order.

각 파일 이름에 대한 파일 소유자 이름이 포함된 하나의 dictionary 구현한다.

각 소유자 이름에 대한 파일 이름의 목록을 포함한 dictionary을 return 한다.

 

For example, for dictionary

{'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'}

the group_by_owners function should return

{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}.

 

 

(예시)

class FileOwners:

 

@staticmethod

def group_by_owners(files):

return None

 

files = {

'Input.txt': 'Randy',

'Code.py': 'Stan',

'Output.txt': 'Randy'

}

print(FileOwners.group_by_owners(files))

 

 

[참고] [문제/풀이] File Owners 문제 풀이

 

 

(7) League Table

(문제)

The LeagueTable class tracks the score of each player in a league. After each game, the player records their score with the record_result function.

 

The player's rank in the league is calculated using the following logic:

 

1. The player with the highest score is ranked first (rank 1). The player with the lowest score is ranked last.

2. If two players are tied on score, then the player who has played the fewest games is ranked higher.

3. If two players are tied on score and number of games played, then the player who was first in the list of players is ranked higher.

Implement the player_rank function that returns the player at the given rank.

 

For example:

 

table = LeagueTable(['Mike', 'Chris', 'Arnold'])

table.record_result('Mike', 2)

table.record_result('Mike', 3)

table.record_result('Arnold', 5)

table.record_result('Chris', 5)

print(table.player_rank(1))

 

All players have the same score. However, Arnold and Chris have played fewer games than Mike, and as Chris is before Arnold in the list of players, he is ranked first. Therefore, the code above should display "Chris".

 

 

(예시)

from collections import Counter

from collections import OrderedDict

 

class LeagueTable:

def __init__(self, players):

self.standings = OrderedDict([(player, Counter()) for player in players])

def record_result(self, player, score):

self.standings[player]['games_played'] += 1

self.standings[player]['score'] += score

def player_rank(self, rank):

return None

table = LeagueTable(['Mike', 'Chris', 'Arnold'])

table.record_result('Mike', 2)

table.record_result('Mike', 3)

table.record_result('Arnold', 5)

table.record_result('Chris', 5)

print(table.player_rank(1))

 

 

(풀이)

직접 풀어 보시오.



(8) Palindrome

(문제)

Anonymous

A palindrome is a word that reads the same backward or forward.

 

Write a function that checks if a given word is a palindrome. Character case should be ignored.

 

For example, is_palindrome("Deleveled") should return True as character case should be ignored, resulting in "deleveled", which is a palindrome since it reads the same backward and forward.


(예시)

class Palindrome:

 

@staticmethod

def is_palindrome(word):

return None

 

print(Palindrome.is_palindrome('Deleveled'))


(풀이)

직접 풀어 보시오.



 

(9) Pipeline

(문제)

As part of a data processing pipeline, complete the implementation of the pipeline method:

 

The method should accept a variable number of functions, and it should return a new function that accepts one parameter arg.

The returned function should call the first function in the pipeline with the parameter arg, and call the second function with the result of the first function.

The returned function should continue calling each function in the pipeline in order, following the same pattern, and return the value from the last function.

 

For example, Pipeline.pipeline(lambda x: x * 3, lambda x: x + 1, lambda x: x / 2) then calling the returned function with 3 should return 5.0.

 

 

(예시)

class Pipeline:

@staticmethod

def pipeline(*funcs):

def helper(arg):

pass

return helper

fun = Pipeline.pipeline(lambda x: x * 3, lambda x: x + 1, lambda x: x / 2)

print(fun(3)) #should print 5.0


(풀이)

직접 풀어 보시오.



 

 

 

 

 

 

(10) Merge Names

 

(문제)

Implement the unique_names method. When passed two arrays of names, it will return an array containing the names that appear in either or both arrays. The returned array should have no duplicates.

 

For example, calling MergeNames.unique_names(['Ava', 'Emma', 'Olivia'], ['Olivia', 'Sophia', 'Emma']) should return an array containing Ava, Emma, Olivia, and Sophia in any order.

 

 

(예시)

class MergeNames:

 

@staticmethod

def unique_names(names1, names2):

return None

 

names1 = ["Ava", "Emma", "Olivia"]

names2 = ["Olivia", "Sophia", "Emma"]

print(MergeNames.unique_names(names1, names2)) # should print Ava, Emma, Olivia, Sophia

 

 

(풀이)

직접 풀어 보시오.

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
반응형

'알고리즘 > 코딩테스트 문제풀기' 카테고리의 다른 글

Python Online test  (0) 2020.12.23

+ Recent posts