티스토리 뷰

키즈 노트

키즈노트 #2 2진법 to 10진법 계산

오리지날초이 2023. 11. 22. 16:43
import random
import sys

def decimal_to_binary(decimal_number):
    binary_number = bin(decimal_number)[2:]  # '0b'를 제거한 2진수 변환
    return binary_number

def explain_decimal_composition(decimal_number):
    explanation = ""
    digits = str(decimal_number) #196

    for i, digit in enumerate(digits):
        if i == len(digits) - 1: # 3-1 == 2 
            explanation += f"{int(digit)}*1"
        else:
            explanation += f"{int(digit)}*10^{len(digits) - i - 1}"

        if i < len(digits) - 1:
            explanation += " + "

    return explanation

def explain_binary_composition(decimal_number):
    binary_number = bin(decimal_number)[2:]  # '0b' 제거
    explanation = ""
    length = len(binary_number)

    for i, bit in enumerate(binary_number):

        if i == length - 1:
            explanation += f"{bit}*1"
        else:
            explanation += f"{bit}*2^{length - i - 1}"

        if i < length - 1:
            explanation += " + "
    return explanation


print("안녕~~ 친구들~~~ 내가 또 왔어~")
print("나는 이 세상에서 컴퓨터를 가장 잘하는 오리지날초이라네")
name = input("너의 이름은 뭐였더라? ")

print(f"\n하하 안녕 {name}! 내가 너를 까먹었을리 없지\n넌 나의 첫번째 퀴즈를 맞춘 유일한 사람인걸")
print("이번엔 훨씬 더 어려운 문제를 내주도록 하지 크크크..")

nono = input("문제를 계속 풀겠어? ")

print("\n난 1부터 999까지 중에서 랜덤 숫자를 너에게 알려주겠어")

random_decimal = random.randint(1, 1000)
print(f"자 나의 랜덤 숫자는 {random_decimal} 야")

composition_explanation = explain_decimal_composition(random_decimal)
print("사실 이 숫자는 말이야 이렇게 풀이할 수 있지")
print(composition_explanation)
print("ok. 여기까진 쉽지?")
none = input()

print("\n진짜 문제는 이거라구\n")

random_decimal = random.randint(1, 100)
print(f"이번엔 1부터 99까지 중에서 랜덤 숫자 {random_decimal} 이야")

composition_explanation = explain_binary_composition(random_decimal)
print(f"{random_decimal}을 2의 자리로 계산하면 이렇게 할 수 있지")
print(composition_explanation)

print(f"그래서 10의 자리 숫자 {random_decimal} 을 2의 자리 숫자로 바꾸면 ")
print(bin(random_decimal)[2:], " 로 바꿀 수 있지. 훗.")
none = input("이해가 돼? ")

print("\n이제 진짜 문제야. 너에게 3번의 기회를 줄게.")

random_decimal = random.randint(1, 100)
bin_answer = bin(random_decimal)[2:]

for i in range(1, 4):
    print(f"\n2의 자리 숫자 {bin_answer} 를 10의 자리숫자로 바꿔봐라!!")
    answer = input("정답 : ")

    if int(answer) == random_decimal:
        print("저저저.. 정답이라니... 놀랍다...")
        print("너의 승리다...")
        none = input()    
        sys.exit(1)
    else:
        print("후후후.. 짱 어렵지?")
        print(f"{i}번 실패하고 {3 - i}번 기회가 남았다.")

    if i == 3:
        print(f"후후 결국 내가 이겼군. 정답은 {random_decimal} 이었다구!")
        composition_explanation = explain_binary_composition(random_decimal)
        print(f"{composition_explanation} 을 계산해 보라구") 

        print("나의 승리다 하하하하하")
        none = input()    
        sys.exit(1)

 

728x90
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함