Etsy's Challenge #2

Posted by Prolific Programmer Wed, 02 Apr 2008 03:09:00 GMT

Some have noticed that Etsy isn't exactly thrilled with my posting solutions to their preinterview questions. I'm not detered, though. The second question they pose is also solved below:

Given 2 strings, determine whether one is an anagram of the other. Implement this in a function "bool isAnagram(str1, str2)" which should be production-worthy code. It is OK to assume the normal English alphabet.
origstr2 = ''
def isAnagram(str1, str2):
  origstr2 = str2 
  while 1:
    shuffledstr2 = str2[1:]+ str2[0]
    if origstr2 == shuffledstr2: 
        return False
    if str1 == shuffledstr2: 
        return True
    str2 = shuffledstr2

Etsy's Challenge #1 1

Posted by Prolific Programmer Tue, 01 Apr 2008 21:57:00 GMT

Aside from the location being wrong (San Francisco is not New York, no matter what Phoenix says!), I enjoyed the brainteaser:

In the dynamic language of your choice, write a short program that will:

1. define a list of the following user ids 42346, 77290, 729 (you can hardcode these, but it should still work with more or less ids)
2. retrieve an xml document related to each user at this url "http://api.etsy.com/feeds/xml_user_details.php?id="
3. retrieve the data contained in the city element from each xml document
4. keep a running total of how many users are found in each city
5. display the total count of users living in each city

You can assume user ids are valid and that the url is available. The output should look something like: Charlotte: 1 New York: 2

Ok... I'll split this into parts, first the first bit is simple:(ruby):

@a=Array.new
def addid(id) 
  begin 
    id.each{|i| @a << i }
  rescue
    @a << i
  end
end

def doc(id)
  require 'net/http'
  require 'open-uri'
  r= open "http://api.etsy.com/feeds/xml_user_details.php?id=#{id}".read
  return r
end
def city(doc)
  require 'rexml/document'
  document = REXML::Document.new(doc)
  ret = Array.new
  REXML::XPath.each(doc, '//city') { |x| ret << x }
  return ret
end
def percity_count(array)
  h = Hash.new
  array.each { |x| begin h[x] = h[x]+1 rescue h[x]=1 end }
  return h
end
@ids =[42346, 77290, 729]
arrayOfCities = Array.new

@ids.each {|x|
   document = doc(id)
   arrayofCities << city(document)
}
hash = percity_count(arrayOfCities)
hash.each_key { |k| puts "#{k} #{hash[k]}\n" }

How to Authenticate Web Users with Cookies

Posted by Prolific Programmer Mon, 14 Jan 2008 12:41:00 GMT

Webmail sites (like Gmail or Yahoo! Mail) usually authenticate users with cookies. This cookie is generated upon login and validated on every request. Write two functions in the language of your choice to issue and validate such a cookie. You will be passed at least the username as a parameter, but you can (and should) add other parameters you think will make your solution more secure without making it less efficient.

First off, this is a question found on the Craigslist posting for a Senior Everything Engineer at Metaweb. Less than 2 weeks in, we have our first brainteaser. Me like!

The first thing to notice is that you need to issue and validate the cookie. By issuing, we'll assume that only construction is required. Validation is mostly handled by the webserver, except for any custom parameters, so check the username matches the one stored in the cookie. Code to do both, after the flip.

import Cookie
class webmail_cookie(object):
  def __init__(self, username):
     self.cookie = Cookie.SmartCookie()
     self.cookie['user'] = username
     self.cookie['secure']=True

  def __str__(self):
     return str(self.cookie)

def validate(cookie, user):
   return cookie['user'] == user

if __name__ == '__main__':
  wc=webmail_cookie('hasan.diwan')
  if validate(wc,'hasan.diwan'):
    print 'should see this'
  if validate(wc, 'boris johnson'):
    print 'bugger off!'

How to Remove Duplicates from a List

Posted by Prolific Programmer Wed, 26 Dec 2007 12:04:00 GMT

Within the bowels of memetrac lies this gem, which removes duplicates. First it builds a list of all articles, then applies certain filters to the list, one of which is below, scores the entries, and sorts by this score. Anyway, onto the uniqueness filter:

seen = {}
keep = []
import datetime,dateutil.relativedelta
for item in keep2:
     marker = item['permalink']
     if marker not in seen:
      seen[marker] = True
      keep.append(item)
     else: item['score']+=1
return keep
Perhaps the reader team would like to steal it?

How to Compute the nth Fibonacci Number

Posted by Prolific Programmer Thu, 13 Dec 2007 04:30:00 GMT

A fairly popular brainteaser that comes up repeatedly during my many job interviews. The answer is just one, leave comments if you have better ways. I'm aware that one can use Python generators to do this more efficiently, but I wanted to keep the code as clean as possible

def fib(n):
    '''Return the nth fibonacci number '''
    f=[1,1,2]
    for x in range(3,n):
        next = f[-1]+f[-2]
        f.append(next)
    return f[-1]

if __name__ == '__main__':
    import sys
    print fib(int(sys.argv[1]))

How to Keep on Your Toes

Posted by Prolific Programmer Thu, 13 Dec 2007 03:49:00 GMT

I don't quite understand why (I'm sure that some psychologist would have a field day with an explanation), but I've always liked brain teasers. I'm lucky because, in my line of work, companies often give out brain teasers freely as part of job advertisements. Now, I have zero intention of applying to these companies, it's just to keep me mind sharp. I'm going to start posting solutions here, so that readers can comment on them.