CodingBat Python make_chocolate code failing in "other tests"

Karma Cool

There is a coding problem on CodingBat.com (Logic-2 Python section) that asks for a function to determine how many small chocolate bars are used for a weight requirement. The question is as follows:

We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.

make_chocolate(4, 1, 9) → 4 make_chocolate(4, 1, 10) → -1 make_chocolate(4, 1, 7) → 2

I came up with this solution to the problem but it still fails in "other tests". Is there any problem that causes this?

Code:

def make_chocolate(small, big, goal):
    if (small + 5*big < goal) or (goal % 5 > small):
        return -1

    elif small >= goal:
        return small
    else:
        smallnum = 0
        for i in range(1,big+1):
            if 5*i + small >= goal:
                if 5*i > goal:
                    break
                smallnum = goal - 5*i
        return smallnum

EDIT: I have managed to finish the problem thanks to Mariah Akinbi. I have updated the code as follows:

def make_chocolate(small, big, goal):
    if (small + 5*big < goal) or (goal % 5 > small):
        return -1

    elif 5 <= goal:
        smallnum = 0
        for i in range(1,big+1):
            if 5*i + small >= goal:
                if 5*i > goal:
                    break
                smallnum = goal - 5*i
        return smallnum
  return goal
Mariah Akinbi

Your code seems to fail on:

make_chocolate(8,1,7)--> returns 8 instead of 2

I believe the issue is:

elif small >= goal:
    return small

The instructions say to use the big bars first, then use the nuggets to meet the goal.

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

Практический вопрос CodingBat - строки Python

рекурсивное упражнение по codingbat

Рекурсия codingbat

Есть ли более простой способ сделать string_match из CodingBat в Python?

monkeypatch in python, leaking mocks to other tests causing them to fail

Есть ли более простой способ сделать rotate_left3 на CodingBat Python?

I am trying to make this code work but failing due to End With

I am trying to make this code work but failing due to End With

Я получаю сообщение об ошибке Time Out, когда отправляю свой код на CodingBat Python (https://codingbat.com/prob/p118406)

failing pjsua python module

AWS Code Deploy Failing Scripts из-за разрешений

Codingbat strDist: упражнение на рекурсию

CodingBat sameEnds работает со строками

twoTwo загадка от CodingBat

Failing to get attribute value in Python

Python: CSV delimiter failing randomly

USMT script is failing with Return Code 71

Artifactory JFrog Backup failing with error code 401

Why is this code failing a test case [Max Distance]

Python failing to recognize the number of arguments of my function

Java Codingbat notAlone - почему он не работает для этого конкретного примера

проблема вычитания рекурсии от CodingBat.com

Есть ли более простое решение для Codingbat fix45?

codingbat Проблема: close_far | провалив только один тест | пятка

Défi Codingbat : maxBlock

KIVY python: make button clickable in python code

Failing task since return code was -1 while expected 0 - Bamboo

Grunt watch task failing to transpile ES6 code

NPM install task failing in Azure Devops, same code worked previously

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  3. 3

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  4. 4

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  5. 5

    How to click an array of links in puppeteer?

  6. 6

    Merging legends in plotly subplot

  7. 7

    ViewPager2 мигает / перезагружается при смахивании

  8. 8

    Отчеты Fabric Debug Craslytic: регистрация, отсутствует идентификатор сборки, применить плагин: io.fabric

  9. 9

    How to normalize different curves drawn with geom = "step" when using stat_summary

  10. 10

    无法通过Vue在传单中加载pixiOverlay

  11. 11

    как я могу удалить vue cli 2?

  12. 12

    Как я могу нарисовать заполненный прямоугольник в JFreeChart?

  13. 13

    SQL Вычтите две строки друг от друга в одном столбце, чтобы получить результат

  14. 14

    Elasticsearch - Нечеткий поиск не дает предложения

  15. 15

    Single legend for Plotly subplot for line plots created from two data frames in R

  16. 16

    Описание моего типа Parser как серии преобразователей монад

  17. 17

    Как изменить цвета запятых и скобок в VS Code

  18. 18

    Сброс значения <input type = "time"> в Firefox

  19. 19

    Почему прокси в vue.config.js 404

  20. 20

    Как установить параметр -noverify с gradle ktx для робоэлектрических тестов Android?

  21. 21

    В чем разница между ifstream, ofstream и fstream?

популярныйтег

файл