본문 바로가기
First step/AI 기초반

[TIL]21.06.18

by Joshua21 2021. 6. 23.


#2차원 리스트에서 copy로 복사한뒤 b의 요소를 변경하면 리스트 a,b모두에 반영됨
a=[[10,20],[30,40]]
b=a

b[0][0]= 500

print(a)
print(b)

a=[[10,20],[30,40]]

b=a.copy()

b[0][0]= 500

print(a)
print(b)

#2차원 이상의 다차원 리스트를 완전히 복사하려면 deepcopy를 써야함

a=[[10,20],[30,40]]
import copy
b = copy.deepcopy(a)

b[0][0]= 500

print(a)
print(b)

a= [[[0 for i in range(3)] for x in range(4)] for y in range(2)] 
print(a)


#replace(바꿀문자열,새문자열) 문자열 자체는 변경하지 않으며 바뀐 결과를 반환함
print('hello,world!'.replace('world','python'))

#바뀐 결과를 유지하고 싶다면 변수에 할당해준다
s='hello,world!'
s.replace('world','python')

print(s)


#str.maketrans(바꿀문자,새문자) translate사용하면 문자를바꾼뒤 결과를 반환
table = str.maketrans('aeuio','12345')
print('apple'.translate(table))

#split() 

print('apple pear grape pinapple orange'.split())

print('apple pear grape, pinapple orange'.split(','))

#join 각 문자열 사이에 공백이들어가도록 만듬
print(' '.join(['apple', 'pear', 'grape', 'pinapple', 'orange']))
#'apple pear grape pinapple orange'

print('-'.join(['apple', 'pear', 'grape', 'pinapple', 'orange']))

#문자열을 대,소문자로 바꾸기
print('Python'.upper())
print('PYTHON'.lower())

#l,r strip 좌 우 문자열의 공백을 삭제
print('          Python           '.rstrip())
print('          Python           '.lstrip())
print('          Python           '.strip())

#strip()안에 '특정문자열'을 문자열 앞뒤로  넣고 삭제시킬수도 있음
print('/*/*Python/*/*'.rstrip('/*'))
print('/*/*Python/*/*'.lstrip('/*'))
print('/*/*Python/*/*'.strip('/*'))

#l,rjust 문자열을 지정된 길이로 만든뒤 한쪽으로 정렬해 남는 공간을 공백으로채움
print('Python'.ljust(10))
print('Python'.rjust(10))


#center 문자열을 지정된길이가운데로 정렬 홀수일경우 왼쪽이 한칸더생김
print('Python'.center(10))


# method chanining 메소드를 줄줄이 연결하는것
print('Python'.rjust(10).upper())

#문자열 왼쪽에 0 채우기 문자열의 길이보다 지정된 길이가 작다면 아무것도 채우지 않음
print('35'.zfill(4))
print('3.5'.zfill(6))
print('hello'.zfill(10))


#find(찾을문자열) 문자열에서 특정 문자열을 찾아서 인덱스를 반환 없으면 -1
#왼쪽부터 문자열을 찾고 같은문자열이여러개일 경우 처음찾은 문자열 인덱스반환
print('apple pineapple'.find('pl'))
print('apple pineapple'.find('텨'))

#문자열의 오른쪽에서 부터 찾아서 인덱스 반환
print('apple pineapple'.rfind('pl'))
print('apple pineapple'.rfind('텨'))

#index(찾을문자열) 을 찾아 인덱스 반환 find와 다르게 없는 문자열은 에러가 발생
print('apple pineapple'.index('pl'))
print('apple pineapple'.rindex('pl'))


#count(문자열) 특정 문자열이 몇번 나오는지 알아냄
print('apple pineapple'.count('pl'))


#연습 문제 내 풀이
'apple pineapple apple pineapple'

alist = 'apple pineapple apple pineapple'.split(' ')

num = 'apple pineapple apple pineapple'.count('pl')
i=0
lenth=0
while i < num:    
    print(alist[i].find('pl')+lenth)
    lenth+=len(alist[i])+i
    i+=1

#정답
str1 = 'apple pineapple apple pineapple'

str2 = 'pl'
posit=str1.find(str2) # 문자열에서 특정문자열을 찾은 index값
print(posit) # 문자열에서 특정문자열을 찾은 index값

while str1[posit+len(str2):].find(str2) != -1:#찾은 인덱스다음 문자부터 특정찾기
    posit = str1[posit+len(str2):].find(str2) + posit + len(str2)
    print(posit)


#와일문안에 전부 넣은 정답
str1 = 'apple pineapple apple pineapple'
str2 = 'pl'
posit=-1
while str1[posit+len(str2):].find(str2) != -1:#찾은 인덱스다음 문자부터 특정찾기
    posit = str1[posit+len(str2):].find(str2) + posit + len(str2)
    print(posit)

    str1[-1+2:].find(str2) + -1 + 2

s='apple pineapple apple pineapple'
count=0
a=0
ina=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,]

while True:
    if count == len(s):
        break
    if s[count] == 'p' and s[count+1]=='l':
        ina[a] = count
        a+=1
    count+=1
print('count :',a)
for i in range(len(ina)):
    if ina[i] == 0:
        break
    print(ina[i])

#%s 서식 지정자로 문자열 넣기

print('i am %s.'%'james')

name = 'maria'
print('i am %s.'%name)    
#%d 정수
print("I'm %d years old"%20) 


#%f 실수 소수점 이하의 자릿수를 지정하고 싶으면 f앞에 .과 자릿수
print('%f'%2.3)
print('%.3f'%2.3)


#숫자를 붙여 문자열을 지정된 길이로 만듬
print('%10s'%'python')#오른쪽으로
print('%-10s'%'python')#쪽으로


#서식 지정자로 문자열 안에 여러개 넣기 ()활용
print('todat is %d %s'%(3,'april'))
      

#format {인덱스값}.format(값) 

print('hello, {0}'.format('world!'))
print('hello, {0}'.format(2021))

print('hello,{0} {2} {1}'.format('python','script',3.6))

#인덱스 없이 쓰면 순서대로 출력됨
print('hello,{} {} {}'.format('python','script',3.6))

#format 매소드에서 인덱스 대신 이름을 지정할수도 있음
print('hello,{language} {version}'.format(language='python',version='script'))


#다음과 같이 변수에 값을넣고 지정하면 되고 이떄는 문자열 앞에  f를 붙임
language = 'python'
version = 3.6
print(f'hello,{language} {version}')


#fotmat으로 문자열 정렬하기 인덱스넘버 : 뒤에 정렬할 방향과 길이를지정해줌
print('{0:<10}'.format('python'))#왼쪽정렬
print('{:>10}'.format('python'))#오른쪽 정

#인덱스를사용하지 않으면 정렬방법만 지정해도 됨
print('{0:<10} {2:>20}{1:<10}'.format('python', 'abc',123))


#{}를 사용할떄는 인덱스나이름뒤에 콜론을 붙이고 0과 갯수를 지정
#  $0갯수d%숫자
print('%03d'%1)
print('%03d'.format(35))
#소수점 이하 자릿수를 지정하고 싶을때는 .뒤에 자릿수를 지정
#  %0갯수.자릿수f%
print('%08.2f'%3.6)
print('{0:08.2f}'.format(150.37))


#인덱스: 채우기 정렬 길이.자릿수 자료형
print('{:0<10}'.format(15))
print('{:0>10}'.format(15))
#실수로 만들고싶으면
print('{:0>10.2f}'.format(15))

#남는 공간을 다양하게 채울수있음
print('{: >10}'.format(15))#빈칸으로 채움
print('{:x>10}'.format(15))#x로 채움
print('{:>10}'.format(15))#비워두면 기본으로 빈칸 채움

#예제
path = 'C:\\Users\\Edu\\AppData\\Local\\Programs\\Python\\Python36-32\\data.txt'

x = path.split('\\')

#x.recerse() ; filename = x[0] 해도 같은값
filename = x[-1] 

print(filename)

note = "the grown-ups' response, this time, was to advise me to lay aside my drawings of boa constrictors, whether from the inside or the outside, and devote myself instead to geography, history, arithmetic, and grammar. That is why, at the, age of six, I gave up what might have been a magnificent career as a painter. I had been disheartened by the failure of my Drawing Number One and my Drawing Number Two. Grown-ups never understand anything by themselves, and it is tiresome for children to be always and forever explaining things to the."
print(note.count('the ')+note.count('the.')+note.count('the,'))
print(note.replace(',','').replace('.','').split().count('the'))

#함수
def hello():
    for i in range(10):
        print('hello,world!')
    
hello()

#def 함수이름 (매개변수1,매개변수2) parameter
def add(a,b):
    print(a+b)
add(20,330) #함수를 호출할떄넣는 값을 인수라고 부름

#함수의결과를 반환 할때 retrun을 사용

def add(a,b):
        return a+b
x=add(10,20)
print(x)

def add(a,b,c):
        return a*b*c
d,e,f=map(int,input('숫자 3개 입력').split())
x=add(d,e,f)
print(x)


#함수 값을 여러개 반환가능 하나의 변수가 반환받으면 튜플이 생성됨
def math(a,b):
    return a+b , a-b
x=math(5,2)

print(x)
print(type(x))#튜플이 생성됨
#두개의 값을두개의 변수로 언팩해서 받아도 되지만 하나의튜플로 받고 인덱스를 활용 값을출력해도됨
print(x[0])
print(type(x[0]))


def math(a,b):
    return a+b,a-b,a*b,a/b

m,n,o,p=math(10,20)
print('+=%.2f =+%.2f *=%.2f /=%.2f'%(m,n,o,p))


#함수를 여러개 만든뒤 각 함수를 호출하는 과정을 스택 다이어그램이라고 함

def mul(a,b):
    c = a*b
    return c

def add(a,b):
    c= a+b
    print(c)
    d=mul(a,b)
    print(d)
x=10
y=20

add(x,y)
    

#연습문제
def get_quotient_remainder(a,b):
    c=a//b
    d=a%b
    return c,d

x=10
y=3

quotient,remainder = get_quotient_remainder(x,y)
print('몫: {0}, 나머지: {1}'.format(quotient,remainder))

#연습문제
def calc(a,b):
    return a+b,a-b,a*b,a/b

x,y=map(int,input().split())

a,s,m,d=calc(x,y)

print('덧셈:{0},뺄셈:{1},곱셈:{2},나눗셈:{3}'.format(a,s,m,d))

'''
def plus(a,b):
    return a+b
def minus(a,b):
    return a-b
def mul(a,b):
    return a*b
def div(a,b):
    return a/b
def etc(a,b):
    return a%b

print('='*30,'\n1.더하기\n2.뺴\n3.곱하기\n4.나누\n5.나머지구하\n6.나가\n','='*30)
x=int(input('원하는 연산자를 입력해 주세요.'))
y=int(input('첫번쨰 숫자를 입력하세요.'))
z=int(input('두번쨰 숫자를 입력하세요.'))
result=0

while True:
    if 0< x <6:
        y=int(input('첫번쨰 숫자를 입력하세요.'))
        z=int(input('두번쨰 숫자를 입력하세요.'))            
        if x==1:
            result=plus(y,z)
            print('결과는',result,'입니다.')      
        elif x==2:
            result=minus(y,z)
            print('결과는',result,'입니다.')
        elif x==3:
            result=mul(y,z)
            print('결과는',result,'입니다.')
        elif x==4:
            result=div(y,z)
            print('결과는',result,'입니다.')
        elif x==5:
            result=etc(y,z)
            print('결과는',result,'입니다.')
        elif x==6:
            print('잘못 입력 하셨습니다.')
            break
      













'First step > AI 기초반' 카테고리의 다른 글

[TIL]21.06.22 텍스트파일 읽기,수정하기,타자연습만들기,GUI기초1  (0) 2021.06.23
[TIL]21.06.21  (0) 2021.06.23
[TIL]21.06.17  (0) 2021.06.23
[TIL]21.06.16  (0) 2021.06.23
[TIL]21.06.14  (0) 2021.06.23