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;
Related
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-2)
I can not seem to be able to figure this problem out. I can find the even integers for even factorials, but I can not seem to figure out how to find even integers for odd factorials at the same time. I've been at it for days now. I am extremely new to python, so any help would be very appreciative. Thanks!
This should work!
def factorial(n):
if n % 2 != 0:
n -= 1
return 1 if (n < 1) else n * factorial(n-2)
print(factorial(6))
print(factorial(7))
The output will be:
48
48
Equals for n = 6 or n = 7 (even and odd numbers) as you can see
factorial = lambda x: functools.reduce(lambda x, y: x*y, range(2, x+1, 2))
Use internal method functools.reduce to prevent maximum recursion depth
I have a calculation that was created in Python and I'm trying to convert it over to Octave 4.2.2 which is similar to Matlab code.
Python Code:
def gcd(a,b):
if b == 0:
return a
else:
return gcd(b,a%b)
def lcm(a,b):
return a*b//gcd(a,b)
def NumberOfShifts(m,n):
N = 1
l = min(-(-m//2),-(-n//2))
for k in range(1,l):
N = lcm(N,2+m+n-4*k)
return 2*N
If m and n are both 5 the answer should be 16.
The Octave / Matlab Code I have so far doesn't work for cases where m and n are the same odd number any idea how to fix this?
m=5 % doesn't work with same odd numbers like 5
n=5 % doesn't work with same odd numbers like 5
N=1
l=min(-floor(-m/2),-floor(-n/2))
for k=1:l
N=lcm(N,2+m+n-4*k)
end
final_repeat_loop=2*N %how many loops to do to repeat
The answer I get is 0.
In Python, range(1,l) does not include the element l (see here).
This is usually a point of confusion for people new to Python - it was and still is for me.
In Matlab, the equivalent for k=1:l does include l. So, to switch from Python to Matlab, range(1,l) should be replaced with for k=1:(l-1)
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))
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
How do I go about computing a factorial of an integer in Python?
The easiest way is to use math.factorial (available in Python 2.6 and above):
import math
math.factorial(1000)
If you want/have to write it yourself, you can use an iterative approach:
def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact
or a recursive approach:
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
Note that the factorial function is only defined for positive integers, so you should also check that n >= 0 and that isinstance(n, int). If it's not, raise a ValueError or a TypeError respectively. math.factorial will take care of this for you.
On Python 2.6 and up, try:
import math
math.factorial(n)
Existing solution
The shortest and probably the fastest solution is:
from math import factorial
print factorial(1000)
Building your own
You can also build your own solution. Generally you have two approaches. The one that suits me best is:
from itertools import imap
def factorial(x):
return reduce(long.__mul__, imap(long, xrange(1, x + 1)))
print factorial(1000)
(it works also for bigger numbers, when the result becomes long)
The second way of achieving the same is:
def factorial(x):
result = 1
for i in xrange(2, x + 1):
result *= i
return result
print factorial(1000)
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
For performance reasons, please do not use recursion. It would be disastrous.
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
Check running results
cProfile.run('fact(126000)')
4 function calls in 5.164 seconds
Using the stack is convenient (like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.
If the stack is high, it means that the computer stores a lot of information about function calls.
The method only takes up constant memory (like iteration).
Or using a 'for' loop
def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
Check running results
cProfile.run('fact(126000)')
4 function calls in 4.708 seconds
Or using the built-in function math
def fact(n):
return math.factorial(n)
Check running results
cProfile.run('fact(126000)')
5 function calls in 0.272 seconds
If you are using Python 2.5 or older, try
from operator import mul
def factorial(n):
return reduce(mul, range(1, n+1))
For newer versions of Python, there is factorial in the math module as given in other answers here.
def fact(n):
f = 1
for i in range(1, n + 1):
f *= i
return f
Another way to do it is to use np.prod shown below:
def factorial(n):
if n == 0:
return 1
else:
return np.prod(np.arange(1,n+1))
Non-recursive solution, no imports:
def factorial(x):
return eval(' * '.join(map(str, range(1, x + 1))))
You can also make it in one line recursively if you like it. It is just a matter of personal choice. Here we are using inline if else in Python, which is similar to the ternary operator in Java:
Expression1 ? Expression2 : Expression3
One line function call approach:
def factorial(n): return 1 if n == 0 else n * factorial(n-1)
One line lambda function approach:
(although it is not recommended to assign lambda functions directly to a name, as it is considered a bad practice and may bring inconsistency to your code. It's always good to know. See PEP8.)
factorial = lambda n: 1 if n == 0 else n * factorial(n-1)