diff --git a/1st_n_last_spell b/1st_n_last_spell deleted file mode 100644 index 4a732be..0000000 --- a/1st_n_last_spell +++ /dev/null @@ -1,19 +0,0 @@ -from collections import Counter #collections에서 Counter 모듈을 임포트 - -with open('test.txt','rt',encoding='utf-8') as f: - data=f.read() #with문으로 첨부파일을 열고 오픈한다. -data=data.lower() #대문자도 인식하기 위해 데이터를 소문자로 변환한다. -removal="-.[]()" #단어 끊기에 방해가 되는 기호들을 removal 변수에 저장한다. -for x in range(len(removal)): - data=data.replace(removal[x]," ") #removal 안에 저장돼있는 기호들을 빈 칸으로 대체한다. -words = data.split() #데이터를 단어 별로 쪼갠다. - -start=input('시작 문자열 입력:') -end=input('끝 문자열 입력:') - -wordlist=[] -for word in words: - if word.startswith(start) and word.endswith(end): - wordlist.append(word) - count = Counter(wordlist) #wordlist라는 리스트를 생성한 후 startswith()와 endswith 메서드를 이용해 시작 문자열과 끝 문자열을 모두 만족하는 단어를 구하고 이를 append()메서드를 통해 wordlist에 요소로 삽입한다. -print(Counter(wordlist).most_common()) #Counter를 이용해 wordlist 요소의 개수를 세며, Counter 내의 most_common()을 이용해 최다 개수 순으로 정렬한다. diff --git a/DataAnalysis/Numpy b/DataAnalysis/Numpy deleted file mode 100644 index 5f30a5c..0000000 --- a/DataAnalysis/Numpy +++ /dev/null @@ -1,73 +0,0 @@ -import numpy as np - -array = np.array(range(5)) - ->> 1차원 array -array = np.array(range(10)) -print(array) #[0 1 2 3 4 5 6 7 8 9] - -# 1. array의 자료형 -print(type(array)) # - -# 2. array의 차원 -print(array.ndim) #1 - - -# 3. array의 모양 -print(array.shape) #(10,) - -# 4. array의 크기를 출력 -print(array.size) #10 - -# 5. array의 dtype(data type) -print(array.dtype) #int64 - -# 6. array의 인덱스 5의 요소 -print(array[5]) #5 - -# 7. array의 인덱스 3의 요소부터 인덱스 5 요소 -print(array[3:6]) #[3 4 5] - - ->> 2차원 array - -#1부터 15까지 들어있는 (3,5)짜리 배열 -matrix = np.array(range(1,16)) -matrix.shape = 3,5 -print(matrix) - -#[[ 1 2 3 4 5] - [ 6 7 8 9 10] - [11 12 13 14 15]] - -# 1. matrix의 자료형 -print(type(matrix)) # - -# 2. matrix의 차원 -print(matrix.ndim) #2 - -# 3. matrix의 모양 -print(matrix.shape) #(3, 5) - -# 4. matrix의 크기 -print(matrix.size) #15 - -# 5. matrix의 dtype(data type) -print(matrix.dtype) #int64 - -# 6. matrix의 dtype을 str로 변경 -print(matrix.astype('str')) - -#[['1' '2' '3' '4' '5'] - ['6' '7' '8' '9' '10'] - ['11' '12' '13' '14' '15']] - -# 7. matrix의 (2,3) 인덱스의 요소 -print(matrix[2,3]) #14 - -# 8. matrix의 행은 인덱스 0부터 인덱스 1까지, 열은 인덱스 1부터 인덱스 3까지 출력 -print(matrix[0:2,1:4]) -#[[2 3 4] - [7 8 9]] - - diff --git a/DataAnalysis/indexing_slicing b/DataAnalysis/indexing_slicing deleted file mode 100644 index 08aa305..0000000 --- a/DataAnalysis/indexing_slicing +++ /dev/null @@ -1,21 +0,0 @@ -import numpy as np - -matrix = np.arange(1, 13, 1).reshape(3, 4) -print(matrix) - -#[[ 1 2 3 4] - [ 5 6 7 8] - [ 9 10 11 12]] - -# 1. Indexing을 통해 값 2를 출력 -answer1 =matrix[0,1] #2 - -# 2. Slicing을 통해 매트릭스 일부인 9, 10을 가져와 출력 -answer2 = matrix[2:,:2] #[[ 9 10]] - -# 3. Boolean indexing을 통해 5보다 작은 수를 찾아 출력 -answer3 = matrix[matrix<5] #[1 2 3 4] - -# 4. Fancy indexing을 통해 두 번째 행만 추출하여 출력 -answer4 = matrix[[1]] #[[5 6 7 8]] - diff --git a/DataAnalysis/module_package b/DataAnalysis/module_package deleted file mode 100644 index 6feb44c..0000000 --- a/DataAnalysis/module_package +++ /dev/null @@ -1,11 +0,0 @@ -from random import randrange -import math - -var1=randrange(1,11) -var2=math.log(5184,72) - -print(var1,var2) - -from urllib.request import urlopen - -webpage = urlopen("https://en.wikipedia.org/wiki/Lorem_ipsum").read().decode("utf-8") diff --git a/DataAnalysis/pandas b/DataAnalysis/pandas deleted file mode 100644 index 600d2e7..0000000 --- a/DataAnalysis/pandas +++ /dev/null @@ -1,19 +0,0 @@ -import numpy as np -import pandas as pd - -# 시리즈 데이터를 만드는 방법 -series = pd.Series([1,2,3,4], index = ['a', 'b', 'c', 'd'], name="Title") -print(series, "\n") - - -# 국가별 인구 수 시리즈 데이터 - -dict = { -'korea' : 5180, -'japan' : 12718, -'china' : 141500, -'usa' : 32676 -} - -country=pd.Series(dict) -print(country) diff --git a/README.md b/README.md index 36ecf55..a22af19 100644 --- a/README.md +++ b/README.md @@ -1,2 +1 @@ -# Python Programming Practices -Programming and Data Analysis with Python +# first-repository diff --git a/bank-interest b/bank-interest deleted file mode 100644 index 9c0ca80..0000000 --- a/bank-interest +++ /dev/null @@ -1,10 +0,0 @@ -principal = int(input('원금(원):')) -interest_rate = int(input('이자율(%):')) / 100 -period = int(input('예치기간(년):')) -# 원금, 이자율, 예치기간을 각각 변수 principal, interest_rate, period로 설정하였다. input() 함수를 이용해 각각의 값을 입력하고, int() 함수를 이용해 정수형 데이터로 변환한다. 이자율은 이자 계산을 위해 이자율 값을 입력한 값에다 별도로 100으로 나눠주도록 한다. -simple = int(((principal + principal * interest_rate * period) - principal)) -compound = int(((principal * (1 + interest_rate)**period) - principal)) -# 단리이자와 복리이자를 각각 변수 simple, compound로 설정하고 이자를 구하는 식을 변수에 저장한 후에 이를 int() 함수를 이용해 정수형 데이터로 변환한다. -print(period, '년 후 단리 이자는', simple, '원입니다.') -print(period, '년 후 복리 이자는', compound, '원입니다.') -# 단리 이자의 값과 복리 이자의 값을 print() 함수를 통해 각각 위와 같이 출력한다. diff --git a/biggest_number_impossible.md b/biggest_number_impossible.md deleted file mode 100644 index 7c1c4b9..0000000 --- a/biggest_number_impossible.md +++ /dev/null @@ -1,131 +0,0 @@ -# 7, 11, 17로 구성할 수 없는 가장 큰 수를 찾기 - -## 어떤 수 N이 7, 11, 17을 조합하여 구성할 수 없는 최대의 수라면, N+1, N+2, N+3…은 모두 7, 11, 17을 조합하여 구성 가능한 숫자다. - -- 30은 구성할 수 없음 -- 31 ~ 36은 구성할 수 있음 (직접 해봤을 때) -- 37 구성 불가능 -- 38 ~ 44 구성 가능 (31 ~ 36이 구성 가능하기 때문에 7을 각각 하나씩 더 써서) -- 45 구성 가능 -- 따라서 이후의 모든 수가 7, 11, 17을 조합하여 구성할 수 있으므로 정답은 37 - -## 1. 단순 반복(Iteration)을 통한 해결 - -위 풀이를 적용한 가장 쉬운 알고리즘은 0부터 시작해서 하나씩 체크하면서 세 개의 input 중 가장 작은 수에 대해 그 수만큼의 연속한 숫자가 세 개의 input의 조합으로 구성 가능할 때까지 반복해 보는 것 - -1. 자연수 3개를 받을 함수 solver를 만든 다음, 그 중 가장 작은 수 minimum을 찾는다. - -2. check_list가 minimum 이하일 때까지 while loop을 설정한다. - -3. possible_range로 구성 가능한지 체크해 볼 조합의 범위를 각 input들에 대해 num을 각각 input1, input2, input3으로 나눈 몫으로 둔다.2 - -4. 기본적으로 구성 가능한지(feasibility)를 False로 두고, input1, input2, input3을 범위 내에서 조합하여 num을 구성할 수 있는지를 확인한다. - -5. 확인하여 구성 가능하다면 feasibility를 True로 두고, check_list에 넣는다. - -6. 모든 가능한 조합에서 num을 조합할 수 없다면 그대로 False로 두고, check_list를 비운다.3 - -7. 다음 num의 크기를 1씩 더해주며 계속 while loop을 돌리고, check_list에 minimum 수만큼 채워지면 check_list의 첫 번째 수보다 1 작은 값을 답으로 리턴한다. -``` -def solver(input1, input2, input3): - minimum = min([input1, input2, input3]) - check_list = [] - num = 0 - while len(check_list) <= minimum: - possible_range = [num//input1, num//input2, num//input3] - feasibility = False - for i in range(0, possible_range[0] + 1): - for j in range(0, possible_range[1] + 1): - for k in range(0, possible_range[2] + 1): - if input1 * i + input2 * j + input3 * k == num: - check_list.append(num) - feasibility = True - break - else: - continue - break - else: - continue - break - if feasibility == False: - check_list = [] - num += 1 - answer = check_list[0] - 1 - return answer - -solution = solver(7, 11, 17) -print(solution) -``` - - -## 2. 동적계획법(DP, Dynamic Programming)을 이용한 코드 - -위의 1번 코드는 생각하기는 쉽지만 연산 속도가 너무 오래 걸린다. -예를 들어 100이 구성 가능한지를 7, 11, 17의 조합으로 확인하려면 최대 14*9*5 = 630번의 연산을 해야 하고, 101, 102, 103... 언제 끝날 지 모르는 연산을 계속해서 해야 한다면 연산 수는 엄청나게 늚 - -동적계획법(Dynamic Programming)을 사용한다면 더 쉽게 문제를 해결할 수 있습니다. - -7, 11, 17의 경우, 0부터 17까지만 체크해서 구성 가능 여부를 기록해 둔 다음, 18부터는 -7, -11, -17을 해 보았을 때 구성가능했는지를 확인해보면 됩니다. 이 때 구성 가능하다면, 그 뺀 수를 한 번 더 사용하면 구성 가능하다는 의미니까요. 그리고 계속해서 기록해 나가면 됩니다. - -이 경우, 17까지만 체크하고 나니 그 뒤에는 기록했던 것을 체크해 보고 다시 기록을 추가하기만 하면 되니 연산이 아주 빨라지게 되겠죠? - -1. memoization_table을 만들고 True를 하나 넣어 놓는다. (왜냐하면 0은 항상 조합 가능) - -2. 1번 코드의 for문을 적용하여 세 개의 input 중 가장 큰 수까지 구성가능한지를 체크하며 memoization_table에 기록한다. - -3. check_list가 다 채워질 때까지 while문을 1번 코드처럼 적용하되, 구성가능한지를 memoization_table을 이용해 판단한다. - -*현재 num에서 input1 or input2 or input3를 뺀 수가memoization_table에서 구성 가능하다고 되어 있다면 거기서 input1or input2 or input3를 한 번 더 쓰면 현재 num이 나오므로 마찬가지로 구성 가능하다고 기록한다. - -4. 다음 num의 크기를 1씩 더해주며 계속 while loop을 돌리고, check_list에 minimum수만큼 채워지면 check_list의 첫 번째 수보다 1 작은 값을 답으로 리턴한다. - -``` -def solver_DP(input1, input2, input3): - minimum = min([input1, input2, input3]) - maximum = max([input1, input2, input3]) - memoization_table = [True] - check_list = [] - - for num in range(maximum): - possible_range = [num//input1, num//input2, num//input3] - memoization_table.append(False) - for i in range(0, possible_range[0] + 1): - for j in range(0, possible_range[1] + 1): - for k in range(0, possible_range[2] + 1): - if input1 * i + input2 * j + input3 * k == num: - memoization_table[num] = True - break - else: - continue - break - else: - num += 1 - continue - break - - while len(check_list) <= minimum: - memoization_table.append(False) - if memoization_table[num - input1] \ - or memoization_table[num - input2] \ - or memoization_table[num - input3]: - memoization_table[num] = True - check_list.append(num) - else: - memoization_table[num] = False - check_list = [] - num += 1 - - answer = check_list[0] - 1 - return answer - -solution = solver_DP(7, 11, 17) -print(solution) -``` - -위 방법의 경우 7, 11, 17일 때는 연산 속도가 크게 차이가 나지 않을 수 있지만 만약 큰 수에 대해 연산해야 한다면 어떨까요? -예를 들어 553, 757, 901로 구성 불가능한 가장 큰 수를 찾아 볼까요? - -solver(553, 757, 901) -solver_DP(553, 757, 901) - -[출처] 실전편 ② 나를 먹어요 케이크 해답|작성자 엘리스코딩 diff --git a/class b/class deleted file mode 100644 index fd0b70b..0000000 --- a/class +++ /dev/null @@ -1,60 +0,0 @@ -class Complex: - def __init__(self, real, image): - self.real = real - self.image = image - - def __add__(self, c): - real = self.real + c.real - image = self.image + c.image - return Complex(real, image) - def __sub__(self, c): - real = self.real - c.real - image = self.image - c.image - return Complex(real, image) - - def __str__(self): - op = '+' if self.image >= 0 else '-' - return '%d %s %di' % (self.real, op, abs(self.image)) - -#---------------------------아래부터 추가된 기능---------------------------------- - - def __neg__(self): - real = -self.real - image = -self.image - return Complex(real, image) - # real과 image에 각각 객체 self와 image에 –를 붙이도록 설정하여 리턴한다. - - def __mul__(self, c): - real = self.real * c.real - image = self.image * c.image - return Complex(real, image) - # real과 image에 각각 객체 self와 c끼리 곱하도록 설정하여 리턴한다. - - def __truediv__(self, c): - real = self.real / c.real - image = self.image / c.image - return Complex(real, image) - # 나눗셈 메서드엔 __div__()와 __truediv__()가 있는데, __div__메서드는 파이썬2만 가능하므로 __truediv__를 사용한다. real과 image에 각각 객체 self와 c끼리 나누도록 설정하여 리턴한다. - - def __pow__(self, power, modulo=None): - real = self.real**2 - image = self.image**2 - return Complex(real, image) - # real과 image에 각각 객체 self에 제곱하도록 설정하여 리턴한다. - -c1 = Complex(2, 3) -c2 = Complex(4, 5) -c3 = c1 + c2 -c4 = c1 - c2 -c5 = c1 * c2 -c6 = c2 / c1 -c7 = c2**2 - -print(c1) # 2 +3i 출력 -print(c2) # 4 + 5i 출력 -print(c3) # 6 + 8i 출력, __add__() 특수메서드 테스트 -print(c4) # -2 – 2i 출력, __sub__() 특수메서드 테스트 -print(-c1) # -2 – 3i 출력, __neg__() 특수메서드 테스트 -print(c5) # 8 + 15i 출력, __mul__() 특수메서드 테스트 -print(c6) # 2+ 1i 출력, __truediv__() 특수메서드 테스트 -print(c7) # 16 + 25i 출력, __pow__() 특수메서드 테스트 diff --git a/sqlite_student-inf.py b/sqlite_student-inf.py deleted file mode 100644 index 019bc69..0000000 --- a/sqlite_student-inf.py +++ /dev/null @@ -1,75 +0,0 @@ -import sqlite3 -conn = sqlite3.connect('crud.db') - -curs = conn.cursor() -curs.execute('''CREATE TABLE IF NOT EXISTS student - (no INT PRIMARY KEY, name VARCHAR(20), sex VARCHAR(20))''') -while True: - print('1.학생 정보 전체 조회') - print('2. 학생 정보 조회') - print('3. 학생 데이터 추가') - print('4. 학생 데이터 수정') - print('5. 학생 데이터 삭제') - print('6. 프로그램 종료') - choice=int(input('선택 >>')) - - if choice==1: - curs.execute('SELECT * FROM student') - rows = curs.fetchall() - if not rows: - print('입력된 학생 데이터가 없습니다.') - else: - curs.execute('SELECT * FROM student') - rows = curs.fetchall() - print(rows) - elif choice==2: - no = int(input('학번 입력:')) - curs.execute('SELECT * FROM student WHERE no =(?)', (no,)) - rows=curs.fetchall() - print(rows) - if not rows: - print('조회된 데이터가 없습니다.') - elif choice==3: - no=int(input('학번 입력:')) - curs.execute('SELECT no FROM student') - rows = curs.fetchall() - a = 0 - for i in rows: - for x in i: - if x == no: - a = 1 - print(no,'는 이미 등록된 학번입니다.') - if a == 0: - name=input('이름 입력:') - sex=input('성별 입력:') - ins = 'INSERT INTO student (no, name, sex) VALUES(?, ?, ?)' - curs.execute(ins,(no, name, sex)) - print('데이터가 저장되었습니다.') - elif choice==4: - value=int(input('수정할 학생의 학번 입력:')) - change=input('이름 수정:') - curs.execute('UPDATE student SET name=(?) WHERE no =(?)', (change, value)) - sex=input('성별 입력:') - if sex == '': - pass - else: - curs.execute('UPDATE student SET sex=(?) WHERE no =(?)', (sex, value)) - print('수정이 완료되었습니다.') - elif choice==5: - value=int(input('삭제할 학생의 학번 입력:')) - curs.execute('SELECT * FROM student WHERE no=(?)', (value,)) - rows = curs.fetchall() - if not rows: - print('해당 학번의 학생은 존재하지 않습니다.') - else: - curs.execute('DELETE FROM student WHERE no=(?)', (value,)) - rows = curs.fetchall() - print('삭제하였습니다.') - elif choice==6: - print('프로그램을 종료합니다.') - conn.commit() - conn.close() - break - - - diff --git "a/\354\240\225\352\267\234\355\221\234\355\230\204\354\213\235.py" "b/\354\240\225\352\267\234\355\221\234\355\230\204\354\213\235.py" deleted file mode 100644 index 61df813..0000000 --- "a/\354\240\225\352\267\234\355\221\234\355\230\204\354\213\235.py" +++ /dev/null @@ -1,24 +0,0 @@ -import re -source = '''I wish I may, I wish might -... Have a dish of fish tonight.''' -re.findall(r'wish', source) -re.findall(r'wish|fish', source) -re.findall(r'^wish', source) -re.findall(r'^I wish', source) -re.findall(r'fish$', source) -re.findall(r'fish tonight\.', source) -re.findall(r'[wf]ish', source) -re.findall(r'[wsh]+', source) -re.findall(r'ght\W', source) -re.findall(r'I (?=wish)', source) -re.findall(r'(?<=I) wish', source) -re.findall(r'\bfish', source) - -text = 'apple banana cat' - -start = input('맨 앞글자: ') - -print(re.findall(r'\b%s\w+'%start, text)) - -pattern = re.compile('Python') # ‘Python’이란 문자열을 정규식으로 컴파일 -print(pattern.match('Python is easy.')) # source(‘Python is easy’)가 정규식 pattern과 일치하는지 확인