【hackerrank】-Day 17: More Exceptions

24 篇文章 0 订阅
24 篇文章 0 订阅

30-more-exceptions

Objective
Yesterday’s challenge taught you to manage exceptional situations by using try and catch blocks. In today’s challenge, you’re going to practice throwing and propagating an exception. Check out the Tutorial tab for learning materials and an instructional video!

Task
Write a Calculator class with a single method: int power(int,int). The power method takes two integers, and , as parameters and returns the integer result of . If either or is negative, then the method must throw an exception with the message: n and p should be non-negative.

Note: Do not use an access modifier (e.g.: public) in the declaration for your Calculator class.

Input Format

Input from stdin is handled for you by the locked stub code in your editor. The first line contains an integer, , the number of test cases. Each of the subsequent lines describes a test case in space-separated integers denoting and , respectively.

Constraints

No Test Case will result in overflow for correctly written code.
Output Format

Output to stdout is handled for you by the locked stub code in your editor. There are lines of output, where each line contains the result of as calculated by your Calculator class’ power method.

Sample Input

4
3 5
2 4
-1 -2
-1 3
Sample Output

243
16
n and p should be non-negative
n and p should be non-negative
Explanation

: and are positive, so power returns the result of , which is .
and are positive, so power returns the result of =, which is .
Both inputs ( and ) are negative, so power throws an exception and is printed.
One of the inputs () is negative, so power throws an exception and is printed.

Current Buffer (saved locally, editable)

#Write your code here
class Calculator(object):
    def power(self, n, p):
        if n < 0 or p < 0:
            return "n and p should be non-negative"
        return n**p

myCalculator=Calculator()
T=int(input())
for i in range(T):
    n,p = map(int, input().split())
    try:
        ans=myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)

Testcase 0 Testcase 1
Input (stdin)Download
4
3 5
2 4
-1 -2
-1 3
Expected OutputDownload
243
16
n and p should be non-negative
n and p should be non-negative
Compiler Message
Success

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值