Coding/Python 삽질기2009. 8. 25. 21:52

# 원점에서 100만큼 떨어진 점 (0, 100)을 원점을 중심으로 15도씩 회전 하였을 때의 좌표
# 리스트를 계산하는 코드

import math

point_xy = []
 
for idx in range (0, 24) :
      end_y = -100;     
      degree = 15.0 * idx
      rad = math.pi * degree / 180.0
      new_end_x = int(-end_y * math.sin(rad))
      new_end_y = int(end_y * math.cos(rad))
   
      point_xy.append((new_end_x, new_end_y))
     
print point_xy


[(0, -100), (25, -96), (49, -86), (70, -70), (86, -50), (96, -25), (100, 0), (96, 25), (86, 49), (70, 70), (49, 86), (25, 96), (0, 100), (-25, 96), (-50, 86), (-70, 70), (-86, 50), (-96, 25), (-100, 0), (-96, -25), (-86, -50), (-70, -70), (-50, -86), (-25, -96)]

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] Simple file viewer  (0) 2010.01.02
WxPython - HelloWorld  (0) 2008.12.22
Sudoku를 풀어주는 스크립트  (0) 2008.10.09
Posted by chobocho
Coding/Python 삽질기2008. 12. 22. 23:42
#!/usr/bin/python
# HelloWorld.py

import wx

app = wx.App()

frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show()

app.MainLoop()


Posted by chobocho
Coding/Python 삽질기2008. 10. 9. 01:12

#!/usr/local/bin/python
#-*- coding: cp949 -*-
# date   : 2006.  10.  15
#
# 스도쿠를 풀어주는 스크립트

import random

class Sodoku:
 def __init__(self):
  self.timer = 0
  self.board = []
  self.tmpBoard=[]
  for y in range(0, 82):
   self.board.append(0)
   self.tmpBoard.append(511)

 def display(self):

  for y in range(0, 9):
   for x in range(0, 9):
    idx = y* 9 + x + 1;

    if self.board[idx] != 0:
     print "%d" %(self.board[idx]),
    else:
     print "_",
    print '|',
   print '\n'
 
 def checkSquare(self,  sx,  sy):
  sum = 0;
 
  for y in range(0, 3):
   for x in range(0, 3):
    if ( int(self.board[ (y+sy)*9+(x+sx)+1]) > 0):
     sum |= (1 << (int(self.board[ (y+sy)*9+(x+sx)+1]-1)))
  return sum

 def checkBoard(self):
  ret = 0;
  for y in range(0, 9):
   sum = 0;
   for x in range(0, 9):
    if ( int(self.board[y*9+x+1]) > 0):
     sum |= (1 << (int(self.board[y*9+x+1]-1)))
   if (sum != 511):
    ret = 1
   
  for x in range(0, 9):
   sum = 0;
   for y in range(0, 9):
    if ( int(self.board[y*9+x+1]) > 0):
     sum |= (1 << (int(self.board[y*9+x+1]-1)))
   if (sum != 511):
    ret = 2

  for y in range(0, 3):
   for x in range(0, 3):
    sum = self.checkSquare(x*3, y*3)
   if (sum != 511):
    ret = 3
  return ret

 def readData(self):
  fp = open("sudoku.dat", 'r')
  self.board = map(int, fp.read().split(','))
  fp.close()
 
  for y in range(0, 82):
   self.tmpBoard[y] =511
 
 def guessCount(self, num):
  count = 0
  for i in range(0, 9):
   if ( (1 << i) & num ) != 0:
    count += 1
  return count

 def findStartPos(self):
  sx = 0
  sy = 0
  mvalue = 511
  mcount = 10
  for y in range(0,9):
    for x in range(0,9):
     if (self.board[y * 9 + x + 1] == 0):
      temp = self.guessCount(self.tmpBoard[y*9 + x + 1] )
      if (mcount >  temp):
       mvalue = self.tmpBoard[y*9 + x + 1]
       mcount = temp
       sx = x
       sy = y
  return (sx, sy, mvalue)

 def isFull(self):
  count = 0
  for y in range(0,9):
    for x in range(0,9):
     if (self.board[y * 9 + x + 1] != 0):
      count += 1
  return count == 81

 def solve(self):
  if (self.checkBoard() != 0):
   if (self.isFull()):
    return 0
   #get position
   (x, y, num) = self.findStartPos()
   # set number
   for i in range(0, 9):
    if ( (1 << i) & num ) != 0:
     self.board[y*9 + x + 1] = i+1
     # checkTempBoard
     self.checkWidthTempBoard(x, y)
     self.checkHeightTempBoard(x, y)
     self.checkSquareTempBoard(x/3, y/3, x, y)
     if (self.solve() == 1):
       return 1
     else:
      self.unCheckWidthTempBoard(x, y)
      self.unCheckHeightTempBoard(x, y)
      self.unCheckSquareTempBoard(x/3, y/3, x, y)
      self.board[y*9 + x + 1] = 0
   return 0
  else:
   return 1

       
 def checkTempBoard(self):
  for y in range(0, 9):
   for x in range(0, 9):
    if (self.board[y * 9 + x + 1] != 0):
     self.checkWidthTempBoard(x, y)
     self.checkHeightTempBoard(x, y)
     self.checkSquareTempBoard(x/3, y/3, x, y)
 
 def checkWidthTempBoard(self, sx, sy):
   for x in range(0,9):
    if (self.board[sy * 9 + x + 1] == 0):
     self.tmpBoard[sy * 9 + x + 1] &= ~(1 << (self.board[sy * 9 + sx + 1] - 1))

 def checkHeightTempBoard(self, sx, sy):
   for y in range(0,9):
    if (self.board[y * 9 + sx + 1] == 0):
     self.tmpBoard[y * 9 + sx + 1] &= ~(1 << (self.board[sy * 9 + sx + 1] - 1))


 def checkSquareTempBoard(self, sx, sy, tx, ty):
   for y in range(0,3):
    for x in range(0,3):
     if (self.board[(y + sy) * 9 + sx + x + 1] == 0):
      self.tmpBoard[(y + sy * 3) * 9 + sx * 3 + x + 1] &= ~(1 << (self.board[ty * 9 + tx + 1] - 1))    

 def unCheckWidthTempBoard(self, sx, sy):
   for x in range(0,9):
    if (self.board[sy * 9 + x + 1] == 0):
     self.tmpBoard[sy * 9 + x + 1] |=  (1 << (self.board[sy * 9 + sx + 1] - 1))
     
 def unCheckHeightTempBoard(self, sx, sy):
   for y in range(0,9):
    if (self.board[y * 9 + sx + 1] == 0):
     self.tmpBoard[y * 9 + sx + 1] |= (1 << (self.board[sy * 9 + sx + 1] - 1))
     
 def unCheckSquareTempBoard(self, sx, sy, tx, ty):
   for y in range(0,3):
    for x in range(0,3):
     if (self.board[(y + sy) * 9 + sx + x + 1] == 0):
      self.tmpBoard[(y + sy * 3) * 9 + sx * 3 + x + 1] |= (1 << (self.board[ty * 9 + tx + 1] - 1))


 def generate(self):
  self.readData()
  self.checkTempBoard()


def main():
 sodoku = Sodoku()
 
 sodoku.generate()
 sodoku.display()
 sodoku.solve()
 print "-"*60
 sodoku.display()

#----------------------------------------------------------
# main
if __name__ == "__main__":    
   main()


 

[sudoku.dat]
0, 6, 0, 9, 0, 0, 0, 0, 4, 3, 0, 0, 0, 2, 9, 0, 7, 1, 0, 0, 0, 4, 0, 1, 0, 0, 5, 8, 5, 0, 0, 0, 0, 8, 0, 6, 0, 8, 0, 7, 1, 0, 9, 4, 0, 5, 0, 3, 0, 7, 0, 0, 0, 0, 2, 1, 5, 0, 0, 8, 0, 3, 0, 0, 0, 4, 8, 0, 6, 2, 0, 0, 0, 7, 2, 0, 0, 0, 0, 6, 0, 9




 

[실행결과]

6 | _ | 9 | _ | _ | _ | _ | 4 | 3 |

_ | _ | _ | 2 | 9 | _ | 7 | 1 | _ |

_ | _ | 4 | _ | 1 | _ | _ | 5 | 8 |

5 | _ | _ | _ | _ | 8 | _ | 6 | _ |

8 | _ | 7 | 1 | _ | 9 | 4 | _ | 5 |

_ | 3 | _ | 7 | _ | _ | _ | _ | 2 |

1 | 5 | _ | _ | 8 | _ | 3 | _ | _ |

_ | 4 | 8 | _ | 6 | 2 | _ | _ | _ |

7 | 2 | _ | _ | _ | _ | 6 | _ | 9 |
-----------------------------
6 | 1 | 9 | 8 | 7 | 5 | 2 | 4 | 3 |

3 | 8 | 5 | 2 | 9 | 4 | 7 | 1 | 6 |

2 | 7 | 4 | 6 | 1 | 3 | 9 | 5 | 8 |

5 | 9 | 2 | 4 | 3 | 8 | 1 | 6 | 7 |

8 | 6 | 7 | 1 | 2 | 9 | 4 | 3 | 5 |

4 | 3 | 1 | 7 | 5 | 6 | 8 | 9 | 2 |

1 | 5 | 6 | 9 | 8 | 7 | 3 | 2 | 4 |

9 | 4 | 8 | 3 | 6 | 2 | 5 | 7 | 1 |

7 | 2 | 3 | 5 | 4 | 1 | 6 | 8 | 9 |


'Coding > Python 삽질기' 카테고리의 다른 글

WxPython - HelloWorld  (0) 2008.12.22
[조각코드] 숫자 배열 읽어서 리스트에 저장하는 코드  (0) 2008.10.06
간단한 메모장2  (0) 2008.09.17
Posted by chobocho
Coding/Python 삽질기2008. 10. 6. 23:43
fp = open("sudoku.dat", 'r')
data = map(int, fp.read().split(','))
fp.close()
print data

[sudoku.dat]

0, 6, 0, 9, 0, 0, 0, 0, 4, 3, 0, 0, 0, 2, 9, 0, 7, 1, 0, 0, 0, 4, 0, 1, 0, 0, 5, 8, 5, 0, 0, 0, 0, 8, 0, 6, 0, 8, 0, 7, 1, 0, 9, 4, 0, 5, 0, 3, 0, 7, 0, 0, 0, 0, 2, 1, 5, 0, 0, 8, 0, 3, 0, 0, 0, 4, 8, 0, 6, 2, 0, 0, 0, 7, 2, 0, 0, 0, 0, 6, 0, 9

'Coding > Python 삽질기' 카테고리의 다른 글

Sudoku를 풀어주는 스크립트  (0) 2008.10.09
간단한 메모장2  (0) 2008.09.17
간단한 메모장  (0) 2008.09.14
Posted by chobocho
Coding/Python 삽질기2008. 9. 17. 23:37
#-*- coding: cp949 -*-
# 메모장
from Tkinter import *
import tkMessageBox
import os.path
 
filename = "data.txt"
def ClearText():
    text.delete(1.0, END)  
   
def AppendData():
    textData = text.get(1.0, END).encode('cp949')
    tempFileData = ""
   
    if os.path.exists(filename):
        fp = open(filename, 'r')
        tempFileData = fp.read()
        fp.close()
   
    fp = open(filename, 'w')
    fp.write(textData)
    fp.write(tempFileData)
    fp.close()

def LoadData():
    if os.path.exists(filename):
        fp = open(filename, 'r')
        tempFileData = fp.read()
        fp.close()
   
        text.insert(1.0, tempFileData.decode('cp949'))   
   
def SaveData():
    textData = text.get(1.0, END).encode('cp949')
   
    fp = open(filename, 'w')
    fp.write(textData)
    fp.close()
       
def ShowInfo():
    tkMessageBox.showinfo("Information","http://chobocho.com\nVersion 0.2")
   
   
#----------------------------------------------------------
# main
if __name__ == "__main__":     
    root = Tk()
   
    text = Text(root, width=50, height = 20)
    text.pack()
    append_button  = Button(root, text="Append", command = AppendData)
    save_button  = Button(root, text="Save", command = SaveData)
    clear_button = Button(root, text="Clear", command = ClearText)
    load_button = Button(root, text="Load", command = LoadData)
    info_button = Button(root, text="Info", command = ShowInfo)

    info_button.pack(side=RIGHT)
    load_button.pack(side=RIGHT)
    clear_button.pack(side=RIGHT)
    save_button.pack(side=RIGHT)
    append_button.pack(side=RIGHT)

    root.mainloop()


사용자 삽입 이미지

'Coding > Python 삽질기' 카테고리의 다른 글

[조각코드] 숫자 배열 읽어서 리스트에 저장하는 코드  (0) 2008.10.06
간단한 메모장  (0) 2008.09.14
Fractal Tree  (0) 2008.06.21
Posted by chobocho
Coding/Python 삽질기2008. 9. 14. 00:15
#-*- coding: cp949 -*-
# 메모장
from Tkinter import *
import tkMessageBox
import os.path
 
filename = "data.txt"
def ClearText():
    text.delete(1.0, END)  
def SaveData():
    textData = text.get(1.0, END).encode('cp949')
    tempFileData = ""
   
    if os.path.exists(filename):
        fp = open(filename, 'r')
        tempFileData = fp.read()
        fp.close()
   
    fp = open(filename, 'w')
    fp.write(textData)
    fp.write(tempFileData)
    fp.close()
   
def ShowInfo():
    tkMessageBox.showinfo("Information","http://chobocho.com\nVersion 0.1")
   
   
#----------------------------------------------------------
# main
if __name__ == "__main__":     
    root = Tk()
   
    text = Text(root, width=50, height = 20)
    text.pack()
    save_button  = Button(root, text="Save", command = SaveData)
    clear_button = Button(root, text="Clear", command = ClearText)
    info_button = Button(root, text="Info", command = ShowInfo)
    info_button.pack(side=RIGHT)
    clear_button.pack(side=RIGHT)
    save_button.pack(side=RIGHT)
    root.mainloop()


사용자 삽입 이미지

'Coding > Python 삽질기' 카테고리의 다른 글

간단한 메모장2  (0) 2008.09.17
Fractal Tree  (0) 2008.06.21
파일을 HEX 값으로 보여 주는 소스  (0) 2008.05.19
Posted by chobocho
Coding/Python 삽질기2008. 6. 21. 02:07

사용자 삽입 이미지

사용자 삽입 이미지

사용자 삽입 이미지



#-*- coding: cp949 -*-
from Tkinter import *
import math
import random
RADIAN = math.pi / 180
aColor = [ "brown", "red", "blue", "green", "orange", "black" ]
def DrawTree( startX, startY, angle, length, depth ):
    if depth == 0:
        return
   
    rand=random.random;
    endX = startX + length * math.cos(angle * RADIAN)
    endY = startY - length * math.sin(angle * RADIAN)
    myCanvas.create_line( startX, startY, endX, endY, width = depth, fill=aColor[int(depth * rand()) % 6])
   
    rand=random.random;
    DrawTree( endX, endY, angle + 30 * rand(), length * (rand() + 0.2), depth - 1 )
    rand=random.random;
    DrawTree( endX, endY, angle - 30 * rand(), length * (rand() + 0.2), depth - 1 )
#----------------------------------------------------------
# main
if __name__ == "__main__": 
    root = Tk()
    scrollbarX = Scrollbar( root, orient = "horizontal" )
    scrollbarY = Scrollbar( root)
  
    myCanvas = Canvas(root, xscrollcommand = scrollbarX.set,  yscrollcommand = scrollbarY.set, confine = 0, scrollregion = (0, 0, 480, 640 ))
   
    scrollbarX.config (command=myCanvas.xview)
    scrollbarY.config (command=myCanvas.yview)
   
    scrollbarX.pack (side=BOTTOM, fill=X)
    scrollbarY.pack (side=RIGHT, fill=Y)
   
    root.configure(width=640, height=640)
    DrawTree(240, 320, 90, 40, 12)
    myCanvas.pack()
    root.mainloop()

'Coding > Python 삽질기' 카테고리의 다른 글

간단한 메모장  (0) 2008.09.14
파일을 HEX 값으로 보여 주는 소스  (0) 2008.05.19
Post it 만들기  (0) 2008.03.04
Posted by chobocho
Coding/Python 삽질기2008. 5. 19. 00:42
#-*- coding: cp949 -*-
# @Author : chobocho
# @Title  : Simple Hex viewer
# @Date   : 2008. 5. 18
import sys
def main(source_file):
   
    source = open(source_file, 'rb')
    source_data = source.read()
    source.close()
   
    char_count = 0
    buffer = ""
   
    for ch in source_data:
        if (char_count % 16 == 0):
            print "|  %s\n%05X " % (buffer, char_count),
            buffer = ""
        if (char_count % 4 == 0):
            print " ",
        print "%02X" % int( ord(ch) ),
       
        if (ch == '\r'):
            buffer += ""
        elif (ch == '\n'):
            buffer += '\\n'
        elif (ch == '\t'):
            buffer += '\\t'
        else :
            buffer += ch
       
        char_count += 1
       
  
   
#-------------------------------------------------------------------------------
# main
if __name__ == "__main__": 
    if len(sys.argv) < 2:
        print "Usage : hex target"
    else:
        main(sys.argv[1])

'Coding > Python 삽질기' 카테고리의 다른 글

Fractal Tree  (0) 2008.06.21
Post it 만들기  (0) 2008.03.04
Python으로 만든 file copy 예제  (2) 2007.11.20
Posted by chobocho
Coding/Python 삽질기2008. 3. 4. 02:15

[2008. 3. 3]

from Tkinter import *

root = Tk()
text = Text(root, width=20, height=20)
text.pack()

root.mainloop()

Posted by chobocho
Coding/Python 삽질기2007. 11. 20. 23:34
급하게 파일을 합쳐하 하는 일이 생겨서 만든 파이썬 스크립트이다.
 
기능은 단지 여러개의  파일을 하나로 붙여준는 것 말고는 없다.

#-*- coding: cp949 -*-
# ACopy
# filename : acopy.py
# author    : chobocho at korea.com
# date        : 2007. 11. 20
#
# 여러개의 파일을 붙여 주는 프로그램
import sys
def main(files):
    file_number = len(files)
    target_file = files[1];
        
    target = file(target_file, 'wb')
 
    for idx in range (2, file_number):
        source = file(files[idx], 'rb')
        source_data = source.read()
        source.close()
        target.write(source_data)
    target.close()
   
#-------------------------------------------------------------------------------
# main
if __name__ == "__main__": 
    if len(sys.argv) < 3:
        print "Usage : acopy target source1 [source2]*"
    else:
        main(sys.argv)


'Coding > Python 삽질기' 카테고리의 다른 글

Post it 만들기  (0) 2008.03.04
http://www.pythonchallenge.com...Level1  (1) 2007.09.29
http://www.pythonchallenge.com  (0) 2007.09.28
Posted by chobocho