Archive for the ‘python’ Category

[Python] Evolution of a Python programmer.py

เจอผ่านๆ ลูกตา รู้สึกประทับใจ เรยเก็บไว้หน่อย นะๆๆ

1
2
3
4
5
6
7
#Newbie programmer
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x – 1)
print factorial(6)

[Python] Optimize what needs optimizing?

ปกติแล้ว เวลาผมเขียนโปรแกรมจะถือคตินี้มาตลอด นั่นคือ
Make it done, make it right, and then make it fast.
blog นี้จะมาบอกว่า เราจะ opimize โปรแกรมที่เขียนด้วยภาษา python ได้อย่างไรบ้าง
อย่างแรก ให้ติดตั้ง Python profiler ก่อน คลิก เพื่อดูว่าแต่ละ function ใช้เวลาในการทำงานนานเท่าไหร่
blog นี้ ผมจะสรุปจาก PerformanceTips ละกันครับ

เลือก Data structure ให้เหมาะสม
ใช้ Sorting ของ Python
อ้างอิงจาก Comparing the well-known sorting algorithm ซึ่งผมเคยเทียบประสิทธิภาพไปแล้วว่า python sorting เร็วกว่าใครเพื่อน นอกจากนั้น Guido van Rossum ยังแนะนำให้ใช้ comparator
String Concatenation
หลีกเลี่ยง (เอา string [...]

[Python] Identify the bottlenecks by Python profilers

Python Profiler package เป็น package ไว้สำหรับ วิเคราะห์ประสิทธิภาพของโปรแกรมที่เขียนด้วยภาษา python เพื่อหา bottleneck หรือปัญหาคอขวดของโปรแกรมของเราว่าอยู่ตรงไหน
Minimum-requirement: Python 2.6 or later [use profiler and pstats package]
ถ้าเครื่องไหนไม่สามารถใช้งานได้ ให้ลงก่อน ด้วยคำสั่งดังกล่าว

$ sudo aptitude install python-profiler

ปกติแล้ว Python profilers จะมี standard library ชื่อว่า profile กับ cProfile ผมแนะนำให้ใช้ cProfile ดีกว่าครับ เพราะค่อนข้าง low-level กว่าและมี overhead ต่ำกว่าด้วยครับ
ตัวอย่างการใช้งานทั่วๆไป

import cProfile
import pstats
 
def foo():

 
if __name__ == ‘__main__’:
[...]

Comparing the well-known sorting algorithm

ไหนๆ เรียนวิชา Algorithm มาแล้ว มาเขียน Blog ให้เป็นประโยชน์กะรุ่นน้องหน่อยละกัน
Bubble Sort [O(n²)]

1
2
3
4
5
6
7
8
9
def bubble(list):
swap = True
while swap:
swap = False
for i in range(len(list)-1):
if list[i] [...]