2016년 3월 28일 월요일

파이썬 os의 listdir

해당 경로에 존재하는 파일과 디렉터리들의 리스트를 반환합니다.


>>>listdir()
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe',
 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']

2016년 3월 25일 금요일

파이썬 리스트 인덱싱 기본

list = [ 10, 20 ,30, 40, 50 ]


list[1:3] = [20 , 30]  -> 인덱스 1 이상 3미만 -> 인덱스 1 , 2 반환


타입 보는법은 type(list)


list[-1] 은 리스트의 제일 뒤의 요소를 가져옴 ( 50 )

2016년 3월 24일 목요일

파이썬 KNN 알고리즘

from numpy import *
import operator
from os import listdir
def CreateDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels = ['A' , 'A' ,'B' ,'B']
    return group, labels
def Classify(inX, dataSet, labels, k):
    dataSetSize        = dataSet.shape[0]
    diffMat            = tile(inX,(dataSetSize,1)) - dataSet  
    sqDiffMat          = diffMat ** 2
    sqDistances        = sqDiffMat.sum(axis  = 1)
    distance           = sqDistances ** 0.5
    sortedDistIndicies = sqDistances.argsort()
    classCount={}
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
    sortedClassCount = sorted(classCount.items(),
                              key = operator.itemgetter(1), reverse = True)
    return sortedClassCount[0][0]

파이썬 dic타입의 sort 에 대한 예제와 설명

Classcount = {'A': 1, 'B': 2} // 딕셔너리 타입


sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)


classCount.items() = dict_items([('B', 2), ('A', 1)]) 이다


key = operator.itemgetter(0) 는 dict_items([('B', 2), ('A', 1)]) 의 ('B' , 2 ) ('A', 1), 즉 행렬의 첫번째 부분의 인덱스 ( 0 ) 을 나타낸다.


key = operator.itemgetter(1) 는 dict_items([('B', 2), ('A', 1)]) 의 ('B' , 2 ) ('A', 1), 즉 행렬의 두번째 부분의 인덱스 ( 1 ) 을 나타낸다.


즉 다시 쓰면


sortedClassCount = sorted( [ ('A', 1) , ('B', 2) ] , key = 행렬의 인덱스1번 부분, reverse = True - 내림차순)




으로 정렬을 하게 된다.


그렇다면


sortedClassCount =  [('B', 2), ('A', 1)]  가 된다.


sortedClassCount[0][0] = B 가 된다.

파이썬 정렬을 위한 .iteritems() 설명과 정렬방법들

iteritems()는 '키'와 '값'의 쌍을 iterator(반복자)로 반환 ex) a = {} a['1'] = ('one') a['2'] = ('two') for i, j in a.iteritems(): print i pintt j -> 1 one 2 two ------------------------ 리스트를 소트하는 여러가지 방법 첫번째 방법은 리스트 클래스 내부에 있는 sort함수 사용하기. result.sort() print(result) 참 쉽다. sort함수가 어떤 알고리즘으로 동작하는지 알 필요가 없다 자동으로 정렬시켜 주기 때문에. 두번째 방법은 리스트 클래스 내부에 있는 sort함수를 사용하여 내림차순으로 정렬 result.sort(reverse=True) print(result) 마찬가지로 리스트 클래스 내부에 있는 sort 함수를 사용했다. 1번에서의 방법과 다른점은 키워드 파라미터를 이용하여 reverse 값을 True로 주었다는 것이다. 이 Reverse 라는 매개변수는 디폴트값으로 False를 가지고 있어서 별도로 입력하지 않았을때 오름차순으로 동작하게 된다. 세번째 방법. 외부 함수인 sorted함수 사용하기 other = sorted(result) print(other) cs sorted 함수는 파이썬 내부에서 지원하는 기본 함수이다. 지금 예제에서 사용하는 리스트 클래스는 내부에 sort라는 함수를 제공하지만 다음에 알아볼 tuple이나 dictionary는 sort라는 함수를 제공하지 않기때문에 해당 클래스를 정렬 시킬때는 이 sorted 클래스를 사용하여야 한다. 리턴값으로 정렬된 내용을 반환하니 저장하여 출력하는 예제가 되겠다. 네번째 방법. 마찬가지로 외부함수인 sorted함수를 사용하여 내림차순으로 정렬하기이다. other = sorted(result,reverse=True) print(other) 매개변수로는 위와같이 정렬할 내용(예제에서는 리스트)와 함께 reversed=True를 키워드 파라미터로 전달하고 반환값으로 정렬된 내용을 받는다. 다섯번째 방법은 키값을 만들어서 사용자 정의 정렬하기 이다. def lastDigit(n): return n%10 other = sorted(result, reverse=True, key = lastDigit) print(other) Colored by Color Scripter cs 위의 코드는 2자리 숫자를 가진 리스트에서 십의자리와는 무관하게 일의자리의 크기를 기준으로 정렬을 한다. def digitSum(n): return n/10 + n %10 other = sorted(result,reverse=True,key=digitSum) print(other) Colored by Color Scripter cs 같은 방법을 이용하여 1의 자리와 10의자리의 합으로 정렬을 하였다.

파이썬 기본함수 딕셔너리 get 함수

Description The method get() returns a value for the given key. If key is not available then returns default value None. Following is the syntax for get() method − dict.get(key, default=None) -Parameters- key -- This is the Key to be searched in the dictionary. default -- This is the Value to be returned in case key does not exist. -Return Value- This method return a value for the given key. If key is not available, then returns default value None. -Example- The following example shows the usage of get() method. intput // dict = {'Name': 'Zara', 'Age': 27} print "Value : %s" % dict.get('Age') print "Value : %s" % dict.get('Sex', "Never") output // Value : 27 Value : Never

파이썬 기본함수 정렬 argsort

There are two issues here; one is that np.argsort returns an array of the indices which would sort the original array, the second is that it doesn't modify the original array, just gives you another. This interactive session should help explain: In [59]: arr = [5,3,7,2,6,34,46,344,545,32,5,22] In [60]: np.argsort(arr) Out[60]: array([ 3, 1, 0, 10, 4, 2, 11, 9, 5, 6, 7, 8]) Above, the [3, 1, 0, ...] means that item 3 in your original list should come first (the 2), then item 2 should come (the 3), then the first (index is 0, item is 5) and so on. Note that arr is still unaffected: In [61]: arr Out[61]: [5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22] You might not need this array of indices, and would find it easier to just use np.sort: In [62]: np.sort(arr) Out[62]: array([ 2, 3, 5, 5, 6, 7, 22, 32, 34, 46, 344, 545]) But this still leaves arr alone: In [68]: arr Out[68]: [5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22] If you want to do it in place (modify the original), use: In [69]: arr.sort() In [70]: arr Out[70]: [2, 3, 5, 5, 6, 7, 22, 32, 34, 46, 344, 545] ------------------------------------------------------------- np.argsort doesn't sort the list in place, it returns a list full of indicies that you are able to use to sort the list. You must assign this returned list to a value: new_arr = np.argsort(arr) Then, to sort the list with such indices, you can do: np.array(arr)[new_arr] ------------------------------------------------------------- In [1]: import numpy as np In [2]: arr = [5,3,7,2,6,34,46,344,545,32,5,22] In [4]: print arr [5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22] In [5]: arr.sort() In [7]: print arr [2, 3, 5, 5, 6, 7, 22, 32, 34, 46, 344, 545] ------------------------------------------------------------ x = numpy.array([1.48,1.41,0.0,0.1]) print x.argsort() >[2 3 1 0] 2 is the index of 0.0. •3 is the index of 0.1. •1 is the index of 1.41. •0 is the index of 1.48.

파이썬 기본함수 sum

Sum by rows and by columns:
>>> x = np.array([[1, 1], [2, 2]])
>>> x
array([[1, 1], [2, 2]])
>>> x.sum(axis=0) # columns (first dimension)
array([3, 3])
>>> x[:, 0].sum(), x[:, 1].sum()
(3, 3)
>>> x.sum(axis=1) # rows (second dimension)
array([2, 4])
>>> x[0, :].sum(), x[1, :].sum()
(2, 4)

파이썬 기본함수1

- 1 - datSet.shape[0] -> 데이터의 0차원의 길이를 반환한다. [EX] >>> a1=ones((1,2)) # 1x2크기의 값이 1인 배열 만들기 >>> a1.shape # 배열 크기를 출력해 주는 함수 (1,2) >>> a1.shape[0] 1 >>> a1.shape[1] 2 - 2 - tile(K,N) -> 데이터A를 N번 반복해 행렬로 만든다. [EX] import numpy as np A = 1 B = np.array([0, 1]) C = np.array([0, 1], [2, 3]) >>> np.tile(A, 3) array([1, 1, 1]) >>> np.tile(B, 3) array([0, 1, 0, 1, 0, 1]) >>> np.tile(C, 3) array([[0, 1, 0, 1, 0, 1], [2, 3, 2, 3, 2, 3]]) >>> np.tile(A, (2, 3)) array([[1, 1, 1], [1, 1, 1]]) >>> np.tile(B, (2, 3)) array([[0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1]]) >>> np.tile(C, (2, 3)) array([[0, 1, 0, 1, 0, 1], [2, 3, 2, 3, 2, 3], [0, 1, 0, 1, 0, 1], [2, 3, 2, 3, 2, 3]]) >>> np.tile(B, (4,2,3)) array([[[0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1]], [[0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1]], [[0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1]], [[0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1]]])

2016년 3월 21일 월요일

파이썬 기본

print( " hellow %s  : %s " %(name , age) )


list = [ 1 , 2 , 3 , 4]


list[ 2 : 4] = [ 3 , 4 ]   < 리스트의 인덱스 2에서 3까지 표시


list.append(10)  -> list = [1,2,3,4,10] 이 된다.


del list [1] -> 인덱스 1인 2가 제거된다.


list + list


list * list


튜플 tuple = (0, 1, 2) ->안의 항목들을 지우거나 추가하는게 불가능


---------------- 흐름 제어 -----------------


 - if -
if age > 20:
   print("test")
   realage = 90
elif age == 30 or age == 32 and age < 35:
   print ("old")
else:
   print("young")


- for -   // list 안의 요소들이순서대로 x 로 들어간후 한번 루프 실행후 다음 요소가 x로 들어가서 다시 루프가 돌아간다.
for x in list:   
    print ("x")


for x in range(0,5):
   print ("x")


-while -  // 조건문이 false 되면 멈춤


step = 0
while step < 1000:
   print ("step")


while true:
   if step == 500:
      print("step")
   elif step == 700:
      break
   else
      step = step + 1


while x > 50 and y < 100:

2016년 3월 20일 일요일

ASP.NET 의 이해

동적 웹 페이지를 만들기위해선 웹 어플리케이션을 개발해야한다.


웹 어플리케이션의 개발에는


ASP , ASP.NET , JSP , PHP , Ruby 등이 있다.



웹 프로그래밍 개요

네트워크


서버 : 자료나 자원을 제공
클라이언트 : 자료나 자원을 요청


 웹 어플리케이션 : 웹을 기반으로 실행되는 프로그램. 웹 페이지를 통해 구현


-정적 웹 페이지-


웹은 자원의 위치를 표현하는 주소인 URL, 자원을 주고받기 위한 약속 HTTP, 자원을 표현하고 자원간의 이동을 쉽게 할 수 있도록 HTML 로 구성된다.


클라이언트는 웹브라우져


서버는 IIS,Apach,Tomcat,PHP를 설치해 제공


-동적 웹 페이지-


과정 : 주소를 입력해 요청 > 요청받은 웹 서버는 HTTP 에 따라 해석, URL 이 가르키는 동적 웹 페이지 호출 > 동적 웹 페이지의 코드(웹 어플리케이션)을 이용하여 여러가지 상황을 고려한 문서를 만든다.  (이때 필요한 자료는 대부분 데이터 베이스로부터 얻는다.) > 웹 어플리케이션이 만든 문서를 규약에따라 보내면 클라이언트는 규약에 따라 응답을 해석한 후, 해당 문서를 웹 브라우저에 전달한다. 웹브라우저는 받은 문서 (HTML)을 해석하여 내용을 화면에 나타낸다.