Я пытаюсь создать класс, генерирующий последовательность Фибоначчи. Ниже приведены два моих модуля: модуль fibonacci.py и модуль test_fibonacci.py. Первые два теста пройдены, но третий, похоже, не пройден, что бы я ни делал. Как мне это пройти? Помогите мне исправить это, пожалуйста.
Код fibonacci.py:
class Fibonacci:
"""An iterable for creating a Fibonacci series"""
def __init__(self, max_count):
"""
Constructor requires a single positional argument
which must be an integer.
"""
self.max_count = max_count # Maximum number of iterations
self.current_count = 0 # Keeps track of number of Fibonacci numbers generated
self.current_number = 0 # Tracks current Fibonacci number
self.next_number = 1 # Tracks next Fibonacci number
# Raises ValueError for non-integer input
if not isinstance(max_count, int):
raise ValueError(f'{max_count} is not an integer.')
def __iter__(self):
"""Returns the instance of Fibonacci class as an iterator"""
return self
def __next__(self):
"""Defines the instance of Fibonacci class as an iterator"""
# Handles the case where max_count is 0 by returning 0 once
if self.max_count == 0 and self.current_count == 0:
self.current_count += 1
return 0
# Stops iteration when the number of iterations equals max_count
if self.current_count >= self.max_count:
raise StopIteration
temp = self.next_number
self.next_number = self.current_number + self.next_number
self.current_number = temp
self.current_count += 1 # Counter incremented for next iteration
return self.current_number # Returns the current Fibonacci number
Вот код теста:
import pytest
from fibonacci import Fibonacci
def test_non_integer():
"""Test that non-integer input raises ValueError"""
with pytest.raises(ValueError):
Fibonacci(3.14)
def test_max_count_0():
"""
Tests that [0] is returned with constructor value of 0
if cast as a list.
"""
assert list(Fibonacci(0)) == [0]
def test_max_count_1():
"""
Tests that [0,1] is returned with constructor value of 1
if cast as a list.
"""
assert list(Fibonacci(1)) == [0,1]
Вот результаты Pytest:
test_fibonacci.py::test_non_integer PASSED [ 33%]
test_fibonacci.py::test_max_count_0 PASSED [ 66%]
test_fibonacci.py::test_max_count_1 FAILED [100%]
test_fibonacci.py:37 (test_max_count_1)
[1] != [0, 1]
Expected :[0, 1]
Actual :[1]
def test_max_count_1():
"""
Tests that [0,1] is returned with constructor value of 1
if cast as a list.
"""
> assert list(Fibonacci(1)) == [0,1]
E assert [1] == [0, 1]
E
E At index 0 diff: 1 != 0
E Right contains one more item: 1
E
E Full diff:
E [
E - 0,
E 1,
E ]
test_fibonacci.py:43: AssertionError
Подробнее здесь: https://stackoverflow.com/questions/792 ... e-properly
Мой класс Python не будет правильно генерировать последовательность Фибоначчи ⇐ Python
Программы на Python
1733108222
Anonymous
Я пытаюсь создать класс, генерирующий последовательность Фибоначчи. Ниже приведены два моих модуля: модуль fibonacci.py и модуль test_fibonacci.py. Первые два теста пройдены, но третий, похоже, не пройден, что бы я ни делал. Как мне это пройти? Помогите мне исправить это, пожалуйста.
Код fibonacci.py:
class Fibonacci:
"""An iterable for creating a Fibonacci series"""
def __init__(self, max_count):
"""
Constructor requires a single positional argument
which must be an integer.
"""
self.max_count = max_count # Maximum number of iterations
self.current_count = 0 # Keeps track of number of Fibonacci numbers generated
self.current_number = 0 # Tracks current Fibonacci number
self.next_number = 1 # Tracks next Fibonacci number
# Raises ValueError for non-integer input
if not isinstance(max_count, int):
raise ValueError(f'{max_count} is not an integer.')
def __iter__(self):
"""Returns the instance of Fibonacci class as an iterator"""
return self
def __next__(self):
"""Defines the instance of Fibonacci class as an iterator"""
# Handles the case where max_count is 0 by returning 0 once
if self.max_count == 0 and self.current_count == 0:
self.current_count += 1
return 0
# Stops iteration when the number of iterations equals max_count
if self.current_count >= self.max_count:
raise StopIteration
temp = self.next_number
self.next_number = self.current_number + self.next_number
self.current_number = temp
self.current_count += 1 # Counter incremented for next iteration
return self.current_number # Returns the current Fibonacci number
Вот код теста:
import pytest
from fibonacci import Fibonacci
def test_non_integer():
"""Test that non-integer input raises ValueError"""
with pytest.raises(ValueError):
Fibonacci(3.14)
def test_max_count_0():
"""
Tests that [0] is returned with constructor value of 0
if cast as a list.
"""
assert list(Fibonacci(0)) == [0]
def test_max_count_1():
"""
Tests that [0,1] is returned with constructor value of 1
if cast as a list.
"""
assert list(Fibonacci(1)) == [0,1]
Вот результаты Pytest:
test_fibonacci.py::test_non_integer PASSED [ 33%]
test_fibonacci.py::test_max_count_0 PASSED [ 66%]
test_fibonacci.py::test_max_count_1 FAILED [100%]
test_fibonacci.py:37 (test_max_count_1)
[1] != [0, 1]
Expected :[0, 1]
Actual :[1]
def test_max_count_1():
"""
Tests that [0,1] is returned with constructor value of 1
if cast as a list.
"""
> assert list(Fibonacci(1)) == [0,1]
E assert [1] == [0, 1]
E
E At index 0 diff: 1 != 0
E Right contains one more item: 1
E
E Full diff:
E [
E - 0,
E 1,
E ]
test_fibonacci.py:43: AssertionError
Подробнее здесь: [url]https://stackoverflow.com/questions/79242841/my-python-class-wont-generate-a-fibonacci-sequence-properly[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия