Is there a way to store the output of the function but only if it isnt false, and not having to call the function 2 times as in the example?
def example(x):
if x>=5:
return "great"
else:
return False
def main():
x = 5
if example(x):
asnwer = example(x)
else:
print("x<5")
main()
If your Python interpreter version 3.8 or greater, you can use Assignment Expresions
import random
def example():
return random.randint(0, 10)
if (result := example()) >= 5:
print(result)
else:
print("x < 5")
def main():
x = 5
result = example(x)
asnwer = result if result else print("x<5")
You could also just modify the function:
def example(x):
return "Great" if x>=5 else print("x<5")
def main():
x = 5
asnwer = example(x)
main()
This would give asnwer == None when x<5 and asnwer == Great when x>=5.
Related
I've made a hexadecimal converter to practice recursion/recursive thinking. I, however, The recurssion doesn't appear to be happening as the functions seems to just output the result of 9 as of current.The code is as follows:
import math
curr=0
def convert(x):
L=len(x)
L-=1
sol=0
if L == 0:
return 0
else:
if x[curr]==["A","a"]:
v=10
elif x[curr]==["B","b"]:
v=11
elif x[curr]==["C","c"]:
v=12
elif x[curr]==["D","d"]:
v=13
elif x[curr]==["E","e"]:
v=14
elif x[curr]==["F","f"]:
v=15
else:
v=int(x[curr])
sol+=((v)*(16**(L-1)))
return sol + convert(x[curr+1])
def main():
print(convert('98A'))
main()
You were setting L = len(x) everytime you call the function. Here is one solution:
import math
def convert(x, L):
c = len(x) - 1
sol=0
if L > c:
return 0
else:
if (x[L]=="A" or x[L]=="a"):
v=10
elif (x[L]=="B" or x[L]=="b"):
v=11
elif (x[L]=="C" or x[L]=="c"):
v=12
elif (x[L]=="D" or x[L]=="d"):
v=13
elif (x[L]=="E" or x[L]=="e"):
v=14
elif (x[L]=="F" or x[L]=="f"):
v=15
else:
v=int(x[L])
sol+=((v)*(16**(c - L)))
print(sol)
return sol + convert(x, L + 1)
def main():
print(convert('98A', 0))
main()
You can use something like this:
class HexMap:
# mapping char to int
d = { hex(n)[2:]:n for n in range(16)}
def convert(x):
s = 0
# use reverse string and sum up - no need for recursion
for i,c in enumerate(x.lower()[::-1]):
s += HexMap.d[c]*16**i
return s
def main():
print(convert('98A'))
main()
Output:
2442
Recursive version:
# class HexMap: see above
def convert(x):
def convert(x,fak):
if not x:
return 0
else:
return HexMap.d[x[-1]]*16**fak + convert(x[:-1],fak+1)
return convert(x.lower(),0)
def main():
print(convert('98A'))
main()
Same output.
When I run the code below I keep getting a syntax error and it is highlighted where shown.
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
sf_area = (int(sf_area))
rio_area = (int(rio_area))
def x= sf_population/sf_area
def y= rio_population/rio_area
if x<y:
print"True"
if x>y:
print"False"
Working example:
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
sf_area = int(sf_area)
rio_area = int(rio_area)
x = sf_population/sf_area
y = rio_population/rio_area
if x < y:
print"True"
if x > y:
print"False"
def is used in python to define functions, not variables. To set the value of x to sf_population/sf_area simply drop the def in lines 5 and 6.
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
sf_area = (int(sf_area))
rio_area = (int(rio_area))
x = sf_population/sf_area
y = rio_population/rio_area
if x<y:
print "True"
if x>y:
print "False"
Unless you want to define a function, there is no need for def
Beside of this, consider using elif for the second condition
if x<y:
print "True"
elif x>y:
print "False"
Can anyone explain this please?
def cube(number):
number = (number**3)
return number
def by_three(number):
if number % 3 == 0:
cube(number)
return number
else:
return False
by_three(3)
Oops, try again. by_three(3) returned 3 instead of 27
Why does this not return 27?
So the problem is that in your by_three function you are returning the parameter "number" passed into the by_three function and not returning the result of the cube function.
Your code:
def by_three(number):
if number % 3 == 0:
cube(number)
## problem is right here you should return cube(number) not number
return number
else:
return False
Fixed code.
def by_three(number):
if number % 3 == 0:
return cube(number) ## note the change here
else:
return False
Check you are not referring the returned value to variable number.The code will be like this.
def cube(number):
number = (number**3)
return number
def by_three(number):
if number % 3 == 0:
number=cube(number)
return number
else:
return False
print by_three(3)
Hope your problem is solved
For example, we have two functions:
def function1(num):
return num * 3
and second function
def function2(num):
if num%2 == 0:
print(num)
function1(num)
return num
If you call function(1), as expected it will return 1
If you call function(2), it will return 2 not 6. WHY?
Lets analyze this function2(2)
def function2(num): # num = 2
if num%2 == 0: # yes, it meets the condition
print(num)
function1(num) # it steps into function 1, this return num*3 == 6 however we do not know where it is saved (its address is unknown).
return num # this 'num' it is just the argument == 2
I need to code a program that can get values from this
Very interesting question. Actually, in your case, it is very simple. You can parse the entire source string with ast module, like this
import ast
import operator
functions = {
"add": operator.add,
"abs": operator.abs,
"multiply": operator.mul
}
def recursive_evaluation(current_element):
if isinstance(current_element, ast.Module):
return recursive_evaluation(current_element.body[0].value)
elif isinstance(current_element, ast.Call):
function = functions[current_element.func.id]
args = [recursive_evaluation(item) for item in current_element.args]
return function(*args)
elif isinstance(current_element, ast.Num):
return current_element.n
else:
raise ValueError("Unknown Element " + str(current_element))
source = "abs(add(add(9465,38),multiply(add(63303,146),46)))"
print recursive_evaluation(ast.parse(source))
source = "add(1, -2)"
print recursive_evaluation(ast.parse(source))
source = "abs(add(1, -2))"
print recursive_evaluation(ast.parse(source))
Output
2928157
-1
1
Interesting problem, here is a potential solution. No doubt you could make a much more elegant solution using libraries or lambdas etc. as thefourtheye did in their answer, but this seems to work.
I have done a few test cases at the bottom, set the global verbose to True if you want debug info:
# globals
verbose = False # set to True if you want debug info printed
max_iter = 1000 # this stops infinate loops incase the code does not allow for some input
def solve(problem_str):
def multiply(arg_list):
x = 1
for i in arg_list:
x *= i
return x
def find_innermost(x_str):
a, b, c, i = [0], [0], 0, 0
while True:
i += 1
start = a[-1]+1
a.append(x_str.find('(', start)) # find next (
b.append(x_str.find(',', start)) # find next ,
c = x_str.find(')', start) # find next )
if (a[-1] > c) or (a[-1] == -1):
if (b[-2] > a[-3]) and (b[-2] < a[-2]):
return x_str[b[-2]+1:c+1]
else:
return x_str[a[-3]+1:c+1]
if i >= max_iter:
raise Exception("Infinite loop")
def do_sum(x_str):
args = [int(x) for x in x_str[x_str.find('(')+1:x_str.find(')')].split(',')]
task = x_str[:3].lower()
if task == 'add':
return sum(args)
elif task == 'sub':
return args[0] - sum(args[1:])
elif task == 'abs':
return abs(args.pop())
elif task == 'mul':
return multiply(args)
else:
print x_str + ': Task not recognised, please modify program or input'
raise Exception("Invalid input")
i = 0
while True:
i += 1
if verbose: print 'debug: problem_str:', problem_str
if problem_str.count('(') > 1:
x_str = find_innermost(problem_str)
else:
x_str = problem_str
if verbose: print '.'*6, 'x_str:\t', x_str
x = do_sum(x_str)
if verbose: print '.'*6, 'x:\t', x, '\n'
problem_str = problem_str.replace(x_str, str(x))
if problem_str.count('(') == 0:
return int(problem_str)
if i >= max_iter:
raise Exception("Infinite loop")
if __name__ == '__main__':
p1 = 'abs(add(add(9465,38),multiply(add(63303,146),46)))'
p2 = 'abs(add(multiply(95,multiply(-1,multiply(13,18875))),multiply(-1,add(18293,26))))'
p3 = 'abs(add(subtract(add(add(151,26875),122),254),subtract(237,multiply(-1,56497))))'
r1, r2, r3 = solve(p1), solve(p2), solve(p3)
print 'p1 evaluates to:', r1
print 'p2 evaluates to:', r2
print 'p3 evaluates to:', r3
Let me know if you have any questions about the code.
Hi I have problems because this function creates the numbers which I wanted but also generates a None. How should I write this code to not produce the NONE
def binary (str):
b = []
for x in str:
b.append(format(ord(x), 'b'))
return ((b))
clave = "1001001000010001001000110111111100110000100011001010100000110001110110011111010010011111000011111001000011101011001101000001110010011110010110000000"
c = list(clave)
msg = binary("Lol")
print("".join(msg))
m = list("".join(msg))
print("Now the right")
def OTP(m,c):
for i in range (0,len(m)):
if c[i]== "1" and m[i]== "1":
m.pop(i)
m.insert(i,"0")
elif c[i] == "1" and m[i] == "0":
m.pop(i)
m.insert(i,"1")
return print("".join(m))
msg1 = OTP(m,c)
print(msg1)
The reason OPT returns none is because you return the return result of the print function -
return print("".join(m))
Which is indeed None. To obtain the string you should just do -
return "".join(m)