'Python'에 해당되는 글 4건

  1. 2013.06.14 A* algorithm implementation 1
  2. 2013.05.02 pygame 설치
  3. 2013.04.18 날씨 가져오는 스크립트의 수정 1
  4. 2013.04.17 날씨 가져오는 스크립트
Programming/Python2013. 6. 14. 00:46

A* 알고리즘을 구현해 보았다. 전체 코드는 Github 에 업로드 되어있다.

def calc_path(self):
        start = self.grid.start
        start.mindistance = 0.0
        start.h_value = self.heuristic(start)
        openset = [start]
        closedset = set()

        while openset:
            u = heapq.heappop(openset)
            closedset.add(u)

            if u == self.grid.goal:
                break

            for target in self.get_neighbors(u):
                g = 1.0 + u.mindistance
                h = self.heuristic(target)
                f = g + h
                if not target.is_obs:
                    if target.isopen or target in closedset:
                        if target.mindistance > g:
                            target.h_value = f
                            target.mindistance = g
                            target.previous = u
                    else:
                        target.isopen = True
                        target.h_value = f
                        target.mindistance = g
                        target.previous = u
                        heapq.heappush(openset, target)

        self.build_path()

target이 openset에 들어있는지 확인하는 것 때문에 몇 시간을 허비했다;

priority queue에서 target을 검색하면 log(n) 시간이 걸리기 때문에 n이 커지면 dijkstra 알고리즘보다 비 효율적이게 되었다.

그래서 한참을 고민했는데, 그냥 노드에 openset에 들어있는지를 표시하는 플래그를 다는 것으로 해결...

'Programming > Python' 카테고리의 다른 글

pygame 설치  (0) 2013.05.02
날씨 가져오는 스크립트의 수정  (1) 2013.04.18
날씨 가져오는 스크립트  (0) 2013.04.17
쉬워 보이는 언어 Python  (0) 2011.12.27
점프 투 파이썬(Jump to Python)  (0) 2011.12.20
Posted by Tanto
Programming/Python2013. 5. 2. 00:01

요즘 이것저것 고민을 해보다가, 뭐 할만한거 없나 해서 보니 게임을 만들어보면 어떨까? 라는 생각을 하게 되었다.

물론 큐브 맞추는 알고리즘도 짤거고...


생각보다 큐브 맞추는 알고리즘은 그다지 어렵지도 않고, 그냥 맞추는게 목적이면 너무 쉽게 구현될 것 같아서 일단 제쳐두었다.


어쨌든 간단한 게임을 만들기 위해 고민해본 결과, pygame 라이브러리를 사용해보기로 하였다. pygame은 이름 그대로 게임 개발을 위한 python 라이브러리이다. 공식홈페이지는 [여기]이다.


pygame은 설치부터 난관이었다. 일단 windows환경에서 개발하기로 했는데, 공식 홈페이지에는 pygame 32bit msi파일 밖에 올려져있지 않아서 뭐 그냥 설치하면 되겠지 하고 설치했더니 [이 글]과 같은 상황이 계속 발생하였다.


저 글 발견하기 전까지 pygame을 몇 번을 다시 설치했는지;;;


그리고 공식 홈페이지를 다시 가보니 이렇게 적혀있었다!!ㅠㅠ



1. windows 64bit 사용자는 32bit python과 32bit pygame을 사용할 것.

2. 64bit용 pre release는 저기서 받을 수 있음.


64bit python을 사용하면서 32bit pygame을 열심히 설치하니 안될 수 밖에...

어쨌든 64bit pre release version을 다운 받아 설치했다.


그리고 설치 성공!


당분간 이걸로 장난감이나 좀 만들어보면서 공부해야겠다.

'Programming > Python' 카테고리의 다른 글

A* algorithm implementation  (1) 2013.06.14
날씨 가져오는 스크립트의 수정  (1) 2013.04.18
날씨 가져오는 스크립트  (0) 2013.04.17
쉬워 보이는 언어 Python  (0) 2011.12.27
점프 투 파이썬(Jump to Python)  (0) 2011.12.20
Posted by Tanto
Programming/Python2013. 4. 18. 05:50

지난번에 아주 단순 무식하게 HTML을 파싱해서 날씨 가져오는 스크립트를 포스팅 한 적이 있었는데,

도저히 코드를 봐줄 수도 없고.. 심지어 그 코드에는 심각한 문제가 있었다!

(문제는 비밀입니다.. 궁금하신분은 한번 알아보세요ㅋ 힌트는 리눅스의 권한)


어쨌든 그래서 새로운 코드를 다시 짜 보았다.

역시 코드가 딱히 마음에 들진 않지만.. BeautifulSoup을 처음으로 사용하는 거라 그렇다고 위안말도안되는 변명을 하며....


#!/usr/bin/env python
#-*- coding:utf-8 -*-

import urllib
from BeautifulSoup import BeautifulSoup
import traceback
from time import localtime, strftime

def display(result):
    print
    print 'Weather in Seoul, Asia at ' + strftime('%H:%M', localtime()) + '\n'
    print 'Condition: ' + result['cond']
    print 'Temparature: ' + result['temp'] + u"\N{DEGREE SIGN}" + 'C'
    print 'RealFeel: ' + result['realfeel'] + u"\N{DEGREE SIGN}" + 'C'
    print result['humid']
    print result['cloud']
    print

def main():
    html = urllib.urlopen("http://www.accuweather.com/en/kr/seoul/226081/current-weather/226081")
    soup = BeautifulSoup(html)

    soup = soup.find('div', {'id':'detail-now'})

    result = {}

    while soup:
        if soup.get('class') == 'cond':
            result['cond'] = soup.text
        elif soup.get('class') == 'temp':
            result['temp'] = soup.text.replace("°", "")
        elif soup.get('class') == 'realfeel':
            s = soup.text.replace("°", "")
            result['realfeel'] = s.replace("RealFeel® ", "")
        elif soup.get('cellspacing') == None and soup.get('class') == 'stats':
            ss = soup.findAll('li')
            for li in ss:
                if 'Humid' in li.text:
                    result['humid'] = li.text.replace(":", ": ")
                elif 'Cloud' in li.text:
                    result['cloud'] = li.text.replace(":", ": ")
            break

        soup = soup.findNext()

    display(result)


if __name__ == "__main__":
    try:
        main()
    except:
        traceback.print_exc()

뭐 어찌됐든 쓸데없는 쓰레기 파일을 만들지도 않고... 더 고치기는 너무 귀찮으니 BeautifulSoup 라이브러리는 언젠가 나중에 더 익숙해지기로 하고 일단 저렇게 써야겠다.


날씨를 가져오는 accuweather.com 해당 페이지의 사이즈가  커서 여전히 속도 문제는 어쩔 수 없는듯하다.


인터넷을 연결해야하는데다가 외국 사이트라 느린 것도 같지만 분단위로 날씨를 업데이트! 해주니 그걸로 만족해야겠다.

'Programming > Python' 카테고리의 다른 글

A* algorithm implementation  (1) 2013.06.14
pygame 설치  (0) 2013.05.02
날씨 가져오는 스크립트  (0) 2013.04.17
쉬워 보이는 언어 Python  (0) 2011.12.27
점프 투 파이썬(Jump to Python)  (0) 2011.12.20
Posted by Tanto
Programming/Python2013. 4. 17. 02:05

옛날에 쓰던 개인 노트북을 서버로 만든 후 이것 저것 잡다한 것들을 하다보니, 문득 날씨 정보를 가져오고 싶은 생각이 들었다.


이미 우분투에는 weather-util 이라는 유틸리티를 apt-get으로 받을 수 있기도 하고, 다른 많은 사람들이 펄이라거나 기타등등의 것들로 많이 개발해 두었지만, 내 힘으로 직접 해보고 싶었다.


그래서 아래와 같은 쓰레기코드 ...가 탄생했다...(와 지금 다시봐도 아주 허접하네;;...)


#!/usr/bin/env python

import os
import re
import traceback
from time import localtime, strftime

def display(result):
    print
    print 'Weather in Seoul, Asia at ' + strftime('%H:%M', localtime()) + '\n'
    print 'Condition: ' + result['Condition']
    print 'Temparature: ' + result['Temparature'] + u"\N{DEGREE SIGN}" + 'C'
    print 'RealFeel: ' + result['RealFeel'] + u"\N{DEGREE SIGN}" + 'C'
    print 'Humidity: ' + result['Humidity']
    print 'Cloud Cover: ' + result['Cloud Cover']
    print

def parse(lines):
    result = dict()
    lines = lines.split('\n')
    for line in lines:
        if 'cond' in line:
            result['Condition'] = line[line.find('cond')+6:line.find('</span>')]
            result['Temparature'] = line[line.find('temp')+6:line.find('<span>°')]
            result['RealFeel'] = line[re.search('RealFeel.*; ', line).end():line.find('<span>°</span></span> </div>')]
        elif 'Humidity' in line:
            result['Humidity'] = line[line.find('strong')+7:line.find('</strong')]
        elif 'Cloud Cover' in line:
            result['Cloud Cover'] = line[line.find('strong')+7:line.find('</strong')]

    return result

def main():
    os.system("w3m -dump_source -no-cookie http://www.accuweather.com/en/kr/seoul/226081/current-weather/226081 > /var/tmp/currentweather.gz")
    os.system("gunzip -cf /var/tmp/currentweather.gz > /var/tmp/currentweather.tmp")

    fp = open("/var/tmp/currentweather.tmp", "r")
    lines = fp.readlines()
    fp.close()

    result = ""
    flag = False

    for line in lines:
        if '<div class="info"> <span' in line:
            result = result + line

        if flag:
            if '</ul>' in line:
                flag = False
            else:
                result = result + line

        if '<ul class="stats">' in line:
            flag = True

    display(parse(result))

if __name__ == '__main__':
    try:
        main()
    except:
        print "Error... Sorry"
        traceback.print_exc()

w3m 브라우저의 -dump를 이용해서 페이지 덤프 후 그냥 노가다로 필요한 부분만 긁어내는 것 뿐이다.

그런데 dump를 하면 그 파일이 이유는 모르겠지만 gz로 압축된 파일이어서...;; gunzip으로 압축도 풀고...

어쨌든 그래서 잘 작동은 하지만 좀 느리다... 날씨정보 띄워주는데까지 빠르면 0.5초 ~ 느리면 1.5초 정도까지 걸리는 것 같다.


아무튼 저러던 차에.. 아래 링크를 발견하게 되었다.


Beautiful Soup 라이브러리 포스팅


위와같은 저런 노가다 하지않고.. 라이브러리를 통해서 정상적인 HTML 파서를 나중에 한번 짜봐야겠다.


'Programming > Python' 카테고리의 다른 글

A* algorithm implementation  (1) 2013.06.14
pygame 설치  (0) 2013.05.02
날씨 가져오는 스크립트의 수정  (1) 2013.04.18
쉬워 보이는 언어 Python  (0) 2011.12.27
점프 투 파이썬(Jump to Python)  (0) 2011.12.20
Posted by Tanto