A sentence sentence is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
Return the final sentence representing the conversion from sentence to Goat Latin.
class Solution:
def toGoatLatin(self, sentence: str) -> str:
# 외계어인줄
vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
words = sentence.split()
for i in range(len(words)):
if words[i][0] in vowels:
words[i] += "ma"
else:
words[i] = words[i][1:] + words[i][0] + "ma"
words[i] += "a"*(i+1)
return ' '.join(words)
sentence
를 공백 기준으로 split
모음으로 시작하면 끝에 ma
붙여주고
자음으로 시작하면 끝에 시작문자 + ma
붙여주기
i
번째 단어 => i+1
개의 a
붙여주기
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 for all the given inputs.
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
# 나누어떨어지면 바로 결과값 return
if numerator % denominator == 0:
return str(numerator // denominator)
# 결과값이 음수인지 확인 => negative 에 따라 부호 붙여주기 & 계산은 절댓값으로
negative = 0
if numerator < 0 and denominator > 0 or numerator > 0 and denominator < 0:
negative = 1
numerator = abs(numerator)
denominator = abs(denominator)
res = "-" if negative else ""
nocycle = "-" if negative else ""
res += str(numerator // denominator) + "." # 몫만 미리 저장
nocycle += str(numerator / denominator) # 순환소수가 아닐 때 사용
numerator = numerator % denominator * 10 # 소수점 이하를 구하기 위해 미리 처리
quotient = [] # 소수점 이하의 몫 저장
nums = [] # 소수점 이하의 numerator 저장
idx = 0
cycle = 0 # 순환소수인지 확인
while numerator % denominator != 0:
if numerator in nums:
idx = nums.index(numerator) # 반복의 시작 위치 => 괄호의 시작 위치
cycle = 1
break
quotient.append(numerator // denominator)
nums.append(numerator)
numerator = numerator % denominator * 10
if cycle:
# 반복 X 부분
for n in quotient[:idx]:
res += str(n)
# 반복 O 부분
res += "("
for n in quotient[idx:]:
res += str(n)
res += ")"
return res
if "e" in nocycle:
for n in quotient:
res += str(n)
res += str(numerator // denominator)
return res
return nocycle
나눠떨어지면 바로 나눗셈 값 return
numerator
, denominator
둘 중에 하나라도 음수면 결과도 음수니까 그때의 경우 처리
=> negative
에 따라 부호 붙여주고 계산은 절댓값으로
res
에 소수점까지의 값을 미리 저장
nocycle
은 순환소수가 아닐 경우에 사용하기 위해 순수한 나눗셈 결과값 저장
이미 몫은 구했으므로 numerator * 10
해주고 계속 나눠주면서
소수점 이하의 몫과 numerator 들을 각각 quotient
와 nums
에 저장
=> numerator 가 반복된다면, 반복 시작의 idx 값 저장 & cycle = 1
& break
순환소수라면 idx
를 기준으로 괄호를 넣어서 return
4.656612873077393e-10
처럼 10 ** (-10)
이 생략돼서 표현됐을 경우 처리
나머지는 순환하지 않으므로 사전에 구해둔 nocycle
return
6 번 처리가 너무 그지 같았네요...