So I have the code
def formula(n):
while(n < 11):
answera = 15/(-4)** n
print(answera)
n = n + 1
formula(1)
How can I add the outputs in condescending order?
For example,
first_output = (the output of n = 1)
second_output = (the output of n = 1) + (the output of n = 2)
third_output = (the output of n = 1) + (the output of n = 2) + (the output of n = 3)
and so on..
you need to define the variable answera outside the while loop, so that its shope should exists outside the loop , so that when you return the value the fully updated value can be returned. Something like this.
def formula(n):
answera = 0
while(n < 11):
answera += 15/(-4)** n
print(answera)
n = n + 1
print(answera)
formula(1)
Now it should give you the right result.
def formula(n):
while(n < 11):
answera += 15/(-4)** n
print(answera)
n = n + 1
The idea is that you will need to accumlate the value of 15/(-4)**n in one of the variables.. (here the answera) and keep printing it out.
I hope this answers your question.
There's some ambiguity in your question; do you want the sum of 'answera', or the sum of 'formula'?
If 'answera', then you can just replace "print" with "yield" and call "sum":
def formula(n):
while(n < 11):
answera += 15/(-4)** n
yield answera
n = n + 1
sum(formula(2))
This makes 'formula' a generator, and "sum" will iterate that generator until it's exhausted.
If you want the sum of multiple 'formula' calls, then follow the KISS principle, and wrap your function with another function:
# assuming that 'formula' is a generator like above
def mega_formula(iterations):
total = []
for i in range(1, iterations + 1): # b/c range indexs from zero
total.append(sum(formula(i))
return sum(total)
Related
I need to write a short program that asks for positive integer, reads the number and then prints results of operations by both functions.
I've already written both fuctions which look like this:
def sumdigits(n):
sum = 0
while (n != 0):
sum = sum + (n % 10)
n = n//10
return sum
n = int(input("enternumber: "))
print(sumdigits(n))
def sumdigits(no):
return 0 if no == 0 else int(no % 10) + sumdigits(int(no / 10))
n = int(input("enternumber: "))
print(sumdigits(n))
The thing that I struggle with is merging these two together in order to make 1 general complex function that will show results of both functions.
One option is to use inner functions. For example:
def sumdigits(n):
def loop(n):
sum = 0
while (n != 0):
sum = sum + (n % 10)
n = n//10
return sum
def recurse(n):
return 0 if n == 0 else int(n % 10) + recurse(int(n / 10))
return loop(n), recurse(n)
n = int(input("enternumber: "))
print(sumdigits(n))
I know how to check if the number can be represented as the sum of two squares with a brute-force approach.
def sumSquare( n) :
i = 1
while i * i <= n :
j = 1
while(j * j <= n) :
if (i * i + j * j == n) :
print(i, "^2 + ", j , "^2" )
return True
j = j + 1
i = i + 1
return False
But how to do it for n distinct positive integers. So the question would be:
Function which checks if the number can be written as sum of 'n' different squares
I have some examples.
For e.g.
is_sum_of_squares(18, 2) would be false because 18 can be written as the sum of two squares (3^2 + 3^2) but they are not distinct.
(38,3) would be true because 5^2+3^2+2^2 = 38 and 5!=3!=2.
I can't extend the if condition for more values. I think it could be done with recursion, but I have problems with it.
I found this function very useful since it finds the number of squares the number can be split into.
def findMinSquares(n):
T = [0] * (n + 1)
for i in range(n + 1):
T[i] = i
j = 1
while j * j <= i:
T[i] = min(T[i], 1 + T[i - j * j])
j += 1
return T[n]
But again I can't do it with recursion. Sadly I can't wrap my head around it. We started learning it a few weeks ago (I am in high school) and it is so different from the iterative approach.
Recursive approach:
def is_sum_of_squares(x, n, used=None):
x_sqrt = int(x**0.5)
if n == 1:
if x_sqrt**2 == x:
return used.union([x_sqrt])
return None
used = used or set()
for i in set(range(max(used, default=0)+1, int((x/n)**0.5))):
squares = is_sum_of_squares(x-i**2, n-1, used.union([i]))
if squares:
return squares
return None
Quite a compelling exercise. I have attempted solving it using recursion in a form of backtracking. Start with an empty list, run a for loop to add numbers to it from 1 to max feasible (square root of target number) and for each added number continue with recursion. Once the list reaches the required size n, validate the result. If the result is incorrect, backtrack by removing the last number.
Not sure if it is 100% correct though. In terms of speed, I tried it on the (1000,13) input and the process finished reasonably fast (3-4s).
def is_sum_of_squares(num, count):
max_num = int(num ** 0.5)
return backtrack([], num, max_num, count)
def backtrack(candidates, target, max_num, count):
"""
candidates = list of ints of max length <count>
target = sum of squares of <count> nonidentical numbers
max_num = square root of target, rounded
count = desired size of candidates list
"""
result_num = sum([x * x for x in candidates]) # calculate sum of squares
if result_num > target: # if sum exceeded target number stop recursion
return False
if len(candidates) == count: # if candidates reach desired length, check if result is valid and return result
result = result_num == target
if result: # print for result sense check, can be removed
print("Found: ", candidates)
return result
for i in range(1, max_num + 1): # cycle from 1 to max feasible number
if candidates and i <= candidates[-1]:
# for non empty list, skip numbers smaller than the last number.
# allow only ascending order to eliminate duplicates
continue
candidates.append(i) # add number to list
if backtrack(candidates, target, max_num, count): # next recursion
return True
candidates.pop() # if combination was not valid then backtrack and remove the last number
return False
assert(is_sum_of_squares(38, 3))
assert(is_sum_of_squares(30, 3))
assert(is_sum_of_squares(30, 4))
assert(is_sum_of_squares(36, 1))
assert not(is_sum_of_squares(35, 1))
assert not(is_sum_of_squares(18, 2))
assert not(is_sum_of_squares(1000, 13))
According to me this code below should print the sum of first n integers but it is giving me name error on line 5. How do I fix this ?
def printsum(n):
n = int(raw_input())
for i in range(1,n+1):
j = i + 1
doublesum = i + j - n
total = doublesum / 2
print total
The variables i and j are local to the function printsum. Simply return the values from the function and use said values to do your calculation.
Try with this code copy and past. Because issue may be indentation
def printsum(n):
n = int(raw_input())
for i in range(1,n+1):
j = i + 1
doublesum = i + j - n
total = doublesum / 2
print total
return;
Your logic is make me confused too.
I am trying to list all the factors of a number called count. Whenever I run it, it returns 1. For example: if 6 = count, then what should be returned when calling findFactor(6) is 1 2 3 6. What is returned is 1
divisors = ""
def findFactor(count):
divisors = ""
valueD = 0
for i in range(1, count+1):
valueD = count/i
if isinstance(valueD,int) == True:
divisors = str(valueD)+" "
print divisors
This can be done on one line using list comprehension.
def factorize(num):
return [n for n in range(1, num + 1) if num % n == 0]
You can refer this code:
def find_factor(n):
factor_values = []
for i in range(1, n + 1):
if n % i == 0:
factor_values.append(i)
values = ""
for v in factor_values:
values += str(v) + " "
return values
The function will return 1 2 3 6
First of all, you have an indentation error. print divisors need to be tabbed to inside the for-loop.
divisors = ""
def findFactor(count):
divisors = ""
valueD = 0
for i in range(1, count+1):
valueD = count/i
if isinstance(valueD,int) == True:
divisors = str(valueD)+" "
print divisors
Furthermore like #juanpa.arrivillaga mentioned, your results will vary between Python 2 and Python 3.
However, if you want your divisors to print in the order you want, i.e. start with 1 you need to change your range to for i in range(count,0, -1). You will get multiple 1's , but that's something I'll leave for you to figure out. A little challenge, if you will. ;)
This is the total code I have come up with. Thank you for all the help.
def findFactor(n):
factorValues = []
for i in range(1, n + 1):
if n % i == 0:
factorValues.append(i)
values = ""
for v in factorValues:
values += str(v) + " "
print values.count(" ")
# prints the number of factors
print values
findFactor(21)
It will print the number of factors, and then the factors on the next line.
The answers given so far are all brute force methods.
For n=10000, they will have to iterate ten thousand times.
The following will iterate only 100 times:
def find_factors(n):
factors = []
i = 1
j = n
while True:
if i*j == n:
factors.append(i)
if i == j:
break
factors.append(j)
i += 1
j = n // i
if i > j:
break
return factors
If there were a list of prime numbers available, it could be made even faster.
Hello I want to make a function that will use enhance(which just changes the word already made it) and print the new word in parts of a given number n. Example for S=test I should get (‘##t’, ‘#te’, ‘tes’, ‘est’, ‘st%’, ‘t%%’)
def enhance(S,n):
S = "#"*(n-1)+S+"%"*(n-1)
return S
def exploder(S,n):
S = enhance(S,n)
x=0
for i in range (n <= len(S)):
print(S[x:i])
x=x+1
S="test"
n = 3
for n in range (0,n):
print(exploder(S,n))
n=n+1
print(exploder(S,n))
One immediate fix. Instead of:
for i in range (n <= len(S)):
I think you want:
for i in range(n, len(S) + 1):
That will give you values of i in the range n <= i < len(s).
Also, as Alex Hall suggested, change:
print(exploder(S,n))
To just:
exploder(S,n)
The exploder function was returning None. So that print is the source your spurious None outputs.
def enhance(S, n):
S = "#" * (n - 1) + S + "%" * (n - 1)
return S
def exploder(S, n):
S = enhance(S, n)
for i in range(len(S)-n+1):
print(S[i:i+n])
S = "test"
n = 3
exploder(S, n)
Output:
##t
#te
tes
est
st%
t%%