Утвердить, что выражение является строкойPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Утвердить, что выражение является строкой

Сообщение Anonymous »

import doctest

def count_wheels(num_bicycles, num_tricycles, num_cars, num_trucks):
pass
def need_to_buy_ticket(age, height):
pass
def pound(expression: str) -> int:
"""
Return the result of the pound operation that is defined as "x # y" = x^2 - y^2

>>> pound("2 # 3")
-5
>>> pound("0 # 0")
0
>>> pound("6 # 1")
35
>>> pound(5)
Traceback (most recent call last):
...
AssertionError: invalid argument type
"""
# Assert that the expression is a string
assert type(expression) == str, "invalid argument type"

# 1 Find x and y in "x # y"
# 1.1 Find where '#' is
pound_index = expression.find('#')

# 1.2 Find what the number is before '#' and let it be x
x_str = expression[:pound_index].strip()
x = int(x_str)

# 1.3 Find what the number is after '#' and let it be y
y_str = expression[pound_index + 1:].strip() # Adjusted to get y correctly
y = int(y_str)

# 2 Calculate the result based on the definition of '#'
# which is x # y = x^2 – y^2
result = x * x - y * y

# Show the result
return result

# Run the doctests to verify the implementation
doctest.testmod()


Подробнее здесь: https://stackoverflow.com/questions/790 ... s-a-string
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»