Python loop freezing with no error - python

I am trying to make a code in Python that shows the number of steps needed to reach one from any number using a simple algorithm. This is my code:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(max - min):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num / 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(int(n)+min)+' Steps needed: '+count)
It freezes up without showing an error message, and I have no clue why this happens.

1) You are invoking range() incorrectly.
Your code: for n in range(max - min): produces the range of numbers starting at 0 and ending at the value max-min. Rather, you want the range of numbers starting at min and ending at max.
Try this:
for n in range(min, max):
2) You are performing floating-point division, but this program should use only integer division. Try this:
num = num // 2
3) You are updating the count variable in the wrong loop context. Try indenting it one stop.
4) Your final line could be:
print('Number: '+str(n)+' Steps needed: '+str(count))
Program:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(min, max):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num // 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(n)+' Steps needed: '+str(count))
Result:
Enter the lowest and highest numbers to test.
Minimum number: 3
Maximum number: 5
Number: 3 Steps needed: 7
Number: 4 Steps needed: 2
Number: 5 Steps needed: 5

It looks like it's getting stuck in the while not num == 1 loop. Remember that range() starts at 0, so num is first set to 0, which is divisible by 2, and so will be reset to 0/2... which is 0 again! It will never reach 1 to break the loop.
EDIT: I earlier said that count = 0 needed to be moved. Actually, looking more carefully it seems like the line count = count + 1 line just needs to be moved under the while loop.

Related

how can i achieve this ? I'm trying to have an Input that will print out all the numbers in sequential order using python

Desired OutputThis is what I want my output to be.
What I have now.
rows = int(input("Please Enter a Number : "))
for I in range(1, rows + 1):
for j in range(1, I + 1):
print('*', end = ' ')
print()
But This is what I want my output to be
Enter any number : 21
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Right Angle triangle output thing.
Its been driving me nuts.
Please help :)
Thanks in anticipation
Ignoring the triangle part, the first step is to print all the numbers:
rows = int(input("Please Enter a Number : "))
for num in range(1, rows + 1):
print(num, end=" ")
From there we want to add an if to also print a new line if our number is
equal to 'rows', or
the number we expect to be at the end of the current level
Since the number of items in each row is an arithmetic progression (i.e. each level is +1 longer than the level above it) we can calculate the number at the end of each level using the formula for summing an arithmetic progression:
number_at_end_of_level = level * (level + 1) / 2
The simple explanation for this formula is that you're finding the average number of items in each level by averaging the first and last level average = (level + 1) / 2. Because we know the average, we can then multiply that by the number of levels to get the total.
So putting it all together the solution is:
rows = int(input("Please Enter a Number : "))
level = 1
for num in range(1, rows + 1):
print(num, end=" ")
number_at_end_of_level = level * (level + 1) / 2
if num == number_at_end_of_level or num == rows:
level += 1
print()
Alternatively, if you don't want to do the calculation, you can just count how many items you've printed in the current level and print a new line when that count is equal to the current level number:
rows = int(input("Please Enter a Number : "))
level = 1
current_level_count = 0
for num in range(1, rows + 1):
print(num, end=" ")
current_level_count += 1
if current_level_count == level or num == rows:
level += 1
current_level_count = 0
print()
Hellor, here's your solution for your problem
rows = int(input("Please Enter a Number : "))
count = 1
number = 1
while number <= rows:
for i in range(count):
print(number, end=" ")
number += 1
count += 1
print("\n", end="")
Since you always need to add one number per line
you need a variable to store the number of numbers
to print (Here count).
You also need a variable to count the current number
that you increment for each iteration of count
(here number) and you stop only when the current
number is greater then the input (Here rows)

How to print 100 values which are divisible by 3 and 5?

lower = int(input("Enter lower range limit:"))
upper = int(input("Enter upper b range limit:"))
Count = 0
for i in range(lower, upper+1):
if((i%3==0) & (i%5==0)):
Count += 1
print(count)
I want to print 100 values which are divisible by 3 and 5, but in count only 7 is showing, can anyone suggest what to do, it will be appreciated!
Use this
num = int(input("How many Numbers you want :"))
i=0
Count = 0
while(Count != num):
if((i%3==0) and (i%5==0)):
Count += 1
print(i)
i = i + 1
print("Count is :",Count)
Python program to print all the numbers
divisible by 3 and 5 for a given number
Result function with N
def result(N):
# iterate from 0 to N
for num in range(N):
# Short-circuit operator is used
if num % 3 == 0 and num % 5 == 0:
print(str(num) + " ", end = "")
else:
pass
Driver code
if name == "main":
# input goes here
N = 100
# Calling function
result(N)

Write a Python program that reads a positive integer n and finds the average of all odd numbers between 1 and n

This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number

finding emrips with python, what am i doing wrong?

An Emirp is a prime number whose reversal is also a prime. For
example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
Write a program that prints out the first N emirps, five on each line.
Calculate the first N emirp (prime, spelled backwards) numbers, where
N is a positive number that the user provides as input.
Implementation Details
You are required to make use of 2 functions (which you must write).
isPrime(value) # Returns true if value is a prime number. reverse
(value) # Returns the reverse of the value (i.e. if value is 35,
returns 53). You should use these functions in conjunction with logic
in your main part of the program, to perform the computation of N
emirps and print them out according to the screenshot below.
The general outline for your program would be as follows:
Step 1: Ask user for positive number (input validation) Step 2:
Initialize a variable Test to 2 Step 3: While # emirps found is less
than the input:
Call isPrime with Test, and call it again with reverse(Test).
If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then
reverse the string. Then turn it back into an int!
MY CODE:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
count = 0
while(test < value):
if( value % test == 0):
count+=count
test+=test
if(count == 0):
return 1
else:
return 0
def reverse(value):
reverse = 0
while(value > 0):
reverse = reverse * 10 + (value % 10)
value = value / 10
return reverse
n = float(input("Please enter a positive number: "))
while(count < n):
i+=i;
if(isPrime(i)):
if(isPrime(reverse(i))):
print("i" + "\n")
count+=count
if((count % (5)) == 0 ):
print("\n")
where are the mistakes?
UPDATED CODE BUT STILL NOT RUNNING:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
def reverse(value):
return int(str(value)[::-1])
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
There are a lot of issues with your code. I altered the function isPrime. There is among other no need for count here and if you want to increment test by 1 every loop use test +=1:
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
return 1
There is an easy way to reverse digits by making value a string in reversed order and to convert this into an integer:
def reverse(value):
return int(str(value)[::-1])
You among other have to assign the input to i. n in your code is a constant 5. You have to increment i by one in any condition and increment the count by one if i is an emirp only:
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
def emrip_no(num):
i=0
j=0
for i in range(1,num+1):
a=0
for j in range(1,i+1):
if(i%j==0):
a+=1
if(a==2):
print("Number is a prime number")
k=0
l=0
rv=0
while(num!=0):
r=num%10
rv=(rv*10)+r
num=num//10
print("It's reverse is: ",rv)
for k in range(1,rv+1):
b=0
for l in range(1,k+1):
if(k%l==0):
b+=1
if(b==2):
print("It's reverse is also a prime number")
else:
print("It's reverse is not a prime number")
n=int(input("Enter a number: "))
emrip_no(n)

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()

Categories

Resources