Like if i told the program n=10, how would I make it return 10*9*8*7*6*5....1?
I thought a while loop but I feel I messed up somewhere because it doesn't sum up all of the numbers in the sequence.
My current code looks like this
def product(n):
i=n
a=n-1
while a>0:
return i * a
b=i * a
a=a-1
i=i-1
Are there any better ways to do it without using recursion? Sorry for the incredibly beginner question, but I'm trying to teach myself how to code. You gotta start somewhere!
Thanks!
Since you are trying to learn to code, I won't give you a total solution, but
I'll give you a few hints instead:
Have a for loop that runs up from 1 to n (using range(1, n+1)) instead of your while-loop. This will generate the values that you want to multiply and iterate the right number of times (which can be a bit tricky with while loops sometimes).
Have a variable named product to store the result of the multiplications each time through the loop.
Initialize product before you enter the for-loop. Once inside you'll be just updating the value of product.
After you are done with the loop, you can use the return statement to return the value of product.
Finally, for testing purposes, you may want to start out with a small value of n, like 4, and print out the values you are computing inside the loop to verify how your code is working.
There are more terse and pythonic ways to do this, but this uses the code structure you have already set up. And of course recursively as well as you mention too.
Once you master the basics, you'll appreciate the more idiomatic ways of writing this, or calling the appropriate functions that do this for you.
Well, here's another Pythonic approach.
>>> import operator
>>> numbers = range(1, 11)
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> reduce(operator.mul, numbers)
3628800
Assuming you what you meant is factorial function, you can simply just use the math.factorial():
>>> import math
>>> math.factorial(10)
3628800
You are trying to find the factorial of a number n, essentially. For finding the factorial of a number, there are 2 methods
Using a Loop structure
Using Recursion (as you've mentioned)
As a new programmer, you would be better off with a simple loop structure that runs from 1 to n and puts the multiplied value at each iteration into a variable. That variable is your answer. But also know that recursion will also work and make the code look elegant. Happy Programming !
This is called the factorial. 10! is equivalent to 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.
def factorial(n):
product = 1
while n > 0:
product *= n
n -= 1
return product
By the way, in practice, just use math.factorial.
def factorial(n):
if n <= 1: return 1
return n * factorial(n-1)
I always think of factorial as the quintessential example in learning recursion ...
Another way to do this is to use scipy.product.
>>> import scipy
>>> scipy.product(xrange(1,11))
3628800
As a learner you should do it without using any inbuilt functions it will help you to learn programming rather just tool as learning a tool is much easier one you become good programmer. there are two ways of doing this I have implemented simpler versions.
Using Recursion:
def product(n):
if n== 1:
return 1
return n * product(n-1)
Using Simple Loop:
def product(n):
res = 1
while n>1:
res = res * n
n = n - 1
return res
For factorials too large to compute directly, there is another way to do that by using the Stirling's approximation.
n! := sqrt(2πn)*(n/e)^n, where e = 2.71828
Related
I'm trying to write a program to find sum of first N natural numbers i.e. 1 + 2 + 3 + .. + N modulo 1000000009
I know this can be done by using the formula N * (N+1) / 2 but I'm trying to find a sort of recursive function to calculate the sum.
I tried searching the web, but I didn't get any solution to this.
Actually, the problem here is that the number N can have upto 100000 digits.
So, here is what I've tried until now.
First I tried splitting the number into parts each of length 9, then convert them into integers so that I can perform arithmetic operations using the operators for integers.
For example, the number 52562372318723712 will be split into 52562372 & 318723712.
But I didn't find a way to manipulate these numbers.
Then again I tried to write a function as follows:
def find_sum(n):
# n is a string
if len(n) == 1:
# use the formula if single digit
return int(int(n[0]) * (int(n[0]) + 1) / 2)
# I'm not sure what to return here
# I'm expecting some manipulation with n[0]
# and a recursive call to the function itself
# I've also not used modulo here just for testing with smaller numbers
# I'll add it once I find a solution to this
return int(n[0]) * something + find_sum(n[1:])
I'm not able to find the something here.
Can this be solved like this?
or is there any other method to do so?
NOTE: I prefer a solution similar to the above function because I want to modify this function to meet my other requirements which I want to try myself before asking here. But if it is not possible, any other solution will also be helpful.
Please give me any hint to solve it.
Your best bet is to just use the N*(N+1)/2 formula -- but using it mod p. The only tricky part is to interpret division by 2 -- this had to be the inverse of 2 mod p. For p prime (or simply for p odd) this is very easy to compute: it is just (p+1)//2.
Thus:
def find_sum(n,p):
two_inv = (p+1)//2 #inverse of 2, mod p
return ((n%p)*((n+1)%p)*two_inv)%p
For example:
>>> find_sum(10000000,1000000009)
4550000
>>> sum(range(1,10000001))%1000000009
4550000
Note that the above function will fail if you pass an even number for p.
On Edit as #user11908059 observed, it is possible to dispense with multiplication by the modular inverse of 2. As an added benefit, this approach no longer depends on the modulus being odd:
def find_sum2(n,k):
if n % 2 == 0:
a,b = (n//2) % k, (n+1) % k
else:
a,b = n % k, ((n+1)//2) % k
return (a*b) % k
Anyone know the most efficient way of displaying the first 100 numbers in the Fibonacci Sequence in Python please?
Here is my current code:
fib1,fib2,fib3= 0,0,1
while fib3< 100:
print(fib3)
fib1=fib2
fib2=fib3
fib3=fib1 + fib2
Understand the working of python and fibonacci Sequence. Use generator feature of python. Follow the code
a = int(input('Give num: '))
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
According to the Fibonacci formula, here's a way to get the nth member of the Fibonacci sequence.
This function doesn't use loops nor recursion (recursions are horrible in Python, they are always slower than an iterative solution, because of how Python handle recursion, see here for more info about it)
I need help with evaluating the expression. I just started it but at a loss for what next plus all the for loops I am using seem unnecessary. it has sum, products and combinations:
What I tried is incomplete and in my opinion not accurate. I tried several but all I can come up with for now. I don't have the denominator yet.
i = 10
N = 3.1
j = []
for x in range(1, i + 1):
for y in range(1, i):
for z in range(1, n - i):
l = N * y * z
j.append(l)
ll = sum(j)
Any help is appreciated. I want to be able to understand it so I can do more complex examples.
Here are some hints. If you try them and are still stuck, ask for more help.
First, you know that the expression involves "combinations," also called "binomial coefficients." So you will need a routine that calculates those. Here is a question with multiple answers on how to calculate these numbers. Briefly, you can use the scipy package or make your own routine that uses Python's factorial function or that uses iteration.
Next, you see that the expression involves sums and products and is written as a single expression. Python has a sum function which works on generator expressions (as well as list and set generators and other iterables). Your conversion from math to Python will be easier if you know how to set up such expressions. If you do not understand these generators/iterables and how to sum them, do research on this topic. This approach is not necessary, since you could use loops rather than the generators, but this approach will be easier. Study until you can understand an expression (including why the final number in the range has 1 added to it) such as
sum(N * f(x) for x in range(1, 5+1))
Last, your expression has products, but Python has no built-in way to take the product of an iterable. Here is such a function in Python 3.
from operator import mul
from functools import reduce
def prod(iterable):
"""Return the product of the numbers in an iterable."""
return reduce(mul, iterable, 1)
With all of that, your desired expression will look like this (you will need to finish the job by replacing the ... with something more useful):
numerator = sum(N * prod(... for y in range(1, 1+1)) for x in range(1, 5+1))
denominator = prod(y + N for y in range(1, 5+1))
result = numerator / denominator
Note that your final result is a function of N.
I'm currently learning Python on repl.it and I have a problem with one of my work.
My code is supposed to:
1.Input a given integer X
2.Find the greatest integer n where 2ⁿ is less than or equal to X.
3.Print the exponent value(n) and the result of the expression 2ⁿ.
But my code fail as the machine insert too big number like 10^8+2. The program completely failed
Here is the piece of code that I'm working on:
X = int(input())
a = X//2
while a > -1:
if (2**a) < =x:
print(a)
print(2**a)
break
else:
a -= 1
Can anyone find me another solution to this problem, or improve the bit of code I'm working on by its runtime? It works with small number(less than 10^6) but otherwise the program freeze.
Thanks in advance!
Of course, I can't refer to the "too big input" that you mention (since you didn't provide it), but as for the problem itself, it could be easier solved in the following way:
import numpy as np
a = int(np.log2(your_input))
The first issue I see is that in you code
if (2**a) < =x:
print(a)
print(2**a)
you calculate the value of 2**a twice. A good start could be to save the value of 2**a into a variable. However, since you are only doing powers of 2 you could also take a look at bitwise operations. So instead of doing a = X//2 you could also write
a= X >> 2
and instead of doing 2**a write
temp = 1 << a
When working with powers of 2 it can be significantly faster to work with bitwise operations.
I did it! (using some of your solutions of course)
This is my teachers code :
x = int(input())
n = 1
while 2 ** n <= x:
n += 1
print(n - 1, 2 ** (n - 1))
So I'm learning python so I'm going through some project euler problems. And I'm not sure if this is a python problem I'm having, or just me being retarded, but I seem to be getting the wrong answer for problem 53. Here's a link to the problem http://projecteuler.net/index.php?section=problems&id=53
and this is my code:
from math import factorial
def ncr(n,r):
return (factorial(n)/(factorial(r)*factorial(n-r)))
i = 0
for x in range(1,100):
for y in range(0,x):
if(ncr(x,y) > 1000000):
i=i+1
print i
I'm getting 3982 which is apparently the wrong answer. Is something wrong that I'm doing that's specific to python?
range( a, b) does not include b.
I think your code is correct, however, you should iterate x to 100 inclusive, so you should use
for x in range(1,101):
Hope that helps. Euler rocks!
Note that n is greater than or equal to 1 AND smaller than or equal to 100. Currently your n goes from 1 to 99. You can use xrange too.
from math import factorial
def ncr(n,r):
return (factorial(n)/(factorial(r)*factorial(n-r)))
i = 0
for x in range(1,101):
for y in range(1,x+1):
if(ncr(x,y) > 1000000):
i=i+1
print i
If you are beginner I use this opportunity, considering project Euler's nature, to give coding alternative, which is self-contained and demonstrates lookup table approach to speed up recursive functions and saving the answers to dictionary and using the len as count.
Hope the 4075 is the right answer!
from __future__ import division
factorials={}
def factorial(n):
""" factorial from lookup table ready or generate it to there """
if n not in factorials:
factorials[n]=1 if n==0 else n*factorial(n-1)
return factorials[n]
def ncr(n,r):
return (factorial(n)/(factorial(r)*factorial(n-r)))
bigones= [(x,y) for x in range(1,1+100) for y in range(x) if ncr(x,y) > 1000000 ]
print len(bigones)
Considering the input from the problem specification:
"It is not until n = 23, that a value exceeds one-million",
you can make the range for the outer from 23 to 101:
for x in range(23,101):
...
Furthermore, n over k can be calculated faster without generating the three factorials:
def noverk(n,k):
noverk=1
if 2*k < n:
k=n-k;
for i in range(1,n-k+1):
noverk *= (i+k)
noverk /= i
return noverk;