Monday, September 19, 2022

How to solve largest prime factor problem?

Description of the problem: The prime factors of 13195 are 5, 7, 13 and 29.What is the largest prime factor of the number 600851475143 ?

Solution: Beginner Level

The basic solution is created without any functions or classes. First the given example (prime factors of 13195) will be confirmed and then the largest prime factor of the number 600851475143 will be found.

The prime factors of 13195 are 5, 7, 13, and 29

The first step is to ask user to type in the number for which we want to find prime factors. This will be done using the input function that will return the string. If we want to use this nubmer we have to convert it to integer so we have to use int function.
n = int(input("Enter a number> "))
The second step is to generate the list of prime nubmers.
primNumbers = [i for i in range(2, 10000+1) if 0 not in [i%n for n in range(2,i)]]
The prime factors that are found have to be stored in the list, so we will create an empty list that will be assigned to PrimeFactors variable.
PrimeFactors = []
The next step is to create a loop in which the prime numbers will be used in division with number that user typed in. If the division between n and the prime number is without remainder than the prime number will be appended into prime factors list. If however the remainder exists that the prime number will be skipped. At the end of each iteration the value of variable n will be lowered will be equal to the result of previous division of number n with the prime number and iteration number will be updated.
i = 0
while i < len(primNumbers):
if n%primNumbers[i] == 0:
print("{}/{} = {}".format(n, primNumbers[i], n/primNumbers[i]))
PrimeFactors.append(primNumbers[i])
n = n/primNumbers[i]
elif n/primNumbers[i] == 1.0:
break
i+=1
Now we will show the list of prime factors.
print("PrimeFactors = {}".format(PrimeFactors))
To find the largest prime number we will use the max function.
print("Largest prime factor = {}".format(max(PrimeFactors))
n = int(input("Enter a number> "))
primNumbers = [i for i in range(2, 10000+1) if 0 not in [i%n for n in range(2,i)]]
PrimeFactors = []
i = 0
while i < len(primNumbers):
if n%primNumbers[i] == 0:
print("{}/{} = {}".format(n, primNumbers[i], n/primNumbers[i]))
PrimeFactors.append(primNumbers[i])
n = n/primNumbers[i]
elif n/primNumbers[i] == 1.0:
break
i+=1
print("PrimeFactors = {}".format(PrimeFactors))
print("Largest prime factor = {}".format(max(PrimeFactors)))
Output:
Enter a number> 13195
13195/5 = 2639.0
2639.0/7 = 377.0
377.0/13 = 29.0
29.0/29 = 1.0
PrimeFactors = [5, 7, 13, 29]
Largest prime factor = 29

Largest Prime Factor of the number 600851475143?

n = int(input("Enter a number> "))
primNumbers = [i for i in range(2, 10000+1) if 0 not in [i%n for n in range(2,i)]]
PrimeFactors = []
i = 0
while i < len(primNumbers):
if n%primNumbers[i] == 0:
print("{}/{} = {}".format(n, primNumbers[i], n/primNumbers[i]))
PrimeFactors.append(primNumbers[i])
n = n/primNumbers[i]
elif n/primNumbers[i] == 1.0:
break
i+=1
print("PrimeFactors = {}".format(PrimeFactors))
print("Largest prime factor = {}".format(max(PrimeFactors)))
Output
Enter a number> 600851475143
600851475143/71 = 8462696833.0
8462696833.0/839 = 10086647.0
10086647.0/1471 = 6857.0
6857.0/6857 = 1.0
PrimeFactors = [71, 839, 1471, 6857]

Solution: Intermediate Level

At this stage we will create a program using only functions. The code from "Beginner level" will be re-used. The program will consist of three functions i.e.:
  • PrimeNumbers function - function that will ask user to type in the number (n) for which we want to find the list of prime factors and the largest prime factor. The function will also create a list of prime numbers that will be used later in the code.
  • FindPrimeFactorsN function - this function will create a list of prime factors that multiplied together will generate a number n that is defined by the user.
  • MultiplyPrime function - this function will multiply all the prime factors obtained in with FindPrimeFacttorsN function and will show the result as output.
The entire code is given below. Output: The prime factors of 13195, and multiplication result of all prime factors in a list.
Enter a number:> 13195
13195/5 = 2639.0
2639.0/7 = 377.0
377.0/13 = 29.0
29.0/29 = 1.0
PrimeFactors = [5, 7, 13, 29]
Largest prime factor = 29
13195
Output: The prime factors of 600851475143, and multiplication result of all prime factors list.
Enter a number:> 600851475143
600851475143/71 = 8462696833.0
8462696833.0/839 = 10086647.0
10086647.0/1471 = 6857.0
6857.0/6857 = 1.0
PrimeFactors = [71, 839, 1471, 6857]
Largest prime factor = 6857
600851475143

Solution: Advanced Level

In this case the functions used from Intermediate level will be used here. The first function will be class __init__ method and the other two methods FindPrimeFactorsN, MultiplyPrime will be used without any additional modifications. The entire code i.e. class LargestPrimeNumber is given below.
class LargestPrimeNumber():
def __init__(self):
while True:
try:
self.n = int(input("Enter a number:> "))
break
except ValueError:
print("Invalid input! Please try again!")
pass
self.primNumbers = [i for i in range(2, 1000+1) if 0 not in [i%self.n for n in range(2,i)]]
def FindPrimeFactorsN(self, n, primNubmers):
PrimeFactors = []
i = 0
while i < len(self.primNumbers):
if self.n%self.primNumbers[i] == 0:
print("{}/{} = {}".format(self.n, self.primNumbers[i], self.n/self.primNumbers[i])) PrimeFactors.append(self.primNumbers[i])
self.n = self.n/self.primNumbers[i]
elif self.n/self.primNumbers[i] == 1.0:
break
i+=1
print("PrimeFactors = {}".format(PrimeFactors))
print("Largest prime factor = {}".format(max(PrimeFactors)))
return PrimeFactors
def MultiplyPrime(self, primFactors):
result = 1
for x in primFactors:
result = result*x
print("{}".format(result))
return result
test = LargestPrimeNumber()
primFactors = test.FindPrimeFactorsN(test.n, test.primNumbers)
res = test.MultiplyPrime(primFactors)
Output: The largest prime factor of 13195, and results of multiplication of all prime factors list
Enter a number:> 13195
13195/5 = 2639.0
2639.0/7 = 377.0
377.0/13 = 29.0
29.0/29 = 1.0
PrimeFactors = [5, 7, 13, 29]
Largest prime factor = 29
13195
Output: The largest prime factor of 600851475143, and multiplication of all prime factors list
Enter a number:> 600851475143
600851475143/71 = 8462696833.0
8462696833.0/839 = 10086647.0
10086647.0/1471 = 6857.0
6857.0/6857 = 1.0
PrimeFactors = [71, 839, 1471, 6857]
Largest prime factor = 6857
600851475143

Sunday, September 18, 2022

How to create Tic-Tac-Toe game in Python ?

Solution: Beginner level

The tic-tac-toe game will be created without using functions or object oriented programming. To create this game we will use loops, conditionals, lists and the random library. The random library will be used by the "computer" to randomly select the field where the sign ("X" or "O") will be placed.
import random
To create Game menu we will use while loop. In this game menu two options are available i.e. 1. New Game (type New), 2. Quit (type Quit). In case the value of the OPTION variable is equal to 1 the New game will start. In case the value of the OPTION variable is equal to 2 the game will be terminated and output will be displayed "Exit the game!".In case the user incorrectly typed New or Quit the string "Invalid entry! Please try again." will be shown as output.
while True:
print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New":
# Game code
elif OPTION == "Quit":
print("Exit the game!")
break
elif OPTION != "New" or OPTION != "Quit":
print("Invalid entery! Please try again.")
continue
The rest of the game code will be placed inside the if conditional i.e. (if OPTION == "New"). The game will start by creating the field that will be used for the game. The field is a 5 nested lists each list with 5 elements. The list is assigned to the variable named test. In each list the first and third element will be filled with vertical lines "|". The 0, 2, and 4 element will be field with empty character " ". The first and third list will be filled with "___________________" string. The code for creating the field for tic-tac-toe game is placed inside the if conditional as the rest of the game and is given below.
test = [[] for i in range(0,5,1)]
print(test)
for i in range(len(test)):
if i%2 == 0:
count = 0
while count < 5:
if count%2 == 0:
test[i].append(" ")
else:
test[i].append("|")
count += 1
else:
test[i].append("_____________________")
for i in range(len(test)):
print(test[i])
The previous block of code when executed will produce an empty field for tic-tac-toe game that consist of 5 rows and 5 columns. However 3 rows (lists with index 0, 2 and 4) and three columns (columns with indexes 0, 2, and 4) are used for in the game.
Output:
[' ', '|', ' ', '|', ' ']
['_____________________']
[' ', '|', ' ', '|', ' ']
['_____________________']
[' ', '|', ' ', '|', ' ']
The available "empty" files are shown as output just before selecting the character that we and opponent (computer) are going to use.
print("""Enter a cell number. Cells are:
[0][0], [0][2], [0][4]
[2][0], [2][2], [2][4]
[4][0], [4][2], [4][4]""")
Now we have to create a piece of code that will ask us which symbol we are going to use "X" or "O". When we type the sign that we are going to use the second sign (character) will be automatically assigned to the opponent (computer). To do this we will use while loop and try and except block.
while True:
USER_INPUT = input("Type X or O:> ")
if USER_INPUT == "X":
COMPUTER = "O"
break
elif USER_INPUT == "O":
COMPUTER = "X"
break
elif USER_INPUT != "X" or USER_INPUT != "O":
print("Invalid Character! Please enter a valid character again!")
continue
After the user has chosen a character with which he is going to play the game the procedure for filling the empty fields inside the nested list must be created. In this case we will also use the while loop. First the user has to type the row number and then the column number. Then it has to check if the cell already contains character "X" or character "O". If the cell contains one of these character the user has to type another row number and another column number. If the cell does not contain any of two character (X or O) then the cell will be field with user character. In case the user accidentally type the character which cannot be converted to integer than the program will skip to except block to prevent Python from raising the ValueError and show the string "Invalid input. Please try again!" as the output. After the user enters a character the entire tic-tac-toe board will be displayed.
while True:
while True:
try:
UR_CellRow = int(input("Enter Cell Row:>"))
UR_CellCol = int(input("Enter Cell Column:>"))
#check if the field is empty
if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
test[UR_CellRow][UR_CellCol] == COMPUTER:
print("Cell is already filled. Please choose another cell.")
continue
else:
test[UR_CellRow][UR_CellCol] = USER_INPUT
break
except ValueError:
print("Invalid input. Please try again!")
continue
# Show the map
for i in range(len(test)):
print(test[i])
In this next step the opponent (Computer) has to play but to do this first the empty cells must be found. So we have to write for loops to collect the indexes of the cells containing "_" character. After all these are found the random function will be used to choose a random cell in which the opponent (computer) character will be placed. After that the entire tic-tac-toe field will be shown.
    #########################################################
# Check empty cells
#########################################################
Empty_rows = []
Empty_cols = []
for i in range(len(test)):
for j in range(len(test[i])):
if test[i][j] == " ":
Empty_rows.append(i)
Empty_cols.append(j)
print("Empty_rows = {}".format(Empty_rows))
print("Empty_cols = {}".format(Empty_cols))
index = random.randint(0,len(Empty_rows)-1)
print("index = {}".format(index))
CR_Index = Empty_rows[index]
CC_Index = Empty_cols[index]
print("CR_Index = {}".format(CR_Index))
print("CC_Index = {}".format(CC_Index))
test[CR_Index][CC_Index] = COMPUTER
# Show the map
for i in range(len(test)):
print(test[i])
After the opponent (computer) placed its character in one of the empty cells the entire tic-tac-toe field has to be evaluated. So in this step we are searching for three characters in a row or column, or diagonal. If there are three characters in a row the game will be finished and the score would be displayed. This final part starts with defining two variables SCORE_USER, and SCORE_COMPUTER and assigning the values 0 to these variables. To see if three characters (USER_INPUT/COMPUTER) are the same the following code is used.
    for i in range(len(test)):
if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
As seen from previous code if three characters are the same in a row (USER_INPUT/COMPUTER) then the value of SCORE_USER or SCORE_COMPUTER changes from 0 to 1 and the output is displayed i.e. "You Win!"/"Computer Wins!" and the execution exits the while loop. To check if the three characters are the same in a column the following code is used.
    for j in range(len(test[0])): #Vertical Elements
if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
SCORE_COMP = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
As seen from previous code block the procedure is the same as in the case of checking for the same three elements in a row (horizontal elements). If the same three elements are found in column (USER_INPUT or COMPUTER) then the SOCRE_USER/SCORE_COMPUTER changes its value from 0 to 1. The string is shown "You Win!" or "Computer Wins!" and the program will exit the while loop. The procedure for checking if the same three characters are placed diagonally are shown below.
    if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
The entire while loop that is responsible for playing the game is given below.
while True:
while True:
try:
UR_CellRow = int(input("Enter Cell Row:>"))
UR_CellCol = int(input("Enter Cell Column:>"))
#check if the field is empty
if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
test[UR_CellRow][UR_CellCol] == COMPUTER:
print("Cell is already filled. Please choose another cell.")
continue
else:
test[UR_CellRow][UR_CellCol] = USER_INPUT
break
except ValueError:
print("Invalid input. Please try again!")
continue
# Show the map
for i in range(len(test)):
print(test[i])
#########################################################
# Check empty cells
#########################################################
Empty_rows = []
Empty_cols = []
for i in range(len(test)):
for j in range(len(test[i])):
if test[i][j] == " ":
Empty_rows.append(i)
Empty_cols.append(j)
print("Empty_rows = {}".format(Empty_rows))
print("Empty_cols = {}".format(Empty_cols))
index = random.randint(0,len(Empty_rows)-1)
print("index = {}".format(index))
CR_Index = Empty_rows[index]
CC_Index = Empty_cols[index]
print("CR_Index = {}".format(CR_Index))
print("CC_Index = {}".format(CC_Index))
test[CR_Index][CC_Index] = COMPUTER
# Show the map
for i in range(len(test)):
print(test[i])
###############################################
# Counting SCORE
###############################################
# Check if three symbols are in rows
###############################################
SCORE_USER = 0
SCORE_COMPUTER = 0
for i in range(len(test)):
if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
for j in range(len(test[0])): #Vertical Elements
if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
The entire program for tic-tac-toe game at beginner level is shown below.
while True:
print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New":
test = [[] for i in range(0,5,1)]
print(test)
for i in range(len(test)):
if i%2 == 0:
count = 0
while count < 5:
if count%2 == 0:
test[i].append(" ")
else:
test[i].append("|")
count += 1
else:
test[i].append("_____________________")
for i in range(len(test)):
print(test[i])
print("""Enter a cell number. Cells are:
[0][0], [0][2], [0][4]
[2][0], [2][2], [2][4]
[4][0], [4][2], [4][4]""")
while True:
USER_INPUT = input("Type X or O:> ")
if USER_INPUT == "X":
COMPUTER = "O"
break
elif USER_INPUT == "O":
COMPUTER = "X"
break
elif USER_INPUT != "X" or USER_INPUT != "O":
print("Invalid Character! Please enter a valid character again!")
continue
while True:
while True:
try:
UR_CellRow = int(input("Enter Cell Row:>"))
UR_CellCol = int(input("Enter Cell Column:>"))
#check if the field is empty
if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
test[UR_CellRow][UR_CellCol] == COMPUTER:
print("Cell is already filled. Please choose another cell.")
continue
else:
test[UR_CellRow][UR_CellCol] = USER_INPUT
break
except ValueError:
print("Invalid input. Please try again!")
continue
# Show the map
for i in range(len(test)):
print(test[i])
#########################################################
# Check empty cells
#########################################################
Empty_rows = []
Empty_cols = []
for i in range(len(test)):
for j in range(len(test[i])):
if test[i][j] == " ":
Empty_rows.append(i)
Empty_cols.append(j)
print("Empty_rows = {}".format(Empty_rows))
print("Empty_cols = {}".format(Empty_cols))
index = random.randint(0,len(Empty_rows)-1)
print("index = {}".format(index))
CR_Index = Empty_rows[index]
CC_Index = Empty_cols[index]
print("CR_Index = {}".format(CR_Index))
print("CC_Index = {}".format(CC_Index))
test[CR_Index][CC_Index] = COMPUTER
# Show the map
for i in range(len(test)):
print(test[i])
###############################################
# Counting SCORE
###############################################
# Check if three symbols are in rows
###############################################
SCORE_USER = 0
SCORE_COMPUTER = 0
for i in range(len(test)):
if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
for j in range(len(test[0])): #Vertical Elements
if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
break
elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
break
if SCORE_USER == 1 or SCORE_COMPUTER == 1:
break
elif OPTION == "Quit":
print("Exit the game!")
break
elif OPTION != "New" or OPTION != "Quit":
print("Invalid entery! Please try again.")
continue
Output:

Solution: Intermediate Level

At these stage we will re-use the code from the Solution: Beginner Level and introduce functions. In this case four functions were created and these are:
  • MainMenu function - when this function is called it will display a menu in which user is asking to choose between New game or Quit Game. For New game user has to type "New", and for Quit Game user has to type "Quit". The Function returns the string typed by user ("New"/"Quit")
  • GamePrep function - this function will generate a tic-tac-toe board in which the user will play against computer. Besides that this function will ask a user to choose a sign "X" or "O"- If the user chooses "X" the "O" will be assigned to other player (COMPUTER) and vice versa. All these three variables will be generated with this function.
  • PlaceCharacter function- will ask user to choose the cell inside the tic-tac-toe filed and then this function will randomly place the opponent sign (COMPUTER) in the tic-tac-toe field.
  • ScoreCounting function - will search for three USER or COMPUTER signs ("X" or "O") if they are placed side-by-side horizontally, vertically, and diagonally.
This program will also require random library that will be used for opponent to randomly choose the empty cell to fill with its character.
import random
The program will start with the MainMenu() function that will ask user to choose between New Game or to Quit Game. For a New Game user has to type New and to quit game user has to type Quit.
def MainMenu():
After all these functions are created they will be called and executed inside the main while loop. The loop is shown below.
while True:
print("""\t Welcome to Tic-Tac-Toe game\n \t 1. New Game (type New)\n \t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New":
# Game code
elif OPTION == "Quit":
print("Exit the game!")
break
elif OPTION != "New" or OPTION != "Quit":
print("Invalid entery! Please try again.")
continue
The body of the GamePrep() function is given below:
def GamePrep():
test = [[] for i in range(0,5,1)]
print(test)
for i in range(len(test)):
if i%2 == 0:
count = 0
while count < 5:
if count%2 == 0:
test[i].append(" ")
else:
test[i].append("|")
count += 1
else:
test[i].append("_____________________")
for i in range(len(test)):
print(test[i])
print("""Enter a cell number. Cells are:
[0][0], [0][2], [0][4]
[2][0], [2][2], [2][4]
[4][0], [4][2], [4][4]""")
while True:
USER_INPUT = input("Type X or O:> ")
if USER_INPUT == "X":
COMPUTER = "O"
break
elif USER_INPUT == "O":
COMPUTER = "X"
break
elif USER_INPUT != "X" or USER_INPUT != "O":
print("Invalid Character! Please enter a valid character again!")
continue
return test, USER_INPUT, COMPUTER
The function used to place the characters ("X" or "O") inside the tic-tac-toe field is called the PlaceCharacter and the body of this function is shown below.
def PlaceCharacter(test, USER_INPUT,COMPUTER):
while True:
try:
UR_CellRow = int(input("Enter Cell Row:>"))
UR_CellCol = int(input("Enter Cell Column:>"))
#check if the field is empty
if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
test[UR_CellRow][UR_CellCol] == COMPUTER:
print("Cell is already filled. Please choose another cell.")
continue
else:
test[UR_CellRow][UR_CellCol] = USER_INPUT
break
except ValueError:
print("Invalid input. Please try again!")
continue
# Show the map
for i in range(len(test)):
print(test[i])
#########################################################
# Check empty cells
#########################################################
Empty_rows = []
Empty_cols = []
for i in range(len(test)):
for j in range(len(test[i])):
if test[i][j] == " ":
Empty_rows.append(i)
Empty_cols.append(j)
print("Empty_rows = {}".format(Empty_rows))
print("Empty_cols = {}".format(Empty_cols))
index = random.randint(0,len(Empty_rows)-1)
print("index = {}".format(index))
CR_Index = Empty_rows[index]
CC_Index = Empty_cols[index]
print("CR_Index = {}".format(CR_Index))
print("CC_Index = {}".format(CC_Index))
test[CR_Index][CC_Index] = COMPUTER
# Show the map
for i in range(len(test)):
print(test[i])
return test
The last function that has to be defined is the function responsible for checking who one after each of the characters ("X" or "O") are placed. This function is named ScoreCounting and the entire function is shown below.
def ScoreCounting(test, USER_INPUT, COMPUTER):
###############################################
# Counting SCORE
###############################################
# Check if three symbols are in rows
###############################################
SCORE_USER = 0
SCORE_COMPUTER = 0
for i in range(len(test)):
if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
SCORE_COMPUTER = 1
print("Computer Wins!")
for j in range(len(test[0])): #Vertical Elements
if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
SCORE_COMP = 1
print("Computer Wins!")
if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
SCORE_USER = 1
print("You Win!")
elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
SCORE_USER = 1
print("You Win!")
return SCORE_USER, SCORE_COMPUTER
All these functions are used in the while loop and this loop is shown below.
while True:
Option = MainMenu()
if Option == "New":
XOempty, UserInput, Computer = GamePrep()
while True:
XOempty = PlaceCharacter(XOempty, UserInput,Computer)
ScoreUser, ScoreComputer = ScoreCounting(XOempty, UserInput, Computer)
if ScoreUser == 1 or ScoreComputer == 1:
break
elif Option == "Quit":
print("Exit the game!")
break
As seen from the previous code block there are two while loops. The first one outer while loop and second inner while loop. The outer while loop will be terminated and the program will be terminated when user types "Quit" instead of "New". On the other hand the inner while loop will be terminated when my score or the computer score is equal to 1.0. The entire code is given below.
            def MainMenu():    
                while True:
                    print("""\t Welcome to Tic-Tac-Toe game\n
                              \t 1. New Game (type New)\n
                              \t 2. Quit (type Quit)\n""")
                    OPTION = input("Choose an option:> ")
                    if OPTION == "New" or OPTION == "Quit":
                        break
                    else:
                        print("Invalid entery! Please try again.")
                        continue
                return OPTION
            
            def GamePrep():
                test = [[] for i in range(0,5,1)]
                print(test)
                for i in range(len(test)):
                    if i%2 == 0:
                        count = 0
                        while count < 5:
                            if count%2 == 0:
                                test[i].append(" ")
                            else:
                                test[i].append("|")
                            count += 1
                    else:
                        test[i].append("_____________________")
                        
                for i in range(len(test)):
                    print(test[i])
                print("""Enter a cell number. Cells are:
                      [0][0], [0][2], [0][4]
                      [2][0], [2][2], [2][4]
                      [4][0], [4][2], [4][4]""")
                while True:
                    USER_INPUT = input("Type X or O:> ")
                    if USER_INPUT == "X":
                        COMPUTER = "O"
                        break
                    elif USER_INPUT == "O":
                        COMPUTER = "X"
                        break
                    elif USER_INPUT != "X" or USER_INPUT != "O":
                        print("Invalid Character! Please enter a valid character again!")
                        continue
                return test, USER_INPUT, COMPUTER
            def PlaceCharacter(test, USER_INPUT,COMPUTER):
                while True:
                    try:
                        UR_CellRow = int(input("Enter Cell Row:>"))
                        UR_CellCol = int(input("Enter Cell Column:>"))
                        #check if the field is empty
                        if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
                            test[UR_CellRow][UR_CellCol] == COMPUTER:
                            print("Cell is already filled. Please choose another cell.")
                            continue
                        else:
                            test[UR_CellRow][UR_CellCol] = USER_INPUT
                            break
                    except ValueError:
                        print("Invalid input. Please try again!")
                        continue
                # Show the map 
                for i in range(len(test)):
                    print(test[i])
                #########################################################
                # Check empty cells 
                #########################################################
                Empty_rows = []
                Empty_cols = []
                for i in range(len(test)):
                    for j in range(len(test[i])):
                        if test[i][j] == " ":
                            Empty_rows.append(i)
                            Empty_cols.append(j)
                print("Empty_rows = {}".format(Empty_rows))
                print("Empty_cols = {}".format(Empty_cols))
                index = random.randint(0,len(Empty_rows)-1)
                print("index = {}".format(index))
                CR_Index = Empty_rows[index]
                CC_Index = Empty_cols[index]
                print("CR_Index = {}".format(CR_Index))
                print("CC_Index = {}".format(CC_Index))
                test[CR_Index][CC_Index] = COMPUTER
                # Show the map 
                for i in range(len(test)):
                    print(test[i])
                return test
            def ScoreCounting(test, USER_INPUT, COMPUTER):
                ###############################################
                # Counting SCORE 
                ###############################################
                # Check if three symbols are in rows 
                ###############################################
                SCORE_USER = 0 
                SCORE_COMPUTER = 0
                for i in range(len(test)):
                    if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
                        SCORE_USER = 1 
                        print("You Win!")
                    elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
                        SCORE_COMPUTER = 1
                        print("Computer Wins!")
                for j in range(len(test[0])): #Vertical Elements
                    if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
                        SCORE_USER = 1
                        print("You Win!")
                    if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
                        SCORE_COMP = 1 
                        print("Computer Wins!")
                if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
                    SCORE_USER = 1 
                    print("You Win!")
                elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
                    SCORE_USER = 1 
                    print("You Win!")
                elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
                    SCORE_USER = 1 
                    print("You Win!")
                elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
                    SCORE_USER = 1 
                    print("You Win!")
                return SCORE_USER, SCORE_COMPUTER
            
            while True:
                Option = MainMenu()
                if Option == "New":
                    XOempty, UserInput, Computer =  GamePrep()
                    while True:
                        XOempty = PlaceCharacter(XOempty, UserInput,Computer)
                        ScoreUser, ScoreComputer =   ScoreCounting(XOempty, UserInput, Computer)
                        if ScoreUser == 1 or ScoreComputer == 1: 
                            break
                elif Option == "Quit":
                    print("Exit the game!")
                    break

Solution: Advanced Level

At this level we will built the Tic-Tac-Toe Program using Object-Oriented programming.To do this the code will be used from previous two examples (beginner and intermediate level). First we will need as in previous cases the random library which is used to randomly selects one of the empty fields and place there its character.
import random
The class is named TicTacToeGame() which consist of four different methods and these are MainMenu, GamePrep, PlaceCharacter, and ScoreCounting method.
class TicTacToe():
The purpose of the MainMenu function is to ask user to choose between New Game or Quit Game. As before to choose New Game the user has to type New and to quit game the user has to type Quit. After the user types "New" or "Quit" the value will be assigned to the variable named OPTION. In case the user types something other than the "New" or "Quit" the output will be shown "Invalid entry! Please try again." The entire code of the Main Menu method paced inside the TicTacToe class is given below.
class TicTacToe():
def MainMenu(self):
while True:
print("""\t Welcome to Tic-Tac-Toe game\n
\t 1. New Game (type New)\n
\t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New" or OPTION == "Quit":
break
else:
print("Invalid entry! Please try again.")
continue
return OPTION
The next method is a GamePrep method which is used to initialize empty table for tic-tac-toe game, ask the user to choose a character (X or O) in a game, and after user chooses the character the other is automatically assigned to the opponent in this case computer. It should be noted that the table in tic-tac-toe game is 5 times 5 table i.e. the list with 5 nested lists each containing 5 elements. The first and third list (lists with indexes 1 and 3) are filled with horizontal line ("a number of "-" characters). These lists represents horizontal borders in tic-tac-toe table. The same goes for columns i.e. first and third columns (indexes 1 and 3) are filled with "|" (Vertical lines). The TicTacToe class with MainMenu and GamePrep method is shown below.
class TicTacToe():
def MainMenu(self):
while True:
print("""\t Welcome to Tic-Tac-Toe game\n
\t 1. New Game (type New)\n
\t 2. Quit (type Quit)\n""")
OPTION = input("Choose an option:> ")
if OPTION == "New" or OPTION == "Quit":
break
else:
print("Invalid entry! Please try again.")
continue
return OPTION
def GamePrep(self):
test = [[] for i in range(0,5,1)]
print(test)
for i in range(len(test)):
if i%2 == 0:
count = 0
while count < 5:
if count%2 == 0:
test[i].append(" ")
else:
test[i].append("|")
count += 1
else:
test[i].append("_____________________")
for i in range(len(test)):
print(test[i])
print("""Enter a cell number. Cells are:
[0][0], [0][2], [0][4]
[2][0], [2][2], [2][4]
[4][0], [4][2], [4][4]""")
while True:
USER_INPUT = input("Type X or O:> ")
if USER_INPUT == "X":
COMPUTER = "O"
break
elif USER_INPUT == "O":
COMPUTER = "X"
break
elif USER_INPUT != "X" or USER_INPUT != "O":
print("Invalid Character! Please enter a valid character again!")
continue
return test, USER_INPUT, COMPUTER
The next method is PlaceCharacter method which will be used to place users character and computer character (X or O). The class with this method is shown below.
            class TicTacToe():
                def __init__(self): 
                    self.OPTION = ''
                    self.test = [[] for i in range(0,5,1)]
                    self.USER_INPUT = ''
                    self.COMPUTER = ''
            
                def MainMenu(self, OPTION):    
                    while True:
                        print("""\t Welcome to Tic-Tac-Toe game\n
                                  \t 1. New Game (type New)\n
                                  \t 2. Quit (type Quit)\n""")
                        OPTION = input("Choose an option:> ")
                        if OPTION == "New" or OPTION == "Quit":
                            break
                        else:
                            print("Invalid entery! Please try again.")
                            continue
                    return OPTION
                def GamePrep(self, test, USER_INPUT, COMPUTER):
                    print(test)
                    for i in range(len(test)):
                        if i%2 == 0:
                            count = 0
                            while count < 5:
                                if count%2 == 0:
                                    test[i].append(" ")
                                else:
                                    test[i].append("|")
                                count += 1
                        else:
                            test[i].append("_____________________")
                        
                    for i in range(len(test)):
                        print(test[i])
                    print("""Enter a cell number. Cells are:
                          [0][0], [0][2], [0][4]
                          [2][0], [2][2], [2][4]
                          [4][0], [4][2], [4][4]""")
                    while True:
                        USER_INPUT = input("Type X or O:> ")
                        if USER_INPUT == "X":
                            COMPUTER = "O"
                            break
                        elif USER_INPUT == "O":
                            COMPUTER = "X"
                            break
                        elif USER_INPUT != "X" or USER_INPUT != "O":
                            print("Invalid Character! Please enter a valid character again!")
                            continue
                    return test, USER_INPUT, COMPUTER
                def PlaceCharacter(self, test, USER_INPUT,COMPUTER):
                    while True:
                        try:
                            UR_CellRow = int(input("Enter Cell Row:>"))
                            UR_CellCol = int(input("Enter Cell Column:>"))
                            #check if the field is empty
                            if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
                                test[UR_CellRow][UR_CellCol] == COMPUTER:
                                print("Cell is already filled. Please choose another cell.")
                                continue
                            else:
                                test[UR_CellRow][UR_CellCol] = USER_INPUT
                                break
                        except ValueError:
                            print("Invalid input. Please try again!")
                            continue
                    # Show the map 
                    for i in range(len(test)):
                        print(test[i])
                    #########################################################
                    # Check empty cells 
                    #########################################################
                    Empty_rows = []
                    Empty_cols = []
                    for i in range(len(test)):
                        for j in range(len(test[i])):
                            if test[i][j] == " ":
                                Empty_rows.append(i)
                                Empty_cols.append(j)
                    print("Empty_rows = {}".format(Empty_rows))
                    print("Empty_cols = {}".format(Empty_cols))
                    index = random.randint(0,len(Empty_rows)-1)
                    print("index = {}".format(index))
                    CR_Index = Empty_rows[index]
                    CC_Index = Empty_cols[index]
                    print("CR_Index = {}".format(CR_Index))
                    print("CC_Index = {}".format(CC_Index))
                    test[CR_Index][CC_Index] = COMPUTER
                    # Show the map 
                    for i in range(len(test)):
                        print(test[i])
                    return test
The entire Class function is given below.
        class TicTacToe():
            def __init__(self): 
                self.OPTION = ''
                self.test = [[] for i in range(0,5,1)]
                self.USER_INPUT = ''
                self.COMPUTER = ''
        
            def MainMenu(self, OPTION):    
                while True:
                    print("""\t Welcome to Tic-Tac-Toe game\n
                              \t 1. New Game (type New)\n
                              \t 2. Quit (type Quit)\n""")
                    OPTION = input("Choose an option:> ")
                    if OPTION == "New" or OPTION == "Quit":
                        break
                    else:
                        print("Invalid entery! Please try again.")
                        continue
                return OPTION
            def GamePrep(self, test, USER_INPUT, COMPUTER):
                print(test)
                for i in range(len(test)):
                    if i%2 == 0:
                        count = 0
                        while count < 5:
                            if count%2 == 0:
                                test[i].append(" ")
                            else:
                                test[i].append("|")
                            count += 1
                    else:
                        test[i].append("_____________________")
                    
                for i in range(len(test)):
                    print(test[i])
                print("""Enter a cell number. Cells are:
                      [0][0], [0][2], [0][4]
                      [2][0], [2][2], [2][4]
                      [4][0], [4][2], [4][4]""")
                while True:
                    USER_INPUT = input("Type X or O:> ")
                    if USER_INPUT == "X":
                        COMPUTER = "O"
                        break
                    elif USER_INPUT == "O":
                        COMPUTER = "X"
                        break
                    elif USER_INPUT != "X" or USER_INPUT != "O":
                        print("Invalid Character! Please enter a valid character again!")
                        continue
                return test, USER_INPUT, COMPUTER
            def PlaceCharacter(self, test, USER_INPUT,COMPUTER):
                while True:
                    try:
                        UR_CellRow = int(input("Enter Cell Row:>"))
                        UR_CellCol = int(input("Enter Cell Column:>"))
                        #check if the field is empty
                        if test[UR_CellRow][UR_CellCol] == USER_INPUT or\
                            test[UR_CellRow][UR_CellCol] == COMPUTER:
                            print("Cell is already filled. Please choose another cell.")
                            continue
                        else:
                            test[UR_CellRow][UR_CellCol] = USER_INPUT
                            break
                    except ValueError:
                        print("Invalid input. Please try again!")
                        continue
                # Show the map 
                for i in range(len(test)):
                    print(test[i])
                #########################################################
                # Check empty cells 
                #########################################################
                Empty_rows = []
                Empty_cols = []
                for i in range(len(test)):
                    for j in range(len(test[i])):
                        if test[i][j] == " ":
                            Empty_rows.append(i)
                            Empty_cols.append(j)
                print("Empty_rows = {}".format(Empty_rows))
                print("Empty_cols = {}".format(Empty_cols))
                index = random.randint(0,len(Empty_rows)-1)
                print("index = {}".format(index))
                CR_Index = Empty_rows[index]
                CC_Index = Empty_cols[index]
                print("CR_Index = {}".format(CR_Index))
                print("CC_Index = {}".format(CC_Index))
                test[CR_Index][CC_Index] = COMPUTER
                # Show the map 
                for i in range(len(test)):
                    print(test[i])
                return test
            def ScoreCounting(self, test, USER_INPUT, COMPUTER):
                ###############################################
                # Counting SCORE 
                ###############################################
                # Check if three symbols are in rows 
                ###############################################
                SCORE_USER = 0 
                SCORE_COMPUTER = 0
                for i in range(len(test)):
                    if test[i][0] == USER_INPUT and test[i][2] == USER_INPUT and test[i][4] == USER_INPUT:
                        SCORE_USER = 1 
                        print("You Win!")
                    elif test[i][0] == COMPUTER and test[i][2] == COMPUTER and test[i][4] == COMPUTER:
                        SCORE_COMPUTER = 1
                        print("Computer Wins!")
                for j in range(len(test[0])): #Vertical Elements
                    if test[0][j] == USER_INPUT and test[2][j] == USER_INPUT and test[4][j] == USER_INPUT:
                        SCORE_USER = 1
                        print("You Win!")
                    if test[0][j] == COMPUTER and test[2][j] == COMPUTER and test[4][j] == COMPUTER:
                        SCORE_COMP = 1 
                        print("Computer Wins!")
                if test[0][0] == USER_INPUT and test[2][2] == USER_INPUT and test[4][4] == USER_INPUT:
                    SCORE_USER = 1 
                    print("You Win!")
                elif test[4][0] == USER_INPUT and test[2][2] == USER_INPUT and test[0][4] == USER_INPUT:
                    SCORE_USER = 1 
                    print("You Win!")
                elif test[0][0] == COMPUTER and test[2][2] == COMPUTER and test[4][4] == COMPUTER:
                    SCORE_USER = 1 
                    print("You Win!")
                elif test[4][0] == COMPUTER and test[2][2] == COMPUTER and test[0][4] == COMPUTER:
                    SCORE_USER = 1 
                    print("You Win!")
                return SCORE_USER, SCORE_COMPUTER
        while True:
            start = TicTacToe()
            Option = start.MainMenu(start.OPTION)
            if Option == "New":
                XO_Field, UserInput, Computer = start.GamePrep(start.test, start.USER_INPUT, start.COMPUTER)
                while True:
                    XO_Field_Modified = start.PlaceCharacter(XO_Field, UserInput, Computer)

Wednesday, September 14, 2022

How to create plot legend in Matplotlib?

To create legned in matplotlib plot the matplotlib.pyplot.legend() function is required. The general form of matplotlib.pyplot.legend function can be written as:
matplotlib.pyplot.legend(*args, **kwargs)
In the legend function, if specified without any extra arguments, the arguments are automatically determined. However, labels should be defined. The labels of multiple curves can be defined in two ways:
  • defining the label inside the matplotlib.pyplot.plot function as
    plt.plot(x,y, label="label name")
  • or
  • using set_label() method
    ax.set_label("label name")
    . It should be noted that in the second case the plot was created using fig,ax = plt.subplots(). Using plt.figure() with set_label() function will raise result in AttributeError: module 'matplotlib.pyplot' has no attribute 'set_label'
The alternative way is to define legend manually i.e. to pass an iterable (list) of plots followed by an iterable (list) of legend labels, respectively.
ax.legend([plo1, plot2, plot3], ['label1', 'label2', label3'])

Example 1 - Create plot containing following functions \begin{eqnarray} y1 &=& \sin(x)\\ y2 &=& \cos(x)\\ y3 &=& 0.5\cdot x + 1\\ y4 &=& 0.25\cdot x + 1 \end{eqnarray} and show the legend using the plt. legend() command.
Solution - The solution consist of three steps i.e. import libraries, calculate data, and plot the functions. For this example, we will need two libraries numpy and matplotlib.
import numpy as np
import matplotlib.pyplot as plt
The second step is to generate the data. The x values will be created using the np.arange command in a range from 0 to 5 with a step size of 0.001.
x = np.arange(0,5,0.001)
The functions will be created also using numpy functions sine and cosine while the remaining two functions require basic mathematical operations (multiplication and addition).
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 0.25*x+1
y4 = 0.5*x + 1
To plot this function first we need to set the figure size. As before we will use \(12\times 8[\mathrm{in}]\) figure size and matplotlib.pyplot.plot method to plot previously calculated function. To set the grid in the plot we will use matplotlib.pyplot.grid() function.
plt.figure(figsize=(12,8))
plt.plot(x,y1, label = "sin(x)")
plt.plot(x,y2,label="cos(x)")
plt.plot(x,y3, label="0.5*x + 1"
plt.plot(x,y4, label="0.25*x + 1")
plt.grid(True)
To set the legend in the plot we will use the matploltib.pyplot.legend() function.
plt.legend()
As seen from the previous code line the legend function does not require any argument since all labels are defined inside each of the plot functions. To show the plot we will use the matplotlib.pyplot.show function.
plt.show()
The entire code used in this example as well as the output are given below.

            The output (result) is shown in Figure 1. 
            
Figure 1 - Matplotlib plot showing four different mathematical functions with legend position at top left corner.
Example 2 Create a plot with legned that contains the same functions from Example 1 using matplotlib.pyplot.subplots() function ?
Soltions - Look into previous example to see how the functions were generated. To code for generating x-values and y1,y2,y3, and y4 values is given below.
x = np.arange(0,5,0.001)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 0.5*x + 1
y4 = 0.25*x + 1
The function matplotlib.pyplot.subplots() return two objects and these are fig (figure) and ax (axes) so we will define two variables (fig, ax) that will be equal to the aforementioned function. We will set the figure size (figisize) to \(12\times 8 [\mathrm{in}]\) as an argument of a matplotlib.pyplot.subplots() function.
fig, ax = plt.subplots(figsize=(12,8))
Now we will use the ax object to plot each function and each plot is assigned to a specific variable name (curve1, ... curve4). After plots are prepared, the grid is defined, and labels are assigned to each plot (variable from curve1 to cruve4). To show all the previously defined labels we have to call a matplotlib.pyplot.legend() function. Finally, to show the plot we used the matplotlib.pyplot.show().
curve1, = ax.plot(x,y1)
curve2, = ax.plot(x,y2)
curve3, = ax.plot(x,y3)
curve4, = ax.plot(x,y4)
ax.grid(True)
curve1.set_label('sin(x)')
curve2.set_label('cos(x)')
curve3.set_label('0.5*x+1')
curve4.set_label('0.25*x+1')
ax.legend()
plt.show()
Output:
Figure 2 - Plot from Example 1 created using matplotlib.pyplot.subplots()
Example 3 Plot functions 0.5*sin(x) and sin(x) in range from 0 to 5 by explicitly listing the legend and using matplotlib.pyplot.subplots() function.
Solution: As in previous examples we have to import two libraries i.e. numpy and matplotlib.
import numpy
import matplotlib.pyplot as plt
To generate the x and y coordinates of the function first we have to generate the x values in a range from 0 to 5 and then use these values as arguments to calculate y. The x values will be created from 0 to 5 using 0.001 steps using function np.arange. Both functions 0.5*sin(x) and sin(x) will be calculated for all values of x using np.sin(x) function.
x = np.arange(0,5,0.001)
y1 = 0.5*np.sin(x)
y2 = np.sin(x)
Regarding the legend function and how to set labels the procedure is very simple. Instead of using set_label function, we will write labels inside the plot functions.
import matplotlib.pyplot
import numpy as np, import matplotlib pypplot as plt, import random
fig, ax = plt.subplots(figsize=(12,8))
line1, = ax.plot(x,y1, label="0.5*sin(x)")
line2, = ax.plot(x,y2, label="sin(x)")
ax.legend(handles=[line1,line2])
ax.grid(True)
plt.show()
Figure 3 - Plot with legend created by explicitly listing the legend and using matplotlib.pyplot.subplots() function
Instead of creating labels in the plot function, we could symply type these labels inside the legend function. However, to do this we have to remove the labels from the plot function.
line1, = ax.plot(x,y1)
line2, = ax.plot(x,y2)
ax.legend(['0.5*sin(x)', 'sin(x)'])