Wednesday, January 15, 2020

Rock - Paper - Scissors in Python 3

# An implementation of Rock-Paper-Scissors in Python

import random

CChoice, PChoice, CScore, PScore = 0, 0, 0, 0
Set = ["Rock", "Paper", "Scissors"]
GameNo = 1
PChoice, pchoice = -1, 0

while GameNo <= 20:
  CChoice = random.randint(1, 3)
  s = "\nGame " + str(GameNo) + ": " + "Enter (R)ock, (P)aper, (S)cissors OR (E)xit: "
  pChoice = input(s).upper()
  if pChoice == 'R':
    PChoice = 1
  elif pChoice == 'P':
    PChoice = 2
  elif pChoice == 'S':
    PChoice = 3
  elif pChoice == 'E':
    PChoice = 0
  else:
    print("Invalid choice")
    continue
  
  if pChoice == 'E':
    break

  print("Computer chose", end = ' ');  print(Set[CChoice-1], end = ' ')
  print("You chose", end = ' ');       print(Set[PChoice-1])

  if CChoice == 1:
    if PChoice == 1:
      print("Both chose Rock - DRAW")
    elif PChoice == 2:
      print("Paper covers Rock", end = '')
      print(" - YOU WIN")
      PScore += 1
    elif PChoice == 3:
      print("Rock smashes Scissors", end = '')
      print(" - COMPUTER WINS")
      CScore += 1
  elif CChoice == 2:
    if PChoice == 1:
      print("Paper covers Rock ", end = '')
      print(" - COMPUTER WINS")
      CScore += 1
    elif PChoice == 2:
      print("Both chose Paper, DRAW")
    elif PChoice == 3:
      print("Scissors cut Paper", end = '')
      print(" - YOU WIN")
      PScore += 1
  elif CChoice == 3:
    if PChoice == 1:
      print("Rock smashes Scissors", end = '')
      print(" - YOU WIN")
      PScore += 1
    elif PChoice == 2:
      print("Scissors cut Paper", end = '')
      print(" - COMPUTER WINS")
      CScore += 1
    elif PChoice == 3:
      print("Both chose Scissors, DRAW")
  print("Computer Score = ", CScore, " Your Score = ", PScore)

  GameNo += 1

Saturday, January 4, 2020

Towers of Hanoi in Python

# https://www.youtube.com/watch?v=8lhxIOAfDss
# (Professor Thorsten Altenkirch)

def hanoi(n, a, b, c):
  if n > 0:
    hanoi(n-1, a, c, b)
    print("Move disc from {} to {}".format(a, c))
    hanoi(n-1, b, a, c)

hanoi(4, 'A', 'B', 'C')

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();
  }
}