when i try to print this line:
print(perfect_square(0))
i should get True but instead i get a time limit exceeded error and i dont know how to fix it.
i tried chaging it to an elif statment instead of 2 separate if statements but i still get that error
This is my current code:
def perfect_square(n):
s = 1
while s != n:
if s*s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
def perfect_cube(n):
s = 1
while s != n:
if s*s * s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
Seems quite clear to me why the perfect_square(0) and perfect_cube(0) cases cause an infinite loop. You start s=1 and always increment it s+=1. It will never be equal to n=0 so you get an infinitely running program. Maybe try making checks for invalid values of n?
def perfect_cube(n):
if n < 1: return False
# ...
I'm having some issues with the psets 2 of cs50p, precisely I'm talking about the "Vanity Plates" problem, where I fulfilled all requests except one, which said:
“Numbers cannot be used in the middle of a plate; they must come at the end. For example, AAA222 would be an acceptable … vanity plate; AAA22A would not be acceptable. The first number used cannot be a ‘0’.” Can you help me? Thank's
this is the code I wrote so far:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s.isalnum() | s[:2].isalpha() | 2 < len(s) < 6 | :
else:
return False
main()
you have to consider all the cases one by one, this is how I solved it:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if len(s) < 2 or len(s) > 6:
return False
elif not s[0].isalpha() or not s[1].isalpha():
return False
elif checkFirstZero(s):
return False
elif checkMiddleZero(s):
return False
elif last(s):
return False
elif worng(s):
return False
return True
def last(s):
isAlp = False
isNum = False
for w in s:
if not w.isalpha():
isNum = True
else:
if isNum:
return True
return False
def checkCuntuNNumber(s):
isFirstTry = True
isNum = False
for w in s:
if not w.isalpha():
if isFirstTry:
isNum = True
isFirstTry = False
if isNum and s[-1].isalpha():
return True
def checkMiddleZero(s):
isFirstTry = True
isNum = False
for w in s:
if not w.isalpha():
if isFirstTry:
isNum = True
isFirstTry = False
if isNum and s[-1].isalpha():
return True
else:
return False
def checkFirstZero(s):
for w in s:
if not w.isalpha():
if int(w) == 0:
return True
else:
return False
def worng(s):
for w in s:
if w in [" ", ".", ","]:
return True
return False
main()
This is how I did it. I am sure there is an easier way to do it out there but hopefully this helps :)
characters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
numbers = ['1','2','3','4','5','6','7','8','9','0']
def main ():
plate = (input ("Plate: ")).upper()
if is_valid(plate):
print ('Valid')
else:
print ('Invalid')
def is_valid (s):
#Check whether length is between 2 and 6 included
if len(s) < 2 or len(s) > 6:
return False
elif char_check(s):
return False
elif char_start(s):
return False
elif zero_check(s):
return False
elif alpha_follow_check (s):
return False
else:
return True
#Check for valid characters
def char_check(s):
for i in s:
if not (i in characters or i in numbers):
return True
#Check whether first two are letters
def char_start (s):
for i in s[:2]:
if not i in characters:
return True
#Check if zero is first number listed
def zero_check (plate_response):
length_string = len (plate_response)
letter_position = 0
number_present = 0
zero_position = None
if any (i in numbers for i in plate_response):
for i in plate_response [0:length_string]:
if i == '0':
zero_position = letter_position
break
letter_position = letter_position + 1
for i in plate_response [0:zero_position]:
if i in numbers:
number_present = 1
if number_present == 0:
return True
else:
return False
#Check alphabet follows numbers
def alpha_follow_check (plate_response):
length_string = len (plate_response)
letter_position = 0
number_position = None
if any (i in numbers for i in plate_response):
for i in plate_response [0:length_string]:
if i in numbers:
number_position = letter_position
break
letter_position = letter_position + 1
for i in plate_response [number_position:length_string]:
if i in characters:
return True
else:
return False
main ()
idk if will help, but the part that i've had the most difficulty in this problem was: "Numbers cannot be used in the middle of a plate; they must come at the end, AAA22A would not be acceptable", then i learned that you can create a full list from the plate that the user inputed, and how to actually use it, with the:
ls = list(s)
for i in range(len(ls)):
After that, we check when the first number appears. "if == '0'" ,then returns False to the function.
After that, if the first number isn't a 0, the program checks if the next item in that list is letter, and, if it is, also return False.
i < len(ls) -1 => this part guarantee that the program will not run in the last item of the list
ls[i+1].isalpha() => and this part check that, if the item on the list was a number, and then the next item is a letter, it returns False
I hope it helps someone, i've spend a lot of time trying to figure it out what to do, and then reached this solution: "for i in range(len(ls))".
Now my code is complete and working.
My code:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if not s.isalnum():
return False
elif len(s) < 4 or len(s) > 7:
return False
elif s[0].isdigit()or s[1].isdigit():
return False
elif s[-1].isalpha() or s[-2].isalpha():
return False
else:
ls = list(s)
for i in range(len(ls)):
if ls[i].isdigit():
if ls[i] == '0':
return False
elif i < len(ls) -1 and ls[i+1].isalpha():
return False
else:
return True
main()
Python: Why don't I get a result in the terminal
def is_even(number):
if number % 2 == 0:
return True
return False
is_even(10)
You need to print the output of the function. You also need to create the function.
def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(10)) #True
print(is_even(7)) #False
def yesno(endwhat):
end = False
while not end:
ok = input("<Y/N>")
if ok.upper == 'Y' or ok.upper == 'N':
if ok.upper == 'Y':
end = True
endwhat = True
else:
print("Enter only <Y/N>")
return(ok)
This Doesn't Work, It Just Repeats even when I put Y or N.
I think the problem is when I enter a var in 'endwhat' it doesn't change it to True.
Any Help is Truly Appreciated.
Thanks...
You forgot to put () to string function.
def yesno(endwhat):
end = False
while not end:
ok = input("<Y/N>")
if ok.upper() == 'Y' or ok.upper() == 'N':
if ok.upper() == 'Y':
end = True
endwhat = True
else:
print("Enter only <Y/N>")
return(ok)
.upper() is a function, and all functions must contain a '()' for any parameters(if there are any). Otherwise they are taken to be default values mentioned. you have forgotten to put '()'. the right version would be-
def yesno(endwhat):
end = False
while not end:
ok = input("<Y/N>")
if ok.upper() == 'Y' or ok.upper() == 'N':
if ok.upper() == 'Y':
end = True
endwhat = True
else:
print("Enter only <Y/N>")
return(ok)
You forgot () for upper.
You can also use the code as following:
def yesno(endwhat):
end = False
while not end:
ok = input("<Y/N>").upper()
if ok == 'Y' or ok == 'N':
if ok == 'Y':
end = True
endwhat = True
else:
print("Enter only <Y/N>")
return(ok)
Basic Tic-Tac-Toe game. I have everything running except I am having trouble with the check_for_winner function. No matter what I do I can't get the code to exit the function once a = True. Without the while loop or with. How can I get the code to stop checking every single possible instance once a winner has been detected?
I've tried setting a == False, I've tried it without the while statement which gets rid of the looping but doesn't get it to exit out when the condition is met.
def check_for_winner():
a = False
while a is False:
for x in range(3):
if print(grid[x] == grid[x+3] and grid[x+3] == grid[x+6]):
a = True
return a
for x in range(0,7,3):
if print(grid[x] == grid[x+1] and grid[x+1] == grid[x+2]):
a = True
return a
if print((grid[0] == grid[4] and grid[4] == grid[8]) or (grid[2] ==
grid[4] and grid[4] == grid[6])):
a = True
return a
It should exit the while loop once one the conditions is met but it continues to loop through. Instead of exiting then printing who one it prints True the False six times, repeating.
The problem is all the unnecessary calls to print(). They're all returning None which causes the if checks to all be equivalent to if None:. Get rid of them.
def check_for_winner():
a = False
while a is False:
for x in range(3):
if grid[x] == grid[x+3] and grid[x+3] == grid[x+6]:
a = True
return a
for x in range(0,7,3):
if grid[x] == grid[x+1] and grid[x+1] == grid[x+2]:
a = True
return a
if (grid[0] == grid[4] and grid[4] == grid[8]) or (grid[2] ==
grid[4] and grid[4] == grid[6]):
a = True
return a
return False
Then you can get rid of the unnecessary a variable and the while loop.
def check_for_winner():
for x in range(3):
if grid[x] == grid[x+3] and grid[x+3] == grid[x+6]:
return True
for x in range(0,7,3):
if grid[x] == grid[x+1] and grid[x+1] == grid[x+2]:
return True
if (grid[0] == grid[4] and grid[4] == grid[8]) or (grid[2] ==
grid[4] and grid[4] == grid[6]):
return True
return False
You can also use comparison chaining to replace foo == bar and bar == baz with foo == bar == baz.
def check_for_winner():
for x in range(3):
if grid[x] == grid[x+3] == grid[x+6]:
return True
for x in range(0,7,3):
if grid[x] == grid[x+1] == grid[x+2]:
return True
if grid[0] == grid[4] == grid[8] or grid[2] == grid[4] == grid[6]:
return True
return False