
[카테고리:] python
Point in polygon

기본 개념은
- 수평선인 경우 점과 선의 y가 동일한경우 (기울기 = 0)
- 수직선인 경우 선의 y 사이에 점의 y가 존재하는 경우(기울기 = 무한대)
- 그외
로 구분하고
A. 점이 선에 존재하는 경우
B. 점의 우측 연장선이 vertex를 통과하는 경우
에는 polygon 내부에 점이 존재하는걸로 인정
A, B 모두에 해당하진 않으나 점의 우측연장선이 선과 만나는 경우를 세어서
가. odd이면 내부 점
나. even이면 외부 점
으로 판별한다.
위 코드는
- inner function 을 사용
- vertex 처리시 point[1] in (y1, y2)인 경우 true로 처리함. (27번째 줄)
- return값을 cross_points % 2로 하여 0인 경우 False, 1인 경우 True가 되도록 처리(38번째줄)
- return값에서 True, False를 정할때 판단식을 이용한 점(18번, 27번 줄)
아래는 내가 작성한 것 (기본적인 내용은 동일하나, 위 코드와 비교하면 엄청난 수준 차이다.)


list index에 대해
- list 인수를 그대로 받으면 됨. 쓸데없이 다시 리스트를 작성할 필요가 없음.
무의미한 작업 
제대로 한 작업 
- list의 갯수가 3일경우, 인덱스는 -3에서 2까지 index로 쓸수 있다.

annotation

def 함수명(parameter: expression) -> expression:

*Args and **Kwargs
함수에 들어가는 변수를 어떻게 처리하는지에 대한 좋은 설명이다.
약간의 트릭을 섞어서 설명하고 있는데 제목 그대로 아주 명쾌하다.
Python args and kwargs: Demystified

위 예제에서 리스트 l을 *l 로 풀어서 1, 2, 3으로 만들어 mysum함수에 넣는다.
mysum함수는 여러개의 parameter를 *plus로 다 받아낸다.
——————————–
*args and **kwargs are special syntax that are used in functions to pass a variable number of arguments to a function.
*args occur before **kwargs in a function definition.
*args and **kwargs are best used in situations where the number of inputs will remain relatively small.
You can use any name you want; args and kwargs are only by convention and not a requirement. For example, you can use *foo instead of *args or **foo instead of **kwargs.
*args
- to use a single asterisk (
*) to unpack iterables
def my_sum(*args): result = 0 # Iterating over the Python args tuple for x in args: result += x return result print(my_sum(1, 2, 3))
def func(*args): # *args means for however many arguments you take in, # it will catch them all for arg in args: print(arg)
**kwargs (keyword arguments)
- to use two asterisks (
**) to unpack dictionaries
def concatenate(**kwargs):
result = ""
# Iterating over the Python kwargs dictionary
for arg in kwargs.values():
result += arg
return result
print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))
def capital_cities(**kwargs): # initialize an empty list to store the result result = [] for key, value in kwargs.items(): result.append("The capital city of {} is {} .format (key,value) return result
if __name__ == “__main__”:
if __name__ == “__main__”:
main program이냐 regular module에 따라 실행여부가 결정된다.
main program이면 실행되고,
regular module이면 실행 안된다.
따라서 템플릿으로 사용할려면 실행안되어야할 부분을 여기에 집어넣어두면 된다.
stackoverflow에 아주 잘 설명된 글이 있어 옮겨둔다.
What does if __name__ == “__main__”: do?
Whenever the Python interpreter reads a source file, it does two things:
- it sets a few special variables like
__name__, and then - it executes all of the code found in the file.
Let’s see how this works and how it relates to your question about the __name__ checks we always see in Python scripts.
Code Sample
Let’s use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py.
# Suppose this is foo.py.
print("before import")
import math
print("before functionA")
def functionA():
print("Function A")
print("before functionB")
def functionB():
print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")
if __name__ == '__main__':
functionA()
functionB()
print("after __name__ guard")
Special Variables
When the Python interpeter reads a source file, it first defines a few special variables. In this case, we care about the __name__ variable.
When Your Module Is the Main Program
If you are running your module (the source file) as the main program, e.g.
python foo.py
the interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.
# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"
When Your Module Is Imported By Another
On the other hand, suppose some other module is the main program and it imports your module. This means there’s a statement like this in the main program, or in some other module the main program imports:
# Suppose this is in some other main program.
import foo
The interpreter will search for your foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.
# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"
Executing the Module’s Code
After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.
Always
- It prints the string
"before import"(without quotes). - It loads the
mathmodule and assigns it to a variable calledmath. This is equivalent to replacingimport mathwith the following (note that__import__is a low-level function in Python that takes a string and triggers the actual import):
# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
- It prints the string
"before functionA". - It executes the
defblock, creating a function object, then assigning that function object to a variable calledfunctionA. - It prints the string
"before functionB". - It executes the second
defblock, creating another function object, then assigning it to a variable calledfunctionB. - It prints the string
"before __name__ guard".
Only When Your Module Is the Main Program
- If your module is the main program, then it will see that
__name__was indeed set to"__main__"and it calls the two functions, printing the strings"Function A"and"Function B 10.0".
Only When Your Module Is Imported by Another
- (instead) If your module is not the main program but was imported by another one, then
__name__will be"foo", not"__main__", and it’ll skip the body of theifstatement.
Always
- It will print the string
"after __name__ guard"in both situations.
Summary
In summary, here’s what’d be printed in the two cases:
# What gets printed if foo is the main program
before import
before functionA
before functionB
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before functionA
before functionB
before __name__ guard
after __name__ guard
Why Does It Work This Way?
You might naturally wonder why anybody would want this. Well, sometimes you want to write a .py file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:
- Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.
- Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing
.pyfiles like your script and running special test functions. You don’t want it to try running the script just because it’s importing the module. - Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.
Beyond those examples, it’s elegant that running a script in Python is just setting up a few magic variables and importing the script. “Running” the script is a side effect of importing the script’s module.
Food for Thought
- Question: Can I have multiple
__name__checking blocks? Answer: it’s strange to do so, but the language won’t stop you. - Suppose the following is in
foo2.py. What happens if you saypython foo2.pyon the command-line? Why?
# Suppose this is foo2.py.
def functionA():
print("a1")
from foo2 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
if __name__ == "__main__":
print("m1")
functionA()
print("m2")
print("t2")
- Now, figure out what will happen if you remove the
__name__check infoo3.py:
# Suppose this is foo3.py.
def functionA():
print("a1")
from foo3 import functionB
print("a2")
functionB()
print("a3")
def functionB():
print("b")
print("t1")
print("m1")
functionA()
print("m2")
print("t2")
- What will this do when used as a script? When imported as a module?
# Suppose this is in foo4.py
__name__ = "__main__"
def bar():
print("bar")
print("before __name__ guard")
if __name__ == "__main__":
bar()
print("after __name__ guard")
PyCharm 팁
Ctrl + 방향키 : 한단어 분량씩 옮겨감
Ctrl + Shift + 좌우방향키(<-, ->) : 한단어 분량씩 선택하며 옮겨감
Ctrl + Shift + 상하방향키 : 코드를 줄단위로 이동시킴
Refactor > Rename
프로젝트명, 파일명, 변수명을 바꿀때 마우스오른쪽버튼을 눌러 Refactor > Rename으로 바꾼다.


TODO comments


PyCharm에서 variables 확인하기
코드에 breakpoint를 설정후 debugging을 하면
아래 variable란에서 변수의 상태를 볼수 있다.

은행 인증서 자동로그인
pyautogui 를 이용하여 은행 자동 로그인하는 코드를 작성해봤다. 클릭할 부분의 그림파일을 미리 다 떠놔야된다.
코드 자체는 몇줄 되지도 않을뿐더러 알고리즘이 필요한 것도 아니지만 작성하는데 어려움이 있었다.
- 마우스클릭이 필요한 부분의 그림을 정확히 인식하지 못하여 여러번 시도해야했다. 조금만 달라도 인식하지 못하고 인식율을 낮추면 엉뚱한 곳을 클릭하기도 한다.
- 끝까지 구현하지 못한 부분은 인증서 입력이다. 구글링을 통해 다른 사람이 구현한 코드를 보면 인증서 입력창에 write()함수를 통해 입력할수 있다고하나, 직접 해보니 입력이 되지 않았다. 며칠동안 노력해봤으나 실패(아시는분 댓글 부탁드립니다.)
- 결국 인증서 입력은 마우스 클릭을 통한 인증서 입력으로 대신하여 구현하였다.
import subprocess
import time
import pyautogui
# 크롬 브라우저 열기
cmd = r”C:\Program Files (x86)\Google\Chrome\Application\chrome.exe”
# 우리은행 접속 (홈페이지에 접속하지 않고 바로 인증서 로그인화면으로 접속)
site = r”https://spib.wooribank.com/pib/Dream?withyou=CMLGN0001″
subprocess.Popen([cmd, site])
time.sleep(2)
pyautogui.hotkey(‘alt’, ‘space’)
time.sleep(1)
pyautogui.press(‘x’)
# pyautogui.hotkey(‘winleft’, ‘right’)
# 일정시간후 그림 중앙부 클릭
def click_on_screen(pic_name, interval=1, confi=.7, focus= 0):
time.sleep(interval)
pic = pyautogui.locateOnScreen(pic_name, grayscale=True, confidence=confi)
pic_center = pyautogui.center(pic)
pyautogui.click(pic_center[0]-focus, pic_center[1]+focus)
## 클릭한곳 스크린 저장(테스트 용)
# shot = pyautogui.screenshot(region=(pic[0], pic[1], pic[2], pic[3]))
# shot.save(“shot_” + pic_name)
# 이부분은 은행 첫 홈페이지에서 로그인할때 필요한부분임
# 그러나 웹페이지를 열때 로그인 화면으로 바로 접속하면 필요없는 화면임
# # 로그인 클릭
# click_on_screen(‘login.jpg’, 2, .5)
# # 로그인 개인 클릭
# click_on_screen(‘person.jpg’, 2, .7, 20)
# 공인인증서 로그인 클릭
click_on_screen(‘public_certificate.jpg’, 4, .7)
# 인증서입력 > 인증서위치 클릭
click_on_screen(‘usb.jpg’, 1, .7)
# USB선택
click_on_screen(‘usb_drive.jpg’, 1, .7)
# 해당 인증서 선택
click_on_screen(‘user.jpg’, 1, .7)
# 인증서 암호 입력창 선택
click_on_screen(‘pw.jpg’, 1, .7)
# pyautogui.write(“password”) # 이부분이 안됨.
# # 인증서 암호 마우스입력 선택
# click_on_screen(‘mouse.jpg’, 1, .7)
# # 페이지다운
# pyautogui.press(‘pagedown’)
# # 인증서 암호 입력
# click_on_screen(‘assword.jpg’, 1, .7)
# click_on_screen(‘enter.jpg’, 2, .7)
