Loop is not repeating - python

I am trying to make this "algorithm", which will take the number and get it down to 4, 2, 1. If anyone have seen the youtube video regarding this math problem, they will understand.
done = False
while True:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num/2)
else:
print(num * 3 + 1)
if num == 1 or 2 or 4:
break
The output is this algorithm not repeating itself.
If I type in number 5 it will x3+1, and print only 16. What I want is it doing this, but keep going till the number is either 1,2 or 4. Hope yall can help :D

The error is in line if num == 1 or 2 or 4:. That always evaluates to True and thus breaks your loop.
Your intention is to have if num == 1 or num == 2 or num == 4:. Or if num in (1,2,4): to be more concise.
(Explanation of your mistake: the if statement has an expression that is being tested. You're chaining a couple of expressions with the or operator, resulting in if expr1 or expr2 or expr3. The if-expression is True if any of those OR'd expressions is True.
Your expr1 is num == 1 which is True only if num equals 1.
Your expr2 is 2 which is True always (!).
Your expr3 is 4 which is True always.
So, your if-expression is always evaluating to True.)

It isn't testing for all three of those numbers (1, 2 and 4).
Here's the fixed code:
done = False
while True:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num/2)
else:
print(num * 3 + 1)
if num == 1:
break
if num == 2:
break
if num == 4:
break

I think you want to repeat num/2 or num*3+1 every output. If you use odd number like 7, it calculates 22 and 22 is a even number and 22 is calculated 11 and it returns 34 and so on. I figure it out like this. But it always ends with 4 :)
done = False
num = int(input("Enter a number: "))
while True:
if (num % 2) == 0:
num/=2
print(num)
else:
num = num * 3 + 1
print(num)
if int(num) in [1,2,4]:
break

Related

Python program to find all prime numbers in the range 1 - n

Hi I know there are lots of solutions to this problem but I wanted some help finding out why my answer is wrong.
Here's my answer:
number = int(input("enter a number: "))
for n in range(2, number + 1):
for i in range(2, number // 2):
if n == 2:
print(n)
elif n % i == 0:
break
else:
print(n)
Here's the output on my terminal:
> enter a number: 12
2 2 2 2 3 5 5 5 7 7 7 7 9 11 11 11 11
thankss
The problem with your solution is that you haven't set up the inner loop properly. The other problem (the lesser one in my opinion) is that the print is inside of your inner loop which causes the multiple prints.
Here is a proper solution:
for n in range(2, number + 1):
isPrime = True
for i in range(2, n - 1):
if n % i == 0:
isPrime = False
if isPrime:
print(n)
thanks everyone i realised i made a lot of really silly mistakes.
i fixed my code in case anyone else sees this question and wants a solution:
number = int(input("enter the number: "))
for n in range(2, number + 1):
for i in range(2, n):
if n % i == 0:
break
else:
print(n)

"super" number in python

I have a problem with the task. The task is:
We say that number 1 is a super number. If a number x is super, then
the numbers 2x and 3x are also super. For example, since the number 1
is super, then the numbers 2 and 3 are super. As 2 and 3 are super,
then the numbers 4, 6 and 9 are super, and so on. At the same time,
numbers 10 and 7 are not super. Write a program that asks the user to
enter a natural number n. The program prints whether the entered
number is super.
And this is what I have done so far
num = int(input("Enter a natural number "))
if num <= 0:
print("That is not a natural number")
else:
if num % 5 == 0 or num % 7 == 0 or num % 11 == 0 or num % 13 == 0:
print("Number is not super.")
elif num == 1 or num % 2 == 0 or num % 3 == 0 or num % 8 == 0 or num % 9 == 0:
print("Number is super")
else:
print("Number is not super.")
The problem is that for some numbers like 62 it says that it is a super number, but it ain't..
Just following the definition of super number:
def is_super(k):
if k == 1: return True
if k % 2 == 0:
return is_super(k / 2)
if k % 3 == 0:
return is_super(k / 3)
return False
Some testing
print(is_super(9))
True
print(is_super(14))
False
print(is_super(32))
True
print(is_super(62))
False
To me it looks like you jumped in without first figuring out how you'd work it out manually.
Personally, I think the easiest way to start this would be recursively, though it'll be very inefficient with large numbers, so it's up to you if you then want to go and optimise it after doing the first version. I got it working pretty easily, but since it's a problem you need to solve, I'm not going to just copy and paste the answer.
It works something like this (psuedocode):
def is_super(i):
if i is below 1: not a super
if i is 1: is a super
if i is above 1: check if i/2 or i/3 is a super
There are some nice recursive solutions here, I'll propose a non-recursive one. As some of the comments hint, super numbers have a tell-tale factorization: they are all of the form 2x * 3y for x, y >= 0, and every integer of that form is a super number. This should become clear after some study because the only way to get a super number is to multiply an existing one by 2 or 3, and we start with 1. That leads to the following code to test for superness:
def is_super(n: int) -> bool:
if n < 1:
return False
while n % 3 == 0:
n //= 3
return n & (n - 1) == 0; // Suggested by #KellyBundy
I tried to find shortcut way to test for superness but failed to find anything better than this.
num = int(input("Enter a natural number "))
if num <= 0:
print("That is not a natural number")
else:
if num % 3 == 0:
while num % 3 == 0:
num = num / 3
print(num)
if num == 1 or num % 2 == 0 or num % 3 == 0:
print("Number is super")
else:
print("Number is not super")
elif num % 2 == 0:
while num % 2 == 0:
num = num / 2
print(num)
if num == 1 or num % 2 == 0 or num % 3 == 0:
print("Number is super")
else:
print("Number is not super")
else:
print("Number is not super")
This is what I've done so far but I don't think it will work for large numbers ?

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

Numbers without remainder python

I need to print out numbers between 1 and n(n is entered with keyboard) that do not divide by 2, 3 and 5.
I need to use while or for loops and the remainder is gotten with %.
I'm new here and I just don't understand the usage of %?
I tried something like this:
import math
print("Hey. Enter a number.")
entered_number = int(input())
for i in range(1, entered_number):
if i%2 != 0:
print("The number", i, "is ok.")
else:
pass
if i%3 != 0:
print("The number", i, "is ok.")
else:
pass
if i%5 != 0:
print("The number", i, "is ok.")
help?
You need to test for all 3 conditions in one statement, not in 3:
for i in range(1, entered_number):
if i % 2 != 0 and i % 3 != 0 and i % 5 != 0:
print("The number", i, "is ok.")
The and operators here make sure that all three conditions are met before printing.
You are testing each condition in isolation, which means that if the number is, say, 10, you are still printing The number 10 is ok. because it is not divisible by 3. For numbers that are okay, you were printing The number ... is ok. 3 times, as your code tests that it is not divisible by 3 different numbers separately, printing each time.
If something divides by 7 then:
something % 7 == 0
If something divides by 7 and 9 then:
something % 7 == 0 and something % 9 == 0
Conversely, if something divides by 7 or 9 then:
something % 7 == 0 or something % 9 == 0
Something that does not divide by 7 or 9 is given by the expression:
not (something % 7 == 0 or something % 9 == 0)
You don't require the else: pass bits from your code and one if statement with an if-expression that has three %, == bits in it should suffice.
You should probably check the three conditions at the same time:
if i%2 != 0 and i%3 != 0 and i%5 != 0:
print("The number", i, "is ok.")
Otherwise, you would print the same message several times for a single number.
Anyway, for your second question, the% operation is called modulo and it gives you the remainder of a division. For instance, 5%3 = 2 because 5 = 3*1 + 2. And when you check i%2 != 0, you actually check if i can be divided by 2.
print("Hey. Enter a number.")
entered_number = int(input())
for i in range(1, entered_number):
if i%2 != 0 and i%3 !=0 and i%5!=0:
print("The number", i, "is ok.")
a%b returns the remainder when a is divided by b. Example:
>> 5%3
2
What you are doing wrong here is that you are printing after checking a single condition so it will print even if i is divisible by other numbers. For example if i is 3, it will satisfy the first condition and therefore print that the number is ok but it is actually divisible by 3.
I saw you've solved your problem but my answer may worth reading.
This problem is actually doing filtering over a list of numbers 1..n. You can define a base function to test if number x is dividable by number y, and then use this base function to filter the list to get the result.
Here's my version.
import math
from functools import partial
print("Hey. Enter a number.")
entered_number = int(input())
def not_dividable_by(x, y):
return False if x % y == 0 else True
number_list = range(1, entered_number)
for i in [2, 3, 5]:
test_func = partial(not_dividable_by, y=i)
number_list = filter(test_func, number_list)
for number in number_list:
print("%d is OK" % (number,))

Python Beginner's Loop (Finding Primes)

I'm truly a beginner at python so I apologise for the lack of knowledge, but the reason I'm asking is that reading the Python manual and tutorial (http://docs.python.org/2.7/tutorial) I'm not unable to totally grasp how loops work. I've written some simple programs so I think I get the basics but for whatever reason this program that is meant to list all primes less than or equal to n is not working:
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
for i in range(2, p):
if p%i == 0:
p=p+1
print "%s" % p,
p=p+1
print "Done"
The output when I enter 100 for example is:
2 3 5 7 11 13 17 19 23 27 29 31 35 37 41 43 47 53 59 61 67 71 73 79 83 87 89 95 97 101 Done
Which looks almost right but for some reason contains 27, 35, 95, which are composite of course. I've been trying to pick apart the way my loop works but I just don't see where it skips checking for divisibility suddenly. I figured that if someone had a look they could explain to me what about the syntax is causing this. Thanks a bunch!
I would actually restructure the program to look like this:
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
print p,
print 'Done'
This is perhaps a more idiomatic solution (using a for loop instead of a while loop), and works perfectly.
The outer for loop iterates through all the numbers from 2 to n.
The inner one iterates to all numbers from 2 to p. If it reaches a number that divides evenly into p, then it breaks out of the inner loop.
The else block executes every time the for loop isn't broken out of (printing the prime numbers).
Then the program prints 'Done' after it finishes.
As a side note, you only need to iterate through 2 to the square root of p, since each factor has a pair. If you don't get a match there won't be any other factors after the square root, and the number will be prime.
Your code has two loops, one inside another. It should help you figure out the code if you replace the inner loop with a function. Then make sure the function is correct and can stand on its own (separate from the outer loop).
Here is my rewrite of your original code. This rewrite works perfectly.
def is_prime(n):
i = 2
while i < n:
if n%i == 0:
return False
i += 1
return True
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
if is_prime(p):
print p,
p=p+1
print "Done"
Note that is_prime() doesn't touch the loop index of the outer loop. It is a stand-alone pure function. Incrementing p inside the inner loop was the problem, and this decomposed version doesn't have the problem.
Now we can easily rewrite using for loops and I think the code gets improved:
def is_prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
n = int(raw_input("What number should I go up to? "))
for p in range(2, n+1):
if is_prime(p):
print p,
print "Done"
Note that in Python, range() never includes the upper bound that you pass in. So the inner loop, which checks for < n, we can simply call range(2, n) but for the outer loop, where we want <= n, we need to add one to n so that n will be included: range(2, n+1)
Python has some built-in stuff that is fun. You don't need to learn all these tricks right away, but here is another way you can write is_prime():
def is_prime(n):
return not any(n%i == 0 for i in range(2, n))
This works just like the for loop version of is_prime(). It sets i to values from range(2, n) and checks each one, and if a test ever fails it stops checking and returns. If it checks n against every number in the range and not any of them divide n evenly, then the number is prime.
Again, you don't need to learn all these tricks right away, but I think they are kind of fun when you do learn them.
This should work and is bit more optimized
import math
for i in range(2, 99):
is_prime = True
for j in range(2, int(math.sqrt(i)+1)):
if i % j == 0:
is_prime = False
if is_prime:
print(i)
Please compare your snippet with the one pasted below and you will notice where you were wrong.
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
is_prime=True
for i in range(2, p):
if p%i == 0:
is_prime=False
break;
if is_prime==True:
print "%d is a Prime Number\n" % p
p=p+1
you do not re-start the i loop after you find a non-prime
p = i = 2
while p <= n:
i = 2
while i < p:
if p%i == 0:
p += 1
i = 1
i += 1
print p,
p += 1
print "Done"
A while loop executes the body, and then checks if the condition at the top is True, if it is true, it does the body again. A for loop executes the body once for each item in the iterator.
def is_prime(n):
if n>=2:
for i in range(2, n):
if n%i == 0:
return False
return True
else:
return False
To find PRIME NUMBER
Let's do a couple more improvements.
You know 2 is the only even prime number, so you add 2 in your list and start from 3 incrementing your number to be checked by 2.
Once you are past the half-way point (see above sqrt and * examples), you don't need to test for a prime number.
If you use a list to keep track of the prime numbers, all you need to do is to divide by those prime numbers.
I wrote my code and each of the above items would improve my code execution time by about 500%.
prime_list=[2]
def is_prime(a_num):
for i in prime_list:
div, rem = divmod(a_num, i)
if rem == 0:
return False
elif div < i:
break;
prime_list.append(a_num)
return True
This in my opinion is a more optimised way. This finds all the prime numbers up to 1,000,000 in less than 8 seconds on my setup.
It is also one of my very first attempts at python, so I stand to be corrected
class prime:
def finder (self):
import math
n = long(raw_input("What number should I go up to? "))
for i in range(2, n):
is_prime = True
if i % 2 == 0:
is_prime = False
for j in range(3, long(math.sqrt(i) + 1), 2):
if i % j == 0:
is_prime = False
break
if is_prime:
print(i)
prime().finder()
print('Enter a Number: ')
number=abs(int(input()))
my_List=[0,1]
def is_prime(n):
if n in my_List:
return True
elif n>=2:
for i in range(2, n):
if n%i == 0:
return False
return True
else:
return False
if is_prime(number):
print("%d is Prime!"%number)
else:
print(number,'is not prime')
for i in range(2, p):
if p%i == 0:
p=p+1
print "%s" % p,
p=p+1
I am going to tell your error only,in line 3 you are incrimenting p but actually what you are missing is your i if your i in previous case is let say 13 then it will check your loop after 13 but it is leaving 2,3,5,7,11 so its an error .that is what happening in case of 27 your i before 27 is 13 and now it will check from 14.and I don't think u need an solution.
def findprime(num):
count = 0
for i in range(1,num+1):
list1 = []
for ch in range(1,i+1):
if i%1==0 and i%ch==0:
list1.append(ch)
if len(list1)==2:
count += 1
print(i,end=", ")
print()
return count
num2 = int(input("enter a number: "))
result=findprime(num2)
print("prime numbers between 1 and",num2,"are",result)
Here's a more extensive example with optimization in mind for Python 3.
import sys
inner_loop_iterations: int = 0
def is_prime(n):
a: int = 2
global inner_loop_iterations
if n == 1:
return("Not prime")
elif n == 2:
return("Prime")
while a * a <= n + 1:
inner_loop_iterations += 1
# This if statement reduces the number of inner loop iterations by roughy 50%
# just weeding out the even numbers.
if a % 2 == 0:
a += 1
else:
a += 2
if n % 2 == 0 or n % a == 0:
return ("Not prime")
else:
return ("Prime")
while True:
sys.stdout.write("Enter number to see if it's prime ('q' to quit): ")
n = input()
if not n:
continue
if n == 'q':
break
try:
n = int(n)
except ValueError:
print("Please enter a valid number")
if n < 1:
print("Please enter a valid number")
continue
sys.stdout.write("{}\n".format(is_prime(n)))
sys.stderr.write("Inner loops: {}\n\n".format(inner_loop_iterations))
inner_loop_iterations=0
This program has two main optimizations, first it only iterates from 2 to the square root of n and it only iterates through odd numbers. Using these optimizations I was able to find out that the number 1000000007 is prime in only 15811 loop iterations.
My fast implementation returning the first 25 primes:
#!/usr/bin/env python3
from math import sqrt
def _is_prime(_num: int = None):
if _num < 2:
return False
if _num > 3 and not (_num % 2 and _num % 3):
return False
return not any(_num % _ == 0 for _ in range(3, int(sqrt(_num) + 1), 2))
_cnt = 0
for _ in range(1, 1000):
if _is_prime(_):
_cnt += 1
print(f"Prime N°: {_:,} | Count: {_cnt:,}")
Better use
for i in range(2, p//2 + 1):

Categories

Resources