규도자 개발 블로그

[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 14: Scope 본문

알고리즘/풀이

[해커랭크(Hackerrank)/30 Days of Code/파이썬3(python3)] Day 14: Scope

규도자 (gyudoza) 2019. 3. 26. 21:02

Objective 
Today we're discussing scope. Check out the Tutorial tab for learning materials and an instructional video!


The absolute difference between two integers,  and , is written as . The maximum absolute difference between two integers in a set of positive integers, , is the largest absolute difference between any two integers in .

The Difference class is started for you in the editor. It has a private integer array () for storing  non-negative integers, and a public integer () for storing the maximum absolute difference.

Task 
Complete the Difference class by writing the following:

  • A class constructor that takes an array of integers as a parameter and saves it to the  instance variable.
  • computeDifference method that finds the maximum absolute difference between any  numbers in  and stores it in the  instance variable.

Input Format

You are not responsible for reading any input from stdin. The locked Solution class in your editor reads in  lines of input; the first line contains , and the second line describes the  array.

Constraints

  • , where 

Output Format

You are not responsible for printing any output; the Solution class will print the value of the  instance variable.

Sample Input

3
1 2 5

Sample Output

4

Explanation

The scope of the  array and  integer is the entire class instance. The class constructor saves the argument passed to the constructor as the  instance variable (where the computeDifference method can access it).

To find the maximum difference, computeDifference checks each element in the array and finds the maximum difference between any  elements:  
 

The maximum of these differences is , so it saves the value  as the  instance variable. The locked stub code in the editor then prints the value stored as , which is .

풀이

	# Add your code here
    maximumDifference = 0
    def computeDifference(self):
        self.maximumDifference = abs(max(self.__elements) - min(self.__elements))

설명

집합으로 주어진 수에서 두 수를 선택해서 뺐을 때 가장 클 때의 절대값을 구하는 문제이다. 입력 제반사항에 음수에 대한 케이스가 없으므로 절대값이 가장 큰 경우는 결국 가장 큰 수와 가장 작은 수를 뺐을 때이다. 하여 파이썬 내장함수를 이용하여 간단하게 구현하였다. 사실 문제의 의도는 scope를 이용하여 모든 경우의 수를 빼면서 나오는 가장 큰 절대값을 계속 교체해가면서 구하는 거지만 굳이 어려운 길을 돌아갈 필요가 있나 싶었다. 의도대로 구현하기 위해선 global 변수를 쓰면 될 것이다.

Comments