Nested for loops and break - nested

Why does the following code not print anything? The first set of values of a and b that satisfies the condition is a = 1 and b = 4. However, I don't see that being printed.
def fun():
for a in range(5):
for b in range(5):
if a + b == 5:
print(a,b)
break
break
fun()

You have an extra break, as the first one will terminate the innermost loop, allowing to increment the outermost (value of a) which is what you want. Breaking twice terminates the whole execution so your code should look like this:
def fun():
for a in range(5):
for b in range(5):
if a+b ==5:
print(a, b)
break
fun()
EDIT
Since you want to display the first set of values then instead of break it's a return that is needed to terminate the whole execution.
def fun():
for a in range(5):
for b in range(5):
if a+b ==5:
print(a, b)
return
fun()

Related

Proper way to list a second heirarchy generator

Let's say we have a generator that do operations on a generator, here's an example:
def print_forever(n):
while True:
yield n
def limit_gen(gen, n):
for i in range(n):
yield next(gen)
What's the proper way to insert the values of the generator in a list? list(limit_gen(print_forever(2), 5) for example raises a StopIteration.
In your example the print_forever is instanciated once, then passed to the limit_gen one. After being called once, the first one has yield its one value and reach its own end, raising a StopIteration exception.
There are various ways to make it work, you could for example instanciate a new generator at each iteration:
def print_forever(v):
yield v
def limit_gen(gen, v, n):
for _ in range(n):
yield next(gen(v))
for v in limit_gen(print_forever, 2, 5):
print(v)
Another option is to make a really infinite generator:
def print_forever(v):
while 1:
yield v
def limit_gen(gen, n):
for _ in range(n):
yield next(gen)
for v in limit_gen(print_forever(2), 5):
print(v)

Checking if three inputs form a triangle

So I want to take three inputs from the user and check whether they form a triangle.Now I want my program to check using any three random values of of the given inputs and check whether a + b > c.Here is my code for that :
def check_triangle(a, b, c):
a, b, c = [float(i) for i in input('Enter the stick lengths: ').split(' ')]
x, y, z = [int(num) for num in [a, b, c]]
list_1 = [x, y, z]
def is_triangle(x, y, z):
for i in list_1:
if (list_1[i] <(list_1[i+1] + list_1[i+2])):
print("Yes")
else:
print("No")
check_triangle(a, b, c)
But I am getting no output.
What is the error
Your are getting no output, because you defined a function inside a function, but you are calling only the first one. So second one is defined but never executed. What you want to do to execute the second one is to add a function call at the end of the first one, so in your case it would be:
def check_triangle(a, b, c):
a, b, c = [float(i) for i in input('Enter the stick lengths: ').split(' ')]
x, y, z = [int(num) for num in [a, b, c]]
list_1 = [x, y, z]
def is_triangle(x, y, z):
for i in list_1:
if (list_1[i] <(list_1[i+1] + list_1[i+2])):
print("Yes")
else:
print("No")
is_triangle(x,y,z)
Indentation can be messed up, because I'm answering on my phone, sorry for that.
Also, from what I can see you will be getting list index out of range error at this line.
if (list_1[i] <(list_1[i+1] + list_1[i+2]))
That is happening because your i is actually an element of your list as defined in the line below, not an index, but you are trying to get an element from the list by it's index with the syntax my_list[index].
for i in list_1
What you want to do instead of the for loop mentioned above is iterate in the range of it's length, meaning iterate over possible indexes in the list, is done like so:
for i in range(len(list_1))
I notice a few other things in your code and a lot of room for improvement, but I hope you can deal with the rest yourself!
you are taking input from the user so you do not need to pass any arguments for your function check_triangle:
def is_triangle(x, y, z):
if x < y + z:
print("Yes")
else:
print("No")
def check_triangle():
x, y, z = map(int, input('Enter the stick lengths: ').split())
is_triangle(x, y, z)
check_triangle()
or you can simplify you code like:
def is_triangle(x, y, z):
print('Yes' if x < y + z else 'No')
is_triangle(*map(int, input('Enter the stick lengths: ').split()))
To begin, since a, b and c are variables input by the user, they do not need to be input into the function as arguments. In fact, because they are not defined before being given as arguments to the function, it is causing the function to raise a NameError with the message name 'a' is not defined when it is called. To fix this issue, you can remove a, b and c as arguments to your function in both its definition and its usage.
At this point, the function will run, but even if the user inputs the numbers in the format which your program is expecting (i.e. separated by single spaces - which is not explicitly specified to the user) the portion of your program that evaluates your target condition will not run because it is contained within the function is_triangle(x, y, z) which is not called. This function can be eliminated and your test condition can be evaluated within the main function. Additionally, there is no need to loop through the elements in the list as you can access its elements directly to evaluate your target condition.
Here is the code with these changes made:
# since a, b and c are given by the user, they do not need to be arguments to the function
def check_triangle():
a, b, c = [float(i) for i in input('Enter the stick lengths: ').split(' ')]
x, y, z = [int(num) for num in [a, b, c]]
list_1 = [x, y, z]
# evaluate your test condition directly within the main function. no secondary function is necessary
# as you want to check that c < a + b, access those elements directly by using the index of the list. no loop is necessary
if list_1[2] < list_1[0] + list_1[1]:
print("Yes")
else:
print("No")
# since a, b and c are not defined before running the function, they cause it to raise a NameError if they are given
check_triangle()
This code will run and evaluate your target condition. However, this condition (that c < a + b) does not (to my knowledge) actually mean that something is a triangle. Good luck and happy coding!

how to pass list of lists for vectorize python

For vectorization of python code, I have seen an example of passing a list of numbers for which our function is to be executed.
example :
def myfunc(a, b):
"Return a-b if a>b, otherwise return a+b"
if a > b:
return a - b
else:
return a + b
vfunc = np.vectorize(myfunc)
vfunc([1, 2, 3, 4], 2)
But our argument in the function is list, how to do the vectorization.
example:
def myfunc(a, b):
#a is the list
if a[0] > a[1]:
return a[0] - a[1]
Since a is list object. Try to use loop method to iterate each values in the list.
def myfunc(a, b):
# loop depends on the length of the list
for i in range(len(a)):
if a[i] > b:
return a[i] - b
else:
return a[i] + b

how to add values to the list in this format

how to input values in this following format because based on that, i need to perform more operations
for i in range(4):
for j in range(10):
if count < tickets:
list[i][j] = loginId
#what to do instead of this statement#what is expect is, values should be assigned to each element in the list in this way how to achieve this
else:
break
what should i use instead of list[i][j] to assign all the values to the list.
According to the output you requested, i modified the code
def fun():
check=6
loginID=1234
count=0
a=[]
for i in range(2):
a.append([])
for j in range(2):
if count<check:
a[i].insert(j, loginID)
count+=1
else:
print(a)
break
fun()
You can modify the values in the ranges of for loops for more customization.
Edit : To print the above list a in a matrix form
for p in a:
for q in p:
print(q, end=' ')
print()
Full program question
def fun():
check=6
loginID=1234
count=0
a=[[None]*5]*4
for i in range(2):
for j in range(2):
if count<check:
a[i][j]=loginID
count+=1
else:
break
print(a)
fun()
output
[[1234,1234],[1234,1234]]
I find difficult in assigning values to the matrix. please provide me a solution in this format

GCD without using recursion

The code given below is only working correctly for some of the inputs such as gcdIter(2, 12) which gives me correct output i.e 2 but if I give input as gcdIter(220,120) it gives me 110 instead of 20. I need some help with the logic.
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
if a<b:
while a>0:
if b%a==0:
print('the gcd is : '+''+str(a))
break
else:
a -= 1
else:
while b>0:
if a%b==0:
print('the gcd is :'+''+str(b))
break
else:
b -= 1
it's simple like that.No need to check a<b or a>b
def gcdIter(a, b):
while b:
a, b = b, a%b
print('the gcd is :'+str(a))

Resources