Brute Force(in python)

Kelvin 영하 273.15°C·2022년 8월 9일
1

what is a Brute force?

It is a technique of blindly exploring the number of all cases to derive a result

  • Brute force is a very simple technique
  • It is the first step to think about problem solving, but the time complexity is very high.
  • Intuitively perform the method required by the problem.
  • count, permutations and combinations, two-dimensional arrays

Example questions about Brute force


source:baekjoon

In this question, it asks to code a program 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 8th column are 8, 16, 24, 32, 40, 48, 56, 64, 72, so 72 is the largest, but in the multiplication table, 8, 61, 42, 23, 4, 84 , 65, 46, 27, and 84 has the largest value.

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))

To answer this question, we need to use a function called set which is similar to list but it doesn't have any orders and it prevents from having same elements.

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

We need to first get a two inputs for multiplication table and one variable 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 number of lists that are reversed by using the repeating function. After repeating is done, it prints out the highest number in the set by using a function called max


source:baekjoon
This question asks to program a code that can print the largest number of golden numbers less than or equal to N.(in this question, Golden number represents a number that is only made out with 4 or 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

Since it is not convenient to search all the things in one code, it is good to make a new function for ourselves using def.

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

After naming the function, we will use a repeating function that can find if the input number is Golden number or not. If the input is Golden number, than it will print True and if it isn't that it will print False

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

Since we made a function to solve this question, the only thing we need to do is input number and see if the number is Golden number or not. If not than we can decrease the input number by 1 until we find it.

This is the explanation of Brute force in coding and some example questions about Brute Force. Thank you for reading!

profile
안녕하세요! python에 관한 문제들 혹은 코드등을 업로드 할 예정입니다! 관심 부탁드립니다!

0개의 댓글