how do I write this code without the imports? I don't know what pickle is or os.path
import pickle # to save and load history (as binary objects)
import os.path #to check if file exists
# character value mapping
values = {'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1, 'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1, ' S': 1, 'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8, 'Y': 4, 'Z': 10}
# function to calculate word score
def find_word_score(x):
x = [ch.upper() for ch in x if ch in values]
score = [values[ch] for ch in x]
return sum(score)
# game variables
game_status = True #exit the game when set to False
total_score = 0
history = []
while game_status == True:
print("""Menu
1. Check the value of a scrabble word.
2. Compare the values of two words.
3. Play a word.
4. Check your current score.
5. Exit the program""")
option = int(input())
if option == 1:
word = input("Enter a word ==> ")
# create a list of valid characters in uppercase
word = [ch.upper() for ch in word if ch in values]
score = [values[ch] for ch in word]
word_score = find_word_score(word)
for i, j in zip(word, score):
print('{} -> {}'.format(i, j))
print('Word Score: {}'.format(word_score))
elif option == 2:
word1 = input("Enter word 1 ==> ")
word2 = input("Enter word 2 ==> ")
word_score1 = find_word_score(word1)
word_score2 = find_word_score(word2)
print("""Word 1 Score: {} & Word 2 Score: {}""".format(word_score1, word_score2))
if word_score1 > word_score2:
print('{} is more valuable'.format(word1))
else:
print('{} is more valuable'.format(word2))
elif option == 3:
# check if game history exists
if os.path.isfile('history.pkl') and os.path.isfile('total_score.pkl'):
history_option = int(input("Select 1 to load the previous Game, any other key to start a new Game ==> "))
# load saved game, if selected
if history_option == 1:
with open('history.pkl','rb') as f:
history = pickle.load(f)
with open('total_score.pkl','rb') as f:
total_score = pickle.load(f)
word = input("Enter a word ==> ")
word_score = find_word_score(word)
total_score += word_score
print('Word Score: {}'.format(word_score))
history.append([word, word_score])
print("Word History")
for i in history:
print ('{} : {}'.format(i[0], i[1]))
print('Total Score: {}'.format(total_score))
elif option == 4:
print('Total Score: {}'.format(total_score))
elif option == 5:
exit_option = int(input("If you would like to save the progress, press 1 else press any other key ==>"))
if exit_option == 1:
with open('history.pkl','wb') as f:
pickle.dump(history, f)
with open('total_score.pkl','wb') as f:
pickle.dump(total_score, f)
game_status = False
Please find below the updated code, code screenshots and output screenshots. Please refer to the screenshot of the code to understand the indentation of the code. Please get back to me if you need any change in code. Else please upvote.
CODE:
# character value mapping
values = {'A': 1, 'B': 3, 'C': 3, 'D': 2, 'E': 1, 'F': 4, 'G': 2, 'H': 4, 'I': 1, 'J': 8, 'K': 5, 'L': 1, 'M': 3, 'N': 1, 'O': 1, 'P': 3, 'Q': 10, 'R': 1, ' S': 1, 'T': 1, 'U': 1, 'V': 4, 'W': 4, 'X': 8, 'Y': 4, 'Z': 10}
# function to calculate word score
def find_word_score(x):
x = [ch.upper() for ch in x if ch in values]
score = [values[ch] for ch in x]
return sum(score)
# game variables
game_status = True #exit the game when set to False
total_score = 0
history = []
while game_status == True:
print("""Menu
1. Check the value of a scrabble word.
2. Compare the values of two words.
3. Play a word.
4. Check your current score.
5. Exit the program""")
option = int(input())
if option == 1:
word = input("Enter a word ==> ")
# create a list of valid characters in uppercase
word = [ch.upper() for ch in word if ch in values]
score = [values[ch] for ch in word]
word_score = find_word_score(word)
for i, j in zip(word, score):
print('{} -> {}'.format(i, j))
print('Word Score: {}'.format(word_score))
elif option == 2:
word1 = input("Enter word 1 ==> ")
word2 = input("Enter word 2 ==> ")
word_score1 = find_word_score(word1)
word_score2 = find_word_score(word2)
print("""Word 1 Score: {} & Word 2 Score: {}""".format(word_score1, word_score2))
if word_score1 > word_score2:
print('{} is more valuable'.format(word1))
else:
print('{} is more valuable'.format(word2))
elif option == 3:
# check if game history exists
try:
with open("history.txt", "r") as file:
with open('total_score.txt','r') as f:
history_option = int(input("Select 1 to load the previous Game, any other key to start a new Game ==> "))
# load saved game, if selected
if history_option == 1:
history = eval(file.readline())
total_score = eval(f.readline())
except:
history = []
total_score = 0
word = input("Enter a word ==> ")
word_score = find_word_score(word)
total_score += word_score
print('Word Score: {}'.format(word_score))
history.append([word, word_score])
print("Word History")
for i in history:
print ('{} : {}'.format(i[0], i[1]))
print('Total Score: {}'.format(total_score))
elif option == 4:
print('Total Score: {}'.format(total_score))
elif option == 5:
exit_option = int(input("If you would like to save the progress, press 1 else press any other key ==>"))
if exit_option == 1:
with open('history.txt','w') as f:
f.write(str(history))
with open('total_score.txt','w') as f:
f.write(str(total_score))
game_status = False
OUTPUT:
how do I write this code without the imports? I don't know what pickle is or...
I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...
My program crashes on the line (print('\nThe maximum value from the file is {}'.format(max(i)))) with the error message TypeError: "int" object not iterable. The purpose of this program is to create an process binary files. Can you tell me what's going wrong? Thanks! ( *'s indicate indentation) from sys import argv from pickle import dump from random import randint from pickle import load if (argv[1] == 'c'): ****output_file = open(argv[2], 'wb') ****for i in range(int(argv[3])): ********dump(randint(int(argv[4]), int(argv[5])), output_file) ****output_file.close() ****print('{}...
Python Problem Hello i am trying to finish this code it does not save guesses or count wrong guesses. When printing hman it needs to only show _ and letters together. For example if the word is amazing and guess=a it must print a_a_ _ _ _ not a_ _ _ _ and _a_ _ _ separately or with spaces. The guess has a maximum of 8 wrong guesses so for every wrong guess the game must count it if...
In python this is what I have for task 3, but I don't know how to fix it so that the computer stops picking from the pile once it reaches zero Task 3: Extend the game to have two piles of coins, allow the players to specify which pile they take the coins from, as well as how many coins they take Finish Task 3 and try three test cases import random remaining_coins1 = 22 remaining_coins2 = 22 while 1:...
For my computer class I have to create a program that deals with making and searching tweets. I am done with the program but keep getting the error below when I try the first option in the shell. Can someone please explain this error and show me how to fix it in my code below? Thanks! twitter.py - C:/Users/Owner/AppData/Local/Programs/Python/Python38/twitter.py (3.8.3) File Edit Format Run Options Window Help import pickle as pk from Tweet import Tweet import os def show menu():...
Something is preventing this python code from running properly. Can you please go through it and improve it so it can work. The specifications are below the code. Thanks list1=[] list2=[] def add_player(): d={} name=input("Enter name of the player:") d["name"]=name position=input ("Enter a position:") if position in Pos: d["position"]=position at_bats=int(input("Enter AB:")) d["at_bats"] = at_bats hits= int(input("Enter H:")) d["hits"] = hits d["AVG"]= hits/at_bats list1.append(d) def display(): if len(list1)==0: print("{:15} {:8} {:8} {:8} {:8}".format("Player", "Pos", "AB", "H", "AVG")) print("ORIGINAL TEAM") for x...
this code is not working for me.. if enter 100 it is not showing the grades insted asking for score again.. #Python program that prompts user to enter the valuesof grddes . Then calculate the total scores , #then find average of total score. Then find the letter grade of the average score. Display the #results on python console. #grades.py def main(): #declare a list to store grade values grades=[] repeat=True #Set variables to zero total=0 counter=0 average=0 gradeLetter='' #Repeat...
Need help writing this code in python. This what I have so far. def display_menu(): print("======================================================================") print(" Baseball Team Manager") print("MENU OPTIONS") print("1 - Calculate batting average") print("2 - Exit program") print("=====================================================================") def convert_bat(): option = int(input("Menu option: ")) while option!=2: if option ==1: print("Calculate batting average...") num_at_bats = int(input("Enter official number of at bats: ")) num_hits = int(input("Enter number of hits: ")) average = num_hits/num_at_bats print("batting average: ", average) elif option !=1 and option !=2: print("Not a valid...
ITEMS SUMMARY 16, < Previous Nex The following program obtains three integers, x, y, and z, as input form the user. Complete the program so that it determines whether there is a subset of two or three of these numbers that sum to zero. If so, the program should print zero sum found. Otherwise, it should print no zero sum found. Check syntax X = int(input) 2 y int(input) int(input) In the word game Boggle, a word is scored according...
how to make my code of python work probely my q is how to write a code to find the average actual water level, average error by using python and my program should be flexible where user can select the column no. If you can see in the main program, it asked which column to know the maximum or average, the column number is passed to the function. The function should look which column to do. #THIS PROGRAMMING IS ABLE...