P
P
Polina2020-01-18 16:20:14
Python
Polina, 2020-01-18 16:20:14

Why does recursion work incorrectly?

Toffee's problem
weighs X grams, tangerine - Y grams, gingerbread - Z grams.
It is required to write a program that will determine how many different variants of gifts weighing exactly W grams Santa Claus can make.
Specifications Input
The single line of the input file INPUT.TXT contains four integers X, Y, Z and W (1 ≤ X, Y, Z ≤ 100, 1 ≤ W ≤ 1000).
Output
The output file OUTPUT.TXT should contain one integer - the number of gift options.

with open('data317.txt') as f:
     a, h, z, n = [int(x) for x in next(f).split()] # read first line

print(a, h, z, n)

edge = max(a, h, z)
zero = 0
w = open("output.txt", "w")
if n != 0:
    def f(n, edge):
        #print("f", n)

        if n == 0: return 1
        if n < 0:
            return 0

        count = 0

        if edge >= a:
            count = f(n - a, a)
        if edge >= h:
            count = count + f(n - h, h)
        if edge >= z:
            count = count + f(n - z, z)

        return count

    print(f(n, edge))

    w.write(str(f(n, edge)))
else:
    w.write(str(0))
w.close()

It does not pass testing, while it seems to determine correctly
Source: https://acmp.ru/index.asp?main=task&id_task=317

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2020-01-19
Mezenina @medigi27

Your program breaks if X=Y, for example.
To fix it, instead of the edge weight and comparing it with the cost of the product, pass a number from 1 to 3 into the function. If the number is <=1, then you can take x and pass 1. If <=2, then you can take y and pass 2, etc.

A
Andrey, 2020-01-18
@anerev

The power of google

with open("input.txt", "r") as file:
  x, y, z, w = [int(x) for x in next(file).split()]

count = 0
for i in range(0, w // x + 1):
    rest = w - x * i
    for j in range(0 , rest // y + 1):
        if (rest - y * j) % z == 0:
            count += 1
  
with open("output.txt", "w") as file:
  file.write(str(count))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question