Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
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
Archives
Today
Total
관리 메뉴

아보카도 Blog

알고리즘 강의 1일차: 랜덤값 import random, 문자열 요약 배열 요소끼리 비교 본문

자료구조, 알고리즘

알고리즘 강의 1일차: 랜덤값 import random, 문자열 요약 배열 요소끼리 비교

수수 아보카도 2022. 11. 23. 12:44

오늘부터 3일간 내배캠에서 알고리즘 강의를 해준다.

우리 자료구조 알고리즘 강의에서 쓰는 강의노트를 기반으로 주석달아주신건데

처음에는 괜찮았지만 마지막에 코드를 직접 입력할 때 자바스크립트랑 파이썬이랑 헷갈렸고,

문자열 요약하기 문제에서는 알고리즘을 짜지 못했다 ㅠㅠ

그래도 실시간으로 시간을 정해놓고 코드를 직접 작성하고 피드백을 받을 수 있어서 좋았다.

 

오늘 배운 것과 느낀 점은

1. 파이썬으로 코딩하는 것에 익숙해지기

2. 기본 코딩 능력을 튼튼히 하기 (변수 선언, 출력, 반복문, 조건문 등)

 

3. 최댓값 for문 두 번 돌려서 푸는 방법 (실험군과 대조군)

def find_max_num(array):
  for num in array:
    for compare_num in array:
      if num < compare_num:
        break
    else:
      return num

print("정답 = 6 / 현재 풀이 값 = ", find_max_num([3, 5, 6, 1, 2, 4]))
print("정답 = 6 / 현재 풀이 값 = ", find_max_num([6, 6, 6]))
print("정답 = 1888 / 현재 풀이 값 = ", find_max_num([6, 9, 2, 7, 1888]))

 

4. 랜덤으로 값 지정하기 import random

random.random() 난수 생성

random.randrange(1,101) 1이상 101미만의 난수

random.shuffle() 시퀀스를 섞어두기

random.choice() 랜덤 원소 뽑기

 

그 밖에 while 반복문 쓰기, count로 입력한 횟수 집계하기, break 걸어주기

import random

answer = random.randint(1, 100)
count = 0
print('1~100 중 랜덤 숫자 하나를 정하였습니다. 과연 맞출 수 있을까요?')

while True:
    count += 1
    guess = int(input('숫자 입력: '))
    if guess > answer:
        print('DOWN')
    elif guess < answer:
        print('UP')
    else:
        print('CORRECT')
        break
print('숫자 입력한 횟수: %d번' % count)

 

5. %d % 사용하는 법 익히기

name = 'marcog'
number = 42
print '%s %d' % (name, number)

print('%s %d' % (name, number))

자세한 내용 https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

 

Built-in Types — Python 3.11.0 documentation

Built-in Types The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that

docs.python.org

 

6. 문자열 요약하기

문제:
1. 입력으로 소문자의 알파벳 순으로 정렬된 문자열이 입력됩니다.
2. 각 알파벳은 중복이 가능합니다.
3. 중간에 없는 알파벳이 있을 수도 있습니다.
입,출력 예시와 같이 입력 문자열에 나타나는 각 알파벳의 종류,갯수를 요약하여 나타내시오.
ex. acccdeee -> a1/c3/d1/e3
def summerize_string(string):
    n = len(string)
    count = 0
    result_str = ""

    # repeat 0 - n-2 in the loop
    for i in range(n - 1):
        # count++ when i and i+1 are same
        if string[i] == string[i + 1]:
            count += 1
        else:
            # make the msg and initiate the count
            result_str += string[i] + str(count + 1) + "/"
            count = 0
    # write the last letter (not in the loop bc not comparable
    result_str += string[n - 1] + str(count + 1)

    return result_str


input = "aaaaabbbccccdeef"

print(summerize_string(input))

 

아이구... 내일은 또 어떤 강의가 기다리고 있을지^^

이해하고 참여하려면 오늘 자료구조 알고리즘 2주차 부지런히 나가야겠다.