Logo F2FInterview

Python Advanced Interview Questions

Q   |   QA

def append_s(words):
  new_words=[]
  for word in words:
    new_words.append(word + 's')
  return new_words

for word in append_s(['a','b','c']):
  print word

The above code adds a trailing s after each element of the list.

def append_s(words):
     return [i+'s' for i in words] ## another list comprehension

for word in append_s(['a','b','c']):
     print word 

best stored in a list of dictionaries..
dictionary format: {‘first_name’:'Ayush’,'last_name’:'Goel’}

from math import sin,cos,atan,acos,asin,atan2,sqrt,pi, modf

def getDistance(loc1, loc2):
   "aliased default algorithm; args are (lat_decimal,lon_decimal) tuples"
   return getDistanceByHaversine(loc1, loc2)

def getDistanceByHaversine(loc1, loc2):
   "Haversine formula - give coordinates as (lat_decimal,lon_decimal) tuples"
   earthradius = 6371.0

   lat1, lon1 = loc1
   lat2, lon2 = loc2

   # convert to radians
   lon1 = lon1 * pi / 180.0
   lon2 = lon2 * pi / 180.0
   lat1 = lat1 * pi / 180.0
   lat2 = lat2 * pi / 180.0

   # haversine formula
   dlon = lon2 - lon1
   dlat = lat2 - lat1
   a = (sin(dlat/2))**2 + cos(lat1) * cos(lat2) * (sin(dlon/2.0))**2
   c = 2.0 * atan2(sqrt(a), sqrt(1.0-a))
   km = earthradius * c
   return km

location1 = (13.01013,80.21122)
location2 = (13.03361,80.26861)

distance = getDistance(location1, location2)

print 'KM', distance

#Output: in KM is 6.74331391328

In order to link this F2FInterview's page as Reference on your website or Blog, click on below text area and pres (CTRL-C) to copy the code in clipboard or right click then copy the following lines after that paste into your website or Blog.

Get Reference Link To This Page: (copy below code by (CTRL-C) and paste into your website or Blog)
HTML Rendering of above code: