Recursion - Python question, return value question [duplicate] - python

This question already has answers here:
Recursive function to calculate sum of 1 to n?
(7 answers)
Closed 20 days ago.
**I am having a problem with solving the question below.
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. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15.**
def sum_positive_numbers(n):
return 0
print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

Remember always to add a breaking condition. The zero evaluation in this case
def sum_positive_numbers(n):
if n == 0:
return n
return n + sum_positive_numbers(n - 1)

def sum_positive_numbers(n):
# The base case is n being smaller than 1
if n < 1:
return n
return n + sum_positive_numbers(n - 1)
# What got me was n - 1. I was using + until I went to the below website to see visualize it
print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15
This is the website I use to visualize code that helps me solve the problem(s). It forces me not to just get an answer from google search, but work through each error, and learn as I go:
Python Visualizer

My best suggestion
def sum_positive_numbers(n):
if n < 1:
return 0
return n + sum_positive_numbers(n-1)
print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

Related

how can my code work for small lists but breaks on bigger lists?

So i am trying to learn python and i am going through codewars practice problems, this one has had my stumped so i have come here for help.
promtp:
You get an array of numbers, return the sum of all of the positives
ones.
Example [1,-4,7,12] => 1 + 7 + 12 = 20
Note: if there is nothing to sum, the sum is default to 0.
my code:
def positive_sum(arr):
for item in arr:
if item**3 < 0:
arr.remove(item)
if sum(arr) > 0:
ans = sum(arr)
return ans
return 0
passed all tests except for the 40 random ones
any help would be awesome
thanks :P

Project Euler's Multiples of 3 and 5 - Problem - Python [duplicate]

This question already has answers here:
Why is my Project Euler problem #1 code returning the wrong result?
(3 answers)
Closed 1 year ago.
I just tried to solve Problem 1 in Project Euler but I don't understand why this code is not working and the output answer is wrong.QUESTION - If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.Find the sum of all the multiples of 3 or 5 below 1000.
correct answer = 233168My output =266333
a = 0
for x in range(0,1000,3):
a = a + x
for x in range(0,1000,5):
a = a + x
print(a)
ProjectEuler #1
def f(x):
n1, n2, n3 = x//3, x//5, x//15
return 3*(n1)*(n1+1)//2+5*(n2)*(n2+1)//2-15*(n3)*(n3+1)//2
for i in range(int(input())):
print(f(int(input())-1))
Here x//3 gives int(x/3) similarly for x//5 and x//15
As LCM(3,5)=15
Σi = n(n+1)/2
answer= sum of multiples of 3 + sum of multiples of 5 - sum of multiples of 15.
corresponds to a solution of ProjectEulerProblem #1
Note: My intention of sharing codes on StackOverflow is to let people know that a given problem could be solved in many ways.
As it's always a difficult for one to pass all cases due to timeError.
Do not use as an answer but learn.
You are overcounting the multiples of 15. One way to fix this would be to have just one loop which checks if the number is a multiple of 3 or 5.
solution = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
solution += i
print(solution)
The comment by Devesh Kumar Singh solves the question:
Because you count the multiples of both 3 and 5 twice, e.g. 15 . Add a loop for subtracting such values e.g. for x in range(0,1000,15): a = a - x

Is there any way to create a python function to finding perfect numbers between 1 to 1000 with using double for loop? [duplicate]

This question already has answers here:
Algorithm to check if a number if a perfect number
(4 answers)
Closed 3 years ago.
I am trying to find perfect number with using a function in python but I want to do this without using any parameters in function and using double for loop.
I wonder that if it is possible. My example code is under the below. I would appreciate it if you help.
def perfectnumber():
sum = 0
#These numbers going to be our numbers which will be divided.
for j in range(1,1001):
#These numbers going to be our numbers which will divide first loop numbers(j)
for k in range(1,1001):
import math
def divisors(n):
divs = [1]
for i in range(2,int(math.sqrt(n))+1):
if n%i == 0:
divs.extend([i,n/i])
return list(set(divs))
def is_perfect_number(n):
return n == sum(divisors(n))
res = []
for i in range(2,1001):
if is_perfect_number(i):
res.append(i)
print(res)

Algorithm: Factorize a integer X to get as many distinct positive integers(Y1...Yk) as possible so that (Y1+1)(Y2+1)...(Yk+1) = X

I recently met a algorithm question in open.kattis.com.
The question's link is https://open.kattis.com/problems/listgame2.
Basically, it is a question ask the players to factorize a integer X (10^3 <= X <= 10^15) to get as many distinct positive integers (Y1,...,Yk) as possible such that (Y1+1)(Y2+1)⋯(Yk+1) = X.
I already came up with a solution using Python3, which does pass several test cases but failed one of them:MyStatus
My code is:
def minFactor(n, start):
maxFactor = round(n**0.5)
for i in range(start, maxFactor+1):
if n % i == 0:
return i
return n
def distinctFactors(n):
curMaxFactor = 1
factors = []
while n > 1:
curMaxFactor = minFactor(n, curMaxFactor+1)
n //= curMaxFactor
factors.append(curMaxFactor)
# This is for the situation where the given number is the square of a prime number
# For example, when the input is 4, the returned factors would be [2,2] instead of [4]
# The if statement below are used to fix this flaw
# And since the question only requires the length of the result, deleting the last factor when repeat do works in my opinion
if factors[-1] in factors[:-1]:
del factors[-1]
return factors
num = int(input())
print(len(distinctFactors(num)))
Specifically, my idea inside the above code is quite simple. For example, when the given input is 36, I run the minFactor function to find that the minimum factor of 36 is 2 (1 is ignored in this case). Then, I get 18 by doing 36/2 and invoke minFactor(18,3) since 2 is no more distinct so I start to find the minimum factor of 18 by 3. And it is 3 clearly, so I get 6 by doing 18/3 in function distinctFactors and invoke minFactor(6,4), since 4 is smaller than sqrt(6) or 6**0.5 so 6 itself will be returned and I finally get the list factors as [2,3,6], which is correct.
I have scrutinised my code and algorithm for hours but I still cannot figure out why I failed the test case, could anyone help me with my dilemma??? Waiting for reply.
Consider the number 2**6.11**5.
Your algorithm will find 5 factors:
2
2**2
2**3
11
11**2
(11**2 this will be discarded as it is a repeat)
A 6 length answer is:
2
2**2
11
11**2
2*11
2**2*11

Summation Of Primes Below a Given Number in Python [duplicate]

This question already has answers here:
Fastest way to list all primes below N
(39 answers)
Closed 6 years ago.
I have written the following block of code to calculate the sum of all the primes below a certain number-2 000 000 in this case to be precise, however it takes quite some time to execute; 20 second:
def summation_of_primes_below_n(n):
list = []
sum = 0
for i in range(2, n):
if checks_if_prime(i) == True:
list.append(i)
return list
for j in list:
sum = sum + j
return sum
def checks_if_prime(n):
if n == 2:
return True
import math
for i in range(2, math.ceil(math.sqrt(n))+1):
if n%i == 0:
return False
elif i == math.ceil(math.sqrt(n)):
return True
print(summation_of_primes_below_n(2000000))
So I was wondering if there was a way to make my code more efficient. I would greatly appreciate suitable advice on the same. Also, I would prefer that you give more basic solutions since I am a beginner and provide the logic for the same. Thanks a lot!
You can start off by implementing some better algorithm. For eg: Sieve of Eratosthenes
Or if you are happy with your current logic, then few optimizations that can help:
Check only for odd numbers:
for i in range(3, n, 2):
Check only for numbers of form 6n+1, 6n+5
You don't need to do this check : elif i == math.ceil(math.sqrt(n)): for each iteration. If the control reached beyond the loop then the number is prime
You can convert your check_prime to generator pattern. Could save some redundancy and possibly improve locality of reference.

Categories

Resources