The calculation of the integer part of the square root of a number can be done by trial and error, starting from 1, by executing the square until the result is less than or equal to the starting value of which is calculated by the root.
The following program returns the integer part of the root
def radice(x):
z = 0
t = 0
while True:
t = z*z
if t > x:
z -= 1
return z
z += 1
radice(17) // 4
Will be possible to write it without using functions and break?
Here is my code witout function but I dont' know how to write the same algo with no break
z = 0
t = 0
while True:
t = z*z
if t > x:
z -= 1
break
z += 1
print 'The integer part of the root is: ', z
This should suffice:
>>> int(17**0.5)
4
17**0.5 generates the square root of 17, and int basically removes the decimals, leaving you with the "integer part of the root".
Without using any functions, and if you want an integer result, complex code (like your own) is needed. However, if a float will do, then you could try this:
>>> (17**0.5)//1
4.0
This essentially does the same as the int call, but will return a float if either side is a float.
As you said the integer part of the square root of a number can be done by trial and error, starting from 1, by executing the square until the result is less than or equal to the starting value of which is calculated by the root.
Said that you can write the code without using function and break statements; here is the code:
n = input("insert a number: ")
r = 1
while (r * r <= n):
r = r + 1
print "the result is:", r -1
Parens are for clarity, not required
>>> (17**.5)-(17**.5)%1
4.0
Ok, let's think logically.
You cannot use break, so the only way to get out of the while loop is to break its condition.
If it's True, it cannot be broken, so we have to think about the proper condition to stop iterating. And this condition is already used in your algorithm: you exit when t > x, or z * z > x. So the condition to continue iteration should be the opposite, i.e. z * z <= x. And we have this simple solution.
x = 17
z = 0
while z * z <= x:
z += 1
print 'The integer part of the root is: ', z - 1
As a general rule, try to shy away from those while True: loops. While they are sometimes useful, they're generally harder to read and understand, this is probably why your teacher limits the use of break. The function was prohibited probably because return is just another way of escaping the loop. But those are exceptional: the normal way to end a loop is to break its condition, so this is how it should be written.
Related
So its just a simple prime factorization calculator
Im not sure why its infinitely looping. Im pretty new to python and not entirely sure on how the while loop works
def print_prime_factors(number):
x = 2
while x < number:
if number % x == 0:
y = number/x
print(str(x)+",")
y = number
if x > y:
break
x = x + 1
print_prime_factors(100)
# Should print 2,2,5,5
# DO NOT DELETE THIS COMMENT```
Your code has an indentation error.
This line:
x = x + 1
should be shifted over one indent. You're only incrementing x whenever it is a factor of the number, which means that the program will enter an infinite loop by repeatedly checking whether number is divisible by a non-factor of number.
after the first iteration x changes and the if statements is never true again, which makes x never changes again. Seens to be just indentation problem.
(1) The first bug is, as others have said, that your line x = x + 1 that increments candidate x should be unindented one level, so it's under the while-loop.
(2) But you also have a bug with what you're doing with quotient y, it's mystifying.
When you identify that x is a factor of number, just print x. You compute the quotient y = number/x, silently throw it away, then assign y = number, which again gets thrown away. You could have just directly tested if x > number: ... break.
but even that is roundabout. Your while-loop that starts x at 2, increments x by +1, and stops when x > number, is really just a for-loop in disguise: for x in range(2, number+1): ...
But you can show we strictly only need to do:
for x in range(2, ceil(sqrt(number)+1): ... where we use math.sqrt, math.ceil
...really you need to store the quotient between iterations, and when it gets to 1 you know you can terminate early; you've found all the divisors of number
I have a general idea of what to do, but my code is a mess and I'm having some trouble writing the algorithm in python for
cos(x)=1-(x^2)/2!+(x^4)/4!-(x^6)/6!+...
where x is in radians, computing cos(x) after 20 terms using while loops. So far what I've written is
x = float(input("Enter a value for x in degrees."))
x = (x*3.14159)/180
num_of_terms = 0
num = 1.0 ##numerator
y = 1.0
cosx = 1.0
while num_of_terms<1:
num_of_terms+=1
cosx = (num/y)
while num_of_terms>=1 and num_of_terms<=20:
num_of_terms+=1
num = num*(x*x)
y = y*num_of_terms*(num_of_terms-1)
if num_of_terms%2==0:
cosx = cosx+(-num/y)
else:
cosx = cosx+(num/y)
print(cosx)
I don't know how close I even am to being correct (I know it's wrong in at least some places so I can't properly check using math.cos) but the main question I have is how to switch from positive --> negative each term. The assignment states that I cannot use exponentiation operators, and before I was trying to do something like
x = float(input("Enter a value for x in degrees."))
x = (x*3.14)/180
num_of_terms = 0
y = 0
z = 1
cosx = ((-1)**(z-1))*((x**z)/(y))
so that the sign would switch for every other term. Now I have (as you can see above)
if num_of_terms%2==0:
cosx = cosx+(-num/y)
else:
cosx = cosx+(num/y)
which is incorrect, or at least the output I'm getting is incorrect.
You can handle the sign quite simply:
sign = -1
while num_of_terms <= 20:
sign = -sign
...
cosx += sign * num/y
You also have a structure problem in your loops: the first loop will terminate after one iteration ... except you've properly prevented it from getting back there. This is poor use of a loop.
Just initialize your variables before the loop, and then proceed as expected. Since you know how many times to iterate, use a for instead of a while.
cosx = (num/y)
for num_of_terms in range(1, 21):
...
You will find other computational problems in your code. Print out values each time through the loop to help track your execution and computations. At the start, just go through 3 or 4 times instead of 20.
For the factorial, keep a running product: it's like a running sum, except that you initialize it at 1, and multiply each time through the loop.
Okay; stick with the while. Now, manage your loop index and computational index. If you're doing term #1, what should the exponent be? What numbers do you multiply into y? Now identify the same values for term #2 and term #3.
More directly, stick in a print statement to track num_of_terms, y, and cosx. When you're doing term #3, what is y? It should be 4! or 6! (depending on how you number your terms), but it's not. Where did you go wrong?
Your problem is in the computation of the factorial. You're multiplying by num_of_terms, which only increments by one each time through the loop - you need something that changes by 2 each time through the loop. At least you're correctly multiplying both that number and the number-1.
So, I read the pseudocode from http://www.javascripter.net/math/primes/miller_rabin_pseudocode.txt, and thought it would be cool to write it in python. So I wrote this:
n = input('Enter a number to test ')
n = int(n)
a=int(5)
d = n - 1
s = 0
while (d % 2 == 0):
s = s + 1
d = int(d/2)
x = a**d
x = x % n
if (x==1 or x==(n-1)):
print("probably prime")
r = int(1)
while(r<(s-1)):
x = x**2
x = x%n
if (x==1):
print ("composite")
if (x==(n-1)):
print ("probably prime")
print("if nothing above is printed n is composite")
It worked pretty well, but as soon as I got into six digit numbers it was incredibly slow. So I found some code of http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python, and it was almost instant, even with large (10^30) numbers.
So, what did I do wrong int the above code that made it so much slower?
You should also replace:
x = a**d
x = x % n
With:
x = pow(a, d, n)
Which does modular exponentiation much faster than the naive method, as it takes modulus at each multiply, rather than building a ginormous number and taking modulus after.
The second loop in the linked code does only 5 iterations at maximum, whereas your does something like log(n).
EDIT:
Or even more - the "r" variable is never modified, so the loop's exit condition will never be satisfied. The only possibility to exit the loop are the breaks.
This is a rather difficult challenge for me as I am new to Python. How would I write a program in python based off this sequence function:
http://oeis.org/A063655
and does the following:
It asks for the value of the sequence and returns the corresponding number. For example, the number corresponding to the 10th value of the sequence is 7. I'd like to be able to do this for values over 300,000,000.
So, the final product would look like this:
Enter a value: 4
[7]
Any ideas where to start? I have a framework to generate sequences where (x) would be to put a mathematical equation or numbers, but I'm not exactly sure how to go from here or how to implement the "Enter a value" portion:
import math
def my_deltas():
while True:
yield (x)
yield (x)
def numbers(start, deltas, max):
i=start
while i<=max:
yield i
i+=next(deltas)
print(','.join(str(i) for i in numbers((x), my_deltas(),(x))))
If you're looking to have your computer keep track of over 300,000,000 elements of a sequence, if each is a 4 byte integer, you'll need at least 300,000,000 * 4bytes, or over 1.1GB of space to store all the values. I assume generating the sequence would also take a really long time, so generating the whole sequence again each time the user wants a value is not quite optimal either. I am a little confused about how you are trying to approach this exactly.
To get a value from the user is simple: you can use val = input("What is your value? ") where val is the variable you store it in.
EDIT:
It seems like a quick and simple approach would be this way, with a reasonable number of steps for each value (unless the value is prime...but lets keep the concept simple for now): You'd need the integer less than or equal to the square root of n (start_int = n ** .5), and from there you test each integer below to see if it divides n, first converting start_int to an integer with start_int = int(start_int) (which gives you the floor of start_int), like so: while (n % start_int) != 0: start_int = start_int - 1, decrement by one, and then set b = start_int. Something similar to find d, but you'll have to figure that part out. Note that % is the modulus operator (if you don't know what that is, you can read up on it, google: 'modulus python'), and ** is exponentiation. You can then return a value with the return statement. Your function would look something like this (lines starting with # are comments and python skips over them):
def find_number(value):
#using value instead of n
start_int = value ** .5
start_int = int(start_int)
while (n % start_int) != 0:
#same thing as start_int = start_int - 1
start_int -= 1
b = start_int
#...more code here
semiperimeter = b + d
return semiperimeter
#Let's use this function now!
#store
my_val = input("Enter a value: ")
my_number = find_number(my_val)
print my_number
There are many introductory guides to Python, and I would suggest you go through one first before tackling implementing a problem like this. If you already know how to program in another language you can just skim a guide to Python's syntax.
Don't forget to choose this answer if it helped!
from math import sqrt, floor
def A063655(n):
for i in range(floor(sqrt(n)), 0, -1):
j = floor(n / i)
if i * j == n:
return i + j
if __name__ == '__main__':
my_value = int(input("Enter a value: "))
my_number = A063655(my_value)
print(my_number)
USAGE
> python3 test.py
Enter a value: 10
7
> python3 test.py
Enter a value: 350000
1185
>
I'm again working on Project Euler, this time problem #4. The point of this script is to find the largest palindromic product of two three digit numbers. I thought it was fairly straightforward to solve, but I'm getting an answer that is too low. More specifically, I am getting 580085, and the answer is 906609.
Could someone tell me what about this is incorrect?
#!/usr/bin/env python
# encoding: utf-8
"""
P4.py
Created by Andrew Levenson on 2010-06-29.
Copyright (c) 2010 __MyCompanyName__. All rights reserved.
"""
import sys
import os
def main():
for x in range(100, 1000):
for y in range(100, 1000):
z = str( x * y )
s = str( z[::-1] ) # Reverse z
if z == s:
t = z
print t
if __name__ == '__main__':
main()
Your code doesn't make sure it prints the largest product, since there could later be a smaller product which replaces it. To fix it, initialize t to zero, and replace your condition with
if z==s and int(z)>t:
t = int(z)
Or equivalently,
if z==s:
t = max(t,int(z))
Edit: Fixed int/string issues above. It's a bit cleaner to avoid the conversion to string and back to int like this though:
def isPalindrome(x):
s = str(x)
return s == s[::-1]
t = 0
for x in range(100, 1000):
for y in range(100, 1000):
z = x * y
if isPalindrome(z) and z > t:
t = z
print t
Here's a tricky but correct way to do it in a single expression...:
def main():
print max(p for x in range(100, 1000) for y in range(x, 1000)
for p in (x * y,) if str(p) == str(p)[::-1])
The tricky part is the single-item for p clause which plays the role of an assignment (just to stop recomputing that product several times;-).
Note that the accepted answer is wrong (as are several others), because it looks for the string "max", which is different from the int max -- try running it, and you'll see!-)
The problem is to find the largest palindrome. You have nothing here to find the largest, simply the last. You assumed the last one would be the largest, but that isn't so because you are examining the entire ZxZ square of possibilities.
For example, you are considering 200*101 after you've considered 101*999.
Because of the way you're using the 2 for loops you're going to get the number with the largest x value, not the largest product.
906609 = 993 * 913
Then x keeps incrementing and the next palindrome is:
580085 = 995 * 583
You need a variable to keep track of the largest palindrome you've found.
def main():
largest = 0
for x in range(100, 1000):
for y in range(100, 1000):
z = str( x * y )
s = str( z[::-1] ) # Reverse z
if z == s:
t = int(z)
if t > largest:
largest = t
print largest
You need to add a check if the one you found is larger than the one you already have.
I'll add that you can save yourself some time in this test. All 6 digit palindromes must be divisible by 11. Therefore at least one of the factors must be divisible by 11.