Python 23

[Python] 최단경로를 찾는 다익스트라(Dijkstra) 알고리즘

다익스트라(Dijkstra) 알고리즘 1. 다익스트라 알고리즘은 도로 교통망 같은 곳에서 나타날 수 있는 그래프에서 꼭짓점 간의 최단 경로를 찾는 알고리즘이다. 2. 각 꼭짓점을 최대 한 번씩만 방문가능하며 방문하지 않은 점 중 최단거리인 점을 찾아 방문하여 최단 거리를 정하고 이를 반복한다. 코드 import heapq def dijkstra(graph, start): # 그래프에서 모든 노드까지의 최단거리를 저장할 딕셔너리 초기화 distance = {node: float('inf') for node in graph} distance[start] = 0 # 시작 노드부터의 최단거리를 저장할 우선순위 큐 초기화 priority_queue = [(0, start)] while priority_queue:..

IT/Python 2023.09.21

[Python] 대/소문자 전환 프로그램

설계 1. 문장의 대문자는 소문자로, 소문자는 대문자로 바꾼다. 코드 def change_char(input): result = "" for char in input: if char.isupper(): result += char.lower() elif char.islower(): result += char.upper() else: result += char return result input = input("영어를 넣어주세요") output = change_char(input) print(output) 실행 실행(PC) 마무리 자바로 자그마한 게임 만들어 보겠다고 씨름하고 있다보니 게시글 작성이 좀 늦어졌습니다...ㅜㅜ 일단 급한대로 간단한코드를 올려봤습니다. 감사합니다.

IT/Python 2023.09.20

[Python] 틱택토 게임 (Tic-Tac-Toe) + 인공지능 AI 추가

설계 1. 최소최대 알고리즘(Minimax algorithm) 을 활용하여 전 게시글의 "Tic-Tac-Toe"게임에 AI기능을 추가했다. 2. AI는 모든 경우에서 최선의 수를 두어 무승부 혹은 승리를 가져간다. 코드 import random board = [' ' for _ in range(9)] def show_board(): print(f'{board[0]} | {board[1]} | {board[2]}') print('- | - | -') print(f'{board[3]} | {board[4]} | {board[5]}') print('- | - | -') print(f'{board[6]} | {board[7]} | {board[8]}') def check_win(player): win_value..

IT/Python 2023.09.18

[Python] 틱택토 게임 (Tic-Tac-Toe)

Tic-Tac-Toe(틱택토) 게임? 틱택토(tic-tac-toe)는 두 명이 번갈아가며 O와 X를 3×3 판에 써서 같은 글자를 가로, 세로, 혹은 대각선 상에 놓이도록 하는 놀이이다. 오목 룰과 흡사하다. 코드 board = [' ' for _ in range(9)] def show_board(): print(f'{board[0]} | {board[1]} | {board[2]}') print('- | - | -') print(f'{board[3]} | {board[4]} | {board[5]}') print('- | - | -') print(f'{board[6]} | {board[7]} | {board[8]}') def check_win(player): win_values = [ [0, 1, 2], ..

IT/Python 2023.09.17

[Python] 포커 족보 검색기

설계 1. 숫자 : 에이스(A), 킹(K), 퀸(Q), 잭(J), 텐(T), 2~9 문양 : 스페이드(S), 하트(H), 다이아(D), 클로버(C) 총 합 52장의 카드 중 5장골라 포커 룰에 따라 그 족보를 확인한다. 2. 입력은 [숫자][문양]으로 이루어진 5자리 리스트로 받는다. EX) [6S, 5D, 2C, AS, KH) 코드 from collections import Counter def handfind(cards): numbers = [card[0] for card in cards] patts = [card[1] for card in cards] number_dict = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T'..

IT/Python 2023.09.15

[Python] 쇼핑몰 이미지 크롤링

설계 1. 웹사이트의 이미지를 크롤링한다. 2. 이미지는 dongwon 폴더를 생성하여 저장한다. 3. 이미지 파일의 이름은 이미지 저장 주소의 마지막 값으로 저장된다. 코드 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time import urllib.request import os driver = webdriver.Chrome() url = 'https://www.dongwonmall.com/index.do' driver.get(url) time.sleep(3) driver.find_element(By.XPATH,'..

IT/Python 2023.09.14

[Python] 대통령 연설문 크롤링

설계 1. 대통령 기록관 사이트에서 연설문을 크롤링해온다 2. 크롤링해온 연설문 내용은 txt파일로 저장한다 3. txt파일은 [이름][년도].txt로 data_speech 폴더에 저장된다. 코드 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time from wordcloud import WordCloud import matplotlib.pyplot as plt from PIL import Image import numpy as np from collections import Counter from konlpy.tag ..

IT/Python 2023.09.13

[Python] 사람인 취업공고 엑셀정리

설계 1. 현재 대전지역에서 모집중인 공고를 10페이지까지 불러온다 2. 불러온 결과를 엑셀로 저장한다. 3. 페이지와 연동하여 데이터가 갱신된다. 코드 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time import csv driver = webdriver.Chrome() url = "https://www.saramin.co.kr/zf_user/jobs/list/domestic?loc_mcd=105000&panel_type=&search_optional_item=n&search_done=y&panel_count=y&..

IT/Python 2023.09.11

[Python] 바이오리듬

바이오리듬? 바이오리듬(영어: biorhythm)은 인체에 신체,감성,지성의 세가지 주기가 있으며 이 세가지 주기가 생년월일의 입력에 따라 어떤 패턴으로 나타나고 이 패턴의 조합에 따라 능력이나 활동 효율에 차이가 있다는 주장이다. 신체(physical cycle)는 23일, 감성(emotional cycle)은 28일 그리고 지성(intellectual cycle)은 33일을 주기로 한다. (생체리듬과는 다른 개념입니다.유사과학) 코드 import matplotlib.pyplot as plt import math from datetime import datetime today = datetime.now() birth = datetime(2000, 7, 16) #생일 입력 print("현재일 : ", t..

IT/Python 2023.09.10

[Python] 글에 사용된 단어 수 세기

설계 1. 글의 사용된 단어를 카운트하여 딕셔너리에 저장한다. 2. 공백, 줄 바꿈기호, 따옴표 등은 지워준다. 3. python/data 경로에 존재하는 txt문서를 불러온다 코드 file = open('data/문재인대통령.txt', 'r', encoding = 'utf-8') contents = file.read() #contents = str(input('내용 : ')) contents = contents.replace('\n',' ') contents = contents.replace('!','') contents = contents.replace('.','') words = contents.split(' ') word_dict = {} for word in words: if word not i..

IT/Python 2023.09.09