Chapter2 Writing Simple Programs (p.27~p.51)
-
Analyze the Problem
-
Determine Specifications
-
Create a Design
-
Implement the Design
-
Test/Debug the Program
-
Maintain the Program
Q1. Difference of Determine Specifications between Create a Design
- Coder & Architecture
이전에는 코더와 아키텍처의 구분이 명확한편이었다.
아키텍처의 역할이 Determine Specification을 하고 코더는 코딩만을 했었지만,
실무에서 miss communiction이 많이 나왔고, 최근에는 test development가 등장하게 되엇다.
- test development
test/debug를 detemine specification 레벨의 단계에서 진행하게끔 되었다.
만약 실무에서 고객사가 있다면 고객사에게 tase case로 Output을 받고,
test를 수행하면서 개발하는편이 miss communication을 줄이고 효율적으로 협업할 수 있다.
Q2. Why do we need a Pseudocode
의사코드(수도코드)는 알고리즘을 계획할 때 사용되는 비공식적인 도구이다.
제약이 있는 컴퓨터 언어로 알고리즘을 처음부터 작성하는 것은 불가능하다.
따라서 수도코드로 프로그램 과정을 단계별로 요약 정리할 수 있으며,
기술적인 부분보다는 프로그램의 흐름을 쉽게 표현할 수 있다.
```
Pseudocode is just precise English that describes what a program does.
It is meant to communicate algorithms without all the extra mental overhead of getting
the details right in any particular programming language.
```
refer: https://ko.wikihow.com/%EC%9D%98%EC%82%AC%EC%BD%94%EB%93%9C-%EC%9E%91%EC%84%B1%EB%B2%95
example
# Pseudocode
# Input the temperature in degrees Celsius (call it celsius) Calculate fahrenheit as (9/S) celsius + 32 Output fahrenheit
# To translate this design into a python program
def temperature_converter():
celsius = eval(input("What is the Celsius temperature?"))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit.")모든 identifiers는 _나 문자로 시작하고, reserved word에는 주의해야한다.
python keywords
False,None,True,and,as,assert,break,class,finally,is,continue,
for,lambda,def,from,nonlocal,del,global,not,elif,if,or,else,
import,pass,except,in,raise,,return,try,while,with,yield모든 데이터는 데이터 형태에 따라서 다른 포맷을 가지고 있으며, 다른 방법으로 저장된다. 프로그램 코드 중 새 데이터 값을 생성하거나 계산하는 프로그램 코드를 expressions 라고 부른다.
- literal : 가장 간단한 표현은 문자 그대로로, literal은 특정 값을 나타내기 위해 사용된다.
- string: Textual data를 String으로 부른다. python에서 ""는 문자열을 만들라고 말하는 매커니즘이다.
Q3. What does the evaluation mean?
언어로써 evaluation의 뜻은 평가이지만, Computer Science에서 eval은 어떤 뜻일까?
간단하게 얘기하자면 expression을 기본 데이터 유형으로 변환하는 프로세스를 말한다.
eval에 대해서 컴퓨터 사이언스 관점으로 설명하고 싶다면 repl에 대해서 자세히 살펴볼 것.
The process of turning an expression into an underlying data type is called evaluation.
When you type an expression into a Python shell evaluates the expression and prints out
a textual representation of the result.
refer: https://www.slipp.net/questions/211
print()
end라는 parameter를 가질 수 있다.
- Simple Assignment
# <variable> = <expr>, identifier expression- A variable can be assigned many times. It always retains the value of the most recent assignment. Remember, the values of variables can change. shows how the current value of a variable can be used to update its value.
- Notice that the old value doesn't get erased by the new one; the variable simply switches to refer to the new value.
i = 5 # create int(5) instance, bind it to i
j = i # bind j to the same int as i
j = 3 # create int(3) instance, bind it to j
print(i) # i still bound to the int(5), j bound to the int(3)
i = [1,2,3] # create the list instance, and bind it to i
j = i # bind j to the same list as i
i[0] = 5 # change the first item of i
print j # j is still bound to the same list as iQ4. Where did the Pointer go in Python?
Variables are not pointers. When you assign to a variable you are binding the name to an object.
From that point onwards you can refer to the object by using the name, until that name is rebound.
In your first example the name i is bound to the value 5.
Binding different values to the name j does not have any effect on i,
so when you later print the value of i the value is still 5.
In your second example you bind both i and j to the same list object.
When you modify the contents of the list, you can see the change regardless of which name you use to refer to the list.
Note that it would be incorrect if you said "both lists have changed".
There is only one list but it has two names (i and j) that refer to it.
# refer: https://stackoverflow.com/questions/13530998/python-variables-are-pointers
# refer: https://docs.python.org/2/reference/executionmodel.html
- garbage collection
this process of automatic memory management is actually called garbage collection.
메모리 관리기법 중 하나로, 프로그램이 동적으로 할당했던 메모리 영역 중에서 필요없게 된 영역을 해제하는 기능이다.
1959년 무렵 리스프의 문제를 해결하기 위해 존 매카시가 개발하였다.
할당문이 변수의 이전 값을 지우고 덮어쓰는 원인이 되지는 않지만 컴퓨터 메모리가 "검색된" 값으로
채워지는 것에 대해 걱정할 필요는 없다. 값이 더 이상 변수에 의해 참조되지 않으면 더 이상 유용하지 않기 때문이다.
Python은 공간이 새 값에 사용될 수 있도록 이러한 값을 메모리에서 자동으로 지운다.
예를들어, 옷장을 뒤져보고 그것에 라벨을 붙일 스티커가 없는 것을 버리는 것과 같다.
# refer - https://ko.wikipedia.org/wiki/%EC%93%B0%EB%A0%88%EA%B8%B0_%EC%88%98%EC%A7%91_(%EC%BB%B4%ED%93%A8%ED%84%B0_%EA%B3%BC%ED%95%99)
# refer- https://rushter.com/blog/python-garbage-collector/import gc
# @ ???????- Assigning Input
<variable> = input(<prompt>)
### <prompt> is a string expression that is used to prompt the user for input: The user types is then stored as a string.
### As a result, the string <prompt> is remembered in the variable <variable>.# User input is a number
<variable> = eval(input<prompt>)- 보안 문제
Q5. Why the eval funciton is dangerous?
사용자가 <prompt>에서 입력한 값이 바로 실행되기 때문에, 만약 악성코드가 입력되었을 경우,
매우 위험할 수 있다. 따라서, eval(input(<prompt>)) 방법은 실제 서비스에서는 잘 상용되지 않는다고 한다.
그렇다면 어떤 방법으로 실제 서비스들은 사용자에게서 input을 받고 있을까?
Beware: the eval function is very powerful and also potentially dangerous. As this example illustrates, when we evaluate user input, we are essentially allowing the user to enter a portion of our program. Python will dutifully evaluate whatever they type. Someone who knows Python could exploit this ability to enter malicious instructions. For example, the user could type an expression that captures private information or deletes files on the computer. In computer security, this is called a code injection attack, because an attacker is injecting malicious code into the running program.
- Simultaneous Assignment
<var1>, <var2>, ... , <varn> = <expr1>, <expr2>, ... , <exprn> 동시할당 - 이것은 Python에게 오른쪽의 모든식을 평가한 다음 이 값을 왼쪽에 명명된 해당 변수에 할당하라고 말한다.
- When you want to swap the values.
첫 번째 문장이 y의 값을 할당하여 x의 원래 값을 어떻게 결합하는지 확인하십시오.
그런 다음 두 번째 단계에서 x개의 장난감을 할당할 때, 우리는 원래 y 값의 복사본 두 개를 갖게 됩니다.
스왑 작업을 수행하는 한 가지 방법은 일시적으로 x의 원래 값을 기억하는 추가 변수를 도입하는 것입니다.
- Three-way-shuffle is common in other programming. In Python, the simultaneous assignment statement offers an elegant alternative.
# variables x, y, temp
x, y = 2, 4
print(x, y)
temp = x
x = y
print(x, y)
print(temp)
y = temp
print(x, y)
print(temp)- Because the assignment is simultaneous, it avoids wiping out one of the original values.
동시 할당이므로 원래 값 중 하나를 지우지 않습니다. 동시 할당을 통해 단일 입력에 있는 사용자로부터 여러 번호를 가져올 수도 있습니다. 이 프로그램을 사용하여 시험 점수를 평균화합니다.
x, y = 2, 4
x, y = y, x
print(x, y)-
What is Loop?
-
A Loop causes Python to go back and do some statements over and over again.
-
Flow Chart
-
for <var> in <sequence>:
<body>
# range, must be some kind of sequene
for <variable> in range(<expr>):얼마나 Loop를 돌릴지 정하고 Loop를 돌리는 것이 Definite Loops라고 한다. Deep learning과 같이 cost가 낮아졌을 때 학습을 멈추기 위해서는 조건문과 함께 infinite loop가 사용된다고 한다.
Definite Loops에서 list의 길이는 루프가 실행되는 횟수를 결정한다.
refer: Definite and indefinite loops
- meta-language - CS 프로그래밍 언어를 기술하기 위해 meta-language라는 정교한 표기법을 개발했다.
print(<expr>, <expr>, ... , <expr>)
print()
print(<expr>, <expr>, ... , <expr>, end="\n")
<variable> = input(<prompt>) -
큰 문제를 작은문제로 쪼개자
-
계산을 반복하지 말자, 즉 계산했던 것을 저장하자
-
DP 단점
- DP는 가독성이 떨어진다는 단점이 있다. 이를 극복하기 위해 메모리 부분과 코드의 로직 부분을 나누려고 한다.
- CHCHE를 어떻게 갱신해야하는 문제가 존재한다. DB가 바꼈을 경우, 이전 CHCHE 값을 배워놓은 DP는 문제가 된다.
-
redis library??
import redis
# Redis는 "REmote DIctionary System"의 약자로 메모리 기반의 Key/Value Store 이다.
Cassandra나 HBase와 같이 NoSQL DBMS로 분류되기도 하고, memcached와 같은 In memory 솔루션으로 분리되기도 한다.
# 성능은 memcached에 버금가면서 다양한 데이타 구조체를 지원함으로
Message Queue, Shared memory, Remote Dictionary 용도로도 사용될 수 있으며,
이런 이유로 인스탄트그램, 네이버 재팬의 LINE 메신져 서비스, StackOverflow,Blizzard,digg 등
여러 소셜 서비스에 널리 사용되고 있다
# refer: http://bcho.tistory.com/654 [조대협의 블로그]
-
example
- DP이나 가독성이 떨어진다는 단점이 존재
# 반복되는 계산이 이루어지는 부분 def sum_part(i): if i == 1: return 1 else: return sum_part(i-1)+1 def sum_total(n): result = 0 for i in range(1, n+1): result += 1/sum_part(i) return result
- 가독성을 위해 메로리를 관리하는 부분과 로직을 관리하는 부분을 나눠준다.
from functools import lru_cache @lru_cache(maxsize=10000) # 값을 기억해줌 @memoize() # 메모리를 관리하는 부분과 로직을 관리하는 부분을 # 메모리를 넣은 FUCNTION으로 바꿔줄것 def memoize(func): # 함수를 받아서 함수를 내뱉어준다. cache = {} def memoized_func(arg): if arg in cache: return cache[arg] else: cache[arg] = func(arg) return chche[arg] return memoized_func
- 첫번째 문제
Q. 자연수 N이 주어졌을 때, 1부터 N까지 한 줄에 하나씩 출력하는 프로그램을1. 작성하시오.
n = eval(input())
for i in range(n):
print(i+1)- eval(input()) 외에 다른 방법?
- Test case 작성
- 평균은 넘겠지 ?
Test case는 문제를 쪼개고 우리가 기본적으로 필요한 것을 명세하는 것이다.
평균은 넘겠지 문제는 두가지로 나눌 수 있다.
- 파싱하는 것
- 계산하는 것 (mock를 만든다. ) input 기능을 흉내만 내면 됨.