균형잡힌_세상_4949번

[Python, Go] 백준 4949번 풀이

균형잡힌 세상

  • 괄호문제 의 연장이다.

  • 소괄호뿐만 아니라 대괄호까지 포함해 문장에서 괄호가 올바르게 되어져있는지 확인해야한다.

  • 괄호안에 있는 괄호의 짝도 맞아야 yes를 출력할 수 있다. 예를들어 ( [ ) ] 와 같은 경우 하나의 괄호 안에 올바른 짝의 괄호가 들어가지 못했으므로 no 를 출력해야 한다.

  • 정규표현식을 사용해 따라가야될 괄호들을 뺀 문자들은 pass 시켜주는 방법을 사용했다.

  • 이외에는 괄호문제와같이 스텍에 ( 와 [ 를 담아서 사용했다.

    • 단 ) 와 ] 를 만났을 때, 스텍의 마지막 요소가 짝이되는 괄호인지를 판별해줘야 한다.
  • Python 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def vps(line):
stack = []
if line[0] == ")" or line[0] == "]":
# print("1")
return "no"
else: pass
for s in line:
if bool(com.match(s)) == True:
pass
elif s == " " or s == ".":
pass
elif s == "(" or s == "[":
stack.append(s)
# print(stack)
elif s == ")" and stack != []:
if stack[-1] == "(":
stack.pop()
else:
# print("2")
return "no"
elif s == "]" and stack != []:
if stack[-1] == "[":
stack.pop()
else:
# print("3")
return "no"
else:
# print("4")
return "no"
if stack == []:
return "yes"
else:
# print("5")
return "no"
  • Go 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
func vps(x string) string {
var stack []string

// fmt.Println(string(x[0]))
// return x
if string(x[0]) == ")" || string(x[0]) == "]" {
return "no"
}
for _, ch := range x {
s := string(ch)
match, _ := regexp.MatchString("[a-zA-Z]", s)
if match == true {
} else if s == " " || s == "." {
} else if s == "(" || s == "[" {
stack = append(stack, s)
} else if s == ")" && stack != nil {
if stack[len(stack)-1] == "(" {
if len(stack) == 1 {
stack = nil
} else {
stack = stack[:len(stack)-1]
}
} else {
return "no"
}
} else if s == "]" && stack != nil {
if stack[len(stack)-1] == "[" {
if len(stack) == 1 {
stack = nil
} else {
stack = stack[:len(stack)-1]
}
} else {
return "no"
}
} else {
return "no"
}
}
if stack == nil {
return "yes"
} else {
return "no"
}
}
  • Go로 풀이할때, 조건이 많을때는 switch가 더 좋기때문에 switch를 사용했다면 더 좋았을것같다.

Full Code

Full Code - Python

Full Code - Go

괄호_9012번

[Python, Go] 백준 9012번 풀이

괄호

  • 괄호의 쌍이 맞게 이루어져있는지 찾아내는 문제이다.

  • “(“괄호와 “)” 괄호의 개수를 세는것에서 끝나면 안된다.

  • 스택에 “(“ 가 들어왔을때 저장하고 “)” 와 만나면 스택에서 하나를 제거하는 방법으로 쌍을 맞춰주었다.

  • 가장 먼저 들어오는 문자열이 “)” 이라면 쌍이 맞을 수 없으므로 NO 를 리턴하며, 문자열 모두를 파악한 후 stack이 비어있다면 YES 그렇지 않다면 NO 이다

  • Python 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import sys

n = int(sys.stdin.readline())


def vps(li):
stack = []

if li[0] == ")":
return "NO"
else:
for s in li:
if s == "(":
stack.append(s)
elif s == ")" and stack != []:
stack.pop()
else:
return "NO"

if stack == []:
return "YES"
else: return "NO"

for i in range(n):
order = list(sys.stdin.readline().rstrip())
print(vps(order))
  • Go 풀이

    • Go 를 사용할때는 파이썬의 pop과같은 내장함수가 없으므로 “)”를 만났을때 슬라이스의 길이가 1인 경우와 그렇지 않은 경우를 나눠서 판단했다.
func vps(x string) string {
    var stack []string

    for idx, ch := range x {
        s := string(ch)
        if idx == 0 && s == ")" {
            return "NO"
        } else {
            if s == "(" {
                stack = append(stack, s)
            } else if s == ")" && stack != nil {
                length := len(stack)
                if length == 1 {
                    stack = nil
                } else {
                    stack = stack[:length-1]
                }
            } else {
                return "NO"
            }
        }
    }
    if stack == nil {
        return "YES"
    } else {
        return "NO"
    }
}

Full Code

Full Code - Python

Full Code - Go

영화감독_숌_1436번

[Python, Go] 백준 1436번 풀이

영화감독 숌

  • 숫자 6이 연속해서 3번 나타나는 수를 구하는 문제이다.

  • 666, 1666, … , 5666, 의 다음은 6660, 6661, … 이다

  • 666 부터 시작해서 수를 1씩 늘려가면서 모두 확인한다.

  • 해당 수를 string으로 바꾸고 for문을 통해 6이 나왔을때 그 다음의 수도 6인지 그리고 그 다음 숫자도 6인지 확인하는 check 변수를 사용했다.

  • 만약 check가 3이되면 해당 숫자는 6이 연속해서 3번 들어갔으므로 count를 1 증가시키고 주어진 목표만큼 count가 증가하면 종료, 출력했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
n = int(input())

name = 666
count = 0

while True:
if count == n:
print(name-1)
break
else:
check = 0
for i in str(name):
if i == "6":
check += 1
if check == 3:
count += 1
continue
else: pass
else:
check = 0
name += 1
  • Go도 같은 방식의 풀이지만, string을 for문에 돌릴때 반환되는 값은 포인터 값이므로 string(x) 로 바꿔주는것만 주의 참조

  • string을 int로 바꿀때 strconv.ParseInt 를 사용했으나 strconv.Atoi를 사용해도됨

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
"fmt"
"strconv"
)

func main() {
var n int
count := 0
name := 666
fmt.Scanf("%d", &n)

for {
if count == n {
fmt.Printf("%d", name-1)
break
} else {
check := 0
for _, k := range strconv.Itoa(name) {
v, _ := strconv.ParseInt(string(k), 10, 8)
if v == 6 {
check += 1
switch check {
case 3:
count += 1
}
} else {
check = 0
}
}
}
name += 1
}
}
  • check 값이 3인지 확인할때 if문을 사용해도 괜찮지만 switch문을 사용해보았다.

Full Code

Full Code - Python

Full Code - Go

스택_10828번

[Python, Go] 백준 10828번 풀이

스택

  • 주어지는 명령에 따라 스택을 처리하는 문제이다. 파이썬은 큐나 스택을 지원하는 라이브러리가 있지만 사용하지 않고 리스트를 통해 구현했으며, Go는 슬라이스를 통해 구현했다.
  • 스택을 초기화할 필요가 있는 문제가 아니었으므로 하나의 파이썬의 경우 하나의 for문안에서 처리하고 Go는 각각의 명령에 따른 함수를 만들어 사용했다.

  • Python 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import sys

n = int(sys.stdin.readline())

stack = []

# n = int(input())

for i in range(n):

order = sys.stdin.readline().rstrip()
# print(order)
if len(order.split()) == 2:
stack.insert(0,int(order.split()[1]))

else:
if order == "pop":
if stack == []:
print(-1)
else:
print(stack[0])
stack.pop(0)
elif order == "size":
print(len(stack))
elif order == "empty":
if stack == []:
print(1)
else:
print(0)
# top
else:
if not stack == []:
print(stack[0])
else:
print(-1)
  • Go를 통해 슬라이스를 다룰때 파이썬의 pop과 같은 내장함수가 없다.

    • 따라서, 슬라이스에서 하나를 제거할 때 슬라이스의 길이가 1인경우와 1이 아닌경우를 나눠서 생각했다.

    • 슬라이스의 길이가 1인경우, 남아있는 하나를 제거하고 empty slice를 만들기 위해 nil 처리

    • 슬라이스의 길이가 1이 아닌 경우, 슬라이스의 가장 끝의 하나를 제거하면 되므로 슬라이스의 길이 L 을 구하고 L-1 까지의 슬라이스만을 가져간다.

  • Go 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main

import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)

var s []int

func s_push(x int) {
s = append(s, x)
}

func s_pop() {

if s == nil {
fmt.Printf("%d\n", -1)
} else if len(s) == 1 {
top := s[0]
fmt.Printf("%d\n", top)
s = nil
} else {
l := len(s)
top := s[l-1]
fmt.Printf("%d\n", top)
s = s[:l-1]
}
}

func s_size() {
l := len(s)
fmt.Printf("%d\n", l)
}

func s_empty() {
if s == nil {
fmt.Printf("%d\n", 1)
} else {
fmt.Printf("%d\n", 0)
}
}

func s_top() {
if s == nil {
fmt.Printf("%d\n", -1)
} else {
l := len(s)
top := s[l-1]
fmt.Printf("%d\n", top)
}
}

func main() {
var n int
inputReader := bufio.NewReader(os.Stdin)
fmt.Scanf("%d", &n)

for i := 0; i < n+1; i++ {
input, _ := inputReader.ReadString('\n')

order := strings.Split(input, " ")

action := strings.TrimSpace(order[0])

if len(order) == 2 {
n := strings.TrimSpace(order[1])
num, _ := strconv.Atoi(n)
s_push(num)
} else {
switch action {
case "pop":
s_pop()
case "size":
s_size()
case "empty":
s_empty()
case "top":
s_top()
}
}
}
}

Full Code

Full Code - Python

Full Code - Go

분해합_2231번

[Python, Go] 백준 2231번 풀이

분해합

  • 자연수 N의 생성자를 찾기 위해 1부터 N이전까지의 수를 모두 탐색한다.

    • N이 1일때는 생성자가 존재하지 않으므로 0을 출력한다.

    • i 를 키워나가면서 가장 작은 생성자를 찾으면 멈추고, N-1까지 탐색했을 때 결과값이 존재하지 않다면 0을 출력한다.

    • i 의 각 자리수를 sum에 더해줄때, 각 자리수를 for문으로 돌려서 더해주었음. —> 10으로 나누고 나머지를 사용하는 방법도있다.

  • Python 풀이

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    n = int(input())

    if n==1:
    print(0)

    for i in range(1,n):
    sum = i
    for j in str(i):
    sum += int(j)
    if sum == n:
    print(i)
    break
    elif i == n-1 :
    print(0)
  • Go 풀이

    • Python과 같은 방법을 사용했는데 Go에서는 int를 스트링으로 바꿔주기 위해 “strconv”를 사용하였다.

    • strconv.Itoa를 통해 int를 string으로 변환

    • strconv.ParseInt를 통해 string을 int로 바꿔주었다.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      package main

      import (
      "fmt"
      "strconv"
      )

      func main() {
      var n int
      fmt.Scanf("%d", &n)

      if n == 1 {
      fmt.Printf("%d", 0)
      }

      for i := 1; i < n; i++ {
      sum := i
      for _, j := range strconv.Itoa(sum) {
      k, _ := strconv.ParseInt(string(j), 10, 8)
      sum += int(k)
      }
      if sum == n {
      fmt.Printf("%d", i)
      break
      } else if i == n-1 {
      fmt.Printf("%d", 0)
      }
      }
      }

Full Code

Full Code - Python

Full Code - Go

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×