Python Forum
Making maths .py program faster
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Making maths .py program faster
#1
Hello!

I just started learning python this week and i'm struggling with this program.

It's a program that gets one input, being a float with 2 decimals called t, and is supposed to give back a, b and c, also floats with 2 decimals.

The conditions are:
a * b * c == t
a + b + c == t
0 <= a <= b <= c

I already have the code and it works! But it's not fast enough. Anyone has ideas to make it faster?
https://hastebin.josephbanks.me/xamohiwenu.py
Reply
#2
(Feb-16-2018, 05:22 PM)Shutcois Wrote: https://hastebin.josephbanks.me/xamohiwenu.py
Quote:
som = float(input())
totaal = int(som*100)
totaal2 = int(totaal*10000)

def sum_to_n(n, size, limit=None):
    """Produce all lists of size positive integers in decreasing order
    that add up to n."""
    if size == 1:
        yield [n]
        return
    if limit is None:
        limit = n
    start = (n + size - 1) // size
    stop = min(limit, n - size + 1) + 1
    for i in range(start, stop):
        for tail in sum_to_n(n - i, size - 1, i):
            yield [i] + tail


for partition in sum_to_n(totaal, 3):
    if partition[0] * partition[1] * partition[2] == totaal2 and partition[0] + partition[1] + partition[2] == totaal:
        c = partition[0]
        b = partition[1]
        a = partition[2]
        break
print(f"${format(a/100, '.2f')} + ${format(b/100, '.2f')} + ${format(c/100, '.2f')} = ${format(a/100, '.2f')} x ${format(b/100, '.2f')} x ${format(c/100, '.2f')} = ${format(som, '.2f')}")

Added your code for you :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Maths and python: Compute stress level cheerful 1 2,677 Oct-20-2021, 10:05 AM
Last Post: Larz60+
  why is there an unexpected maths result from a float calculation? maryab 3 2,821 Jun-09-2019, 08:28 PM
Last Post: snippsat
  Increasing difficulty of a maths game Maxxy_Gray 1 3,151 Apr-04-2018, 03:00 PM
Last Post: sparkz_alot
  making a program for counting hurmet 8 118,097 Oct-01-2017, 06:40 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020