from math import *
def prime():
a = 0
b = 0
x = 2*a+1
y = b
for a in range (1,5000) and b in range (0,5000) and y<x :
ctr = 0
if (x % y == 0):
ctr += 1
return [None]
else:
primes = (x)
ctr+= 1
return [None]
print (primes[999]);
I have a problem I need to solve but when it gets to the modulo ( %) sign it says TypeError: 'bool' object is not iterable"
Instead of comparing the values, you are assigning 0 to x % y, which is not possible. You can fix it like this
if (x % y == 0):
After fixing that,
for a in range (1,5000) and b in range (0,5000) and y<x :
this line will not work, you have to split the loops like this
for a in range (1,5000):
for b in range (0,5000):
...
...
The modulo sign is fine, note the ^ in the error message.
File "so-modulo-test.py", line 11
if (x % y = 0):
^
SyntaxError: invalid syntax
= indicates an assignment statement. You want ==, the equal comparison operator, as in
if x % y == 0:
Additionally, and is the logical AND, and not to be confused with how a human would talk. Your loop should look like:
for a in range (1,5000):
for b in range (0, x):
...
Related
for x in range(0,501):
m = x ** 2
if m > 500:
break
print (m,x)
#this outputs a value for the highest square that is above 500 when I want the highest that is below 500
Your code assigns the value of m before breaking, so it stores that value before breaking.
Try this instead:
for x in range(0, 501):
if (x + 1) ** 2 > 500:
m = x ** 2
break
print(x, m)
Notes
Since you're new and it sounds like you're still learning about coding, I will add a few pointers.
First, you don't need to assign value to x to test the value of a function applied to it. Second, a better approach would be to use a while loop rather than a for loop, like this:
x = 0
while (x + 1) ** 2 < 500:
x = x + 1
print(x, x**2)
Additionally, loops are slow, brute force ways to write code. Sometimes that's okay or necessary, but when there's a very efficient way to solve a problem without a loop, it's usually better to use it. For example, to find the smallest integer whose square is less than or equal to x, we can use:
import math
def int_root(x):
return int(math.sqrt(x))
int_root(500)
The problem is you are breaking the loop once the value for m has already exceeded 500. So when you try to print the value for m it is the value that is above 500.
A solution would be to use the value of x and because we know that the desired value would be one less than this, we can compute m like so:
for x in range(501):
m = x ** 2
if m > 500:
break
x -= 1
print(x**2, x)
Yet another approach:
n = 0
for x in range(500):
m, n = n, (x + 1) ** 2
if n > 500:
break
print(m, x) # 484 22
As mentioned by others the issue with your code is that when you check to see if m is greater than 500, if m is exceeding 500 the program breaks the loop, the catch is that m has already been given the value that is over 500 and as such prints that out instead of the desired one before. To counteract this we can add to x and square the result to see if that answer is over 500 and if it is the program will break.
def squareless(top):
for x in range(0, top):
if (x + 1) ** 2 > top + 1:
m = x ** 2
print(x, m)
break
squareless(500)
You break the loop after m already exceeds 500, so (529, 23) is expected. Note that 23 ** 2 = 529. You want to retreat to the previous x and previous m in this case.
for x in range(0,501):
m = x ** 2
if m > 500:
x -= 1
m = x ** 2
break
print (m,x) # 484 22
Or check the next x to break before exceeding 500:
for x in range(0,501):
m = x ** 2
if (x+1) ** 2 > 500:
break
from random import randrange
a = randrange(1, 9)
print (a)
if (a % 2) == 0:
y = a / 2
while True:
if (y % 2) == 0:
y = y / 2
print (y)
else:
b = (a * 3) + 1
while True:
if (b % 2) == 0:
b = b / 2
else:
b = (a * 3) + 1
print (b)
"I want to make a math problem solver in python that can find a random number
between 1 and 9. Then if it is odd so it multiply it with 3 and add 1 in it and if it
is even so it divide it by two and this process keep repeating. For example a number
computer choose is 7 so :
7*3 + 1 = 22
22/2 = 11
11*3 = 33
and so on.
It shouldn't stop until the answer is 0.Here is my code in which I tried but not sure where should I make it right?"
You have too many lines in there. You need to loop to stop repeating when the number becomes 1 (it will never become 0):
from random import randrange
a = randrange(1, 9)
while a != 1:
print(a)
if a % 2 == 0:
a = a // 2
else:
a = (a * 3) + 1
print(a)
You can use the following code to check for any number or any range of numbers. This code is created by using the recursive function approach.
def f(x): #creating a function
if x!=4:
a.append(x)
if x%2==0:
while x%2==0:
x=x/2
a.append(x)
x=3*x+1
f(x)
For checking a particular value, run this:
a=[]
f(2**100+1) #2 to the power 10, plus 1
a[-1]
For checking for a range of values, run this:
for i in range(1,100):
a=[]
f(i)
print(i, "gives output" ,a)
I call it impossible maths because never reaches zero, it just keeps on looping forever Collatz problem. But this function does that, it does not take any parameter.
import random as r
def impossible_math():
x = r.ran(1,9)
while x !=0:
if x%2 ==0:
x = x/2
print(x)
else:
x = (x*3)+1
print(x)
x = impossible_math()
In numbers like 16, performing bitwise AND on all numbers from 1 to 15 gives result 0. I want to find out the first number that doesn't give 0 when bitwise AND is performed on it.
TLDR : Find smallest x such that x AND y ! = 0
y is given
You can do brute force approach:
while True:
y=int(input('y='))
x=1
while True:
if(x & y !=0):
print(x)
break
x*=2
The solution is to find the first bit from right, which is 1.
For example,
y = 16 = 0b10000
^
y = 12 = 0b1100
^
def get_x(y):
i = 0
while True:
if (y >> i) & 1 == 1:
break
i += 1
return 1 << i
This seems cleverer.
def get_x(y):
return y & (-y)
Find the lowest set bit
I'm new to programming and i'm doing the Project Euler challenges to give me a reason to learn.
Find below my very simple python code
x = 1
thirdDivide = 0
fifthDivide=0
total = 0
print('Enter the max value')
maxValue = input()
while (x != maxValue):
thirdDivide = x / 3
fifthDivide = x / 5
if (thirdDivide).is_integer():
total = total + x
x = x + 1
elif (fifthDivide).is_integer():
total = total + x
x = x + 1
print ("The sum of the multiples of 3 and 5 between 0 and " + maxValue + " is " + total)
When I run it it asks for my max value, then ceases doing anything.
Thanks!
Assuming you are in Python 3, the fixes for using strings instead of floats, or floats instead of strings, infite loop is following:
x = 1
thirdDivide = 0
fifthDivide=0
total = 0
maxValue = float(input('Enter the max value: '))
while (x != maxValue):
thirdDivide = x / 3
fifthDivide = x / 5
if (thirdDivide).is_integer():
total = total + x
elif (fifthDivide).is_integer():
total = total + x
x = x + 1
print("The sum of the multiples of 3 and 5 between 0 and " + str(maxValue) + " is " + str(total))
Note, I dont check for correctness of your algoritm and whether it calculates what it is supposed to do. But now it produces some results and compiles.
You can solve it with a functional approach using filter and reduce:
def f(acc, v): return acc + v
def g(x): return x % 3 == 0 or x % 5 == 0
print reduce(f, filter(g, range(1000)))
How it works:
filter: takes two arguments:
The first is a function g applied for every element of range(1000). g takes one argument x and check if is multiple of 3 or 5 (checking the remainder of the modulo operation %).
The second is the range from 0 to 1000.
reduce: takes two arguments:
The first is a function f that takes two arguments: an accumulator acc and a variable v that represents the current element in the list.
The second argument is the filtered range returned before by filter.
Output:
with range(10) = 23
with range(1000) = 233168
Using lambda functions (same logic just different syntax):
print reduce(lambda acc, v: acc + v, filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1000)))
You only increment x if thirdDivide.is_integer() or fifthDivide.is_integer() are true. So if neither it true, you'll just loop infinitely on the same value of x.
If neither thirdDivide nor fifthDivide is an integer, x is never updated -- you enter an infinite loop. You need to make sure you have a "base case" so that the iteration variable is always changing. Here's a slightly cleaner algorithm:
total = 0
for i in range(0, x):
if i % 3 == 0 or i % 5 == 0:
total += i
I think you'll find that for most iteration, for loops are easier to reason about. Happy coding!
As many said before, you are stuck in an infinite loop with x not being incremented. If you added a "else" statement at the end and printed the output you could see what they are talking about. You can do this in one line of code.
print(sum(x for x in range(maxValue) if x % 3 == 0 or x % 5 == 0))
I've written this function to calculate sin(x) using Taylor series to any specified degree of accuracy, 'N terms', my problem is the results aren't being returned as expected and I can't figure out why, any help would be appreciated.
What is am expecting is:
1 6.28318530718
2 -35.0585169332
3 46.5467323429
4 -30.1591274102
5 11.8995665347
6 -3.19507604213
7 0.624876542716
8 -0.0932457590621
9 0.0109834031461
What I am getting is:
1 None
2 6.28318530718
3 -35.0585169332
4 46.5467323429
5 -30.1591274102
6 11.8995665347
7 -3.19507604213
8 0.624876542716
9 -0.0932457590621
Thanks in advance.
def factorial(x):
if x <= 1:
return 1
else:
return x * factorial(x-1)
def sinNterms(x, N):
x = float(x)
while N >1:
result = x
for i in range(2, N):
power = ((2 * i)-1)
sign = 1
if i % 2 == 0:
sign = -1
else:
sign = 1
result = result + (((x ** power)*sign) / factorial(power))
return result
pi = 3.141592653589793
for i in range(1,10):
print i, sinNterms(2*pi, i)
I see that you are putting the return under the for which will break it out of the while loop. You should explain if this is what you mean to do. However, given the for i in range(1,10): means that you will ignore the first entry and return None when the input argument i is 1. Is this really what you wanted? Also, since you always exit after the calculation, you should not do a while N > 1 but use if N > 1 to avoid infinite recursion.
The reason why your results are off is because you are using range incorrectly. range(2, N) gives you a list of numbers from 2 to N-1. Thus range(2, 2) gives you an empty list.
You should calculate the range(2, N+1)
def sinNterms(x, N):
x = float(x)
while N >1:
result = x
for i in range(2, N):
Your comment explains that you have the lines of code in the wrong order. You should have
def sinNterms(x, N):
x = float(x)
result = x
# replace the while with an if since you do not need a loop
# Otherwise you would get an infinite recursion
if N > 1:
for i in range(2, N+1):
power = ((2 * i)-1)
sign = 1
if i % 2 == 0:
sign = -1
# The else is not needed as this is the default
# else:
# sign = 1
# use += operator for the calculation
result += (((x ** power)*sign) / factorial(power))
# Now return the value with the indentation under the if N > 1
return result
Note that in order to handle things set factorial to return a float not an int.
An alternative method that saves some calculations is
def sinNterms(x, N):
x = float(x)
lim = 1e-12
result = 0
sign = 1
# This range gives the odd numbers, saves calculation.
for i in range(1, 2*(N+1), 2):
# use += operator for the calculation
temp = ((x ** i)*sign) / factorial(i)
if fabs(temp) < lim:
break
result += temp
sign *= -1
return result