Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
cat > .gitignore << 'EOF'
# Python cache / bytecode
__pycache__/
*.py[cod]
*.pyo
*.pyd

# Test/pytest
.pytest_cache/

# Virtual envs
.venv/
venv/

# IDE
.idea/
.vscode/

# macOS
.DS_Store
EOF
93 changes: 93 additions & 0 deletions Area of triangle/advanced_area.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""
advanced_area.py
Fast, flexible triangle area calculator.
- Interactive prompts (default)
- CLI: python advanced_area.py <base> <height>
- Batch: echo "b1 h1\nb2 h2\n..." | python advanced_area.py
- Auto-NumPy for big batches, if available
"""
import os
import sys

def _read_float_interactive(prompt: str) -> float:
while True:
try:
return float(input(prompt))
except ValueError:
print("Please enter a valid number.")

def _areas_python(floats):
it = iter(floats)
return [0.5 * float(b) * float(h) for b, h in zip(it, it)]

def _stdin_has_data() -> bool:
"""
Return True only if there is real data waiting on stdin.
Avoids blocking in IDEs (like PyCharm) where stdin is a pipe without data.
"""
# If it's a real terminal, there's no piped data
if sys.stdin.isatty():
return False
# POSIX: non-blocking poll
try:
import select # noqa
r, _, _ = select.select([sys.stdin], [], [], 0.0)
return bool(r)
except Exception:
# Fallback: in uncertain environments (e.g., some IDEs), don't block
# unless explicitly forced by an env var or flag.
return False

def main():
argv = sys.argv[1:]

# 1) CLI: python advanced_area.py 3 4 -> 6
if len(argv) == 2:
try:
b = float(argv[0]); h = float(argv[1])
except ValueError:
print("Error: arguments must be numbers (usage: advanced_area.py <base> <height>)", file=sys.stderr)
sys.exit(2)
print(0.5 * b * h)
return

# 2) Batch via stdin (only if data is present)
if _stdin_has_data():
data = sys.stdin.buffer.read()
parts = data.split()
try:
floats = list(map(float, map(bytes.decode, parts)))
except ValueError:
print("Error: All piped values must be numeric.", file=sys.stderr)
sys.exit(2)

if len(floats) == 2:
print(0.5 * floats[0] * floats[1])
return
if len(floats) % 2 != 0:
print("Error: Provide an even count of numbers (pairs of base height).", file=sys.stderr)
sys.exit(2)

# Auto NumPy for big batches
if len(floats) >= 2000:
try:
import numpy as np
arr = np.asarray(floats, dtype=np.float64).reshape(-1, 2)
areas = 0.5 * arr[:, 0] * arr[:, 1]
sys.stdout.write("\n".join(f"{x:.10g}" for x in areas) + "\n")
return
except Exception:
pass

areas = _areas_python(floats)
sys.stdout.write("\n".join(f"{a:.10g}" for a in areas) + ("\n" if areas else ""))
return

# 3) Interactive prompts (default in PyCharm)
b = _read_float_interactive("Enter base length of triangle: ")
h = _read_float_interactive("Enter height of triangle: ")
print(f"Area of triangle is: {0.5 * b * h:.10g}")

if __name__ == "__main__":
main()
25 changes: 23 additions & 2 deletions Area of triangle/area.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,23 @@
# Area of Triangle
This program .
# advanced_area.py — Fast Area of Triangle

This is a faster, flexible alternative to `area.py` that keeps the original script intact while adding **CLI**, **batch**, and **auto-vectorized** modes (NumPy if available).

## Why this exists
- Keep `area.py` unchanged for tutorials and simple users.
- Provide a high-throughput path for large inputs (stdin / files).
- Offer a clean CLI for scripting and CI.

## Quick start
```bash
# Interactive prompts
python advanced_area.py

# One-off CLI
python advanced_area.py 3 4
# -> 6

# Batch via stdin (one area per line in output)
printf "3 4\n5 2\n8 7\n" | python advanced_area.py
# -> 6
# -> 5
# -> 28
31 changes: 31 additions & 0 deletions Area of triangle/tests/test_advanced_area.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import subprocess, sys, os, math

PYTHON = sys.executable
SCRIPT = os.path.join(os.path.dirname(__file__), "..", "advanced_area.py")

def run(cmd, inp=None):
p = subprocess.run([PYTHON, SCRIPT, *cmd],
input=inp.encode() if isinstance(inp, str) else inp,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p.returncode, p.stdout.decode().strip(), p.stderr.decode().strip()

def test_cli_single():
rc, out, err = run(["3", "4"])
assert rc == 0
assert math.isclose(float(out), 6.0, rel_tol=1e-12)

def test_stdin_pair():
rc, out, err = run([], "3 4\n")
assert rc == 0
assert math.isclose(float(out), 6.0, rel_tol=1e-12)

def test_stdin_multiple_lines():
rc, out, err = run([], "3 4\n5 2\n8 7\n")
assert rc == 0
vals = list(map(float, out.split()))
assert vals == [6.0, 5.0, 28.0]

def test_reject_odd_count():
rc, out, err = run([], "3 4 5")
assert rc != 0
assert "even count" in err
5 changes: 5 additions & 0 deletions CONTRIBUTER_INFO.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

# Contributer Section:-

- Name : Mohammad Saqib Manan
- Company name : CivicDataLab

<br>

- Name : Ayush
- Collage name : ISM Dhanbad

Expand Down