ssssmaner
ssssmaner

Reputation: 25

Pythagorean triple with list

num_list = [(20, 99, 101),
            (60, 91, 109),
            (16, 112, 113),
            (44, 117, 125)]

Three numbers a, b, c, are called Pythagorean triple if a2 + b2 = c2 . Make a lambda function called is_pythagorean_triple that accepts three arguments. It returns the value True if it is a pythagorean triple. Otherwise, it is False. By using that function and the provided list, print the following:

(20, 99, 101) is a triple Pythagoras.
(60, 91, 109) is a triple Pythagoras.
(16, 112, 113) is not a triple Pythagoras.
(44, 117, 125) is a triple Pythagoras.

Hint: To get the first element in the first triple, you can write num_list[0][0]

My code is a little bit mistakes like below:

is_pythagorean_triple = lambda a, b, c : a **2 + b**2 == c**2
print(is_pythagorean_triple(5, 6, 2))
print(is_pythagorean_triple(20, 99, 101))

the first print can get false and the second one is True I want to know how to use the num_list[0][0] so that I can use that list?

Upvotes: 0

Views: 199

Answers (1)

azro
azro

Reputation: 54148

For a specific element of your list, you can pass the values to the method like this

print(is_pythagorean_triple(num_list[0][0], num_list[0][1], num_list[0][2]))

# Or flatten values like this
print(is_pythagorean_triple(*num_list[0]))

You may iterate on your list to test for all

for x, y, z in num_list:
    print(x, y, z, is_pythagorean_triple(x, y, z))

for coord in num_list:
    print(coord, is_pythagorean_triple(*coord))

Get expected output

for coords in num_list:
    if is_pythagorean_triple(*coords):
        print(coords, "is a triple Pythagoras.")
    else:
        print(coords, "is not a triple Pythagoras.")

You lambda is correct, it's the same as the following. It takes argument named a, b, c and return a bool result, then you provide values from num_list

def is_pythagorean_triple(a: int, b: int, c: int) -> bool:
    return (a ** 2 + b ** 2) == c ** 2

Upvotes: 1

Related Questions