5.python을 이용한 알고리즘 문제(91~120)

53 minute read

91. 석차 출력[문제]

# ex96_문제.py

# 석차 출력
# 성적 순으로 이름 출력


name = ["홍길동", "김영", "자바킹", "민병철", "메가맨"]
scores = [87, 42, 100, 11, 98]

정답

# ex96_정답.py

# 석차 출력
# 성적 순으로 이름 출력


name = ["홍길동", "김영", "자바킹", "민병철", "메가맨"]
scores = [87, 42, 100, 11, 98]

size = len(name)

i = 0
while i < size:
    max_score = scores[i]
    max_idx = i

    j = i
    while j < size:
        if max_score < scores[j]:
            max_score = scores[j]
            max_idx = j
        j = j + 1

    temp = scores[i]
    scores[i] = scores[max_idx]
    scores[max_idx] = temp

    temp = name[i]
    name[i] = name[max_idx]
    name[max_idx] = temp

    i = i + 1

print(scores)
print(name)

92. 리스트 컨트롤러(2단계)[문제] : 함수 적용

# ex98_문제.py

# 리스트 컨트롤러[2단계] : 함수 적용시
# 1. 추가
# . 값을 입력받아 순차적으로 추가
# 2. 삭제(인덱스)
# . 인덱스를 입력받아 해당 위치의 값 삭제
# 3. 삭제(값)
# . 값을 입력받아 삭제
# . 없는 값 입력 시 예외처리
# 4. 삽입
# . 인덱스와 값을 입력받아 삽입

score = []

while True:
    print("[리스트 컨트롤러]")
    print("[1]추가")
    print("[2]삭제(인덱스)")
    print("[3]삭제(값)")
    print("[4]삽입")
    print("[0]종료")

    choice = int(input("메뉴 선택 : "))
    if choice == 1:
        pass
    elif choice == 2:
        pass
    elif choice == 3:
        pass
    elif choice == 4:
        pass
    elif choice == 0:
        print("프로그램 종료")
        break

정답

# ex98_정답.py

# 리스트 컨트롤러[2단계] : 함수 적용시
# 1. 추가
# . 값을 입력받아 순차적으로 추가
# 2. 삭제(인덱스)
# . 인덱스를 입력받아 해당 위치의 값 삭제
# 3. 삭제(값)
# . 값을 입력받아 삭제
# . 없는 값 입력 시 예외처리
# 4. 삽입
# . 인덱스와 값을 입력받아 삽입

score = []

while True:
    print(score)

    print("[리스트 컨트롤러]")
    print("[1]추가")
    print("[2]삭제(인덱스)")
    print("[3]삭제(값)")
    print("[4]삽입")
    print("[0]종료")

    choice = int(input("메뉴 선택 : "))
    if choice == 1:
        my_score = int(input("[추가]성적 입력 : "))
        score.append(my_score)
    elif choice == 2:
        del_idx = int(input("[삭제]인덱스 입력 : "))
        del score[del_idx]
    elif choice == 3:
        del_value = int(input("[삭제]값 입력 : "))
        score.remove(del_value)
    elif choice == 4:
        insert_idx = int(input("[삽입]인덱스 입력 : "))
        insert_value = int(input("[삽입]값 입력 : "))
        score.insert(insert_idx, insert_value)
    elif choice == 0:
        print("프로그램 종료")
        break

주의사항 및 Tip

기존의 리스트컨트롤러(1단계)와 다른점이라고 하면, 1단계는 scores가 빈 배열이 아닌 이미 있는 배열(scores=[10,20,0,0,0])이라 값들을 넣고 지우는데 위치의 이동을 하면 되었지만, 이 문제의 배열은(scores=[])인 빈 배열이라는점을 주목해야한다.

이미 있는 배열(scores=[10,20,0,0,0])에 함수(append 등)을 적용시킬경우 append같은경우 0에 채워지는것이 아닌 추가가 되어 다음과 같은 모습이 나오게 된다

scores.append(30) ==> scores=[10,20,30,0,0] (X)

scores.append(30) ==> scores=[10,20,0,0,0,30] (O)

93. 리스트 컨트롤러(2단계)[문제] : 함수 X [다시,삽입 코드 다시보기]

# ex99_문제.py


# 리스트 컨트롤러[2단계] : 함수 적용시
# 1. 추가
# . 값을 입력받아 순차적으로 추가
# 2. 삭제(인덱스)
# . 인덱스를 입력받아 해당 위치의 값 삭제
# 3. 삭제(값)
# . 값을 입력받아 삭제
# . 없는 값 입력 시 예외처리
# 4. 삽입
# . 인덱스와 값을 입력받아 삽입

score = []
count = 0

while True:
    print(score)

    print("[리스트 컨트롤러]")
    print("[1]추가")
    print("[2]삭제(인덱스)")
    print("[3]삭제(값)")
    print("[4]삽입")
    print("[0]종료")

    choice = int(input("메뉴 선택 : "))
    if choice == 1:
        pass
    elif choice == 2:
        pass
    elif choice == 3:
        pass
    elif choice == 4:
        pass
    elif choice == 0:
        print("프로그램 종료")
        break

정답

# ex99_문제.py

# 리스트 컨트롤러[2단계] : 함수 적용시
# 1. 추가
# . 값을 입력받아 순차적으로 추가
# 2. 삭제(인덱스)
# . 인덱스를 입력받아 해당 위치의 값 삭제
# 3. 삭제(값)
# . 값을 입력받아 삭제
# . 없는 값 입력 시 예외처리
# 4. 삽입
# . 인덱스와 값을 입력받아 삽입

score = []
count = 0

while True:
    print(score)

    print("[리스트 컨트롤러]")
    print("[1]추가")
    print("[2]삭제(인덱스)")
    print("[3]삭제(값)")
    print("[4]삽입")
    print("[0]종료")

    choice = int(input("메뉴 선택 : "))
    if choice == 1:

        num = int(input("값을 입력해주세요"))

        if count == 0 :

            score = [0]

        elif count > 0 :

            temp = score

            score = [0 for i in range(count+1)]

            i = 0

            while i < count :

                score[i] = temp[i]

                i+=1

        score[count] = num
        count+=1

    elif choice == 2:

         del_idx = int(input("[삭제]인덱스 입력 : "))


         if count <= del_idx or del_idx < 0:
            print("[메세지]해당 위치 값은 삭제할 수 없습니다.")
            continue

         if count == 1:

             score = []

         elif count > 1 :

             temp = score

             score = [0 for i in range(count-1)]

             i = 0
             j = 0
             while i < count :

                if i != del_idx :

                    score[j] = temp[i]
                    j+=1

                i+=1

         count-=1


    elif choice == 3:

        del_score = int(input("[삭제]점수 입력 : "))



        if count == 1:

            score=[]

        elif count > 1 :

            #점수가 있는지 확인

            i = 0
            index = -1
            while i < count :

                if del_score == score[i]:

                    index = i

                i+=1

            if index == -1 :
                print("해당값이 없습니다")

            else :

                temp = score

                score = [0 for i in range(count-1)]

                i=0
                j=0

                while i < count :

                    if i != index :

                        score[j] = temp[i]
                        j+=1

                    i+=1

                count-=1


    elif choice == 4:

        insert_score = int(input("score를 입력해주세요"))
        insert_idx = int(input("index를 입력해주세요"))

        if count == 0 :

            score=[0]

        elif count > 0 :

            temp = score

            score = [0 for i in range(count+1)]

            i = 0
            j= 0
            while i < count :

                if i != insert_idx :

                    score[i] = temp[j]

                    j+=1

                i+=1

        score[insert_idx] = insert_score
        count+=1


    elif choice == 0:
        print("프로그램 종료")
        break

    print(score)

주의사항 및 Tip

이 문제는 기존 배열이 빈공간이므로 값을 삽입하거나 삭제하기 위해서는 빈공간을 공간으로 만들어아한다는 특징이 있다. 이것을 주의하면서 풀면 될것 같다

삽입 코드가 틀림, 물어보자

94. 관리비[문제]

# ex101_문제.py

# 관리비

apt = [
        [101, 102, 103],
        [201, 202, 203],
        [301, 302, 303]
    ]

pay = [
        [1000, 2100, 1300],
        [4100, 2000, 1000],
        [3000, 1600,  800]
    ]

# 문제 1) 각층별 관리비 합 출력
# 정답 1) 4400, 7100, 5400

# 문제 2) 호를 입력하면 관리비 출력
# 예    2) 입력 : 202	관리비 출력 : 2000

# 문제 3) 관리비가 가장 많이 나온 집, 적게 나온 집 출력
# 정답 3) 가장 많이 나온 집(201), 가장 적게 나온 집(303)

# 문제 4) 호 2개를 입력하면 관리비 교체

정답

# ex101_정답.py

# 관리비

apt = [
        [101, 102, 103],
        [201, 202, 203],
        [301, 302, 303]
    ]

pay = [
        [1000, 2100, 1300],
        [4100, 2000, 1000],
        [3000, 1600,  800]
    ]

# 문제 1) 각층별 관리비 합 출력
# 정답 1) 4400, 7100, 5400

tot = [0, 0, 0]
i = 0
while i < 3:
    j = 0
    while j < 3:
        tot[i] += pay[i][j]
        j += 1
    i += 1
print(tot)

# 문제 2) 호를 입력하면 관리비 출력
# 예    2) 입력 : 202	관리비 출력 : 2000
my_ho = int(input("호 입력 : "))

i = 0
while i < 3:
    j = 0
    while j < 3:
        if my_ho == apt[i][j]:
            print(my_ho, "관리비 =", pay[i][j])
        j += 1
    i += 1

# 문제 3) 관리비가 가장 많이 나온 집, 적게 나온 집 출력
# 정답 3) 가장 많이 나온 집(201), 가장 적게 나온 집(303)

max_i = 0
max_j = 0

max_pay = 0

i = 0
while i < 3:
    j = 0
    while j < 3:
        if max_pay < pay[i][j]:
            max_pay = pay[i][j]
            max_i = i
            max_j = j
        j += 1
    i += 1
print("가장 많이 나온 집 =", apt[max_i][max_j])
#-----------------------------------------------------------

min_i = 0
min_j = 0

min_pay = pay[0][0]

i = 0
while i < 3:
    j = 0
    while j < 3:
        if min_pay > pay[i][j]:
            min_pay = pay[i][j]
            min_i = i
            min_j = j
        j += 1
    i += 1
print("가장 많이 나온 집 =", apt[min_i][min_j])


# 문제 4) 호 2개를 입력하면 관리비 교체

ho1 = int(input("호1 입력 : "))
ho2 = int(input("호2 입력 : "))

ho1_i = 0
ho1_j = 0
ho2_i = 0
ho2_j = 0

i = 0
while i < 3:
    j = 0
    while j < 3:
        if ho1 == apt[i][j]:
            ho1_i = i
            ho1_j = j
        if ho2 == apt[i][j]:
            ho2_i = i
            ho2_j = j
        j += 1
    i += 1

temp = pay[ho1_i][ho1_j]
pay[ho1_i][ho1_j] = pay[ho2_i][ho2_j]
pay[ho2_i][ho2_j] = temp

print(pay)

95. 사다리[문제] [다시]

# ex102_문제.py

# 사다리 게임
# 1. 0을 만나면 아래로 내려간다.
# 2. 1일 때에는 좌우를 검사해 1인 쪽으로 이동 후 아래로 내려간다.
# 3. x의 위치를 입력받고 사다리를 표현한다.
# 		x = 0	x = 4
# 		x = 1	x = 2
# 		x = 2	x = 1
# 		x = 3	x = 3
# 		x = 4	x = 0

ladder = [
        [0, 0, 0, 0, 0],
        [1, 1, 0, 1, 1],
        [0, 1, 1, 0, 0],
        [0, 0, 1, 1, 0],
        [1, 1, 0, 0, 0],
        [0, 1, 1, 0, 0],
        [1, 1, 0, 0, 0],
        [0, 0, 0, 1, 1],
        [0, 0, 0, 0, 0]
    ]

x = 0
y = 0

정답

# ex102_정답.py

# 사다리 게임
# 1. 0을 만나면 아래로 내려간다.
# 2. 1일 때에는 좌우를 검사해 1인 쪽으로 이동 후 아래로 내려간다.
# 3. x의 위치를 입력받고 사다리를 표현한다.
# 		x = 0	x = 4
# 		x = 1	x = 2
# 		x = 2	x = 1
# 		x = 3	x = 3
# 		x = 4	x = 0

ladder = [
        [0, 0, 0, 0, 0],
        [1, 1, 0, 1, 1],
        [0, 1, 1, 0, 0],
        [0, 0, 1, 1, 0],
        [1, 1, 0, 0, 0],
        [0, 1, 1, 0, 0],
        [1, 1, 0, 0, 0],
        [0, 0, 0, 1, 1],
        [0, 0, 0, 0, 0]
    ]

x = 0
y = 0

#--------------------------------------------
# 사다리 출력
i = 0
while i < 9:
    j = 0
    while j < 5:
        if ladder[i][j] == 0:
            print("│", end="")
        elif ladder[i][j] == 1:
            if j != 0 and ladder[i][j - 1] == 1:
                print("┤", end="")
            elif j != 5 and ladder[i][j + 1] == 1:
                print("├", end="")

        j += 1
    print()
    i += 1
#--------------------------------------------

x = int(input("번호(0~4) 선택 : "))

y = 0
while y < 9:
    if ladder[y][x] == 0:
        y += 1
    elif ladder[y][x] == 1:
        if x != 0 and ladder[y][x - 1] == 1:
            x -= 1
        elif x != 4 and ladder[y][x + 1] == 1:
            x += 1
        y += 1

print(x)

주의사항 및 Tip

문제에서 x의 위치 입력받고 사다리를 표현한다고했으므로, x가 실질적으로는 y의 역할을 한다고 보면되서 x와y의 위치를 바꿨다. A and B 일때 항상 A부터 검사하고 B를 검사한다. A에서 조건에 부합하지 않으면 B는 점검할 필요없이 전체가 부합하지 않게 된다

따라서

i = 0
while i < 9:
    j = 0
    while j < 5:
        if ladder[i][j] == 0:
            print("│", end="")
        elif ladder[i][j] == 1:
            if  ladder[i][j - 1]==1 and  j != 0:
                print("┤", end="")
            elif ladder[i][j + 1] == 1 and j != 5:
                print("├", end="")

        j += 1
    print()
    i += 1

여기서 답과는 다르게 if 의 A와B의 위치를 바꿨는데, j가 4일때 j+1에서 5가 되므로 out of index의 오류가 발생하며 중단된다. 그 이유는 앞서 설명했듯이 앞 조건에서 이미 오류가 발생했기 때문이다.

96. 쇼핑몰(관리자)[문제]

# ex103_문제.py

# 쇼핑몰[관리자]
# 1. 카테고리와 아이템을 입력받아 아래의 예시와 같이 저장한다.
# 2. 카테고리는 각 행의 첫번째 열에 저장한다.
# 3. 아이템은 각 행의 두번째 열에 저장한다.
#    단, 아이템은 여러개를 추가할 수 있도록 슬러시(/)를 구분자로 연결해준다.
# 예)
# [
# 		["과일", "사과/포도/"],
# 		["과자", "홈런볼/쪼리퐁/"],
# 		["음료", "콜라/"],
# 		["육류", "소고기/"],
# 		...
# ]


items = [[""] * 2 for i in range(100)]

item_count = 0

while True:
    i = 0
    while i < item_count:
        print(items[i][0] + " : " + items[i][1])
        i += 1

    print("[관리자 모드]")
    print("[1]카테고리 관리")
    print("[2]아 이 템 관리")
    print("[3]전체품목 관리")

    sel = int(input("메뉴 선택 : "))

    if sel == 1:
        pass
    elif sel == 2:
        pass
    elif sel == 3:
        pass

정답

# ex103_정답.py

# 쇼핑몰[관리자]
# 1. 카테고리와 아이템을 입력받아 아래의 예시와 같이 저장한다.
# 2. 카테고리는 각 행의 첫번째 열에 저장한다.
# 3. 아이템은 각 행의 두번째 열에 저장한다.
#    단, 아이템은 여러개를 추가할 수 있도록 슬러시(/)를 구분자로 연결해준다.
# 예)
# [
# 		["과일", "사과/포도/"],
# 		["과자", "홈런볼/쪼리퐁/"],
# 		["음료", "콜라/"],
# 		["육류", "소고기/"],
# 		...
# ]


items = [[""] * 2 for i in range(100)]

item_count = 0

while True:
    print("[관리자 모드]")
    print("[1]카테고리 관리")
    print("[2]아 이 템 관리")
    print("[3]전체품목 관리")

    sel = int(input("메뉴 선택 : "))

    if sel == 1:
        category = input("추가할 카테고리 입력 : ")
        items[item_count][0] = category

        item_count += 1
    elif sel == 2:
        i = 0
        while i < item_count:
            print(i, items[i][0])
            i += 1

        choice = int(input("카테고리 선택 : "))

        item = input("추가할 아이템 입력 : ")
        items[choice][1] += item
        items[choice][1] += "/"
    elif sel == 3:
        i = 0
        while i < item_count:
            print(items[i][0] + " : " + items[i][1])
            i += 1

97. 쇼핑몰(장바구니)[문제]

# ex104_문제.py

# 쇼핑몰[장바구니]
#  1. 로그인 후 쇼핑 메뉴를 선택하면, 다음과 같이 상품목록을 보여준다.
#  1) 사과
#  2) 바나나
#  3) 딸기
#
#  2. 번호를 선택해 상품을 장바구니에 담을 수 있다.
#  3. 로그인 회원의 인덱스 번호는 각 행의 첫번째 열에 저장한다.
#  4. 해당 회원이 구매한 상품의 인덱스 번호는 각 행의 두번째 열에 저장한다.
#  예)
#  [
#  		[0, 1],				qwer회원 			> 사과구매
#  		[1, 2],				javaking회원 		> 바나나구매
#  		[2, 1],				abcd회원			> 사과구매
#  		[0, 3],				qwer회원			> 딸기구매
#  		...
#  ]

ids = ["qwer", "pythonking", "abcd"]
pws = ["1111",       "2222", "3333"]

items = ["사과", "바나나", "딸기"]

jang = [[0] * 2 for i in range(100)]

count = 0

log = -1

while True:
    print("[MEGA MART]")
    print("[1]로 그 인")
    print("[2]로그아웃")
    print("[3]쇼    핑")
    print("[4]장바구니")
    print("[0]종    료")

    sel = int(input("메뉴 선택 : "))

    if sel == 1:
        pass
    elif sel == 2:
        pass
    elif sel == 3:
        pass
    elif sel == 4:
        pass
    elif sel == 0:
        print("프로그램 종료")
        break

정답

# ex104_정답.py

# 쇼핑몰[장바구니]
#  1. 로그인 후 쇼핑 메뉴를 선택하면, 다음과 같이 상품목록을 보여준다.
#  1) 사과
#  2) 바나나
#  3) 딸기
#
#  2. 번호를 선택해 상품을 장바구니에 담을 수 있다.
#  3. 로그인 회원의 인덱스 번호는 각 행의 첫번째 열에 저장한다.
#  4. 해당 회원이 구매한 상품의 인덱스 번호는 각 행의 두번째 열에 저장한다.
#  예)
#  [
#  		[0, 1],				qwer회원 			> 사과구매
#  		[1, 2],				javaking회원 		> 바나나구매
#  		[2, 1],				abcd회원			> 사과구매
#  		[0, 3],				qwer회원			> 딸기구매
#  		...
#  ]

ids = ["qwer", "pythonking", "abcd"]
pws = ["1111",       "2222", "3333"]

items = ["사과", "바나나", "딸기"]

jang = [[0] * 2 for i in range(100)]

count = 0

log = -1

while True:
    if log == -1:
        print("로그아웃 상태")
    else:
        print(ids[log], "님 로그인중")

    print("[MEGA MART]")
    print("[1]로 그 인")
    print("[2]로그아웃")
    print("[3]쇼    핑")
    print("[4]장바구니")
    print("[0]종    료")

    sel = int(input("메뉴 선택 : "))

    if sel == 1:
        my_id = input("ID 입력 : ")
        my_pw = input("PW 입력 : ")

        i = 0
        while i < 3:
            if my_id == ids[i] and my_pw == pws[i]:
                log = i
            i += 1

        if log == -1:
            print("[메세지]ID와 PW를 확인해주세요.")
        else:
            print(ids[log], "님, 환영합니다.")
    elif sel == 2:
        log = -1
        print("[메세지]로그아웃 되었습니다.")
    elif sel == 3:
        if log == -1:
            print("[메세지]로그인 후 이용가능합니다.")
            continue

        while True:
            print("[상품목록]")
            i = 0
            while i < 3:
                print(i+1, items[i])
                i += 1
            print("4 뒤로가기")

            choice = int(input("상품번호 선택 : "))
            if choice == 4:
                break

            jang[count][0] = log
            jang[count][1] = choice

            count += 1
    elif sel == 4:
        apple_cnt = 0
        banana_cnt = 0
        berry_cnt = 0

        i = 0
        while i < count:
            if jang[i][0] == log:
                if jang[i][1] == 1:
                    apple_cnt += 1
                elif jang[i][1] == 2:
                    banana_cnt += 1
                elif jang[i][1] == 3:
                    berry_cnt += 1
            i += 1

        print("사과 :", apple_cnt)
        print("바나나 :", banana_cnt)
        print("딸기 :", berry_cnt)
    elif sel == 0:
        print("프로그램 종료")
        break

98. 당첨복권 1셋트[문제] [다시]

# ex105_문제.py

# 당첨복권 1셋트
# 1. 3이 연속으로 3번 등장하면 당첨복권이다.
# 2. 랜덤으로 5개의 복권을 생성하되,
#    당첨복권은 한 개만 생성되도록 설정한다.

lotto = [[0]*7 for i in range(5)]

정답

import random

lotto = [[0]*7 for i in range(5)]





win = 0

i = 0



while i < 5:
    j = 0
    while j < 7:
        r = random.randint(0, 1)
        if r == 0:
            lotto[i][j] = 3
        else:
            lotto[i][j] = 0
        j += 1

    check = 0
    count = 0
    j = 0
    while j < 7:
        if lotto[i][j] == 3:
            count += 1
        else:
            count = 0
        if count == 3:
            check = 1
        j += 1

    # 333이 연속인게 하나를 출력하기 위함

    if check == 1 and win == 0:
        win = 1
        i += 1
    elif check == 1 and win == 1:
        pass
    # 여기서 pass가 아닌 i+=1을 할경우 333이 만들어지니까, 다시 만들어야하므로
    elif check == 0 and win == 0:
        pass
    elif check == 0 and win == 1:
        i += 1

i = 0
while i < 5:
    j = 0
    while j < 7:
        print(lotto[i][j], end=" ")
        j += 1
    print()
    i += 1

주의사항 및 Tip

여기서 pass가 아닌 i+=1을 할경우 아예 333이 안나올수도 있다.

 # 여기서 pass가 아닌 i+=1을 할경우 아예 333이 안나올수도 있다.
    elif check == 0 and win == 0:
        pass

99. 중복안된 숫자 제거[문제] [다시]

# ex106_문제.py

# 중복안된 숫자 제거

test1 = [1, 2, 3, 2, 1]
test2 = [1, 3, 4, 4, 2]
test3 = [1, 1, 1, 2, 1]

# 위 리스트에서 중복 안된 숫자를 제거하시오.
# [1] [1, 2, 2, 1]
# [2] [4, 4]
# [3] [1, 1, 1, 1]

정답

# ex106_정답.py

# 중복안된 숫자 제거

test1 = [1, 2, 3, 2, 1]
test2 = [1, 3, 4, 4, 2]
test3 = [1, 1, 1, 2, 1]

# 위 리스트에서 중복 안된 숫자를 제거하시오.
# [1] [1, 2, 2, 1]
# [2] [4, 4]
# [3] [1, 1, 1, 1]

temp = []


i = 0
while i < 5:
    check = 0
    j = 0
    while j < 5:
        if i != j and test1[i] == test1[j]:
            check = 1
        j += 1

    if check == 1:
        temp.append(test1[i])
    i += 1

print(temp)

101. 2차원 배열(삭제)[문제]

# ex107_문제.py

# 2차원배열[삭제]
# 이름과 번호를 입력받아 삭제하기

# 예)
# 삭제할 이름 입력 : 철수
# 삭제할 번호 입력 : 1
# 삭제 => ["철수", "김밥"]
#
# 삭제할 이름 입력 : 철수
# 삭제할 번호 입력 : 2
# 삭제 => ["철수", "바나나"]

jang = [
        ["철수", "소고기"],
        ["철수", "김밥"],
        ["영희", "김치"],
        ["철수", "바나나"],
        ["철수", "새우깡"],
        ["영희", "오징어"],
        ["영희", "맛밤"]
    ]

정답

# ex107_정답.py

# 2차원배열[삭제]
# 이름과 번호를 입력받아 삭제하기

# 예)
# 삭제할 이름 입력 : 철수
# 삭제할 번호 입력 : 1
# 삭제 => ["철수", "김밥"]
#
# 삭제할 이름 입력 : 철수
# 삭제할 번호 입력 : 2
# 삭제 => ["철수", "바나나"]

jang = [
        ["철수", "소고기"],
        ["철수", "김밥"],
        ["영희", "김치"],
        ["철수", "바나나"],
        ["철수", "새우깡"],
        ["영희", "오징어"],
        ["영희", "맛밤"]
    ]

i = 0
while i < 7:
    print(jang[i][0], ":", jang[i][1])
    i += 1

del_name = input("삭제할 이름 입력 : ")

del_num = int(input("삭제할 번호 입력 : "))

del_idx = -1
count = 0
i = 0
while i < 7:
    if jang[i][0] == del_name:
        if count == del_num:
            del_idx = i
        count += 1
    i += 1

# print(del_idx)

temp = [[""] * 2 for _ in range(6)]

j = 0
i = 0
while i < 7:
    if i != del_idx:
        temp[j] = jang[i]
        j += 1
    i += 1

jang = temp

i = 0
while i < 6:
    print(jang[i][0], ":", jang[i][1])
    i += 1

###

# ex107_정답.py

# 2차원배열[삭제]
# 이름과 번호를 입력받아 삭제하기

# 예)
# 삭제할 이름 입력 : 철수
# 삭제할 번호 입력 : 1
# 삭제 => ["철수", "김밥"]
#
# 삭제할 이름 입력 : 철수
# 삭제할 번호 입력 : 2
# 삭제 => ["철수", "바나나"]

jang = [
        ["철수", "소고기"],
        ["철수", "김밥"],
        ["영희", "김치"],
        ["철수", "바나나"],
        ["철수", "새우깡"],
        ["영희", "오징어"],
        ["영희", "맛밤"]
    ]

i = 0
while i < 7:
    print(jang[i][0], ":", jang[i][1])
    i += 1

del_name = input("삭제할 이름 입력 : ")

del_num = int(input("삭제할 번호 입력 : "))

del_idx = -1
count = 0
i = 0
while i < 7:
    if jang[i][0] == del_name:
        if count == del_num:
            del_idx = i
        count += 1
    i += 1

# print(del_idx)

temp = [[""] * 2 for _ in range(6)]

j = 0
i = 0
while i < 7:
    if i != del_idx:
        temp[j] = jang[i]
        j += 1
    i += 1

jang = temp

i = 0
while i < 6:
    print(jang[i][0], ":", jang[i][1])
    i += 1

주의사항 및 Tip

  • tip

    • 첫째, 배열에서 내가 입력한 이름과 번호에 부합하는 것이 배열의 몇번째 있는지를 알아야한다.

    • 둘째, 찾은 번호를 삭제해야하므로, 복사할 배열을 만들어준다음 삭제할 번호가 아닌것들을 집어넣어준다

    • 셋재, 복사된 배열은 다시 원본에 넣어준다.

101. 2차원 배열(정렬)[문제] [다시]

# ex108_문제.py

# 2차원배열[정렬]
# 영희 : 감
# 영희 : 김밥
# 영희 : 사과
# 철수 : 김밥
# 철수 : 사과

jang = [
        ["철수", "김밥"],
        ["영희", "감"],
        ["철수", "사과"],
        ["영희", "사과"],
        ["영희", "김밥"]
    ]

jang_count = 5

i = 0
while i < jang_count:
    print(jang[i][0], ":", jang[i][1])
    i += 1

정답

# 이름 정렬
i = 0
while i < jang_count:
    min_name = jang[i][0]
    min_idx = i

    j = i
    while j < jang_count:
        if min_name > jang[j][0]:
            min_name = jang[j][0]
            min_idx = j
        j += 1

    temp = jang[i]
    jang[i] = jang[min_idx]
    jang[min_idx] = temp

    i += 1

# 상품 정렬
i = 0
while i < jang_count:
    min_name = jang[i][1]
    min_idx = i

    j = i
    while j < jang_count:
        if jang[i][0] == jang[j][0]:
            if min_name > jang[j][1]:
                min_name = jang[j][1]
                min_idx = j
        j += 1

    temp = jang[i]
    jang[i] = jang[min_idx]
    jang[min_idx] = temp

    i += 1

i = 0
while i < jang_count:
    print(jang[i][0], ":", jang[i][1])
    i += 1

주의사항 및 Tip

이 문제에서는 상품정렬은, 이름이 같은것끼리중에 상품 정렬을 의미한다.

101. 빙고(1인용 )[문제] [다시]

# 빙고 ver1.

# 1. 5 x 5 2차원 리스트
# 2. 1~50 사이의 랜덤 숫자 25개를 중복없이 저장
# 3. 숫자 선택 시, y와 x좌표를 입력받아 처리
# 4. 한줄 완성 시, 빙고!(게임 종료)

bingo = [[0]*5 for _ in range(5)]
mark = [[0]*5 for _ in range(5)]

정답

# 빙고 ver1.

# 1. 5 x 5 2차원 리스트
# 2. 1~50 사이의 랜덤 숫자 25개를 중복없이 저장
# 3. 숫자 선택 시, y와 x좌표를 입력받아 처리
# 4. 한줄 완성 시, 빙고!(게임 종료)

import random

bingo = [[0]*5 for _ in range(5)]
mark = [[0]*5 for _ in range(5)]

win = False

# 1~50 랜덤숫자 중복없이 저장하기
temp = [0 for i in range(5*5)]
i = 0
while i < len(temp):
    r = random.randint(1, 50)

    check = 0

    j = 0
    while j < i:
        if r == temp[j]:
            check = 1
        j += 1

    if check == 0:
        temp[i] = r
        i += 1

k = 0
i = 0
while i < 5:
    j = 0
    while j < 5:
        bingo[i][j] = temp[k]
        k += 1
        j += 1
    i += 1

# 게임시작
while True:

    # 화면 출력
    i = 0
    while i < 5:
        j = 0
        while j < 5:
            print(bingo[i][j], end="\t")
            j += 1
        print()
        i += 1

    # 게임종료
    if win:
        print("게임종료")
        break

    # 번호 선택
    y = int(input("y좌표 입력 : "))
    x = int(input("x좌표 입력 : "))

    if mark[y][x] == 0:
        mark[y][x] = 1
        bingo[y][x] = "O"
    else:
        print("이미 선택한 숫자입니다.")

    # 빙고확인

    i = 0
    while i < 5:
        # 가로
        if mark[i][0] == 1 and mark[i][1] == 1 and mark[i][2] == 1 and mark[i][3] == 1 and mark[i][4] == 1:
            win = True
        # 세로
        if mark[0][i] == 1 and mark[1][i] == 1 and mark[2][i] == 1 and mark[3][i] == 1 and mark[4][i] == 1:
            win = True
        i += 1

    # 대각선
    if mark[0][0] == 1 and mark[1][1] == 1 and mark[2][2] == 1 and mark[3][3] == 1 and mark[4][4]:
        win = True
    if mark[0][4] == 1 and mark[1][3] == 1 and mark[2][2] == 1 and mark[3][1] == 1 and mark[4][0]:
        win = True
# 빙고 ver1.

# 1. 5 x 5 2차원 리스트
# 2. 1~50 사이의 랜덤 숫자 25개를 중복없이 저장
# 3. 숫자 선택 시, y와 x좌표를 입력받아 처리
# 4. 한줄 완성 시, 빙고!(게임 종료)

import random

bingo = [[0]*5 for _ in range(5)]
mark = [[0]*5 for _ in range(5)]

# 1~50 랜덤숫자 중복없이 저장하기
check = [0 for i in range(50)]

i = 0
while i < 5 :

    j=0

    while j < 5 :

        r = random.randint(1,50)

        if check[r-1] != 1 :

            bingo[i][j] = r
            check[r-1] = 1
            j+=1

    i+=1

run = True
while run :

    # 화면
    i = 0
    while i < 5 :

        j = 0

        while j < 5 :

            print(bingo[i][j],end="\t")

            j+=1

        print()

        i+=1

    # 게임시작

    y = int(input("x의 좌표를 입력해주세요"))
    x = int(input("y의 좌표를 입력해주세요"))

    if mark[y][x] == 0 :

        bingo[y][x] = "O"
        mark[y][x] = 1
    else :
        print("이미 선택한 숫자입니다.")

    # 빙고확인

    i = 0
    while i < 5:
        # 가로
        if mark[i][0] == 1 and mark[i][1] == 1 and mark[i][2] == 1 and mark[i][3] == 1 and mark[i][4] == 1:

            run = False

        # 세로
        if mark[0][i] == 1 and mark[1][i] == 1 and mark[2][i] == 1 and mark[3][i] == 1 and mark[4][i] == 1:

            run = False
        i += 1

    # 대각선
    if mark[0][0] == 1 and mark[1][1] == 1 and mark[2][2] == 1 and mark[3][3] == 1 and mark[4][4] == 1:

        run = False

    if mark[0][4] == 1 and mark[1][3] == 1 and mark[2][2] == 1 and mark[3][1] == 1 and mark[4][0] == 1:

        run = False

주의사항 및 Tip

  • tip

    • 첫째, 1~50까지 수중 25개를 랜덤숫자를 넣는 방법은 그 값이 이미 있는지0 확인할수 있는 배열은 새롭게 만들어서 넣어주면된다.

    • 둘째, 승리조건을 생각해본다. mark의 용도는 가로, 세로, 대각선의 승리조건을 확인하기 위해 사용된다.

102. 빙고(2인용 )[문제] [다시]

# 빙고 ver2.

# 1. 5 x 5 2차원 리스트
# 2. 1~50 사이의 랜덤 숫자 25개를 중복없이 저장
# 3. 숫자 선택 시, y와 x좌표를 입력받아 처리
# 4. 한줄 완성 시, 빙고!(게임 종료)
# ----------------------------------------------
# 5. 내가 선택한 번호가 상대방에게도 있을 경우, 함께 마킹

import random

p1 = [[0]*5 for _ in range(5)]
p2 = [[0]*5 for _ in range(5)]
mark1 = [[0]*5 for _ in range(5)]
mark2 = [[0]*5 for _ in range(5)]

win = 0
turn = True

정답

# 빙고 ver2.

# 1. 5 x 5 2차원 리스트
# 2. 1~50 사이의 랜덤 숫자 25개를 중복없이 저장
# 3. 숫자 선택 시, y와 x좌표를 입력받아 처리
# 4. 한줄 완성 시, 빙고!(게임 종료)
# ----------------------------------------------
# 5. 내가 선택한 번호가 상대방에게도 있을 경우, 함께 마킹

import random

p1 = [[0]*5 for _ in range(5)]
p2 = [[0]*5 for _ in range(5)]
mark1 = [[0]*5 for _ in range(5)]
mark2 = [[0]*5 for _ in range(5)]

win = 0
turn = True

# p1과 p2 빙고판 만들기
temp1 = [0 for i in range(5 * 5)]
i = 0
while i < len(temp1):
    r = random.randint(1, 50)

    check = 0

    j = 0
    while j < i:
        if r == temp1[j]:
          check = 1
        j += 1

    if check == 0:
        temp1[i] = r
        i += 1

temp2 = [0 for i in range(5 * 5)]
i = 0
while i < len(temp2):
    r = random.randint(1, 50)

    check = 0

    j = 0
    while j < i:
        if r == temp2[j]:
          check = 1
        j += 1

    if check == 0:
        temp2[i] = r
        i += 1

k = 0
i = 0
while i < 5:
    j = 0
    while j < 5:
        p1[i][j] = temp1[k]
        k += 1
        j += 1
    i += 1

k = 0
i = 0
while i < 5:
    j = 0
    while j < 5:
        p2[i][j] = temp2[k]
        k += 1
        j += 1
    i += 1

# 게임시작
while True:
    # 화면 출력
    print("[p1]")
    i = 0
    while i < 5:
        j = 0
        while j < 5:
            print(p1[i][j], end="\t")
            j += 1
        print()
        i += 1

    print("[p2]")
    i = 0
    while i < 5:
        j = 0
        while j < 5:
            print(p2[i][j], end="\t")
            j += 1
        print()
        i += 1

    # 게임 종료
    if win == 1:
        print("p1승리")
        break
    elif win == 2:
        print("p2승리")
        break

    if turn:
        # p1차례
        yy = int(input("[p1차례]y좌표 입력 : "))
        xx = int(input("[p1차례]x좌표 입력 : "))

        if mark1[yy][xx] == 0:
            i = 0
            while i < 5:
                j = 0
                while j < 5:
                    if p1[yy][xx] == p2[i][j]:
                        p2[i][j] = "X"
                        mark1[i][j] = 2
                    j += 1
                i += 1

            p1[yy][xx] = "O"
            mark1[yy][xx] = 1

            turn = False
        else:
            print("이미 선택한 번호입니다.")
    else:
        # p2차례
        yy = int(input("[p2차례]y좌표 입력 : "))
        xx = int(input("[p2차례]x좌표 입력 : "))

        if mark2[yy][xx] == 0:
            i = 0
            while i < 5:
                j = 0
                while j < 5:
                    if p2[yy][xx] == p1[i][j]:
                        p1[i][j] = "O"
                        mark2[i][j] = 1
                    j += 1
                i += 1

            p2[yy][xx] = "X"
            mark2[yy][xx] = 2

            turn = True
        else:
            print("이미 선택한 번호입니다.")

    # 승패결정
    i = 0
    while i < 5:
        # 가로
        if mark1[i][0] == 1 and mark1[i][1] == 1 and mark1[i][2] == 1 and mark1[i][3] == 1 and mark1[i][4] == 1:
            win = 1
        if mark2[i][0] == 2 and mark2[i][1] == 2 and mark2[i][2] == 2 and mark2[i][3] == 2 and mark2[i][4] == 2:
            win = 2

        # 세로
        if mark1[0][i] == 1 and mark1[1][i] == 1 and mark1[2][i] == 1 and mark1[3][i] == 1 and mark1[4][i] == 1:
            win = 1
        if mark2[0][i] == 2 and mark2[1][i] == 2 and mark2[2][i] == 2 and mark2[3][i] == 2 and mark2[4][i] == 2:
            win = 2
        i += 1

    # 대각선
    if mark1[0][0] == 1 and mark1[1][1] == 1 and mark1[2][2] == 1 and mark1[3][3] == 1 and mark1[4][4] == 1:
        win = 1
    if mark2[0][0] == 2 and mark2[1][1] == 2 and mark2[2][2] == 2 and mark2[3][3] == 2 and mark2[4][4] == 2:
        win = 2

    if mark1[4][0] == 1 and mark1[3][1] == 1 and mark1[2][2] == 1 and mark1[3][1] == 1 and mark1[4][0] == 1:
        win = 1
    if mark2[4][0] == 2 and mark2[3][1] == 2 and mark2[2][2] == 2 and mark2[3][1] == 2 and mark2[4][0] == 2:
        win = 2

103. 오목[문제] [다시]

# 오목게임

omok = [[0]*10 for i in range(10)]

p1Y = 0
p1X = 0

p2Y = 0
p2X = 0

turn = 0
win = 0

정답

# 오목게임

size = 10
omok = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]

p1_y = 0
p1_x = 0

p2_y = 0
p2_x = 0

turn = 0
win = 0

while True:
    # 게임화면 출력
    i = 0
    while i < 10:
        j = 0
        while j < 10:
            if omok[i][j] == 1:
                print("○", end="\t")
            elif omok[i][j] == 2:
                print("●", end="\t")
            else:
                print(omok[i][j], end="\t")
            j += 1
        print("\n")
        i += 1

    # 게임종료
    if win == 1:
        print("[p1 승리]")
        break
    elif win == 2:
        print("[p2 승리]")
        break

    # p1차례
    if turn % 2 == 0:
        p1_y = int(input("[p1차례]y좌표 입력 : "))
        p1_x = int(input("[p1차례]x좌표 입력 : "))

        if omok[p1_y][p1_x] == 0:
            omok[p1_y][p1_x] = 1
            turn += 1
    # p2차
    elif turn % 2 == 1:
        p2_y = int(input("[p1차례]y좌표 입력 : "))
        p2_x = int(input("[p1차례]x좌표 입력 : "))

        if omok[p2_y][p2_x] == 0:
            omok[p2_y][p2_x] = 2
            turn += 1

    # 승패처리
    # 가로
    i = 0
    while i < size:
        j = 0
        while j < size - 4:
            if omok[i][j] == 1 and omok[i][j + 1] == 1 and omok[i][j + 2] == 1 and omok[i][j + 3] == 1 and omok[i][j + 4] == 1:
                win = 1
            if omok[i][j] == 2 and omok[i][j + 1] == 2 and omok[i][j + 2] == 2 and omok[i][j + 3] == 2 and omok[i][j + 4] == 2:
                win = 2
            j += 1
        i += 1

    # 세로
    i = 0
    while i < size - 4:
        j = 0
        while j < size:
            if omok[i][j] == 1 and omok[i + 1][j] == 1 and omok[i + 2][j] == 1 and omok[i + 3][j] == 1 and omok[i + 4][j] == 1:
                win = 1
            if omok[i][j] == 2 and omok[i + 1][j] == 2 and omok[i + 2][j] == 2 and omok[i + 3][j] == 2 and omok[i + 4][j] == 2:
                win = 2
            j += 1
        i += 1

    # 대각선 /
    i = 0
    while i < size - 4:
        j = 4
        while j < size:
            if omok[i][j] == 1 and omok[i + 1][j - 1] == 1 and omok[i + 2][j - 2] == 1 and omok[i + 3][j - 3] == 1 and omok[i + 4][j - 4] == 1:
                win = 1
            if omok[i][j] == 2 and omok[i + 1][j - 1] == 2 and omok[i + 2][j - 2] == 2 and omok[i + 3][j - 3] == 2 and omok[i + 4][j - 4] == 2:
                win = 2
            j += 1
        i += 1

    # 대각선 \
    i = 0
    while i < size - 4:
        j = 0
        while j < size - 4:
            if omok[i][j] == 1 and omok[i + 1][j + 1] == 1 and omok[i + 2][j + 2] == 1 and omok[i + 3][j + 3] == 1 and omok[i + 4][j + 4] == 1:
                win = 1
            if omok[i][j] == 2 and omok[i + 1][j + 1] == 2 and omok[i + 2][j + 2] == 2 and omok[i + 3][j + 3] == 2 and omok[i + 4][j + 4] == 2:
                win = 2
            j += 1
        i += 1

주의사항 및 tip

  • 주의사항

    • 첫째, 빙고와 다르게 오목은 가로 세로 전부가 아닌 5개 일때 승리한다는 점을 토대로 , 승리조건의 모든 가지수를 생각해봐야한다.

    • 둘째, 빙고와 다르게 , mark 표시를 하지 않고도 구현이 가능했다. 빙고도 내가 생각할떄는 mark를 사용하지 않고 표현이 가능할듯

104. 소코반[문제] [다시]

# 소코반

# 1. 게임 map의 사이즈는 7 x 7의 2차원 리스트이다.
# 2. 사용자로부터 벽의 설치개수를 물어 랜덤한 위치에 설치한다.
# 3. 공과 골대를 벽과 겹치지 않도록 랜덤한 위치에 설치한다.
# 4. 사용자로부터 플레이어의 위치 값을 입력받아 배치시킨다.
# 5. 플레이어는 상하좌우로 이동이 가능하다.
# 6. 플레이어를 이동시켜 공을 골대에 넣으면 게임이 종료된다.

# 예)
# 0 9 0 0 0 0 0
# 7 0 0 9 0 0 0
# 3 0 9 0 0 0 0
# 2 0 0 0 0 9 0
# 0 0 9 0 0 0 0
# 0 9 0 0 0 0 0
# 0 9 0 0 0 0 0
# 상(1)하(2)좌(3)우(4) 입력 : 1

# 0 9 0 0 0 0 0
# 3 0 0 9 0 0 0
# 2 0 9 0 0 0 0
# 0 0 0 0 0 9 0
# 0 0 9 0 0 0 0
# 0 9 0 0 0 0 0
# 0 9 0 0 0 0 0
# 게임 종료

import random

game = [[0] * 7 for i in range(7)]

size = 7
player = 2
ball = 3
goal = 7
wall = 9

wall_count = 0
p_y = 0
p_x = 0
ball_y = 0
ball_x = 0
goal_y = 0
goal_x = 0

# 벽 설치
wall_count = int(input("벽을 몇 개 설치하시겠습니까?"))
while wall_count != 0:
    r_y = random.randint(0, size-1)
    r_x = random.randint(0, size-1)

    game[r_y][r_x] = wall
    wall_count -= 1

# 공 설치
while True:
    r_y = random.randint(0, size-1)
    r_x = random.randint(0, size-1)

    if game[r_y][r_x] == 0:
        game[r_y][r_x] = ball
        ball_y = r_y
        ball_x = r_x
        break

# 골대 설치
while True:
    r_y = random.randint(0, size-1)
    r_x = random.randint(0, size-1)

    if game[r_y][r_x] == 0
        game[r_y][r_x] = goal
        goal_y = r_y
        goal_x = r_x
        break

# 캐릭터 배치
while True:
    p_y = int(input("캐릭터의 y좌표 입력 : "))
    p_x = int(input("캐릭터의 x좌표 입력 : "))

    if game[p_y][p_x] == 0:
        game[p_y][p_x] = player
        break
i = 0
while i < size:
    j = 0
    while j < size:
        print(game[i][j], end=" ")
        j += 1
    print()
    i += 1

정답

# 소코반

# 1. 게임 map의 사이즈는 7 x 7의 2차원 리스트이다.
# 2. 사용자로부터 벽의 설치개수를 물어 랜덤한 위치에 설치한다.
# 3. 공과 골대를 벽과 겹치지 않도록 랜덤한 위치에 설치한다.
# 4. 사용자로부터 플레이어의 위치 값을 입력받아 배치시킨다.
# 5. 플레이어는 상하좌우로 이동이 가능하다.
# 6. 플레이어를 이동시켜 공을 골대에 넣으면 게임이 종료된다.

# 예)
# 0 9 0 0 0 0 0
# 7 0 0 9 0 0 0
# 3 0 9 0 0 0 0
# 2 0 0 0 0 9 0
# 0 0 9 0 0 0 0
# 0 9 0 0 0 0 0
# 0 9 0 0 0 0 0
# 상(1)하(2)좌(3)우(4) 입력 : 1

# 0 9 0 0 0 0 0
# 3 0 0 9 0 0 0
# 2 0 9 0 0 0 0
# 0 0 0 0 0 9 0
# 0 0 9 0 0 0 0
# 0 9 0 0 0 0 0
# 0 9 0 0 0 0 0
# 게임 종료

import random

game = [[0] * 7 for i in range(7)]

size = 7
player = 2
ball = 3
goal = 7
wall = 9

wall_count = 0
p_y = 0
p_x = 0
ball_y = 0
ball_x = 0
goal_y = 0
goal_x = 0

# 벽 설치
wall_count = int(input("벽을 몇 개 설치하시겠습니까?"))
while wall_count != 0:
    r_y = random.randint(0, size-1)
    r_x = random.randint(0, size-1)

    game[r_y][r_x] = wall
    wall_count -= 1

# 공 설치
while True:
    r_y = random.randint(0, size-1)
    r_x = random.randint(0, size-1)

    if game[r_y][r_x] == 0:
        game[r_y][r_x] = ball
        ball_y = r_y
        ball_x = r_x
        break

# 골대 설치
while True:
    r_y = random.randint(0, size-1)
    r_x = random.randint(0, size-1)

    if game[r_y][r_x] == 0:
        game[r_y][r_x] = goal
        goal_y = r_y
        goal_x = r_x
        break

# 캐릭터 배치
while True:
    y = int(input("캐릭터의 y좌표 입력 : "))
    x = int(input("캐릭터의 x좌표 입력 : "))

    if game[y][x] == 0:
        game[y][x] = player
        p_y = y
        p_x = x
        break

# 게임시작
while True:
    # 화면 출력
    i = 0
    while i < size:
        j = 0
        while j < size:
            print(game[i][j], end=" ")
            j += 1
        print()
        i += 1
    print()

    # 게임종료
    if goal_y == ball_y and goal_x == ball_x:
        print("게임 종료")
        break

    # 입력받기
    move = int(input("상(1)하(2)좌(3)우(4) : "))

    yy = p_y
    xx = p_x

    if move == 1:
        yy = yy - 1
    elif move == 2:
        yy = yy + 1
    elif move == 3:
        xx = xx - 1
    elif move == 4:
        xx = xx + 1

    # 예외처리
    if size <= xx or xx < 0:
        continue
    if size <= yy or yy < 0:
        continue
    if game[yy][xx] != 0 and game[yy][xx] != ball:
        continue

    # 공을 만나면,
    if game[yy][xx] == ball:
        yyy = yy
        xxx = xx
        if move == 1:
            yyy = yyy - 1
        elif move == 2:
            yyy = yyy + 1
        elif move == 3:
            xxx = xxx - 1
        elif move == 4:
            xxx = xxx + 1

        if size <= yyy or yyy < 0:
            continue
        if size <= xxx or xxx < 0:
            continue
        if game[yyy][xxx] != 0 and game[yyy][xxx] != goal:
            continue

        game[ball_y][ball_x] = 0
        ball_y = yyy
        ball_x = xxx
        game[ball_y][ball_x] = ball

    # 캐릭터 이동
    game[p_y][p_x] = 0
    p_y = yy
    p_x = xx
    game[p_y][p_x] = player

105. 식권 자판기[문제] [다시 , 잘 모르겠음]

# ex117_문제.py

# 식권 자판기 프로그램
# [1] 관리자
# 1) 식권충전
# 2) 잔돈충전
# 3) 뒤로가기
# [2] 사용자
# 1) 구입
# . 입금 금액 입력
# . 구매 매수 입력
# . 잔돈 출력
# 2) 뒤로가기

# 예)
# 잔돈이 7,600원이다.
# 기계에 5,000원 권이 없으면 1,000원짜리로 7장 출력

moneys  = [50000, 10000, 5000, 1000, 500, 100]      # 출력용
charges = [    1,     1,    1,    1,   5,  10]      # 잔돈 개수

tickets = 5    # 식권 개수
price = 3200    # 식권 가격

while True:
    print("[1]관리자")
    print("[2]사용자")

    choice = int(input("메뉴 선택 : "))

    if choice == 1:
        while True:
            print("1)식권충전")
            print("2)잔돈충전")
            print("3)뒤로가기")

            sel1 = int(input("메뉴 선택 : "))
            if sel1 == 1:
                pass
            elif sel1 == 2:
                pass
            elif sel1 == 3:
                break
    elif choice == 2:
        while True:
            print("1)구입")
            print("2)뒤로가기")

            sel2 = int(input("메뉴 선택 : "))
            if sel2 == 1:
                pass
            elif sel2 == 2:
                break

정답

# ex117_정답.py

# 식권 자판기 프로그램
# [1] 관리자
# 1) 식권충전
# 2) 잔돈충전
# 3) 뒤로가기
# [2] 사용자
# 1) 구입
# . 입금 금액 입력
# . 구매 매수 입력
# . 잔돈 출력
# 2) 뒤로가기

# 예)
# 잔돈이 7,600원이다.
# 기계에 5,000원 권이 없으면 1,000원짜리로 7장 출력

moneys  = [50000, 10000, 5000, 1000, 500, 100]      # 출력용
charges = [    1,     1,    1,    1,   5,  10]      # 잔돈 개수

tickets = 5    # 식권 개수
price = 3200    # 식권 가격

while True:
    print("[1]관리자")
    print("[2]사용자")

    choice = int(input("메뉴 선택 : "))

    if choice == 1:
        while True:
            print("식권 수량 =", tickets)
            i = 0
            while i < len(moneys):
                print(moneys[i], ":", charges[i])
                i += 1

            print("1)식권충전")
            print("2)잔돈충전")
            print("3)뒤로가기")

            sel1 = int(input("메뉴 선택 : "))
            if sel1 == 1:
                count = int(input("충전할 식권 수를 입력하세요 : "))
                tickets += count
            elif sel1 == 2:
                while True:
                    i = 0
                    while i < len(moneys):
                        print("[%d] %d : %d장" % (i+1, moneys[i], charges[i]))
                        i += 1
                    print("[0]뒤로가기")

                    num = int(input("메뉴 선택 : "))
                    if num == 0:
                        break
                    else:
                        charges[num - 1] += 1
            elif sel1 == 3:
                break
    elif choice == 2:
        while True:
            print("1)구입")
            print("2)뒤로가기")

            sel2 = int(input("메뉴 선택 : "))
            if sel2 == 1:
                count = int(input("구입할 식권 수 입력 : "))

                if count > tickets:
                    continue

                result = count * price
                print("총 금액 =", result)

                my_charges = [0 for i in range(len(moneys))]
                print("돈을 투입구에 넣어주세요.")
                while True:
                    i = 0
                    while i < len(moneys):
                        print("[%d] %d : %d장" % (i+1, moneys[i], charges[i]))
                        i += 1
                    print("[0]뒤로가기")

                    num = int(input("메뉴 선택 : "))
                    if num == 0:
                        break
                    else:
                        my_charges[num - 1] += 1

                my_result = 0
                i = 0
                while i < len(my_charges):
                    my_result += my_charges[i] * moneys[i]
                    i += 1
                print(my_result, "원 입금하였습니다.")

                charge = my_result - result
                print("잔돈 =", charge)

                # 만약 잔돈이 있을경우
                if charge >= 0:


                    temp_charges = [0 for i in range(len(charges))]
                    i = 0
                    while i < len(temp_charges):
                        temp_charges[i] = charges[i]
                        i += 1
                    temp_charge = charge

                    i = 0
                    while i < len(temp_charges):
                        while True:
                            # 만약 잔돈이 금액보다크거나 갯수가 0 이 아닌경우
                            if temp_charge >= moneys[i] and temp_charges[i] > 0:
                                # 잔돈에서 그 금액을 제외하고
                                temp_charge -= moneys[i]
                                # 잔돈갯수에서 하나를 뺀다.
                                temp_charges[i] -= 1
                            else:
                                break
                        i += 1


                    if temp_charge == 0:
                        i = 0

                        while i < len(temp_charges):
                            charges[i] = temp_charges[i]
                            charges[i] += my_charges[i]
                            i += 1
                        tickets -= count
                        print("식권 수량 =", tickets)

                        j = 0
                        while j < len(moneys):
                            print(moneys[j], ":", charges[j])
                            j += 1
                    else:
                        print("기계상의 잔돈 부족으로 거래가 불가합니다.")
                else:
                    print("입금하신 돈이 부족합니다.")
            elif sel2 == 2:
                break

주의사항 및 Tip

사용자

106. 문자열[문제]

# ex84_문제.py

# 문제1) 문자열 hello를 olleh로 출력
text = "hello"

# 문제2) 남성인지 여성인지 판단
jumin = "870612-1012940"

정답

# ex84_정답.py

# 문제1) 문자열 hello를 olleh로 출력
text = "hello"

i = len(text) - 1
while i >= 0:
    print(text[i], end="")
    i = i - 1
print()

# 문제2) 남성인지 여성인지 판단
jumin = "870612-1012940"

key = jumin[7]
if key == "1" or key == "3":
    print("남성")
elif key == "2" or key == "4":
    print("여성")

107. 문자열 2차원[문제]

# 문자열 2차원[문제]
data = "박소리,97/안새롬,100/유철민,24"

# 문제 1) data의 문자열을 잘라내서
#         names와 scores 리스트에 알맞은 데이터를 저장하시오.
names = ["", "", ""]
scores = [0, 0, 0]

# 문제 2) 아래 두 리스트 자료를
#         data 변수에 하나의 문자열로 연결하여 다음과 같이 저장하시오.
#         "박소리,97/안새롬,100/유철민,24"
names = ["박소리", "안새롬", "유철민"]
scores = [97, 100, 24]
data = ""

정답

# 문자열 2차원[정답]
data = "박소리,97/안새롬,100/유철민,24"

# 문제 1) data의 문자열을 잘라내서
#         names와 scores 리스트에 알맞은 데이터를 저장하시오.
names = ["", "", ""]
scores = [0, 0, 0]

temp = data.split("/")
size = len(temp)

i = 0
while i < size:
    info = temp[i].split(",")
    names[i] = info[0]
    scores[i] = int(info[1])
    i += 1

print("names =", names)
print("scores =", scores)


# 문제 2) 아래 두 리스트 자료를
#         data 변수에 하나의 문자열로 연결하여 다음과 같이 저장하시오.
#         "박소리,97/안새롬,100/유철민,24"
names = ["박소리", "안새롬", "유철민"]
scores = [97, 100, 24]
data = ""

size = len(names)

i = 0
while i < size:
    data += names[i]
    data += ","
    data += str(scores[i])
    if i != size - 1:
        data += "/"
    i += 1
print(data)

108. 끝말잇기[문제]

# 끝말잇기 게임
# 제시어 : 자전거
# 입력 : 거미
# 제시어 : 거미
# 입력 : 미술
# ...

start = "자전거"
print("제시어 =", start)

정답

# 끝말잇기 게임
# 제시어 : 자전거
# 입력 : 거미
# 제시어 : 거미
# 입력 : 미술
# ...

start = "자전거"
print(start[-1])

while True:
    print("제시어 =", start)

    answer = start[-1]

    my_word = input(": ")
    my_answer = my_word[0]

    if answer == my_answer:
        start = my_word
start = "자전거"

while True :


    print("제시어 =", start)

    size = len(start)

    value = input("입력 : ")

    if start[size-1] == value[0] :

        start = value
        continue

109. 타자연습 게임[1단계]

# 타자연습 게임[1단계]
# 1. 문제를 섞는다.(shuffle)
# 2. 순서대로 문제를 출제하고, 문제를 다 맞추면 게임 종료
# 예)
# 문제 : mysql
# 입력 : mydb
# 문제 : mysql
# 입력 : mysql	<--- 정답을 맞추면, 다음 문제 제시
# 문제 : jsp

words = ["java", "mysql", "jsp", "spring"]

정답

# 타자연습 게임[1단계]
# 1. 문제를 섞는다.(shuffle)
# 2. 순서대로 문제를 출제하고, 문제를 다 맞추면 게임 종료
# 예)
# 문제 : mysql
# 입력 : mydb
# 문제 : mysql
# 입력 : mysql	<--- 정답을 맞추면, 다음 문제 제시
# 문제 : jsp

import random

words = ["java", "mysql", "jsp", "spring"]

size = len(words)

# shuffle
i = 0
while i < size:
    r = random.randint(0, size - 1)

    temp = words[0]
    words[0] = words[r]
    words[r] = temp

    i += 1
# print(words)

# 게임시작
count = 0
while count != size:
    print("문제 :", words[count])

    my_word = input("입력 : ")

    if words[count] == my_word:
        print("정답")
        count += 1
    else:
        print("땡")
import random

words = ["java", "mysql", "jsp", "spring"]


#shuffle

i = 0

while i < len(words):

    r = random.randint(0,3)

    temp = words[r]
    words[r] = words[0]
    words[0] = temp

    i+=1



i = 0

while i < len(words):
    answer = words[i]
    print(f"문제 : {answer}")
    my_answer = input("입력 : ")
    if words[i] == my_answer :
        i+=1
        continue

110. 타자연습게임(2단계)[문제] [다시]

# 타자연습 게임[2단계]
# 1. 문제를 섞는다.(shuffle)
# 2. 순서대로 문제를 출제하고, 문제를 다 맞추면 게임 종료
# 3. 단 문제를 출제할 때, 단어의 랜덤한 위치 한 곳만 *로 출력
# 예)
# 문제 : mys*l
# 입력 : mysql	<--- 정답을 맞추면, 다음 문제 제시
# 문제 : *sp
# 입력 : jsp
# ...

words = ["java", "mysql", "jsp", "spring"]

정답

import random

words = ["java", "mysql", "jsp", "spring"]

#-------------------------------------------------
# "java"의 "j"를 출력
#-------------------------------------------------

size = len(words)

# shuffle
i = 0
while i < size:
    r = random.randint(0, size - 1)

    temp = words[0]
    words[0] = words[r]
    words[r] = temp

    i += 1
# print(words)

i = 0

while i < len(words):

    r = random.randint(0,len(words[i])-1)

    j = 0

    print("문제 : ",end="")

    while j < len(words[i]) :

        if j != r :

            print(words[i][j],end="")

        else :

            print("*",end="")

        j+=1

    print()

    my_answer = input("입력 : ")

    if words[i] == my_answer :
        i+=1
        continue
import random

words = ["java", "mysql", "jsp", "spring"]

#-------------------------------------------------
# "java"의 "j"를 출력
print(words[0][0])
#-------------------------------------------------

size = len(words)

# shuffle
i = 0
while i < size:
    r = random.randint(0, size - 1)

    temp = words[0]
    words[0] = words[r]
    words[r] = temp

    i += 1
# print(words)

# 게임시작
count = 0
while count != size:
    length = len(words[count])
    r = random.randint(0, length-1)

    print("문제 = ", end="")
    i = 0
    while i < length:
        if i != r:
            print(words[count][i], end="")
        else:
            print("*", end="")
        i += 1
    print()


    my_word = input(": ")
    if my_word == words[count]:
        count += 1

주의사항 및 Tip

‘str’ object does not support item assignment : str 개체는 항목할당을 지원하지 않습니다.

string 개체도 배열형태여서 print(a[1])을 하면 “요” 가 나오지만, string 개체는 항목할당을 지원하지 않기 때문에 a[0]=”김”을 넣을수 없다.

a=[“정요섭”] 이라고 할때 a[0]=”정요섭” , a[0][0]=”정” , a[0][1]=”요” 이다

a = "정요섭"

a[0] = "김"

print(a) # 'str' object does not support item assignment

b = [0]

b[0] ="안녕"

print(b) # [안녕]

111. 파일쓰기:연습문제1[문제]

# ex111_문제.py

# 파일 쓰기 : 연습문제1

# 김철수/20,이만수/30,이영희/40

names = ["김철수", "이만수", "이영희"]
ages  = [     20,       30,      40]

# 숫자 => 문자
str_age = str(ages[0])
print(str_age)
print(type(str_age))

file_name = "file_ex01.txt"
data = ""

정답

# ex111_정답.py

# 파일 쓰기 : 연습문제1

# 김철수/20,이만수/30,이영희/40

names = ["김철수", "이만수", "이영희"]
ages  = [     20,       30,      40]

# 숫자 => 문자
str_age = str(ages[0])
print(str_age)
print(type(str_age))

file_name = "file_ex01.txt"
data = ""

#-----------------------------------------
i = 0
while i < len(names):
    data += names[i]
    data += "/"
    data += str(ages[i])

    if i != len(names) - 1:
        data += ","
    i += 1

print(data)
#-----------------------------------------

f = open(file_name, "wt")
f.write(data)
f.close()

112. 파일쓰기:연습문제2[문제]

# ex112_문제.py

# 파일 쓰기 : 연습문제2

# momk/1111/20000
# megait/2222/30000
# github/3333/40000

names  = ["momk", "megait", "github"]
ages   = ["1111",   "2222",   "3333"]
moneys = [ 20000,    30000,    40000]

file_name = "file_ex02.txt"
data = ""

정답

# ex112_정답.py

# 파일 쓰기 : 연습문제2

# momk/1111/20000
# megait/2222/30000
# github/3333/40000

names  = ["momk", "megait", "github"]
ages   = ["1111",   "2222",   "3333"]
moneys = [ 20000,    30000,    40000]

file_name = "file_ex02.txt"
data = ""

#----------------------------------------------
i = 0
while i < len(names):
    data += names[i]
    data += "/"
    data += str(ages[i])
    data += "/"
    data += str(moneys[i])

    if i != len(names) - 1:
        data += "\n"
    i += 1
print(data)
#----------------------------------------------
f = open(file_name, "wt")
f.write(data)
f.close()

113. 파일 읽기[문제]

# ex113_문제.py

# 파일 읽기 : 연습문제

ids = []
pws = []
moneys = []

file_name = "file_ex02.txt"

정답

# ex113_정답.py

# 파일 읽기 : 연습문제

import os

ids = []
pws = []
moneys = []

file_name = "file_ex02.txt"

if os.path.exists(file_name):
    f = open(file_name, "rt")
    data = f.read()
    f.close()

    print(data)

    temp = data.split("\n")
    size = len(temp)

    i = 0
    while i < size:
        info = temp[i].split("/")

        ids.append(info[0])
        pws.append(info[1])
        moneys.append(int(info[2]))
        i += 1
else:
    print("파일을 불러올 수 없습니다.")

print("ids =", ids)
print("pws =", pws)
print("moneys =", moneys)

114. 파일 컨트롤러(1단계) : 리스트[문제] [다시, 함수O 과 함수 X 인 방법 모두 해보자]

# ex114_문제.py

# 파일 컨트롤러[1단계] : 리스트

vector = []
count = 0

file_name = "list.txt"

while True:
    print("[리스트 컨트롤러]")
    print("[1]추가하기")
    print("[2]삭제하기")
    print("[3]저장하기")
    print("[4]로드하기")
    print("[5]종료하기")

    sel = int(input("메뉴 선택 : "))
    if sel == 1:
        pass
    elif sel == 2:
        pass
    elif sel == 3:
        pass
    elif sel == 4:
        pass
    elif sel == 5:
        print("프로그램 종료")
        break

정답

# ex114_정답.py

# 파일 컨트롤러[1단계] : 리스트

import os

vector = []
count = 0

file_name = "list.txt"

while True:
    # 요소 출력
    i = 0
    while i < count:
        print(vector[i], end=" ")
        i += 1
    print()
    # 메뉴 출력
    print("[리스트 컨트롤러]")
    print("[1]추가하기")
    print("[2]삭제하기")
    print("[3]저장하기")
    print("[4]로드하기")
    print("[5]종료하기")

    sel = int(input("메뉴 선택 : "))
    if sel == 1:
        add_num = int(input("추가할 값 입력 : "))
        vector.append(add_num)
        count += 1
    elif sel == 2:
        del_num = int(input("삭제할 값 입력 : "))

        del_idx = -1
        i = 0
        while i < count:
            if vector[i] == del_num:
                del_idx = i
            i += 1

        if del_idx == -1:
            print("입력 오류!")
        else:
            temp = vector

            vector = [0 for i in range(count - 1)]
            j = 0
            i = 0
            while i < count:
                if i != del_idx:
                    vector[j] = temp[i]
                    j += 1
                i += 1
            count -= 1
    elif sel == 3:
        data = ""
        i = 0
        while i < count:
            data += str(vector[i])
            if i != count - 1:
                data += ","
            i += 1

        f = open(file_name, "wt")
        f.write(data)
        f.close()
        print("파일을 저장하였습니다.")
    elif sel == 4:
        if os.path.exists(file_name):
            f = open(file_name, "rt")
            data = f.read()
            f.close()

            temp = data.split(",")
            count = len(temp)

            vector = [0 for i in range(count)]

            i = 0
            while i< count:
                vector[i] = int(temp[i])
                i += 1
            print("파일을 불러왔습니다.")
        else:
            print("파일을 불러올 수 없습니다.")
    elif sel == 5:
        print("프로그램 종료")
        break

115. 파일 컨트롤러(2단계) : ATM[문제]

# ex115_문제.py

# 파일 컨트롤러[2단계] : ATM

size = 5
count = 0
log = -1

accs = ["" for i in range(size)]
pws = ["" for i in range(size)]
moneys = [0 for i in range(size)]

file_name = "atm.txt"

while True:
    print("[MEGA ATM]")
    print("[1]회원가입")
    print("[2]회원탈퇴")
    print("[3]로그인")
    print("[4]로그아웃")
    print("[5]입금")
    print("[6]출금")
    print("[7]이체")
    print("[8]잔액조회")
    print("[9]저장")
    print("[10]로드")
    print("[0]종료")

    sel = int(input("메뉴 선택 : "))

    if sel == 1:
        pass
    elif sel == 2:
        pass
    elif sel == 3:
        pass
    elif sel == 4:
        pass
    elif sel == 5:
        pass
    elif sel == 6:
        pass
    elif sel == 7:
        pass
    elif sel == 8:
        pass
    elif sel == 9:
        pass
    elif sel == 10:
        pass
    elif sel == 0:
        print("프로그램 종료")
        break

정답

# ex115_정답.py

# 파일 컨트롤러[2단계] : ATM

import os

size = 5
count = 0
log = -1

accs = ["" for i in range(size)]
pws = ["" for i in range(size)]
moneys = [0 for i in range(size)]

file_name = "atm.txt"

while True:
    if log == -1:
        print("로그아웃 상태")
    else:
        print(accs[log], "님, 로그인 중")
    i = 0
    while i < count:
        print(accs[i], ":", pws[i], ":", moneys[i])
        i += 1

    print("[MEGA ATM]")
    print("[1]회원가입")
    print("[2]회원탈퇴")
    print("[3]로그인")
    print("[4]로그아웃")
    print("[5]입금")
    print("[6]출금")
    print("[7]이체")
    print("[8]잔액조회")
    print("[9]저장")
    print("[10]로드")
    print("[0]종료")

    sel = int(input("메뉴 선택 : "))

    if sel == 1:
        if count == 5:
            print("더이상 가입할 수 없습니다.")
        else:
            my_acc = input("계좌번호 입력 : ")
            my_pw = input("비밀번호 입력 : ")

            accs[count] = my_acc
            pws[count] = my_pw
            moneys[count] = 1000

            count += 1
            print("회원가입을 축하합니다.")
    elif sel == 2:
        if log != -1:
            i = log
            while i < count-1:
                accs[i] = accs[i + 1]
                pws[i] = pws[i + 1]
                moneys[i] = moneys[i + 1]
                i += 1
            count -= 1

            log = -1
            print("탈퇴되었습니다.")
        else:
            print("로그인 후 이용해주세요.")
    elif sel == 3:
        if log == -1:
            my_acc = input("계좌번호 입력 : ")
            my_pw = input("비밀번호 입력 : ")

            i = 0
            while i < count:
                if accs[i] == my_acc and pws[i] == my_pw:
                    log = i
                i += 1
            if log == -1:
                print("계좌번호와 비밀번호를 확인해주세요")
        else:
            print(accs[log], "님, 로그인 중..")
    elif sel == 4:
        if log != -1:
            log = -1
            print("로그아웃 되었습니다.")
        else:
            print("로그인 후 이용해주세요.")
    elif sel == 5:
        if log != -1:
            my_money = int(input("입금할 금액 입력 : "))

            moneys[log] += my_money
            print("입금을 완료하였습니다.")
        else:
            print("로그인 후 이용해주세요.")
    elif sel == 6:
        if log != -1:
            my_money = int(input("출금할 금액 입력 : "))

            if moneys[log] >= my_money:
                moneys[log] -= my_money
                print("출금을 완료하였습니다.")
            else:
                print("계좌잔액이 부족합니다.")
        else:
            print("로그인 후 이용해주세요.")
    elif sel == 7:
        if log != -1:
            check = -1
            your_acc = input("이체할 계좌번호 입력 : ")
            i = 0
            while i < count:
                if accs[i] == your_acc:
                    check = i
                i += 1

            if check == -1:
                print("계좌번호를 확인해주세요.")
            else:
                money = int(input("이체할 금액을 입력하세요 : "))
                if moneys[log] >= money:
                    moneys[log] -= money
                    moneys[check] += money
                    print("이체를 완료하였습니다.")
                else:
                    print("계좌잔액이 부족합니다.")
        else:
            print("로그인 후 이용해주세요.")
    elif sel == 8:
        if log != -1:
            print(moneys[log], "원")
        else:
            print("로그인 후 이용해주세요.")
    elif sel == 9:
        data = ""
        data += str(count)
        data += "\n"

        i = 0
        while i < count:
            data += accs[i]
            data += ","
            data += pws[i]
            data += ","
            data += str(moneys[i])
            if i != count - 1:
                data += "\n"
            i += 1

        f = open(file_name, "wt")
        f.write(data)
        f.close()
        print("파일을 저장하였습니다.")
    elif sel == 10:
        if os.path.exists(file_name):
            f = open(file_name, "rt")
            data = f.read()
            f.close()
            temp = data.split("\n")

            count = int(temp[0])

            accs = [0 for i in range(count)]
            pws = [0 for i in range(count)]
            moneys = [0 for i in range(count)]

            i = 0
            while i < count:
                info = temp[i + 1].split(",")

                accs[i] = info[0]
                pws[i] = info[1]
                moneys[i] = int(info[2])

                i += 1
            print("파일을 불러왔습니다.")
        else:
            print("파일을 불러올 수 없습니다.")
    elif sel == 0:
        print("프로그램 종료")
        break

116. 파일 컨트롤러(3단계) : 장바구니[문제]

# ex116_문제.py

# 파일 컨트롤러[3단계] : 장바구니

ids = ["qwer", "python", "abcd"]
pws = ["1111",   "2222", "3333"]

items = ["사과", "바나나", "딸기"]

max_size = 100
jang = [[0] * 2 for i in range(max_size)]

count = 0

log = -1

file_name = "jang.txt"

while True:
    print("[MEGA SHOP]")
    print("[1]로그인")
    print("[2]로그아웃")
    print("[3]쇼핑")
    print("[4]장바구니")
    print("[5]저장")
    print("[6]로드")
    print("[0]종료")

    sel = int(input("메뉴 선택 : "))
    if sel == 1:
        pass
    elif sel == 2:
        pass
    elif sel == 3:
        pass
    elif sel == 4:
        pass
    elif sel == 5:
        pass
    elif sel == 6:
        pass
    elif sel == 0:
        print("프로그램 종료")
        break

정답

# ex116_정답.py

# 파일 컨트롤러[3단계] : 장바구니

import os

ids = ["qwer", "python", "abcd"]
pws = ["1111",   "2222", "3333"]

items = ["사과", "바나나", "딸기"]

max_size = 100
jang = [[0] * 2 for i in range(max_size)]

count = 0

log = -1

file_name = "jang.txt"

while True:
    i = 0
    while i < count:
        print(jang[i][0], ":", jang[i][1])
        i += 1

    print("[MEGA SHOP]")
    print("[1]로그인")
    print("[2]로그아웃")
    print("[3]쇼핑")
    print("[4]장바구니")
    print("[5]저장")
    print("[6]로드")
    print("[0]종료")

    sel = int(input("메뉴 선택 : "))
    if sel == 1:
        if log == -1:
            my_id = input("아이디 입력 : ")
            my_pw = input("패스워드 입력 : ")

            i = 0
            while i < len(ids):
                if ids[i] == my_id and pws[i] == my_pw:
                    log = i
                i += 1
            if log == -1:
                print("[메세지]ID와 PW를 확인해주세요")
            else:
                print(ids[log], "님, 환영합니다.")
        else:
            print("[메세지]현재", ids[log], "님, 로그인 중...")
    elif sel == 2:
        if log != -1:
            log = -1
            print("[메세지]로그아웃 되었습니다.")
        else:
            print("[메세지]로그인 후 이용해주세요")
    elif sel == 3:
        if log != -1:
            while True:
                i = 0
                while i < len(items):
                    print(i+1, items[i])
                    i += 1
                print("0 종료")

                choice = int(input("상품을 선택하세요."))
                if choice == 0:
                    break
                else:
                    jang[count][0] = log
                    jang[count][1] = choice

                    count += 1
        else:
            print("[메세지]로그인 후 이용해주세요")
    elif sel == 4:
        if log != -1:
            apple_cnt = 0
            banana_cnt = 0
            berry_cnt = 0
            print("log =", log)
            i = 0
            while i < count:
                if jang[i][0] == log:
                    if jang[i][1] == 1:
                        apple_cnt += 1
                    elif jang[i][1] == 2:
                        banana_cnt += 1
                    elif jang[i][1] == 3:
                        berry_cnt += 1
                i += 1
            print("사과 =", apple_cnt)
            print("바나나 =", banana_cnt)
            print("딸기 =", berry_cnt)
        else:
            print("[메세지]로그인 후 이용해주세요")
    elif sel == 5:
        data = ""

        data += str(count)
        data += "\n"

        i = 0
        while i < count:
            data += str(jang[i][0])
            data += "/"
            data += str(jang[i][1])

            if i != count - 1:
                data += "\n"
            i += 1

        f = open(file_name, "wt")
        f.write(data)
        f.close()

        print("[메세지]파일을 저장하였습니다.")
    elif sel == 6:
        if os.path.exists(file_name):
            f = open(file_name, "rt")
            data = f.read()
            f.close()

            temp = data.split("\n")

            count = int(temp[0])

            i = 0
            while i < count:
                info = temp[i + 1].split("/")

                jang[i][0] = int(info[0])
                jang[i][1] = int(info[1])
                i += 1
    elif sel == 0:
        print("프로그램 종료")
        break

117. [07] 달팽이 [다시]

size = 5
arr = [[0]*size for i in range(size)]
check = [[0]*size for i in range(size)]
x = 0
y = 0
dir = 1
num = 1
arr[y][x] = num
check[y][x] = True

정답

size = 5
arr = [[0]*size for i in range(size)]
check = [[0]*size for i in range(size)]
x = 0
y = 0
dir = 1
num = 1
arr[y][x] = num
check[y][x] = True
for i in range(size*size-1):
    num += 1
    xx = x
    yy = y
    if dir == 1:
        xx = x + 1
    elif dir == 2:
        yy = y + 1
    elif dir == 3:
        xx = x - 1
    elif dir == 4:
        yy = y - 1
    if xx >= size  or xx < 0 or yy >= size or yy < 0  or check[yy][xx] == True:

        #예외인 순간에는 바뀌지 않은값을 다시 넣어주고 방향을 바꿔준다.
        xx = x
        yy = y
        dir += 1
        if dir == 5:
            dir = 1
        if dir == 1:
            xx = x + 1
        elif dir == 2:
            yy = y + 1

        elif dir == 3:
            xx = x - 1
        elif dir == 4:
            yy = y - 1

    arr[yy][xx] = num
    x = xx
    y = yy
    check[y][x] = True
    print(y , " , " , x)
for i in range(size):
    for j in range(size):
        pass
    print(arr[i])

주의사항 및 Tip

방향이 틀어지는 조건을 잘 알아야한다

첫째, xx>=size일때, 즉 배열보다 xx가 클때는 더이상 오른쪽으로 가지 못하게 방향을 틀어 아래로 내려가야한다 둘째, yy>=size일때, 즉 배열보다 yy사 클때는 더이상 아래로 내려가지 못하게 방향을 틀어왼쪽으로 가야한다 셋째, xx<0 일때, 즉 xx가 0보다 작을때는 더이상 왼쪽으로 가지 못하게 방향을 틀어 위로 올라가야한다 넷째, yy가 <0일떄 즉 yy가 0보다 작을때는 더이상 위로 가지 못하게 해야한다 다섯쨰, 이미 앞에 check가 되어있는경우 방향을 틀어야한다

이 모든 조건을 만족하는것이 다음코드이다

 if xx >= size  or xx < 0 or yy >= size or yy < 0  or check[yy][xx] == True:

        xx = x
        yy = y
        dir += 1
        if dir == 5:
            dir = 1
        if dir == 1:
            xx = x + 1
        elif dir == 2:
            yy = y + 1

        elif dir == 3:
            xx = x - 1
        elif dir == 4:
            yy = y - 1

118. [08] 나만의 마블 [다시]

size = 5
check = [
         [0,  1, 2, 3, 4],
         [15,"", "", "", 5],
         [14,"", "", "", 6],
         [13,"", "", "", 7],
         [12,11,10,9,8]]
player = 0

정답

size = 5
check = [
         [0,  1, 2, 3, 4],
         [15,"", "", "", 5],
         [14,"", "", "", 6],
         [13,"", "", "", 7],
         [12,11,10,9,8]]
player = 0
while True:
    for i in range(size):
        for n in range(size):
            if check[i][n] == player:
                print("★" ,end="")
            elif(check[i][n] == ""):
                print("■" ,end="")
            else:
                print("□",end="")
        print()
    sel = int(input("1~3 일 입력하세요"))
    player += sel
    player %= 15

주의사항 및 Tip

이 문제는 판의 숫자가 적힌것에 따라 플에이어의 위치가 표시가 되는것이다.

119. 게시판[문제] [다시, 답이 없고 모르겠음]

# 게시판
# 1. [이전] 또는 [이후] 버튼을 누르면 페이지 번호가 변경된다.
# 2. 현재 페이지 번호에 해당되는 게시글만 확인 및 삭제가 가능하다.
# 3. 2차원 리스트 board_list에 0열에는 제목을, 1열에는 게시글의 내용을 저장한다.
# 4. 게시글이 추가되고 삭제될 때마다 데이터가 바로 저장된다.
# 5. 실행시 저장되어 있는 파일이 존재한다면, 바로 파일을 불러오도록 설계한다.

board_list = []

count = 0         # 전체 게시글 수
page_size = 3     # 한 페이지에 보여줄 게시글 수
cur_page_num = 1  # 현재 페이지 번호
page_count = 0    # 전체 페이지 수
start_row = 0     # 현재 페이지의 게시글 시작번호
end_row = 0       # 현재 페이지의 게시글 마지막번호

file_name = "board.txt"

while True:
    print("[게시판]")
    print("[1] 이전")
    print("[2] 이후")
    print("[3] 추가하기")
    print("[4] 삭제하기")
    print("[5] 내용확인")

    sel = int(input("메뉴 선택 : "))
    if sel == 1:
        pass
    elif sel == 2:
        pass
    elif sel == 3:
        pass
    elif sel == 4:
        pass
    elif sel == 5:
        pass

정답


120. 딕셔너리 컨트롤러[문제] [다시]

# 딕셔너리와 리스트

studentList = []
info = {"이름":"김철수", "수학":100, "국어":32}
studentList.append(info)

info = {"이름":"이만수", "수학":11, "국어":84}
studentList.append(info)

info = {"이름":"박영희", "수학":95, "국어":58}
studentList.append(info)

while True:
    print("[1]추가")
    print("[2]삭제")
    print("[3]정렬")
    print("[4]출력")
    print("[5]종료")

    sel = int(input("메뉴 선택 : "))

    if sel == 1:
        pass
    elif sel == 2:
        pass
    elif sel == 3:
        pass
    elif sel == 4:
        pass
    elif sel == 5:
        break

정답

# 딕셔너리와 리스트

studentList = []
info = {"이름":"김철수", "수학":100, "국어":32}
studentList.append(info)

info = {"이름":"이만수", "수학":11, "국어":84}
studentList.append(info)

info = {"이름":"박영희", "수학":95, "국어":58}
studentList.append(info)

while True:
    for i in range(len(studentList)):
        print(studentList[i])
    print()

    print("[1]추가")
    print("[2]삭제")
    print("[3]정렬")
    print("[4]출력")
    print("[5]종료")

    sel = int(input("메뉴 선택 : "))

    if sel == 1:
        name = input("추가할 이름 입력 : ")
        math = int(input("수학성적 입력: "))
        kor = int(input("국어성적 입력 : "))

        temp = {}
        temp["이름"] = name
        temp["수학"] = math
        temp["국어"] = kor

        studentList.append(temp)
    elif sel == 2:
        del_name = input("삭제할 이름 입력 : ")

        # 삭제할 인덱스 검색
        del_idx = -1
        for i in range(len(studentList)):
            if studentList[i]["이름"] == del_name:
                del_idx = i
        if del_idx == -1:
            print("이름을 다시 확인해주세요.")
            continue

        # 삭제
        temp = studentList
        studentList = []

        for i in range(len(temp)):
            if i != del_idx:
                studentList.append(temp[i])
    elif sel == 3:
        for i in range(len(studentList)):
            min_name = studentList[i]["이름"]
            min_idx = i
            for j in range(i, len(studentList)):
                if min_name > studentList[j]["이름"]:
                    min_name = studentList[j]["이름"]
                    min_idx = j
            temp = studentList[i]
            studentList[i] = studentList[min_idx]
            studentList[min_idx] = temp

    elif sel == 4:
        for i in range(len(studentList)):
            print("이름 : %s\t수학 : %d점\t국어 : %d점\t" % (studentList[i]["이름"], studentList[i]["수학"], studentList[i]["국어"]))
    elif sel == 5:
        break

주의사항 및 Tip

정렬방법이 어떤방식으로 진행이 되는지에 대해서 알아야한다

가장 작은값이 자기 자신일때 for문이 돌지않게 짜지않도록 조심하자

info를 추가할때 info={}를 해주고 추가하지 않을시에는 맨 마지막 info의 이름 점수들이 수정된다

# 딕셔너리 수정 방법

a = {"나":"요섭"}

a["나"] = "요셉셉"

print(a) #{"나" : "요셉셉"}

Leave a comment