Python으로 분수 간단히 다루기

in #kr6 years ago (edited)


백준 1735번, 2609번, 2702번같이 단순히 분수끼리 계산이나 최대공약수를 구하는 문제는 머릿속으로는 간단히 해결되지만 소스코드로 구현하기에는 살짝 귀찮습니다.

fractions 모듈을 이용해 분수를 간단히 다룰 수 있습니다.

>>> import fractions
>>> fractions.Fraction(1, 2) #fractions.Fraction(분자, 분모)
Fraction(1, 2)
>>> fractions.Fraction(1/3) #fractions.Fraction(분자/분모)
Fraction(1, 3)
>>> fractions.Fraction('1/4') #fractions.Fraction('분자,분모')
Fraction(1, 4)
>>> fractions.Fraction('1.8') #fractions.Fraction('유리수')
Fraction(9, 5)
>>> fractions.Fraction(2,8) #알아서 기약분수로 변환
Fraction(1, 4)
>>> fractions.Fraction(5) #분자만 쓰면 분모는 1로 자동 입력
Fraction(5, 1)


간단하죠?ㅎㅎ

이러한 Fraction객체로 사칙연산도 가능합니다.

>>> import fractions
>>> a = fractions.Fraction(1, 2) #a = 1/2
>>> b = fractions.Fraction(2, 3) #b = 2/3
>>> a+b
Fraction(7, 6)
>>> a-b
Fraction(-1, 6)
>>> a*b
Fraction(1, 3)
>>> a/b
Fraction(3, 4)
>>> a+1
Fraction(3, 2)
>>> a*3
Fraction(3, 2)


역시 간단하죠?ㅎㅎ

분수를 Fraction객체로 다루는 것 까지는 좋은데 분자, 분모값을 따로 받아오고 싶을때는?

numerator, denominator 메소드를 이용하면 됩니다. (각각 분자, 분모라는 뜻)

>>> import fractions
>>> a = fractions.Fraction(13, 24)
>>> a.numerator #분자
13
>>> a.denominator #분모
24


역시 역시 간단하죠?ㅎㅎ

이번엔 최대공약수를 구해봅시다.

gcd 메소드를 이용합니다. (gcd: greatest common divisor, 최대공약수)

>>> import fractions
>>> fractions.gcd(10, 25) #10과 25의 최대공약수
5
>>> fractions.gcd(7, 9) #7과 9의 최대공약수
1


역시 역시 역시 간단하죠?ㅎㅎ


ㅂㅂ (_ _)>

Sort:  

Congratulations @coinchuu! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

SteemitBoard Ranking update - A better rich list comparator
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

여러분 혹시 마크다운 모드로 소스코드 편집도 가능한가요?

컬러링 말씀하시는거라면 불가능합니당

글쿤여... 그것만 되면 정말 편할것같은데...

가까히 하기엔... 너무 먼 ... Python 입니다.... ㅠ,.ㅠ

좋은 파이썬 정보들 항상 감사합니다.
수업에서 맛보기만 해봤었는데 이렇게 다시 보니 기억이 나네요!

어려워요ㅠㅠ
100팔로이벤트 많은참여바랍니다^^
https://steemit.com/kr-newbie/@dmgpol09/100

Congratulations @coinchuu! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 69852.07
ETH 3757.14
USDT 1.00
SBD 3.75