0

Processing multiple text files using python

Included in USAOnline is the baby name file for 1986 (yob1986.txt). For this
assignment, you will need to read in both the 1986 and 2016 (yob2016.txt) files. The user
should enter a baby name to search for. Your program should not only give the total (not separated
by gender) number of babies named that for both 1986 and 2016, but also give the percentage
change from 1986 to 2016 for that name

Code

f = open("yob2016.txt")
f2 = open("yob1986.txt")
names_data_2016 = {}
names_data_1986 = {}
for row in f:
row = row.rstrip()
data = row.split(",")
name = data[0]
count = int(data[2])
if name not in names_data_2016.keys():
names_data_2016[name] = 0
names_data_2016[name] += count

for row in f2:
row = row.rstrip()
data = row.split(",")
name = data[0]
count = int(data[2])
if name not in names_data_1986.keys():
names_data_1986[name] = 0
names_data_1986[name] += count

name = input("Enter name : ").title()
if name in names_data_2016 and name in names_data_1986:
count_2016 = names_data_2016[name]
count_1986 = names_data_1986[name]
print(name,"in 2016 counts =",count_2016)
print(name,"in 1986 counts =",count_1986)
total = count_2016 + count_1986
change = count_2016 - count_1986
st = "increases"
if change < 0:
st = "decreases"
change = change * -1
percentage = round((change * 100) / total,2)
print(f"Percentage change from 1986 to 2016 {st} by {percentage}%")
else:
print("Name not in files")

Output

keep visiting : shaadcoding

1

processing text files using python

Working with the 2016 baby name file (yob2016.txt) again, your code should
calculate the total number of babies whose names begin with each letter of the alphabet. Then,
your code should print out a nicely formatted table with each letter of the alphabet and the total
number of babies with names beginning with that letter.

Code

f = open("yob2016.txt")
letters_count = {}
for row in f:
    row = row.rstrip()
    data = row.split(",")
    name = data[0]
    count = data[2]
    if name[0] not in letters_count.keys():
        letters_count[name[0]] = 0
    letters_count[name[0]] += int(count)
print('{:<15} | {:<15} '.format("LETTER","COUNT"))
print("="*30)
for k in sorted(letters_count):
    print('   {:<10}   | {:<15} '.format(k,letters_count[k]))
print("="*30)

Output

keep visiting : shaadcoding

0

python bill calculator for grocery shop project using file handling and lists

Assume that the user has a file (named grocerylist.dat) which includes a
grocery list with three columns of data: the name of the item, the quantity of the item to be bought,
and the price of each item. These columns are separated by commas. There is also a header line for
the file.
Your program should read in this file, print out a well-formatted table with each item, as well as its
quantity, price, and total price.

Code

f = open("grocerylist.dat")
header = f.readline().split(",")

print('{:<20} | {:<15} | {:<20} | {:<20}'.format(header[0],header[1],header[2].rstrip() ,'TOTAL'))
print("="*70)
i = 0
final_total = 0
for row in f:
row = row.rstrip()
data = row.split(",")
item = data[0]
qnty = data[1]
price = data[2]
total = float(qnty) * float(price)
final_total += total
print('{:<20} | {:<15} | {:<20} | {:<20.2f}'.format(item,qnty,price ,total))
print("="*70)
print('{:<20} {:<15} {:<20} | {:<20.2f}'.format("FINAL TOTAL","","" ,final_total))

Output

output

keep visiting : shaadcoding

2

Rock, Paper, Scissors, Saw Game in Python

Project requires students to create a design for a text-based “Rock, Paper, Scissors, and Saw”
game and then implement it in Python.

Scope

The software to be created will be a stand-alone PC representation of the hand game called
“Rock, Paper, Scissors, and Saw”, implemented with procedural approach using Python. It will
have two human players and a computer acting as the third player.

General Description

When user(s) starts the program, he will be prompted for the names of the two human players.
These values will be used for all prompts and statistics in the program.
Then there will be a menu with the following selections: “1. Play game”, “2. Show game rules”,
“3. Show statistics”, and “4. Exit” in that order. Rules selection will provide rules of the game,
statistics will show the accumulative wins, loses, and ties per each player (both rounds and
games), and exit will close the program.
When play game is selected, each player will be able to select his weapon (rock, paper, scissors,
or saw) and computer will make its choice. Each of the players will be playing against the
computer. A game will consist of 3 rounds. After each round either a player or computer will be
the winner of the round and after 3 rounds, again either computer or player will be the winner of
the game. User(s) will be able to run multiple games and their wins/loses/ties will be displayed in
the statistics option along with the overall human winner.

CODE

import random

games = [[0,0],[0,0],[0,0],[0,0]]
rounds = [[0,0],[0,0],[0,0],[0,0]]

def check_name(name):
if not name:
return False
elif len(name) < 5 or len(name) > 20:
return False
else:
return True
def player1_name():
while True:
name = input("What is the name of the first player?")
if check_name(name):
return name
else:
print("Name must contain letters(5-20)")
def player2_name(p1):
while True:
name = input("What is the name of the second player?")
if check_name(name):
if name.lower() == p1.lower():
print("Second player name must be different from first player")
else:
return name
else:
print("Name must contain letters(5-20)")
def menu():
while True:
print("1. Play game")
print("2. Show game rules")
print("3. Show statistics")
print("4. Exit")
ch = input("Enter your choice : ")
if ch.isdigit() and int(ch) > 0 and int(ch) <= 4:
return int(ch)
else:
print("choice must be from 1 - 5")
def rules():
print('''[R4.1] When game starts, each Player gets prompted for his selection of Rock, Paper, Scissors,
and Saw. The prompt must use the player’s name.
[R4.2] Computer makes its random selection to be used against each player (same selection
will be used against both human players)
Software Requirements Specification Page iii
<RPS Game>
[R4.3] For each player, program displays that player’s selection, computer’s selection and who
won that round (computer or player)
[R4.4] Next round repeats the prompting and announcement of the round winners. This is
repeated for a total of 3 rounds.
[R4.5] Once all 3 rounds are completed winners of the game are announced for each player.
Just like rounds, each player is playing against the computer and so the winner of the game is
either the player or the computer.
[R4.6] The winner of the game is one who won most rounds. The program must account for
ties. For example, if a player won 2 rounds and lost 1 round, then he won the game against the
computer. If the player won 1 round, lost 1 round, and tied 1 round then he tied the game
against the computer.
[R4.7] After game winners are announced, user is able to go back to menu where they can
again select one of the options.
[R4.8] Users can play as many games as they want''')
def valid_weapon(w):
if w not in ['rk', 'pr', 'sc', 'sw']:
return False
return True

def check_winner(w1,w2):
if w1 == w2:
return -1
if w1=='rk':
if w2 in ['sc','sw']:
return 1
return 2
if w1 == 'sc':
if w2 in ['rk','sw']:
return 2
else:
return 1
if w1 == 'pr':
if w2 in ['sc','sw']:
return 2
else:
return 1
if w1 == 'sw':
if w2 in ['sc','pr']:
return 1
else:
return 2
def play(p1,p2):
round = 0
gwinner1 = 0
gwinner2 = 0
while round != 3:
print(f"ROUND {round+1}\n***************")
print("Enter 'rk' for Rock, 'pr' for Paper, 'sc' for Scissors, 'sw' for Saw")
w1 = input(f"{p1}'s weapon? : ")
if valid_weapon(w1):
while True:
w2 = input(f"{p2}'s weapon? : ")
if valid_weapon(w2):
break
else:
print("invalid choice!!!")
continue
cw = random.choice(['rk', 'pr', 'sc', 'sw'])
#print(cw)
winner1 = check_winner(w1,cw)
rounds[0][0] += 1
rounds[0][1] += 1
if winner1 == -1:
rounds[3][0] += 1
print(f"{p1} ties in round {round + 1} against computer")
elif winner1 == 1:
rounds[1][0] += 1
gwinner1 += 1
print(f"{p1} wins in round {round+1} against computer")
else:
rounds[2][0] += 1
print(f"{p1} lose in round {round + 1} against computer")
winner2 = check_winner(w2,cw)
if winner2 == -1:
rounds[3][1] += 1
print(f"{p2} ties in round {round + 1} against computer")
elif winner2 == 1:
rounds[1][1] += 1
gwinner2 += 1
print(f"{p2} wins in round {round + 1} against computer")
else:
rounds[2][1] += 1
print(f"{p2} lose in round {round + 1} against computer")
round += 1


else:
print("invalid choice!!!")
continue
games[0][0] += 1
games[0][1] += 1
print("\n******Game Result*****")
if gwinner1 == gwinner2:
games[3][0] += 1
games[3][1] += 1
print("Game ties")
if gwinner1 < gwinner2:
games[1][1] += 1
games[2][0] += 1
print(f"{p2} wins")
if gwinner1 > gwinner2:
games[1][0] += 1
games[2][1] += 1
print(f"{p1} wins")
input("Enter to continue...")


def stats(p1,p2):
print("\n******STATS******\n")
print(f"{p1} STATS")
print(f"Total Games = ",games[0][0])
print(f"Games Won = ",games[1][0])
print(f"Games Lost = ",games[2][0])
print(f"Games Ties = ",games[3][0])
print(f"Total Rounds = ",rounds[0][0])
print(f"Rounds Won = ",rounds[1][0])
print(f"Rounds Lost = ",rounds[2][0])
print(f"Rounds Ties = ",rounds[3][0])
print()
print(f"{p2} STATS")
print(f"Total Games = ", games[0][1])
print(f"Games Won = ", games[1][1])
print(f"Games Lost = ", games[2][1])
print(f"Games Ties = ", games[3][1])
print(f"Total Rounds = ", rounds[0][1])
print(f"Rounds Won = ", rounds[1][1])
print(f"Rounds Lost = ", rounds[2][1])
print(f"Rounds Ties = ", rounds[3][1])

def main():
p1 = player1_name()
p2 = player2_name(p1)
while True:
ch = menu()
if ch == 1:
play(p1,p2)
elif ch == 2:
rules()
elif ch == 3:
stats(p1,p2)
elif ch == 4:
print("Good Bye!")
break

if __name__ == '__main__':
main()

Demo

keep visiting : shaadcoding

0

Evaluate String expression but converting to tokens using python

In this program, we will evaluate a string but converting it to tokens and calculate if the string is a valid arithmetic expression

Code

def check_exp_validity(exp):
try:
eval(exp)
return True
except SyntaxError:
print("Incomplete expression.")
return False
except TypeError:
print("Incomplete expression.")
return False
except ZeroDivisionError:
print("Division by zero.")
return False

def calculate(tokens):
string = ''
if "(" in tokens:
start = tokens.index("(")
end = tokens.index(")")
s = tokens[start:end+1]
try:
res1 = str(eval(s))
except ZeroDivisionError:
print("Division by zero.")
return
tokens = tokens.replace(s,'')
if start == 0:
tokens = res1 + tokens
else:
tokens = tokens + res1
lst = []
for c in tokens:
if ('+' in string or '-' in string or '*' in string or '/' in string) and c in ['+','-','*','/']:
lst.append(string)
string = ''
string += c
lst.append(string)
try:
lst[0] = str(eval(lst[0]))
fexp = ''.join(lst)
result = eval(fexp)
print(round(result,2))
except ZeroDivisionError:
print("Division by zero.")
return



exp = input("??> ").strip()
if check_exp_validity(exp):
calculate(exp)

Output


??> 56+65
121

keep visiting : shaadcoding

1

Use of Python in Chemistry

Description

The program has a choice of two methods to calculate volume of a molecule: Van der Waals volume and the ideal gas law.

IMPORTANT: For this to work, an empty excel csv file named perfectGas needs to be saved in the same place as the file for the code is saved in.

If choice 1 is entered, the volume is calculated by Wan der Waals formula and if 2 is entered, the volume is calculated by PV=nRT

1) Option 1 calculates the volume with Van der Waals volume formula

The user must enter the formula of molecule which are in the elements list, followed by the number of aromatic and non-aromatic rings.
An example calculation of benzene is given below

Input instructions for Wan der Waals and output against the input values:

””’Enter the choice : 1
Please enter the formula of molecule : C6H6
Enter the number of non-aromatic rings in the molecule : 0
Enter the number of aromatic rings in the molecule : 1

Output:
Occurrence of molecule in elements list : [‘C’, 6, ‘H’, 6]
Van der Waals volume is: 81.17 ų (Å3 it is taken as unit ) ””””

2) Option 2 uses the ideal gas law (pV = nRT) to calculate volume of a molecule or other parameters if the user chooses

The user can press p, V, n or T to calculate any parameters and the values are saved in a csv file.

The code can accept these parameters in non-standard units such as atmospheres and degrees Celsius.

Input Instructions for PV=nRT and output against the input values:

”””Enter the choice : 2
What do you want to calculate? (entry is case sensitive): For pressure press ‘p’ , for volume press ‘V’ , for moles press ‘n’ and for temperature press ‘T’ : V

Enter the temperature in °C : 25
Enter the Pressure in atm : 1
Enter the number of Moles : 0.05

Output:

Pressure: 1.0 atm Calculated Volume : 0.0012232021218850234 m³ Moles: 0.05 Temperature: 25.0 °C

IMPORTANT : Again, to reiterate, for this to work an empty excel csv file named perfectGas needs to be saved in the same place as the file for the code is saved in.

Mostly all functions are called in exec function which is in the last of the code .

Comments are included in the code for easier code reading

CODE


#open and save a blank excel file called perfectGas.csv in same place as this code as per ReadMe.txt file
import matplotlib.pyplot as plt
# matplotlib library for graph plotting
import re
# re library for regex
import math
# math library for math functions
import string
elements ={"H": 1.20, "He": 1.40, "Li": 1.82, "Be": 1.53,
"B": 1.92, "C": 1.70, "N": 1.55, "O": 1.52, "F": 1.47,
"Ne": 1.54, "Na": 2.27, "Mg": 1.73, "Al": 1.84,
"Si": 2.10, "P": 1.80, "S": 1.80, "Cl": 1.75,
"Ar": 1.88, "K": 2.75, "Ca": 2.31, "Sc": 2.30,
"Ti": 2.15, "V": 2.05, "Cr": 2.00, "Mn": 1.97,
"Fe": 1.94, "Co": 2.00, "Ni":1.63, "Cu":1.40,
"Zn": 1.39, "Ga": 1.87, "Ge":2.11, "As":1.85,
"Se": 1.90, "Br": 1.85, "Kr": 2.02, "Rb": 3.03,
"Sr": 2.49, "Y": 2.40, "Zr": 1.86, "Nb": 2.07,
"Mo": 2.09, "Tc": 2.05, "Ru": 2.05, "Rh": 2.00,
"Pd": 1.63, "Ag": 1.72, "Cd": 1.58, "In": 1.93,
"Sn": 2.17, "Sb": 2.06, "Te": 2.06, "I": 1.98,
"Xe": 2.16, "Cs": 3.43, "Ba": 2.68, "La": 2.40,
}
#atomic radii of elements
# user can choose to calculate volume with either the ideal gas equation, or the Van der Waals volume equation
print ("Hello, what formula do you want to use to calculate the volume of your molecule?")
print("----Press 1 for Van der Waals solution------- ")
print("----Press 2 for ideal gas law solution----- ")
choice=int(input("Enter the choice : "))

if(choice==1):
no_of_bonds = 0
volume = 0
x = 0
tempvol = 0
found = False
while found == False:
found = True
# inputs for Wan der Waals solution
# Enter the formula from the elements in the above list
molecule = input("Please enter the formula of molecule : ")
# regex include for proper format to find molecule in element list
list_of_molecule = re.findall('[A-Z][a-z]?|[0-9]+', molecule)
non_aromatic_rings = int(input("Enter the number of non aromatic rings in the molecule : "))
aromatic_rings = int(input("Enter the number of aromatic rings in the molecule : "))
moleculelist_maxlenth = 2 * len(list_of_molecule)
for i in range(0, moleculelist_maxlenth):
try:
if (list_of_molecule[i] in elements) and (list_of_molecule[i + 1] in elements):
list_of_molecule.insert(i + 1, "1")
except IndexError:
break

if (list_of_molecule[-1] in elements):
list_of_molecule.append("1")

for i in range(0, len(list_of_molecule)):
if list_of_molecule[i].isdigit():
list_of_molecule[i] = int(list_of_molecule[i])
# Occurrence of molecule in elements list
print(" ")
print("Occurrence of molecule in elements list :" ,list_of_molecule)
for a in range(0, len(list_of_molecule)):
if (list_of_molecule[a] in elements):
tempvol = ((4 / 3) * math.pi * pow((elements[list_of_molecule[a]]), 3))
volume = volume + tempvol
else:
volume = volume - tempvol
tempvol = tempvol * (int(list_of_molecule[a]))
volume = volume + tempvol
no_of_bonds = no_of_bonds + list_of_molecule[a]
# bonds calculation by number of aromatic rings and non aromatic rings
no_of_bonds = no_of_bonds - 1 + aromatic_rings + non_aromatic_rings
volume = volume - (5.92 * no_of_bonds) - (14.7 * aromatic_rings) - (3.8 * non_aromatic_rings)
print("Van der Waals volume is:",round(abs(volume) , 2), "Å\u00b3")

# Angstroms cubed, Å3 is the unit

elif(choice==2):
r1 = 298.15
# inputs of either temperature ,pressure ,number of moles, or volume and the other parameters will be asked for
what = str(input("What do you want to calculate? (entry is case sensitive): For pressure press 'p' , for volume press 'V' , for moles press 'n' and for temperature press 'T' : "))
if(what=='p'):
t1 = float(input("Enter the temperature in °C : "))
pressure=None
V = float(input("Enter the volume in m\u00b3 :"))
n = float(input("Enter the number of moles :"))
elif(what=='V'):
t1 = float(input("Enter the temperature in °C : "))
pressure = float((input("Enter the pressure in atm : ")))
V=None
n = float(input("Enter the number of moles :"))

elif(what=='T'):
pressure = float((input("Enter the pressure in atm : ")))
V = float(input("Enter the volume in m\u00b3 :"))
n = float(input("Enter the number of moles :"))
t1=None
elif(what=='n'):
t1 = float(input("Enter the temperature in °C : "))
pressure = float((input("Enter the pressure in atm : ")))
n=None
V = float(input("Enter the volume in m\u00b3 :"))
else:
print("Invalid Choice")

#the user can choose to calculate pressure, temperature, moles or volume
# t1 = float(input("Enter the temperature °C : "))
# pressure = float((input("Enter the Pressure in atm : ")))
# V=float(input("Enter the volume in meters cubed :"))
# n=float(input("Enter the numbers of Moles :"))
R = 0
S = 0



'''
parameters as input: data(list of values calculated in perfectgGas function), filename
This function is used to save the data calculated and readings in csv format
Csv files are made by using pandas library

'''
def perfectGasCSV(data, filename="perfectGas.csv"):
import pandas as pd
output = pd.DataFrame()
output = output.append(data, ignore_index=True)
output.to_csv(filename, index=False, mode='a', header=False)


'''
The ideal gas solution takes three parameters from the user and calculates the missing one, it also
calls the above function perfectGasCSV to save data points in csv file.
'''

def perfectgas(what, p, V, n, T):

if what is None:
return

R = 8.314
data = []

# if p is selected, pressure is calculated
if (what == "p"):
p = (((n) * R * (T+ 273.15 ) / (V))/ 101325)

data = {"p": p, "V": V, "n": n, "T": T}
perfectGasCSV(data)
result = "The Calculated Pressure : {0} atm Volume: {1} m\u00b3 Moles: {2} Temperature: {3} °C".format(p, V, n, T)
print(" ")
print(result)
return p
# if V is selected, volume is calculated
elif (what == "V"):
V = (n) * R * (T + 273.15) / (p * 101325)

data = {"p": p, "V": V, "n": n, "T": T}
perfectGasCSV(data)
result = "Pressure: {0} atm Calculated Volume : {1} m\u00b3 Moles: {2} Temperature: {3} °C".format(p, V, n, T) # data
print(" ")
print(result)
return V
# if n is selected, number of moles is calculated
elif (what == "n"):

n = ((p * 101325 ) * (V)) / (R * (T + 273.15))

data = {"p": p, "V": V, "n": n, "T": T}
perfectGasCSV(data)
result = "Pressure: {0} atm Volume: {1} m\u00b3 Calculated Moles: {2} Temperature: {3} °C".format(p, V, n, T)
print(" ")
print(result)
return n
# if T is selected, temperature is calculated
elif (what == "T"):

T = ((((p * 101325) * (V)) / ((n) * R))-273.15)

data = {"p": p, "V": V, "n": n, "T": T}
perfectGasCSV(data)
result = "Pressure: {0} atm Volume: {1} m\u00b3 Moles: {2} Calculated Temperature : {3} °C".format(p, V, n, T)
print(" ")
print(result)
return T

else:

return "Incorrect Input"


#unknown is calculated


def exec(what, pressure, V, n, t1, R, S):


if (what and R and S):
x_lab = ""
y_lab = ""
data_x = []
data_y = []
y=range(R,S)
for i in y:
# if the pressure is calculated, it is then appended in data list
if what == 'p':
data_x.append(i)
data_y.append(perfectgas(what, None, i, n, t1))

# if the volume is calculated, it is then appended in data list
elif what == 'V':
data_x.append(i)
data_y.append(perfectgas(what, i, None, n, t1))

# if the temperature is calculated, it is then appended in data list
elif (what == 'T'):
data_x.append(i)
data_y.append(perfectgas(what, pressure, i, n, None))



else:

perfectgas(what, pressure, V, n, t1)

# calling of the main function exec for all possible operations, all functions of code are called inside this function
exec(what,pressure,V,n,t1, R, S)


else:
print("Invalid Choice .Please Press 1 or 2 for operations")


0

Orthokon game in python

Description:

Write a class called OrthokonBoard that represents the board for a two-player game that is played
on a 4×4 grid. This class does not do everything needed to play a game – it’s just responsible for
handling the rules concerning the game board. Things like asking the user for moves, printing results
for the user, keeping track of whose turn it is, and running the game loop would be the responsibility
of one or more other classes. You’re already familiar with breaking down a complex task into multiple
functions. Likewise, a large, complex program can be simplified by being broken down into multiple
classes, each of which has multiple methods. Objects of these different classes then interact with
each other to accomplish the desired tasks. This is known as object-oriented programming (OOP). you are only concerned with the
OrthokonBoard class.
The board starts with four red pieces on row 0 and four yellow pieces on row 3. A valid move
consists of a player moving one of their pieces orthogonally or diagonally as far as it can go until it
hits another piece or the edge of the board (it must move at least one space). After the piece
stops, any opponent pieces on orthogonally adjacent squares are flipped over to its color. The
OrthokonBoard class doesn’t keep track of whose turn it is, so it will allow multiple moves by the
same player consecutively. A player wins upon making a move that either flips over the remaining
opponent pieces or leaves the opponent without a move.
The class should have the following private data members: a representation of the board, and the
current state, which holds one of the three following values: “RED_WON”, “YELLOW_WON”, or
“UNFINISHED”.
It should have an init method that initializes the starting board positions, initializes the current_state
to “UNFINISHED”, and appropriately initializes any other data members. Tip: Probably the easiest
way of representing the board is to use a list of lists. The init method could then initialize the board to
a list of 4 lists, each of which contains 4 empty strings (or whatever character you want to use to
represent an empty space).
It should have a get method named get_current_state, which returns the current state.
It should have a method named make_move that takes four parameters – the row and column (in
that order) of the piece being moved, and the row and column (in that order) of the square it’s being
moved to. If the game has already been won, or if the move is not valid, make_move should just
return False. Otherwise, it should record the move, update the board and the current state, and
return True. To update the current state, you need to detect if this move causes a win for either
player.
It’s not required, but you’ll probably find it useful for testing and debugging to have a method that
prints out the board.
Whether you think of the list indices as being [row][column] or [column][row] doesn’t matter as long
as you’re consistent

CODE

# Constructing a class OrthokonBoard
class OrthokonBoard:
    """ This class is responsible for handling the rules concerning the game board. This class has
    a representation of the board, and the current state, which holds one of the three following
    values: "RED_WON", "YELLOW_WON", or "UNFINISHED". This class has a get method for the current state
    and has a make move method that takes four parameters."""

    # constructor with initial 4x4 board
    def __init__(self):
        """This init method creates the board with Red at index 0 and Y at index 3. We also initialize the current state
        to "UNFINISHED"""
        self.__board = [['R', 'R', 'R', 'R'],
                        ['', '', '', ''],
                        ['', '', '', ''],
                        ['Y', 'Y', 'Y', 'Y']]
        self.__current_state = "UNFINISHED"

    # method to print board
    def print_board(self):
        """This method is used to print the board"""
        for row1 in range(len(self.__board)):
            print(self.__board[row1])

        print()

    # methods return current state of game
    def get_current_state(self):
        return self.__current_state

    # This method return true if it's valid diagonal
    def valid_diagonal(self, row1, col1, row2, col2):
        """This method is used to check if the move is valid in the diagonal aspect of the move"""
        # this condition checks if both points are diagonal to each other
        if abs(row2 - col2) == abs(row1 - col1) or row2 + col2 == row1 + col1:
            # This will check diagonal from bottom row
            # if it is diagonal then it will check that if it is backward diagonal
            if row1 > row2:
                if col1 > col2:
                    # getting first element attach with current element in diagonal
                    temp = row1 - 1
                    b = col1 - 1
                    # if it is not empty then returning False else True
                    if self.__board[temp][b] != '':
                        return False
                    else:
                        return True
                # if it is diagonal then it will check that if it is forward diagonal
                else:
                    # getting first element attach with current element in diagonal
                    temp = row1 - 1
                    b = col1 + 1
                    # if it is not empty then returning False else True
                    if self.__board[temp][b] != '':
                        return False
                    else:
                        return True

            else:
                # This will check diagonal from top row
                if col1 > col2:
                    temp = row1 + 1
                    b = col1 - 1
                    if self.__board[temp][b] != '':
                        return False
                    else:
                        return True
                else:
                    temp = row1 + 1
                    b = col1 + 1
                    if temp > 3:
                        return True
                    if self.__board[temp][b] != '':
                        return False
                    else:
                        return True

            # return True
        else:
            return False

    # This method if check if target place is valid row
    def valid_row(self, row1, col1, row2, col2):
        """This method checks if the target destination of the piece is a valid row"""
        # check if both points are in same row
        if row1 == row2:
            # if target is in down direction
            if col1 > col2:
                temp = col1 - 1
                # loop to check if no element is placed in path of current color to target place in row
                while temp != col2 or temp == 0:
                    if self.__board[row1][temp] != '':
                        return -1
                    temp -= 1
                return temp
            else:
                # if target is in upward direction
                temp = col1 + 1
                while temp != col2:
                    if self.__board[row1][temp] != '':
                        return -1
                    temp += 1
                return temp
        else:
            return -1

    # This method if check if target place is valid column
    def valid_col(self, row1, col1, row2, col2):
        """This method determines if the target destination of the piece is a valid column"""
        # check if both points are in same column
        if col1 == col2:
            # if target is in down direction in column
            if row1 > row2:
                temp = row1 - 1
                # loop to check if no element is placed in path of current color to target place in column
                while temp != row2 or temp == 0:
                    if self.__board[temp][col1] != '':
                        return -1
                    temp -= 1
                return temp
            else:
                # if target is in upward direction in column
                temp = row1 + 1
                while temp != row2:
                    if temp > 3:
                        break
                    if self.__board[temp][col1] != '':
                        return -1
                    temp += 1
                return temp
        else:
            return -1

    # This method will flip color on board
    def flipColor(self, from_row, from_col, to_row, to_col):
        """This method flips the color on the board of the piece orthogonal to it as per the rules of the game"""
        # getting symbol from previous place
        symbol = self.__board[from_row][from_col]
        # setting empty on previous place
        self.__board[from_row][from_col] = ''
        # setting symbol on target place
        self.__board[to_row][to_col] = symbol
        # if its row 0 then making attached top cell to same color
        if to_row == 0:
            if self.__board[to_row + 1][to_col] != '':
                self.__board[to_row + 1][to_col] = symbol
        # if its row 1 and 2then making attached top cell and bottom cell of it to same color
        if to_row == 1 or to_row == 2:
            if self.__board[to_row + 1][to_col] != '':
                self.__board[to_row + 1][to_col] = symbol
            if self.__board[to_row - 1][to_col] != '':
                self.__board[to_row - 1][to_col] = symbol
        # if its row 3 then making attached top cell to same color
        if to_row == 3:
            if self.__board[to_row - 1][to_col] != '':
                self.__board[to_row - 1][to_col] = symbol

    # This will make move and make changes in board and state accordingly
    def make_move(self, from_row, from_col, to_row, to_col):
        state = self.get_current_state()
        # getting both point color symbols
        p1 = self.__board[from_row][from_col]
        p2 = self.__board[to_row][to_col]
        count = 0
        # all combination of board
        combinations = [[0, 0], [0, 1], [0, 2], [0, 3],
                        [1, 0], [1, 1], [1, 2], [1, 3],
                        [2, 0], [2, 1], [2, 2], [2, 3],
                        [3, 0], [3, 1], [3, 2], [3, 3]]
        # if any index is not less than 4
        if from_row < 4 and to_row < 4 and from_col < 4 and to_col < 4:
            # checks if any combination/move possible ,if count remain 0 then it means color is blocked so other
            # color will win
            for cmb in combinations:
                x = cmb[0]
                y = cmb[1]
                # if source and target are same
                if x == to_row and y == to_col:
                    continue
                # check for all valid move in row,col or diagnal
                is_valid_row = self.valid_row(from_row, from_col, x, y)
                is_valid_column = self.valid_col(from_row, from_col, x, y)
                is_valid_diagonal = self.valid_diagonal(from_row, from_col, x, y)
                if is_valid_row == -1 and is_valid_column == -1 and is_valid_diagonal == False:
                    pass
                else:
                    count += 1
            # print(count)
            # if none of combination pass then color other than current one wins
            if count == 0:
                if self.__board[from_row][from_col] == 'R':
                    self.__current_state = "O_WON"
                if self.__board[from_row][from_col] == 'Y':
                    self.__current_state = "X_WON"

            # if no one wins
            if state == "UNFINISHED" and p1 != '' and p2 == '':
                # checking move validity
                is_valid_row = self.valid_row(from_row, from_col, to_row, to_col)
                is_valid_column = self.valid_col(from_row, from_col, to_row, to_col)
                is_valid_diagonal = self.valid_diagonal(from_row, from_col, to_row, to_col)
                # if move is not valid returning False
                if is_valid_row == -1 and is_valid_column == -1 and is_valid_diagonal == False:
                    return False
                else:
                    # if move is valid flipping color and changing position
                    self.flipColor(from_row, from_col, to_row, to_col)

            else:
                return False
        else:
            return False







board = OrthokonBoard()
board.make_move(3,2,1,0) # The yellow player moves temp piece diagonally, flipping one red piece to yellow
board.make_move(0,2,2,0) # The red player moves temp piece diagonally, flipping two yellow pieces to red
board.print_board()
print(board.get_current_state())

keep visiting : shaadcoding

1

Hangman Game Using Python Tkinter In Simplest Way

Hangman Game Using Python Tkinter

hangman game in python for beginners

The Hangman Game is GUI situated In Tkinter Python is written in python programming language, In this Hangman Game Project is to execute the Hangman Game Using Python. It doesn’t need a particular modules other than irregular and time. Python circles and capacities are sufficient to assemble this game here. In This article I will tell you on The best way To Code A Hangman Game In Python.

A Hangman Game On Python is tied in with speculating letters (A-Z) to shape the words. On the off chance that the player surmises the right letter that is inside the word, the letter shows up at its right positions. The client needs to figure the right word until a man is hung, then, at that point the game is finished.

CODE

from tkinter import messagebox
from tkinter import *
import random


window = Tk()
window.title("Hangman")
window.resizable(0, 0)

word_list = ['UNIVERSITY','COUNTRY','FREELANCING','POSITIVITY','NATURAL','COMEDY',
'EXCELLENT','OUTSTANDING',"CROCODILE","STRAWBERRY"]

photos = [PhotoImage(file="1.png"),PhotoImage(file="2.png"),PhotoImage(file="3.png"),
PhotoImage(file="4.png"),PhotoImage(file="5.png"),PhotoImage(file="6.png"),PhotoImage(file="7.png")]


def play():
global spaced_word
global tries
tries = 0
imgLabel.config(image=photos[0])
random_word = random.choice(word_list)
spaced_word = " ".join(random_word)
lblWord.set(" ".join("_" * len(random_word)))


def guess(event):
letter_to_guess = txtWord.get().upper()
txtWord.set("")
global tries
if tries < 6:
txt = list(spaced_word)
print(txt)
guessed = list(lblWord.get())
if spaced_word.count(letter_to_guess) > 0:
for c in range(len(txt)):
if txt[c] == letter_to_guess:
guessed[c] = letter_to_guess
lblWord.set("".join(guessed))
if lblWord.get() == spaced_word:
messagebox.showinfo("Hangman", "You guessed it!")
play()

else:
tries += 1
print(tries)
imgLabel.config(image=photos[tries])
if tries == 6:
messagebox.showwarning("Hangman", "Game over")
imgLabel = Label(window)
imgLabel.grid(row=0, column=0, columnspan=3, padx=10, pady= 40)
imgLabel.config(image=photos[0])

lblWord=StringVar()
Label(window, textvariable=lblWord, font=("Consolas 24 bold")).grid(row=0, column=3, columnspan=6, padx=10)

txtWord=StringVar()
Entry(window, textvariable=txtWord, font=("Consolas 24 bold")).grid(row=1, column=6, columnspan=2, padx=10)
window.bind('<Return>', guess)


Button(window, text="New\nGame", command=lambda:play(), font=("Helvetica 10 bold")).grid(row=3, column=8, sticky="NSWE")

play()
window.mainloop()

NOTE:- you can find images used in this project from here

DEMO

2

Mini project to practice file handling and lists in python

ractice file handling and lists in python

file handling and lists in python – We’re going to create some summary data for a hardware store by reading their file of sales and creating some
departmental totals.

  1. The file name is inventory.txt. Download the file and save it in the same directory as your .py files will be.
  2. Open the file inventory.txt and look at it. You’ll see that each line has 3 pieces of information. The first
    is the department name. We only have a Lighting, a Plumbing and a Garden department at our little
    store. Be careful to not make any changes to this file. If you happen to make a change, feel free to
    download a “clean” version of the file and start over

Your job is to write a program that calculates the total sales for the hardware store as well as the total sales
for each department.(file handling and lists in python)
Your final output should look like this (with the correct numbers, though). Notice the line spacing and
formatting of the values.
Sales by Department:
Plumbing: $3568.24
Lighting: $241.34
Garden: $6423.21
Total Sales: $10232.79

Requirements:

  1. Each line in the file must be read as a string and then split into a list.
  2. Based on the department name in the line that was just read, add the value of the sales to the total
    sales for that department. Remember, we read the line as a string, converted it to a list of strings – but
    we can only add numbers. You will be ignoring the second data value in each line…..for now.
  3. At the end, print the total sales for the entire store.

Assumptions that you may make:

  1. The file exists and contains at least one line.
  2. There are no lines which have any department other than those 3 departments.
  3. All data is “valid” (i.e. the 3rd value in each line is a number, the 1st value is a valid department)

CODE

file_name = "inventory.txt" 

my_file = open(file_name,"r")

lines = my_file.readlines()

total_sales = 0.0
Plumbing = 0
Lighting = 0
Garden = 0
total = 0
for line in lines:

data = line.split(",")

department = data[0]

sales = float(data[2])

if department == "Plumbing":
Plumbing += sales

if department == "Lighting":
Lighting += sales
if department == "Garden":
Garden += sales

total += sales




print("Sales by Department:\n")

print("Plumbing: $",round(Plumbing,2))
print("Lighting: $",round(Lighting,2))
print("Garden : $",round(Garden,2))



print("\nTotal Sales: $",round(total,2))

keep visiting : shaadcoding

0

Employee Management System in C++/ CPP

Employee Management System

PROBLEM STATEMENT:

You are hired as an Application developer for a company called XYZ to facilitate the Human resource Management Department (HRM) to keep employee record. You are requested to write a program for HRM department to keep record of maximum 10 employees. Following is a menu and step by step guidance.

Menu: Welcome to Human Resource Management (HRM) Software of Company XYZ.

To do specific task please choose one of the following commands.

1. Add new employee

2. Delete employee information

3. Update employee information

4. Quit

Please enter the related number of your requested command?

Consider the following part of Person class which is containing some data members in it. Class Person should include following private fields:

• FirstName (String)

• LastName (String)

• PersonalID (Integer)

• Salary (Double)

Class Person should have public member functions for setting and getting the private fields. Member functions should have the following naming style:

• set_FieldName()

• get_FieldName() The field “PersonalID” of class Person should be unique and auto-increment with the initial value of 8248001 for the first employee. It means that user should not enter the value for “personalID”. Class HRM should include following private fields:

• Array of employees with the type Person (Private)

• The actual number of employees which is stored in Array of employees(private) Class HRM should include following public member functions:

• AddPerson()

• DeletePerson(…)

• UpdatePerson(…)

CODE:

#include<iostream>
#include<conio.h>
using namespace std;
int id=1234567,i=0;
class Person
{
	private:
		string FirstName;
		string LastName;
		int PersonalId;
		double Salary;
	public:
		void set_FirstName(string fn);
		void set_LastName(string ln);
		void set_PersonalId(int z);
		void set_Salary(double sal);
		string get_FirstName();
		string get_LastName();
		int get_PersonalId();
		double get_Salary();
		
};
class HRM
{
	private:
		Person p[15];
	public:
		void AddPerson();
		void DeletePerson();
		void UpdatePerson();	
};
	void Person::set_FirstName(string fn)
	{
		FirstName = fn;
	}
	void Person::set_LastName(string ln)
	{
		LastName = ln;
	}
	void Person::set_PersonalId(int z)
	{
		PersonalId = z;
	}
	void Person::set_Salary(double sal)
	{
		Salary = sal;
	}
	string Person::get_FirstName()
	{
		return FirstName;
	}
	string Person::get_LastName()
	{
		return LastName;
	}
	int Person::get_PersonalId()
	{
		return PersonalId;
	}
	double Person::get_Salary()
	{
		return Salary;
	}
	void HRM::AddPerson()
	{
		string fn,ln;
		double sal;
		cout<<"\n\n First Name : ";
		cin>>fn;
		p[i].set_FirstName(fn);
		cout<<" Last Name : ";
		cin>>ln;
		p[i].set_LastName(ln);
		p[i].set_PersonalId(id);
		id++;
		cout<<" How much is his/her Salary? =";
		cin>>sal;
		p[i].set_Salary(sal);
		i++;
		cout<<"\n\n New employee information added in the system";
		cout<<"\n\n First Name     Last Name     Personal ID     Salary per year (Rupees)";
		cout<<"\n -----------  ------------- ---------------    -----------------------";
		for(int a=0;a<i;a++)
		{
			cout<<"\n "<<p[a].get_FirstName()<<"          "<<p[a].get_LastName()<<"          "<<p[a].get_PersonalId()<<"               "<<p[a].get_Salary();
		}
	}
	void HRM::DeletePerson()
	{
		int t_id;
		char x;
		cout<<"\n\n ID of Employee to Remove : ";
		cin>>t_id;
		cout<<"\n Do you want to really delete employee (Y,N) : ";
		cin>>x;
		if(x == 'Y' || x == 'y')
		{
			for(int a=0;a<i;a++)
			{
				if(p[a].get_PersonalId() == t_id)
				{
					for(int k=a;k<i;k++)
					{
						p[k].set_FirstName(p[k+1].get_FirstName());
						p[k].set_LastName(p[k+1].get_LastName());
						p[k].set_PersonalId(p[k+1].get_PersonalId());
						p[k].set_Salary(p[k+1].get_Salary());
					}
					cout<<"\n\n Delete employee information from the system";
					i--;
				}
			}
		}
		cout<<"\n\n First Name     Last Name     Personal ID     Salary per year (Rupees)";
		cout<<"\n -----------  ------------- ---------------    -----------------------";
		for(int a=0;a<i;a++)
		{
			cout<<"\n "<<p[a].get_FirstName()<<"          "<<p[a].get_LastName()<<"          "<<p[a].get_PersonalId()<<"               "<<p[a].get_Salary();
		}
	}
	void HRM::UpdatePerson()
	{
		int t_id,x;
		double sal;
		char choice;
		string fn,ln;
		cout<<"\n\n Employee ID for modify information : ";
		cin>>t_id;
		do{
			cout<<"\n\n 1. First Name";
			cout<<"\n 2. Last Name";
			cout<<"\n 3. Salary";
			cout<<"\n\n Number of Field for modify : ";
			cin>>x;
			for(int a=0;a<i;a++)
			{
				if(p[a].get_PersonalId() == t_id)
				{
					if(x == 1)
					{
						cout<<"\n First Name : ";
						cin>>fn;
						p[a].set_FirstName(fn);
					}
					else if(x == 2)
					{
						cout<<"\n Last Name : ";
						cin>>ln;
						p[a].set_LastName(ln);
					}
					else if(x == 3)
					{
						cout<<"\n Salary : ";
						cin>>sal;
						p[a].set_Salary(sal);
					}
					cout<<"\n\n Modify employee information from the system";
				}
			}
			cout<<"\n\n Do you want modify another field (Y,N) : ";
			cin>>choice;
		}while(choice == 'Y' || choice == 'y');
		cout<<"\n\n First Name     Last Name     Personal ID     Salary per year (Rupees)";
		cout<<"\n -----------  ------------- ---------------    -----------------------";
		for(int a=0;a<i;a++)
		{
			cout<<"\n "<<p[a].get_FirstName()<<"          "<<p[a].get_LastName()<<"          "<<p[a].get_PersonalId()<<"               "<<p[a].get_Salary();
		}
	}
main()
{
	HRM obj;
	int choice;
	char x;
	p:
	cout<<"\n\n\t1. Add New Employee";
	cout<<"\n\t2. Delete Employee Information";
	cout<<"\n\t3. Update Employee Information";
	cout<<"\n\t4. Quit";
	cout<<"\n\n\tEnter Your Choice : ";
	cin>>choice;
	switch(choice)
	{
		case 1:
			cout<<"\n\n Enter the information of the new employee";
			do{
				obj.AddPerson();
				cout<<"\n\n Do you want to add another employee (Y,N) : ";
				cin>>x;
			}while(x == 'Y' || x == 'y');
			break;
		case 2:
			obj.DeletePerson();
			break;
		case 3:
			obj.UpdatePerson();
			break;
		case 4:
			exit(0);
		default:
			cout<<"\n\n\tInvalid Value...Please Try Again...";
	}
	goto p;
}

DEMO: