Part 2 Specific Word Count:
Hi, I have 3 parts that I am doing to this program and so far I have the first one which is wordcount. Part 2 is the specific word count and while I am able to put it in one of the elif statements, the requirement is to define it. I want to know how to define a specific input such as "ship" from a text file into my "Specific Word Count" where it says "print(2)"
Part 3 Find the Message:
If you can also help with this part this would be nice too. I'm looking for a secret message in the text file that is between 2 # symbols and I want to print what is between those 2 # symbols. The condition is also having to define it. I have tried a few things but so far no luck as well. This is what I have so far that has a word and I have tested all the if, elif, and else statements.
#################################################
from http.client import LineTooLong
import string
def display_menu():
print( "############################" )
print( "# 1 Total Word Count #" )
print( "# 2 Specific Word Count #" )
print( "# 3 Find The Message #" )
print( "# 4 Exit #" )
print( "############################" )
option = input('Enter your selection > ')
return option
##################################################
x = display_menu()
count = 0
def get_word_count( handle_input ):
handle_input.seek(0)
lines = 0
count = 0
for line in handle_input:
words = len(line.split())
count= count + words
return(count)
def get_specific_count( handle_input):
handle_input.seek(0)
def find_message( handle_input ):
handle_input.seek(0)
return(0)
while x != '4':
if x == '1':
fhand = open('Moby Dick.txt')
y = get_word_count(fhand)
print("Total:"+ str(y))
elif x == '2':
print(2)
elif x == '3':
print(3)
else:
print('Error try again!')
x = display_menu()
This is a Sample of what the Text file looks like since I cant attach a file
CHAPTER 1
Loomings.
Call me Ishmael. Some years ago--never mind how long
precisely--having little or no money in my purse, and nothing
particular to interest me on shore, I thought I would sail about a
little and see the watery part of the world. It is a way I have of
driving off the spleen and regulating the circulation. Whenever I
find myself growing grim about the mouth; whenever it is a damp,
drizzly November in my soul; whenever I find myself involuntarily
pausing before coffin warehouses, and bringing up the rear of every
funeral I meet; and especially whenever my hypos get such an upper
hand of me, that it requires a strong moral principle to prevent me
from deliberately stepping into the street, and methodically knocking
people's hats off--then, I account it high time to get to sea as soon
as I can. This is my substitute for pistol and ball. With a
philosophical flourish Cato throws himself upon his sword; I quietly
take to the ship. There is nothing surprising in this. If they but
knew it, almost all men in their degree, some time or other, cherish
very nearly the same feelings towards the ocean with me.
Related
I have a problem regarding a competition question I'm attempting to do. Here is the question (its a bit long)
""""
Welcome aboard, Captain! Today you are in charge of the first ever doughnut-shaped spaceship, The
Circular. There are N cabins arranged in a circle on the spaceship. They are numbered from 1 to N in
a clockwise direction around the ship. The ith and the (i + 1)th cabins are connected. So too are cabin
1 and cabin N.
Currently the ith cabin has Ai crewmates, however the spaceship cannot depart unless there are exactly
Bi crewmates in this cabin.
To achieve this, you have the power to pay crewmates to change cabins. You can pay a crewmate $1 to
move to an adjacent cabin. A crewmate can be asked to move multiple times, provided that you pay
them $1 each time.
What is the fewest dollars you must pay before you can depart? It is always be possible to depart.
""""
https://orac2.info/problem/aio22spaceship/ (the link to the intereactive Qs)
I searched the web and i found no solutions to the Q. My code seems to be infinite looping i guess but im not sure as i cant see what cases the sit uses to determine if my code is right.
Heres my code
#!/usr/bin/env python
import sys
sys.setrecursionlimit(1000000000)
#
# Solution Template for Spaceship Shuffle
#
# Australian Informatics Olympiad 2022
#
# This file is provided to assist with reading and writing of the input
# files for the problem. You may modify this file however you wish, or
# you may choose not to use this file at all.
#
# N is the number of cabins.
N = None
# A contains the initial number of crewmates in each cabin. Note that here the
# cabins are numbered starting from 0.
A = []
# B contains the desired number of crewmates in each cabin. Note that here the
# cabins are numbered starting from 0.
B = []
answer = 0
# Open the input and output files.
input_file = open("spacein.txt", "r")
output_file = open("spaceout.txt", "w")
# Read the value of N.
N = int(input_file.readline().strip())
# Read the values of A and B.
input_line = input_file.readline().strip()
A = list(map(int, input_line.split()))
input_line = input_file.readline().strip()
B = list(map(int, input_line.split()))
AM = A
#AM is my modifying set
# TODO: This is where you should compute your solution. Store the fewest
# dollars you must pay before you can depart into the variable
while AM != B:
#Check if the set is correct
#notfound is a testing variable to see if my code was looping due to input error
notfound = True
for i in range(N):
#Check which places needs people to be moved
while AM[i]>B[i]:
notfound = False
#RV and LV check the "neediness" for each half's people requirements. I check how many people
#are needed on one side compared to the other and subtract the "overflow of people"
RV = 0
LV = 0
for j in range(int(N/2-0.5)):
#The range thing makes sure that if N is odd, im splitting the middle but if N is even, i leave out the end pod
RV += B[(i+j+1)%N]-AM[(i+j+1)%N]
LV += B[(i-j-1)%N]-AM[(i-j-1)%N]
answer +=1
if RV>LV:
AM[i]+=-1
AM[(i+1)%N]+=1
else:
AM[i]+=-1
AM[(i-1)%N]+=1
print(AM,B)
if notfound:
break
print(answer)
# Write the answer to the output file.
output_file.write("%d\n" % (answer))
# Finally, close the input/output files.
input_file.close()
output_file.close()
please help i really neeed to know the answer, driving me mad ngl
Welp, there aren't any resources online and I've tried everything. I think the problem might be that because of my solving method, passengers may be flicked between two pods indefinitely. Not sure since i could make a case that demoed this.
also my post probably is messy since this is my first time posting
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm new to programming and trying to create a branching story program in python. as far as I can tell everything should be working, but for some reason it doesn't register the input response, just repeats the original. (it doesn't rewrite the variable 'listo' like it should). Instead of moving on to the next line in the story(=rewriting 'listo' to the appropriate list and operating on it), it goes back to the first line of the story with it's 3 options. here's the relevant code:
#different story lines with their respective options
s1= 'You awaken from a sudden noise in your tent. An axe is coming straight towards your head.'
s2= 'You be dead.'
s3= 'The creature wielding the axe is thrown off balance by the momentum of his swing'
s4='You manage to parry the weapon away from you, where it sinks through your bed. The creature wielding it falls on top of you, carried by it’s momentum. You grapple with it on the ground trying to gain an advantage.'
s5='You run out of your tent. The entire camp is in a state of chaos. People and more of the creatures are skirmishing all around and a large amount of the camp is on fire. All of the pack animals are running around like headless chickens.'
s6='You take advantage of the creature’s misstep, lift up your small desk and bring it down hard on the creature’s head. It crumples and drops to the ground.'
s7='As you try to gain purchase on it’s throat the creature grabs your hand in its mouth and bites down hard. You feel white hot pain in your arm and black out.'
s8='You push the creature off of you and roll away.'
s9='You grapple in the dirt for something useful and manage to grab a hard oblong object. You stab it into the creature’s face and hear it squeal in agony as you push it off of you and get up. '
s10 = 'goodbye'
#different choices
o1='Roll out of the way'
o2='Try to block it'
o3='Stare at it and hope it goes away.'
o4='Exit program'
o5='Restart story'
o6='Run away'
o7='attack'
o8='Try to strangle it'
o9='Try to get it off of you'
o10='Try to find a weapon'
oo=''
#setting defaults so it wont give me issues:
a2 = []
a3 = []
a4 = []
a5 = []
a6 = []
a00 =[]
#the master lists. [story line, choices[references]]
a1 = [s1,o1,o2,o3,a2,a3,a4]
a2.append([s3,o6,o7,oo,a5,a6])
a3.append([s4,o8,o9,o10,a00,a00,a00])
a4.append([s2,o4,o5,oo,a00,a1,a00])
a5.append([s5,o4,o5,oo,a00,a1,a00])
a6.append([s6,o4,o5,oo,a00,a1,a00])
a00.append([s10,oo,oo,oo,a00,a00,a00])
correct_answers = ['a','b','c']
l = 0
#the program:
listo = a1
print(listo[4])
while True:
l +=1
print('\nloop '+ str(l)+ '\n')
x = input('\n'+str(listo[0])+'\nwhat do you do?: \na.'+str(listo[1])+'\nb.'+str(listo[2])+'\nc.'+str(listo[3])+'\n\nyour choice:')
print(type(x))
if x not in correct_answers:
print('Wrong answer wiseguy, type a lowercase a,b or c.')
print(x)
exit()
if x == 'a':
print('\ngot this far yall')
listo = listo[4]
print('\nreassigned value')
print(listo)
elif x == 'b':
listo = listo[5]
elif x == 'c':
listo = listo[6]
any help would be much appreciated, thanks!
Edit: post has been altered, see comments.
You are facing this error because the input() function always returns a string value. However, you are checking x against integers. Try using this instead:
x = int(input(...))
Here, you convert the input given by the user into an integer.
You can also change your code to be shorter like so:
x = int(input(...))
listo = listo[4][x - 1]
I am doing a project in school which is asking me to make a music quiz in python that reads a file, displays the first letters of each word of the song and the artist (e.g Dave F F). In my file I have a list of 10 song names where python fetches a random line and does the displaying. It must be from a file (mine is notepad) The user must have 2 chances to guess the name of the song, and if they don't then the game ends. The problem that I have is I cannot get my code to ask another question, and store the last one asked so that it doesn't ask it again (e.g if the first question is Dave and F F, I want it to not come again). I would also appreciate it if I was shown how to get python to display a leaderboard. Could answers please be the full code with improvements as i'm not good with indents and putting code In the right place.
I have already gave the user 2 chances to get the song right, and If they dont then the program ends, but doesn't loop to the start.
import random
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
random_song, random_artist = random.choice(songs_and_artists)
songs_intials = "".join(item[0].upper() for item in random_song.split())
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
nb_tries_left = 3
guess = input("Guess the name of the song! ")
nb_tries_left -= 1
finished = False
while not finished:
answer_found = (guess == random_song)
if not answer_found:
guess = input("Nope! Try again! ")
nb_tries_left -= 1
elif answer_found:
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
finished = (answer_found or nb_tries_left <= 0)
if answer_found:
The songs' initials are LT and the name of the artist is Fredo
Guess the name of the song! Like That
The songs' initials are LT and the name of the artist is Fredo
Well done!
Python then doesn't ask another question, and I don't know If it will be that one again.
getting it wrong on purpose outputs this:
The songs' initials are CS and the name of the artist is 50 Cent
Guess the name of the song! candysong
Nope! Try again! carpetshop
Nope! Try again! coolsong
Sorry, you've had two chances. Come back soon!
>>>
First You want to get 2 unique songs. To do that you could use random.sample. For your use case, It is
indexes = random.sample(range(len(songs_and_artists)), 2) # 2 random songs (sampling without replacement)
# song 1
random_song, random_artist = songs_and_artists[indexes[0]]
# song 2
random_song, random_artist = songs_and_artists[indexes[1]]
Additionally, I recommend you to put your code to the function and use it with each selected song.
In order to ask more than one question every game you have to do something like this:
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
def getSongAndArtist():
randomIndex = random.randrange(0, len(songs_and_artists))
return songs_and_artists.pop(randomIndex)
while(len(songs_and_artists) > 0):
random_song, random_artist = getSongAndArtist()
#play game with the song
You save the list of songs in a python list and pop a random one out each round as long as you have more songs to play with.
For the leaderboard you have to ask for a user name before you start the game and save a list of usernames and their score and then pick the top ones. you should also figure out how to score the users
So I am a total beginner yet this is 100% my code and I am proud of it. Now mind you I need a little cleaning up, however it does what I want it too. My issue is this: In order to turn this in for credit, one of the things is that procedures(functions) should not contain more than 18 lines. My function gameCont() has many more. Would anyone have suggestions on how I could shorten it up? Additionally I am obviously challenged when it comes to function parameters so any help is appreciated. Please be gentle as I am BRAND NEW! :)
game1 = "When dealing with SCUBA diving there are many dangers to consider. The very first one is _1_. \
I mean if you take water into your lungs, you are NOT SCUBA diving. Another is rising to the surface too quickly which could \
result in the _2_. Now this is a funny name, as I am sure when it happens, you dont feel 'bendy'. Let's also consider Nitrogen Narcosis.\
If you dont know what that is, well when you are very deep and your body is absorbing more nitrogen than it is used to, you can get \
feeling kinda _3_ feeling as though you just drank not one, but _4_ martinis"
game1_answers = ["drowning", "bends", "drunk", "2"]
game2 = "When you first learn to dive you are taught to do dives within a no DECOmpression limit(NDL). \n This means you do not want to \
stay that deep too long or you will rack up _1_. \n If you DO stay longer than what the NDL allows, you will have an obligation to \
take your time getting to the surface allowing that _2_ gas to leave your body. If you were taking IN gas you may call it \
in-gassing, but when you are decompressing, it may be called _3_-gassing. You are taught also, how to read _4_"
game2_answers = ["deco", "nitrogen", "off", "tables"]
game3 = "Equipment used by cold water divers such as myself are as such. On my head I would wear a _1_. To help regulate the breathing\
pressure from my SCUBA tank I would use a _2_. To help me propel through the water I would place_3_ on my feet. Considering \
we cannot see underwater I need to be wearing a _4_ on my face. Diving in the tropic, many people would use wetsuits, however it's\
very cold where I dive so we wear _5_ suits."
game3_answers = ["hood", "regulator", "fins", "mask", "dry"]
def howManyTries():
gameTries = raw_input("Thanks for giving my quiz a try, how many attempts do you want? ")
return int(gameTries)
def game_choice(): #this function is used to determin which difficulty the user wants and returns the proper game and answer list
user_input = raw_input("Greetings. This is my Udacity project for fill in the blanks. Which one of my options would you like?\
easy, hard, or hardest? Please take note of capitalization ")# this will define the user_input variable to raw input placed in by user
print ("\n" * 20)# just something to clean up the screen
print "Decided to choose " + user_input + '?' " Well " + user_input + " it is"# this confirms to the user which difficulty they chose.
print ""
print ""
if user_input == "easy": #easy returns game1 and game1 answers
return game1, game1_answers
elif user_input == "hard": # hard returns game2 and game2 answers
return game2, game2_answers
elif user_input == "hardest": #hardest returns game3 and game 3 answers
return game3, game3_answers
else:
print "It seems that " + user_input + " is not a valid response" #in case the user doesnt choose or spell choice correctly
def gameCont():
blanks = 1 #this assings blank to 1 which will tell the user which blank they are guessing in below prompt
attempts = howManyTries() #this calls the howManyTries function for a user choice integer
quiz, answers = game_choice() #this returns 2 values (game# and game# answers)
while attempts > 0: #while attempts (called from function) is greater than 0 we will loop this
print quiz #prints the chosen quiz for user updated each time the loop runs with correct answer
print("\n" * 10) #clears some more screen to loook better for the user
guess = raw_input("Reading the above paragraph, What would your guess be for _" + str(blanks) + "_") #asks for guess for current blank which always starts at 1
print("\n" * 10) #clears some more screen to loook better for the user
if guess == answers[blanks - 1]: #because indexing count starts at zero, and blanks start at 1 this will check if answer is equal to blanks - 1
print "As you can see your correct choice has replaced the variable, great job!!"#this will print if the guess is correct
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz
break
elif guess != answers[blanks -1]: #if the answer does not match the list index
attempts = attempts - 1 #then we will subtract 1 from the attempts
print ("\n" * 10)
print "Oops that is not correct, there should be hints in the paragraph" # lets user know they were wrong
print "You have " + str(attempts) + " attempts left." # lets the user know how many attempts they have left
print ""
if attempts < 1:
print "Well it looks like you are out of choices, Try again?"
break
print "Thanks for playing"
gameCont()
All of the printing that you're doing could be done in a separate function
def game_print(newlines_before, text, newlines_after)
print ("\n" * newlines_before + text + "\n" * newlines_after)
Two suggestions:
Delegate tasks that are accomplished by your function to smaller functions. So, for example, if you had a function that needed perform task A and performing that task could be divided into tasks B, C, and D, then create helper functions and call them inside of the function that does task A.
You have long strings, maybe store them somewhere else? Create a class just for constant strings of related functions and access that when you need a particular string. It'll make it less likely that you'll make a mistake when you need to use that string in multiple locations.
class Constants:
str1 = "..."
str2 = "..."
print(Constants.str1)
you can call a function from inside another function. inside an if statement you could call a small new function that just prints some stuff. this should make it easy to get the function size down.
something like this should work:
def correct(quiz, blanks):
print "As you can see your correct choice has replaced the variable, great job!!"
quiz = quiz.replace("_" + str(blanks) +"_", answers[blanks - 1]) # here is the line of code that replaces the blank with the correct guess
blanks += 1 # this adds 1 to the blank which will prompt the user to move to the NEXT blank when loop begins again
if blanks > len(answers):
print ("\n" * 10)
print "YOU DID IT!! Here is the final paragraph with all the correct answers"
print ("\n" * 2)
print quiz`
remember that you still want to break after calling that function in order to exit your loop.
I'm writing a program that is basically a study guide/ practice test for the current section of my A&P class (it keeps me more engaged than just rereading notes over and over). The test works without any problems, but I have an issue where some of my questions use an "enterbox" input, I can have the question loop if the answer is incorrect, but I can't get it to break without a correct answer.
I figured out a way to make it work by putting the entire function back into the initial "else" tree, so that right or wrong you advance to the next question but it looks incredibly ugly and I can't believe there isn't a better way.
So my "solution" looks like such:
def question82():
x = "which type of metabolism provides the maximum amount of ATP needed for contraction?"
ques82 = enterbox(msg = x, title = version)
#version is a variable defined earlier
if ques82.lower() in ["aerobic"]:
add() #a function that is explained in the example further below
question83()
else:
loss() #again its a housecleaning function shown below
ques82b = enterbox(msg = x, title = version)
if ques82b.lower() in ["aerobic"]:
add()
question83()
else:
loss()
question83()
Okay so it worked, but using a nested if tree for each "enterbox" question looks kinda sloppy. I'm self taught so it may be the only solution but if there is something better I would love to learn about it.
So here is a complete section from my program:
from easygui import *
import sys
version = 'A&P EXAM 3 REVIEW'
points = 0
def add():
global points
msgbox("Correct", title = version)
points = points + 1
def loss():
global points
msgbox("Try Again", title = version)
points = points - 1
def question81():
x = "What chemical is stored by muscle as a source of readily available energy for muscle contractions"
ques81 = enterbox(msg = x, title = version)
if ques81.lower() in ["creatine"]:
add()
question82()
else:
loss()
question81()
It works as is so any errors from what's provided are probably my fault from copy and pasting.
Also I'm running it in python 2.7rc1 if that helps.
Thanks for any help in advance.
I don't know if there is a way to combine "enterbox" that has a button for "skip" as that would also be a solution.
Consider the following approach:
We define a list of question and answer pairs. We do this in one place so it's easy to maintain and we don't have to search all over the file to make changes or re-use this code for a different questionset.
We create an ask_question function that we can call for all of our questions. This way, if we want to make a change about how we implement our question logic, we only have to make it in one spot (and not in each of the questionXX functions).
We compare user input to our answer using == and not in (in will do something else, not what you expect).
We create an object to keep track of our answer results. Here, it's an instance of ResultsStore, but it can be anything really, let's just try to get away from global variables.
Use a loop when prompting for answers. The loop will repeat if the answer given was incorrect (and if retry_on_fail is False).
Allow for the user to enter some "skip" keyword to skip the question.
Display the results once the "test" is complete. Here, we do that by defining and calling the store.display_results() method.
So, what about:
from easygui import enterbox
question_answer_pairs = [
("1 + 1 = ?", "2"),
("2 * 3 = ?", "6"),
("which type of metabolism provides the maximum amount of ATP needed for contraction?", "aerobic")
]
VERSION = 'A&P EXAM 3 REVIEW'
class ResultStore:
def __init__(self):
self.num_correct = 0
self.num_skipped = 0
self.num_wrong = 0
def show_results(self):
print("Results:")
print(" Correct:", self.num_correct)
print(" Skipped:", self.num_skipped)
print(" Wrong: ", self.num_wrong)
def ask_question(q, a, rs, retry_on_fail=True):
while True:
resp = enterbox(msg=q, title=VERSION)
# Force resp to be a string if nothing is entered (so .lower() doesn't throw)
if resp is None: resp = ''
if resp.lower() == a.lower():
rs.num_correct += 1
return True
if resp.lower() == "skip":
rs.num_skipped += 1
return None
# If we get here, we haven't returned (so the answer was neither correct nor
# "skip"). Increment num_wrong and check whether we should repeat.
rs.num_wrong += 1
if retry_on_fail is False:
return False
# Create a ResultsStore object to keep track of how we did
store = ResultStore()
# Ask questions
for (q,a) in question_answer_pairs:
ask_question(q, a, store)
# Display results (calling the .show_results() method on the ResultsStore object)
store.show_results()
Now, the return value currently doesn't do anything, but it could!
RES_MAP = {
True: "Correct!",
None: "(skipped)",
False: "Incorrect" # Will only be shown if retry_on_fail is False
}
for (q,a) in question_answer_pairs:
res = ask_question(q, a, store)
print(RES_MAP[res])
Quick and dirty solution could be using the default value "skip" for the answer:
def question81():
x = "What chemical is stored by muscle as a source of readily available energy for muscle contractions"
ques81 = enterbox(msg = x, title = version, default = "skip")
if ques81.lower() == 'creatine':
add()
question82()
elif ques81 == 'skip':
# Do something
else:
loss()
question81()
But you should really study the answer given by jedwards. There's a lot to learn about
program design. He's not giving you the fish, he's teaching you to fish.