Tuesday, December 31, 2019

1000 simulations of the Monty Hall problem (Python)

The Monty Hall problem was popularized as part of a television game show called "Let's Make a Deal" and named after its original host, Monty Hall.

In the show, there is a host and a player. There are 3 doors on the set. One has a car behind it and the other two have a goat each, behind them. Only the host knows where the car is and where the goats are.

The player was asked to guess behind which door the car was. Let's say he picked Door 1. That means that either Door 2 or Door 3 or both has a goat behind it.




The host, who knew what was behind each of the doors, opens one of the 2 doors not chosen, behind which he knew there was a goat. Let's say he opened Door 3.





So, there were 2 closed doors left; one with a goat and another with a car. The host gave the player the opportunity to stick to his original choice of Door 1 or switch to Door 2. What do you think the player should do - stick to their initial choice or should they switch?


It would be advantageous to the player to switch to the door which was not chosen nor opened, because as shown, it now has the combined probability of 2 doors.

Although there is no certainty that a switch is always advantageous, in the long run, it would be so.

This can be demonstrated through a Python script that simulates a 1000 trials of the Monty Hall problem. 

from random import randint
wins, losses = 0, 0

print("In our 1000 simulations, we assume that the player always switches doors.")
print("Hence, if car and choice are the same, he loses by switching.")
print("In all other cases, he wins.\n")
input("Press any key to continue\n=========================")

print("Car Choice Wins Losses")
print("=== ====== ==== ======")

for i in range(1000):
  list1 = list2 = [1, 2, 3]
  car, choice = randint(1, 3), randint(1, 3)
  print("%2d%5d" % (car, choice), end='')
  
  if car == choice:
    losses += 1
  else:
    wins += 1
  print("%7d%7d" % (wins, losses))

print("            |      |")
print("            v      v")
print("           Wins  Losses")

if wins > losses:
  print("The wins is greater than the losses. Shows that switching is advantageous.")
else:
  print("This turn of events was not expected.")

OUTPUT 


 :    :    :::    :::
 :    :    :::    :::
 :    :    :::    :::
 :    :    :::    :::

 1    1    668    330
 3    3    668    331
 3    1    669    331
            |      |
            v      v
            Wins   Losses

The figures vary slightly from execution to execution. Output reveals that switching is advantageous over sticking to the original choice.

Wednesday, November 20, 2019

Day of the week in Python

D = int(input("Enter day: "))
M = int(input("Enter month number: "))
Y = int(input("Enter year: "))
MCode = [0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5]
CCode = [6, 4, 2, 0, 6]      # 1600-1699, 1700-1799, etc.
Days = ["Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday"]
C = (Y // 100) % 16          # C -> Century

num = D + MCode[M-1] + (Y%100) + ((Y%100)//4) + CCode[C]
print(Days[num%7])

Explanation below


Inputs
Output
Month Codes
Century Codes
Day Codes
January
0
1600 - 1699
6
Sunday
0
February
3
1700 - 1799
4
Monday
1
March
3
1800 - 1899
2
Tuesday
2
April
6
1900 - 1999
0
Wednesday
3
May
1
2000 - 2199
6
Thursday
4
June
4


Friday
5
July
6


Saturday
6
August
2




September
5




October
0




November
3




December
5





11 – 08 – 1966
(Day +MCode + Last 2 digits of year + Last 2 digits of year // 4 + CCode) % 7
(11   +      2      +             66                   +                66                // 4 +     0) % 7
(11   +      2      +             66                   +                           16             +     0) % 7
95 % 7 = 13 4/7
4 (Thursday)


Wednesday, November 6, 2019

Text-based Hangman in Python

import random
from idlecolors import *

L = ['education', 'residence', 'conveying', 'Suppose', 'shyness', 'behaved', 'morning', 'unsatiable', 'assistance', 'compliment', 'occasional',
     'reasonably', 'advantages', 'Unpleasing', 'acceptance', 'partiality', 'alteration', 'understood', 'Worth', 'tiled', 'house', 'added', 'Married',
     'hearing', 'totally', 'removal', 'Remove', 'suffer', 'wanted', 'lively', 'length', 'Moonlight', 'applauded', 'conveying', 'direction',
     'principle', 'expenses', 'distance', 'weddings', 'perceive', 'strongly', 'domestic', 'Effects', 'present', 'letters', 'inquiry', 'removed',
     'friends', 'Desire', 'behind', 'latter', 'though', 'Supposing', 'shameless', 'engrossed', 'additions', 'possible', 'peculiar', 'together',
     'Desire', 'better', 'cannot', 'before', 'points', 'Remember', 'mistaken', 'opinions', 'pleasure', 'debating', 'Court', 'front', 'maids',
     'forty', 'aware', 'their', 'Chicken', 'pressed', 'removed', 'Sudden', 'looked', 'elinor', 'estate', 'silent', 'extent', 'entire', 'Curiosity',
     'remaining', 'repulsive', 'household', 'advantage', 'additions', 'Supposing', 'exquisite', 'daughters', 'eagerness', 'repulsive', 'Praise',
     'turned', 'lovers', 'warmly', 'Little', 'eldest', 'former', 'decisively', 'impression', 'attachment', 'friendship', 'everything', 'Whose',
     'enjoy', 'chief', 'young', 'Felicity', 'required', 'likewise', 'doubtful', 'attention', 'necessary', 'provision', 'otherwise', 'existence',
     'direction', 'Unpleasing', 'announcing', 'unpleasant', 'themselves', 'advantage', 'listening', 'belonging', 'supposing', 'Invitation',
     'excellence', 'imprudence', 'understood', 'continuing', 'Fifteen', 'winding', 'related', 'hearted', 'colonel', 'studied', 'County', 'suffer',
     'twenty', 'marked', 'moment', 'Valley', 'silent', 'cannot', 'things', 'remain', 'merits', 'season', 'better', 'tended', 'hunted', 'sometimes',
     'behaviour', 'contented', 'listening', 'eagerness', 'objection', 'collected', 'Together', 'feelings', 'continue', 'juvenile', 'Unknown',
     'service', 'subject', 'letters', 'Child', 'noise', 'forty', 'entrance', 'disposal', 'bachelor', 'remember', 'relation', 'Unpacked', 'declared',
     'confined', 'daughter', 'improved', 'Celebrated', 'imprudence', 'interested', 'especially', 'reasonable', 'Wonder', 'family', 'secure',
     'Depend', 'repair', 'before', 'admire', 'observe', 'covered', 'delight', 'hastily', 'message', 'ladyship', 'endeavor', 'settling',
     'Marianne', 'husbands', 'stronger', 'Considered', 'middletons', 'uncommonly', 'Promotion', 'perfectly', 'consisted', 'chatty', 'dining',
     'effect', 'ladies', 'active', 'Equally', 'journey', 'wishing', 'several', 'behaved', 'chapter', 'Deficient', 'procuring', 'favourite',
     'extensive', 'diminution', 'impossible', 'understood', 'stuff', 'think', 'jokes', 'Going', 'known', 'noise', 'wrote', 'round', 'leave',
     'Warmly', 'branch', 'people', 'narrow', 'Winding', 'waiting', 'parlors', 'married', 'feeling', 'Marry', 'fruit', 'spite', 'jokes', 'times',
     'Whether', 'unknown', 'warrant', 'herself', 'winding', 'Parties', 'brother', 'amongst', 'fortune', 'Twenty', 'behind', 'wicket', 'itself',
     'Consulted', 'perpetual', 'pronounce', 'delivered', 'months', 'change', 'relied', 'beauty', 'wishes', 'matter', 'Ignorant', 'dwelling',
     'occasion', 'thoughts', 'overcame', 'consider', 'Polite', 'depend', 'talked', 'effect', 'worthy', 'Household', 'shameless',
     'incommode', 'objection', 'behaviour', 'Especially', 'possession', 'insensible', 'sympathize', 'boisterous', 'Songs', 'widen', 'event',
     'truth', 'Certain', 'brother', 'sending', 'amongst', 'covered']

for i in range(len(L)):
  word = L[i].upper()
  del L[i]
  L.insert(i, word)

num = random.randint(0, len(L)-1)

word = L[num]
print(word)
length = len(word)
Word = word
word = list(word)
length = len(word)
guessword = ['_'] * length
misses = 0
available = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
played = ''
guess = ''

printc(red("Red ") + orange("Orange ") + green("Green ") + blue("Blue"))

while True:
  found = 'F'

  lineA = "                          _"
  lineB = "______                     "
  lineC = "                         |/"
  lineD = "      |                    " if misses > 0 else ""
  lineE = "                         | "
  lineF = "     (_)                   " if misses > 1 else ""
  lineG = "                         | "
  lineH = "     \|/                   " if misses > 2 else ""
  lineI = "                         | "
  lineJ = "      |                    " if misses > 3 else ""
  lineK = "                         | "
  lineL = "     / \\                  " if misses > 4 else ""

  print(lineA, end='');  print(lineB)
  print(lineC, end='');  printc(red(lineD))
  print(lineE, end='');  printc(red(lineF))
  print(lineG, end='');  printc(red(lineH))
  print(lineI, end='');  printc(red(lineJ))
  print(lineK, end='');  printc(red(lineL))

  print("                         |")
  print("                         |")
  print(" _                       |                     ")
  print("| |                      |                     ")
  print("| |__   __ _ _ __   ___  |_ __ __   __ _ _ __  ")
  print("| '_ \ / _` | '_ \ / _`\\ / '_ ` _ \/ _` | '_ \ ")
  print("| | | | (_| | | | | (_| | | | | | | (_| | | | |")
  print("|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|")
  print("                    __/ |                      ")
  print("                   |___/                     \n")
  
  if misses == 5:
    print("You have lost your 5 lives.")
    print("The word was '" + Word + "'")
    break

  if guess in available and guess not in played:
    played += guess
  played = sorted(played)
  played = str(played)
  #print(played)

  for i in available:
    if i not in played:
      print(i, end=' ')
    else:
      print(' ', end=' ')
  print('\n')
  
  for i in range(length):
    print(guessword[i] + " ", end='')
  guess = input("\n\nYou have " + str(5 - misses) + " lives left.\tEnter a character: ")
  guess = guess[0].upper()

  ctr = word.count(guess)
  for i in range(length):
    if word[i] == guess:
      guessword[i] = guess
      found = 'T'

  if found == 'F':
    misses += 1
  
  if guessword == word:
    for i in range(length):
      print(guessword[i] + " ", end='')
    print("\nGotcha")
    break

Friday, November 1, 2019

Thomas Answers in Dev C++

#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <windows.h>

void change_color(int color)
{ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);  }

int main()
{ char ch, str1[100] = "AI, please answer this question", str2[100], str3[100], question[100];
  int ctr1=0, ctr2=0, stop;
  change_color(3);
  
  do { ch = getch();
       str3[ctr1++] = ch;
       cout << str1[ctr1-1];
       if(ch == ',')
         ctr2 = -1;
       str2[ctr2++] = ch;
       if(ch == '.')
         stop = ctr2 - 1;
     } while(ch != 13 && ch != 27);

  if(ch == 27)
    return 0;

  str2[stop] = 0;
  str3[ctr1] = '\0';
  change_color(2); //128);
  cout << "\n\nOK, ask! \n\n";
  change_color(3);
  gets(question);
  
  if(ch == 13)
  { change_color(2);  //128);
    cout << "\n" << str2;
    getch();
  }
}

Rock Paper Scissors in C++ (Dev C++)

#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main()
{ srand(time(NULL));
  int CChoice, PChoice, CScore=0, PScore=0;
  char C[9], P[9], set[][9] = { { "Rock" }, { "Paper" }, { "Scissors" } };
  int GameNo=0;
  
  while(++GameNo <= 10)
  { CChoice = rand() % 3 + 1;
    cout << "Game " << GameNo << "\n";
    cout << "Enter 1 (ROCK), 2 (PAPER), 3 (SCISSORS), 0 (EXIT): ";
cin >> PChoice;
    if(PChoice == 0)
      return -1;
   
    cout << "C chose " << CChoice << "  (" << set[CChoice-1] << "). You chose " << PChoice << "  (" << set[PChoice-1] << ")\n";
    
    if(CChoice == 1)
    { if(PChoice == 1)
      { cout << "Both chose rock, draw\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
      else if(PChoice == 2)
      { PScore++;  cout << "Paper covers rock, you win\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
      else if(PChoice == 3)
      { CScore++;  cout << "Rock smashes scissors, you lose\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
    }
  
    if(CChoice == 2)
    { if(PChoice == 1)
      { CScore++;  cout << "Paper covers rock, you lose\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
      else if(PChoice == 2)
      { cout << "Both chose paper, draw\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
      else if(PChoice == 3)
      { PScore++;  cout << "Scissors cuts paper, you win\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
    }
  
    if(CChoice == 3)
    { if(PChoice == 1)
      { PScore++;  cout << "Rock smashes scissors, you win\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
      else if(PChoice == 2)
      { CScore++;  cout << "Scissors cuts paper, you lose\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
      else if(PChoice == 3)
      { cout << "Both chose scissors, draw\nC Score = " << CScore << " Your Score = " << PScore << "\n\n\n";  }
    }
  }
  
  cout << "Computer Score = " << CScore << " Your Score = " << PScore << " Draws = " << GameNo-1-(PScore + CScore);
  getch();
}

Cows and Bulls in Python

import random

def Pic():
  print("        =        ,         =                  _____                                 ")
  print("       /'\\    )\\,/,/(_    / \\                / ____|                             ")
  print("      |  (  ,\\\\)\\//\\)\\/_  ) |               | |     __ __      __ __           ")
  print("   ___\\   `\\\\\\/\\\\/\\/\\\\///'  /               | |    / _ \\ \\ /\\ / / __|   ")
  print(",-\"~`-._ `\"--'_   `\"\"\"`  _ \\`'\"~-,_         | |___| (_) \\ V  V /\\__ \\     ")
  print("\\       `-.  '_`.      .'_` \\ ,-\"~`/         \\_____\\___/ \\_/\\_/ |___/        ")
  print(" `.__.-'`/   (-\\        /-) |-.__,'                                                ")
  print("   ||   |     \\O)  /^\\ (O/  |                                        _   _   _    ")
  print("   `\\\\  |         /   `\\    /                                       ( ) | | | |  ")
  print("     \\\\  \\       /      `\\ /                                        |/  |  \\| |")
  print("      `\\\\ `-.  /' .---.--.\\                                             | . ` |  ")
  print("        `\\\\/`~(, '()      ('                 ____        _ _            | |\\  |  ")
  print("         /(O) \\\\   _,.-.,_)                 |  _ \\      | | |           |_| \\_| ")
  print("        //  \\\\ `\\'`      /                  | |_) |_   _| | |___                 ")
  print("       / |  ||   `\"\"\"\"~\"`                   |  _ <| | | | | / __|              ")
  print("     /'  |__||                              | |_) | |_| | | \\__ \\                 ")
  print("          `o                                |____/ \\__,_|_|_|___/                  ")

while True:
  flag = 'T'
  num = random.randint(1234, 9876)
  num = list(str(num))
  for i in num:
    if num.count(i) > 1:
      flag = 'F'
  if flag == 'T':
    break
print(num, "\n")

ctr = 1
while True:
  Pic()
  bulls, cows = 0, 0
  s = "Guess " + str(ctr) + ": "
  try:
    guess = int(input(s))
  except:
    print("Enter only an integer\n")
    continue
  if guess < 1000 or guess > 9999:
    print("Enter a 4-digit number\n")
    continue

  guess = list(str(guess))
  if num[0] == guess[0]:
    bulls += 1
  elif guess[0] in num:
    cows += 1
  if num[1] == guess[1]:
    bulls += 1
  elif guess[1] in num:
    cows += 1
  if num[2] == guess[2]:
    bulls += 1
  elif guess[2] in num:
    cows += 1
  if num[3] == guess[3]:
    bulls += 1
  elif guess[3] in num:
    cows += 1
  if bulls == 4:
    print("You got it in", ctr, "attempt(s).")
    break
  print(bulls, "bull(s)", cows, "cow(s)", "\n")
  ctr += 1

Idlecolors (Print in color / colours in Python IDLE)




# The driver code

from idlecolors import *

printc(red("Red ") + orange("Orange ") + green("Green ") + blue("Blue"))
printc(purple("Purple ") + black("Black ") + brown("Brown"))
printc(sel("sel ") + hit("hit ") + ERROR("ERROR "))


# idlecolors.py
# Save this to Python's Lib folder

import sys, random

shell_connect = sys.stdout.shell

def printc(text, end="\n", sep="*"):
  buff = ""
  for char in text:
    if char == "{":
      shell_connect.write(buff, "SYNC")
      buff = ""
    elif char == "}":
      tag_write = buff.split(":")
      shell_connect.write(tag_write[0], tag_write[1])
      buff = ""
    else:
      buff += char
  sys.stdout.write(end )

def red(text):
  return "{"+ text + ":" + "COMMENT}"

def orange(text):
  return "{"+ text  + ":" + "KEYWORD}"

def green(text):
  return "{"+ text + ":" + "STRING}"

def blue(text):
  return "{"+ text  + ":" + "stdout}"

def purple(text):
  return "{"+ text + ":" + "BUILTIN}"

def black(text):
  return "{"+ text  + ":" + "SYNC}"

def brown(text):
  return "{"+ text + ":" + "console}"

def sel(text):
  return "{"+ text + ":" + "sel}"

def hit(text):
  return "{"+ text + ":" + "hit}"

def ERROR(text):
  return "{"+ text + ":" + "ERROR}"


Sunday, October 27, 2019

Happy New Year

WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
WWWW   WWW   WWWWWW:    :WWWWWW       'WWWW       'WWW. 'WWW' .WWWW
WWWW   WWW   WWWWW:  ..  :WWWWW   WW.  'WWW   WW.  'WWW. 'W' .WWWWW
WWWW         WWWW:   WW   :WWWW   WW:   WWW   WW:   WWWW. ' .WWWWWW
WWWW   WWW   WWWW'        'WWWW       .:WWW       .:WWWWW   WWWWWWW
WWWW   WWW   WWW:   WWWW   :WWW   WWWWWWWWW   WWWWWWWWWWW   WWWWWWW
WWWW   WWW   WWW'  .WWWW.  'WWW   WWWWWWWWW   WWWWWWWWWWW   WWWWWWW
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
  :W   W: :WWWWW: WW.     .WW  WW   WW :WWWWW:    .W.    :WWWW:.
  :W:  W: :W: WW: :W:     :W:  'W: :W' :W: WW:   .:W:.   :W: 'W:
  :WW: W: :W:      W:.   .:W    'W:W'  :W:       :W W:   :W: .W:
  :WWW:W: :WWWW:   :W:.W.:W:     :W:   :WWWW:   :WWWWW:  :WWWW:'
  :W :WW: :W:       WWWWWWW      :W:   :W:     .WW' 'WW. :W':W.
  :W  :W: :W: WW:   :W:':W:      :W:   :W: WW: :W:   :W: :W ':W.
  :W   W: :WWWWW:    W: :W       :W:   :WWWWW: WW'   'WW :W  ':W.

            ::        ''     SS    : ''    :    :''    ':S:.
        ''        :         .SS        ''          ':     ':S.
      ''          ''       .SS'        '      '            :SS
              ::          .SS'  ::        '       ::     .::S'
   /:.   ''         ''    :SS     ''                   .::'
   ///:.                   'SS.         :'   '        :::'
   /// +:.      '     :      'S. ::           :''     ':SS.
   // ++ /:.                   '.                    '  'S:.
   /  + // =:.     ''      '                             'SS.
   /++ // = //:.                                           SS:
   /+ // = //// :.              :                         .SS
   / // = ////.  /:.                ''                   .:S'
   /// = //// . ////:.                                  .:S'
   // = ////.  //// ' :.                               .:S
   / = //// . //// ' ///:.                             ::'
   /= ////.  //// ' //// ':.                           '::.
   / //// . //// ' //// ' //:.                           '::.
   /////.  //// ' //// ' /// /.                            ':.
   //// . //// ' //// ' /////''Y.           O                :.
   ///.  //// ' ////////''..,YYYYYY.             O          .:
   // . //// ' ////'' ..,YYYYYYYYYYY          O            .'
   /.  ///////''..,YYYYYYYYYYYYYYYY          O      O     O
   / ////''..,YYY'''''''''''YYYYYYYY.         O    O
   /''..,YY                  'YYYYYYY      O      O    O
  ..,:YYYY                     'YYYYY.      O     OO       O
 .YYYYY  .,.,.,.,      ,.,.,.,  'YYYYY      OO     O    O
 YYYYYY  VWWWWWW/.    ./WWWWWV  'YYYY'  =======================
  Y(YY  V'   WWW'V   V'   WWW'V 'YY)'   'I.   O O    O  O   .I'
   ((V  V;,..WWW,V   V;,..WWW,V  V))      'I.//////O//OO//.I'
   (( V               V/        V ))        'I.///O//O//.I'
   (( 'V              '/       V' ))     .'''''I.///O/.I'
    (.)V       ,       . ,     V(.)      V,     'I///I'
       'V      '.     ,;W;    V'           V.     IIV''V,
        V       '':;;;;:'     V              '.   IV    V
        V  ,.             .,  V              .;   IV,,,/,,,.
        V   VW,         ,WV   V             .V    IV'       V
         V   'VWWWWWWWWWWV'  V              V     IV,..   .,' 
          V    'VVVVVVVV'   V               V     IV'      'V.''',
           ;V.            .WW               'V,.,,IV,.   .,/V    V 
           W 'V,.       .;WWW              .,;II;;III;;II;,.V,,,V'
           W     '/WWWWWWWWWW                  W    ';WWWW
           W       '/WWWWWWWW                  W      ';WW

Pacman ASCII Art

================================================.    
      .-.   .-.     .--.                         |    
     | OO| | OO|   / _.-' .-.   .-.  .-.   .''.  |    
     |   | |   |   \  '-. '-'   '-'  '-'   '..'  |    
     '^^^' '^^^'    '--'                         |    
 ===============.  .-.  .================.  .-.  |    
                | |   | |                |  '-'  |    
                | |   | |                |       |    
                | ':-:' |                |  .-.  |    
 l42            |  '-'  |                |  '-'  |    
 ==============='       '================'       |    

Happy Independence Day !!

H A P P Y I N D E P E N D E N C E D A Y ! !
-----------------------------------------------
JAI HIN JA JAI HIND JAI HIND J JAI HIND JAI HI JAI HIND JAI HIN JAI HIND JAI H JAI HIND JAI JAI HIND JAI JAI HIND JAI HIND J JAI HIND JAI H JAI HIND JAI HIN JAI HIND JAI HIN JAI H JAI HIND JAI HIND J JAI HIND J JAI HIND JAI HIND JAI H JAI HIND J JAI HIND JAI HIND JAI HIND JAI JA JAI HIND JAI JAI HIND JAI HIND JAI HIND JAI HIND J JA JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIN JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND J JAI HIND JAI JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI JAI HI JAI HIND JAI HIND JAI HIND JAI HIND JAI HIN JAI HI JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI H JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI JAI JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIN J JAI HI JAI HIND JAI HIND JAI HIND JAI HIND JAI JAI H JAI HIND JAI HIND JAI HIND JAI HIND J JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI JAI HIND JAI HIND JAI HIND JAI JAI HIND JAI HIND JAI HIND J JAI HIND JAI HIND JAI HIND JAI HIND JAI HIND JAI HIN JAI HIND JAI HIND JAI HI JAI HIND JAI HIND JA JAI HIND JAI HIND J JAI HIND JAI HIN JAI HIND JAI HIN JAI HIND JAI HI JAI HIND JAI H JAI HIND JAI JAI HIND JAI JAI HIND JAI JAI HIND JAI HIN JAI H JA

Monday, October 21, 2019

Number Conversions in Python

def Den2Bin(den):
  bin = ""
  while den > 0:
    rem = den % 2
    bin = str(rem) + bin
    den //= 2
  return bin

def Bin2Den(bin):
  exp, oct = 0, 0
  bin = str(bin)
  for i in bin[::-1]:
    i = int(i)
    raised = i * (2 ** exp)
    oct += raised
    exp += 1
  return oct

print(Den2Bin(28))
print(Bin2Den(1010))