Brute Force [Python] [BOJ 13410,1526]

HyunMin Yang·2022년 8월 9일
1

Algorithm

목록 보기
4/4
post-thumbnail

What's Brute Force?

Technique of blindly exploring the number of all cases to get to the result

Brute force is very simple. It is the first step of problem solving, but it has a very hight time complexity. It intuitively performs the method required by the problem.

Questions solving

Baekjoon: 거꾸로 구구단 13410

Code:

x,y = map(int,input().split())
z = {}
z = set()
for i in range(1,y+1):
  z.add(int(str(x*i)[::-1])) 
print(max(z))

The question asks to program a code that can reverse the number of multiplication table of two values and find the highest number among them.

For example, the values of the 9 terms in the 7th column of the multiplication table are 7, 14, 21, 28, 35, 42, 49, 56, 63, so 63 is the largest, but in the swapped multiplication table, 7, 41, 21, 82, 53, 24, 94 , 65, 36, so 94 is the largest value.

To solve this question, we need to use 'set'.
Set is similar to list but doesn't have any orders and it prevents from having same elements.

x,y = map(int,input().split())
z = {}
z = set()

We first use this code to recieve a number for the multiplication table and one for the set.

for i in range(1,y+1):
  z.add(int(str(x*i)[::-1])) 
print(max(z))

This code allows to make a list with the numbers that are reversed by using the repeating function. After repeating, it prints out the highest number in the set by max function.

Baekjoon: 가장 큰 김민수 1526

This question asks to program a code that can print the largest number of certain numbers less than or equal to N. The certain numbers in this question is 4 and 7

Code:

def is_4or7(n):
  for i in str(n):
    if i!="4" and i!="7":
      return False
  return True

N = int(input())
while True:
  if is_4or7(N):
    print(N)
    break
  else:
    N -= 1

It isn't convenient to search all the numbers in one go, so it is good to make a new function for defining 4 or 7 using the define function.

After naming the function, we use the for function that can find if the input number is the certain number or not. If the input is equal to the certain number, it will print True and if it isn't, it will print False

def is_4or7(n):
  for i in str(n):
    if i!="4" and i!="7":
      return False
  return True

Because we made the function to solve this question, we need to input numbers and see if the numbers are certain numbers or not. If not, we start decreasing the input number by 1 until we find it.

N = int(input())
while True:
  if is_4or7(N):
    print(N)
    break
  else:
    N -= 1
profile
Hello World!

1개의 댓글

comment-user-thumbnail
2022년 8월 9일

숙제끝!

답글 달기