Basic Python Help ASAP !?

Hi, I am a beginner to Python, and I have a few questions regarding Python that I just can't figure out how to completely do.

Without using branches or loops:

Two numbers a and b are called Pythagorean pairs if both a and b are integers and there exists an integer c such that a 2 + b2 = c2. Write a function pythagorean_pair(a,b) that takes two integers a and b as input and returns True if a and b are Pythagorean pairs and False otherwise.

Write a program the computes the minimum number of coins that the cashier can return. To solve this problem use the greedy algorithm explained below.

The program should first ask the user for the amount of money he/she is owed (in dollars). You may assume that the user will enter a positive number. It should then print the minimum number of coins with which that amount can be made. Assume that the only coins available are quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent).

Thank you.

1 Answer

  • 5 months ago

    All you need to do in the first case is to test to see if the quantity (a^2 + b^2) is a perfect square, so compute the square root, round it to an integer and see if the square of that is the right value.

    c_squared = a**2 + b**2 # or, a*a + b*b is the same thing only faster and smaller

    c = round(c_squared ** 0.5) # round sqrt(c) to nearest whole number

    is_pythagorean_pair = (c*c == c_squared)

    For small enough numbers, that's even easier:

    is_pythagorean_pair = ((a*a + b*b) ** 0.5).is_integer()

    I've used x**0.5, which gives the same result as math.sqrt(x) without importing anything.

    For the change problem, I suggest learning about the divmod() built-in function. If you have $77 to hand out, with as much as possible in $20 bills, you'd choose 77//20 = 3 $20 bills and be left with 77%20 = 17 dollars to dispense in smaller bills. Right?

    Well, divmod(a, b) returns a pair of numbers (a//b,. a%b):

    >>> divmod(77,20)

    (3, 17)

    So you can use:

    twenties, dollars_left = divmod(total_dollars, 20) get the number of $20 bills and the number of dollars left, in one statement. Then:

    tens, dollars_left = divmod(dollars_left, 10)

    fives, ones = divmod(dollars_left, 5)

    With the $77 example, the first of those two makes dollars == 17//10 == 1 and dollars_left == 7. The second makes fives == 7//5 == 1 and ones == 2. Another sample from Idle:

    >>> divmod(17, 10)

    (1, 7)

    >>> divmod(7, 5)

    (1, 2)

    That's the essence of the "greedy" method in dollars. Your problem is very similar, but with quarters, dimes, nickels, and pennies.

    • Log in to reply to the answers
Still have questions? Get answers by asking now.