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}"