The series:-
I want to write a python program in which we can can input the the value of x and n and solve this series.
can anyone help me please?
The Series:- x-x^2+x^3/3-x^4/4+...x^n/n
x = int (input ("Enter value of x: "))
numbed = int (input ("Enter value of n: "))
summed = 0
for a in range (numbed + 1) :
if a%2==0:
summed += (x**a)/numbed
else:
summed -= (x**a)/numbed
print ("Sum of series", summed)
**I tried this code, but no matter what values I enter, the output is always 0.00. **
This should do the trick:
x = int(input("Enter value of x: "))
n = int(input("Enter value of n: "))
total = x
for i in range(2, n+1):
if i%2==0:
total -= x**i/i
else:
total += x**i/i
print("Sum: ", total)
I assume the series you mentioned in your question is this: x - x^2/2 + x^3/3 - x^4/4 +... x^n/n.
If yes, try this:
x = int (input ("Enter value of x: "))
numbed = int (input ("Enter value of n: "))
sum1 = x
for i in range(2,numbed+1):
if i%2==0:
sum1=sum1-((x**i)/i)
else:
sum1=sum1+((x**i)/i)
print("The sum of series is",round(sum1,2))
just as an example of using recurcion:
x = int(input("Enter value of x: "))
n = int(input("Enter value of n: "))
def f(x,n,i=1,s=1):
return 0 if i>n else x**i/i*s + f(x,n,i+1,-s)
f(3,5) # 35.85
Related
This question already has answers here:
Convert for loop to recursive function in python3
(3 answers)
Closed 3 months ago.
I have written a python for loop iteration as show below. I was wondering if its possible to convert into a recursive function.
a = int(input("Please enter the first number: "))
b = int(input("Please enter the second number: "))
res = 0
for i in range(a,b+1):
temp = 1
for j in range(1,i+1):
temp = temp * j
res = res + temp
print("Sum of products from 1 to each integer in the range ",a," to ",b," is: ",res)
I am expecting something like the below example:
def recursion(a,b):
res = 0
if condition or a while condtion
....
return ....
a = int(input("Please enter the first number: "))
b = int(input("Please enter the second number: "))
print("Sum of products from 1 to each integer in the range ",a," to ",b," is: ",res)
Any idea ?
a = int(input("Please enter the first number: "))
b = int(input("Please enter the second number: "))
res = sum([x for x in range(int(a), int(b)+1)])
print(res)
My question is why do you need it to be recursive?
I ask that because this particular answer doesn't seem best approached through recursion.
if you need to use recursion
def recursive_sum(m,n):
if n <= m:
return n
else:
return n+recursive_sum(m, n-1)
EDIT:
the question asked included the sum of the factorial of a range, apologies for only including the sum portion.
def factorial(b):
if (b==1 or b==0):
return 1
else:
return (b * factorial(b - 1))
res = sum(map(factorial, range(a,b+1)))
The original code you're multiplying each value in the range by the product of the previous and summing.
range(5,10) for instance
total for the way the problem is written
res comes to 4500198
where the factorial sum = 4037880
If you print out just for value 5
you get 1+3+9+33+153 where !5=120
Which is the way you're trying to accomplish it?
Could be something like this, imagine dividing the problem into smaller sub-problems
def recursive_sum(a, b, res=0):
if a > b:
return res
temp = 1
for j in range(1, a+1):
temp = temp * j
res = res + temp
return recursive_sum(a+1, b, res)
a = int(input("Please enter the first number: "))
b = int(input("Please enter the second number: "))
res = recursive_sum(a, b)
print(f"Sum of products from 1 to each integer in the range {a} to {b} is: {res}")
I need help with this Python program.
With the input below:
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
the program must output:
Output: 54321
My code is:
n = 0
t = 1
rev = 0
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
a = n % 10
rev = rev * 10 + a
n = n // 10
print(rev)
Its output is "12345" instead of "54321".
What should I change?
try this:
t = 1
rev = ""
while(t <= 5):
n = input("Enter a number:")
t+=1
rev = n + rev
print(rev)
Try:
x = [int(input("Enter a number")) for t in range(0,5)]
print(x[::-1])
There could be an easier way if you create a list and append all the values in it, then print it backwards like that:
my_list = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
my_list.append(n)
my_list.reverse()
for i in range(len(my_list)):
print(my_list[i])
You can try this:
n = 0
t = 1
rev = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
rev.append(n)
rev.reverse()
rev = ''.join(str(i) for i in rev)
print(rev)
Maintaining a numerical context: use "10 raised to t" (10^t)
This code is not very different from your solution because it continues to work on integer numbers and return rev as an integer:
t = 0
rev = 0
while (t < 5):
n = int(input("Enter a number:"))
# ** is the Python operator for 'mathematical raised to'
rev += n * (10 ** t)
t += 1
print(rev)
(10 ** t) is the Python form to do 10^t (10 raised to t); in this context it works as a positional shift to left.
Defect
With this program happens that: if you insert integer 0 as last value, this isn't present in the output.
Example: with input numeric 12340 the output is the number 4321.
How to solve the defect with zfill() method
If you want manage the result as a string and not as a integer we can add zeroes at the start of the string with the string method zfill().
In this context the zfill() method fills the string with zeros until it is 5 characters long.
The program with this modification is showed below:
NUM_OF_INTEGER = 5
t = 0
rev = 0
while (t < NUM_OF_INTEGER):
n = int(input("Enter a number: "))
rev += n * (10 ** t)
t += 1
# here I convert the number 'rev' to string and apply the method 'zfill'
print(str(rev).zfill(NUM_OF_INTEGER))
With previous code with input "12340" the output is the string "04321".
n = int(input("How many number do you want to get in order? "))
list1 = []
for i in range(n):
num = int(input("Enter the number: "))
thislist = [num]
list1.extend (thislist)
list1.sort()
print ("The ascending order of the entered numbers, is: " ,list1)
list1.sort (reverse = True)
print ("The descending order of the entered numbers, is: " ,list1)
For example, if user keys in 6, the output is 21 (1+2+3+4+5+6)
sum = 0
num = int(input("Enter number: "))
…..
….
This is my code below:
x=0
sum = 0
nums = int(input("enter num "))
while sum <= nums:
sum+=1
x= x + sum
y = x - nums -1
print(y)
First of all, I suggest not to use sum as variable name, this will shadow the built-in sum() function.
There are two ways to do it using while loop, the first one is close to yours but turn <= to < in the condition so you don't need extra - num - 1 at the end.
n = 0
total = 0
num = int(input("enter num "))
while n < num:
n += 1
total += n
print(total)
Second one adds number in descending order, it also change the value of num. If you need num for later use, use the first one.
total = 0
num = int(input("enter num "))
while num:
total += num
num -= 1
print(total)
If loop is not needed, as you are going to obtain a triangular number, just use the formula.
num = int(input("enter num "))
print(num * (num + 1) // 2)
If you don't have use a loop you could do it in a single line:
print(sum(range(1, int(input('Enter a number: ')) + 1)))
Test:
Enter a number: 6
21
I want to make a loop where I can input numbers, and then the loop will give me the average of the numbers that I inputted. But a problem that I am facing is that I do not know how to make the loop remember the previous numbers that I inputted. I want the loop to end if I put -1.
x = (input ("enter a number: "))
while x != "-1":
y = int(input("enter another number: " ))
total = 0 + y
if total <= 0:
totally = total
print (totally)
you may use a list to store all your numbers, when you finish the input you can compute the average:
nums = []
i = int(input("enter another number: " ))
while i != -1:
nums.append(i)
i = int(input("enter another number: " ))
avg = sum(nums) / len(nums)
print(avg)
if you like one-line solution:
from statistics import mean
from itertools import takewhile, count
print(mean(takewhile(lambda x : x !=-1, (int(input()) for _ in count() ))))
if you want to print intermediary average:
nums = []
i = int(input("enter another number: " ))
while i != -1:
nums.append(i)
print(sum(nums) / len(nums))
i = int(input("enter another number: " ))
also, you could use 2 variables to hold the current sum and the total count:
i = int(input("enter another number: " ))
s = 0
c = 0
while i != -1:
c += 1
s += i
print(s / c)
i = int(input("enter another number: " ))
Probably you should define your total var before, something like this:
x = int(input ("enter a number: "))
total = x
numLoops = 1
y = 0
while y != -1:
y = int(input("enter another number: " ))
total += y # This will store the summation of y's in total var
numLoops += 1
print(f"The average is: {total/numLoops}") # Prints the average of your nums
You can do the following:
values = []
while True:
x = int(input ("enter a number: "))
if x == -1:
break
else:
values.append(x)
print(sum(values)/len(values))
problem with sorting
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
while i <= n:
s = input()
total = total + int(s)
i = i + 1
s.sort()
print s
print('The sum is ' + str(total))
Because you are trying to sort on input. sort only work on iterating like list and tuples.
I just rewrite your code,
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
Edit
Just change whole operation into a function and put yes/no question in a while loop, And for wrong entry exit from program.
def foo():
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
while True:
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
foo()
elif a == 'n':
print 'We are giving one more option.'
continue
else:
print 'Wrong entry'
break
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
array = []
while i <= n:
s = int(input())
array.append(s)
total = total + int(s)
i = i + 1
array.sort()
print(array)
print('The sum is ' + str(total))
this will solve your problem, sort applies on list not on str object
Store the numbers in a list. Then use sum(list) to get the sum of elements in the list, and sorted(list) to get the list sorted in ascending order.
n = int(input("Enter the number of inputs: "))
l=[]
for i in range(n):
s = input()
l.append(int(s))
print('The sum is', sum(l))
print('Sorted values', sorted(l))
Were you looking for this?