AttackOnNunu

Once more into the fray


  • 홈

  • About

  • 태그

  • 카테고리

  • 아카이브

  • 검색

(PYTHON) Day - 26 Numpy

작성일 2020-03-18 In LANGUAGE 🚀 , PYTHON , HACKERRANK 댓글:

Reference

  • 문제 출처 - HackerRank
  • 파이썬 연습 - Practice - Python

개인적인 생각과 상상으로 작성한 내용들이 포함되어 있습니다
문제를 풀고 Discussion Tab을 참고하며 코드 스타일을 개선하려고 노력하고자 합니다


HackerRank

HackerRank의 Python 연습문제들은 아래와 같은 카테고리로 분류 된다

Subdomain

- ~~Introduction~~
- ~~Basic Data Types~~
- ~~Strings~~
- ~~Sets~~
- ~~Math~~
- ~~Itertools~~
- ~~Collections~~
- ~~Date and Time~~
- ~~Errors and Exceptions~~
- ~~Classes~~
- ~~Built-Ins~~
- ~~Python Functionals~~
- ~~Regex and Parsing~~
- ~~XML~~
- ~~Closures and Decorators~~
- <strong style="color:blue">Numpy</strong>
- ~~Debugging~~

드디어 파이썬 끝냈다!!

fin


Numpy

지난번에 이어서…

  • 기본개념 - Day 2
  • 앞선 문제들 - Day 3

Problem

  • Arrays
  • Shape and Reshape
  • Transpose and Flatten
  • Concatenate
  • Zeros and Ones
  • Eye and Identity
  • Array Mathematics
  • Linear Algebra

Arrays


문제 : float형 원소들을 가지는 numpy 배열을 만드는 문제
입력 : 배열에 들어갈 원소들
출력 : 원소들을 거꾸로 출력하며 float형으로 바꾼다

  • INPUT
  • OUTPUT
input
1 2 3 4 -8 -10 
input
[-10. -8. 4. 3. 2. 1.] 

numpy.array() 안에서 타입 변환이 가능하다

import numpy

def arrays(arr):
return (numpy.array(arr[::-1], float))

arr = input().strip().split(' ')
result = arrays(arr)
print(result)

Shape and Reshape


문제 : 배열의 구조를 바꾸는 문제
입력 : 9개의 정수들
출력 : 3x3 구조로 배열을 수정

  • INPUT
  • OUTPUT
input
1 2 3 4 5 6 7 8 9 
output
[[1 2 3]
[4 5 6]
[7 8 9]]

numpy.shape() 함수를 사용하면 원본 배열을 수정하게 된다

import numpy

my_array = numpy.array([int(n) for n in input().split()])
my_array.shape = (3, 3)
print(my_array)

하지만 numpy.reshape() 함수는 새로운 배열을 만들기 때문에 원본 데이터를 건드리지 않는다

import numpy

my_array = numpy.array([int(n) for n in input().split()])
print(my_array.reshape(3, 3))

Transpose and Flatten


문제 : 전치 행렬(transpose)과 다차원을 1차원으로 반환하는(flatten) 문제
입력 : 행렬 크기 N, M; 행렬 입력;
출력 : transpose array; flatten;

  • INPUT
  • OUTPUT
input
2 2
1 2
3 4
input
[[1 3]
[2 4]]
[1 2 3 4]
import numpy

N, M = input().split()
my*array = numpy.array([input().split() for * in range(int(N))], int)

print(my_array.transpose())
print(my_array.flatten())

Concatenate


문제 : concatenate 함수를 사용해 NxP 행렬과 MxP 행렬을 합치는 문제
입력 : N, M, P; NxP 행렬; MxP 행렬;
출력 : (N + M) * P 크기의 행렬을 출력

  • INPUT
  • OUTPUT
input
4 3 2
1 2
1 2
1 2
1 2
3 4
3 4
3 4
input
[[1 2]
[1 2]
[1 2]
[1 2]
[3 4]
[3 4]
[3 4]]

axis=0 을 기준으로 합친다

import numpy

N, M, P = input().split()
N*array = numpy.array([input().split() for * in range(int(N))], int)
M*array = numpy.array([input().split() for * in range(int(M))], int)

print(numpy.concatenate((N_array, M_array), axis=0))

Zeros and Ones


문제 : 영행렬과 1로 채운 행렬을 구하는 문제
입력 : 행렬의 크기
출력 : numpy.zeros; numpy.ones;

  • INPUT
  • OUTPUT
input
3 3 3 
input
[[[0 0 0]
[0 0 0]
[0 0 0]]

[[0 0 0]
[0 0 0]
[0 0 0]]

[[0 0 0]
[0 0 0]
[0 0 0]]]
[[[1 1 1]
[1 1 1]
[1 1 1]]

[[1 1 1]
[1 1 1]
[1 1 1]]

[[1 1 1]
[1 1 1]
[1 1 1]]]

tuple로 묶어서 shape로 정리하는 것이 깔끔함

import numpy

shape = tuple(map(int, input().split()))
print(numpy.zeros(shape, int))
print(numpy.ones(shape, int))

Eye and Identity


문제 : 주 대각 원소들(main diagonal elements)이 1인 단위행렬을 구하는 문제
입력 : 행렬의 크기 N, M;
주의 : identity 함수는 정방행렬(행과 열의 크기가 같음)에 사용된다. 즉, 여기서는 eye 함수를 사용

  • INPUT
  • OUTPUT
input
3 3 
output
[[1.  0.  0.]
[ 0. 1. 0.]
[ 0. 0. 1.]]

numpy 출력할 때 공백이 하나 더 있어서 프린트 옵션을 추가하지 않으면 오류 처리됨

import numpy

N, M = map(int, input().split())
numpy.set_printoptions(sign=' ')
print(numpy.eye(N, M))

Array Mathematics


문제 : 사칙연산 결과를 구하는 문제
입력 : 행렬의 크기 N, M; (NxM 크기의)행렬 A; (NxM 크기의)행렬 B;
출력 : +, -, *, /, %, ** 의 결과를 차례로 출력

  • INPUT
  • OUTPUT
input
1 4
1 2 3 4
5 6 7 8
output
[[6  8 10 12]]
[[-4 -4 -4 -4]]
[[5 12 21 32]]
[[0 0 0 0]]
[[1 2 3 4]]
[[1 64 2187 65536]]

나눗셈은 그냥 divide()가 아닌 floor_divide() 사용해야함

import numpy

N, M = input().split()
A = numpy.array([input().split() for _ in range(int(N))], int)
B = numpy.array([input().split() for _ in range(int(N))], int)

print(numpy.add(A, B))
print(numpy.subtract(A, B))
print(numpy.multiply(A, B))
print(numpy.floor_divide(A, B))
print(numpy.mod(A, B))
print(numpy.power(A, B))

Linear Algebra


문제 : 행렬식을 구하는 문제
입력 : 행렬 크기 N; NxN 크기의 행렬;
출력 : 행렬식(determinant)

  • INPUT
  • OUTPUT
input
2
1.1 1.1
1.1 1.1
output
0.0 

legacy 를 1.13으로 변경해 줘야한다

import numpy

n = int(input())
a = numpy.array([input().split() for _ in range(n)],float)

numpy.set_printoptions(legacy='1.13')
print(numpy.linalg.det(a))

(PYTHON) Day - 25 Closures and Decorators & Debugging

작성일 2020-03-17 In LANGUAGE 🚀 , PYTHON , HACKERRANK 댓글:

Reference

  • 문제 출처 - HackerRank
  • 파이썬 연습 - Practice - Python

개인적인 생각과 상상으로 작성한 내용들이 포함되어 있습니다
문제를 풀고 Discussion Tab을 참고하며 코드 스타일을 개선하려고 노력하고자 합니다


HackerRank

HackerRank의 Python 연습문제들은 아래와 같은 카테고리로 분류 된다

Subdomain

- ~~Introduction~~
- ~~Basic Data Types~~
- ~~Strings~~
- ~~Sets~~
- ~~Math~~
- ~~Itertools~~
- ~~Collections~~
- ~~Date and Time~~
- ~~Errors and Exceptions~~
- ~~Classes~~
- ~~Built-Ins~~
- ~~Python Functionals~~
- ~~Regex and Parsing~~
- ~~XML~~
- <strong style="color:blue">Closures and Decorators</strong>
- Numpy
- <strong style="color:blue">Debugging</strong>

Closures and Decorators

Problem

  • Standardize Mobile Number Using Decorators
  • Decorators 2 - Name Directory

파이썬의 기초를 다루고 있어서 그런지 클로저와 데코레이터를 깊이 다루지는 않는다

기본개념

외부 참조
Understanding Python Decorators in 12 Easy Steps! - Simeon Franklin

Standardize Mobile Number Using Decorators


문제 : 전화번호를 양식에 맞게 수정하고 정렬해서 출력하는 문제
입력 : 전화번호는 10자리, 앞에 +91, 91, 0 등이 붙어서 입력될 수 있음
출력 : +91 xxxxx xxxxx 형식으로 출력

  • INPUT
  • OUTPUT
input
3
07895462130
919875641230
9195969878
output
+91 78954 62130
+91 91959 69878
+91 98756 41230

앞에 +91, 91, 0 중 무엇이 오던 그냥 뒤에서 10자리만 생각하면 된다

def wrapper(f):
def fun(l):
f([f"+91 {num[-10:-5]} {num[-5:]}" for num in l]) # f('+91 {} {}'.format(num[-10:-5], num[-5:]) for num in l)
return fun

@wrapper
def sort_phone(l):
print(\*sorted(l), sep='\n')

if **name** == '**main**':
l = [input() for _ in range(int(input()))]
sort_phone(l)

Decorators 2 - Name Directory


문제 : 이름, 나이, 성별을 입력받았을 때 나이순으로 출력하며 성별에 따라 이름 앞을 변경하는 문제
입력 : 이름, 나이, 성별
출력 : 남성이면 Mr, 여성이면 Ms 를 붙인다

  • INPUT
  • OUTPUT
input
3
Mike Thomson 20 M
Robert Bustle 32 M
Andria Bustle 30 F
output
Mr. Mike Thomson
Ms. Andria Bustle
Mr. Robert Bustle

리스트를 나이 순으로 정렬하고 포맷을 변경한다

import operator

def person_lister(f):
def inner(people):
return map(f, sorted(people, key= lambda x: int(x[2])))
return inner

@person_lister
def name_format(person):
return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1]

if **name** == '**main**':
people = [input().split() for i in range(int(input()))]
print(\*name_format(people), sep='\n')


Debugging

Problem

  • Words Score
  • Default Arguments

소스코드가 주어지고 디버깅을 통해 오류를 찾아내는 문제들이여서 생략함

(PYTHON) Day - 24 XML

작성일 2020-03-16 In LANGUAGE 🚀 , PYTHON , HACKERRANK 댓글:

Reference

  • 문제 출처 - HackerRank
  • 파이썬 연습 - Practice - Python

개인적인 생각과 상상으로 작성한 내용들이 포함되어 있습니다
문제를 풀고 Discussion Tab을 참고하며 코드 스타일을 개선하려고 노력하고자 합니다


HackerRank

HackerRank의 Python 연습문제들은 아래와 같은 카테고리로 분류 된다

Subdomain

- ~~Introduction~~
- ~~Basic Data Types~~
- ~~Strings~~
- ~~Sets~~
- ~~Math~~
- ~~Itertools~~
- ~~Collections~~
- ~~Date and Time~~
- ~~Errors and Exceptions~~
- ~~Classes~~
- ~~Built-Ins~~
- ~~Python Functionals~~
- ~~Regex and Parsing~~
- <strong style="color:blue">XML</strong>
- Closures and Decorators
- Numpy
- Debugging

XML

Problem

  • XML 1 - Find the Score
  • XML2 - Find the Maximum Depth

XML 1 - Find the Score


문제 : XML 문서의 속성값들의 개수를 구하는 문제
참고 : XML

  • INPUT
  • OUTPUT
input
6
<feed xml:lang='en'>
<title>HackerRank</title>
<subtitle lang='en'>Programming challenges</subtitle>
<link rel='alternate' type='text/html' href='http://hackerrank.com/'/>
<updated>2013-12-25T12:00:00</updated>
</feed>
output
5
import sys
import xml.etree.ElementTree as etree

def get_attr_number(node):
num = len(node.attrib)
return num + sum((get_attr_number(child) for child in node))

if **name** == '**main**':
sys.stdin.readline()
xml = sys.stdin.read()
tree = etree.ElementTree(etree.fromstring(xml))
root = tree.getroot()
print(get_attr_number(root))

XML2 - Find the Maximum Depth


문제 : XML 문서의 최대 depth를 구하는 문제
예제 : feed 태그는 root로 depth는 0이다. title, subtitle, link, updated 태그들은 depth가 1이다.

  • INPUT
  • OUTPUT
input
6
<feed xml:lang='en'>
<title>HackerRank</title>
<subtitle lang='en'>Programming challenges</subtitle>
<link rel='alternate' type='text/html' href='http://hackerrank.com/'/>
<updated>2013-12-25T12:00:00</updated>
</feed>
output
1
import xml.etree.ElementTree as etree

maxdepth = 0
def depth(elem, level):
global maxdepth
level += 1
if level >= maxdepth:
maxdepth = level
for child in elem:
depth(child, level)

if **name** == '**main**':
n = int(input())
xml = ""
for i in range(n):
xml = xml + input() + "\n"
tree = etree.ElementTree(etree.fromstring(xml))
depth(tree.getroot(), -1)
print(maxdepth)
1…456…33
NUNU

NUNU

개인적으로 공부하면서 정리한 내용들을 블로그에 남기고 있습니다.
99 포스트
18 카테고리
53 태그
RSS
Creative Commons
© 2021 NUNU
Powered by Hexo v3.9.0
|
Theme – NexT.Mist v7.2.0