알고리즘 연습

LSH·2023년 8월 1일
0

교육 정보

  • 교육 명: 경기미래기술학교 AI 교육
  • 교육 기간: 2023.05.08 ~ 2023.10.31
  • 오늘의 커리큘럼:
    알고리즘 연습
  • 강사: 이현주, 이애리 강사님
  • 강의 계획:
    1. 자료구조
    2. 알고리즘 연습

알고리즘 연습

  • 10~99 사이의 난수 n개 생성하기 13 나오면 중단

import random 
n = int(input('난수 갯수 입력:'))

list1 = random.sample(range(10, 100), n)
if (13 in list1) and (list1.index(13)<=n):
  print(list1[:list1.index(13)+1])
  print('프로그램을 종료합니다.')
else:
  print(list1)
  
#
# 결과

난수 갯수 입력:47
[41, 88, 28, 33, 83, 65, 14, 11, 84, 89, 64, 16, 13]
프로그램을 종료합니다.

  • 최댓값 찾기
    • .max 함수 사용하지 않고 최댓값 찾기
def find_max(a):
  cand = 0
  for a in a:
    if a > cand:
      cand = a 
  return cand


v = [17, 92, 18, 33, 58, 7, 33, 42]
print(find_max(v))
  
#
# 결과

92

  • Palindrome 여부 확인하기

from typing import List

def isPalindrome() -> bool:
  # text = input('입력:')

  text = 'A man, a plan, a canal: Panama'
  text = list(filter(str.isalpha, text))
  text = ''.join(text).lower()
  return text == text[::-1]

print(isPalindrome())
  
#
# 결과

True
  • Palindrome 여부 확인하기 (정규 표현식)

from typing import List 
import re

def isPalindrome() -> bool:
  # text = input('입력:')

  text = 'A man, a plan, a canal: Panama'
  text = text.lower()
  # re.sub(패턴, 바꿀문자열, 문자열, 바꿀횟수)
  text = re.sub('[^a-z0-9\text]', '', text)
  return text == text[::-1]

print(isPalindrome())
  
#
# 결과

True

  • 애너그램 2차원 리스트로 반환하기

import collections
from typing import List

def groupAnagrams(strs: List[str]) -> List[List[str]]:
  result = []
  unique = []
  for word in strs:
    w = list(word)
    w.sort()
    w = ''.join(w)
    if w not in unique:
      unique.append(w)
      result.append([])
      result[unique.index(w)].append(word)
    elif w in unique:
      result[unique.index(w)].append(word)
  return result


groupAnagrams(["eat","tea","tan","ate", "nat","bat"])

#
# 결과

[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

  • 애너그램 2차원 리스트로 반환하기(dict 사용)

from typing import List

def groupAnagrams(strs: List[str]) -> List[List[str]]:
  dicts = {}
  for s in strs:
    s_sorted = ''.join(sorted(s))
    if s_sorted not in dicts:
      dicts[s_sorted] = [s]
    else:
      dicts[s_sorted].append(s)
  return list(dicts.values())
    

groupAnagrams(["eat","tea","tan","ate", "nat","bat"])

#
# 결과

[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

  • 애너그램 2차원 리스트로 반환하기(dict collection 사용)
from typing import List
import collections

def groupAnagrams(strs: List[str]) -> List[List[str]]:
  dict = collections.defaultdict(list)
  for word in strs:
    dict[''.join(sorted(word))].append(word)
  return list(dict.values())
    

groupAnagrams(["eat","tea","tan","ate", "nat","bat"])

#
# 결과

[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
profile
:D

0개의 댓글