This question already has an answer here:
Why Python recursive function returns None [duplicate]
(1 answer)
Closed 3 years ago.
I am trying to write a recursive function which takes an integer as its parameter and returns the number of pairs of numbers within the integer that sum to 10. For example, findPairs(28164730) would return 3 because 2+8=10, 6+4=10, and 7+3=10.
This is what my code looks like now:
def find(x):
x = str(x)
count = 0
if str((10 - int(x[0]))) in x:
count = count + 1
x = x[1:]
find(x)
elif len(x) > 1:
x = x[1:]
find(x)
return count
The problem I am having is that the function will always return that the count is 1 because I am calling it again for recursion and it is setting the count back to 0 instead of just adding 1 to the count every time a pair is found. Does anyone know how I can fix this?
Right now, your code isn't using the returned value of the recursive find call; it's just calling find(x). This will fix your problem:
def find(x):
x = str(x)
count = 0
if str((10 - int(x[0]))) in x:
# count = count + 1
x = x[1:]
count = 1 + find(x)
elif len(x) > 1:
x = x[1:]
count = find(x)
return count
One possible solution would be to simplify by e.g. not using recursion at all. See e.g. the following attempt:
def find(x):
x = str(x)
count = 0
for i in range(len(x)-1):
if str((10-int(x[i]))) in x[i+1:]:
count += 1
return count
Either have a separate function that declares count then calls find(), or set count as a global variable. I think the first method is preferable.
def get_count(x):
count = 0
find(str(x))
return count
Or something like that. Also if you use that method, make sure to remove the count = 0 from the original find function
Related
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
For educational purposes of understanding recursion I would like to solve the following problem: given a list of integers foo in which 0 is guaranteed, I would like to choose a number from that list randomly until either the random generator chooses 0 or until it works 100 times.
Iteratively speaking, my solution looks like this:
def num_random(foo):
nums = 0
x = math.inf
while nums < 100 and x != 0:
x = random.choice(foo)
nums += 1
return nums
My recursive version of the same function is this:
def count_random(foo, number):
x = random.choice(foo)
print("x = {0}".format(x)) # debug purposes
if x != 0 and number < 100:
count_random(foo, number + 1)
else:
return number
Initial call:
print(count_random([0, 1, 2, 3, 4, 5], 0))
The problem with the recursive solution is that it always returns None and I don't understand why. My reasoning: if the chosen number is not 0, we know that the number of integers in the next call will be the number of integers in the current call plus 1. If the randomly chosen integer is 0, we need to return the number of integers in the outer scope. However, my function always returns None.
Why does my function always return None and how do I fix it?
You are missing the return statement in your recursive call:
def count_random(foo, number):
x = random.choice(foo)
print("x = {0}".format(x)) # debug purposes
if x != 0 and number < 100:
return count_random(foo, number + 1)
else:
return number
I am new to python and trying to write a program to add all the numbers starting from 1 through n and print their sum. Can anyone please tell me what is wrong with my code. I am getting 1 as an output.
def problem1_3(num):
sum_= 0
num = int(num)
for i in range(1,num):
sum_ = sum_ + i
print(sum_)
i+=1
return(sum_)
You are returning the sum_ on the first iteration of the function. You want to finish the for loop, and only then return it. Read more about loops in python, they are based on indentation, unlike some other languages.
Two mistakes that you are making in your code:
1- You are incrementing i by +1 but you don't have to do this because python will automatically increment loop variable.
2- You are returning your sum_ variable inside for loop that's why you got 1 as an output.
def problem1_3(num):
sum_= 0
num = int(num)
for i in range(1,num+1):
sum_ = sum_ + i
#print(sum_)
# i+=1
return(sum_)
ans = problem1_3(5)
print(ans)
Output:
15
So you are returning inside your for loop, so it does not go to completion.
but if you would like an easier more concise way to write that function,
def problem1_3(num):
return sum(range(num)) #for up to, but not including num
or
def problem1_3(num):
return sum(range(num+1)) #for up to, AND including num
Since you already have the range function, range produces a list of numbers. So range(5) is [0,1,2,3,4]
and summing them will get you 1+2+3+4
it's just a shorter way of doing the same thing.
If you don't have to use for loop, it's better to use recursion.
def problem1_3(num : int) -> int:
if num == 1:
return 1
else:
return num + problem1_3(num-1)
# 5 + problem1_3(4)
# 5 + 4 + problem1_3(3)
# 5 + 4 + 3 + problem1_3(2)
# 5 + 4 + 3 + 2 + problem1_3(1)
# 5 + 4 + 3 + 2 + 1
.
if you have to use loops.
your problem is when you are returning sum_. you should to finish your loop and after all, Outside the loop, return the sum:
def problem1_3(num : int) -> int:
sum_ = 0
for i in range(1, num+1):
sum_ += i
return (sum_)
Write a function named "counting" that takes a list of numbers as a parameter and returns the number of values in the input that are between 29.88 and 48.05 not including these end points. (My code below)
def counting(number):
sum = 0
for x in number:
if (29.88 < x < 48.05):
sum = sum + x
return sum
How do I return the number of values in the input instead of the first number of an input?
your return statement is indented too deep; you should return it after the for loop. also sum is not a good name as it is a built-in function that you overwrite.
and you should add 1 to the sum (you are counting) and not x itself.
you could also try this using the built-in function sum:
def counting(number):
return sum(29.88 < x < 48.05 for x in number)
(this is actually short for sum(1 for x in number if 29.88 < x < 48.05) and works because True is basically 1 and False is basically 0).
Or to be similar to yours:
def counting(number):
c = 0
for x in number:
if 29.88 < x < 48.05:
c += 1
return c
Or can do one-liner, len:
def counting(number):
return len([29.88 < x < 48.05 for x in number])
You could also use filter() on your list to keep only elements that the given function evaluates to true.
def counting(number):
return len(list(filter(lambda x: 29.88 < x < 48.05, number)))
I am puzzled by this python code:
def Counting(x):
if x <= 0:
return x
else:
print(x)
x = x-1
Counting(x)
print("count up",x)
print(Counting(10))
#
The out put is:
10
9
8
7
6
5
4
3
2
1
count up 0
count up 1
count up 2
count up 3
count up 4
count up 5
count up 6
count up 7
count up 8
count up 9
None
What I don't understand is why the return value is None? Shouldn't I get the value of x? Is it possible to have a return value of my choice?
Thank you
What I don't understand is why the return value is None? Shouldn't I
get the value of x? Is it possible to have a return value of my
choice?
If a method doesn't have a explicit return python returns None. That's standard.
in line no 7 Counting(x) you are not capturing / returning what is returned. So when x is 0 and if x <= 0: returns 0 you ignore that.
you go to the print("count up", x) which prints 0.
now the method returns None which goes to the recursion caller. And finally comes back to the original method call as None. I hope it's clear now.
If you change your code as.
def Counting(x):
if x <= 0:
return x
else:
print(x)
x = x-1
Counting(x)
print("count up",x)
return x
print(Counting(10)) # This will return 9
# here Counting(10) calls Counting(9) but ignores what it returns
# and Counting(9) calls Counting(8) but ignores what it returns
# Counting(10) finally returns x which is 9
On the other hand if you want to preserve the last value then that should be returned.
def Counting(x):
if x <= 0:
return x
else:
print(x)
x = x-1
return Counting(x)
print("count up", x) # this line is dead code.
Counting(10) # This will return 0
# here Counting(10) returns what Counting(9) returns.
# and Counting(9) returns what Counting(8) returns and so on....
# finally returning Counting(0)
Is it possible to have a return value of my choice?
Yes, Depending on what value you want to return from what state of the recursion you can get what you want. It's programming. Anything that you can logically explain can be done with programming :)
In the function, you are not returning anything.
Update the function as follows
Code
def Counting(x):
result = None
if x <= 0:
return x
else:
print(x)
x = x-1
result = Counting(x)
print("count up",x)
return result
print Counting(10)
I am learning python, and trying to use some ternary operators.
I am trying to make the function below using a ternary:
def array_count9(nums):
count = 0
for i in nums:
if i == 9:
count += 1
return count
I have tried:
def array_count9(nums):
count = 0
count += 1 if i == 9 for i in nums else pass
return count
which threw a SyntaxError, then after looking around I found this and changed my code for what I believed was better ordering:
def array_count9(nums):
count = 0
count += 1 if i == 9 else pass for i in nums
return count
Still receiving SyntaxError which is pointing at the for. I've tried using parentheses in different places too.
I have looked around and there are other related threads such as this and this, which resulted in me trying this:
def array_count9(nums):
count = 0
count += 1 if i == 9 else count == count for i in nums
return count
I've also tried other resources by searching Google, but I can't quite work it out. Please teach me.
Thanks
I think this is the most idiomatic way to write the code:
def array_count9(nums):
return sum(num == 9 for num in nums)
But you could also do this if you want to use the if/else construct:
def array_count9(nums):
return sum(1 if num == 9 else 0 for num in nums)
The blueprint for a ternary operator is:
condition_is_true if condition else condition_is_false
The statement where the syntax error occurs is at
count += 1 if i == 9 else pass for i in nums
ie count += 1 does not meet the blueprint specification, because condition_is_true should not need to be evaluated.
Okay so using your examples was a little tricky because a ternary operator can't include anything outside it's specific blueprint; that being the for loop you're trying to pass with it.
count += 1 if i == 9 for i in nums else pass
So after fiddling around with the code:
def array_count9(nums):
count = 0
count += 1 if i == 9 for i in nums else pass
return count
I was sure you were looking for something that works involving ternary operators and that for loop. So keeping your goal in mind, this is what I came up with.
numss = [3,6,9,10,35]
def count9(nums):
count = 0
a = count + 1
for i in nums:
count = (a if i == 9 else count) #This being the ternary operator
return count
print (count9(numss))
Hope this helps.