def find_ins_idx(r, v):
# Check the data of the already sorted list r from the beginning one by one
for i in range (0, len (r)):
# If the value of the data in position i is greater than the value of v,
# v must be immediately preceded by its value to preserve the sort order
if v < r[i]:
return i
# If you can't find the right location,
# Insert last because v means that it is larger than all of r's resources
return len (r)
r = [5, 1, 3, 2, 7]
v = 4
print(find_ins_idx(r,v))
Hello, if you look at the code above, there are two return statements, but if you say print(find_ins_idx(r,v))
then
Will the result be i
only? Why doesn't the return len(r)
value come out?
If you do so, only one result is '0'
returnlen(r)
value 5
does not appear!
I think it's a basic concept, but I'm asking because I don't know it well! Of course, if you do print(len(r)
separately, 5
is returned well
If you return to the for statement, it doesn't come out of the for statement, but it ends there.
How about writing a break
sentence instead of returni
to follow your intention?
def find_ins_idx(r, v):
# Check the data of the already sorted list r from the beginning one by one
for i in range (0, len (r)):
# If the value of the data in position i is greater than the value of v,
# v must be immediately preceded by its value to preserve the sort order
if v < r[i]:
break
# If you can't find the right location,
print('---------')
# Insert last because v means that it is larger than all of r's resources
return i, len(r)
r = [5, 1, 3, 2, 7]
v = 4
print(find_ins_idx(r,v))
v = 10
I think I'll get 5.
If it's a code you made, I think you'll understand it by changing it like this and that. It's hard to figure out what you're really curious about just by asking questions.
© 2024 OneMinuteCode. All rights reserved.