Homework 6.5 marked incorrect

Can someone please tell me why was this marked incorrect? It's almost the same as the solution in the video. And it works for all the examples. Here is my code:

def lucky_search(index, ranks, keyword):
    urls = lookup (index, keyword)
    if urls:
        bestrank = ranks[urls[0]]
        for e in urls:
            if ranks[e] > bestrank:
                bestrank = ranks[e]
                lucky_url = e
        return lucky_url
    else:
        return None

asked 05 Apr '12, 07:13

buba-1's gravatar image

buba-1
344
accept rate: 0%

edited 05 Apr '12, 07:16


3 Answers:

What if urls[0] happens to be the best URL? Although you iterate over the entire list, there's going to be no rank higher than the highest, so lucky_url won't get set, and you'll have an error. Your code only works if the best URL is at urls[1] or later. Probably the simplest change to make is changing the greater than to greater than or equal or to set lucky_url initially to urls[0].

link

answered 05 Apr '12, 07:24

Charles%20Lin's gravatar image

Charles Lin
9.2k4294135

Man, you're fast!

(05 Apr '12, 07:27) Monty Monty's gravatar image

Your code fails when the first entry has the highest rank as you initialize lucky_url in your if block, which will never be entered if the first url is the one with the highest rank, so when you return lucky_url, it will have no value assigned to it

link

answered 05 Apr '12, 07:25

elssar's gravatar image

elssar
19.2k2563155

Oh, yes. Missed that one... :/

link

answered 05 Apr '12, 07:30

buba-1's gravatar image

buba-1
344

Edge cases are the hard ones to catch (at the beginning of a list, at the end, testing the empty list, etc).

(05 Apr '12, 07:58) Charles Lin Charles%20Lin's gravatar image

True. Especially if you're doing your homework at he last minute. :) Thank you for your answers and good luck on the exam!!

(05 Apr '12, 08:07) buba-1 buba-1's gravatar image
Your answer
Question text:

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×15,226
×1,718
×192

Asked: 05 Apr '12, 07:13

Seen: 116 times

Last updated: 05 Apr '12, 08:07