728x90
import math
n=int(input()) 

def star(k):
    a=int(k/3)
    if k==6: 
        return ['  *  ',' * * ','*****']
    arr=star(k//2) 
    stars=[]
    for i in arr: 
        
        stars.append(' '*(3*(2**((int(math.log2(a)))-2)))+i+' '*(3*(2**((int(math.log2(a)))-2)))) 
    for i in arr:
        stars.append(i+' '+i) 
  
    return stars 
        


print("\n".join(star(n*2)))

 

후 마지막에 저 수식을 어케짤까 하다가 도저히 로그 쓰는거 말고는 생각이 안나서 math를 import해버렸다...

더 효율적인지 아닌지는 모르겠지만 일단 돌아는 감.

 

2447번 코드에서 살짝 수정만 한것. 

 

일단 알고리즘은 평범한 재귀함수임. 

어떤 함수냐면 일단 기본 베이스가 되는 삼각형을 만들고, 그 삼각형으로 프랙탈마냥 계속 만들어내는거

근데 만드는 과정에서 좀 수학적인게 필요했음 (수1 수열에 해당하는 부분인듯)

 

코드는 뭐 12넣어보고 24넣어보고 그러다보면 이해 가능할거고

 

중간에 몇번 에러떴는데 이유:

 

1. 공백 수를 정하는 코드를 짜야하는데, 6은 1, 12는 2, 24는 3 이런식으로 매칭시키는게 필요했음. 

무지성으로 다 6으로 나눴다가 24나누기 6을 3이 아니라 4라는걸 깨달음. 어쩐지 공백이 12더라 ㅅ발

 

2. log를 쓸때는 차피 int만 들어간다는걸 알아도 컴퓨터는 모르기 때문에 int형으로 바꿔줘야함. (당연하지만 실수함)

 

 

728x90
728x90
import math

T=int(input())

for i in range(T):
  x1,y1,r1,x2,y2,r2 = map(int,input().split())
  distance = math.sqrt((x1-x2)**2 + (y1-y2)**2)

  if distance==0 and r1==r2:
    print(-1)

  elif abs(r1-r2)==distance or r1+r2==distance:
    print(1)
  
  elif abs(r1-r2) < distance < (r1+r2) :  
        print(2)
  else:
      print(0)
728x90
728x90
n=int(input()) #n 값 입력. 3^a꼴로 될 예정

def star(k):
    if k==3: #프렉탈의 가장 기본이 되는 사각형
        return ['***','* *','***']
    arr=star(k//3) #3이 아니라면 3으로 나눈 값을 star에 넣고 그걸 arr에 넣음.
    stars=[]
    for i in arr: #만약 n이 9라면, arr에는 *이 들어있는 배열이 들어있을 예정. 배열 크기는 3.
        stars.append(i*3) #n이 9라면 i는 k==3일때 리턴되는 값
    for i in arr:
        stars.append(i+' '*(k//3)+i) #공백은 k//3크기만큼
    for i in arr:
        stars.append(i*3)
    return stars #배열임
        


print("\n".join(star(n)))

 

728x90
728x90
import sys

n=int(sys.stdin.readline())
ex=list(map(int, sys.stdin.readline().split()))
num=0;
have=0;
ans =[0 for i in range(n)]

for j in range(0,n):
  if(j==0):
    ans[j]=0

  else:
    for k in range(j-1,0,-1):
      if(ex[j]-ex[k]<=0):
        ans[j]=k+1
        have=1
        break
    if(have==0):
      ans[j]=0

print(*ans)

 

728x90

'언어는 과-학인가요? > python 파이썬' 카테고리의 다른 글

백준 1072 파이썬 - 게임  (0) 2022.07.27
백준 골드 (2447번) 파이썬 - 별찍기  (0) 2022.07.27
백준 2108  (0) 2022.07.26
백준 골드 (2981번) 파이썬  (0) 2022.07.26
백준 1단계 문제풀이  (0) 2022.07.04
728x90

어이없어서 올림. 

pypy3으론 잘돌아감.

python3 쓰면 시간초과남. 

 

from collections import Counter

N=int(input())
list=[]
ave=0
for i in range(N):
  list.append(int(input()))

list.sort()

for i in range(N):
  ave+=list[i]

print(round(ave/N))
mid=int((N-1)/2)
print(list[mid])

cnt_li = Counter(list).most_common()
if len(cnt_li) > 1 and cnt_li[0][1]==cnt_li[1][1]: #최빈값 2개 이상
    print(cnt_li[1][0])
else:
    print(cnt_li[0][0])


dif=max(list)-min(list)
print(dif)

 

시간초과 해결하려면 

 

input() 대신에 sys import 한다음에 int(sys.stdin.readline())쓰면 됨 

728x90
728x90

N = input()
list = []
M=[]
check=0
for x in range(int(N)):
  inp=int(input())
  list.append(inp)

for x in range(2,int(min(list))+1):
  for y in range(int(N)):
    ms=list[y]%(x)
    M.append(ms)
    a=M[0]
    b=M[y]
    if(a!=b):
      check=1
      break
      
  if(check!=1):
    print(x)

  M=[]
  check=0

 

(일단은 돌아가는 코든데 쓴게 아까워서 올리는 오답)

 

이건 오답이다. 

사실 이거 돌려봐도 답은 제대로 나온다. 

근데 왜 오답이냐고?

 

만약 이게 정답이였다면 문제가 골드일 리가 없겠지. 

시간초과가 뜬다. 

 

이유는 다음과 같다:

N이 1,000,000,000 보다 작거나 같은 수 이기에 일일히 나머지를 찾는 방식을 쓰면 컴퓨터가 좆된다ㅋㅋㅋㅋㅋㅋ

문제를 제대로 안읽은걸 반성하자. 

시발.

 


그래서 쓴 방법은 수학을 사용하는것이다. 

한국수학 수학 상에 나오는 내용을 그대로 사용해서 연립방정식을 풀면 답이 나온다 (이건 내 과외 말버릇)

마침 내 학생중 하나가 수학 상을 하니 이걸 숙제로 내줄까도 생각중임 

 

이렇게 연립방정식을 만들어서 나머지 R을 없애주고 M에 대한 식을 만듧

 

import math
N = int(input())
s = []
M = []
gcd = 0 #greatest commend divisor (최대공약수)
for i in range(N):
    s.append(int(input()))
    if i == 1:
        gcd = abs(s[1] - s[0])
    gcd = math.gcd(abs(s[i] - s[i - 1]), gcd)
gcd_last = int(gcd ** 0.5) #너무 많이 돌리면 시간초과뜸
for i in range(2, gcd_last + 1):
    if gcd % i == 0: #최대공약수가 어떤 수로 나눠졌을때 나머지가 0이 되면 그 어떤 수는 최대공약수의 약수가 된다 (즉 약수찾는 반복문임)
        M.append(i) 
        M.append(gcd // i) #최대공약수를 반갈죽해서 넣어주는거랑 동시에 하면 연산이 줄어듦 (gcd ** 0.5 최대공약수의 루트만큼만 계산하기 때문) 시간초과 방지
M.append(gcd) #당연히 최대공약수도 넣어줘야지
M = list(set(M)) #중복제거
M.sort() #정리함
for i in M:
    print(i, end = ' ')

 

자세한 설명은 생략한다. (위에 이미 다 주석으로 설명되있음)

728x90

'언어는 과-학인가요? > python 파이썬' 카테고리의 다른 글

백준 1072 파이썬 - 게임  (0) 2022.07.27
백준 골드 (2447번) 파이썬 - 별찍기  (0) 2022.07.27
백준 골드 (2493번) 파이썬  (0) 2022.07.27
백준 2108  (0) 2022.07.26
백준 1단계 문제풀이  (0) 2022.07.04
728x90

2557

print('Hello World!')

 

10718

print('강한친구 대한육군\n강한친구 대한육군')

 

10171

print('\\    /\\\n )  ( \')\n(  /  )\n \\(__)|')

역슬래쉬 (\) 와 따음표 (",') 앞에는 \를 붙여줍니다.

 

10172

print('|\\_/|\n|q p|   /}\n( 0 )\"\"\"\\\n|\"^\"`    |\n||_/=\\\\__|')

10171과 동일

 

1000

A,B=input().split()
print(int(A)+int(B))

.split()으로 A 와 B에 input 값을 나누어 넣는다

A와 B를 int형으로 바꿔 프린트한다

 

1001

A,B=input().split()
print(int(A)-int(B))

1000번과 동일 

int 형으로 바꾼 두 input값 사이에 부호만 바꿈.

 

10998

A,B=input().split()
print(int(A)*int(B))

1000번과 동일

 

1008

A,B=input().split()
print(int(A)/int(B))

1000번과 동일

 

10869

A,B=input().split()
print(int(A)+int(B))
print(int(A)-int(B))
print(int(A)*int(B))
print(int(int(A)/int(B)))
print(int(A)%int(B))

나누기 할때는 나누면 정수로 안나오는 경우도 있기에 int를 다시한번 더 붙여주는

 

10926

A=input()
print(A+'??!')

input형태를 안알려줘도 알아서 되는 갓이썬

 

18108

A=input()
print(int(A)-543)

꼭 형태를 int로 바꿔줍시다

 

10430

A,B,C=input().split()
A=int(A)
B=int(B)
C=int(C)
print((A+B)%C)
print(((A%C) + (B%C))%C)
print((A*B)%C)
print(((A%C)*(B%C))%C)

A, B, C를 인트로~

 

2588

A = int(input())
B = input()
for i in range(3, 0, -1) :
    print(A * int(B[i - 1]))
print(A * int(B))

A 는 정수니까 int형으로 받고, B는 그냥 문자열로 저장해 준다. 

문자열 (배열)은 이제 for반복문 안에 들어가서 2번째 배열부터 0번째 배열까지 순서대로 뽑힌다

그리고 마지막에 그냥 AB값 곱해준거 하면 끝

 

25083

print('         ,r\'\"7\nr`-_   ,\'  ,/\n \\. \". L_r\'\n   `~\\/\n      |\n      |')

10171과 동일

728x90
728x90

Client-server architecture

  • World Wide Web (WWW) uses the client-server architecture
    • Clients obtain service from a centralized server
    • Server waits for client requests and make response

The OSI network model

  • communication between clients and servers can be seen in multiple layers
    • Abstraction è reducing complexity of problems to smaller ones
    • Division of labour

THE OSI NETWORK MODEL

 

Communication protocols

  • Clear definition of steps is needed for two computers to communicate
    • rules
    • syntax
    • semantics
    • synchronization of communication
    • error recovery methods
  • There are protocols for every layer in the networking model
  • The internet engineering Task force (IETF) develops and promotes voluntary internet standards

MAC and IP addresses

  • Mac address (layer2): locating a piece of communication device on a local network
  • IP address(layer3): identifying a network interface in networks
    • IPv4 (32-bit) vs IPv6 (128-bit)
    • Public addresses vs private addresses
      • Private addresses limit datagrams to be sent within local network only
      • e.g., 192.168.1.123 is only meaningful within a local network
  • The ARP table on a device maintains the correspondence between MAC addresses and IP addresses within a local network

TCP VS UDP

  • Layer 4 protocols: ensuring reliability of data transmission
  • Transmission control protocols (TCP)
    • Handshakes to establish a connection
    • Built in system to check for errors
    • Guarantee for data order and completeness
    • Good for HTTPSs, HTTP etc. 
  • User Datagram Protocols (UDP_
    • connectionless -> reducing the overhead of computation (time)
    • Extensive error checking and recovery not required
    • Good for: video conferencing, media streaming etc

Communicating over ports 

  • In networking, connections are made on ports of a network device
  • Each port is "listen to" served by one piece of software server
  • Well known ports: 0-1023 (Http:80, Https:443)
  • Registered ports: 1024-49151
  • Private ports:49152-65535

Socket

  • In network programming, a network socket is an endpoint for communication
  • socket=transport protocol+IP address+port number
  • Implementation depends on the programming language/environment

Localhost

  • It is also possible to have both ends of communication only on one computer
    • Although it is in the same computer, this way allows communication to still go through network layers in the OS
  • Usually identified in the computer as "localhost" or 127.0.0.1

Hypertext transfer protocol

  • HTTP - hypertext transfer protocol
  • Communication is initiated by a client 
    • a client sends a HTTP request to a server
    • the server returns a HTTP response to the client 
  • It is stateless
    • every request is treated as an independent request
    • the protocol itself does not offer any means to relate two separate request
  • HTTP/1.1 — 1997, HTTP/2 — 2015, HTTP/3 — expired draft (2020)

 

HTTP clients 

  • Web client (“user-agent”): a software communicating with the web server over HTTP or HTTPS
    • web browsers: for end-user experience
      • html/css rendering
      • js execution
      • web technologies
    • web crawlers/ search engines
    • programmatic interfaces

HTTP servers

  • Web server: handling requests for web documents with http/https, supporting server-side scripts
    • apache (was still the first last yr!)
    • nginx
    • Microsoft ISS
    • node.js
  • Web caching
    • forward/reverse proxies
    • Content delivery networks(CDN)

 

728x90

'언어는 과-학인가요? > 전반적인 web development (html css JS )' 카테고리의 다른 글

HTML 에 CSS파일 연결하는법  (0) 2022.11.15
HTML Article 과 Section의 차이  (0) 2022.11.15
Web security  (0) 2022.03.03
CSS로 form 만들기  (0) 2022.01.19
유용한 CSS들  (0) 2022.01.14
728x90

Cyber security

  • Application security
    • Assets at the software level
    • Database, document
  • Network security
    • The infrastructure of network level
    • Connection, hardware

Important terms

  • Validation
    • to check if something is valid or existing
  • Varification
    • To check if something is real
  • Autohentication
    • To verify a user with credentials as the correct person
  • Authorization
    • To determine the permission on what a user can access.

 

To 10 of OWASP (open web application security project)

• Top 10 Web Application Security Risks (2021) • See more: https://owasp.org/Top10/

1. Broken access control

2. Cryptographic failures

3. Injection

4. Insecure design

5. Security misconfiguration

6. Vulnerable and outdated components

7. Identification and authentication failures

8. Software and data integrity failures

9. Security logging and monitoring failures

10. Server-side request forgery

 

Common Access Control Vulnerabilities

  • Access granted to more than necessary capabilities, roles, or users 
  • Bypassing access control checks possible with URL modificaiton
  • Permitting access to someone else's account with unique identifier
  • Metabeta manipulation with cookies or security tokens
  • CORS misconfiguration giving rise to access from unauthorized orgins.

 

Bad implementation

  • There may be carelessness or ignorance of threats
    • including sensitive data in URL
    • password not encrypted in storage or transit
    • Storing credentials in public code responsitories
    • permitting brute force attacks
    • running application in development debug mode for production
    • session timeout unhandled
    • missing access control to functions
    • using components with known vulnerabilities
  • Using security frameworks(misconfig) instead might be helpful!
    • test the application thoroughly and rigorously

 

Mitigation to attacks (어떻게 완화하냐)

  • Plan carefully for authentication and authorization
  • combination of multiple layers of security measures
  • sanitize all untrusted data
    • All user input should be considered untrusted (do not trust all users!), and should go through:
      • Validation: sting format expected?
      • Escaping: special characters (<,>) can inject HTML code. change to &lt or &gt 
      • Sanitization: if needed, only allow certain code in a whitelist.
  • Enforce same-site requirements
    • Allow cross-site only if needed, with only minimal possibilities

 

Https (web security)

  • By design, HTTP transfers everything in plain text
  • HTTP secure is an extension to http
    • Authentication:
    • Encryption:
  • Transport layer security(TLS)
    • private connection with symmetric cryptography
      • a key is used for encryption of plain text and decryption of ciphertext
      • a unique session key is generated at the beginning of each connection during the handshake

 

 

Certificates

  • to verify identity, signed by a certificate authority(CA)
  • Server certificates
    • Domain verification: only prove that domain is owned by a certain person (who.is 들어가면됨)
    • Organization Verification: company name and public address
    • Extended Verification: existence and location of a legal entity
  • Browsers and OSes maintain a trusted list of CAs
    • If a cert is issued by these CAs, the cert is trusted

DDOS

  • Distributed Denial-of-service attack
    • Exhausting the resources of the target, ex)consuming all the available bandwidth, or computation power
    • Distributed: not a single source of attack, usually using botnets
  • Layer 7 DDOS
    • Flooding with application requests (ex, HTTP)
    • 전체 네크워크가 아닌 특정 웹 어플리케이션만 공격해서 마비시킴

Cloud solution for DDOS

  • Distributed and intelligent system to mitigate attacks (ex) are you human?)

 

 

728x90

'언어는 과-학인가요? > 전반적인 web development (html css JS )' 카테고리의 다른 글

HTML Article 과 Section의 차이  (0) 2022.11.15
SERVER, CLIENT, and HTTP  (0) 2022.03.09
CSS로 form 만들기  (0) 2022.01.19
유용한 CSS들  (0) 2022.01.14
CSS 쓰는법  (0) 2022.01.13
728x90

Data types in JAVA

이걸 다시 복습해보자. 일단 int, double, char을 제일 많이쓸거니까 heighlight 쳐놓을게

type description range
boolean true or flase true, false
byte twos-complement integer -128 to 127
char  Unicode character ASCII value 0 to 255
short twos-complement integer  -32768 to 32767
int twos-complement integer  -2147483648 to 2147483647
long twos-complement integer  -9223372036854755808 to 922337203685475587
float IEEE 754 floating point up to 7 decimal digits
double IEEE 754 floating point up to 16 decimal digits

 

Integer overflow 

 

Number conversion

class Main {
    public static void main(String[] args) {
        int big;
        byte small;

        big = 10;
        small = big;

        System.out.println(big);
        System.out.println(small);
    }
}

이렇게 하면 compile error 남. 왜? big(int) 에 들어가있는 value가 small(byte)에 들어가려고하면 에러나지. C면 돌아가기라도 할텐데 자바는 바로 에러난다는걸 보여주는 예시. 

 

+number conversion 예시:

 

3.75를 integer 로 바꾸면 3이 나온다. 이걸 다시 floatfh 바꾸면 3.0이 나온다. 즉 3.75를 int에 넣으면 3이되는거임. 0.75 순삭됨



Character type: Char

char c;

c='a';

Single quotation mark 으로 c 에 character를 넣으면 됨. 

ASCII table 에서 character 0랑 integer 0 는 다르다. 

보셈 character 0은 48에 있음. 

 

Relational Operators

>,< 이런걸 뜻한다. 

근데 여기 룰이 있는데,

Rule #1. The two inputs must be numbers, not necessarily of the same type.

Rule #2. If the two inputs are numbers with different types, the inferior one will be upgraded automatically.

 

relational operator를 사용한 코드:


class Main {
    public static void main(String[] args) {
        double UV_level = 12;
        boolean UV_danger;

        UV_danger = (UV_level > 10);

        // warn the user
        System.out.println("UV Danger: " + UV_danger);
    }
}

자 이 코드를 분석하자면, UV_danger라는 이름을 가진 boolean 변수는 0또는 1이다. boolean 이니까.

그니까 UV_danger는 UV_level이 10보다 클시에 true 인 1, 크지 않을시에 false 인 0이 되는거다. 

지금같은 케이스는 UV_level에 12이고, 10보다 크니까 true 인 1이 UV_danger에 들어갈것이당

 

이러한 operator가 있다. 

== 랑 =는 다르다. =는 assignment operator고 ==는 equality operator다. 

쉽게말하면 =는 걍 값 넣는거고 ==는 같다는뜻.

 

Boolean (or logical) operator

걍 true 냐 false냐 따지는 operator 말하는거다. 

 

 이처럼 !나 &&따위의 operator 를 말한다. 

 

&&(and라는뜻) 는 걍 

condition a && condition b 가 있다면, 

a랑 b 둘다 true 일 시에 true가 나오는거고

두게중 하나라도 false거나 둘다 false면 걍 가차없이 false 나오는거지. 

마치 하나라도 틀리면 0점주는 문제처럼

 

||(or라는뜻) 은 뭐냐면

condition a || condition b 이렇게 있으면 

둘다 false 가 아닌이상 다 true로 나온다. or이니까 둘중에 하나라도 true가 있으면 true인거지. 

 

Operator Precedence & Associativity

자 이런식으로! 뭐가 더 중요하냐 이거임. 지금 저기에선 10>=4+10&&4+6==10이 있으면, (10>=4+10)랑 (4+6==10)를 비교해서 둘다 true이냐를 따지는건데, 일단 첫번째 condition 인 10>=4+10 부터가 false니까 가차없이 false 나오는거지.

 

그래서 결괴는 false. 

 

728x90

'언어는 과-학인가요? > JAVA' 카테고리의 다른 글

1. Java Language Basics  (0) 2022.01.16
JAVA 깔고 쓰는법  (0) 2022.01.15

+ Recent posts