I would like to ask how can I retrieve out the list of fibo list and then check whether does the input value by the user is inside the fibo list.
a , b = 1, 1
while num <= sys.maxint:
fibo == a , b = b, a+b
if num == (b +a+b):
print "It is a Fibonacci number"
break
else:
print "It is not a Fibonacci number"
break
Thank you!
Using a more sophisticated Fibonacci number test, you could use
def is_fibonacci(n):
phi = 0.5 + 0.5 * math.sqrt(5.0)
a = phi * n
return n == 0 or abs(round(a) - a) < 1.0 / n
(This is probably the most efficient way to determine whether a number is a Fibonacci number, and it is most probably not the intended solution to your homework. I just included this answer for future reference.)
A pythonic one-liner
def is_fibonacci(n):
return n >= 0 and (n==0 or sqrt( 5*n*n - 4).is_integer() or sqrt( 5*n*n + 4).is_integer())
Possibly a not very efficient solution - using the close formula is more efficient (see Sven's answer), but you can do this:
def fibs():
a,b = 0,1
yield a
yield b
while True:
a,b = b,a+b
yield b
n = int(raw_input("please, enter a number "))
for fib in fibs():
if n == fib:
print "your number is a Fibonacci number!"
break
if fib > n:
print "your number is not a Fibonacci number!"
break
The fibs generator gives you the list of Fibonacci numbers. You can go through the list, and every number you can check if it's equal to the one the user entered (in which case you're done), or if it's bigger than the one the user entered (and also in this case you're done).
I hope this is useful, at least to understand Python generators.
x = int(input("Enter a number: "))
A = [0, 1]
for i in range(2,720):
A.append(A[i-1]+A[i-2])
bool=False
for i in range(2,720):
if x==A[i]:
bool=True
break
if bool==True:
print "Found,Index is:",i+1
else:
print "Not Found"
Related
We've been given a challenge to write a program that prints prime factors of an input number. We're given an outline: the program checks for factors of the original number; each such factor gets one point. Then, if that factor is prime, it gets another point. Each factor with two points gets printed.
Here's what I have so far.
print('Please enter a number')
x = int(input('Number:'))
a = int(0)
b = int(0)
c = int(1)
d = int(0)
counter = int(0)
while (a < x-1):
a = a + 1
counter = 0
if (x / a % 1 == 0):
b = a
counter = counter + 1
while(c < b - 1):
c = c + 1
if((b / c) % 1 != 0):
d = b
counter = counter + 1
if(counter == 2):
print(d)
With input of 15, I get 3 and 5, but also 15 (wrong). With 24, I get 3, 4, 6, 8, and 12; several of these are not prime.
I believe the issue lies somewhere in the innermost loop, but I can't pinpoint the problem.
At first the issue was I wasn't resetting the "counter", so future factors would exceed 2 "points" and nothing would print. I fixed that by resetting it before it enters the innermost loop, but sadly, that didn't fix the problem.
I've also tried getting rid of 'b' and 'd' and just using two variables to see if I was somehow overcomplicating it, but that didn't help either.
EDIT: Edited slightly for clarity.
Your first sentence was enough of a clue for me to unravel the rest of your posting. Your main problems are loop handling and logic of determining a prime factor.
In general, I see your program design as
Input target number
Find each factor of the number
For each factor, determine whether the factor is prime. If so, print it.
Now, let's look at the innermost loop:
while(c < b - 1):
c = c + 1
if((b / c) % 1 != 0):
d = b
counter = counter + 1
if(counter == 2):
print(d)
As a styling note, please explain why you are building for logic from while loops; this makes your program harder to read. Variable d does nothing for you. Also, your handling of counter is an extra complication: any time you determine that b is a prime number, then simply print it.
The main problem is your logical decision point: you look for factors of b. However, rather than waiting until you know b is prime, you print it as soon as you discover any smaller number that doesn't divide b. Since b-1 is rarely a factor of b (only when b=2), then you will erroneously identify any b value as a prime number.
Instead, you have to wait until you have tried all possible factors. Something like this:
is_prime = True
for c in range(2, b):
if b % c == 0:
is_prime = False
break
if is_prime:
print(b)
There are more "Pythonic" ways to do this, but I think that this is more within your current programming sophistication. If it's necessary to fulfill your assignment, you can add a point only when you've found no factors, and then check the count after you leave the for loop.
Can you take it from there?
I'm not entirely sure I follow you're problem description, but here is my attempt at interpreting it as best I can:
import math
def is_factor(n,m):
return m % n == 0
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def assign_points(n):
for i in range(1,n+1):
if is_factor(i,n) and is_prime(i):
print('two points for: ', i)
elif is_factor(i,n):
print('one point for: ', i)
print(assign_points(15))
The problem statement goes like this:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Here is my solution:
x=2520.0
list=[]
true_list=[11.0, 12.0, 13.0, 14.0, 16.0, 17.0, 18.0, 19.0, 20.0]
b=1
def test():
for n in true_list:
z=x/n
if z%2==0:
list.append(n)
while b==1:
test()
if list==true_list:
b=2
print x
else:
x=x+20
list=[]
-> Basically, I have defined an empty list which gets filled up by the function test(). What test() does is it checks if the given number (x in this case) is evenly divisible by values from 11-20. If it is, it places that value(between 11-20) in the empty list.
When test() has run it's course, the program checks whether the list is equal to a predefined true_list which contains all numbers from 11-20. If it is, x is printed. Else, the program continues after incrementing the value of x.
This means that if list is equal to true_list, all the numbers from 11-20 are evenly dividing our number (x), which is what's asked in the problem.
It gives the answer: 465585120.0 after running for a minute or so. This happens to be incorrect. I do not know why that is. I've been trying to solve this for 8+ hours now and am at my wit's end. What is the error?
You do not need to read ahead, but in case you have queries about why I've used certain things in my solution, then I've addressed some of them here:
->I have not used all 20 numbers in true_list to speed up the program as any number evenly divisible by 11-20 is also evenly divisible by 1-20 as well.
->I have used x=x+20 to speed up the program because it is just as valid as x=x+1 or x+2;only, it is faster.
->I have used float values because I am using z=x/n in the function 'test()', and i do not want to chop off the decimal part because doing that would make even float values eligible for the subsequent operation i.e. z%2.
example:
1) with int values:
x=17
n=2
z=x/n=8
Here, z%2==0 is valid which should not be the case since it is not actually valid in mathematics.
2) with float values:
x=17.0
n=2.0
z=x/n=8.5
Here, z%n != 0 which is how it should be.
Like other people have mentioned just find the lcm, but here is a simple way to do it. Just remember lcm(a, b, c) = lcm(a, lcm(b, c)). That's all this is:
from fractions import gcd
print(reduce(lambda a, b: a * b / gcd(a, b), range(1, 21)))
If you want to write your own gcd function, it works like this (https://en.wikipedia.org/wiki/Euclidean_algorithm):
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
Tht % operator is called the "modulus" operator. In english: a % b is read "a mod b" and means "the remainder of a/b". So 100%3=1 and 12%5=2.
A common way to check divisibility is to check "Does my number modulo my divisor equal 0?". Or in code:
if a%b == 0:
print("b divides a!")
In your code you want to check if n divides x. You checked:
z=x/n
if z%2==0:
print("n divides x?") #No not really
z is the quotient of x and n. if z%2==0 can be interpreted as "If z is divisible by 2".
So you are asking "Is the quotient of x and n divisible by 2?" Which of course is nowhere close to what you want. Instead simply do
if x%n==0:
print("n divides x?") # YES!
I suggest you do a couple python tutorials so that you can get the basics down before attempting problems. :)
If you need anymore help let me know. :)
First of all as I stated in the comment, why are you trying to do it the brute force way? You could much easier calculate the LCM of the numbers 1 through to 20 in a couple of seconds.
Second of all, your line of code,
if z%2==0:
list.append(n)
That essentially gives you double the answer you want, as this statement causes you to calculate the LCM*2, as it must divide into an extra factor of 2.
The correct answer is 232792560, which I calculated using a piece of paper and a calculator in <20 seconds.
As you can see, the answer you are getting is double that
<-- Edit my previous code was wrong. this one works----->
You can correct this by doing:
x=2520.0
list=[]
true_list=[11.0, 12.0, 13.0, 14.0, 16.0, 17.0, 18.0, 19.0, 20.0]
b=1
def test():
for n in true_list:
if x%n==0:
list.append(n)
while b==1:
test()
if list==true_list:
b=2
print(x)
else:
x=x+20
list=[]
This is how you can do it by working out the LCM:
allFactors={}
#for each divisor (ignore 1 as it can divide into everything)
for n in range(2,21,1):
factors={}
i=2
while i<=n:
while n%i==0:
try:
factors[i]+=1
except KeyError:
factors[i]=1
n=n/i
i+=1
for pf,v in factors.iteritems():
try:
if allFactors[pf] < v:
allFactors[pf]=v
except KeyError:
allFactors[pf]=v
lcm=1
for pf,v in allFactors.iteritems():
lcm=lcm*(int(pf)**v)
print(lcm)
There are many ways to solve this problem. Since you're doing an early exercise from Project Euler, I suppose you'd like to develop an approach that helps you understand the basic Python constructs (as opposed to the "batteries included" approach with gcd and so on).
Here's a basic approach, not efficient in run time or developer time :) but a decent exercise:
found = None
n = 0
while not found:
n += 1
for d in xrange(2,21):
if n % d:
break
else:
found = n
print found
Which goes like this:
Examine a numerator n starting at 0. (You could actually start at 2520 since we know the answer must be no smaller than the answer to the 1-10 case, but that's a tiny optimization.)
Loop forever until a solution is found. (In a real-world program, you would probably put in some kind of safety check so this can't run forever, but this is fine for what we're doing.)
If we haven't found a solution yet, bump the numerator up by one for the next round.
Divide the numerator by a denominator d in the 2-20 range. If any value of d results in a non-zero remainder, break out of the loop - no point in testing the remaining denominators. (If we wanted to be more efficient, we could use xrange(2,n) since there is no point in dividing by a value greater than the numerator. If efficiency was an extreme concern, like if the range was vastly larger (2-1000 instead of 2-20), we could actually use xrange(2,floor(sqrt(n)) since there is no possibility of no remainder for a divisor great than the square root).
If we make it all the way through the for loop without breaking out early, the else clause operates, and we record the curent value of the numerator - this is the solution.
This approach is clearly brute force. It's fine as a learning exercise. For larger versions of the same problem, you'd be much better off using Euclid's algorithm and hardware-aware optimizations.
import time
start_time = time.time()
for i in range(2520,10000000000):
if i % 11 == 0 and\
i % 12 == 0 and\
i % 13 == 0 and\
i % 14 == 0 and\
i % 15 == 0 and\
i % 16 == 0 and\
i % 17 == 0 and\
i % 18 == 0 and\
i % 19 == 0 and\
i % 20 == 0:
print(i)
break
print(time.time() - start_time," seconds")
You can find the LCM of the Prime Numbers and the Composite Numbers separately, and then find the LCM of their LCMs. Gets the job done in almost a second! Here's my code:
import time
start_time = time.time()
nums = []
primeNums = []
allNums = []
def findFactors(num):
factors = []
for i in range(1, num + 1):
if num % i == 0:
if i not in factors:
factors.append(i)
x = int(num / i)
factors.append(x)
else:
break
return factors
def isDivisibleByAll(number, numbers):
isDivisbleBy = []
for num in numbers:
if number % num == 0:
isDivisbleBy.append(num)
return isDivisbleBy == numbers
for i in range(11, 21):
nums.append(i)
for num in nums:
if findFactors(num) == [1, num]:
primeNums.append(num)
nums.remove(num)
currentNum = nums[-1]
currentPrimeNum = primeNums[-1]
while isDivisibleByAll(currentNum, nums) == False:
currentNum = currentNum + nums[-1]
print(currentNum)
while isDivisibleByAll(currentPrimeNum, primeNums) == False:
currentPrimeNum = currentPrimeNum + primeNums[-1]
print(currentPrimeNum)
allNums.append(currentNum)
allNums.append(currentPrimeNum)
currentAllNum = allNums[-1]
while isDivisibleByAll(currentAllNum, nums) == False:
currentAllNum = currentAllNum + allNums[-1]
print(currentAllNum)
print(currentNum, currentPrimeNum, currentAllNum)
end_time = time.time()
print("Time taken: ", end_time - start_time)
A more efficient and shorter way of solving this problem will be the code mentioned below. So, as we know from the question that number that is divisible from all numbers between 1 to 10 is 2520. And we know that the factors of x are also the factors of yx. So, we can create a function that checks whether the number is divisible from all the numbers from 11 to 20. And we can make a while loop in which will increment the value of x by 2520 until the value of x is the answer. This method takes less than a second(on my i5 machine and 0.6083979606628418 seconds exactly).
def isdivisiblebyall(n):
for i in range(11, 21):
if n % i != 0:
return False
return True
no = 2520
while not isdivisiblebyall(no):
## if number is not divisible by range of 11 to 20 the value of 'no' will be incremented by 2520
no+=2520
print(no)
I have to make a program that from random numbers with N digits, which N is given by user, the program must print the first prime number it finds.
However, I have to check if a number is prime using the following and only equation: a^p=a mod p. (a is a random number and takes different values each time).
If p passes the test 10 times, then it's a prime, if it fails even once, it's not.
My problem is that "a^p = a mod p" isn't always working. My pals said that it's right and it should work.
Here's my code:
from __future__ import division
import random
found = False
flag = True
def prime(p):
i=0
flag = True
while (i<10) and (flag == True):
i+=1
a=random.randint(1,10)
if a**p!=a%p:
flag=False
break
if flag==True:
return 1
else:
return 0
n = int(raw_input("Enter length: "))
if n==0:
print "Enter another value except: 0"
while found==False:
if n!=0:
x=(10**(n-1))
y=(10**n - 1)
num = random.randrange(x, y)
if prime(num):
print str(num) + " is a prime number"
found=True
else:
print str(num) + " is not a prime number"
The problem is because of the difference between mathematical notation and the Python equivalent.
You have to use Fermat's little theorem to do a probabilistic primality test. The relevant formula is a^p = a (mod p). Note that the (mod p) applies to the whole equation and not only to the right side.
Example: 11 = 6 (mod 5) in math (because 11/5 = 2 with remainder 1, just as 6/5 = 1 with remainder 1), but 11 != 6%5 because 11 != 1.
You have to do %p on both sides of the equation or better yet, use Python's 3 parameter pow function that does exactly what you need (copied from tobias_k's comment).
I am attempting to do Project Euler problem #2. Which is:
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
However the terminal window hangs when I use the following code with 4000000. Smaller numbers run ok. Is there something about this code that is really inefficient, hence the lagginess?
n = int(raw_input("Enter the start number: "))
def fib_generator():
a, b = 0, 1
yield 0
while True:
a, b = b, a + b
yield a
def even_sum(fib_seq):
seq = []
seq = [next(fib_seq) for number in range(n)]
seq = [number for number in seq if number % 2 == 0]
return sum(seq)
def start():
fib = fib_generator()
even_sum = even_sum(fib)
print even_sum
start()
You have a bug. You're generating the first 4,000,000 Fibonacci numbers, but the problem statement only asks for those Fibonacci numbers whose values are not more than 4,000,000.
Since the Fibonacci numbers grow exponentially (Fn ~ 1.618n), you're generating some numbers with a very large number of digits (log10 Fn ~ n / 5) and that will take an immense amount of time.
Fix the bug, and you'll be okay.
You just need to add logic to stop when the next fibonacci number exceeds 4000000.
Also, I spy a potential problem with this line:
def start():
fib = fib_generator()
even_sum = even_sum(fib) #<--- right here
print even_sum
It isn't good to have a variable name the same as the function name.
Yes, there is something inefficient in your code, you load a very long list into memory twice, with your two seq = ... statements. Why not try one generator expression rather than two list comprehensions? Also, you could alter your Fibonacci generator to stop at a certain number:
def fib_generator(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
def even_sum(fib_seq):
seq = (number for number in fib_seq if not number % 2)
return sum(seq)
def start():
n = int(raw_input('Enter max constraint: '))
fib_seq = fib_generator(n)
even_sum1 = even_sum(fib_seq)
print even_sum1
start()
This ran pretty fast for me
lst = []
num1 = 1
num2 = 2
sum = 0
jump = 0
next = 0
while next<4000000:
next = num1 + num2
if next<4000000:
if jump ==0:
num1 = next
jump = 1
else:
num2 = next
jump = 0
if next%2 == 0:
lst.append(next)
for item in lst:
sum+=item
print ''
print "Sum: ",
print sum
I was about to code a program which evaluates a polynomial. But the code below is just a try-out for that. The code below gives an output that stops when "counter = t"... I want it to give an output up to when counter=0. How can that be? I wanted to treat every number(input) as a coefficient of the polynomial. If I was successful doing this, I'm planning to make a list then for every, say, element in the list, I will then multiply it to a certain number raised to its index then add them up so that I've evaluated a polynomial.. Am I clear? And will my plan work out?? Thank you so much.. Please help..
t = input("Enter degree of Polynomial: ")
while t < 0:
print ("Not possible! ")
t = input("Enter degree of Polynomial: ")
counter = 0
while counter < t:
x = input("n: ")
if x <= 0:
print "Not possible!"
else:
print x**t
t-=1
counter += 1
THe ouput goes like this:
Enter degree of polynomial: 5
n: 5
3125
n:4
256
n:3
27
then it ends.. it should continue asking for an input n up to five times..
Try to use raw_input() and keep in mind that raw_input() returns always a string. So you have to convert the returned string to an integer like:
>>> x = int(raw_input("foo: "))
Then it is possible to test something like x > 2 etc. Without casting to integers the following would happen:
>>> "2" > 1
True
>>> "2" > 3
True
First of all: Well done - it's only a little mistake: Remove the "syntactic whitespace" in your last line, or remove it completly
Secondly: Don't forget to add the values ;-) - and with regards to your headline, this is best done with a python list.
The problem seems (to me) that you are having the loop depend on 2 variables, where you perhaps expected it to be only dependent on 1.
Perhaps this works a little better:
while t > 0:
x = input("n: ")
if x <= 0:
print "Not possible!"
else:
print x**t
t-=1
Something like this?
while True:
degree = int(raw_input("Enter degree of Polynomial: "))
if degree >= 0:
break
print ("Not possible!")
x = float(raw_input("x = "))
y = 0.0
for exponent in reversed(range(degree)):
k = float(raw_input("k[{0}] = ".format(exponent)))
y += k * (x ** exponent)
print("y = ", y)
This solves a polynomial of the form:
y = (k[N-1] * (x ^ N-1) + (k[N-2] * (x ^ N-2) + ... + k[0]