Skip to content

Commit 54c8cc4

Browse files
committed
add a few twitter interview problems
1 parent 48289bb commit 54c8cc4

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

flip/flip_fun.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import urllib2
2+
import time
3+
import re
4+
5+
def isTerminated(base_url, x, y):
6+
url = formURL(base_url, x,y)
7+
print 'cur_url is ', url
8+
text = getPageText(url)
9+
if text.startswith('end:true'):
10+
return True
11+
12+
def parseNextSteps( s):
13+
slash_pos = s.find("/")
14+
s = s[slash_pos+1:]
15+
pattern = "\(.*?\)"
16+
res = re.findall(pattern, s)
17+
to_return = []
18+
for r in res:
19+
t = r[1:-1].split(',')
20+
to_return.append( (int(t[0]), int (t[1])) )
21+
return to_return
22+
23+
def formURL(base_url, x, y):
24+
return base_url+"x="+str(x)+"&y="+str(y)
25+
26+
def getInitial(url):
27+
response = urllib2.urlopen(url)
28+
res_url = response.url
29+
base_url_pos = res_url.find("x=")
30+
base_url = res_url[:base_url_pos]
31+
return base_url, response.read()
32+
33+
def getPageText(url):
34+
response = urllib2.urlopen(url)
35+
return response.read()
36+
37+
def getNext(base_url, x, y):
38+
url = formURL(base_url, x , y)
39+
text = getPageText(url)
40+
return parseNextSteps(text)
41+
42+
def main():
43+
MAXN = 100
44+
45+
#open the url given to start a maze journey!
46+
base_url, text = getInitial('http://challenge.flipboard.com/m') #the id of the task change every time.keep track of this base id as a base_url
47+
print 'base is ', base_url
48+
initial_step = parseNextSteps(text) #initial
49+
visited =[ [0 for i in range(MAXN)] for j in range(MAXN) ]
50+
queue = []
51+
queue.append( (0,0) )
52+
while( len(queue)!=0 ):
53+
cur = queue.pop()
54+
visited[cur[0]][cur[1]] = True
55+
time.sleep(0.00001)
56+
if(isTerminated(base_url, cur[0], cur[1])):
57+
print 'answer is ',cur[0], cur[1]
58+
break
59+
next_steps = getNext(base_url, cur[0], cur[1])
60+
print 'cur at ',cur, 'next would be', next_steps
61+
for ns in next_steps:
62+
if visited[ns[0]][ns[1]] == False:
63+
queue.append( ns )
64+
65+
main()
66+
67+

0 commit comments

Comments
 (0)