# Another Challenge

#Basic#CSV

Let's do another coding challenge related to triangle.

# Assignment 20

Create a Python script named triangle_simulation.py that prompts the user for a number of triangles to be generated. Then randomly create triangles and calculate the area of each triangle.

For any random triangle, we only know that one side has length that is within range [10, 100) and another side has length that is within range [20, 90), which means we don't know whether it's acute, right, or obtuse.

Finally create a triangles.csv file with the lengths of sides and area information for each triangle.

Here's a list of resources that you need to read before getting started, if you have no clue.

A sample run looks like the following.

python triangle_simulation.py
Enter number of triangles: 3
3 triangles generated
1
2
3

The triangles.csv looks like the following.

a,b,c,area
27.371837490898923,64.30764583882535,73.10392131172875,872.5803092319529
53.92225612843062,54.46279074600567,47.28866198862315,1152.8798641166993
67.86950940943723,73.431943006571,30.40005862427104,1031.0399492358679
1
2
3
4
Sample Solution
import csv
from math import sqrt
from random import random

number = int(input("Enter number of triangles: "))

triangles = []
for _ in range(number):
    a = 10 + random() * 90
    b = 20 + random() * 70

    diff = abs(a - b)
    while True:
        c = diff + (a + b - diff) * random()
        if c != diff:
            break

    triangles.append((a, b, c))


def area(a, b, c):
    p = (a + b + c) / 2
    return sqrt(p * (p - a) * (p - b) * (p - c))


with open("triangles.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["a", "b", "c", "area"])
    writer.writerows([[a, b, c, area(a, b, c)] for a, b, c in triangles])

print(f"{number} triangles generated")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31