Please explain my mistake. |
The question has been closed for the following reason "The question is answered, right answer was accepted" by Estilo 14 Mar '12, 07:49
|
Hrm. Let's see if I can work through what your code is doing in English... Okay, you're taking a list, p as an input. You're setting the variable great to the first element of p, then setting temp and i to 0. Then you're looping over each element of p. If the current element of p (which is identified as p[i]) is greater than great (which starts at p[0]), you're:
If p[i] is equal to or less than great, you're doing none of the above. Either way, you're incrementing i. At the end of the procedure, you're returning great. I think your logic is off here. What's happening is: Let's say you're checking p[1]. The value of p[1] is 5, and the value of great is 4. So p[1] is greater than great. Awesome.
So you're not getting the correct value out of this, because your logic isn't working quite the same. What you want to do, I think, is simply set great to the higher value, and then move on. No need for the tmp variable. (Or indeed for iterating i, when instead of p[i], you could simply use e in this for loop. Hope that's helpful. |
|
When the list is empty your code breaks. You should assign 0 to great to start with. That's the problem, but there are other serious flaws in your code albeit not as critical. First since you are using a for ... in statement, you don't have to use i as an index to go through all elements, the for statement does that for you. You just have to use e instead of p[i] since the for statement assigns it to the next element during each loop iteration. The second problem concerns the three lines of code in your if statement. As I understand the three elements basically extract the greatest element and put the previously greatest element back in the list. All of this you shouldn't do. The question asks you to determine the greatest element, not to find it and remove it from the list. You can get to the answer without modifying any of the elements in the list. The statement
in the if statement would have sufficed. or if you were to take my advice
|
|
You don't take care of the null list possibility |
|
See MarkC's answer and your slightly modified code: def greatest(p):
great=0
for e in p:
if e>great:
great=e
return great
|