This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Closed 8 years ago.
I'm in my intro to programming class and for some reason am a bit stumped as to how to proceed from here. Basically the prompt is to compare three numbers the user inputs and see if the first number is between the last two.
def fun1(a,b,read,):
if a < read and read > b:
return print("Yes")
elif b < read and read > a:
return print("Yes")
else:
return print("No")
def main():
read = input("mid: ")
a = input("num1 ")
b = input("num2 ")
fun1(read,a,b,)
print("result:",fun1)
So as you see I can't figure out how to get the comparing function down in the first function. Any help is much appreciated!
Python allows you to chain comparison operators:
if a < b < c:
This will test if b is between a and c exclusive. If you want inclusive, try:
if a <= b <= c:
So, in your code, it would be something like:
if a < read < b:
return print("Yes")
elif b < read < a:
return print("Yes")
else:
return print("No")
or, more concisely:
if (a < read < b) or (b < read < a):
return print("Yes")
else:
return print("No")
Note too that print always returns None in Python. So, return print("Yes") is equivalent to return None. Perhaps you should remove the return statements:
if (a < read < b) or (b < read < a):
print("Yes")
else:
print("No")
Related
This question already has answers here:
Print vs Return in Python Function
(2 answers)
Closed 6 months ago.
I'm doing some Kaggle exercises and the question is asking me to "In the cell below, define a function called sign which takes a numerical argument and returns -1 if it's negative, 1 if it's positive, and 0 if it's 0". This was my function:
def sign(x):
if x < 0:
print('-1')
elif x > 0:
print('1')
else:
print('0')
I tested on VS Code but Kaggle saying it's "incorrect". The proper solution it's the following:
def sign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
I would like to know what's the real difference between my function and Kaggle's?
Cheers
The difference between print and return is that when you use print, you don`t have to call your function with print, example:
def sign(x):
if x > 0:
print('123')
elif x < 0:
print('134')
else:
print('Hey')
sign(1) # That is how you call your func with no print
Otherwise, if you use returns in your code, than you have to use print when you call your fucn, example:
def sign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
print(sign(1)) # That is how you call your func with print
Also if you need to get the result value of func, then you can assign a value to a variable, example:
def func(x=0):
x = x ** 2
return x
a = func(5)
print(a) # 25
I need help with converting my iterative code to recursive.
def pattern(int):
if int == 0:
return ''
else:
result = '*-'
for i in range(int-1):
if i%2 != 0:
result += '*-'
elif i % 2 == 0:
result += '*--'
return result
Above is the code I wrote to convert an integer into repetitive patterns. For int%2 != 0, it prints '*-' , and for int%2 == 0, it prints '*--'.
I have been stucked with converting the above to recursive. I understand the base case is '*-' with the terminating condition of int == 1. I should then concatenate the base case with pattern(int-1) recursively. Can anyone advise me?
IIUC, Use:
def pattern(n):
if n == 1: # Base case
return "*-"
if n % 2 == 0:
return pattern(n - 1) + "*--"
else:
return pattern(n - 1) + "*-"
Calling the function:
print(pattern(10)) # builds the pattern corrensponding to integers from 1,2...10.
This prints:
*-*--*-*--*-*--*-*--*-*--
I really don't know what to do.
This is what I'm trying to do:
If a number in my lst is bigger than 'a' and smaller than 'b', the function has to return true. else, false.
What's wrong here?
def is_in_range(lst,a,b):
for num in lst:
if num> a and num < b:
return True
i+=1
elif num >=b:
return False
return c
elif num <= a:
return False
elif len(lst) ==0:
return True
print is_in_range([1,2,3,5],0,4)
The function prints me true unless b = the first number in my lst.
Actually your indentation and control flow is not really clear. But based on your description this would solve your problem:
def is_in_range(lst, a, b):
return any(a < num < b for num in lst)
This is quite generic as well, if you would like to see that ALL the numbers are in the range, you would only have to change any to all.
To take it closer to what you started off with:
def is_in_range(lst, a, b):
if len(lst) == 0:
return True
for num in lst:
if a < num < b:
return True
return False
Note that each function returns only once, thus if no corresponding value was found, only then will you return with False.
This question already has answers here:
How do I iterate through two lists in parallel?
(8 answers)
Closed 5 months ago.
I'm trying to compare the first character of two different strings (and so on) to form a new string based on those results. This is what I've tried using, however its comparing every element of each list to each other.
def compare(a,b):
s = ""
for x in a:
for y in b:
if x == y:
s+=str(x)
else:
s+=str(y)
It seems like such a simple question but I'm stuck.
Use zip:
def compare(a, b):
for x, y in zip(a, b):
if x == y:
...
Are you perhaps looking for something with logic similar to this? It chooses the alphabetically earlier character from each input string:
def compare(a,b):
s = ""
for i in range(len(a)):
if a[i] < b[i]:
s+=str(a[i])
else:
s+=str(b[i])
return s
print compare ("seven", "eight")
Output:
eegen
The one-line version of this is
return ''.join(a[i] if a[i] < b[i] else b[i] for i in range(len(a)))
input(x)
input(y)
cnt = 0
for char_val in x:
if b[cnt] == char_val:
print("match")
else:
print("mis-match")
Here is a complete function
def compare_strings(a,b):
result = True
if len(a) != len(b): print('string lengths do not match!')
for i,(x,y) in enumerate(zip(a,b)):
if x != y:
print(f'char miss-match {x,y} in element {i}')
result = False
if result: print('strings match!')
return result
def twoStrings(s1, s2):
for i in range(len(s1)):
for j in range(len(s2)):
if s2[j] == s1[i]:
return 'YES'
return 'NO'
We can write simple and easy method to compare similar letters in two strings
def compare(a,b):
s = ""
t=""
for x in a:
for y in b:
if x == y:
t=x
s=s+t
print(s)
compare("xyz","axy")
Here first for loop will compare each letters in string and display all similar character.
This question already has answers here:
Python function returns None (all trivial solutions checked and they do not work) [duplicate]
(1 answer)
Weird function return value? [duplicate]
(3 answers)
Closed 9 years ago.
count = []
def problem14(n):
count.append(n)
if n == 1:
return count
if n % 2 == 0:
n = n/2
problem14(n)
else:
n = 3*n + 1
problem14(n)
print problem14(13)
So this is code that I have written. I have no idea why it's returning None while in my opinion it should return list 'count'. Any help?
You still need a return statement when using recursion, otherwise the return value will be lost:
def problem14(n):
count.append(n)
if n == 1:
return count
if n % 2 == 0:
n = n/2
return problem14(n) # <--
else:
n = 3*n + 1
return problem14(n) # <--
By the way, this is probably the wrong approach for Project Euler #14 :-) Consider using a dynamic programming approach instead (that's all I'll say so as to not ruin the fun).
You should use the return keyword in order to return a value from a function.
return problem14(n)