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!
Related
Function stops running after first print
When I run the following and input p=7, q=11, it runs fine all the way through and prints both keys. However, if I chose slightly larger numbers suck as p=67, q=83 it prints the value of “e” (line 13) and then stops running and exits the program that this function is within entirely when it should print the keys and return to a home menu. Any ideas why this might be?
import random
import math
def create_key_set():
p = int(input('Insert prime number for value of p: '))
q = int(input('Insert new prime number for value of q: '))
N = p * q
y = (p-1) * (q-1)
while True:
cop = random.randint(2, y-1)
gcd = math.gcd(cop, y)
if gcd == 1:
break
e = cop
print(e)
pubkey = [e, N]
while True:
d = random.randint(1, 150)
g, x = divmod((e*d), y)
if x == 1:
break
print(d)
privkey = [d, N]
print('Public Key is: ', pubkey)
print('Private Key is: ', privkey)
I’m don’t think it’s a computing issue because I tried it with cloud computing and it did the same thing. I definitely could be wrong though. Also it may be written terribly. This is the first time I’ve written python in a few years and I pretty much pieced it together from the internet. I’ve got no idea what’s wrong so any help on the issue and general tips in general would be appreciated.
The loop to find d (the second loop) is very likely to be an infinite loop. There's really no reason to use randint in that loop at all, and no reason to restrict randint to be between 1 and 150. Take out that entire loop and throw it away, and replace it with this one line: d = pow(e, -1, y), so you're code looks something like
def create_key_set():
p = int(input('Insert prime number for value of p: '))
q = int(input('Insert new prime number for value of q: '))
N = p * q
y = (p - 1) * (q - 1)
while True:
cop = random.randint(2, y - 1)
gcd = math.gcd(cop, y)
if gcd == 1:
break
e = cop
print(e)
pubkey = [e, N]
d = pow(e, -1, y)
print(d)
privkey = [d, N]
print('Public Key is: ', pubkey)
print('Private Key is: ', privkey)
I'm matching first value of a pair in tuples, and returning the second value if the first value matches across tuples. The code I wrote is working but I want to make it more pythonic, this code looks overly long:
def intersect(A, B):
setx = set()
for i in A:
i, y = i[0], i[1]
for x in B:
if i in x:
x = x[1]
setx.add((y,x))
print(setx)
return setx
Now I execute function in interpreter and get the result I want:
intersect(
{ (8, 'huit'),
(10, 'dixA'),
(12, 'douze')},
{ (5, 'cinq'),
(10, 'dixB'),
(15, 'quinze')})
and the output shows:
{('dixA', 'dixB')}
I try to get fancy and try to clean up the code:
def intersect(A, B):
setx = set()
for i in A:
i, y = i[0], i[1]
c = x for x in B if i in x
#x = c[1]
setx.add((y,x))
print(setx)
return setx
The above code gives me an invalid syntax error. When I create a list comprehension
[x[1] for x in B if i in x]
It returns a list and I cant add lists using the add method of set. Would someone be able to help me clean up my code a bit?
Interestingly this worked, I haven't used the double ++ sign in a while:
def intersect(A, B):
setx = set()
for i in A:
for x in B:
if i[0] == x[0]:
setx.add(i[1]), setx.add(x[1])
return setx
when I enter
45 200
why I am getting no
and the reason is the if-else statement is coming false
but I don't know why
T = int(input("i"))
for _ in range(T):
X,Y = map (int, input().split(" "))
if Y in (X, X+200):
print("yes")
else:
print("no")
if Y in (X,X+200) will check if Y exists in the tuple consisting of the values X and X+200. You might be looking for the python range function.
if Y in range(X,X+200) should do what you need.
I have this code in python and I am trying to make a counter for the iteration of the binary search (yeah I know it is incomplete...), but I am stuck with the variable inside the function, when i try to print the variable count I get this error
name 'count' is not defined in python
can someone explain why i get this error?
import csv
def binarySearch(arr, l, r, x):
count=0
while l <= r:
mid = int(l + (r - l) / 2)
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return -1
with open('bl_printed_music_500.csv', newline='', encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
arr=[]
for row in reader:
if row ["Publication date (standardised)"] != "":
arr.append(int(row["Publication date (standardised)"])) #create list for searching
list.sort(arr) #list must be sorted to work
#print (arr)
x = 1850 #year to search
# Function call
result = binarySearch(arr, 0, len(arr) - 1, x)
found = False
if result != -1:
found = True
print(found)
print(count)
I think it's because you defined count in binarySearch but try to use it outside of the method. Try using a global variable (define it outside of binarySearch), it should work.
You can return count as well.
For example:
def myFunc():
x = 5
y = 10
return x,y
a, b = myFunc()
print(a)
print(b)
This will be:
5
10
Note that, I could have written x, y = myFunc(). These x and y are not the same as the ones inside myFunc(). The latter are local to the function.
In your code, you can return your local count variable:
return mid, count #(A)
return -1, count #(A)
And get its value by:
result, count = binarySearch(arr, 0, len(arr)-1, x) #(B)
Again, these two count variables, (A) and (B) are different variables with different scopes.
See, for instance:
https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
Alternatively, if a global variable, as suggested in the other answer, suits you best, you can see an example of its usage in the link.
1 function:
def first_func():
x = input('Tell me')
if x == 'q':
y, z = 5, 5
return y, z
if x == 'w':
y, z = 6, 6
return y, z
else:
print('Nothing for you')
run_other_function()
return None
I want the user to be able to answer both q, w but also what ever letter the user wants, and then I want to use this function with two variables:
r, t = first_func()
But if the x is not q or w, I get:
TypeError: Cannot unpack non-iterable NoneType object
Which I fully understand why I get, but is there anyway to use it like this, or I can't use it at all like this? Can my function return anything in the else, so that r and t don't get a NoneType object?
I want to use r and t as input in another function:
coordinates(r,t)
But if user inputs anything else then r and t, it will break even before I get there.
Ok, I understand now that this question might be very hard to understand, I might need to re-write it, so everything can be understood.
TIA!
A better approach is to raise an exception instead of returning None. This will make it clear for the calling code if the call succeeded or not. If it did, then the return type is always a two-tuple.
def first_func():
x = input('Tell me')
if x == 'q':
y, z = 5, 5
return y, z
if x == 'w':
y, z = 5, 5
return y, z
else:
print('Nothing for you')
run_other_function()
raise ValueError
try:
r, t = first_function()
except ValueError:
print('we know for sure something bad happened')
else:
print('nothing bad happened, we know for sure both r and t are defined and not None')
print(r, t)
If you don't like this approach, you can return None, None instead of return None. This way r and t will both be None, but then any calling code will need to check if r and/or t are integers or None.
You are expecting two results, but you are returning only one.
Try following small change.
def first_func():
x = input('Tell me')
if x == 'q':
y, z = 5, 5
return y, z
if x == 'w':
y, z = 6, 6
return y, z
else:
print('Nothing for you')
run_other_function()
return None, None