This is what my code needs to do:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
Test.it("Basic tests")
Test.assert_equals(persistence(39), 3)
Test.assert_equals(persistence(4), 0)
Test.assert_equals(persistence(25), 2)
Test.assert_equals(persistence(999), 4)
This is a Codewars challenge. I can test assert samples individually but not all at once. Codewars need to be able to run all its test samples all at once. I need to find a way to reset count after completing one test sample without resetting count during the recursive function.
count = 0
def persistence(n):
# your code
global count
#def recursion(result):
number_str = str(n)
ints = [int(i) for i in number_str if i != '0']
result = 1
for j in ints:
result = result * j
if result >= 10:
print(ints,"\n\n------------------------------------------")
count += 1
print(count)
print(result)
return persistence(result)
else:
if count > 0:
count += 1
return count
else:
return count
This is the code I came up with. I need my function to run all four tests at once. My function can recursively render one test at a time, but not all tests at once. I need to figure out how to reset count after each test sample assertion.
Your recursive function should not need a global variable. You can pass counts as a parameter instead, with a default value to handle the public API case where it's not passed in:
def persistence(n, count=0):
...
# everything is the same up until the recursion
return persistence(result, count)
You could simplify the code a bit by just doing inline addition rather than using += statements on count, if you want, but it won't change the behavior of the code.
I'd also note that since your function is tail recursive, you could pretty easily replace the recursion with a loop. I think something like this might do it:
def persistance(n):
count = 0
while n >= 10:
count += 1
ints = [int(i) for i in str(n) if i != '0']
n = 1
for i in ints:
n *= i
return count
You can just pass along the count down the recursive call, like this:
count = 0
def persistence(n, count):
# ..
# update count
# ..
return persistence(result, count)
# ...
return count
or if you cant change the signature of persistance, use an auxiliary function, which is very common in functional programming.
def persistance(n):
return persistance_aux(n, 0)
def persistance_aux(n, count):
# ....
I am writing a filter function such that when I insert my wave number, which is a list of numbers, the filter_wave_num function will be executed n times to change the wave number.
However, it doesnt seem to work, it repeats the output only once, when I want it to do it n times. Will appreciate your help in this.
def filter_wave_num(wave):
new_wave = []
for i in range(len(wave)):
if i == 0:
new_wave.append(int(wave[i]*0.6 + wave[i+1]*0.2))
elif i == len(wave)-1:
new_wave.append(int(wave[i-1]*0.2 + wave[i]*0.6))
else:
new_wave.append(int(wave[i-1]*0.2 + wave[i]*0.6 + wave[i+1]*0.2))
return new_wave
def filter_wave(wave,n):
for i in range(n):
filter_wave_num(wave)
return filter_wave_num(wave)
wave = [600, 3200, 7600, 13400, 18400, 22600, 24400]
# each element inside the list has to be changed n times
The filter_wave_num function works.
If you need to use it recursively n times (each time on the result obtained the previous time) modify your second function like this:
def filter_wave(wave, n):
for _ in range(n):
wave = filter_wave_num(wave)
return wave
The function you have written creates each time a new list, but you don't return the result each iteration and it's lost.
You do call your function n times, but you are calling it with the same input so you get the same output after all iterations.
Here's what you need to do:
Notice that I changed the name of 'i' to '_', this is a convention indicates we don't need to use the value of this variable
def filter_wave(wave,n):
result = wave
for _ in range(n):
result = filter_wave_num(result)
return result
Store all the iteration results in a list and then return it:
def filter_wave(wave,n):
result = []
for i in range(n):
wave = filter_wave_num(wave)
result.append(wave)
return result
How to use a recursive function to count the sum of the positive elements of a list?
I'm not sure how to go about it? I know how to do it without using a recursive function:
sum=0
for i in range(len(List)):
if List[i]>0:
sum=sum+List[i]
You need to divide the problem, into a 'current' step and the remainder to be handled by recursion. You also need to determine when to end the recursion.
The current step is determining what to sum in this step. That's the current value, or 0 if the value is smaller than 0.
The remainder is summing the current value to the recursive call for the rest of the list.
You end the recursion when an empty list is passed in; the sum of an empty list is always 0.
In the end, that gives:
def recursive_positive_sum(l):
# end recursion for an empty list
if not l:
return 0
# get a value
value = l[0]
if value < 0:
value = 0
# recurse, sum the value with the remainder
return value + recursive_positive_sum(l[1:])
We can use a max() to get the value or 0 and inline that:
def recursive_positive_sum(l):
if not l:
return 0
return max(l[0], 0) + recursive_positive_sum(l[1:])
Demo:
>>> def recursive_positive_sum(l):
... if not l:
... return 0
... return max(l[0], 0) + recursive_positive_sum(l[1:])
...
>>> recursive_positive_sum([])
0
>>> recursive_positive_sum([-42])
0
>>> recursive_positive_sum([-42, 10, -81, 100])
110
this can be one wy of doing it.
def fun(l):
if len(l)==0:
return 0
num = l.pop()
if num > 0:
return num + fun(l)
return fun(l)
but be careful. this function destroys the list that has benn passed to it. so make a copy of your list before passing it to the function or:
def fun(l):
if len(l)==0:
return 0
if len(l)==1:
return l[0]
num = l[0]
if num > 0:
return num + fun(l[1:])
return fun(l[1:])
Implement the sum_positive_numbers function, as a recursive function that returns the sum of all positive numbers between the number n received and 1. [solved]
def sum_positive_numbers(n):
if n <= 1:
return n
return n + sum_positive_numbers(n-1)
print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15
As a new learner without recursion i would write a few more lines of code as follows. This is for the problem of adding the numbers till n.
def sum_positive_numbers(n):
# Initialise variables
sum=0
i=1
while i<n+1:
sum=sum+i
i+=1
return sum
I am calculating the prime factors for all numbers contained in a list numbers. They are returned from my helper-method primefactors_of_number as a list. I want to keep track of all of them (e.g. in a list all_factors and have them in the correct quantity).
As an example, for the input
[12,16,17]
find_all_primefactors should return
[2,2,3,2,2,17]
in any order.
The point that makes me problems is to update all_factors to contain 2 only four times.
Here is my code so far:
def find_all_primefactors(list_with_numbers):
prime_factors = []
all_factors = []
for number in list_with_numbers:
prime_factors = primefactors_of_number(number)
# missing part:
# Update all_factors in a way that it contains all elements of prime_factors at least in the same quantity
return all_factors
def primefactors_of_number(number):
'''
Returns all primefactors of the specified number as a list
'''
i=2
prime_factors=[]
while i<=number:
while number%i==0:
prime_factors.append(i)
number/=i
i+=1
return prime_factors
I think I could solve this with a lot of looping and temporary values, but I assume there is probably a more elegant solution.
Another approach would be to first compute the least common multiple of the list of numbers, and then factorize that single number:
from fractions import gcd
def find_all_primefactors(list_with_numbers):
lcm = reduce(lambda a, b: a * b / gcd(a, b), list_with_numbers)
return primefactors_of_number(lcm)
I was thinking of something like:
from collections import Counter
def find_all_primefactors(list_with_numbers):
all_factors = {}
for number in list_with_numbers:
all_factors |= Counter(primefactors_of_number(number))
return all_factors
Here's a suggestion how you could modify your first function:
def find_all_primefactors(list_with_numbers):
all_factors = []
for number in list_with_numbers:
prime_factors = primefactors_of_number(number)
for x in set(prime_factors): # loop over factors without duplicates
in_all = all_factors.count(x) # how many x are already in all_factors
in_p = prime_factors.count(x) # how many x are in prime_factors
diff = in_p - in_all
all_factors.extend([x]*diff) # extend all_factors based on difference
# note that [x]*diff is [] for diff <= 0
return all_factors
primefactors_of_number stays the same. Output for
print(find_all_primefactors([12,16,17]))
is
[2, 2, 3, 2, 2, 17]
I'm trying to do a lab work from the textbook Zelle Python Programming
The question asked me to "write and test a recursive function max() to find the largest number in a list. The max is the larger of the first item and the max of all the other items." I don't quite understand the question from the textbook.
def Max(list):
if len(list) <= 1:
else:
return list[0]
else:
m = Max(list[1:])
return m if m > list[0] else list[0]
def main():
list = eval(raw_input(" please enter a list of numbers: "))
print("the largest number is: ", Max(list))
main()
Or maybe I'm suppose to open a txt file with numbers in it and then use recursive?
I believe recursive works like this
def function()
> if something:
>>return 0
>else:
>>return function()
Your understanding of how recursion works seems fine.
Your if-block is messed up, you have two elses to one if and the alignment is out. You need to remove your first else and un-indent everything below the if one level. eg:
def Max(list):
if len(list) == 1:
return list[0]
else:
m = Max(list[1:])
return m if m > list[0] else list[0]
def main():
list = eval(raw_input(" please enter a list of numbers: "))
print("the largest number is: ", Max(list))
main()
I post a different solution approach of the problem. Most of the answers manipulate the list using the slice operator in each recursive call. By the time the exercise does not provide a strict function prototype to be used, I also pass as function parameter the length of the list.
Suppose that we try to find and return the maximum element from a sequence S, of n elements.
Function prototype: Max(S, n)
Base case: If S contains only one item, return it. (Obviously the only item in the sequence is the max one.)
Recur: If not the base case, call Max each time for one less item, that is call Max(S, n-1). We then store the returning value to a variable called previous that indicate the previous element from the sequence and check that value with the next element in the sequence, which is the right most element in the current recursive call, and return the max of these values.
A recursion trace of the above procedure is given in the following figure. Suppose we try to find the max from a list that contains [5, 10, 20, 11, 3].
Note: To help you further, keep in mind that we recursively iterate the list from the right most element to the left most one.
Finally here is the working code:
def find_max_recursively(S, n):
"""Find the maximum element in a sequence S, of n elements."""
if n == 1: # reached the left most item
return S[n-1]
else:
previous = find_max_recursively(S, n-1)
current = S[n-1]
if previous > current:
return previous
else:
return current
if __name__ == '__main__':
print(find_max_recursively([5, 10, 20, 11, 3], 5))
Note: The recursive implementation will work by default only with sequences of 1000 most elements.
To combat against infinite recursions, the designers of Python made an
intentional decision to limit the overall number of function
activations that can be simultaneously active. The precise value of
this limit depends upon the Python distribution, but a typical default
value is 1000. If this limit is reached, the Python interpreter
raises a RuntimeError with a message, maximum recursion depth exceeded.
Michael T. Goodrich (2013), Data Structures and Algorithms in Python, Wiley
To change the default value do:
import sys
sys.setrecursionlimit(1000000)
here is one more approach to solve above problem
def maximum(L):
if len(L) == 1:
return L[0]
else:
return max(L[0],maximum(L[1:]))
so example input and output:
L= [2,4,6,23,1,46]
print maximum(L)
produces
46
The basic approach is this.
If the list contains only a single element, that element is the max. Return it immediately.
Otherwise, the list contains multiple elements. Either the first element in the list is the maximum, or it is not.
The maximum of the first element is simply the first element in the list.
Recursively call Max on the rest (all but first element) to find the maximum of those elements.
Compare the results from step 3 and 4. The result is the number that is greater. Return it.
Right now you have some syntax errors. For example, you have two else clauses for a single if, and the indentation looks funny. You can only have one else for an if block. But if you follow these instructions, you should have a working algorithm.
def Max(lis,maxx=-float("inf")):
if len(lis) == 1: #only one element in lis
return maxx if maxx>lis[0] else lis[0] #return lis[0] if it's greater than maxx
else:
m=lis[0] if lis[0]>maxx else maxx # m = max(lis[0],maxx)
return Max(lis[1:],m) #call Max with lis[1:] and pass 'm' too
print Max([1,2,39,4,5,6,7,8]) #prints 39
print Max([1,2,3,4,5,6,7,8]) #prints 8
These solutions fail after certain list size.
This is a better version:
def maximum2(a, n):
if n == 1:
return a[0]
x = maximum2(a[n//2:], n - n//2)
return x if x > a[0] else a[0]
def maximum(a):
return maximum2(a, len(a))
maximum(range(99999))
>>> 99998
One simple way would be to sort the list first then use indexing.
Here's a function that would work:
a = [1,233,12,34]
def find_max(a):
return sorted(a)[-1]
def find_max(my_list, max):
if len(my_list) <= 1:
return max
else:
if my_list[0] > max:
return find_max(my_list[1:], my_list[0])
else:
return find_max(my_list[1:], max)
if __name__ == '__main__':
my_list = [1, 5, 16, 9, 20, 40, 5]
print(find_max(my_list, my_list[0]))
def find_max(arr):
"""find maximum number in array by recursion"""
if arr == []: # if its an empty array
return 0
if len(arr) == 1: # if array has only one element
return arr[0]
else: # get max of first item compared to other items recursively
return max(arr[0], find_max(arr[1:])) # 1: means all other excluding 0th element
def main():
print(find_max([2,3,5,6,7,1])) # will print max - 7
if __name__ == "__main__":
main()
You can also do it in this way:
def maximum(data, start, stop):
if start >= stop:
return data[start]
else:
if data[start] >= data[stop - 1]:
return maximum(data, start, stop - 1)
else:
return maximum(data, start + 1, stop)
def recursiveMax(a):
if len(a) == 1:
return a[0]
else:
return a[0] if a[0] > recursiveMax(a[1:]) else recursiveMax(a[1:])
Test:
print(recursiveMax([1, 2, 15, 6, 3, 2, 9]))
print(recursiveMax([98, 2, 1, 1, 1, 1, ]))
TLDR; This code will also work when the list passed to the function is empty!
#jam's answer is amazing. However, I found some problems with the conditions, I think #Blender was hinting at it.
That code will fail in the case when the list passed to the function is empty. There are two base cases:
When the list is empty -> return None
When the list has one item -> return list[0]
And then the recursive case ... to reduce any other case into the base case.
def recursive_max(arr):
if len(arr) == 0:
return None
elif len(arr) == 1:
return arr[0]
else:
maxItem = recursive_max(arr[1:])
return maxItem if maxItem > arr[0] else arr[0]
Here is my answer, with a one line of code :))
def max_value(n_list):
return n_list[0] if len(n_list) == 1 else max(n_list[0], max_value(n_list[1:]))
def getMaxNumber(numbers):
return 'N.A' if len(numbers) == 0 else max(numbers)