As the title says, this is a double integer checker, meaning it has two functions + the main. Please correct me if I do not paraphrase it correctly. Anyways, here is the model:
def is_integer(kraai):
kraai.replace(" ", "")
if len(kraai) == 1:
if kraai.isdigit():
print(valid)
else:
print(invalid)
exit()
elif len(kraai) > 1:
if roek == "-" or roek == "+" or roek.isdigit():
print(valid)
else:
print(invalid)
exit()
elif len(kraai) == 0:
print(invalid)
exit()
def remove_non_integer(kauw):
if len(kauw) >= 1:
for z in kauw:
if not z.isdigit():
ekster = kauw.replace(z, "")
print(invalid)
print(f'''\nNot all characters after the first are integers...
\nnogsteeds, vet raaf!:, {ekster}''')
if __name__ == '__main__':
valid = "valid"
invalid = "invalid"
kraai = input("Welcome to the integer tester. Please give an input: ")
if len(kraai) > 1:
roek = kraai[0]
kauw = kraai[1:]
y = "".join([roek, kauw])
corvidae = is_integer(kraai), remove_non_integer(kauw)
elif len(kraai) < 1:
corvidae = is_integer(kraai)
As you can see, one functions to check the integer while the other functions to remove every non-integer. However, three problems:
It will remove only one unique character
It will print the same message every time a non-integer is in the integer
It will print both 'valid' and 'invalid' for some reason when the remove_integer(x) function filters a non-integer.
Any help?
So yeah there were multiple errors at the time I posted this question.
def is_integer(kraai):
valid = "valid"
invalid = "invalid"
if len(kraai) == 1:
if kraai.isdigit():
print(valid)
elif not kraai.isdigit():
print(invalid)
elif len(kraai) > 1:
if kraai[0] == "-" or kraai[0] == "+" or kraai[0].isdigit():
if kraai[1:].isdigit():
print(True)
print(valid)
else:
print(False)
else:
print(invalid)
elif len(kraai) == 0:
print(invalid)
exit()
def remove_non_integer(bonte_kraai):
invalid = "invalid"
roek = bonte_kraai[0]
kauw = bonte_kraai[1:]
y = "".join([roek, kauw])
for x in kauw:
if x.isalpha():
ekster = ''.join([i for i in y if i.isdigit() or i == "-"])
print(False)
print(invalid, f'''\nNot all characters after the first are integers...
\nnogsteeds, vet raaf!: {ekster}''')
break
if __name__ == '__main__':
kraai = input("Welcome to the integer tester. Please give an input: ")
kraai.replace(" ", "")
if len(kraai) == 1:
corvidae = is_integer(kraai)
elif len(kraai) > 1:
for x in kraai[1:]:
if kraai[1:].isdigit():
corvidae = is_integer(kraai)
break
elif x.isalpha():
bonte_kraai = kraai
corvidae = remove_non_integer(bonte_kraai)
break
The difference between both codes, now, is first of all that they work individually as observable in the if name == 'main' block.
Secondly, I used the 'break' statement to break the loop after it has fulfilled its task. Otherwise it will repeat a number of times and that is unwanted (it should only run once).
Thirdly, as you can see I moved some variables to functions so that pytest doesn't return an 'x is not defined' error. I substituted the variables with indexes [].
Thanks.
Related
so my code is designed to basically create a bingo card, then when you press enter draws a number and changes the bingo card value to 0 if the drawn number matches. My issue is that my code isn't properly producing a bingo or not a bingo which you can see towards the end of the code. How should I change this so that my code will return bingo when I have bingo.
import random #Condernsed solo version with call and player together
import numpy as np
def bingo_card(): #Code to generate BINGO card using numpy array
test1=np.array(random.sample(range(1,16),5))
test2=np.array(random.sample(range(16,31),5))
test3=np.array(random.sample(range(31,46),5))
test4=np.array(random.sample(range(46,61),5))
test5=np.array(random.sample(range(61,76),5))
test= np.concatenate((test1,test2,test3,test4,test5))
test= test.reshape(5,5)
test[2,2]=0
bingo_card.test = test
BINGO= print("Your Card")
print("B", test[0]),
print("I", test[1]),
print("N", test[2]),
print("G", test[3]),
print("O", test[4])
card = BINGO
return card
def called_value(): #should be close to the code we use to check if called value is in generated matrix, may need some formatting and fixing
checked_card = bingo_card.test
while True:
called_num = input ("Type called number to mark card or press 's' to quit if you think you have bingo").lower()
if called_num != "s":
number_check = int(called_num)
checked_card = np.where(checked_card==number_check,0,checked_card)
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
elif called_num == "s":
BINGO = print("Your Card")
print("B", checked_card[0]),
print("I", checked_card[1]),
print("N", checked_card[2]),
print("G", checked_card[3]),
print("O", checked_card[4])
row_zeros = np.count_nonzero(checked_card == 0, axis=1)
col_zeros = np.count_nonzero(checked_card == 0, axis=0)
diagonal_zeros = np.count_nonzero(np.diag(checked_card) == 0)
diagonal1_zeros = np.count_nonzero(np.diag(np.fliplr(checked_card)) == 0)
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
def solo():
bingo_card()
called_value()
solo()
You've committed one of the classic blunders.
for i in range (5):
if (row_zeros[i] or col_zeros[i]) == 5:
return ("Bingo!")
elif (diagonal_zeros or diagonal1_zeros) == 5:
return ("Bingo!")
else:
return ("Not Bingo")
row_zeros[i] or col_zeros[i] is going to be True or False (usually True), which is never equal to 5. And you don't need to loop to check the diagonals. You need:
if diagonal_zeros == 5 or diagonal1_zeros == 5:
return ("Bingo!")
for i in range (5):
if row_zeros[i] == 5 or col_zeros[i] == 5:
return ("Bingo!")
return ("Not Bingo")
Here is my code for converting infix to postfix using a previous stack code. The stack code is functional but I don't understand what is wrong with my postix converter code. It is returning "RecursionError: maximum recursion depth exceeded". But I don't think that is the problem. I think it might be the PrecedenceCheck function
def postfix(expr):
if len(expr)<=0 or not isinstance(expr,str):
print("expr error: postfix")
return "error"
expr=expr.strip()
items=Stack()
outputVariable = ""
pos=0
for i in range(len(expr)):
if expr[i] in '+-*/^()':
items.push(expr[pos:i].strip())
items.push(expr[i]) # operator
pos=i+1
items.push(expr[pos:].strip())
elif expr[i] is '1234567890':
outputVariable += i
elif expr[i] is '(':
items.push(expr[i])
elif expr[i] is ')':
while True:
temp = items.pop()
if temp is None or temp == '(':
break
else:
outputVariable += temp
elif expr[i] in '+-*/^' and (items is False or items.peek() is '('):
items.push(expr[i])
elif PrecedenceCheck(expr[i]) is True:
items.push(expr[i])
elif expr[i] in '+-*/^' and PrecedenceCheck(expr[i]) is False:
while True:
items.pop()
if items.isEmpty() is True:
items.push(expr[i])
break
return outputVariable
precedence = {}
precedence['*'] = 3
precedence['/'] = 3
precedence['+'] = 2
precedence['-'] = 2
precedence['('] = 1
precedence['^'] = 1
def PrecedenceCheck(char):
items=Stack()
outputVariable= " "
if char in '1234567890':
return False
elif PrecedenceCheck(char) is True:
while precedence[char] < precedence[items.peek()]:
x = items.pop()
x += outputVariable
items.push(char)
return outputVariable
else:
return 'error message'
Input: ('1 ^ 2')
Expected output: '1.0 2.0 ^'
Actual Output: RecursionError: maximum recursion depth exceeded
if PrecedenceCheck(char) is True: occurs several times, yet PrecedenceCheck can return False or a string, neither of which will be True. Probably better to clean up PrecedenceCheck to always return a bool, or at least change your conditionals to if PrecedenceCheck(char): and cross your fingers that it never returns ''.
Doesn't let me to input values to x.
It runs and it says that is completed with exit code 0. Why?
def donuts():
x = int(input("How many donutes?"))
if x < 10:
print("Numbers of donuts: "+ x)
else:
print("Number of donute: many")
def litere():
x = input("Type a word! : ")
if len(x) <= 2:
print("NULL")
else:
k = len(x) -1
print(x[0:3] + x[k-2])
if ' name ' == ' main ':
donuts()
__name__ is a variable. It should have quotes around it. When you surround it with quotes python treats it like a regular string. Replace the bottom with
if __name__ == "__main__":
donuts()
Remove quotes around '__name__' so it becomes __name__:
def donuts():
x = int(input("How many donutes?"))
if x < 10:
print("Numbers of donuts: "+ x)
else:
print("Number of donute: many")
def litere():
x = input("Type a word! : ")
if len(x) <= 2:
print("NULL")
else:
k = len(x) -1
print(x[0:3] + x[k-2])
if __name__ == "__main__":
donuts()
Here is the change I made to your code:
if __name__ == "__main__":
donuts()
Using Spyder Python 3.6 this code does not execute, says that the method ispal is not defined. However when I run it and put in an integer first (say my string input = 0), then it will run after and recognize the method. It seems like I have to go through a branch other than the call to the method first. Thanks for the critique.
s = input('enter a string: ')
s1 = s
s1 = s1.lower()
s1 = s1.replace(',', '')
s1 = s1.replace(' ', '')
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[1:])
First, as pointed out by TGKL you're calling ispal before it's defined. So define it before calling, i.e:
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[1:])
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')
Second your palindrome recursive function is right except when you call ispal inside itself. Instead of ispal(s1[1:]) you should do ispal(s1[1:-1]) which will remove both the first and the last character, which has been just tested.
You have to define your method first, then call it:
s = raw_input('enter a string: ') #use raw_input so the text it takes will give to you directly a string without ""
s1 = s
s1 = s1.lower()
s1 = s1.replace(',', '')
s1 = s1.replace(' ', '')
def ispal(s1):
if len(s1) <= 1:
return True
else:
#if the first and last char are the same
#and if all
return s1[0] == s1[-1] and ispal(s1[2:]) # here you put ispal(s1[1:]) it doesn't work properly :/
if s1.isalpha():
if ispal(s1) == True:
print(s,' is a palindrome')
else:
print(s,' is not a palindrome')
else:
print('you entered illegal chars')
Like using this to validate that an input is only alpha-numeric:
while True:
str = input('')
if str.isalnum():
break
else:
print("Please include only alpha-numeric characters.\n")
This code has worked for all instances that I have tested it in, but is this bad practice?
That's fine. Here is a note, however: you can find out if the while loop exited with a break or without one by using else:
x = 0
while x < 4:
x += 1
else:
print("no break")
# prints no break
If you break, however:
x = 0
while x < 4:
x += 1
if x == 2:
break
else:
print("no break")
# Does not print
you can abstract it further
def verified_input(prompt='',test_condition=lambda x:1,err_message="Please Enter Valid Input"):
while True:
result = input(prompt)
if test_condition(result):
return result
print( err_message )
def verified_alnum(prompt,err_message="Please enter Only alpha numerics"):
return verified_input(prompt,lambda x:x.isalnum(),err_message)
result = verified_alnum("Enter Password:","A password must be only letters and numbers")
this allows you to create any number of test conditions quickly and relatively verbosely