I have been doing some Leetcode recently to prepare for interviews and I have recently come across a problem with my code. I was wondering what was wrong with this code and why my code will not return false when it is supposed to. Any help is appreciated.
def isHappy(n):
num = [int(i) for i in str(n)]
newSum = 0
for i in num:
newSum += i ** 2
if newSum != 1:
print('repeating')
try:
isHappy(newSum)
except RecursionError:
return False
return True
print(isHappy(2))
Related
I need to write a code that prints out valid or invalid for an input of letters and numbers for a license plate. The conditions are: first two characters must be letters, characters have to be between 2 and 6, and if numbers are used, 0 should not be the first, nor should a number appear before a letter.
I put the code below on Thonny and cannot understand why len(l) == 4 part of the conditional statement for def valid_order() returns None and does not execute the next line of the code whereas others work fine. My code should return "Valid" for CSAA50, but it returns invalid. Why?
Also, is there an elegant way to write def valid_order()?
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s[0:2].isalpha() and 6 >= len(s) >= 2 and s.isalnum() and valid_order(s):
return True
else:
return False
def valid_order(c):
n = []
l = list(c[2:len(c)])
for i in c:
if i.isdigit():
n += i
if n and n[0] == "0":
return False
if len(l) == 2:
if l[0].isdigit() and l[1].isalpha():
return False
if len(l) == 3:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha():
return False
else:
if l[1].isdigit() and l[2].isalpha():
return False
if len(l) == 4:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha() or l[3].isalpha():
return False
else:
if l[1].isdigit():
if l[2].isalpha() or l[3].isalpha():
return False
else:
if l[2].isdigit() and l[3].isalpha():
return False
else:
return True
main()
Can anyone explain this please?
def cube(number):
number = (number**3)
return number
def by_three(number):
if number % 3 == 0:
cube(number)
return number
else:
return False
by_three(3)
Oops, try again. by_three(3) returned 3 instead of 27
Why does this not return 27?
So the problem is that in your by_three function you are returning the parameter "number" passed into the by_three function and not returning the result of the cube function.
Your code:
def by_three(number):
if number % 3 == 0:
cube(number)
## problem is right here you should return cube(number) not number
return number
else:
return False
Fixed code.
def by_three(number):
if number % 3 == 0:
return cube(number) ## note the change here
else:
return False
Check you are not referring the returned value to variable number.The code will be like this.
def cube(number):
number = (number**3)
return number
def by_three(number):
if number % 3 == 0:
number=cube(number)
return number
else:
return False
print by_three(3)
Hope your problem is solved
For example, we have two functions:
def function1(num):
return num * 3
and second function
def function2(num):
if num%2 == 0:
print(num)
function1(num)
return num
If you call function(1), as expected it will return 1
If you call function(2), it will return 2 not 6. WHY?
Lets analyze this function2(2)
def function2(num): # num = 2
if num%2 == 0: # yes, it meets the condition
print(num)
function1(num) # it steps into function 1, this return num*3 == 6 however we do not know where it is saved (its address is unknown).
return num # this 'num' it is just the argument == 2
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 5 years ago.
I am trying to write a program that finds happy numbers:
more info here.
This is not a school assignment, but I'm just trying to practice my Python 2.7.
Basically, recursion is a vital part of this because I have to keep squaring every digit.
In my code, I use recursion to keep running it, I have a base case, and it works, but for some reason, even though I call the function, no recursion occurs.
It just returns the digits squares for the first number, which is a bug test, and it returns None, then it stops running.
What's the problem?
num = raw_input('Pick a positive integer that you want to check for a happy number')
def happyn(number,second,third,fourth):
if len(number) == 2:
go = int(number[0])**2 + int(number[1])**2
elif len(number) == 3:
go = int(number[0])**2 + int(number[1])**2 + int(number[2])**2
elif len(number) == 4:
go = int(number[0])**2 + int(number[1])**2 + int(number[2])**2 + int(number[2]**2)
if len(number) == 1 and int(number) == 1 or int(number) == 7:
return True
elif len(number) == 1:
return False
else:
print go
go = str(go)
go1 = go[0]
print go1
if len(go) == 1:
go1 = go[0]
happyn(go1,0,0,0)
elif len(go) == 2:
go1 = go[0]
go2 = go[1]
happyn(go1,go2,0,0)
elif len(go) == 3:
go1 = go[0]
go2 = go[1]
go3 = go[2]
happyn(go1,go2,go3,0)
elif len(go) == 4:
go1 = go[0]
go2 = go[1]
go3 = go[2]
go4 = go[4]
happyn(go1,go2,go3,go4)
print happyn(num,0,0,0)
All the possible execution branches must return something, otherwise the recursion won't work. For example, this is wrong:
happyn(go1,0,0,0)
If nothing is explicitly returned, the function will return None. Therefore, the correct way is:
return happyn(go1,0,0,0)
The same goes for all the other exit points in your function.
You are not returning the result of your recursive calls, ie return happyn(go1, 0, 0, 0). In Python, any function that ends without a return statement implicitly returns None.
This is not really a good place to use recursion; a simple while loop would suit better.
def sum_sq(i):
total = 0
while i:
total += (i % 10) ** 2
i //= 10
return total
def is_happy(i):
while i >= 10:
i = sum_sq(i)
return i in (1, 7)
def main():
i = int(raw_input("Please enter a positive integer: "))
if is_happy(i):
print("{} is a happy number.".format(i))
else:
print("{} is an unhappy number.".format(i))
if __name__=="__main__":
main()
I'm new to programming world, and I'm struggling with recursion.
This is my code, but I'm not sure why it doesn't work :(
enter_number = input("enter 'x' value: ")
def g(x):
if x == 0:
return 1
elif x == 1:
return 2
else:
return g(x−1) + g(x−3) + g(x−4)
print(g(enter_number))
thank you
Your g function doesn't handle inputs 2 and 3.
I have this code that should break once it fulfills a certain condition, ie when the isuniquestring(listofchar) function returns True, but sometimes it doesn't do that and it goes into an infinite loop. I tried printing the condition to check if there's something wrong with the condition, but even when the condition is printed true the function still continues running, I have no idea why.
one of the strings that throws up an infinite loop is 'thisisazoothisisapanda', so when I do getunrepeatedlist('thisisazoothisisapanda'), it goes into an infinite loop.
would be really grateful if someone could help
thanks!
Here's my code:
def getunrepeatedlist(listofchar):
for ch in listofchar:
if isrepeatedcharacter(ch,listofchar):
listofindex = checkrepeatedcharacters(ch,listofchar)
listofchar = stripclosertoends(listofindex,listofchar)
print (listofchar)
print (isuniquestring(listofchar))
if isuniquestring(listofchar):
return listofchar
#print (listofchar)
else:
getunrepeatedlist(listofchar)
return listofchar
just for reference, these are the functions I called
def isrepeatedcharacter(ch,list):
if list.count(ch) == 1 or list.count(ch) == 0:
return False
else:
return True
def checkrepeatedcharacters(ch,list):
listofindex=[]
for indexofchar in range(len(list)):
if list[indexofchar] == ch:
listofindex.append(indexofchar)
return listofindex
def stripclosertoends(listofindices,listofchar):
stringlength = len(listofchar)-1
if listofindices[0] > (stringlength-listofindices[-1]):
newstring = listofchar[:listofindices[-1]]
elif listofindices[0] < (stringlength-listofindices[-1]):
newstring = listofchar[listofindices[0]+1:]
elif listofindices[0] == (stringlength-listofindices[-1]):
beginningcount = 0
endcount = 0
for index in range(listofindices[0]):
if isrepeatedcharacter(listofchar[index],listofchar):
beginningcount += 1
for index in range(listofindices[-1]+1,len(listofchar)):
if isrepeatedcharacter(listofchar[index],listofchar):
endcount += 1
if beginningcount < endcount:
newstring = listofchar[:listofindices[-1]]
else:
#print (listofindices[0])
newstring = listofchar[listofindices[0]+1:]
#print (newstring)
return newstring
def isuniquestring(list):
if len(list) == len(set(list)):
return True
else:
return False
It may be due to the fact that you are changing listofchar in your for loop. Try cloning that variable to a new name and use that variable for manipulations and return the new variable.