How to restart this program - for-loop

So this is my code that works fine alone.....
def program():
for x in y:
for g in t:
if x == g:
return True
return False
print ("Welcome")
y = input(" enter...").lower().split()
with open("pro.txt", "r")as file:
lines = file.readlines()
o = False
for line in lines:
item = line.split("-")
t = item[0].split()
a = item[1]
if program():
print (a)
o = True
if o == False:
print ("sorry")
I did ask this question before, but I didn't explain well enough. so the problem I have here is that I do not know how to restart this program one of my attempts was this.....
def restart():
answer = ''
while answer not in ('y','n'):
answer = input('Run again? (y/n): ')
if answer == 'y':
return program()
if answer == 'n':
return False
else:
return None
while restart() == True:
program()
This code is at the bottom
however this didn't seem to work as I answer the question with 'y' or 'n' didn't seem to work as when I answer the program ends. so my question is why doesn't it work and how will you make it work. Thanks.

Related

User input manipulation

Please I'm in need of a lift right now. I want the user to be able to have the option of re-entering his numerical input if perhaps, he/she entered an alphabet by mistake.
Right now it just loops infinitely on the "Please select a valid option" and "Try again" outputs.
print("\n-----Factorial Calculator------\n")
def option():
opt = (input('Try again? y/n: '))
if option == 'y':
facto(num)
elif option == 'n':
exit()
else:
print("Please select a valid option")
option()
def facto(factorial):
fact = 1
for nums in range(1, num+1):
fact = fact * nums
return fact
try:
num = int(input("Number(Just input the number): "))
except ValueError:
print("Invalid input")
option()
print(f" {num}! = {facto(num)}")
First, rather than calling option recursively, simply put a loop inside it.
Second, when the user enters y into the "Try again?" input, it should not calculate the factorial there, but return the user back to the original input, by breaking out of the loop within the option call.
Putting these two together will fix option:
def option():
while True:
retry = input('Try again? y/n: ')
if retry == 'y':
break
elif retry == 'n':
exit()
else:
print("Please select a valid option")
Third, you need some kind of loop around your initial input, otherwise how will they enter the number again after indicating they want to try again?
Fix this by sticking the initial num assignment and option call in a while loop, with the same try; except statement you had before:
while True:
try:
num = int(input("Number(Just input the number): "))
break
except ValueError:
print("Invalid input")
option()
continue
I see someone else got an answer in ahead of me which identified the bug in option() and the bug which prevents user re-entering the number but I'll post this anyway because there are other ways your code can be restructured.
print("\n-----Factorial Calculator------\n")
# Each function should handle just one thing
# Eg, option() should just handle whether user wants to continue, not try to handle factorial calc
# Also it's best to let the mainline logic decide whether to exit() or not
# This function should just return 'y' or 'n'
# Note that the original code captured the user's option in variable `opt` but then checked variable `option`.
# That's why it looped endlessly
def option():
opt = ' '
while ( opt != 'y' and opt != 'n' ):
opt = (input('Try again? y/n: '))
if opt == 'y':
return opt
elif opt == 'n':
return opt
else:
print("Please select a valid option")
# You specified argument `factorial` in original code but then did not use it.
# It still worked because the variable `num` was defined at the top level in the mainline
# Functions should be self-contained and rely only on the arguments that are passed into them
def facto(n):
fact = 1
for nums in range(1, n+1):
fact = fact * nums
return fact
opt = 'y'
is_print = False
while ( opt == 'y' ):
try:
num = int(input("Number(Just input the number): "))
opt = 'n'
is_print = True
except ValueError:
print("Invalid input")
opt = option()
if ( is_print ):
print(f" {num}! = {facto(num)}")
Thanks everyone for the help, but after struggling with it for a couple of days and taking few days off due to illness, I somehow did it. Eureka!
def facto(n):
fact = 1
for i in range(1, n + 1):
fact = fact * i
return fact
def opt():
option = (input("Do you want to try again? y/n: "))
if option == 'y':
number()
elif option == 'n':
exit()
else:
print("\nPlease select a valid option.")
opt()
def number():
try:
num = int(input("Number: "))
print(f"{num}! = {facto(num)}")
except ValueError:
print("Invalid input! Please input integers only")
opt()
number()

Multithreading attempt Python fail

The following code is an attempt of mine at a voice recognition program. The voice recognition works fine and can understand me, but I encountered a problem at certain points in the program the code would sort of freeze, or hang but without an error.
To get around this I attempted to add a timer using multi-threading which should begin at a = True and after 3 seconds the program would automatically close. If the recognising worked perfectly the a = False should stop the timer before it closed the program. This obviously hasn't worked or I wouldn't be here.
I added a few print statements here and there so I could visually see where the code was when running, and I saw the the code for the timer begins however the code for voice recognition does not.
import speech_recognition as sr
r = sr.Recognizer()
import os, threading, time, sys
import subprocess as sp
print("Voice Recognition Software\n\n***********************************\n")
class myThread (threading.Thread):
def run():
print("Checking")
while True:
if a == True:
if a == False:
continue
for x in range(3):
time.sleep(1)
if a == False:
break
sys.exit()
def program():
while True:
print("voice recog has begun")
r.energy_threshold = 8000
t = None
with sr.Microphone() as source:
print (">")
a = True
audio = r.listen(source)
a = False
try:
a = True
print("Processing...")
t = r.recognize_google(audio)
a = False
print (": " + t)
except sr.UnknownValueError:
print("Unknown input")
continue
except sr.RequestError as e:
print("An error occured at GAPI\nA common cause is lack of internet connection")
continue
if "open" in t:
t = t.replace("open","")
t = t.replace(" ","")
t = t + ".exe"
print (t)
for a,d,f in os.walk("C:\\"):
for files in f:
if files == t.lower() or files == t.capitalize() or files == t.upper():
pat = os.path.join(a,files)
print (pat)
sp.call([pat])
success = True
if success == True:
continue
a = False
success = False
thread1 = myThread.run()
thread2 = myThread.program()
thread1.start()
thread2.start()
EDIT:
I see some mistakes of my own here like indentation of the def function but even after fixing what I see it doesn't work as intended.

For loop won't end. Don't know why

I'm writing a for loop for a project that prompts the user to input a number and keeps prompting, continually adding the numbers up. When a string is introduced, the loop should stop. I've done it with a while loop, but the project states that we must do it with a for loop also. The problem is that the prompt keeps running even when 'a = false'. Could someone explain javascript's thinking process? I want to understand why it keeps running back through the loop even though the condition isn't met. Thank you
var addSequence2 = function() {
var total = 0;
var a;
for (; a = true; ) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
a = true;
total = +total + +input;
}
else if (isNaN(input)) {
a = false;
document.write("Your total is " + total);
}
}
};
There is a difference between a = true and a == true.
Your for-loop is basically asking "can I set 'a' to true?", to which the answer is yes, and the loop continues.
Change the condition to a == true (thus asking "Is the value of 'a' true?")
To elaborate, in most programming languages, we distinguish between assignment ("Make 'x' be 4") and testing for equality ("Is 'x' 4?"). By convention (at least in languages that derive their syntax from C), we use '=' to assign/set a value, and '==' to test.
If I'm understanding the specification correctly (no guarantee), what happens here is that the condition condenses as follows:
Is (a = true) true?
Complete the bracket: set a to true
Is (a) true? (we just set it to true, so it must be!)
Try using the equal to operator, i.e. change
for (; a = true; ) {
to
for (; a == true; ) {
You should use a == true instead of a = true......= is an assignment operator
for (; a = true; ), you are assigning the value to the variable "a" and it will always remain true and will end up in infinite loop. In JavaScript it should a===true.
I suspect you want your for to look like this :
for(;a==true;)
as a=true is an assignment, not a comparison.
a == true. The double equal sign compares the two. Single equal assigns the value true to a so this always returns true.
for (; a = true; ) <-- this is an assignation
for (; a == true; ) <-- this should be better
Here's your fixed code :
var addSequence2 = function() {
var total = 0;
var a = true;
for(;Boolean(a);) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
total = total + input;
}
else{
a = false;
document.write("Your total is " + total);
}
}
};

generating TTT game tree in lua

I am attempting to write a tic-tac-toe game in lua, and plan on using the minimax algorithm to decide non-human moves. The first step in this involves generating a tree of all possible board states from a single input state. I am trying to recursively do this, but cannot seem to figure out how. (I think) I understand conceptually how this should be done, but am having trouble implementing it in lua.
I am trying to structure my tree in the following manner. Each node is a list with two fields.
{ config = {}, children = {} }
Config is a list of integers (0,1,2) that represent empty, X, and O and defines a TTT board state. Children is a list nodes which are all possible board states one move away from the current node.
Here is my function that I currently have to build the game tree
function tree_builder(board, player)
supertemp = {}
for i in ipairs(board.config) do
--iterate through the current board state.
--for each empty location create a new node
--representing a possible board state
if board.config[i] == 0 then
temp = {config = {}, children = {}}
for j in ipairs(board.config) do
temp.config[j] = board.config[j]
end
temp.config[i] = player
temp.children = tree_builder(temp, opposite(player))
supertemp[i] = temp
end
end
return supertemp
end
The function is called in the following manner:
start_board = {config = {1,0,0,0}, children = {} }
start_board.children = tree_builder(start_board, 1)
When I comment out the recursive element of the function (the line "temp.children = builder(temp, opposite(player))") and only generate the first level of children. the output is correct. When called via code that is conceptually identical to (I am using love2D so formatting is different):
for i in pairs(start_board.children) do
print (start_board.children[i].config)
The three children are:
1,1,0,0
1,0,1,0
1,0,0,1
However, once I add the recursive element, the following is output for the same three children
1,1,2,1
1,1,2,1
1,1,2,1
I have been searching online for help and most of what I have found is conceptual in nature or involves implementation in different languages. I believe I have implemented the recursive element wrongly, but cannot wrap my head around the reasons why.
Don't understand what opposite(player) means in temp.children = tree_builder(temp, opposite(player)).
Notice that a recursion need an end condition.
This is my solution under your structure:
local COL = 3
local ROW = 3
local function printBoard( b )
local output = ""
local i = 1
for _,v in ipairs(b.config) do
output = output .. v .. ( (i % COL == 0) and '\n' or ',' )
i = i + 1
end
print( output )
end
local function shallowCopy( t )
local t2 = {}
for k,v in pairs(t) do
t2[k] = v
end
return t2
end
local MAX_STEP = COL * ROW
local ING = 0
local P1 = 1
local P2 = 2
local TIE = 3
local STATUS = { [P1] = "P1 Win", [P2] = "P2 Win", [TIE] = "Tied" }
local start_board = { config = {P1,0,0,0,0,0,0,0,0}, children = {} }
local function checkIfOver( board, step )
local config = board.config
local over = false
--check rows
for i=0,ROW-1 do
over = true
for j=1,COL do
if 0 == config[i*COL+1] or config[i*COL+j] ~= config[i*COL+1] then
over = false
end
end
if over then
return config[i*COL+1]
end
end
--check cols
for i=1,COL do
over = true
for j=0,ROW-1 do
if 0 == config[i] or config[i] ~= config[i+COL*j] then
over = false
end
end
if over then
return config[i]
end
end
--check diagonals
if config[1] ~= 0 and config[1] == config[5] and config[5] == config[9] then
return config[1]
end
if config[3] ~=0 and config[3] == config[5] and config[5] == config[7] then
return config[3]
end
if step >= MAX_STEP then
return TIE
else
return ING
end
end
local function treeBuilder( board, step )
--check the game is over
local over = checkIfOver( board, step )
if over ~= ING then
printBoard( board )
print( STATUS[over], '\n---------\n' )
return
end
local child
local childCfg
for i,v in ipairs(board.config) do
if 0 == v then
child = { config = {}, children = {} }
childCfg = shallowCopy( board.config )
childCfg[i] = (step % 2 == 0) and P1 or P2
child.config = childCfg
table.insert( board.children, child )
treeBuilder( child, step + 1 )
end
end
end
treeBuilder( start_board, 1 )

Reapeat/until help in lua

Hello I've been trying to get this code to work, I even cheated and added in the goal to my code and its still not accepting my answer, any suggestions?
-- Functions...
function p() -- For user imput..
print("Enter # and try to get the closest to it! (Valid range is 1-100)")
local var = tonumber(io.read())
if var == nil then
var = 0
end
return var
end
--Start main code..
-- Initialize the pseudo random number generator (I'm on windows...)
math.randomseed( os.time() )
math.random(); math.random(); math.random()
-- Setting goal
goal = math.random(1,100)
-- Guessing loop...
repeat
g = p()
print(g)
print(goal)
until g == Goal
print("YOU GUESSED THE GOAL!")
Replace the G by a lower case g.
until g == goal

Resources