머신러닝 프로그래밍 3주차

l = [3,4,5,6,7]
l.sort()
  1. list 본체 정렬 reverse : 리스트를 거꾸로 뒤집는다. desc 정렬이 아님

a = [1, 10, 5, 7, 6]

a.reverse()

a

[6, 7, 5, 10, 1]

sort : 정렬, 기본값은 오름차순 정렬, reverse옵션 True는 내림차순 정렬

a = [1, 10, 5, 7, 6]

a.sort()

a

[1, 5, 6, 7, 10]

a = [1, 10, 5, 7, 6]

a.sort(reverse=True)

a

[10, 7, 6, 5, 1]

sort의 key 옵션, key 옵션에 지정된 함수의 결과에따라 정렬, 아래는 원소의 길이

m = ‘나는 파이썬을 잘하고 싶다’

m = m.split()

m

[‘나는’, ‘파이썬을’, ‘잘하고’, ‘싶다’]

m.sort(key=len)

m

[‘나는’, ‘싶다’, ‘잘하고’, ‘파이썬을’]

type(l)
list
help(l)
Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None
# 함수 선언
def myFunction():
    print("Hello World")
myFunction()
Hello World
def myFunction():
    n =1 
    for i in range(1,11):
        n *= i
    print(n)
myFunction()
3628800
#매개변수 사용하기
def myFunction(m):
    n =1 
    for i in range(1,m):
        n *= i
    print(n)
myFunction(10)
myFunction(20)
myFunction(30)
362880
121645100408832000
8841761993739701954543616000000
# 위코드와 같음
n =1 
for i in range(1,10):
    n *= i
print(n)

n =1 
for i in range(1,20):
    n *= i
print(n)

n =1 
for i in range(1,30):
    n *= i
print(n)
362880
121645100408832000
8841761993739701954543616000000
#return 사용하기
def myFunction(m):
    n =1 
    for i in range(1,m):
        n *= i
    print(n)
    
    return ("result is", n)
a = myFunction(10)
362880
a
('result is', 362880)
# factorial
n =1
for i in range(1,6):
    n *= i
print(n)
120
# factorial
def factorial(m):
    n =1 
    for i in range(1,m+1):
        n *=i
    return n
a = factorial(10)
a
3628800
def factorialR(m):
    if m ==1: return 1
    return m * factorialR(m-1)
#재귀함수 이용함
print(factorialR(10))
3628800
def explore(path):
    if path_is_terminal:
        print("this is terminal")
        return this_is_terminal
    for next_path in path:
        return explore(next_path)
l = [1,2,3,4,5]
l.sort()
l
[1, 2, 3, 4, 5]
 l = ["x4","b5","c4","d3"]
l.sort()
l #알파벳 순서대로 정렬됨 (a,b,c,d...)
['b5', 'c4', 'd3', 'x4']
def lessByTail(s1,s2):
    a = int(s1[-1])
    b = int(s2[-1])
    return (a < b)
print(lessByTail(l[0],l[1]))
False
lessByTail(l[0],l[1])
False
def takeTail(s):
    a = int(s[-1])
    return a
type(takeTail(l[0]))
int
l.sort(key=takeTail)
l
['d3', 'c4', 'x4', 'b5']
l = ["a_12314","b_33321","c_663","d_-2"]
def takeTail(s):
    prefix, suffix = s.split('_')
    suffix = int(suffix)
    return suffix
takeTail(l[1])
33321
l.sort(key=takeTail) #숫자순서대로 정렬됨
l
['d_-2', 'c_663', 'a_12314', 'b_33321']
def takeTail(s):
    prefix, suffix = s.split('_')
    suffix = int(suffix)
    print("taking...",s,"=>",suffix)
    return suffix
takeTail(l[2])
taking... a_12314 => 12314





12314
#1시 10분  
l.sort(key=takeTail)
taking... d_-2 => -2
taking... c_663 => 663
taking... a_12314 => 12314
taking... b_33321 => 33321
l
['d_-2', 'c_663', 'a_12314', 'b_33321']
help(str.split)
Help on method_descriptor:

split(...)
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.
l = ["a____12314","b___33321","c_663","d_-2"]
# ___ 언더바 많을 경우 이 함수 사용함
def takeTail(s):
    prefix, suffix = s.split('_',maxsplit=1)
    suffix = suffix.strip('_')
    suffix = int(suffix)
    print("taking...", s,"=>",suffix)
    return suffix
takeTail(l[0])
taking... a____12314 => 12314





12314
# # ___ 언더바 많을 경우 이 함수 사용함 (2번째 방법)
def takeTail(s):
    prefix, suffix = s.rsplit('_',maxsplit=1)#오른쪽부터 쪼개짐
    #suffix = suffix.strip('_')
    suffix = int(suffix)
    print("taking...", s,"=>",suffix)
    return suffix
takeTail(l[0])
taking... a____12314 => 12314





12314
l.sort(key=takeTail)
taking... a____12314 => 12314
taking... b___33321 => 33321
taking... c_663 => 663
taking... d_-2 => -2
l
['d_-2', 'c_663', 'a____12314', 'b___33321']
# 변수를 통해 호출하기

f = takeTail
f
<function __main__.takeTail(s)>
f("23331_2424")
taking... 23331_2424 => 2424





2424
l = [f,takeTail,l.sort]
l[0]("asdasdsa_11223")
taking... asdasdsa_11223 => 11223





11223
l = ["a____12314","b___33321","c_663","d_-2"]
def takeTail(x):
    return int(x.rsplit('_',1)[-1])# suffix는 뒷쪽에 있으므로 -1을 넣어줌
# 람다식으로 정렬하기 ,위에 코드와 동일한 코드
l.sort(key=lambda x:int(x.rsplit('_',1)[-1]))
l
['d_-2', 'c_663', 'a____12314', 'b___33321']
# class 

class MyClass:
    pass
myClass = MyClass() #class 인스턴스 만들었음
class Cup:
    def __init__(self, name, title):
        print("Initializing the cup",name,"title=",title)
        
a = Cup("lst cup","xx")
b = Cup("2st cup","dd")
Initializing the cup lst cup title= xx
Initializing the cup 2st cup title= dd
class Cup:
    def __init__(self, name, title="_"):
        print("Initializing the cup",name,"title=",title)
        
        
a = Cup("lst cup","xx")
b = Cup("2st cup") #지정안해주면 디폴트 값이 출력됨
Initializing the cup lst cup title= xx
Initializing the cup 2st cup title= _
class Cup:
    def __init__(self, name, title="_"):
        print("Initializing the cup",name,"title=",title)
        
        
    def fill(self,amount):
        print(amount)
a = Cup("lst cup","xx")
b = Cup("2st cup") #지정안해주면 디폴트 값이 출력됨
Initializing the cup lst cup title= xx
Initializing the cup 2st cup title= _
a
<__main__.Cup at 0x240eae25ac8>
dir(a)
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'fill']
a.fill(10)
10
class Cup:
    def __init__(self, name, title="_"):
        print("Initializing the cup",name,"title=",title)
        self.name = name
        self.title = title
        self.amount = 0.0
       
    #물의 양을 증가시키겠다
    def fill(self,amount):
        self.amount += amount
        print(self.name,self.title,"filled=",amount)
        self.isEverFilled = True
a = Cup("1st cup", "xx")
b = Cup("2nd cup")
Initializing the cup 1st cup title= xx
Initializing the cup 2nd cup title= _
dir(a)
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'amount',
 'fill',
 'name',
 'title']
a.name
'1st cup'
a.fill(10)
1st cup xx filled= 10
a.amount
10.0
a.fill(10)
1st cup xx filled= 10
a.amount
20.0
a.isEverFilled
True
a.fill(0)
1st cup xx filled= 0
a.isEverFilled
True
a.isEverFilled = False
a.isEverFilled
False
a.isEverFilled = ("asdd1","dss")
a.isEverFilled
('asdd1', 'dss')
#클래스를 사용하는 이유 - 액셀 안에 개인 정보 관리를 위해 사용함
 
# 1번째 방법
class UserInfo:
    def __init__(self, familyName, name, birthdate, year):
        self.familyName = familyName
        self.name = name
        pass
    
    def getFullName(self):
        return self.familyName + ' ' + self.name
ui = UserInfo("kim","ara","0101","1999")
ui.name
'ara'
ui.familyName
'kim'
ui.getFullName()
'kim ara'
# 2번째 방법
class UserInfo:
    def __init__(self, famailyName, name,birthdate, year):
        self.famailyName = famailyName
        self.name = name
        pass
    
    def getFullName(self, isNameFirst=False):
        if isNameFirst: 
            return self.name + ' ' + self.famailyName
        
        return self.famailyName + ' ' + self.name
        
ui = UserInfo("kim","ara","0101","1999")
ui.getFullName(True)
'ara kim'
ui.getFullName(False)
'kim ara'
#3번째 방법 ( 성은 대문자로 바꾸기)
class UserInfo:
    def __init__(self, famailyName, name,birthdate, year):
        self.famailyName = famailyName
        self.name = name
        pass
    
    def getFullName(self, isNameFirst=False):
        if isNameFirst: # true일 경우에 실행됨
            return self.name + ' ' + self.famailyName
        
        return self.famailyName.upper() + ', ' + self.name
        
ui = UserInfo("kim","Ara","0101","1999")
ui.getFullName(False)
'KIM, Ara'
ui.getFullName()# 기본값이 false로 되있음
'KIM, Ara'
#예제 
class SpecialUserInfo(UserInfo):
    def special(self):
        pass
sui = SpecialUserInfo("s","p","dkdkd","2283")
sui.getFullName()
'S, p'
sui.special()
dir(sui)
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'famailyName',
 'getFullName',
 'name',
 'special']