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))




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 = []


# 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))

def hello():


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

i = 0


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

    print(greetings[i])

    i = i + 1


hello()


i = 1

j = 1


while i <= 9:

    j = 1

    while j <= 9:

        sol = i * j

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

        j = j + 1

    i = i + 1

def fibonacci(number):

    previous = 0

    current = 1

    i = 1

    

    while i <= number:

        print(current)

        temp = previous                 #temp는 임시저장 공간

        previous = current

        current = current + temp

        i = i + 1 #i += i

        

fibonacci(20)        

        

def calculate(number):

i = 1

count = 0

while i <= number:

if number % i == 0:

print(i)

count = count + 1

i = i + 1

print("%d의 약수는 총 %d개입니다" % (number, count))

#print(str(number) + "의 약수는 총 " + str(count) + "개입니다.")


calculate(120)

calculate(240)


100이하의 8의 배수이지만 12의 배수는 아닌 숫자를 출력하라



i = 1

while i <= 100:

if i % 8 == 0 and i % 12 != 0:

print(i)

i = i + 1




def notify_grade(midterm, finalterm): #함수 정의

    score = midterm + finalterm # 점수는 중간 + 기말

    if 90 <= score:

        print("A학점입니다.") # 90점 이상 A학점

    elif 80 <= score:

        print("B학점입니다.") # 80점 이상 90점 미만 B학점

    elif 70 <= score:

        print("C학점입니다.") # 70점 이상 80점 미만 C학점

    elif 60 <= score:

        print("D학점입니다.") # 60점 이상 70점 미만 D학점

    else:

        print("낙제입니다.")   # 60점 미만 낙제


notify_grade(100,20) # A학점

notify_grade(40,23)  # D학점

notify_grade(80,80)  # A학점

def even_or_odd(number):

return number & 2 == 0


print(even_or_odd(3)) #결과값 False

print(even_or_odd(4)) #결과값 true

#돈을 냈을 때, 5만원, 1만원, 5천원, 1천원의 지폐의 합이 최소가 되도록 거스름돈을 알려주는 예제

#payment=내가 내는 돈, cost=상품의 가격


#함수 정의

def calculate_change(payment, cost):

change = payment - cost

fifty_thousand = int(change / 50000)


change = change % 50000

ten_thousand = int(change / 10000)


change = change % 10000

five_thousand = int(change / 5000)


change = change % 5000

one_thousand = int(change / 1000)


print("거스름돈은 다음과 같습니다")

print() #공백

print("50000원짜리 지폐 : " + str(fifty_thousand) + "장")

print("10000원짜리 지폐 : " + str(ten_thousand) + "장")

print("5000원짜리 지폐 : " + str(five_thousand) + "장")

print("1000원짜리 지폐 : " + str(one_thousand )+ "장")


#100,000원을 내고 54,000원짜리 상품을 구매할 때 받는 거스름돈

calculate_change(100000, 54000)


#다른 방법으로 함수 정의하기

def calculate_change(payment, cost):

change_money = payment - cost
fifty_thousands = change_money//50000
ten_thousands = (change_money - fifty_thousands*50000)//10000
five_thousands = (change_money - fifty_thousands*50000 - ten_thousands*10000)//5000
thousands = (change_money - fifty_thousands*50000 - ten_thousands*10000 - five_thousands*5000)//1000

print("50000원 지폐: " + str(fifty_thousands) + "장")
print("10000원 지폐: " + str(ten_thousands) + "장")
print("5000원 지폐: " + str(five_thousands) + "장")
print("1000원 지폐: " + str(thousands) + "장")






+ Recent posts