Aug-11-2020, 02:50 AM
It looks simple because it is simple. You are doing this:
When you are programming, how do you start? Do you write a detailed description of the problem you are trying to solve? I do. Even for simple programs like this. Writing down the problem description places it clearly in my mind. If I don't write down the problem description I may end up solving the wrong problem.
The next thing I do is draw pictures of the problem and my solution. Everyone is a visual thinker and everyone will benefit from drawing. I always write the program on paper first. I fill notebooks with problem descriptions and notes and drawings and pseudocode. If you had drawn a picture of your solution with a short list and maybe some index values I bet you wouldn't have had any trouble writing the code. You are trying to do you designing with Python. You are not comfortable with Python and that makes it a terrible tool for doing design.
My simple drawing above makes me realize there is a bug in my solution. Looking at it now I see the end of the slice was off. If you want the four before and the four after the slice should be
Quote:Find the letter d and return d, the letter before and the letter after.That is simple.
0 a
1 b
[2 c
3 d
4 e]
5 f
6 g
Answer: [2:5]
When you are programming, how do you start? Do you write a detailed description of the problem you are trying to solve? I do. Even for simple programs like this. Writing down the problem description places it clearly in my mind. If I don't write down the problem description I may end up solving the wrong problem.
The next thing I do is draw pictures of the problem and my solution. Everyone is a visual thinker and everyone will benefit from drawing. I always write the program on paper first. I fill notebooks with problem descriptions and notes and drawings and pseudocode. If you had drawn a picture of your solution with a short list and maybe some index values I bet you wouldn't have had any trouble writing the code. You are trying to do you designing with Python. You are not comfortable with Python and that makes it a terrible tool for doing design.
My simple drawing above makes me realize there is a bug in my solution. Looking at it now I see the end of the slice was off. If you want the four before and the four after the slice should be
lines[max(0,index-4):min(index+5, len(lines))
] If index was 4 we would want lines 0 through 8. To get those lines the slice should be 0 to 9 where line[9] is not part of the slice.max(index+5, len(lines))
does the same thing you were doing with max(0,index-4)
except for the end. Thinking some more about it I don't think the min is required. If you ask for a slice that extends beyond the source, the slice is "sliced" to fit.x = [0, 1, 2] print(x[0:10])
Output:[1, 2, 3]
The same is not true if you specify a negative value for the start of slice.print(x[-2, 3])
Output:[2, 3]
The same as x[3-2, 3]