eng
competition

Text Practice Mode

Code Snippets (Python, Java, JavaScript, Go, Rust, and C++)

created Friday June 27, 23:03 by Abraham Bekele


0


Rating

1077 words
0 completed
00:00
# Python typing practice snippet
# This snippet defines a simple function to calculate the factorial of a number
# and then calls it for demonstration.
 
def calculate_factorial(n: int) -> int:
    """
    Calculates the factorial of a non-negative integer.
 
    Args:
        n: The non-negative integer.
 
    Returns:
        The factorial of n.
    """
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers.")
    elif n == 0:
        return 1
    else:
        result = 1
        for i in range(1, n + 1):
            result *= i
        return result
 
# --- Main execution ---
if __name__ == "__main__":
    number = 5
    try:
        fact = calculate_factorial(number)
        print(f"The factorial of {number} is: {fact}")
    except ValueError as e:
        print(f"Error: {e}")
 
    # Another example
    number_two = 7
    try:
        fact_two = calculate_factorial(number_two)
        print(f"The factorial of {number_two} is: {fact_two}")
    except ValueError as e:
        print(f"Error: {e}")
 
# This code demonstrates basic function definition, loops,
# conditional statements, and error handling in Python.
```java
// Java typing practice snippet
// This Java program calculates the sum of the first N natural numbers.
 
public class SumOfNaturalNumbers {
 
    /**
     * Calculates the sum of the first 'n' natural numbers.
     *
     * @param n The number of natural numbers to sum.
     * @return The sum of the first 'n' natural numbers.
     */
    public static int calculateSum(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Input must be a non-negative number.");
        }
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
 
    // Main method - entry point of the program
    public static void main(String[] args) {
        int limit1 = 10;
        try {
            int result1 = calculateSum(limit1);
            System.out.println("The sum of the first " + limit1 + " natural numbers is: " + result1);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
 
        int limit2 = 25;
        try {
            int result2 = calculateSum(limit2);
            System.out.println("The sum of the first " + limit2 + " natural numbers is: " + result2);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
// This snippet covers basic class structure, methods, loops,
// and exception handling in Java.
```javascript
// JavaScript typing practice snippet
// This script defines a function to reverse a given string
// and then demonstrates its usage.
 
/**
 * Reverses a given string.
 * @param {string} str The input string to reverse.
 * @returns {string} The reversed string.
 */
function reverseString(str) {
    if (typeof str !== 'string') {
        console.error("Input must be a string.");
        return "";
    }
    return str.split('').reverse().join('');
}
 
// --- Demonstration ---
console.log("Original string: Hello World");
const reversed1 = reverseString("Hello World");
console.log("Reversed string: " + reversed1); // Expected: dlroW olleH
 
console.log("\nOriginal string: JavaScript");
const reversed2 = reverseString("JavaScript");
console.log("Reversed string: " + reversed2); // Expected: tpircSavaJ
 
console.log("\nTesting with non-string input:");
const reversed3 = reverseString(12345); // Should log an error
console.log("Reversed string (invalid input): " + reversed3);
 
// This JavaScript code showcases function definition, string manipulation,
// and basic type checking for robustness.
```go
// Go typing practice snippet
// This Go program checks if a given number is prime.
 
package main
 
import "fmt"
 
// isPrime checks if a number is prime.
// A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
func isPrime(num int) bool {
    if num <= 1 {
        return false // Numbers less than or equal to 1 are not prime
    }
    for i := 2; i*i <= num; i++ {
        if num%i ==  {
            return false // Divisible by a number other than 1 and itself
        }
    }
    return true // No divisors found, so it's prime
}
 
func main() {
    // Test cases for isPrime function
    numbersToTest := []int{1, 2, 3, 4, 5, 7, 10, 11, 13, 17, 20, 23, 29}
 
    fmt.Println("Checking prime numbers:")
    for _, num := range numbersToTest {
        if isPrime(num) {
            fmt.Printf("%d is a prime number.\n", num)
        } else {
            fmt.Printf("%d is not a prime number.\n", num)
        }
    }
}
 
// This Go snippet demonstrates basic function definition, loops,
// conditional statements, and array iteration.
```rust
// Rust typing practice snippet
// This Rust program calculates the nth Fibonacci number using an iterative approach.
 
// Calculates the nth Fibonacci number.
// The sequence starts with 0, 1, 1, 2, 3, 5...
fn fibonacci(n: u32) -> u64 {
    if n ==  {
        return 0;
    } else if n == 1 {
        return 1;
    }
 
    let mut a: u64 = 0;
    let mut b: u64 = 1;
    let mut sum: u64 = 0;
 
    // Iterate n-1 times to reach the nth Fibonacci number
    for _i in 2..=n {
        sum = a + b;
        a = b;
        b = sum;
    }
    b // 'b' will hold the nth Fibonacci number
}
 
fn main() {
    // Test cases for the fibonacci function
    let n1 = 0;
    println!("Fibonacci({}) is: {}", n1, fibonacci(n1)); // Expected: 0
 
    let n2 = 1;
    println!("Fibonacci({}) is: {}", n2, fibonacci(n2)); // Expected: 1
 
    let n3 = 5;
    println!("Fibonacci({}) is: {}", n3, fibonacci(n3)); // Expected: 5 (0, 1, 1, 2, 3, 5)
 
    let n4 = 10;
    println!("Fibonacci({}) is: {}", n4, fibonacci(n4)); // Expected: 55
 
    let n5 = 20;
    println!("Fibonacci({}) is: {}", n5, fibonacci(n5)); // Expected: 6765
}
 
// This Rust code demonstrates function definition, mutable variables,
// loops, and basic ownership/borrowing concepts (implicitly here).
```cpp
// C++ typing practice snippet
// This C++ program implements a simple function to check if a number is even or odd.
 
#include <iostream> // Required for input/output operations
#include <string>   // Required for using string class
 
// Function to check if a number is even or odd
// Returns "Even" if the number is even, "Odd" otherwise.
std::string checkEvenOrOdd(int number) {
    if (number % 2 == 0) {
        return "Even";
    } else {
        return "Odd";
    }
}
 
int main() {
    // Test cases for the checkEvenOrOdd function
    int num1 = 4;
    std::cout << num1 << " is " << checkEvenOrOdd(num1) << std::endl; // Expected: 4 is Even
 
    int num2 = 7;
    std::cout << num2 << " is " << checkEvenOrOdd(num2) << std::endl; // Expected: 7 is Odd
 
    int num3 = 0;
    std::cout << num3 << " is " << checkEvenOrOdd(num3) << std::endl; // Expected:  is Even
 
    int num4 = -3;
    std::cout << num4 << " is " << checkEvenOrOdd(num4) << std::endl; // Expected: -3 is Odd
 
    // Return  to indicate successful execution
    return 0;
}
 
// This C++ snippet covers basic function definition, conditional statements,
// input/output using iostream, and string manipulation.
 

saving score / loading statistics ...