Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm making a hangman game and testing how different letter picking algorithms fare, but to do this, the guessing algorithm function has to feed a letter into the hangman function's input('Select a letter').
How do you make it so that a function detects when another function is waiting for an input ?
Assuming you are doing input() in a loop inside your hangman function, you could switch that to a yield and let an external function drive input as needed. In this example I have a hangman function that uses yield to get data. Now its a generator and driving function can use next and the generator's .send method to pump data into it.
def hangman(chances=5):
for i in range(chances):
letter = yield "prompt"
if letter == "quit":
yield "quit"
return
print("letter", letter)
# do all the things
solved = False
if solved:
yield "solved"
yield "failed"
def command_line_prompt_hangman():
feeder = hangman()
state = next(feeder)
while state == "prompt":
state = feeder.send(input("Next letter: "))
def test():
# after years of testing the best algorithm is
test = ['a', 'b', 'c', 'd', 'e', 'f']
feeder = hangman()
assert next(feeder) == "prompt"
for count, letter in enumerate(test, 1):
state = feeder.send(letter)
if state == "solved":
print("did it in ", count, "tries")
break
if state == "failed":
print("exceeded count")
break
command_line_prompt_hangman()
test()
Instead of using the input function, write a custom function to pull an output from whatever algorithm you are using. That would look something like this:
user_input = algo_obj.get_input(game_state)
In this case, algo_obj would be an object storing the current state of the algorithm/generator (if such a state exists, otherwise you can just call the function normally). game_state would be some representation of the game's current state (available letters, the word-form -- ie. blanks & letters).
You can then feed user_input to your Hangman function.
This should be as simple as:
Define both functions.
Pass one function return value to the other one as argument.
This can be done by using input() as according to this
e.g. Define the functions
def first_function():
input_variable = input("Please enter some data")
return input_variable
def second_function(a):
print(a) # Do some calculations here
And use them:
second_function(first_function())
I wouldn't say that this is necessarily the best way to go about but it solves Your problem. If You would like to receive a more detailed answer please provide code samples.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The program runs and the function works but I am not able to see my docCountryList in the output. Can someone tell me why?
I have this code
def ViewByCountry(docID,user_selection):
docCountryList=[]
for x in jfile:
if x.get('subject_doc_id') == docID:
docCountryList.append(x['visitor_country'])
if user_selection == '2a':
x = []
y = []
#Insert countries and number of occurences in two seperate lists
for k,v in Counter(docCountryList).items():
x.append(k)
y.append(v)
plt.title('Countries of Viewers')
plt.bar(range(len(y)), y, align='center')
plt.xticks(range(len(y)), x, size='small')
plt.show()
return docCountryList
and in my main
from program import ViewByCountry
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
docID = input("Enter required document ID: ")
user_selection = input("Enter selection")
ViewByCountry(docID,user_selection)
You never print out the value of docCountryList, so try this:
print(ViewByCountry(docID,user_selection))
This will print out the value.
You can do this as well:
lst = ViewByCountry(docID,user_selection)
print(lst)
In your main you can change to myView = ViewByCountry(docID,user_selection) and then add print(myView). This saves the list created by your function to a variable to be printed or used later.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am new to OOP side of python and I am wondering if it is worth to refactor my non-OOP programming code to an OOP code. my code is as follows:
import time
import numpy as np
import pandas as pd
def choices_chooser(possibilities):
final_choice = None
while final_choice is None:
temp_input = input(f'please enter one of the following: {possibilities}\n')
if temp_input == 'True': temp_input = True
elif temp_input == 'False':temp_input = False
if temp_input in possibilities:
final_choice= temp_input
else:
print('typo! plz enter again')
return final_choice
def status_updater(dic, key, possibilities):
if key in dic and type(possibilities) in {list,tuple}:
print(f"the status of {key} before modification: {dic[key]}")
print('now we are changing it')
dic[key]= choices_chooser(possibilities)
print(f"the status of {key} after modification: {dic[key]}")
def funcA(df):df['Be'] *= -1.5
def funcB(df):df['Ch'] *= -2
def funcC(df):df['De'] *= -3
def funcD(df):df['Ep'] *= -4
def funcE(df):df['Fi'] *= -5
def funcF(df):df['Al'] *= -6
func_dict = {'Al': funcA,
'Be': funcB,
'Ch': funcC,
'De': funcD,
'Ep': funcE,
'Fi': funcF}
options_lst = [True, False]
status = ['Null']+['Al','Be','Ch','De','Ep','Fi']
status_dict = dict.fromkeys(status, False)
status_count = dict.fromkeys(status, 0)
status_index = 0
next_status_index = 1
previous_status_index = None
num_of_iteration = 0
num_of_complete_run = 0
df = pd.DataFrame(np.ones((4, len(status))), columns = status)
while num_of_complete_run < 1:
time.sleep(0.2)
num_of_iteration += 1
current_state = status[status_index]
next_state = status[next_status_index]
if previous_status_index is None:
print(f'current state: {current_state};next_state: {next_state}; iteration: {num_of_iteration}')
else:
previous_state = status[previous_status_index]
print(f'previous state: {previous_state}; current state: {current_state}; next state: {next_state}; iteration: {num_of_iteration}')
status_updater(status_dict,
next_state,
options_lst)
if status_dict[next_state]:
previous_status_index = status_index
status_index = next_status_index
previous_state = status[previous_status_index]
current_state = status[status_index]
print(f'we have attained a new state\n' + '-----'*10)
if current_state == 'Be':
print('after state Beta we may directly skip to De, depending on RNG')
next_state = choices_chooser(['Ch','De'])
next_status_index = status.index(next_state)
elif current_state == 'De':
print('after state Delta we may directly skip to Fi, depending on RNG')
next_state = choices_chooser(['Ep','Fi'])
next_status_index = status.index(next_state)
elif current_state == 'Fi':
print('we are at state Fi, which means a full run has been completed')
num_of_complete_run += 1
next_status_index = 1
next_state = status[next_status_index]
else:
next_status_index += 1
next_state = status[next_status_index]
print(f'previous state: {previous_state}; current state: {current_state}; next state: {next_state}')
#'do something unique at state {current_state}
func_dict[current_state](df)
status_count[current_state] += 1
This is my attempt to create a real-time-ish application. It has status variables. Different functions are run at different states. Whether certain states will be visited next depends on the user's input. The code terminates when the status 'Fi' has been reached once.
I am asking for help here because I have almost 0 knowledge when it comes to good program designs, technical debts, or basically any in-depth knowledge about what/when to do OOP and how to do it correctly.
My questions are the following:
1) Is it worth to refactor my non-OOP programming code to an OOP code?
2) If so, what should I pay extra care and attention to in the process? if not, what can I do to improve the existing code?
3) When should we convert a non-OOP code to OOP code and when shouldn't
4) Do you mind posting an example of what a good OOP version of this code is like in the answer?(I mean if one had to learn how to OOP, might as well learn from a great example)
Thank you guys in advance.
——
EDIT1:
changed “functional peogramming” to non-OOP to better reflect the situation
If you need your program to do only one thing and do it well, just use functional programming. If your program need to do more than one set of different things to do, use OOP. For example, if you build an app to calculate some scientific things (for example, velocity, gravity, etc.) you make it as OOP, 1 object only for GUI, 1 object to set things up and call calculation object, and other to perform calculation.
Other example if you build a web app, use one object to send view to user, 1/more object to set things up and calling the object to take things from database (with different usage for each object, i.e. one for home, one for user control, one for calculating item etc.), and last one/more object to operate the database (CRUD), it could be different object accessing different databases.(this one is called MVC model).
If your code slowly becoming spaghetti code and isn't readable, consider using OOP.
I'm not really an expert but that's how I do things for 4 years now.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I would like to know how I could allow my code to let the user restart the quiz at any time throughout the program however, I have no idea how to do this from scratch. It preferably needs to be fairly simple. Would it be easiest doing it as an if statement and if so what would I put in it? I tried this:
while True:
# main program
while True:
answer = raw_input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print 'Invalid input.'
if answer == 'y':
continue
else:
print 'Goodbye'
break
breaking your problem down into parts is the first step
# 1. ask a question and validate the response
def ask_question(prompt,possible_choices):
while True:
result = raw_input(prompt)
if result in possible_choices:
return result
print "Invalid Response Please Enter One Of:",possible_choices
# 2. run a whole quiz (ask all our questions)
def do_quiz():
answers = []
for question_text in questions_list:
answer = ask_question(question_text,['a','b','c','d','quit','restart')
if answer == "restart":
return False
# instead of returning false we could also simply call recursively
# return do_quiz()
elif answer == "quit":
print "Adios muchacho"
sys.exit(0)
else:
answers.append(answer)
return answers
# 3. play forever (or atleast until the user wants to quit...)
while True:
results = do_quiz()
if not results:
print "Lets Start Over!!"
continue
else:
check_answers(results)
if raw_input("Play again?")[0].lower() == "n":
print "Goodbye!"
sys.exit(1)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
RANDOM_COR=random.randrange(5,6)
def check_xy_data():
global COUNT
COUNT=0
input_xy=input("input(x,y) : ")
think_xy=list(map(int,input_xy.split(",")))
if(random_array[think_xy[0]][think_xy[1]] == "C"):
screen_array[think_xy[0]][think_xy[1]] = "O"
COUNT=COUNT+1
else:
screen_array[think_xy[0]][think_xy[1]] = "X"
def main():
make_intro()
init_screen_array ()
init_random_array ()
make_random_num(RANDOM_COR)
while(True):
check_xy_data()
draw_outline_start(TOTAL_COL_NUM//2)
draw_out_rowline(TOTAL_COL_NUM//2, "Input : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Correct : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Error : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Total : ")
draw_outline_mid(TOTAL_COL_NUM//2)
if(COUNT==RANDOM_COR-1):
break
The if at the bottom of my code is supposed to get me out of the while loop, but I'm stuck in an infinite loop. Help?
(assignment, 2016) 예고편 The Assignment | 어싸인먼트 감독: 월터 힐 각본: 월터 힐, 데니스 해밀 출연: 김성훈 출연 현빈, 유해진, 김주혁 개봉 2016 한국 상세보기 그간...
Try this change:
RANDOM_COR=random.randrange(5,6)
COUNT = 0
def check_xy_data():
global COUNT
With COUNT inside check_xy_data, you set it back to 0 on every call. It can never reach more than 1. Your check is whether it's in the range 5-6. This is never true, so you can never leave the loop.
Note that trivial debugging skills would have found this: just stick a print statement before you test your loop condition, to see what the values are. Use that next time ... :-)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have looked all over Stackoverflow and I can't find an answer, and all the web tutorials just go right over my head. I have a functioning code that I don't understand
import random
import time
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy nd hungry, and will eat you on sight.')
print()
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
print('Gives you his treasure')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('do you want to play again? (yes or no)')
playAgain = input()
I don't understand the def checkCave(chosenCave): parts, why does the argument say chosenCave?
Can someone explain please?
In the function
def checkCave(chosenCave):
...
chosenCave becomes a local variable that you passed to the function. You can then access the value inside that function to process it, provide whatever side-effects you're looking to provide (like printing to the screen, as you're doing), and then return a value, (which if you don't do explicitly, Python returns None, its null value, by default.)
Algebraic Analogy
In algebra we define functions like this:
f(x) = ...
for example:
f(x) = x*x
In Python we define functions like this:
def f(x):
...
and in keeping with the above simple example:
def f(x):
return x*x
When we want the results of that function applied to a particular x, (e.g., 1), we call it, and it returns the result after processing that particular x.:
particular_x = 1
f(particular_x)
And if it returns a result we want for later usage, we can assign the results of calling that function to a variable:
y = f(particular_x)
The name chosenCave appears to have been chosen to describe what it represents, namely, the cave the player chose. Were you expecting it to be named something else? The name isn't required to match or not match any names located elsewhere in the program.