Coding Start Python

2021. 3. 12. 19:54Work/Python

728x90
반응형

문자열 뒤집기

def revert(s):
    if s:
        s = s[-1] + revert(s[:-1])
    return s

def revert2(s):
    return s[::-1]

str = "Hello python"

print(revert(str))
print(revert2(str))

문자열 단어 단위 뒤집기

def reverse(s):
    words = s.split(' ')
    rev = ' '.join(reversed(words))
    return rev

strWord = "Hello python"
print(reverse(strWord))

문자열 압축

def compression(s):
    count, last = 1, ""
    list_aux = []
    for i, c in enumerate(s):
        if last == c:
            count += 1
        else:
            if i != 0:
                list_aux.append(str(count))
            list_aux.append(c)
            count = 1
            last = c
    list_aux.append(str(count))
    return ''.join(list_aux)

print(compression("AABBBCCCCCDDDD"))

문자열 순열(permutations) : n개 중 r개를 골라 순서를 고려해 나열한 경우의 수 

# O(n!)
def perm(s):
    if len(s) < 2:
        return s
    res = []
    for i, c in enumerate(s):
        for cc in perm(s[:i] + s[i+1:]):
            res.append(c + cc)
    return res

print(perm("012"))
#0.084114초

import itertools
def permIter(s):
    res = itertools.permutations(s)
    return [''.join(i) for i in res]

print(permIter("012"))
# 0.023024초

문자열 조합(combinations) : 순열에서 순서를 고려하지 않는다.

def combi(s):
    if len(s) < 2:
        return s
    res = []
    for i, c in enumerate(s):
        res.append(c)
        for j in combi(s[:i] + s[i+1:]):
            res.append(c + j)
    return res

print(combi("01232131"))

import itertools
def combiIter(s):
    return list(itertools.combinations(s, 2))

print(combiIter("01232131"))

문자열 회문(palindrome) : 앞에서 읽는 것과 뒤에서 읽는 것이 동일한 단어

def palin(s):
    l = s.split(' ')
    s2 = ''.join(l)
    return s2 == s2[::-1]

print(palin("토마토"))

Set(집합) : 반복 가능, 가변적, 중복X, 정렬되지 않은 컬렉션, 삽입 : O(1), 합집합(union) : O(m+n), 교집합(intersection) : O(n)

# add
setP = {"A", "B", "C"}
setP.add("F")

print(setP)

# update or |= (합집합)
setP = {"A", "B", "C"}
setP.add("F")
setP.update({"A","B","D"}) # setP |= ({"A","B","D"})
print(setP)

# intersection or & (교집합)
setP = {"A", "B", "C"}
setP.add("F")
setV = setP.intersection({"B","C"}) # setV = setP & {"B","C"}
print(setV)

# difference or - (차집합)
setP = {"A", "B", "C"}
setP.add("F")
setV = setP.difference({"B","C"}) # setV = setP - {"B","C"}
print(setV)

# clear
setP = {"A", "B", "C"}
setP.clear()
print(setP)

# discard, remove, pop
setP = {"A", "B", "C"}
setP.add("F")
setP.discard("C") 
# setP.remove("C") #-> 항목이 없으면 KeyError
print(setP)

setP = {"A", "B", "C"}
setP.add("F")
print(setP.pop())
print(setP)

Dictionary 비교

def hello():
    print("hello")
def word():
    print("word")

action = "h"
func = dict(h=hello, w=word)
func[action]()

가정 assert

def test(t):
    assert type(t) is int, '정수 아닌 값이 있네'

for i in lists:
    test(i)
#결과
AssertionError: 정수 아닌 값이 있네

 

728x90
반응형

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

Python 공부!  (0) 2021.02.24