코드 

설명 

\n

문자열 안에서 줄을 바꿀 때 사용 

\t 

문자열 사이에 탭 간격을 줄 때 사용 

\\ 

문자 \를 그대로 표현할 때 사용 

\' 

작은 따옴표(')를 그대로 표현할 때 사용 

\" 

큰 따옴표(")를 그대로 표현할 때 사용 



from collections import deque


# 지하철역 클래스

class Station:

    def __init__(self, name):

        self.name = name

        self.neighbors = []


    def add_connection(self, another_station):

        self.neighbors.append(another_station)

        another_station.neighbors.append(self)



# Breadth-First Search 알고리즘

def bfs(start, goal):

    # 변수 정의

    previous = {}

    queue = deque()

    current = None


    # 초기 설정

    previous[start] = None

    queue.append(start)


    # 탐색

    while len(queue) > 0 and current != goal:

        current = queue.popleft()


        for neighbor in current.neighbors:

            if neighbor not in previous.keys():

                queue.append(neighbor)

                previous[neighbor] = current


    # 길이 있으면 경로를 만들어서 리턴

    if current == goal:

        path = [goal]

        x = goal


        while previous[x] != None:

            x = previous[x]

            path.append(x)


        return path


    # 길이 없으면 None 리턴

    return None



# 파일 읽기

stations = {}

in_file = open('stations.txt')


for line in in_file:

    previous_station = None

    data = line.strip().split("-")


    for name in data:

        station_name = name.strip()

        if station_name not in stations.keys():

            current_station = Station(station_name)

            stations[station_name] = current_station

        else:

            current_station = stations[station_name]


        if previous_station != None:

            current_station.add_connection(previous_station)


        previous_station = current_station


in_file.close()



# 테스트

start_name = "이태원"

goal_name = "잠원"


start = stations[start_name]

goal = stations[goal_name]


path = bfs(start, goal)

for station in path:

    print(station.name)


대칭되는 단어 = 팔린드롬 여부 확인하기 (ex. stars, 토마토...)


def is_palindrome(word):

for left in range(len(word) // 2):

# 한 쌍이라도 일치하지 않으면 바로 False를 리턴하고 함수를 끝냄

right = len(word) - left - 1

if word[left] != word[right]:

return False


#for 문에서 나왔다면 모든 쌍이 일치

return True


print(is_palindrome("racecar"))

print(is_palindrome("stars"))

print(is_palindrome("토마토"))

print(is_palindrome("hello"))

주민등록번호 끝 4자리를 *로 마스킹하는 코드


문자열은 immutable하기 때문에 mutable한 리스트로 만드는 것이 핵심


def mask_security_number(security_number):

#security_number를 리스트로 변환            

num_list = []

for i in range(len(security_number)):

num_list.append(security_number[i])


#더 좋은 코드 - 문자열을 한 번에 리스트로 바꾸는 형 변환

def mask_security_number(security_number):

num_list = list(security_number)


# 마지막 네 값을 * 로 대체

for i in range(len(num_list) - 4, len(num_list)):

num_list[i] = "*"


# 리스트를 문자열로 복구

total_str = ""

for i in range(len(num_list)):

total_str += num_list[i[


return total_str




def mask_security_number(security_number):

# security_number를 리스트로 변환

num_list = list(security_number)


# 마지막 네 값을 * 로 대체

for i in range(len(num_list) - 4, len(num_list)):

num_list[i] = "*"


# 리스트를 문자열로 복구

total_str = "".join(num_list)


return total_str




def mask_security number(security_number):

return security_number[:len(security_number) - 4] + "****"

num을 파라미터로 받는 함수 sum_digit 정의하기


# 자리수

def sum_digit(num):

str_num = str(num)

sum_digit = 0


# 각 자리수를 sum_digit에 추가

for digit in str_num:

sum digit = sum_digit + int(digit)

return sum_digit


# sum_digit(1) 부터 sum_digit(1000)까지의 합 구하기

total = 0

for i in range(1, 1001):

total = total + sum_digit(i)

print(total)



reverse / insert / append 메소드 와 del 함수 등을 이용하지 않고 리스트를 뒤집기


numbers = [2, 4, 6, 8, 10, 12, 14]


for i in range(4):

temp = numbers[i]

numbers[i] = numbers[6 - i]

numbers[6 - i] = temp


print("뒤집어진 리스트 : " + str(numbers))




a < b < c일때, a + b+ c = 1000 을 만족하는 피타고라수 수 (a, b ,c)의 곱을 구하라


for a in range(1, 1001):

    for b in range(1, 1001):

        c = 1000 - a - b

        if a * a + b * b == c * c and a < b < c:

            print(a * b * c)


# 효율적인 코드

for a in range(1, 333):

for b in range(a + 1, 500):

c = 1000 - a - b

if a ** 2 + b ** 2 == c ** 2:

print(a * b * c)

for i in range(1, 10):

    for j in range(1, 10):

        print("%d * %d = %d" % (i, j, i * j))

for i in range(11):

    print("2^%d = %d" % (i, 2 ** i))

numbers = [2, 3, 5, 7, 11, 13, 17, 19]


for values in range(len(numbers)):

print(values, numbers[values]

#print("%d %d" % (values, numbers[values]))


리스트에서 값의 존재 확인하기


# value가 some_list의 요소인지 확인

def in_list(some_list, value):

    i = 0

    while i < len(some_list):

        # some_list에서 value를 찾으면 True를 리턴

        if some_list[i] == value:

            return True

        i = i + 1


    # 만약 some_list에서 value를 발견하지 못했으면 False를 리턴

    return False


# 테스트

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]

print(in_list(primes, 7))

print(in_list(primes, 12))


in 활용 / not in

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]

print(7 in primes)

print(12 in primes)


리스트 안의 리스트 (Nested List)


# 세 번의 시험을 보는 수업

grades = [[62, 75, 77], [78, 81, 86], [85, 91, 89]]


# 첫 번째 학생의 성적

print(grades[0])


# 세 번째 학생의 성적

print(grades[2])


# 첫 번째 학생의 첫 번째 시험 성적

print(grades[0][0])


# 세 번째 학생의 두 번째 시험 성적

print(grades[2][1])


# 첫 번째 시험의 평균

print((grades[0][0] + grades[1][0] + grades[2][0]) / 3)


메소드

sort - some_list.sort() : 새로운 리스트를 생성하지 않고 some_list를 정렬 상태로 바꿔줌

reverse - some_list.reverse() : 원소들을 뒤집어진 상태로 배열

index - some_list.index(x) : some_list 에서 x의 값을 갖고 있는 원소의 인덱스를 리턴

remove - some_list.remove(x) : some_list에서 첫 번쨰로 x의 값을 갖고 있는 원소를 삭제

# 빈 리스트 만들기

numbers = []


# numbers에 자연수 1부터 10까지 추가

i = 1

while i <= 10:

    numbers.append(i)

    i = i + 1

print(numbers)


# numbers에서 홀수 제거

i = len(numbers) - 1

while i>= 0:

    if numbers[i] % 2 == 1:

        del numbers[i]

    i = i - 1

print(numbers)


# numbers의 인덱스 0 자리에 20이라는 값 삽입

numbers.insert(0, 20)

print(numbers)


# numbers를 정렬해서 출력

print(sorted(numbers))


# 다른 코드


numbers = []


i = 1


while i <= 10:

    numbers.append(i)

    i = i + 1


print(numbers)


j = 0


while j < len(numbers):

    if numbers[j] % 2 != 0:

        del numbers[j]

    else:

        j = j + 1

print(numbers)


numbers.insert(0, 20)

print(numbers)


numbers = sorted(numbers)

print(numbers)

# 원화 > 달러 > 엔화로 리스트를 변경하는 예제


def krw_to_usd(won):

    return won / 1000

def usd_to_jpy(dollar):

    return dollar * 125


i = 0


amounts = [1000, 2000, 3000, 5000, 8000, 13000, 21000, 34000]

print("한국 화폐: " + str(amounts))


while i < len(amounts): 

    amounts[i] = round(krw_to_usd(amounts[i]), 1)

    i = i + 1

    

print("미국 화폐: " + str(amounts))


i = 0


while i < len(amounts):

    amounts[i] = round(usd_to_jpy(amounts[i]), 1)

    i = i + 1


print("일본 화폐: " + str(amounts))


# 결과값

한국 화폐: [1000, 2000, 3000, 5000, 8000, 13000, 21000, 34000]

미국 화폐: [1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 21.0, 34.0]

일본 화폐: [125.0, 250.0, 375.0, 625.0, 1000.0, 1625.0, 2625.0, 4250.0]

i = 0


def fahrenheit_to_celsius(fahrenheit):

    return (fahrenheit - 32) * 5 / 9


fahrenheit_temperatures = [40, 15, 32, 64, -4, 11]


print("화씨 온도 리스트: " + str(fahrenheit_temperatures))


while i < len(fahrenheit_temperatures):

    fahrenheit_temperatures[i] = round(fahrenheit_to_celsius(fahrenheit_temperatures[i]), 2)

    i = i + 1

    

print("섭씨 온도 리스트: " + str(fahrenheit_temperatures))

원소 갯수 세기

- len 함수


alphabet = ["a", "b", "c", "d"]

print("리스트의 길이는 : %d % len(alphabet))


원소 추가하기

- insert 함수와 append 함수를 통해서 리스트에 원소 추가 가능


numbers = []


# 마지막 위치에 5 추가

numbers.append(5)

print(numbers)


# 마지막 위치에 8 추가

numbers.append(8)

print(numbers)


# 마지막 위치에 10 추가

numbers.append(10)

print(numbers)


# 인덱스 0 자리에 0 추가

numbers.insert(0, 0)

print(numbers)


# 인덱스 3 자리에 12 추가

numbers.insert(3, 12)

print(numbers)


원소 빼기

- del 함수


numbers = [1, 2, 3, 4, 5, 6]


# 인덱스 3에 있는 값 삭제

del numbers[3]

print(numbers)


# 인덱스 4부터 마지막 값까지 삭제

del numbers[4:]

print(numbers)



원소 정렬하기

- sorted 함수 : 리스트의 원소들을 오름차순으로 정렬한 새로운 리스트를 리턴


numbers = [8, 6, 9, 1, 2, 4, 7, 5, 3]

numbers = sorted(numbers)


print(numbers)


리스트 연결하기

- 리스트들을 +로 연결하기


alphabet1 = ["a", "b", "c"]

alphabet2 = ["d", "e", "f"]

alphabet = alphabet1 + alphabet2


print(alphabet)

def hello():


greetings = ["안녕", "니하오", "곤니찌와", "올라", "싸와디캅", "헬로", "봉주르"]

i = 0


while i < len(greetings): # len은 리스트의 길이를 리턴해주는 함수

    print(greetings[i])

    i = i + 1


hello()


from random import randint


count = 1

number = randint(1, 20)


while count <= 4:

   

    notification = int(input("기회가 %d번 남았습니다. 1 - 20 사이의 숫자를 맞춰보세요:" % (5 - count)))

   

    if notification < number:

        print("UP")

    elif number < notification:

        print("DOWN")

        

    else:

        print("축하합니다. %d번만에 숫자를 맞추셨습니다." % (count))

        break

    

    count = count + 1

    

    if 4 < count:

        print("아쉽습니다. 정답은 %d였습니다." % (number))



# 다른 코드


from random import randint


# 상수

NUM_TRIES = 4

ANSWER = randint(1, 20)


# 변수

tries = 0

guess = -1


# 시도가 남았고 아직 답을 못 맞췄을 경우

while tries < NUM_TRIES and guess != ANSWER

#guess는 처음에 -1이고 ANSWER는 1과 20사이기 때문에, 처음에 무조건 True

    guess = int(input("기회가 %d번 남았습니다. 1 - 20 사이의 숫자를 맞춰보세요: " % (NUM_TRIES - tries)))

    tries = tries + 1

    

    if guess < ANSWER:

        print("Up")

    elif guess > ANSWER:

        print("Down")


if guess == ANSWER:

    print("축하합니다. %d번만에 숫자를 맞추셨습니다." % (tries))

else:

    print("아쉽습니다. 정답은 %였습니다." % (ANSWER))

name = input("이름을 입력하세요: ") #괄호 안은 입력 창에 뜨는 안내 문구


#만약 콘솔 창에서 YOUR_NAME을 입력하면

print("Hello " + name)


#print("Hello " + name)의 결과는 Hello YOUR_NAME이 된다



input으로 정수나 소수 입력을 하려면


x = int(input("첫 번째 정수: "))

y = int(input("두 번째 정수: "))

print("두 정수의 합: %d" % (x + y))



'Python > 문법정리' 카테고리의 다른 글

[리스트] 리스트 종합  (0) 2017.08.13
[리스트] 함수  (0) 2017.08.13
[랜덤함수] randint 함수와 uniform 함수  (0) 2017.08.13
[모듈] 파일 생성 & import  (0) 2017.08.13
[제곱수 구하기] pow(x, n)  (0) 2017.08.13

radint - 두 정수 사이의 랜덤한 정수를 리턴시켜주는 함수

파이썬에 기본적으로 깔려있는 random 모듈에 정의되어 있다.


from random import randint


# a <= N <= b인 랜덤한 정수 N의 값을 리턴

randint(a, b)


x = randint(1, 20)

print(x)


uniform - random 모듈 안에 정의되어 있는 두 수 사이의 랜덤한 소수를 리턴시켜주는 함수


from random import uniform


x = uniform(0, 1)

print(x)

'Python > 문법정리' 카테고리의 다른 글

[리스트] 함수  (0) 2017.08.13
[input] 유저에게 입력을 받기 위한 내장함수  (0) 2017.08.13
[모듈] 파일 생성 & import  (0) 2017.08.13
[제곱수 구하기] pow(x, n)  (0) 2017.08.13
[조건문] if / elif / else  (0) 2017.08.12

모듈?

변수, 함수, 클래스 등을 모아 놓은 파일. 모듈에 함수나 정보등을 정의해두고 가져다 쓰는 식



calculator.py 파일 생성


#합

def sum(x, y):

return x + y


# 차이

def difference(x, y):

return x + y


# 곱

def product(x, y):

return x * y


# 제곱

def square(x):

return x * x



이후 이 모듈을 쓸 파이썬 문서에서


from calculaotr import sum, square #difference, product도 가능, from calculator import * < 전부 임포트할 경우


print(sum(3, 5)) # 이런식으로 불러 쓸 수 있다.


+ Recent posts