Optimizing Python code for Project Euler #5 [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
This is my solution for the 5th problem in Project Euler. Is there any way to improve the while loop conditional instead of using the sum?
table = range(1,21)
result = 1
pf = 2
while sum(table) > len(table):
flag = False
for x,y in enumerate(table):
if y % pf == 0:
table[x] = y/pf
flag = True
if flag:
result *= pf
else:
pf += 1
print result

It's always clearer to write a program using a higher-order function instead of a loop because all of the extraneous variables that control the operation of the loop disappear. Here's a program that performs the same computation as yours, but the while and for loops disappear, as do the variables table, result, pf, and flag; variables x and y remain, but limited to a support role in an auxiliary function rather than as part of the main calculation:
>>> from fractions import gcd
>>> def lcm(x,y): return x*y/gcd(x,y)
...
>>> print reduce(lcm,range(1,21))
232792560

Use a constant. It's easier to understand when you want to go back and try a different value too.
MAX_DIVISOR = 20
table = range(1,MAX_DIVISOR + 1)
result = 1
pf = 2
while pf < MAX_DIVISOR + 1:
flag = False
for x,y in enumerate(table):
if y % pf == 0:
table[x] = y/pf
flag = True
if flag:
result *= pf
else:
pf += 1
print result

You could use any() to test the table, like so:
while any(n != 1 for n in table):
# do stuff
I think this is clearer than sum(table) > len(table).
Also, as #JoeClacks recommended, use a constant.
Complete revised solution:
MAX_DIVISOR = 20
table = list(range(1, MAX_DIVISOR+1))
result = 1
pf = 2
while any(n != 1 for n in table):
assert pf <= MAX_DIVISOR
flag = False
for i,n in enumerate(table):
if n % pf == 0:
table[i] = n//pf
flag = True
if flag:
result *= pf
else:
pf += 1
print(result)
I added an assert to make sure that pf only has legal values; this isn't needed as long as there is no bug in the code, but it can be a good idea to make code sanity-check itself.
I used i and n for the index and the number, rather than x and y.
I used Python's integer division operator // rather than /, so the code will work the same on Python 3.x as on Python 2.x. Also, the way I wrote the print statement it will work equally well in Python 3.x and Python 2.x.
I changed the indentation to steps of 4 spaces in accordance with PEP 8.
http://www.python.org/dev/peps/pep-0008/
Note: I like this algorithm for solving this problem. It's elegant. Did you invent this, get it from a book, or what?
EDIT: Actually, Project Euler problem 5 has been discussed before here on StackOverflow. Here is an answer that I just compared to the above answer. This one is almost exactly ten times faster than the one above. It's a bit trickier though!
https://stackoverflow.com/a/8026041/166949

Related

Improving perfomance(speed) of exponent problem

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

How to write a Python program to determine which of these two quantities is bigger? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to determine if the factorial of n raised to the same power is larger or the factorial of (n raised to the power n).
Here's my Python code.
def whichIsLarger():
def fact(n):
assert type(n) == int
if n == 0 or n == 1:
return 1
else:
return n * fact(n-1)
print max( fact(n**n), fact(n)**fact(n) )
Will this code execute correctly (i.e. without yeilding any semantic errors)?
Is there any way of testing this code without assigning any particular value to the variable n?
I mean I would like Python to do a general (i.e. a mathematical or algebraic osrt of) comparison for me, not just the usual arithmetical one that assigning the value 8, for example, to the integer n would effect.
Is there any built-in function in Python for computing factorials?
What is the difference if we write the factorial function inside or outside of the whichIsLarger function?
You'll probably want to look at the maths for something that's gonna blow up like that. Doing it naively will mean your code will take ages to execute and you'll be repeating lots of stuff if n starts getting large. If you can get a relationship between n-1 and n you may find you can clear a lot of the work
Nonetheless, here is naive code to get you started, but you will want to try and simplify it if you can
def factorial(n):
if n == 1:
return 1
return n *factorial(n-1)
def func1(n):
return factorial(n)**(factorial(n))
def func2(n):
return factorial(n**n)
for i in range(1, 5):
val1 = func1(i)
val2 = func2(i)
if val1 > val2:
print "func1 is larger: " + str(val1)
elif val2 > val1:
print "func2 is larger: " + str(val2)
else:
print "equal"
EDIT
Recursion sucks, especially on python, go with:
def factorial(n):
x = 1
for i in range(1,n+1):
x = x*i
return x
from math import factorial
def first_equation(n):
nf = factorial(n)
return nf ** nf
def second_equation(n):
return factorial(n ** n)
but you will very soon find that the numbers get insanely huge, you spend a long time waiting, and it really doesn't prove much because you might get a different result for really big n.
Instead you need to approach it symbolically. I suggest using Stirling's approximation - as n -> +inf, n! -> (n/e)**n * (2pi * n)**0.5
Another approach is to use the sympy symbolic math package:
import sympy as sp
# if you want LaTeX output, ie in iPython notebook
sp.init_printing(use_latex=True)
n = sp.symbols("n")
first_equation = sp.factorial(n) ** sp.factorial(n)
second_equation = sp.factorial(n ** n)
You can then use the equations directly, like
for n_val in range(7):
fen = first_equation .evalf(subs={"n":n_val})
sen = second_equation.evalf(subs={"n":n_val})
print(n_val, fen, sen)
which produces
0 1.00000000000000 1.00000000000000
1 1.00000000000000 1.00000000000000
2 4.00000000000000 24.0000000000000
3 46656.0000000000 1.08888694504184e+28
4 1.33373577685028e+33 8.57817775342843e+506
5 3.17504237378034e+249 2.41317228491761e+9566
6 1.90281878633202e+2057 6.89642755739806e+197572
or symbolically, like
# find the limit as n -> +infinity
relation = first_equation / second_equation
limit = sp.limit(relation, n, sp.oo)
print("Limit of eq1/eq2 as n -> +inf is {}.".format(limit))
which produces
Limit of eq1/eq2 as n -> +inf is 0.
(that is, (n**n)! will become infinitely larger than n! ** n!.)

computes the logarithm of a number x relative to a base b.n other words [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 months ago.
Write a simple procedure, myLog(x, b), that computes the logarithm of a number x relative to a base b.n other words, myLog should return the largest power of b such that b to that power is still less than or equal to x.
x and b are both positive integers; b is an integer greater than or equal to 2. Your function should return an integer answer.
Do not use Python's log functions; instead, please use an iterative or recursive solution to this problem that uses simple arithmatic operators and conditional testing.
What is wrong in the below code? As they have not mentioned what to return when the condition fails, so had kept false
def myLog(x, b):
count = 1
while x > 0 and b >= 2:
ans = b ** count
if (ans == x):
print str(count)
break
elif (ans > x):
print str(count-1)
break
count += 1
else:
return False
Since you haven't explained what problem you're trying to solve, all I can do is guess. But…
Your function never returns a number. If it succeeds, it prints out a number, then falls off the end of the function and returns None. If it fails, it returns False. And there's no other return anywhere in the code.
That's easy to fix: just return the value instead of print-ing it:
def myLog(x, b):
count = 1
while x > 0 and b >= 2:
ans = b ** count
if (ans == x):
return count
elif (ans > x):
return count-1
count += 1
else:
return False
You can improve performance by doing ans *= b each time through the loop instead of ans = b ** count. If the numbers are huge, dividing x by b might be better—division is usually slower than multiplication, but getting out of the huge-number domain early might help more than avoiding division.
It's also got some style problems, like the unnecessary parentheses some (but not all) of your conditions.
And finally, you may want to consider writing a "test driver". For example:
repcount = 100
errcount = 0
for _ in range(repcount):
x = generate_nice_random_x()
b = generate_random_base()
log1, log2 = myLog(x, b), int(math.log(x, b))
if log1 != log2:
print('log({}, {}): {} != {}'.format(x, b, log1, log2))
errcount += 1
print('{}/{} errors'.format(errcount, repcount))
Start with a small repcount to make sure you don't spam the screen; when you're happier with it, use a much larger one. Meanwhile, I'll leave it to you to figure out a good domain to choose from for testing log functions.
This is a question on an exam, that is currently ongoing.MITx: 6.00.1x Introduction to Computer Science and Programming

Ordering of evaluation using boolean or

So I've got this snippet of code. And it works (It says 1 is non-prime).:
n = 1
s = 'prime'
for i in range(2, n / 2 + 1):
if n == 1 or n % i == 0:
s= 'non-' +s
break
print s
My problem is that if I change the fourth line to: if n % i == 0 or n == 1:, it doesn't work (it says 1 is prime.)
Why is that? Since I'm using or should it be that either one of them is True so the order doesn't count?
(I'm still learning about boolean so I may be making some basic mistake.)
Thanks in advance!
EDIT: Thanks for the answers; I never realized my issue with the range() function. And about the code working and not working: I have no idea what happened. I may have made some mistake somewhere along the way (maybe forgot to save before running the script. Although I could've sworn that it worked differently :P ). Maybe I'm just getting tired...
Thanks for the answers anyways!
In both cases, the body of the loop does not run, because when 'n' is 1, it does not fall within the range of (n,n/2+1)
The code you posted says that 1 is prime (again, because the loop body does not execute at all)
The precedence is fine. % is evaluated first, then ==, then or, so it breaks down into:
___or___
/ \
== ==
/ \ / \
n 1 % 0
/ \
n i
Your problem is that your for loop is not being executed at all, so that s is still set to "prime".
The range 2,n/2+1 when n is 1 equates to 2,1 which will result in the body not being executed.
In fact it won't be executed where n is 2 either since 2/2+1 is 2 and the range 2,2 doesn't execute. The values are the start and terminating value, not start and end (last) value - it's just fortuitous there that 2 is considered a prime by virtue of the initialisation of s :-)
Try this instead:
#!usr/bin/python
n = 9
s = 'prime'
if n == 1:
s = 'non-prime'
else:
i = 2
while i * i <= n:
if n % i == 0:
s= 'non-prime'
break
i = i + 1
print s
It's wasteful going all the way up to n/2, the square root of n is all that's needed.
i think the problem is when n is 1, the loop is skipped.
Other answers already correctly addressed your specific problem (which, in other words, is that the loop executes only if n/2 + 1 > 2, that is, n/2 > 1, which means n > 2 with new-style division [[python 3 or suitable imports from the future or flags...]], n > 3 with classic style truncating division).
Wrt the specific question you posed:
Since I'm using or should it be that
either one of them is True so the
order doesn't count?
The order does count because or (like and) is a short-circuiting operator: specifically, or is guaranteed to go left to right, and stop if the left operand is true (because it does not need to know about the right one). This doesn't matter for your specific code, but it's crucial in cases such as, e.g.:
if i == 0 or n / i > 3: ...
If or wasn't going left-to-right (and stopping ASAP), the right-hand operand might get executed even when i equals 0 -- but then the division would raise an exception! With Python's rules, this code snippet won't raise exceptions (if i is an int, at least;-).
Again: this has nothing to do with the specific problem you're having (see other answers and the start of this one), but it's important for you to know for the future, so, since you asked, I took the opportunity to explain!-)
for n in range(101):
s = 'prime'
if n < 2 or not (n & 1): ## not(n & 1) == is even number (last bit 0) == not (n % 2)
s = 'non-'+s
else:
for i in range(3, int(n**0.5) + 1,2):
if not(n % i):
s= 'non-' +s
break
print "%i is %s" % (n,s)
You need not check all even numbers and you can stop the check at square root of n.

Python Syntax Problem

I'm just getting back into Project Euler and have lost my account and solutions, so I'm back on problem 7. However, my code doesn't work. It seems fairly elementary to me, can someone help me debug my (short) script?
Should find the 10001st Prime.
#!/usr/bin/env python
#encoding: utf-8
"""
P7.py
Created by Andrew Levenson on 2010-06-29.
Copyright (c) 2010 __ME__. All rights reserved.
"""
import sys
import os
from math import sqrt
def isPrime(num):
flag = True
for x in range(2,int(sqrt(num))):
if( num % x == 0 ):
flag = False
if flag == True:
return True
else:
return False
def main():
i, n = 1, 3
p = False
end = 6
while end - i >= 0:
p = isPrime(n)
if p == True:
i = i + 1
print n
n = n + 1
if __name__ == '__main__':
main()
Edit*: Sorry, the issue is it says every number is prime. :/
The syntax is fine (in Python 2). The semantics has some avoidable complications, and this off-by-one bug:
for x in range(2,int(sqrt(num))):
if( num % x == 0 ):
flag = False
range(2, Y) goes from 2 included to Y excluded -- so you're often not checking the last possible divisor and thereby deeming "primes" many numbers that aren't. As the simplest fix, try a 1 + int(... in that range. After which, removing those avoidable complications is advisable: for example,
if somebool: return True
else: return False
is never warranted, as the simpler return somebool does the same job.
A simplified version of your entire code (with just indispensable optimizations, but otherwise exactly the same algorithm) might be, for example:
from math import sqrt
def isPrime(num):
for x in range(3, int(1 + sqrt(num)), 2):
if num % x == 0: return False
return True
def main():
i, n = 0, 3
end = 6
while i < end:
if isPrime(n):
i += 1
print n
n += 2
if __name__ == '__main__':
main()
"Return as soon as you know the answer" was already explained, I've added one more crucial optimization (+= 2, instead of 1, for n, as we "know" even numbers > 3 are not primes, and a tweak of the range for the same reason).
It's possible to get cuter, e.g.:
def isPrime(num):
return all(num % x for x n range(3, int(1 + sqrt(num)), 2))
though this may not look "simpler" if you're unfamiliar with the all built-in, it really is, because it saves you having to do (and readers of the code having to follow) low level logic, in favor of an appropriate level of abstraction to express the function's key idea, that is, "num is prime iff all possible odd divisors have a [[non-0]] remainder when the division is tried" (i.e., express the concept directly in precise, executable form). The algorithm within is actually still identical.
Going further...:
import itertools as it
def odd():
for n in it.count(1):
yield n + n + 1
def main():
end = 5
for i, n in enumerate(it.ifilter(isPrime, odd())):
print n
if i >= end: break
Again, this is just the same algorithm as before, just expressed at a more appropriate level of abstraction: the generation of the sequence of odd numbers (from 3 included upwards) placed into its own odd generator, and some use of the enumerate built-in and itertools functionality to avoid inappropriate (and unneeded) low-level expression / reasoning.
I repeat: no fundamental optimization applied yet -- just suitable abstraction. Optimization of unbounded successive primes generation in Python (e.g. via an open-ended Eratosthenes Sieve approach) has been discussed in depth elsewhere, e.g. here (be sure to check the comments too!). Here I was focusing on showing how (with built-ins such as enumerate, all, and any, the crucial itertools, plus generators and generator expressions) many "looping" problems can be expressed in modern Python at more appropriate levels of abstraction than the "C-inspired" ones that may appear most natural to most programmers reared on C programming and the like. (Perhaps surprisingly to scholars used to C++'s "abstraction penalty" first identified by Stepanov, Python usually tends to have an "abstraction premium" instead, especially if itertools, well known for its blazing speed, is used extensively and appropriately... but, that's really a different subject;-).
Isn't this better?
def isPrime(num):
for x in range(2,int(sqrt(num))):
if( num % x == 0 ):
return False
return True
And this:
def main():
i, n = 1, 3
while i <= 6:
if isPrime(n):
i = i + 1
print n
n = n + 1
Also, I'm not seeing a 10001 anywhere in there...

Categories

Resources