Printing Sum of first n Integers - python

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.

Related

Why does a change in multiplication sign in factorial to addition sign give such an output?

Question: Why is the output 11 not 12?
i+4+i+3+i+2 = 1+4+1+3+1+2 = 12
Code:
def factorial(n):
i = 1
while n >= 1:
#I changed the signs from * to + after getting the factorial from * method.
i = i * n --> i = i + n
n = n - 1
return i
print factorial(4)
11
To get expected i+4 + i+3 + i+2 and result 12 you need
def factorial(n):
result = 0
i = 1
while n > 1:
result += i + n
n = n - 1
return result
print(factorial(4))
I add to new variable result so I don't change i and it is 1 all the time.
I also use > instead of >= so it ends after i+2 and it doesn't add i+1
def factorial(n):
i = 1
while n >= 1:
#I changed the signs from * to + after getting the factorial from * method.
print(i)
i = i + n
n = n - 1
return i
print(factorial(4))
If you print i, you will find i has changed after first loop.
So the output should be 1+4+3+2+1=11
(Posted on behalf of the question author).
Tips from me to solve the problem: 1. understand the concept of loop 2. try to print the answer on your own - i=5, n=3, i=8, n=2, i=10, n=1, i=11

List all factors of number

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.

Print a word in parts python

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%%

Project Euler #6 Python

The question I'm trying to solve is here: https://projecteuler.net/problem=6
I tried this but all that was printed were two zeroes:
sumsquare = 0
ssum = 0
def sumsquaredif(n):
for i in range(1, n+1):
num = i ** 2
num += sumsquare
i += ssum
squaresum = ssum**2
print (squaresum)
print (sumsquare)
return
sumsquaredif(10)
And then of course I'd have to add the code to subtract sumsquare from squaresum and print that. But this preliminary code isn't working. I'd really appreciate it if someone could help. I'm still a beginner. Thank you!
Your += assignments are the wrong way! num += sumsquare is adding the sum to the current number, not the other way around, and similar for ssum. Also, the sum variables should be declared inside of the function.
def sumsquaredif(n):
sumsquare = 0 # inside function
ssum = 0 # inside function
for i in range(1, n+1):
num = i ** 2
sumsquare += num # inversed
ssum += i # inversed
squaresum = ssum**2
Also, you could make that code much shorter by using list comprehensions:
sumsquare = sum(n for n in range(1, n+1))**2
squaresum = sum(n**2 for n in range(1, n+1))

Use Python To Sum A Series

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)

Categories

Resources