AttackOnNunu

Once more into the fray


  • 홈

  • About

  • 태그

  • 카테고리

  • 아카이브

  • 검색

(PYTHON) Day - 21 Python Functionals

작성일 2020-03-12 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~~
- <strong style="color:blue">Python Functionals</strong>
- Regex and Parsing
- XML
- Closures and Decorators
- Numpy
- Debugging

Python Functionals

Problem

  • Map and Lambda Function
  • Validating Email Addresses With a Filter
  • Reduce Function

Map and Lambda Function


문제 : 피보나치 수열을 출력하는 문제
입력 : 수열의 길이
출력 : 피보나치 수열 리스트

  • INPUT
  • OUTPUT

5

[0, 1, 1, 8, 27]

기본 형식에 맞춰서 문제를 풀면 다음과 같다

cube = lambda x: x\*\*3 # complete the lambda function

def fibonacci(n): # return a list of fibonacci numbers
fibo = [0, 1]
for i in range(2, n):
fibo.append(fibo[i-1]+fibo[i-2])

return fibo[0:n]

if **name** == '**main**':
n = int(input())
print(list(map(cube, fibonacci(n))))

피보나치 수열을 재귀함수로 풀면서 lambda 함수로 표현하면 다음과 같다

cube = lambda x: x\*\*3 # complete the lambda function

fibonacci = lambda x: x if x <= 1 else fibonacci(x-1) + fibonacci(x-2)

if **name** == '**main**':
n = int(input())
print(list(map(cube, map(fibonacci, range(n)))))

Validating Email Addresses With a Filter


문제 : 유효한 이메일 주소를 사전순으로 출력하는 문제
입력 : 이메일 개수 N; (N 반복) 이메일 주소
출력 : 사전순으로 정렬된 리스트로 출력
조건 :
username@websitename.extension 형식을 따른다
username은 오직 문자, 숫자, 대시 그리고 언더스코어만 가질 수 있다
websitename은 오직 문자와 숫자만 가질 수 있다
extension의 최대 길이는 3 이다

  • INPUT
  • OUTPUT

3
lara@hackerrank.com
brian-23@hackerrank.com
britts_54@hackerrank.com

[‘brian-23@hackerrank.com’, ‘britts_54@hackerrank.com’, ‘lara@hackerrank.com’]

isalnum() 함수를 사용하여 문자나 숫자로 이루어졌는지 확인할 수 있다

def fun(s): # return True if s is a valid email, else return False
try:
username, site = s.split('@')
websitename, extension = site.split('.')
except:
return False

username = ''.join(i for i in username if i not in "-_")

return username.isalnum() and websitename.isalnum() and len(extension) <= 3

def filter_mail(emails):
return list(filter(fun, emails))

if **name** == '**main**':
n = int(input())
emails = []
for \_ in range(n):
emails.append(input())

filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)

정규표현식을 사용하면서 and 연산자가 아닌 all 연산자로 마지막을 확인하는 방법(fun 함수만 작성 이하 동일)

import re

def fun(s):
try:
user,website,domain=re.split('\@|\.',s)
except:
return False
processed=user.replace('-','').replace('\_','')
return all( [processed.isalnum(), website.isalnum(), len(domain)<=3] )

__


Reduce Function


문제 : (분수로 표현되는)유리수들의 곱셈 결과를 출력하는 문제
입력 : 유리수 개수 n; (n 반복) 분자, 분모 형식으로 입력;
출력 : 곱셈의 결과

  • INPUT
  • OUTPUT

3
1 2
3 4
10 6

5 8

reduce() 함수 안에서 lambda 식을 사용하지 않고도 operator 모듈을 사용해서 구현할 수 있는 것을 배웠다

from fractions import Fraction
from functools import reduce

# from operator import mul

def product(fracs):
t = reduce(lambda x, y: x \* y, fracs) # t = reduce(mul, fracs)
return t.numerator, t.denominator

if **name** == '**main**':
fracs = []
for \_ in range(int(input())):
fracs.append(Fraction(*map(int, input().split())))
result = product(fracs)
print(*result)

(PYTHON) Day - 20 Built-Ins

작성일 2020-03-11 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~~
- <strong style="color:blue">Built-Ins</strong>
- Python Functionals
- Regex and Parsing
- XML
- Closures and Decorators
- Numpy
- Debugging

Built-Ins

Problem

  • Zipped!
  • Input()
  • Python Evaluation
  • Athlete Sort
  • Any or All
  • ginortS

Zipped!


문제 : 학생들의 성적 평균을 구하는 문제
입력 : 학생수 N, 과목수 X; (X 반복) 과목당 학생들의 성적 score;
출력 : 과목별 평균

mark sheet은 다음과 같다

Student ID → **\_1\_\_\_**2**\_**3**\_**4**\_**5**  
Subject 1 | 89 90 78 93 80
Subject 2 | 90 91 85 88 86
Subject 3 | 91 92 83 89 90.5
|************\_\_\_\_**************
Average 90 91 82 90 85.5
  • INPUT
  • OUTPUT

5 3
89 90 78 93 80
90 91 85 88 86
91 92 83 89 90.5

90.0
91.0
82.0
90.0
85.5

N, X = map(int, input().split())
subjects = []
for \_ in range(X):
subjects.append(map(float, input().split()))

for scores in zip(\*subjects):
print(sum(scores)/len(scores))

Input()


문제 : 입력받은 x와 k의 값이 식을 만족하는지 확인하는 문제
입력 : x, k; 다항식 P;
출력 : 다항식에 x의 값을 대입했을 때 k와 같으면 True, 아니면 False 출력

  • INPUT
  • OUTPUT

1 4
x3 + x2 + x + 1

True

x, k = map(int, input().split())
print(eval(input()) == k)

Python Evaluation


문제 : 단순히 eval() 함수를 사용하면 되는 문제
입력 : 실행할 표현식
출력 : 표현식의 결과값

  • INPUT
  • OUTPUT

print(2 + 3)

5

eval(input()) 

Athlete Sort


문제 : 데이터를 k번째 속성을 기준으로 정렬하는 문제
입력 : 데이터수 N, 속성수 M; (N 반복) 데이터 입력; 기준이 될 속성 K;
출력 : k번째 원소 기준으로 정렬된 결과값

example

  • INPUT
  • OUTPUT

5 3
10 2 5
7 1 0
9 9 9
1 23 12
6 5 9
1

7 1 0
10 2 5
6 5 9
9 9 9
1 23 12

정렬할 때, key를 잘 신경써주면 쉽게 풀리는 문제

N, M = map(int, input().split())
data = [input().split() for _ in range(N)]
k = int(input())

for d in sorted(data, key=lambda d: int(d[k])):
print(\*d)

Any or All


문제 : 입력받은 정수들이 모두 양수인지 확인하고 대칭수(palindromic number)가 있는지 확인하는 문제
입력 : 정수의 개수 N; 정수들;
출력 : True/False

  • INPUT
  • OUTPUT

5
12 9 61 5 14

True

commet

\_, numbers = input(), input().split()
print(all(map(lambda x: int(x)>=0, numbers)) and any(map(lambda x: x==x[::-1], numbers)))

# 혹은

\_, numbers = input(),input().split()
print(all(int(x)>0 for x in numbers) and any(x==x[::-1] for x in numbers))

ginortS


문제 : 조건에 맞게 문자열을 재정렬 하는 문제
입력 : 문자열 S
조건 : 소문자 > 대문자 > 숫자 순으로 정렬한다. 홀수가 짝수 앞에 온다.
출력 : 새로 정렬된 문자열

ginortS

  • INPUT
  • OUTPUT

Sorting1234

ginortS1324

def getKey(x):
if x.islower():
return(1,x)
elif x.isupper():
return(2,x)
elif x.isdigit() :
if int(x)%2==1:
return(3,x)
else :
return(4,x)

print(\*sorted(input(),key=getKey),sep='')

(PYTHON) Day - 19 Classes

작성일 2020-03-10 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~~
- <strong style="color:blue">Classes</strong>
- Built-Ins
- Python Functionals
- Regex and Parsing
- XML
- Closures and Decorators
- Numpy
- Debugging

Classes

Problem

  • Classes: Dealing with Complex Numbers
  • Class 2 - Find the Torsional Angle

Classes: Dealing with Complex Numbers


문제 : 복소수 2개를 입력 받고 4칙연산과 나머지를 구하는 문제
입력 : 실수와 허수 부분을 정수로 입력(e.g. 2 1 -> 2.00 + 1.00i)
출력 : 더하기, 빼기, 곱하기, 나누기, 나머지를 출력

복소수의 사칙연산 - HI-KIM
덧셈
뺄셈
곱셈
나눗셈
모듈러스

  • INPUT
  • OUTPUT

2 1
5 6

7.00+7.00i
-3.00-5.00i
4.00+17.00i
0.26-0.11i
2.24+0.00i
7.81+0.00i

나눗셈이 가장 까다로웠다. 공식대로 푸는 방법과 실수, 허수 부분을 구분해서 구하는 방법 2가지로 구현할 수 있다.

import math

class Complex(object):
def **init**(self, real, imaginary):
self.real = real
self.imaginary = imaginary

def __add__(self, no):
real = self.real + no.real
imaginary = self.imaginary + no.imaginary
return Complex(real, imaginary)

def __sub__(self, no):
real = self.real - no.real
imaginary = self.imaginary - no.imaginary
return Complex(real, imaginary)

def __mul__(self, no):
real = (self.real * no.real) - (self.imaginary * no.imaginary)
imaginary = (self.real * no.imaginary) + (self.imaginary * no.real)
return Complex(real, imaginary)

def __truediv__(self, no):
# 공식 대입
# calc = self.__mul__(Complex(no.real, -1 * no.imaginary).__mul__(Complex(1.0/(no.mod().real**2), 0)))

# 실수 허수 따로 계산
denom = no.real**2 + no.imaginary**2
real = (self.real * no.real + self.imaginary * no.imaginary) / denom
imaginary = (self.imaginary * no.real - self.real * no.imaginary) / denom
calc = Complex(real, imaginary)
return calc

def mod(self):
return Complex(math.sqrt(self.real**2 + self.imaginary**2), 0)

def __str__(self):
if self.imaginary == 0:
result = "%.2f+0.00i" % (self.real)
elif self.real == 0:
if self.imaginary >= 0:
result = "0.00+%.2fi" % (self.imaginary)
else:
result = "0.00-%.2fi" % (abs(self.imaginary))
elif self.imaginary > 0:
result = "%.2f+%.2fi" % (self.real, self.imaginary)
else:
result = "%.2f-%.2fi" % (self.real, abs(self.imaginary))
return result

if **name** == '**main**':
A = Complex(*map(float, input().split()))
B = Complex(*map(float, input().split()))

print(A + B)
print(A - B)
print(A * B)
print(A / B)
print(A.mod())
print(B.mod())

Class 2 - Find the Torsional Angle


문제 : 3차원 공간에서 평면 ABC와 BCD가 이루는 각도를 구하는 문제
입력 : 3차원 직교 좌표계로 입력
출력 : (radian이 아닌) degree로 출력

angle

  • INPUT
  • OUTPUT

0 4 5
1 7 6
0 5 9
1 7 2

8.19

matplotlib 를 사용하여 예제의 좌표를 찍고 ABC, BCD 삼각형을 그려보았다.
matplotlib

소스코드
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d.art3d import Poly3DCollection # appropriate import to draw 3d polygons
from matplotlib import style
import matplotlib.pyplot as plt
from collections import defaultdict

fig = plt.figure()
ax = fig.gca(projection='3d')

# 4개의 좌표 입력

points = defaultdict(list)

for \_ in range(4):
xi, yi, zi = map(int, input().split())
points['x'].append(xi)
points['y'].append(yi)
points['z'].append(zi)

ax.scatter(points['x'], points['y'], points['z']) # 좌표 찍어보기
#########################################################

# 삼각형 ABC, BCD 좌표 저장

ABC = defaultdict(list)
BCD = defaultdict(list)

for i in range(3):
ABC['x'].append(points['x'][i])
ABC['y'].append(points['y'][i])
ABC['z'].append(points['z'][i])
BCD['x'].append(points['x'][i+1])
BCD['y'].append(points['y'][i+1])
BCD['z'].append(points['z'][i+1])

for i in ABC.items():
print(*i)
for i in BCD.items():
print(*i)
#########################################################

# 두 삼각형을 좌표계에 추가

# 1. create vertices from points

tri_1 = [list(zip(ABC['x'], ABC['y'], ABC['z']))]
tri_2 = [list(zip(BCD['x'], BCD['y'], BCD['z']))]

# 2. create 3d polygons and specify parameters

srf_1 = Poly3DCollection(tri_1, alpha=.5, facecolor='#800000')
srf_2 = Poly3DCollection(tri_2, alpha=.5, facecolors='C0')

# 3. add polygon to the figure (current axes)

plt.gca().add_collection3d(srf_1)
plt.gca().add_collection3d(srf_2)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# ax.set_xlim(0, 10)

# ax.set_ylim(0, 10)

# ax.set_zlim(0, 10)

plt.show()
import math

class Points(object):
def **init**(self, x, y, z):
(self.x, self.y, self.z) = (x, y, z)

def __sub__(self, no):
return Points((self.x - no.x), (self.y - no.y), (self.z - no.z))

def dot(self, no):
return (self.x * no.x) + (self.y * no.y) + (self.z * no.z)

def cross(self, no):
return Points((self.y * no.z - self.z * no.y), (self.z * no.x - self.x * no.z),
(self.x * no.y - self.y * no.x))

def absolute(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)

if **name** == '**main**':
points = list()
for i in range(4):
a = list(map(float, input().split()))
points.append(a)

a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3])
x = (b - a).cross(c - b)
y = (c - b).cross(d - c)
angle = math.acos(x.dot(y) / (x.absolute() * y.absolute()))

print("%.2f" % math.degrees(angle))
1…678…33
NUNU

NUNU

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