Issue
I want a function that searches for a number in similarly named arrays and then return specific values which correspond to the particular array it was found in.
I have written the following code which uses if and elif:
bf0 = np.arange(38,75,1)
for i in range(1,5):
globals()["bf"+str(i)] = globals()["bf"+str(i-1)]+37
def func(x):
if x in bf0:
return "x is in bf0"
elif x in bf1:
return "x is in bf1"
elif x in bf2:
return "x is in bf2"
elif x in bf3:
return "x is in bf3"
elif x in bf4:
return "x is in bf4"
Althought this works, is there any way I can simplify the code to fewer unrepetitive lines?
Solution
import numpy as np
arrays = {}
for i in range(5):
array_name = "bf" + str(i)
start = 38 + i * 37
end = 75
arrays[array_name] = np.arange(start, end, 1)
def search_array(x):
for array_name, array in arrays.items():
if x in array:
return f"{x} is in {array_name}"
return f"{x} is not in any array"
result = search_array(45)
print(result)
Answered By - Aria Noorghorbani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.