Python. Nested While Loop - python-3.x

I'm a complete beginner trying to write a nested while loop using Python where I'd like a countdown to print three times.
Currently I have:
def amigo (counter, n):
while counter > 0:
while n > 0:
print (n)
n= n - 1
print('Hola!')
counter = counter - 1
Where I'm setting counter and n to both equal 2.
What I'd like it to do is print:
3
2
1
Hola!
3
2
1
Hola!
But right now it is printing:
3
2
1
Hola!
Hola!
Can someone point me in the right direction?

always reset counters.
Before each loop set counter value to initial position
For your inner loop it will be i = n
Use assignment with actions
Operator x += y is equivalent to x = x + y
Then your code will be n -= 1 instead of n = n - 1
Improved code
def amigo (counter, n):
while counter > 0:
i = n # Reset counter befor cycle. Used i to prevent editing n's value
while i > 0:
print (i)
i -= 1 # Decrease i by 1, will loop from N to 1
print('Hola!')
counter -= 1 # Descrease counter by 1

Related

How can I make a nested for loop to print n, n-1 .... n - (n - 1)?

I have been trying to make a nested for loop that prints the following:
if n = 5
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
Below you can find the code I have been using to try to get this but it is not working:
def main():
n = 5
for i in range(1, n + 1):
for j in range(1, i):
print(n, end=' ')
n = n - 1
print('\n')
main()
You can make few changes:
Store n to variable and use it inside inner loop, decrement by one in each iteration.
Inside loop should run till i+1, because the end is exclusive.
def main():
n = 5
for i in range(n):
n1 = n
for j in range(i+1):
print(n1, end=' ')
n1 -= 1
print('\n')
main()
so code is
def main():
n = 5
for i in range(n):
for j in range(0, i+1):
print(n-j, end=' ')
print('\n')
main()

minimum steps by 1 or 2 but divisible by given number

I am working on a python program where I want to find the minimum number of steps needed to reach a top floor such that the count of steps should be divisible by given number say m
Here is my program taken from here:
# A program to count the number of ways to reach n'th stair
# Recurssive program to find n'th fibonacci number
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# returns no. of ways to reach s'th stair
def countWays(s):
return fib(s + 1)
# Driver program
s = 10
print("Number of ways = ", countWays(s) )
Here I am getting the total number of ways, but I want to filter them by those divisible by a given number say m, how to do this?
Example:
1) s = 10 and m = 2, output should be 6, as the steps are {2,2,2,2,1,1}
2) s = 3 and m = 5 output should be -1 as the possible steps are {1,1,1}, {2,1}, {1,2}
--> here none of them (means 3 steps, 2 steps, 2 steps) are divible by 5.
s = 10
m = 2
if s % m == 0:
print(s)
outputs: 10
Using % is a modulo operation. This provides a "remainder" after division. So if your item has no remainder, it is divisible by the selected number.
# A program to count the number of ways to reach n'th stair
# Recursive function used by countWays
def countWaysUtil(n,m):
res = [0 for x in range(n)] # Creates list res witth all elements 0
res[0],res[1] = 1,1
for i in range(2,n):
j = 1
while j<=m and j<=i:
res[i] = res[i] + res[i-j]
j = j + 1
return res[n-1]
# Returns number of ways to reach s'th stair
def countWays(s,m):
return countWaysUtil(s+1, m)
# Driver Program
s,m = 4,2
print "Number of ways =",countWays(s,m)
# Contributed by Harshit Agrawal
You can use this:
# A program to count the number of ways to reach n'th stair
# Recurssive program to find n'th fibonacci number
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# returns no. of ways to reach s'th stair
def countWays(s, m):
# Add in a division by m, which you pass to the function
# Cast it as an int to return a whole # and not decimal
return int(fib(s + 1) / m)
# Driver program
s = 10
# Set this to whatever
m = 3
print("Number of ways = ", countWays(s, m) )

My code for finding Prime Number is working fine but printing an unexpected value of 9. Explain how?

I have written a logic to find Prime Number up to some entered value. It is working fine but printing an unexpected 9 which don't go well with logic as 9%3 will be 0 and it have to skip that number.
n = int(input())
for i in range(2,n+1):
for j in range(2,n+1):
if i%j == 0 and i!=j:
break
else:
print(i,end=" ")
break
Input : 20
Output : 2 3 5 7 9 11 13 15 17 19
You output a candidate number as soon as it is found not divisible by any other number, so for the candidate number 9, as soon as the inner loop starts with the divisor number 2, it would immediately go into the else block and output the number and break the inner loop because 9 is not divisble by 2.
You should wait until all the divisors from the inner loop have exhausted before deciding that the candidate number from the outer loop is indeed a prime number, and for that you can use the for-else construct:
n = int(input())
for i in range(2, n + 1):
for j in range(2, n + 1):
if i % j == 0 and i != j:
break
else:
print(i, end=" ")
Sample input/output:
20
2 3 5 7 11 13 17 19
Just take a variable, e.g. is_prime to set it to True/False by checking if the number gets divided by any number in closed interval [2, n/2].
Do not decide immediately and come out of the loop once the if expression gets satisfied using break as you are doing.
With a tiny change in your code, you may make your code working and with less number of iterations (to decrease runtime complexity) as follows.
n = int(input())
for i in range(2,n+1):
is_prime = True
for j in range(2, n//2 + 1):
if i % j == 0 and i != j:
is_prime = False
break
if is_prime:
print(i, end= " ")

Given a positive integer, determine if it's the nth Fibonacci number for some n

I try to find out the index of a certain Fibonacci number. However my program returned to me this result "Your program took too long to execute. Check your code for infinite loops, or extra input requests" after typing in 1134903171.
num = 1
num_prev = 1
n = int(input())
i = 1
if n < 2:
print(1, 2)
else:
while i <= n + 2:
num_prev, num = num, num + num_prev
i += 1
if n == num:
print(i + 1)
break
elif i == n + 3:
print(-1)
#break`
Thank you guys. The problem of last code is that: if the number isn't a Fibonacci number and meanwhile it is too large, it will took to many loops for the calculation. As I used a web compiler to calculate, they do not allow such "infinity" loop to operate. Then I used a math methode to limite the loop.
import math
N=int(input())
root1=math.sqrt(5*N*N+4)
root2=math.sqrt(5*N*N-4)
i=1
num, num_prev = 1, 1
if root1%1==0 or root2%1==0:
while i <= N+2:
num_prev,num = num,(num+num_prev)
i+=1
if N==num:
print(i+1)
break
else:
print(-1)
But the best answer could be:
prev, next = 1, 1
index = 2
possible_fib = int(input())
while possible_fib > next:
prev, next = next, prev + next
index += 1
if possible_fib == next:
print(index)
else:
print(-1)

Python 3: skipping to next iteration if condition is not fulfilled - loop in loop

I have a loop in a loop like following:
iGen = (i for i in range(1,10))
for i in iGen:
for j in range(1,10):
some operations
if certain operation not fulfilled:
next(iGen)
So for example if i = 5 and the condition is not fulfilled then the j loop should be canceled and i should iterate to 6.
However, this does not work. Anyone have a suggestion why this logic would be faulty?
Here is the real code. The pseudocode above is just to make the logic clearer.
array = [];
for k in range(1, 20):
y=2**k*(2**(k+1)-1)
array.append(y)
iGen = (i for i in range(0, len(array)))
for i in iGen:
x = 1
for j in range(2, array[i]):
if array[i] % j == 0:
g = x
x = x + j
if x / g < 2:
next(iGen)
if x == array[i]:
print(array[i])
You want to use a break. This will break out of your j-loop and continue on with the next item in the i-loop.
iGen = (i for i in range(1,10))
for i in iGen:
for j in range(1,10):
some operations
if certain operation not fulfilled:
break

Resources