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]
Related
i am looking for help. We need to write a program that prints all numbers in the range of (n -20,n + 20). In addition, the program asks you beforehand to input a number. If that number is not even or multiple of 10, you need to take a guess again. Only if the number is even and multiple by 10 the program prints the range aforementioned. I struggle with that.
I came up with that solution:
i = int(input("please enter a number: "))
while (i % 10 == 0) and ((i % 2) == 0):
x = 20
while (x >= 0):
print(i - x)
x = x - 1
break
but it will only print the range n-20 and not +20 and it also won't ask you again if you input a false number.
I know there is also the possibility to use for I in range() but I am at a loss for ideas at the moment.
Thank you!
You can simply do:
while True:
i = int(input("please enter a number: "))
if i % 10 == 0:
for x in range(i-20,i+21):
print(x)
break
It will keep on asking until it satisfies the condition.
Better make use of range, something like:
x = 20
for number in range(i - x, i + x + 1):
print(number)
Note: range(1, 5) creates a generator which yields the numbers 1 to 4, excluding 5. Thus the i + 20 + 1.
Doing it the hard way: you want to start from i-20, so:
n = i - 20
and go to i+20, so:
while n < i+20:
print(n)
n += 1
All there is to it.
Or, the easy way, aka one liner using range
print(range(i-20, i+20), sep="\n")
Start with
i = 1
while not (i % 10 == 0):
i = int(input("please enter a number: "))
to keep asking until valid input is entered and the problem is solved.
I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)
I am writing a program in Python that defines a function that takes a single argument. The function has to be a while loop the returns the largest power of 16 that it is equal to. However, I am not sure how to write the while loop.
Python Docs
while True:
n = input("Please enter 'hello':")
if n.strip() == 'hello':
break
so, in layman's terms
while <condition>:
...
I couldn't completely understand your question but here's how to do a while loop to get the x to the 16th power of an input:
def loop_function(x):
y = 1
start = x
while y != 16:
result = start * x
start = result
y += 1
return result
print loop_function(3)
The above code will return the answer to 3^16 which is 43046721
You can even make this a broader function two arguements
def loop_function(x, y):
z = 1
start = x
while z != z:
result = start * x
start = result
z += 1
return result
print loop_function(3, 2)
The above code will return 9 i.e 3^2
Here is a pretty simple example of what I mean:
def work():
x = input("Give me a number : ")
if x in range(30000):
print "hello"
So as long as I put in a number in that range it will print hello, but what if I want it to only accept an odd number in that range? I tried defining a separate function that's range is only odd numbers like this:
def work():
a = input("Give me a number : ")
if a in range(30000):
X = range(30001)
y = (2*X)-1
if a in range(y):
print "hello"
but that doesn't work.
if 0 <= x < 30000 and x % 2 == 1:
print "hello"
Note: Python 2.x didn't do the optimisation - so this only applies to Python 3.x's range
You can take advantage that xrange (or range in 3.x - needn't generate the list and can do membership testing...) by providing it with a step parameter as well as the start and end stops...
So, you could use to check for odd numbers up until 30000:
if number in xrange(1, 30000, 2):
pass
eg:
>>> for number in (1, 2, 3, 999999):
print number in xrange(1, 30000, 2)
True
False
True
False
An odd number doesn't divide by 2, so you verify this using the modulo operator:
x % 2
In Python a number not equal to 0 is considered True, so this will do the work:
def work():
x = input("Give me a number : ")
if x in range(30000) and x % 2:
print "hello"
If you wanted to list the numbers, here is a general way to do this (but you should just use the range() function):
def every(increment, range, offset=0):
current = offset
yield current
while(1):
current += increment
if current < range:
yield current
else:
break
So for odds to 30,000 it would be :
for i in every(2, 30000, 1):
...
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"