4
\$\begingroup\$

I have such a method which takes a URL, such as http://twitter.com/ttt or twitter.com/dasd, and should show its domain with http: http://twitter.com and name twitter

def show_domain(url):
 sites = {
 'twitter': ['http://www.twitter.com/', 'twitter'],
 'facebook': ['http://www.facebook.com/', 'facebook'],
 'pininterest': ['http://www.pininterest.com/', 'pininterest']
 }
 if sites['twitter'][0] in url:
 link = sites['twitter'][0]
 brand = sites['twitter'][1]
 elif sites['facebook'][0] in url:
 link = sites['facebook'][0]
 brand = sites['facebook'][1]
 else:
 link = sites['pininterest'][0]
 brand = sites['pininterest'][1]
 return link, brand

Is there way to optimise this code?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 12, 2014 at 10:11
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Have you considered using the urlparse module? \$\endgroup\$ Commented Aug 12, 2014 at 11:46

1 Answer 1

5
\$\begingroup\$

You can use tuple unpacking/list unpacking to write :

if sites['twitter'][0] in url:
 link, brand = sites['twitter']
elif sites['facebook'][0] in url:
 link, brand = sites['facebook']
else:
 link, brand = sites['pininterest']
return link, brand

Now, the data structure you are using is a bit akward because you don't use the key at all. Instead of mapping string to list of strings, you could have a list of list of strings. Even better, you could use list of tuple of strings :

sites = [
 ('http://www.twitter.com/', 'twitter'),
 ('http://www.facebook.com/', 'facebook'),
 ('http://www.pininterest.com/', 'pininterest')
]
if sites[0][0] in url:
 link, brand = sites[0]
elif sites[1][0] in url:
 link, brand = sites[1]
else:
 link, brand = sites[2]
return link, brand

Now, this seems to be begging to be written with a loop

for (link, brand) in sites:
 if link in url:
 return link, brand
return None # or anything you like
answered Aug 12, 2014 at 10:24
\$\endgroup\$
2
  • \$\begingroup\$ but it local variables link, brand are unused, pycharm says \$\endgroup\$ Commented Aug 12, 2014 at 11:14
  • 1
    \$\begingroup\$ @user2424174 then it is a bug in pycharm, because they are being returned, so used. \$\endgroup\$ Commented Aug 12, 2014 at 12:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.