Coding Set 2
Coding Set 2
1. Factorial Calculation
Problem: Write a program that computes the factorial of a given non-negative integer n.
Sample Input:
Input: 4
Sample Output:
Output: 24
(Explanation: 4! = 4 * 3 * 2 * 1 = 24)
Problem: Create a function that returns a list of all prime numbers up to a given number n.
Sample Input:
Input: 10
Sample Output:
Output: [2, 3, 5, 7]
3. Anagram Checker
Problem: Write a function that checks if two given strings are anagrams of each other.
Sample Input:
Input: "listen", "silent"
Sample Output:
Output: True
4. Matrix Multiplication
Sample Input:
Input: [[1, 2], [3, 4]] and [[5, 6], [7, 8]]
Sample Output:
Output: [[19, 22], [43, 50]]
Sample Output:
Output: 1
(Explanation: The first element enqueued, 1, is dequeued first.)
Answers :
1. Factorial Calculation
Python:
def factorial(n):
if n == 0:
return 1
result = 1
result *= i
return result
print(factorial(4))
# Output: 24
JAVA :
int result = 1;
result *= i;
return result;
}
public static void main(String[] args) {
System.out.println(factorial(4));
// Output: 24
Python:
def is_prime(n):
if n <= 1:
return False
if n % i == 0:
return False
return True
def find_primes(n):
print(find_primes(10))
# Output: [2, 3, 5, 7]
JAVA :
import java.util.ArrayList;
import java.util.List;
public class PrimeNumbers {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
3. Anagram Checker
Python:
def are_anagrams(str1, str2):
print(are_anagrams("listen", "silent"))
# Output: True
JAVA :
import java.util.Arrays;
Arrays.sort(arr1);
Arrays.sort(arr2);
System.out.println(areAnagrams("listen", "silent"));
// Output: true
4. Matrix Multiplication
Python:
def matrix_multiply(A, B):
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
return result
print(matrix_multiply(A, B))
JAVA :
import java.util.Arrays;
}
}
return result;
System.out.println(Arrays.deepToString(result));
Python:
class QueueUsingStacks:
def __init__(self):
self.stack1 = []
self.stack2 = []
self.stack1.append(item)
def dequeue(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue())
# Output: 1
JAVA :
import java.util.Stack;
stack1.push(item);
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
public static void main(String[] args) {
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.dequeue());
// Output: 1