Category Archive : Python 3.8

Play Rock Paper Scissors with Python

In this article, we have built a program that plays rock paper scissor, with the Python code. Please install python 3.8 from the link given below to run this code.
https://www.python.org/downloads/

I prefer you to use atom text editor to type your code or to save the given code:
https://atom.io/

You can download the the Play Rock Paper Scissors.py from GitHub using the given link:

Link for the code in GitHub

Example Input:

R

Output:

You Win!!!
~~CONGRATS~~
 You:R
 Computer:S

Example Input:

R

Output:

===========
====TIE====
===========

Example Input:

R

Output:

You Lose!!!
~~TRY AGAIN:-(~~
 You:P
 Computer:S

Example Input:

Something else

Output:

=====Error=====
Input Format: R
        or
Input Format: S
        or
Input Format: P

Code:

x = input().upper()
y = {'R','P','S'}.pop()
if (x=='R'and y=='S') or (x=='S' and y=='P')or(x=='P'and y=='R'):
   print(f"You Win!!!\n~~CONGRATS~~\n You:{x}\n Computer:{y}")
elif (y=='R'and x=='S') or (y=='S' and x=='P')or(y=='P'and x=='R'):
   print(f"You Lose!!!\n~~TRY AGAIN:-(~~\n You:{x}\n Computer:{y}")
elif x==y:print('===========\n====TIE====\n===========')
else:print('=====Error=====\nInput Format: R\n\tor\nInput Format: S\n\tor\nInput Format: P')

Code Explanation:

In this code, we get input from the user, which is turned to upper case using the function upper() to avoid case confusion.

In order to store a random value for y, we use pop() function to a set.

As per the conditions of the game, we use if, elif and else statement that prints “You Win!!!…” if user wins and “You Lose!!!…” if not.

If equal values are received from both the sides, the code prints out “TIE”.

If the user enters anything other than R,P or S, the code prints out the input format.

And now, our code works perfectly fine.

Conclusion:

The above article explains the Rock Paper Scissor game using python coding. If you want to download the code from GitHub, click here. If you have any questions or feedback on this, feel free to post in the comments section below.

Sudoku Validator using Python

In this article, we have built a program to find whether the given Sudoku Solution is valid or not, with the Python code.(Sudoku Validator using Python). Please install python 3.8 from the link given below to run this code.
https://www.python.org/downloads/

I prefer you to use atom text editor to type your code or to save the given code:
https://atom.io/

You can download the the Sudoku.py from GitHub using the given link:

Link for the code in GitHub

Example Input:

123456789
234567891
345678912
456789123
567891234
678912345
789123456
891234567
912345678

Output:

False

Code:

try:a = input(),input(),input(),input(),input(),input(),input(),input(),input()
except:print('You must enter a 9x9 input')
def vert(a,num):
	x=[]
	for i in range(9):
		x+=(a[i][num])
	return ''.join(x)
b=[]
for i in range(9): b+=list(vert(a,i))+[' ']
b = ''.join(b).split()

box1,box2,box3,box4,box5,box6,box7,box8,box9=[],[],[],[],[],[],[],[],[]
for i in range(3):box1+=(a[i][:3])
box1=''.join(box1)

for i in range(3,6):box2+=(a[i][:3])
box2=''.join(box2)

for i in range(6,9):box3+=(a[i][:3])
box3=''.join(box3)

for i in range(3):box4+=(a[i][3:6])
box4=''.join(box4)

for i in range(3,6):box5+=(a[i][3:6])
box5=''.join(box5)

for i in range(6,9):box6+=(a[i][3:6])
box6=''.join(box6)

for i in range(3):box7+=(a[i][6:])
box7=''.join(box7)

for i in range(3,6):box8+=(a[i][6:])
box8=''.join(box8)

for i in range(6,9):box9+=(a[i][6:])
box9=''.join(box9)


hc,vc,bc = 0,0,0
def horcheck(a):
    hc= 0
    for i in a:
        for j in i:
            if i.count(j)>1:
                hc = 1
                return False
                break
        if hc==1:break
    if hc==0:return True
def vercheck(a):
    vc= 0
    for i in a:
        for j in i:
            if i.count(j)>1:
                vc = 1
                return False
                break
        if vc==1:break
    if vc==0:return True
def boxcheck(a,b,c,d,e,f,g,h,j):
    bc =0
	for i in a:
		if a.count(i)>1:
           bc =1
		   return False
    if  bc ==0:
		for i in b:
			if b.count(i)>1:
	           bc =1
			   return False
    if  bc ==0:
		for i in c:
			if c.count(i)>1:
	           bc =1
			   return False
	if  bc ==0:
		for i in d:
			if d.count(i)>1:
	           bc =1
			   return False
    if  bc ==0:
		for i in e:
			if e.count(i)>1:
	           bc =1
			   return False
	if  bc ==0:
		for i in f:
			if f.count(i)>1:
	           bc =1
			   return False
    if  bc ==0:
		for i in g:
			if g.count(i)>1:
	           bc =1
			   return False
	if  bc ==0:
		for i in h:
			if h.count(i)>1:
	           bc =1
			   return False
    if  bc ==0:
		for i in j:
			if j.count(i)>1:
	           c =1
			   return False
if horcheck(a) and vercheck(b) and boxcheck(box1,box2,box3,box4,box5,box6,box7,box8,box9):
    print(True)
else:
    print(False)

Code Explanation:

In this code, we get 9 inputs from the user, where each input has 9 characters.

At first we Try to get the inputs from the user, and if the user does not enter exactly 9 inputs, the Except statement prints out ‘You must enter a 9×9 input’.

Function vert():

Now in order to check whether the solution characters are vertically unique, we define a function called vert() that takes two parameters.

We store the vertical version of the input in the variable b.

Boxes:

We define variables that store the values of the bigger boxes that is usually seen 3×3 in the game. And since we have 9 big boxes, we define 9 variables (box1, box2, box3, box4, box5, box6, box7, box8, box9)

Sudoku Validator Python
Sudoku

Function horcheck(), vercheck() and boxcheck():

We define another 3 functions horcheck(), vercheck and boxcheck() that checks the character uniqueness horizontally, vertically and with each box respectively.

The functions return True if all the characters are unique horizontally, vertically and with respect to each box, and False is not.

And now, our code works perfectly fine.

Conclusion:

The above article explains the Sudoku Validator using python coding. If you want to download the code from GitHub, click here. If you have any questions or feedback on this, feel free to post in the comments section below.

The Classic Tic-Tac-Toe with Python

In this article, we have built a program to find the player who wins the Tic Tac Toe with the Python code. Please install python 3.8 from the link given below to run this code.
https://www.python.org/downloads/

I prefer you to use atom text editor to type your code or to save the given code:
https://atom.io/

You can download the the Classic Tic-Tac-Toe.py from GitHub using the given link:

Link for the code in GitHub

Example Input:

O O X
X O X
X X O

Output:

Player O

Code:

x,y,z= input().split(),input().split(),input().split()
xwin,owin = 0,0
#Horizontal Wins Check
for i in x:
    if x.count(i)==3 and i == 'X':
       print('Player X')
       xwin=1
       break
    elif x.count(i)==3 and i == 'O':
       print('Player O')
       owin = 1
       break
for i in y:
    if y.count(i)==3 and i == 'X':
       print('Player X')
       xwin=1
       break
    elif y.count(i)==3 and i == 'O':
       print('Player O')
       owin = 1
       break
for i in z:
    if z.count(i)==3 and i == 'X':
       print('Player X')
       xwin=1
       break
    elif z.count(i)==3 and i == 'O':
       print('Player O')
       owin = 1
       break
#Vertical Wins Check
vx = list(x[0]+y[0]+z[0])
vy = list(x[1]+y[1]+z[1])
vz = list(x[2]+y[2]+z[2])

if xwin ==0 and owin ==0:
   for i in vx:
      if vx.count(i)==3 and i == 'X':
         print('Player X')
         xwin=1
         break
      elif vx.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break
   for i in vy:
      if vy.count(i)==3 and i == 'X':
         print('Player X')
         xwin=1
         break
      elif vy.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break
   for i in vz:
      if vz.count(i)==3 and i == 'X':
         print('Player X')
         xwin=1
         break
      elif vz.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break
#Diagonal Wins Check

dx = list(x[0]+ y[1]+z[2])
dy = list(x[2]+ y[1] + z[0])
if xwin ==0 and owin ==0:
   for i in dx:
       if dx.count(i) == 3 and i=='X':
         print('Player X')
         xwin = 1
         break
       elif dx.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break
   for i in dy:
      if dy.count(i)==3 and i == 'X':
         print('Player X')
         xwin=1
         break
      elif dy.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break
if xwin ==0 and owin==0:
   print('Tie')

Code Explanation:

In this code, we get three inputs from the user, where each character is separated

The first three For loops checks whether any Horizontal wins exists.

for i in x:
    if x.count(i)==3 and i == 'X':
       print('Player X')
       xwin=1
       break
    elif x.count(i)==3 and i == 'O':
       print('Player O')
       owin = 1
       break
for i in y:
    if y.count(i)==3 and i == 'X':
       print('Player X')
       xwin=1
       break
    elif y.count(i)==3 and i == 'O':
       print('Player O')
       owin = 1
       break
for i in z:
    if z.count(i)==3 and i == 'X':
       print('Player X')
       xwin=1
       break
    elif z.count(i)==3 and i == 'O':
       print('Player O')
       owin = 1
       break

For Example:

Input:
O X O
O O X
X X X
Output:
Player X

But,

Input:
X O X
X O X
O O X
Output:
No Output

This is because our code does not know how to deal with vertical wins.

In order to correct this, we must replace the values of x, y and z with the first, second and third values of the three inputs respectively with the three new variables vx, vy and vz.

vx = list(x[0]+y[0]+z[0])
vy = list(x[1]+y[1]+z[1])
vz = list(x[2]+y[2]+z[2])

After this we repeat our for loops again, but this time, with the three new variables.

if xwin ==0 and owin ==0:
   for i in vx:
      if vx.count(i)==3 and i == 'X':
         print('Player X')
         xwin=1
         break
      elif vx.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break
   for i in vy:
      if vy.count(i)==3 and i == 'X':
         print('Player X')
         xwin=1
         break
      elif vy.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break
   for i in vz:
      if vz.count(i)==3 and i == 'X':
         print('Player X')
         xwin=1
         break
      elif vz.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break

We got an If Statement before the Loop that checks whether any player won horizontally. If they did, the following 4 loops will not get executed.

Now,

Input:
X O X
X O X
O O X
Output:
Player X

But,

Input:
X O X
O X X
X O O
Output:
No Output

Here, X wins Diagonally, but our code does not do well with Diagonal wins. At this point we declare variable dx that takes the first value of x, second value of y and third value of z , and variable dy that takes third value of x, second value of y and first value of z.

dx = list(x[0]+ y[1]+z[2])
dy = list(x[2]+ y[1] + z[0])

Now again we bring our for loops with the same condition.

if xwin ==0 and owin ==0:
   for i in dx:
       if dx.count(i) == 3 and i=='X':
         print('Player X')
         xwin = 1
         break
       elif dx.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break
   for i in dy:
      if dy.count(i)==3 and i == 'X':
         print('Player X')
         xwin=1
         break
      elif dy.count(i)==3 and i == 'O':
         print('Player O')
         owin = 1
         break

This time,

Input:
X O X
O X X
X O O
Output:
Player X

But,

Input:
O X O
X X O
O O X
Output:
No Output

“No Output” does not look good for our code, hence bring a condition where, if nobody wins, the code prints out “Tie”.

if xwin ==0 and owin==0:
   print('Tie')

And now, our code works perfectly fine.

Conclusion:

The above article explains the Tic-Tac-Toe using python coding. If you want to download the code from GitHub, click here. If you have any questions or feedback on this, feel free to post in the comments section below.

Hofstadter Q-Sequence in Python

In this article, we have built a program to find the value of a number in the Q-Sequence (By Using Hofstadter Q-Sequence) with the Python code. Please install python 3.8 from the link given below to run this code.
https://www.python.org/downloads/

I prefer you to use atom text editor to type your code or to save the given code:
https://atom.io/

You can download the the Hofstadter Q-Sequence.py from GitHub using the given link:

Link for the code in GitHub

Example Input:

34

Output:

20

Code:

def Q(n):
    try:
        if n>0 and n<3:
           return 1
        elif n<0:
           return 'Invalid'
        else:
           return Q ( n - Q ( n - 1 ) ) + Q ( n - Q ( n - 2 ) )
    except:return "Enter an INTEGER value!"
print(Q(int(input())))

Code Explanation:

In this code, we get an input from the user which is the value of n in Q(n) .

Q ( 1 ) = Q ( 2 ) = 1 , Q ( n ) = Q ( n − Q ( n − 1 ) ) + Q ( n − Q ( n − 2 ) ) , n > 2

Hofstadter Q sequence Definition

Function Definition:

Here, we define a function that takes n as its parameter (input).
We use ‘try and ‘except’ in order to prevent unnecessary errors .

The error is caused only if the user enters anything other than float or int.

Here, we use Recursion in order to call back the same function to use Q ( n − Q ( n − 1 ) ) + Q ( n − Q ( n − 2 ) ) .

If the user enters a negative integer, the code outputs “Enter an INTEGER value!”

The base of the recursion is the condition “if n>0 and n<3:”
It returns 1 if the value becomes <3 (0,1 or 2).

Function Call:

At last, we call the function Q with int(input()) as parameter and print it out

Conclusion:

The above article explains the Hofstadter Q-Sequence using python coding. If you want to download the code from GitHub, click here. If you have any questions or feedback on this, feel free to post in the comments section below.

Pythagorean Theorem Professional Calculator -Python

In this article, we have built a calculator that finds the length of any side of a right triangle (By Using Pythagorean Theorem) with the Python code. Please install python 3.8 from the link given below to run this code.
https://www.python.org/downloads/

I prefer you to use atom text editor to type your code or to save the given code:
https://atom.io/

You can download the the Pythagorean Theorem.py from GitHub using the given link:

Link for the code in GitHub

Code

#Pythagorean Theorem Professional Calculator -Python
def find_base(perpendicular,hypotenuse):
    base = ((hypotenuse**2)-(perpendicular**2))**(1/2)
    return base
#Function to find Base when Hypotenuse and perpendicular is given
def find_perpendicular(base,hypotenuse):
    perpendicular = ((hypotenuse**2)-(base**2))**(1/2)
    return perpendicular
#Function to find perpendicular when Hypotenuse and Base is given
def find_hypotenuse(base,perpendicular):
    hypotenuse= ((perpendicular**2)+(base**2))**(1/2)
    return hypotenuse
#Function to find Hypotenuse when perpendicular and Base is given
print("Enter any two values, Enter Unknown Value as '0'!!")
b = int(input('Base: '))
p = int(input('Perpendicular: '))
h = int(input('Hypotenuse: '))
#getting Input from user - Unknown Value is Entered '0'

if (h != 0) and (h<b or h<p): #CHECK: Whether Hypotenuse > Other 2 Sides
    print('Hypotenuse cannot be lesser than the other two sides')
elif (h == 0 and b == 0)or(b == 0 and p == 0)or(p == 0 and h == 0): #CHECK: Whether ONLY 1 side is Entered 0  or not
    print('Error Finding the value \n You Must Enter 2 Values \n Please Check And Try Again!')
elif (h == 0 or (h>b and h>p)) and (h == 0 or b == 0  or p == 0): # CHECK: If All Conditions Satisfy
    if b == 0:
        print(find_base(p,h)) #Using the Functions
    elif p == 0:
        print(find_perpendicular(b,h)) #Using the Functions
    elif h == 0:
        print(find_hypotenuse(b,p)) #Using the Functions
else:
    print("Error!") #If No Conditions Satisfy

Example Input:

Enter any two values, Enter Unknown Value as '0'!!
Base: 3
Perpendicular: 4
Hypotenuse: 0

Output:

5.0

Code Explanation:

In this code, what we basically do is that, we get the 3 inputs from the user which are the values of base, perpendicular and hypotenuse, where the unknown value is entered ‘0’.

Pythagorean Theorem

Function Definition:

In the first 12 lines we define three functions that finds the base, perpendicular and the hypotenuse [find_base , find_perpendicular, find_hypotenuse]

Input:

We Prompt 3 inputs from the user whose value is Base, Perpendicular and Hypotenuse respectively and the unknown value is entered ‘0’.

If…else:

The if statement checks if ‘hypotenuse’ is a known value, but is lesser than any of the two sides. If True , returns ‘Hypotenuse cannot be lesser than the other two sides’

The first elif statement checks if not more than one side is unknown so that the formula can be used. If true, returns:
‘Error Finding the value
You Must Enter 2 Values
Please Check And Try Again!’

The second elif statement simply returns the necessary output if any one value is unknown.

The else statement returns “Error!” if no conditions given satisfies

Conclusion:

The above article explains the Pythagorean Theorem Calculator using python coding. If you want to download the code from GitHub, click here. If you have any questions or feedback on this, feel free to post in the comments section below.

Quadratic Equation Code in Python

Introduction:

In this article, I am going to explain how to find the solutions for the quadratic equation with the Python code. Please install python 3.8 from the link given below to run this code.
https://www.python.org/downloads/

I prefer you to use atom text editor to type your code or to save the given code:
https://atom.io/

You can download the the Quadratic Equation.py from GitHub using the given link:

Link for the code in GitHub

Code:

#Quadratic equation
a=int(input())
b=int(input())
c=int(input())

d_d = b**2-(4*a*c) #Assigning variables to make the program simpler
d = d_d**(1/2)  #Root of b square -4ac
sol1 = ((-b)+d)/(2*a)
sol2 = ((-b)-d)/(2*a)

#Check if solution exists

if d_d < 0:
   print('Solution exists in complex numbers')

#Return the solution if it exists in real numbers) 
else:
   print('x = {0} or x = {1}'.format(sol1,sol2))  

Example Input:

1
2
1

Output:

x = -1.0 or x = -1.0

Code Explanation:

In this code, what we basically do is that, we get the 3 inputs from the user which are the values of a,b and c in a quadratic equation of the form ax2+bx+c.

Quadratic Equation in Python
Quadratic Equation

Code (Assignings):

  • The variable d_d is assigned the value of b2-4ac.
  • The variable d is assigned the value of root of d_d, that is root of b2-4ac.
  • Since an equation has 2 values ( ± ).
  • The value when used ‘+’ is assigned to the variable sol1.
  • Similarly, the value when used ‘-‘ is assigned to the variable sol2.

Code(If…Else):

  • In a quadratic equation when the value of b2-4ac is less than 0, then solution is in complex numbers.
  • In order to test this, we are checking whether d_d is less than 0 or not.
  • If less than 0, the ‘if’ statement is executed where the string (‘Solution exists in complex numbers’) is executed. If not then the real number value is executed (else statement)

Conclusion:

The above article explains the solution to quadratic equation using python coding. If you have any questions or feedback on this, feel free to post in the comments section below.