Check whether a string is a valid number - python

I need to check if a string is a valid number or not.
Here are some examples of valid:
1234
-1234
12.4
0.6
-0.6
-1234567890.123456789
Non-valid:
+123
123.
.6
00.6
12-.6335
If the first digit is a 0, a decimal point "." must come after it.
I have tried the following code but it says "time limit exceeded". I'm not sure what that means.
def valid_float(number_string):
counter = 0
if number_string[0].isdigit() or number_string[0] == "-" or number_string[0] == "0":
while number_string[0] == "-":
if number_string[1].isdigit():
counter += 1
else:
counter = 0
while number_string[0].isdigit():
if number_string[1] == "." and number_string[2].isdigit():
counter += 1
else:
counter = 0
while number_string[0] == "0":
if number_string[1] == ".":
counter += 1
else:
counter = 0
if counter == 3:
return True
else:
return False
else:
counter = 0

The error you get means that the program keeps going for a long time because it is 'stuck' somewhere. Most of the time its because of a bad recursion function or, in this case, a while loop that will loop forever.
Your while loops will loop forever because you don't change the thing it checks as condition: if the condition is true in the beginning it will be true all the time so the program will never quit the while loop.
I wanted to correct your code but I can't figure out what you where trying so here is some code that will hopefully help you out:
for i in range(0,len(number_string)):
if i == 0 and number_string[0] == "." :
return false
if i != 0 and number_string[0] == "." :
continue
if i == 0 and number_string[0] == "-" :
continue
if i == 0 and number_string[0] == "0" and len(number_string[0])>1:
if number_string[1] != "." :
return false
if number_string[i].isdigit():
continue
return false

Related

Python Restarting a loop

How can I restart the loop in the following code after it hits 1 since in 3N+1 it goes 1>4>2>1?
Code:
import math
import random
num = 1
NumTF = False
play = True
while play:
if num % 2 == 0:
num = num / 2
else:
num = 3 * num + 1
print(num)
if num == 1:
play = False
if play == False:
num += 1 and play == True
I'm assuming that you want to end the loop, because ...Collatz Conjecture.
All you have to do is add this simple if statement to the end:
elif num == 1:
play = False
after the if num%2 == 0 statement, so the while loop ends. Currently, your doing this after your doing num = 3*num+1, which makes it 4, so that case never happens. as rv.kvetch mentioned, the play==True does unexpected things, so just delete everything after print(num), as those are unnecessary.

Binary Search not working when it should be

I have a binary search that searches a list from a user given input of an email. I get no errors and I get no output from it. I can't see where its going wrong?
def BubbleSort(logindata):
NoSwaps = 1
N = len(logindata)
logindata = list(logindata)
while NoSwaps == 1:
Count = 1
NoSwaps = 0
for Count in range(N-1):
if logindata[Count] > logindata[Count+1]:
temp = logindata[Count]
logindata[Count] = logindata[Count+1]
logindata[Count+1]=temp
NoSwaps=1
return tuple(logindata)
def BinarySearch(logindata,ItemSought):
First=0
Last=len(logindata)-1
ItemFound = False
SearchFailed = False
while ItemFound == False or SearchFailed == False:
Midpoint = (First + Last) // 2
if logindata[Midpoint] == ItemSought:
print("Item Found")
ItemFound = True
print("Item Found")
break
elif logindata[Midpoint][0] > ItemSought:
Last = Midpoint - 1
else:
First = Midpoint + 1
if __name__ == "__main__":
logindata=["tom#gmail.com","Password1"],["harry#gmail.com","Password2"],["jake#gmail.com","Password3"]
logindata=BubbleSort(logindata)
print(logindata)
ItemSought=input("Enter username")
BinarySearch(logindata,ItemSought)
In
if logindata[Midpoint] == ItemSought:
you compare list with a string. So I think you need
if logindata[Midpoint][0] == ItemSought:
You never terminate the search. If the item isn't in the list, you get to a stable midpoint and loop infinitely. If you do find the item, you loop infinitely on that (see Yehven's answer).
I traced it with the additions you see here:
SearchFailed = False
iter = 0
while iter < 10 and (ItemFound == False or SearchFailed == False):
iter += 1
Midpoint = (First + Last) // 2
print (First, Midpoint, Last, ItemSought)
if logindata[Midpoint] == ItemSought:
Note that you don't ever change SearchFailed. For instance, when I search for "harry", the loop hits a stable infinite point at (0, -1, -2) for First, Middle, Last.
Is that enough of a hint to let you fix it yourself?

Loop stops even though only 1 of 2 variables is true

So I'm attempting to make a Brainfuck interpreter, however in the while loop that I am using to execute the Brainfuck loop, it is breaking out even though only one condition is true.
Example:
+++[>+<-]
Should result in:
[0, 3]
However, when the loop begins at [, it will create a new cell so the structure goes from [3] to [3, 0]. Thus, the current working cell is 0 and the loop is breaking out. However, I have it to only break if it is 0 and the current character is ].
cells = [0] # Array of data cells in use
brainfuck = str(input("Input Brainfuck Code: ")) # Brainfuck code
workingCell = 0 # Data pointer position
count = 0 # Current position in code
def commands(command):
global cells
global workingCell
if command == ">":
workingCell += 1
if workingCell > len(cells) - 1:
cells.append(0)
elif command == "<":
workingCell -= 1
elif command == "+":
cells[workingCell] += 1
elif command == "-":
cells[workingCell] -= 1
elif command == ".":
print(chr(cells[workingCell]))
elif command == ",":
cells[workingCell] = int(input("Input: "))
def looper(count):
global cells
global workingCell
print("START LOOP", count)
count += 1
looper = loopStart = count
while brainfuck[looper] != "]" and cells[workingCell] != 0: # This line is causing trouble
if brainfuck[looper] == "]":
looper = loopStart
commands(brainfuck[looper])
count += 1
looper += 1
return count
while count < len(brainfuck):
if brainfuck[count] == "[":
count = looper(count)
print("END LOOP", count)
else:
commands(brainfuck[count])
count += 1
Thank you in advance.
I have it to only break if it is 0 and the current character is ]
If that's what you want, you have the logic in your while wrong. It should be:
while not (brainfuck[looper] == "]" and cells[workingCell] == 0):
And according to deMorgan's Laws, when you distribute not across and, you invert each of the conditions and change and to or, so it should be:
while brainfuck[looper] != "]" or cells[workingCell] != 0:
If this is confusing, you could just write:
while True:
if brainfuck[looper] == "]" and cells[workingCell] == 0:
break
This mirrors what you said in the description exactly.

List index out of range when coding a valid move for board game

Hey everyone im new here and im trying to make a game called HiQ now i got the board drawn and everything and i can click on one of the pieces, but when i do the piece does change color and i get an error in the shell as well (listed below) im not sure why im getting this and i was hoping you guys could give me better insight. Ill provide my code below as well and it is coded in python 3, thank you
builtins.IndexError: list index out of range
boardcirc =[[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[1,1,1,1,1,1,1,1,1],
[1,1,1,1,2,1,1,1,1],
[1,1,1,1,1,1,1,1,1],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0]]
def HiQ():
splash_screen()
make_board()
def make_board():
make_sqr()
make_circ()
get_click()
def get_click():
global count, boardcirc
while 1!=0:
count = count - 1
displaymessage("Pieces: " + str(count))
where = win.getMouse()
col = where.x//90
row = where.y//90
valid_move(row,col)
make_move(row,col)
def valid_move(row,col):
if boardcirc[row][col] == 0:
return False
if boardcirc[row-1][col] == 1 and boardcirc[row-2][col] == 1:
return True
if boardcirc[row+1][col] == 1 and boardcirc[row+2][col] == 1:
return True
if boardcirc[row][col-1] == 1 and boardcirc[row][col-2] == 1:
return True
if boardcirc[row][col+1] == 1 and boardcirc[row][col+2] == 1:
return True
def make_move(row,col):
while valid_move(row,col) == True:
col = (col*85)+42
row = (row*85)+42
circ = Circle(Point(col,row),35)
circ.setFill("white")
circ.draw(win)
thats everything that applies to the error
For your valid_move(row,col), you can't have all those if statements.
Instead of doing this, use elif's after the initial if statement, and don't forget to write an else statement
if boardcirc[row][col] == 0:
return False
if boardcirc[row-1][col] == 1 and boardcirc[row-2][col] == 1:
return True
elif boardcirc[row+1][col] == 1 and boardcirc[row+2][col] == 1:
return True
elif boardcirc[row][col-1] == 1 and boardcirc[row][col-2] == 1:
return True
elif boardcirc[row][col+1] == 1 and boardcirc[row][col+2] == 1:
return True
else:
return False

Turning iteration into recursion

I want to check if the string user entered has a balanced amount of ( and )'s
ex. ()( is not balanced
(()) is balanced
def check(string):
counter=0
string=string.replace(" ","")
if string[0] is "(":
for x in string:
if x is "(":
counter=counter+1
elif x is ")":
counter=counter-1
if counter1 is 0:
print("Balanced")
else:
print("Unbalanced")
else:
print ("Unbalanced")
so this works, but how do I solve this problem with recursion? I am trying to think how I can make a variable decrease each time i call it recursively and once it's 0, stop.s
>>> def check(mystr, barometer=0):
... if not mystr:
... return barometer
... elif mystr[0] == "(":
... return check(mystr[1:], barometer+1)
... elif mystr[0] == ")":
... return check(mystr[1:], barometer-1)
... else:
... return check(mystr[1:], barometer)
...
>>> for s in ["()", "(()", "(())", "()()"]: print(s, check(s))
...
() 0
(() 1
(()) 0
()() 0
0 means you're properly balanced. Anything else means you're not balanced
A direct, equivalent conversion of the algorithm would look like this:
def check(string, counter=0):
if not string:
return "Balanced" if counter == 0 else "Unbalanced"
elif counter < 0:
return "Unbalanced"
elif string[0] == "(":
return check(string[1:], counter+1)
elif string[0] == ")":
return check(string[1:], counter-1)
else:
return check(string[1:], counter)
Use it like this:
check("(())")
=> "Balanced"
check(")(")
=> "Unbalanced"
Notice that the above algorithm takes into account cases where the closing parenthesis appears before the corresponding opening parenthesis, thanks to the elif counter < 0 condition - hence fixing a problem that was present in the original code.

Categories