[Mock] Facebook 8

shsh·2021년 7월 5일
0

Mock

목록 보기
76/93

824. Goat Latin

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:

  • If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word.
    For example, the word 'apple' becomes 'applema'.
  • If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma".
    For example, the word "goat" becomes "oatgma".
  • Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.
    For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on.

Return the final sentence representing the conversion from sentence to Goat Latin.

My Answer 1: Accepted (Runtime: 32 ms - 58.63% / Memory Usage: 14.1 MB - 74.59%)

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 붙여주기


166. Fraction to Recurring Decimal

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.

My Answer 1: Accepted (Runtime: 32 ms - 62.39% / Memory Usage: 14.2 MB - 87.17%)

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
  1. 나눠떨어지면 바로 나눗셈 값 return

  2. numerator, denominator 둘 중에 하나라도 음수면 결과도 음수니까 그때의 경우 처리
    => negative 에 따라 부호 붙여주고 계산은 절댓값으로

  3. res 에 소수점까지의 값을 미리 저장
    nocycle 은 순환소수가 아닐 경우에 사용하기 위해 순수한 나눗셈 결과값 저장

  4. 이미 몫은 구했으므로 numerator * 10 해주고 계속 나눠주면서
    소수점 이하의 몫과 numerator 들을 각각 quotientnums 에 저장
    => numerator 가 반복된다면, 반복 시작의 idx 값 저장 & cycle = 1 & break

  5. 순환소수라면 idx 를 기준으로 괄호를 넣어서 return

  6. 4.656612873077393e-10 처럼 10 ** (-10) 이 생략돼서 표현됐을 경우 처리

  7. 나머지는 순환하지 않으므로 사전에 구해둔 nocycle return

6 번 처리가 너무 그지 같았네요...

profile
Hello, World!

0개의 댓글

Powered by GraphCDN, the GraphQL CDN