예제 #1
0
def index(request):
    '''
    index.html handler
    '''

    global thread

    if request.method == 'POST':

        # Here we are getting days and hours selection from webpage
        days = request.POST.get('days')
        hours = request.POST.get('hours')

        # converting the days and hours into seconds for scheduling
        secs = round(int(days) * 24 * 60 * 60 + int(hours) * 60 * 60) / 360
        if secs == 0:
            secs = 60
        print('secs: ', secs)

        # Kill the previous thread
        if thread:
            thread.cancel()
            del thread
            thread = None
            print('canceled', thread)

        else:
            print('not canceled', thread)
        # Running the function that authenticates, uploads the csvs on the drive and generates links
        main.main()

        # Making the new thread that schedules the functions
        try:
            thread = TimerHandler(secs, main.main)
            thread.start()
        except Exception as ex:
            print(ex)

        print('waiting for', secs)

        print(thread, active_count())

        return render(request, "index.html")

    elif request.method == 'GET':
        print('P:', main.products_link, '\nPS:', main.products_sotcks_link,
              '\nPF:', main.products_full_link)

        # Getting the links of files
        value4PS = main.products_sotcks_link
        value4P = main.products_link
        value4PF = main.products_full_link
        return render(request, "index.html", {
            'key4P': value4P,
            'key4PS': value4PS,
            'key4PF': value4PF
        })
예제 #2
0
    def handle(self, *args, **options):
        products = main()

        for product in products:

            if not Product.objects.filter(id=product['id']):
                product_db = Product(
                    **{
                        key: value
                        for (key, value) in product.items() if key in
                        [fields.name for fields in Product._meta.get_fields()]
                        and key != "categories" and key != "nutriments"
                    })

                nutriment_db = Nutriment(
                    **{
                        key: value
                        for (key, value) in product['nutriments'].items()
                        if key in [
                            fields.name
                            for fields in Nutriment._meta.get_fields()
                        ]
                    })

                product_db.nutriment = nutriment_db
                nutriment_db.save()
                product_db.save()

                for category in product['categories']:
                    category_db, category_created = Category.objects.update_or_create(
                        name=category)
                    product_db.categories.add(category_db)
                    product_db.save()

            self.stdout.write(
                self.style.SUCCESS(
                    'Data has been successfully downloaded and created'))
예제 #3
0
NOTE: Once the chain starts the terms are allowed to go above one million.
"""


def next_collatz_number(n):
    if n % 2 == 0:
        return n/2
    return 3*n + 1


def longest_collatz_chain(n):
    collatz = {1:0}
    longest = 1
    for a in xrange(2, n):
        new = [a]
        while new[-1] not in collatz:
            new.append(next_collatz_number(new[-1]))

        print a, new
        for i, val in enumerate(new[:-1]):
            collatz[val] = collatz[new[-1]] + len(new) - i - 1

        if collatz[a] > collatz[longest]:
            longest = a

    return longest


if __name__ == '__main__':
    main(longest_collatz_chain, 100)
예제 #4
0
from utils.my_math import Prime, Triangle
from utils.main import main

def get_amount_of_divisors(pl, n):
    factors, frequencies = pl.get_prime_factor_frequency(n)
    possible_combinations = 1
    for f in frequencies:
        possible_combinations *= f + 1

    return possible_combinations


def first_triangle_divisors(n):
    tri = Triangle()
    pl = Prime()
    while get_amount_of_divisors(pl, tri.sequence[-1]) < n:
        tri.find_next()
    return tri.sequence[-1]


if __name__ == '__main__':
    main(first_triangle_divisors, 500)
예제 #5
0
integers:

0.123456789101112131415161718192021...

It can be seen that the 12th digit of the fractional part is 1.

If dn represents the nth digit of the fractional part, find the value of the
following expression.

d1 x d10 x d100 x d1000 x d10000 x d100000 x d1000000
"""


def get_product_of_fraction():
    fraction = ''
    count = 1
    total = 1

    while len(fraction) < 10**6:
        fraction += str(count)
        count += 1

    for n in [0, 9, 99, 999, 9999, 99999, 999999]:
        total *= int(fraction[n])

    return total


if __name__ == '__main__':
    main(get_product_of_fraction)
예제 #6
0
from datetime import date

"""
You are given the following information, but you may prefer to do some research for yourself.

1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the mntury (1 Jan 1901 to 31 Dec 2000)?
"""


def number_of_mondays():
    start = date(1901, 1, 1)
    end = date(2000, 12, 31)
    count = 0

    for dt in rrule.rrule(rrule.MONTHLY, dtstart=start, until=end):
        if dt.weekday() == 6:
            count += 1

    return count

if __name__ == '__main__':
    main(number_of_mondays)
예제 #7
0
from utils.main import main

"""
Starting in the top left corner of a 22 grid, there are 6 routes (without
backtracking) to the bottom right corner.


How many routes are there through a 2020 grid?
"""

def find_option_through_grid(size):
    grid = [[1]*size for x in xrange(size)]
    for x in range(1, size):
        for y in range(1, size):
            grid[x][y] = grid[x-1][y] + grid[x][y-1]

    return grid[size - 1][size - 1]


if __name__ == '__main__':
    main(find_option_through_grid, 21)
예제 #8
0
which divide evenly into n).
If d(a) = b and d(b) = a, where a  b, then a and b are an amicable pair and
each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55
and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and
142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.
"""


def d(n, pl):
    return sum(pl.get_proper_divisors(n))


def sum_of_amicable_numbers(n):
    pl = Prime()
    amicable_sum = 0

    for i in xrange(2, n):
        divisor_sum = d(i, pl)
        if divisor_sum < i and divisor_sum > 0 and d(divisor_sum, pl) == i:
            amicable_sum += divisor_sum + i

    return amicable_sum


if __name__ == '__main__':
    main(sum_of_amicable_numbers, 10000)
예제 #9
0
from utils.main import main
from itertools import product


def palindrome(sequence):
    return sequence == sequence[::-1]


def palindrome_product(mini, maxi):

    numbers = range(mini, maxi)
    products = list(set(map(lambda x: x[0] * x[1], product(numbers, numbers))))

    for n in sorted(products, reverse=True):
        if palindrome(str(n)):
            return n
    return 0


if __name__ == '__main__':
    main(palindrome_product, 1, 1000)
예제 #10
0
The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?
"""

def get_fibonnaci_over_digits(n):
    fib = Fibonacci()
    fib.up_to(10**n)
    return len(fib.sequence)


if __name__ == '__main__':
    main(get_fibonnaci_over_digits, 999)
def synon(sentence):
    return main(sentence)
예제 #12
0
from utils.main import main
from math import factorial

"""
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

Find the sum of all numbers which are equal to the sum of the factorial of their digits.

Note: as 1! = 1 and 2! = 2 are not sums they are not included.
"""

def is_curious_number(n):
    return n == sum(map(lambda x: factorial(int(x)), str(n)))


def sum_of_curious_numbers(lim):
    curious_numbers = []
    for n in xrange(10, lim):
        if is_curious_number(n):
            curious_numbers.append(n)

    return sum(curious_numbers)



if __name__ == '__main__':
    main(sum_of_curious_numbers, 10**5)
예제 #13
0
from utils.my_math import Prime
from utils.main import main


def largest_primefactor(n):
    ps = Prime()
    return ps.get_prime_factors(n)[-1]


if __name__ == '__main__':
    main(largest_primefactor, 600851475143)
예제 #14
0
    while p > 9:
        if not pl.is_prime(p / 10):
            return False
        p /= 10

    while len(str_p) > 1:
        if not pl.is_prime(int(str_p[1:])):
            return False
        str_p = str_p[1:]

    return True


def sum_of_truncatable_primes():
    pl = Prime()
    truncatable_primes = []

    pl.up_to(10)

    while len(truncatable_primes) < 11:
        if is_truncatable_prime(pl.sequence[-1], pl):
            print pl.sequence[-1]
            truncatable_primes.append(pl.sequence[-1])
        pl.find_next()

    return sum(truncatable_primes)


if __name__ == '__main__':
    main(sum_of_truncatable_primes)
예제 #15
0
number that can be written as the sum of two abundant numbers is 24. By
mathematical analysis, it can be shown that all integers greater than 28123 can
be written as the sum of two abundant numbers. However, this upper limit cannot
be reduced any further by analysis even though it is known that the greatest
number that cannot be expressed as the sum of two abundant numbers is less than
this limit.

Find the sum of all the positive integers which cannot be written as the sum of
two abundant numbers.
"""

def get_abundant_numbers(n):
    pl = Prime()
    abundant = []

    for i in xrange(12, n):
        if i < proper_divisor_sum(i, pl):
            abundant.append(i)

    return abundant


def sum_of_non_abundant(n):
    abundant = get_abundant_numbers(n)
    abundant_sums = map(sum, combinations_with_replacement(abundant, 2))
    return sum(set(xrange(n)).difference(abundant_sums))


if __name__ == '__main__':
    main(sum_of_non_abundant, 28123)
예제 #16
0
from utils.main import main
"""
Starting in the top left corner of a 22 grid, there are 6 routes (without
backtracking) to the bottom right corner.


How many routes are there through a 2020 grid?
"""


def find_option_through_grid(size):
    grid = [[1] * size for x in xrange(size)]
    for x in range(1, size):
        for y in range(1, size):
            grid[x][y] = grid[x - 1][y] + grid[x][y - 1]

    return grid[size - 1][size - 1]


if __name__ == '__main__':
    main(find_option_through_grid, 21)
예제 #17
0
from utils.main import main
from pe018 import find_max_route

"""
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom in triangle.txt (right click and 'Save
Link/Target As...'), a 15K text file containing a triangle with one-hundred
rows.

NOTE: This is a much more difficult version of Problem 18. It is not possible to
try every route to solve this problem, as there are 2^99 altogether! If you
could check one trillion (10^12) routes every second it would take over twenty
billion years to check them all. There is an efficient algorithm to solve it.
;o)
"""

if __name__ == '__main__':
    main(find_max_route, './pe067_data.txt')
예제 #18
0
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name
score.

For example, when the list is sorted into alphabetical order, COLIN, which is
worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
obtain a score of 938  53 = 49714.

What is the total of all the name scores in the file?
"""

def alphabetical_value(name):
    return sum(map(lambda x: ord(x) - 64, name))


def total_name_scores(filename):
    total_score = 0
    f = open(filename)
    names = f.read().replace('"', '').split(',')
    names.sort()
    for i, n in enumerate(names, start=1):
        total_score += alphabetical_value(n) * i

    return total_score


if __name__ == '__main__':
    main(total_name_scores, './pe022_data.txt')
예제 #19
0
Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?
"""


def get_fibonnaci_over_digits(n):
    fib = Fibonacci()
    fib.up_to(10**n)
    return len(fib.sequence)


if __name__ == '__main__':
    main(get_fibonnaci_over_digits, 999)
예제 #20
0
from utils.my_math import Fibonacci
from utils.main import main

"""
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
"""

def even_fibonaci_sum(max_fib):
    f = Fibonacci()
    fibo_numbers = f.up_to(max_fib)
    return sum(fibo_numbers[2::3])  #Every third number in the sequence is even


if __name__ == '__main__':
    main(even_fibonaci_sum, 4e6)
예제 #21
0
from utils.main import main
from pe018 import find_max_route
"""
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom in triangle.txt (right click and 'Save
Link/Target As...'), a 15K text file containing a triangle with one-hundred
rows.

NOTE: This is a much more difficult version of Problem 18. It is not possible to
try every route to solve this problem, as there are 2^99 altogether! If you
could check one trillion (10^12) routes every second it would take over twenty
billion years to check them all. There is an efficient algorithm to solve it.
;o)
"""

if __name__ == '__main__':
    main(find_max_route, './pe067_data.txt')
예제 #22
0
from utils.main import main

"""
Work out the first ten digits of the sum of the following one-hundred 50-digit
numbers*.

* See 013_data.txt for the numbers

"""


def get_first_digits_of_sum(amount, filename):
    f = open(filename, 'r')
    numbers = map(int, f.read().split('\n')[:-1])
    return str(sum(numbers))[:10]


if __name__ == '__main__':
    main(get_first_digits_of_sum, 10, './pe013_data.txt')
예제 #23
0
from utils.main import main
from utils.my_math import Prime
from itertools import permutations

"""
We shall say that an n-digit number is pandigital if it makes use of all the
digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is
also prime.

What is the largest n-digit pandigital prime that exists?
"""

def get_largest_pandigital_prime():
    pl = Prime()
    combis = []

    for n in xrange(2, 10):
        combis.extend(permutations(range(1, n + 1), n))
    combis = map(lambda x: int(''.join(map(str, x))), combis)

    for n in combis[::-1]:
        if pl.is_prime(n):
            return n


if __name__ == '__main__':
    main(get_largest_pandigital_prime)
예제 #24
0
from utils.my_math import Prime
from utils.main import main

def largest_primefactor(n):
    ps = Prime()
    return ps.get_prime_factors(n)[-1]


if __name__ == '__main__':
    main(largest_primefactor, 600851475143)
예제 #25
0
An irrational decimal fraction is created by concatenating the positive
integers:

0.123456789101112131415161718192021...

It can be seen that the 12th digit of the fractional part is 1.

If dn represents the nth digit of the fractional part, find the value of the
following expression.

d1 x d10 x d100 x d1000 x d10000 x d100000 x d1000000
"""

def get_product_of_fraction():
    fraction = ''
    count = 1
    total = 1

    while len(fraction) < 10**6:
        fraction += str(count)
        count += 1

    for n in [0, 9, 99, 999, 9999, 99999, 999999]:
        total *= int(fraction[n])

    return total


if __name__ == '__main__':
    main(get_product_of_fraction)
예제 #26
0
from utils.main import main

"""
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?
"""


def find_sum_of_digits(number):
    return sum(map(int, str(number)))


if __name__ == "__main__":
    main(find_sum_of_digits, 2 ** 1000)
예제 #27
0
from utils.main import main
from itertools import product

def palindrome(sequence):
    return sequence == sequence[::-1]

def palindrome_product(mini, maxi):

    numbers = range(mini, maxi)
    products = list(set(map(lambda x: x[0] * x[1], product(numbers, numbers))))

    for n in sorted(products, reverse=True):
        if palindrome(str(n)):
            return n
    return 0

if __name__ == '__main__':
    main(palindrome_product, 1, 1000)
예제 #28
0
from utils.main import main
from pe016 import find_sum_of_digits
from math import factorial

"""
n! means n  (n  1)  ...  3  2  1

For example, 10! = 10  9  ...  3  2  1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!
"""

if __name__ == '__main__':
    main(find_sum_of_digits, factorial(100))
예제 #29
0
from utils.main import main
"""
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?
"""


def find_sum_of_digits(number):
    return sum(map(int, str(number)))


if __name__ == '__main__':
    main(find_sum_of_digits, 2**1000)
예제 #30
0
def is_circular_prime(p, pl):
    p = str(p)
    circular_p = p
    if not re.match("^[1379]*$", p):
        return False

    for c in p[:-1]:
        circular_p = circular_p[1:] + circular_p[0]

        if not pl.is_prime(int(circular_p)):
            return False

    return True


def amount_of_circular_primes(lim):
    pl = Prime()
    pl.up_to(lim)
    circular_primes = pl.sequence[:4]

    for p in pl.sequence[4:-1]:
        if is_circular_prime(p, pl):
            circular_primes.append(p)

    return len(circular_primes)


if __name__ == "__main__":
    main(amount_of_circular_primes, 10 ** 6)
예제 #31
0
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
"""

def quintuplewise(iterable):
    a, b, c, d, e = tee(iterable, 5)
    next(b)
    c = islice(c, 2, None)
    d = islice(d, 3, None)
    e = islice(e, 4, None)
    return izip(a, b, c, d, e)


def max_product_from_file(filename):
    prod = 0
    f = open(filename, 'r')

    number = map(int, re.sub(r'\D', '', f.read()))

    for group in quintuplewise(number):
        if prod < product(group):
            prod = product(group)
    return prod


if __name__ == '__main__':
    main(max_product_from_file, './pe008_data.txt')
예제 #32
0
from utils.my_math import Prime
from utils.main import main

"""
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.
"""

def sum_of_primes_up_to(n):
    pl = Prime()
    return sum(pl.up_to(n))


if __name__ == '__main__':
    main(sum_of_primes_up_to, 2000000)
예제 #33
0
from utils.my_math import Fibonacci
from utils.main import main
"""
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
"""


def even_fibonaci_sum(max_fib):
    f = Fibonacci()
    fibo_numbers = f.up_to(max_fib)
    return sum(fibo_numbers[2::3])  #Every third number in the sequence is even


if __name__ == '__main__':
    main(even_fibonaci_sum, 4e6)
예제 #34
0
from utils.main import main

"""
The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025  385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""

def diff_between_sum_of_squares(n):
    sum_of_squares = sum(map(lambda x: x**2, range(n)))
    square_of_sum = sum(range(n))**2

    return square_of_sum - sum_of_squares


if __name__ == '__main__':
    main(diff_between_sum_of_squares, 101)
예제 #35
0
containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name
score.

For example, when the list is sorted into alphabetical order, COLIN, which is
worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
obtain a score of 938  53 = 49714.

What is the total of all the name scores in the file?
"""


def alphabetical_value(name):
    return sum(map(lambda x: ord(x) - 64, name))


def total_name_scores(filename):
    total_score = 0
    f = open(filename)
    names = f.read().replace('"', '').split(',')
    names.sort()
    for i, n in enumerate(names, start=1):
        total_score += alphabetical_value(n) * i

    return total_score


if __name__ == '__main__':
    main(total_name_scores, './pe022_data.txt')
예제 #36
0
from utils.my_math import Prime, Triangle
from utils.main import main


def get_amount_of_divisors(pl, n):
    factors, frequencies = pl.get_prime_factor_frequency(n)
    possible_combinations = 1
    for f in frequencies:
        possible_combinations *= f + 1

    return possible_combinations


def first_triangle_divisors(n):
    tri = Triangle()
    pl = Prime()
    while get_amount_of_divisors(pl, tri.sequence[-1]) < n:
        tri.find_next()
    return tri.sequence[-1]


if __name__ == '__main__':
    main(first_triangle_divisors, 500)
예제 #37
0
NOTE: Once the chain starts the terms are allowed to go above one million.
"""


def next_collatz_number(n):
    if n % 2 == 0:
        return n / 2
    return 3 * n + 1


def longest_collatz_chain(n):
    collatz = {1: 0}
    longest = 1
    for a in xrange(2, n):
        new = [a]
        while new[-1] not in collatz:
            new.append(next_collatz_number(new[-1]))

        print a, new
        for i, val in enumerate(new[:-1]):
            collatz[val] = collatz[new[-1]] + len(new) - i - 1

        if collatz[a] > collatz[longest]:
            longest = a

    return longest


if __name__ == '__main__':
    main(longest_collatz_chain, 100)
예제 #38
0
    numbers[20] = 'twenty'
    numbers[30] = 'thirty'
    numbers[40] = 'forty'
    numbers[50] = 'fifty'

    for i in range(60, 100, 10):
        numbers[i] = numbers[i / 10] + 'ty'

    numbers[80] = 'eighty'

    for i in range(20, 100, 10):
        generate_written_out_numbers(i, numbers[i], '', range(1, 10), numbers)

    for i in range(100, 1000, 100):
        numbers[i] = numbers[i / 100] + 'hundred'
        generate_written_out_numbers(i, numbers[i] + 'and', '', range(1, 100),
                                     numbers)

    numbers[1000] = 'onethousand'

    return numbers


def length_of_written_out_numbers(start, end):
    numbers = get_written_out_numbers()
    return sum(map(len, numbers[start:end]))


if __name__ == '__main__':
    main(length_of_written_out_numbers, 1, 1001)
예제 #39
0
from datetime import date
"""
You are given the following information, but you may prefer to do some research for yourself.

1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the mntury (1 Jan 1901 to 31 Dec 2000)?
"""


def number_of_mondays():
    start = date(1901, 1, 1)
    end = date(2000, 12, 31)
    count = 0

    for dt in rrule.rrule(rrule.MONTHLY, dtstart=start, until=end):
        if dt.weekday() == 6:
            count += 1

    return count


if __name__ == '__main__':
    main(number_of_mondays)
예제 #40
0
from utils.my_math import Prime
from utils.main import main
"""
2520 is the smallest number that can be divided by each of the numbers from 1
to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20?
"""


def divisible_by_all_lower(max_divisor):
    """ Return the number that is divisible by all numbers lower than the
        max_divisor
    """
    smallest = 1
    pl = Prime()
    prime_divisors = pl.up_to(max_divisor)

    for p in prime_divisors:
        temp = p
        while temp <= max_divisor:
            temp *= p
            smallest *= p

    return smallest


if __name__ == '__main__':
    main(divisible_by_all_lower, 21)
예제 #41
0
from utils.main import main
from pe004 import palindrome

"""
The decimal number, 585 = 1001001001_2 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)
"""

def is_double_base_palindrome(n):
    return palindrome(str(n)) and palindrome(bin(n)[2:])

def sum_of_double_base_palindrome(lim):
    double_base_palindromes = []

    for n in xrange(lim):
        if is_double_base_palindrome(n):
            double_base_palindromes.append(n)

    return sum(double_base_palindromes)


if __name__ == '__main__':
    main(sum_of_double_base_palindrome, 10**6)
예제 #42
0
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

NOTE: As there are only 16384 routes, it is possible to solve this problem by
trying every route. However, Problem 67, is the same challenge with a triangle
containing one-hundred rows; it cannot be solved by brute force, and requires a
clever method! ;o)
"""

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)


def find_max_route(filename):
    f = open(filename)
    triangle = map(lambda x: map(int, x.split(' ')), f.read().split('\n')[:-1])
    for under, above in pairwise(triangle[::-1]):
        for i, pair in enumerate(pairwise(under)):
            above[i] += max(pair)

    return triangle[0][0]


if __name__ == '__main__':
    main(find_max_route, './018_data.txt')
예제 #43
0
from utils.main import main
"""
The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025  385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""


def diff_between_sum_of_squares(n):
    sum_of_squares = sum(map(lambda x: x**2, range(n)))
    square_of_sum = sum(range(n))**2

    return square_of_sum - sum_of_squares


if __name__ == '__main__':
    main(diff_between_sum_of_squares, 101)
예제 #44
0
from utils.my_math import Prime
from utils.main import main

""" Add all the natural numbers below one thousand
that are multiples of 3 or 5.
"""

def using_union(maximum):
    three = range(3, maximum, 3)
    five = range(5, maximum, 5)
    return sum(set().union(three, five))

def using_iteration(maximum):
    sum_ = 0

    for i in range(3, maximum, 1):
        if i % 3 == 0 or i % 5 == 0:
            sum_ += i

    return sum_


if __name__ == '__main__':
    main(using_union, 1000)
    main(using_iteration, 1000)
예제 #45
0
from utils.main import main

"""
A Pythagorean triplet is a set of three natural numbers, a  b  c, for which,

a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""

def product_of_triplet_with_sum(sum_):
    for a in range(1, sum_ / 3):
        for b in range(a, (sum_ / 3)*2 - a):
            c = sum_ - a - b
            if (a**2 + b**2) == c**2:
                return a*b*c


if __name__ == '__main__':
    main(product_of_triplet_with_sum, 1000)
예제 #46
0
from utils.my_math import Prime
from utils.main import main

def find_prime(n):
    ps = Prime()
    return ps.up_to_element(n)[-1]


if __name__ == '__main__':
    main(find_prime, 10001)
예제 #47
0
from utils.my_math import Prime
from utils.main import main


def find_prime(n):
    ps = Prime()
    return ps.up_to_element(n)[-1]


if __name__ == '__main__':
    main(find_prime, 10001)
예제 #48
0
Let d(n) be defined as the sum of proper divisors of n (numbers less than n
which divide evenly into n).
If d(a) = b and d(b) = a, where a  b, then a and b are an amicable pair and
each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55
and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and
142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.
"""

def d(n, pl):
    return sum(pl.get_proper_divisors(n))


def sum_of_amicable_numbers(n):
    pl = Prime()
    amicable_sum = 0

    for i in xrange(2, n):
        divisor_sum = d(i, pl)
        if divisor_sum < i and divisor_sum > 0 and d(divisor_sum, pl) == i:
            amicable_sum += divisor_sum + i

    return amicable_sum


if __name__ == '__main__':
    main(sum_of_amicable_numbers, 10000)
예제 #49
0
    numbers[30] = 'thirty'
    numbers[40] = 'forty'
    numbers[50] = 'fifty'

    for i in range(60, 100, 10):
        numbers[i] = numbers[i/10] + 'ty'

    numbers[80] = 'eighty'

    for i in range(20, 100, 10):
        generate_written_out_numbers(i, numbers[i], '', range(1, 10), numbers)

    for i in range(100, 1000, 100):
        numbers[i] = numbers[i/100] + 'hundred'
        generate_written_out_numbers(i, numbers[i] + 'and', '', range(1, 100),
                                     numbers)

    numbers[1000] = 'onethousand'

    return numbers


def length_of_written_out_numbers(start, end):
    numbers = get_written_out_numbers()
    return sum(map(len, numbers[start:end]))



if __name__ == '__main__':
    main(length_of_written_out_numbers, 1, 1001)