Java Python Code Equivalence - Numerical Methods
Java Python Code Equivalence - Numerical Methods
Python
Variables are dynammically typed. No need to write data type while declaring
a variable.
a = 123 #integer
b = 1.23 #float
c = 1 + 2j #complex
d = "Hello World" #string
e = True #boolean true
f = False #boolean false
Introduction to Python 1
Java
public class PrintingVariable{
public static void main(String[] args){
[Link](a);
[Link](b);
[Link](c);
[Link](d);
[Link](e);
[Link](f);
}
}
# Output
123
1.23
1.23
Hello World
true
false
Python
print (a)
print (b)
print (c) #Bracket for complex number
print (d)
print (e)
print (f)
# Output
123
1.23
(1+2j)
Introduction to Python 2
Hello World
True
False
Checking types
Java
You cannot check primitive types at runtime because java is statically typed.
However for non-primitive data types, you can use instanceof .
# Output
true
Python
c = 1 + 2j
type(c)
# Output
complex
Introduction to Python 3
For floor division both numbers should be of int datatype.
# Output
7
3
10
2.5
2
1
16
Python
print (5 + 2)
print (5 - 2)
print (5 * 2)
print (5 / 2)
print(5//2)
print (5 % 2)
print (2 ** 4)
Introduction to Python 4
# Output
7
3
10
2.5
2
1
16
Concatination
Java
public class Contatination{
public static void main(String[] args){
int a = 123;
int b = 456;
[Link]("The current value of a is "+ a);
[Link]("The current value of a is " + a +
" and b is" + b);
}
}
# Output
The current value of a is 123
The current value of a is 123 and b is 456
Python
a = 123
b = 456
Introduction to Python 5
print ("The current value of a is", a)
print ("The current value of a is", a, "and b is", b)
#Concatenated using +
print ("The current value of a is " + a)
print ("The current value of a is " + a + " and b is " + b)
# Output
The current value of a is 123
The current value of a is 123 and b is 456
The current value of a is 123
The current value of a is 123 and b is 456
String
String Concatination
Java
public class StrContatination{
public static void main(String[] args){
String a = "Welcome to ";
String b = "CSE330 Lab.";
[Link](a + b);
}
}
# Output
Welcome to CSE330 Lab.
Python
Introduction to Python 6
a = "Welcome to "
b = "CSE330 Lab."
z = a + b
print (z)
# Output
Welcome to CSE330 Lab.
String Indexing
Java
//Accessing String with character position number. Space is a
lso a character
public class StrIndexing{
public static void main(String[] args){
String a = "Welcome to ";
String b = "CSE330 Lab.";
[Link]([Link](0));
[Link]([Link](5));
}
}
# Output
W
0
Python
a = "Welcome to "
b = "CSE330 Lab."
Introduction to Python 7
print (a[0])
print (b[5])
# Output
W
0
[Link]([Link]());
}
}
#Output
22
Python
a = "Welcome to "
b = "CSE330 Lab."
z = a + b
print(len(z))
Introduction to Python 8
#Output
22
[Link]([Link]([Link]() - 1));
}
}
#Output
.
Python
a = "Welcome to "
b = "CSE330 Lab."
print(b[len(b)-1])
print(b[-1])
#Output
.
.
Introduction to Python 9
String Slicing
Java
public class StrSlice {
public static void main(String[] args) {
#Output
Welco
Welco
Python
s = "Welcome to CSE330 Lab."
print(s[0:5]) # prints characters from index 0 to 4
#Output
Welco
Welco
Introduction to Python 10
Java
public class StrSlice {
public static void main(String[] args) {
//===========================================
Introduction to Python 11
#Output
Welcom
e to CSE330 Lab.
Lab.
#=================
Welcom
e to CSE330 Lab.
Lab.
Python
s = "Welcome to CSE330 Lab."
print (s[:6])
print (s[6:])
print (s[-4:])
#Output
Welcom
e to CSE330 Lab.
Lab.
User Input
Java
import [Link];
Introduction to Python 12
[Link]("Username is: " + username);
//=====================================
[Link](username + username + username);
//=====================================
[Link]("Enter number: ");
int num = [Link]();
[Link](num * 2);
}
}
#Output
Enter username:coder
Username is: coder
#=====================================
codercodercoder
#=====================================
Enter number:4
8
Python
username = input("Enter username:")
print("Username is: " + username)
#=====================================
print(username*3)
#=====================================
num = int(input("Enter number:"))
print (num * 2)
#Output
Enter username:coder
Username is: coder
#=====================================
codercodercoder
Introduction to Python 13
#=====================================
Enter number:4
8
Conditional Statement
Java
public class CondStat {
public static void main(String[] args) {
int x = 5;
int y = 6;
if (x > y) {
[Link]("Maximum is x");
} else {
[Link]("Maximum is y");
}
}
}
#Output
Maximum is y
Python
x = 5
y = 6
if x > y:
print("Maximum is x")
else:
print ("Maximum is y")
Introduction to Python 14
#Output
Maximum is y
elif
Java
// elif
public class CondStat {
public static void main(String[] args) {
int x = 5;
int y = 5;
if (x > y) {
[Link]("Maximum is x");
} else if (x == y) {
[Link]("x and y are equal");
} else {
[Link]("Maximum is y");
}
}
}
#Output
x and y are equal
Python
#elif
x = 5
y = 5
if x > y:
Introduction to Python 15
print("Maximum is x")
elif x == y:
print ("x and y are equal")
else:
print ("Maximum is y")
#Output
x and y are equal
and
Both conditions need to be True
Java
public class CondStat {
public static void main(String[] args) {
int a = 200;
int b = 10;
int c = 500;
#Output
Both conditions are True
Python
Introduction to Python 16
a = 200
b = 10
c = 500
if a > b and c > a:
print("Both conditions are True")
else:
print("Negative!!")
#Output
Both conditions are True
or
Either one of the conditions = True should be enough
Java
public class CondStat {
public static void main(String[] args) {
int a = 200;
int b = 10;
int c = 500;
if (a > b || a > c) {
[Link]("At least one of the condition
s is True");
} else {
[Link]("Negative!!");
}
}
}
Introduction to Python 17
#Output
At least one of the conditions is True
Python
a = 200
b = 10
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
else:
print("Negative!!")
#Output
At least one of the conditions is True
Nested if
Java
public class CondStat {
public static void main(String[] args) {
int x = 50;
if (x > 10) {
[Link]("Above ten!");
if (x > 20) {
[Link]("and also above 20!");
} else {
[Link]("but not above 20!");
}
Introduction to Python 18
} else {
[Link]("Not even above ten!");
}
}
}
#Output
Above ten!
and also above 20!
Python
x = 50
if x > 10:
print("Above ten!")
if x > 20:
print("and also above 20!")
else:
print("but not above 20!")
else:
print("Not even above ten!")
#Output
Above ten!
and also above 20!
pass
Java
public class PassStat{
public static void main(String[] args) {
Introduction to Python 19
int a = 10;
int b = 20;
if (b > a) {
// do nothing (equivalent to pass)
} else {
[Link]("hello");
}
}
}
Python
a = 10
b = 20
if b > a:
pass
#else:
#print("hello")
Python
Introduction to Python 20
#Initializing
list = [1, 2, 3, 4, 5]
print(list)
#Output
[1, 2, 3, 4, 5]
#Output
[1, 2, 3]
#List Methods
print(len(list))
print(4 in list) #Search
#output
5
True
[1, 2, 'New', 4, 5]
[1, 2, 'New', 4, 5, 'World']
Introduction to Python 21
[Link](1) #Remove using index
print(list)
#Output
[1, 2, 4, 5, 'World']
[1, 4, 5, 'World']
[1, 4, 5, 'World', 16, 55]
List Slicing
my_list = ['a', 'b', 'c', 'e', 'f', 'd']
print (my_list[3])
print (my_list[1:3])
print (my_list[:3])
print (my_list[3:])
print (my_list[-3:])
#Output
e
['b', 'c']
['a', 'b', 'c']
['e', 'f', 'd']
['e', 'f', 'd']
Introduction to Python 22
print (my_list[::2])
print (my_list[::-1]) #Reverse order
#Output
['a', 'c']
['a', 'b', 'c', 'e', 'f', 'd']
['a', 'c', 'f']
['d', 'f', 'e', 'c', 'b', 'a']
print (my_list[-1:-5:-1])
#Output
['f', 'e', 'd', 'c']
['e', 'd', 'c', 'b']
# |1 2 3 4|
# |5 6 7 8|
print (matrix[1][2])
#Output
7
Introduction to Python 23
Tuple
Immutable (unchangable) - Items can not be modified
Collection of elements of multiple data types
Commonly used in programming (like Python) and databases to store a fixed
sequence of related data
Python
tuple = (1, 2, 3, 4, 5)
tuple[0]
#===================
tuple[1] = "hello"
#Output
1
#======================
TypeError Traceback (most rec
ent call last)
<ipython-input-41-f3de6cd25f9c> in <cell line: 0>()
----> 1 tuple[1] = "hello"
Set
Immutable - Items can not be modified
Unordered - No index
No duplicates allowed
Python
set = {"apple", "banana", "cherry", "banana"}
print(set)
Introduction to Python 24
#====================
[Link]("orange")
print(set)
[Link]("banana")
print(set)
#Output
{'apple', 'cherry', 'banana'}
#====================
{'apple', 'cherry', 'orange', 'banana'}
{'apple', 'cherry', 'orange'}
Dictionary
Values stored as key : value pair
Unordered, mutable
Key must be unique and immutable types (e.g., strings, numbers, tuples).
Python
drivers = {
16: "Charles",
1: "Max",
55: "Carlos",
"Extra": "Liam"
}
print(drivers)
#Output
Introduction to Python 25
{16: 'Charles', 1: 'Max', 55: 'Carlos', 'Extra': 'Liam'}
drivers["Extra"] = "Ollie"
print(drivers)
[Link]({81:"Oscar"})
print(drivers)
[Link]("Extra")
print(drivers)
#Output
Liam
{16: 'Charles', 1: 'Max', 55: 'Carlos', 'Extra': 'Ollie'}
{16: 'Charles', 1: 'Max', 55: 'Carlos', 'Extra': 'Ollie', 81:
'Oscar'}
{16: 'Charles', 1: 'Max', 55: 'Carlos', 81: 'Oscar'}
Loops
While loop
Java
public class WhileLoop{
public static void main(String[] args) {
int i = 0;
Introduction to Python 26
}
}
Python
i = 0
while i < 10:
print(i)
i = i + 1
#Output
0
1
2
3
4
5
6
7
8
9
For loop
Java
public class ForLoop{
public static void main(String[] args) {
for (int i = 0; i < 10; i += 2) {
[Link](i);
}
}
}
Introduction to Python 27
Python
for i in range(0, 10, 2):
print(i)
#Output
0
2
4
6
8
Introduction to Python 28
}
}
#Output
a
b
c
d
e
------------------
0
1
2
3
4
------------------
Index = 0, Value = a
Index = 1, Value = b
Index = 2, Value = c
Index = 3, Value = d
Index = 4, Value = e
Python
#Iterate over the list
list = ['a', 'b', 'c', 'd', 'e']
for i in list:
print (i)
print("------------------")
for i in range(len(list)):
print(i)
print("------------------")
Introduction to Python 29
for i in range(0, len(list)):
print("Index =", i, "Value =", list[i])
# OUTPUT
a
b
c
d
e
------------------
0
1
2
3
4
------------------
Index = 0, Value = a
Index = 1, Value = b
Index = 2, Value = c
Index = 3, Value = d
Index = 4, Value = e
Break Statement
Java
Break statement - Out of the loop
Introduction to Python 30
}
}
}
}
# OUTPUT
apple
banana
Python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
# OUTPUT
# OUTPUT
apple
banana
Continue Statement
Java
Continue statement - Stop the current iteration of the loop and continue with
the next
Introduction to Python 31
continue;
}
[Link](fruits[i]);
}
}
}
# OUTPUT
apple
cherry
Python
fruits = ["apple", "banana", "cherry"]
for i in fruits:
if i == "banana":
continue
print(i)
# OUTPUT
apple
cherry
Nested Loop
Java
public class NestedLoop{
public static void main(String[] args){
int[] num_arr = {1,2,3};
String[] alphabet_arr = {"a","b","c"};
for(int i = 0; i < num_arr.length; i++){
[Link](num_arr[i]);
Introduction to Python 32
for(int j = 0; j < alphabet_arr.length; j++){
[Link](alphabet_arr[j]);
}
}
}
}
# OUTPUT
1
a
b
c
2
a
b
c
3
a
b
c
Python
#Nested loop
num_list = [1 , 2, 3]
alphabet_list = ['a', 'b', 'c']
# OUTPUT
1
Introduction to Python 33
a
b
c
2
a
b
c
3
a
b
c
Functions or Methods
Java
We cannot create a java method with default value but we can use method
overloading (same method name but different numbers of parameters).
Introduction to Python 34
}
public static void main(String[] args){
hello_method();
name_method("Cristiano", "Ronaldo");
int x = sum_numbers(2, 3);
[Link](x);
[Link](increment(2,5));
[Link](increment(2));
}
}
# OUTPUT
Hello
Cristiano Ronaldo
5
4
12
Python
def hello_function():
print("Hello")
hello_function()
Introduction to Python 35
name_function("Cristiano", "Ronaldo")
x = sum_numbers(2, 3)
print(x)
print(increment(2))
print(increment(2, 5))
# Keyword arguments
print(increment(by=1, number=2))
NumPy
Java
import [Link];
public class JavaArr{
public static void main(String[] args){
String[] arr = {"1", "2", "3", "2.45", "hello"};
[Link]([Link](arr));
[Link]("Arr Length: " + [Link]);
}
}
# OUTPUT
[1, 2, 3, 2.45, hello]
Arr Length: 5
Python
A Python library
Used for working with arrays
Short form of "Numerical Python”
Aims to provide an array object that is up to 50x faster than traditional Python
lists
Provides a lot of supporting functions
Introduction to Python 36
# As arrays can store only one type of data, therefore it con
verts everything to String
# We cannot perform any kind of calculations
import numpy as np
# OUTPUT
['1' '2' '3' '2.45' 'hello']
<class '[Link]'>
5
(5,)
Append
Java
import [Link];
public class JavaAppend{
public static void main(String[] args){
// We need to create another array (y), where the siz
e is greater than the previous
// array (x). Then copy all values from x to y and fi
nally insert the new value (70)
int[] x = {1,2,3,4,5};
int[] y = new int[[Link]+1];
for(int i = 0; i < [Link]; i++){
y[i] = x[i];
}
Introduction to Python 37
y[[Link]-1] = 70;
[Link]([Link](y));
[Link]([Link](x));
}
}
# OUTPUT
[1,2,3,4,5,70]
[1,2,3,4,5]
Python
import numpy as np
x = [Link]([1, 2, 3, 4, 5])
y = [Link](x, [70])
print(y)
print(x) #No change in main array
[ 1 2 3 4 5 70]
[1 2 3 4 5]
Delete
Java
import [Link];
Introduction to Python 38
// array (x). Then copy all values from x to
y while checking the value's index you want to remove and the
n insert the other values other than the removed value.
int deleteValue = 3; // value we want to remove
int index = 0;
for (int i = 0; i < [Link]; i++) {
if (x[i] != deleteValue) {
y[index] = x[i];
index++;
}
}
[Link]([Link](y));
[Link]([Link](x));
}
}
#Output
[1, 2, 4, 5]
[1, 2, 3, 4, 5]
Python
x = [Link]([1, 2, 3, 4, 5])
y = [Link](x, 3) #Delete using index
print(x)
print(y)
#Output
[1, 2, 4, 5]
Introduction to Python 39
[1, 2, 3, 4, 5]
Sorting
Java
import [Link];
[Link](numbers); //Ascending
[Link]([Link](numbers));
[Link]([Link](revArr));
}
}
#Output
[1, 2, 5, 8, 9]
[9, 8, 5, 2, 1]
Python
Introduction to Python 40
x = [Link]([7, 8, 3, 10, 5])
sorted_x = [Link](x)
print(sorted_x) #Ascending
print(sorted_x[::-1]) #Descending - Reverse the Ascending ord
er sorted array
#Output
[1, 2, 5, 8, 9]
[9, 8, 5, 2, 1]
2-D Array
Java
import [Link];
int[][] arr_2d = {
{1, 2, 3, 7, 55},
{4, 5, 6, 99, 10}
};
[Link]([Link](arr_2d));
}
}
#Output
[[1, 2, 3, 7, 55], [4, 5, 6, 99, 10]]
Python
Introduction to Python 41
arr_2d = [Link]([[1, 2, 3, 7, 55],
[4, 5, 6, 99, 10]])
print(arr_2d)
#Output
[[ 1 2 3 7 55]
[ 4 5 6 99 10]]
int[][] arr_2d = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10}
};
Introduction to Python 42
#Output
Number of rows: 2
Shape: (2, 5)
Number of dimensions: 2
Python
print(len(arr_2d))
print(arr_2d.shape) #row, column
print(arr_2d.ndim) #Dimension
#Output
2
(2, 5)
2
Indexing
Java
//1st & last element of an array
import [Link];
[Link](numbers[0]);
[Link](numbers[[Link]-1]);
}
}
Introduction to Python 43
#Output
5
9
Python
arr = [Link]([5, 2, 8, 1, 9])
print(arr[0])
print(arr[-1])
#Output
5
9
Java
import [Link];
int[][] arr = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10}
};
[Link]([Link](arr));
Introduction to Python 44
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
4th element on 2nd row: 9
Python
arr = [Link]([[1,2,3,4,5],
[6,7,8,9,10]])
print(arr)
#Output
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
4th element on 2nd row: 9
int[][] arr = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10}
};
//From the second row, slice elements from in
dex 1 to index 4 (not included)
int[] slice1 = [Link](arr[1], 1, 4);
[Link]([Link](slice1));
Introduction to Python 45
//From both rows, slice index 1 to index 4 (n
ot included)
int[][] slice2 = new int[2][3];
[Link]([Link](slice2));
}
}
#Output
[7, 8, 9]
[[2, 3, 4], [7, 8, 9]]
Python
arr = [Link]([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]])
#Output
[7 8 9]
[[2 3 4]
[7 8 9]]
Introduction to Python 46
Taking last column and row
Java
import [Link];
int[][] arr = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10}
};
#Output
[1 6]
[1 2 3 4 5]
Python
Introduction to Python 47
print(arr[:, 0]) #column
print(arr[0, :]) #row
#Output
[1 6]
[1 2 3 4 5]
Zero Matrix
Java
import [Link];
[Link]([Link](y));
}
}
#Output
[[0, 0], [0, 0], [0, 0], [0, 0]]
Python
#zero matrix
y = [Link]((4,2)) #row, column
print(y)
Introduction to Python 48
#Output
[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]
int sumA = 0;
int prodA = 1;
for (int i = 0; i < [Link]; i++) {
sumA += a[i];
prodA *= a[i];
}
[Link]("Sum of a: " + sumA);
[Link]("Product of a: " + prodA);
}
}
#Output
Sum of a: 12
Product of a: 60
Python
Introduction to Python 49
a = [Link]([3, 4, 5])
print([Link](a))
print([Link](a))
#Output
12
60
int[][] b = {
{1, 2, 3},
{4, 5, 6}
};
int sumB = 0;
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < b[i].length; j++) {
sumB += b[i][j];
}
}
[Link]("Sum of b: " + sumB);
Introduction to Python 50
colSum[j] += b[i][j];
}
}
[Link]("Column-wise sum: " + [Link]
ing(colSum));
#Output
Sum of b: 21
Column-wise sum: [5, 7, 9]
Row-wise sum: [6, 15]
Python
b = [Link]([[1,2,3],
[4,5,6]])
print([Link](b))
print([Link](b, axis=0))
print([Link](b, axis=1))
#Output
21
Introduction to Python 51
[5 7 9]
[ 6 15]
int[][] arr = {
{1, 2, 3},
{4, 5, 6}
};
#Output
1 2 3
4 5 6
Python
arr = [Link]([[1, 2, 3],
[4, 5, 6]])
Introduction to Python 52
for x in arr:
print(x)
#Output
[1 2 3]
[4 5 6]
int[][] arr = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arr[i].length; j++) {
[Link](arr[i][j]);
}
}
}
}
#Output
1
2
3
4
5
6
Introduction to Python 53
Python
arr = [Link]([[1, 2, 3], [4, 5, 6]])
for x in arr:
for y in x:
print(y)
#Output
1
2
3
4
5
6
Linspace
Create a random array, same difference between the numbers
Java
public class JavaLinspace {
public static void main(String[] args) {
double start = 0;
double end = 100;
int n = 4;
Introduction to Python 54
for (int i = 0; i < n; i++) {
[Link](x[i] + " ");
}
}
}
#Output
0.0 33.333333333333336 66.66666666666667 100.0
Python
x = [Link](0, 100, 4) #start, end, how many numbers
print(x)
#Output
[ 0. 33.33333333 66.66666667 100. ]
Introduction to Python 55