This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
I would write a recursive function that take a list of number as argument and return maximum element of the list. I don't want to use max() function.
a = [2,1,3,5]
def f(a, m=0):
if m<a[0]:
m = a[0]
if len(a) == 1:
return m
else:
f(a[1:])
print(f(a))
but it returns None! how can I fix it?
You should define m in your else statement and add a return in it:
a = [2,1,3,5]
def f(a, m=0):
if m<a[0]:
m = a[0]
if len(a) == 1:
return m
else:
m = f(a[1:], m)
return m
print(f(a))
Related
This question already has answers here:
Python Bool and int comparison and indexing on list with boolean values
(4 answers)
Closed 1 year ago.
I was doing a leetcode problem and while reviewing a solution I was quite dumbfounded by a certain line in the solution. The leetcode problem in particular is https://leetcode.com/problems/binary-subarrays-with-sum/
The solution:
class Solution:
def numSubarraysWithSum(self, A: List[int], S: int) -> int:
res = 0
sm = 0
sums = collections.defaultdict(int)
for a in A:
sm += a
res += sums[sm - S] + (sm == S)
sums[sm] += 1
return res
I understand everything that is going on besides this line:
res += sums[sm - S] + (sm == S)
I have never seen a conditional in an addition operation before.
Conditional expressions evaluate to booleans, which in Python are just subtypes of int. False is 0, True is 1, so adding sm == S is the same as adding 1 if sm equals S or adding 0 otherwise.
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 4 years ago.
I had trouble understanding why this function returns None:
def rem(x, a):
"""
x: a non-negative integer argument
a: a positive integer argument
returns: integer, the remainder when x is divided by a.
"""
if x == a:
return 0
elif x < a:
return x
else:
rem(x-a, a)
rem(7, 5)
I then realized that the last line in the function should be:
return rem(x-a, a)
I am still unsure as to what really happens in the first one. It looks like there are 2 seperate function calls, one returning 2 and the other None... any help?
All python function returns None if it doesn't terminate by a return statement. In your case, you successfully called the recursion but you discarded the result in the else part. And after the if-block, the default return None is implicitly executed.
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 4 years ago.
I have the following function written in python 3
def nullstelle(f,a,b,counter=0,TOL=10 ** -4):
counter = counter + 1
if counter <= 100:
g = f((a + b)/2)
if f(a) * g <= 0:
b = (a + b)/2
else:
a = (a + b)/2
if abs(a-b) <= 2*TOL:
return (a,b)
else:
nullstelle(f,a,b,counter,TOL)
else:
return (a,b)
my problem is, that for the input
def f(x):
return x ** 3 -2
nullstelle(f,0,3)
it does not return anything. I really do not understand how this is possibly.
Im sorry if this looks like a trivial question to you guys, but programming is absolutely not my main field of interest and I know nearly nothing about it (yet).
I feel like this is a duplicate, but couldn't find one quickly. The problem is that you're not returning the result of your recursive call, so you get None if you have to recurse. Change that line to:
return nullstelle(f,a,b,counter,TOL)
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 7 months ago.
I tried to write a program to return he max number, however it returns none. I look into similar questions but I did't find the answer.
def findMax(alist):
if len(alist) == 1:
return alist[0]
else:
if alist[0] > alist[1]:
alist[1] = alist[0]
findMax(alist[1:])
def main():
a = [1,3,4,2,6,7,9,12,3,20,4,32,5,6,9,10]
print(findMax(a))
main()
Recursive functions need to return something under all conditions, you don't return anything under the else condition. Try return findMax(alist[1:]).
This question already has answers here:
Check if a number is a perfect square
(25 answers)
Closed 9 years ago.
I wrote this python function which takes a list as a parameter and determines which elements of the list are perfect squares and then returns a new list of just those select elements.
Here is my function:
def square(n):
return n**2
def perfectSquares1(L):
import math
m=max(L)
for n in L:
if type(n) is int and n>0:
Result=map(square,range(1,math.floor(math.sqrt(m))))
L1=list(Result)
L2=list(set(L).intersection(set(L1)))
return L2
But now I'm trying to re-work it a little: I want to write a one-line Boolean function that takes n as a parameter and returns True if n is a perfect square and returns false otherwise.
Any advice? I can't figure out a way to make it only one line.
lambda n: math.sqrt(n) % 1 == 0
You can do:
import math
def perfect_sq(n):
return n == int(math.sqrt(n)) * int(math.sqrt(n))
Or you can use:
import math
def perfect_sq(n):
return n == int(math.sqrt(n)) ** 2
Could use the modulo operator:
>>> def perfectsquare(n):
... return not n % n**0.5
...
>>> perfectsquare(36)
True
>>> perfectsquare(37)
False
>>> perfectsquare(25)
True
>>> perfectsquare(4215378*4215378)
True