Created
February 10, 2012 18:34
-
-
Save adrianp/1791505 to your computer and use it in GitHub Desktop.
Embedly Challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""These are my answers for the Embedly Challenge""" | |
from xml.etree import ElementTree | |
from numpy import std # you'll need numpy for Question 2 | |
def question1(): | |
def digitSum(x): | |
# pretty ugly, eh? | |
return sum(map(int, list(str(x)))) | |
f, i = 1, 1 | |
while digitSum(f) < 8001: | |
f, i = f * i, i + 1 | |
return i - 1 | |
def question2(): | |
l = [] | |
def recurNode(node, level): | |
if node != None: | |
if node.tag == "p": | |
l.append(level) | |
for item in node.getchildren(): | |
recurNode(item, level + 1) | |
else: | |
return 0 | |
# here I got lazy: did not fetch the html directly from the website and I | |
# removed everything (e.g., body tag) except the article tag to make | |
# things easier | |
recurNode(ElementTree.parse("2.html").getroot(), 0) | |
return std(l) # std from numpy | |
def question3(): | |
# a simple bruteforce solution | |
l = [2520] | |
for i in range (1,900): | |
l.append(l[0] / (i + 1)) | |
total, half, i = sum(l), 0, 0 | |
while half < (total / 2): | |
half, i = half + l[i], i + 1 | |
return i | |
if __name__ == "__main__": | |
print(question1()) | |
print(question2()) | |
print(question3()) |
@yassersouri Yes, it's 22 and that's what I get. Can you give me more details about your machine (Python version, 32/64 bit, OS)? Let me know if you discover the issue.
I'm running python 2.7 on windows 7, 32 bit
I don't think It's a machine dependency issue.
I just tried to implement your solution using Java and got the same (21) output:
public class Problem3 {
public static void main(String[] args) {
int[] l = new int[900];
l[0] = 2520;
for (int i = 1; i < l.length; i++) {
l[i] = l[0] / (i + 1);
}
int total = 0;
for (int i = 0; i < l.length; i++) {
total += l[i];
}
int half = 0;
int i = 0;
while (half < total/2) {
half = half + l[i];
i++;
}
System.out.println(i);
}
}
BTW I have no idea why this code does not generate the required output. It seems to be ok.
@yassersouri It's a rounding issue; try using float/double instead of int in your Java code.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just tried your question3 on my computer and it returns 21!
I'm pretty sure the answer is 22!