Uploaded by zamanarooba

Comparison between Python and C++

advertisement
Comparison between Python and C++
Semester Project
Group Members
Abdul Rafay
21-NTU-CS-1197
Arooba Zaman
21-NTU-CS-1211
Department of Computer Science
National Textile University Faisalabad
25-12-2023
Introduction
We comprehensively explore the Python and C++ programming languages and examine
critical dimensions that significantly impact their applicability in diverse software development
scenarios. The comparative analysis encompasses execution speed, syntax clarity, code length,
memory management, portability, and a detailed examination of algorithmic complexities in
searching, sorting, insertion, and deletion operations.
Problem Description
Selecting the correct programming language is a pivotal decision in software
development. However, the complex landscape of choices, especially between Python and
C++, demands a nuanced understanding. A consolidated resource is necessary for decisionmakers to make well-informed choices.
Objective
This study aims to compare Python and C++ in diverse software development contexts
comprehensively. Our objectives include evaluating execution speed, syntax clarity, code length,
memory management, and algorithmic complexities. We seek to provide a nuanced
understanding of each language's historical evolution, type systems, and computational models.
We aim to offer insights for developers and decision-makers through graphical
representations, including graphs, charts, and tables, facilitating informed language choices
based on specific project requirements and optimizing software development processes.
History of C++
C++ was invented by Danish computer scientist Bjarne Stroustrup at AT&T Bell Labs in
1979. It originated from analyzing the UNIX kernel to investigate how much it can be distributed
over a network. C++ has come a long way since the first steps in 1979 and continues to evolve.
It continues evolving with C++11, C++14, and C++17 standards based on object-oriented
programming concepts. C++23 will soon be released with small but significant adjustments, and
work has already begun on C++26.
C++ continues to rise in popularity, and its use is expanding, including creating
applications for virtual reality (VR) via the Unreal Engine and in cryptocurrency applications. [1]
History of Python
Guido van Rossum created Python, first released on February 20, 1991. While you may
know Python as a giant snake, the name Python as a name of programming language came from
an old comedy sketch series, i.e., Monty Python's Flying Circus. [2]
It first started as a hobby project because he was looking for an exciting project to keep
him occupied during Christmas. Python succeeded in the ABC programming language, interfacing
with the Amoeba Operating System and had the exception handling feature. [3]
Key Dimensions of Comparison
1. Execution Speed:
Time at which the program executes. It is different for different languages, influenced by
compiler efficiency, memory management, and library optimization—low-level control,
concurrency support, and platform dependencies impact performance, language syntax, and
expressiveness. [4]
Now, we will discuss the execution speed of C++ and Python through an example of insertion
and summation.
Insertion and Summation in Array [5]
C++
Python
#include <iostream>
#include <ctime>
import time
def ex3(A,SIZE):
total_sum = 0
for i in range(SIZE):
total_sum += A[i]
return total_sum
int ex3(const int* A, int SIZE) {
int total_sum = 0;
for (int i = 0; i < SIZE; ++i) {
total_sum += A[i];
}
return total_sum;
}
# Example usage with timing:
array = [1]
int main() {
int array[] = {1};
int SIZE = sizeof(array) / sizeof(array[0]);
start_time = time.time()
result = ex3(array,1)
end_time = time.time()
clock_t start_time = clock();
int result = ex3(array, SIZE);
clock_t end_time = clock();
execution_time = end_time - start_time
print("Result:", result)
print("Execution Time:", execution_time,
"seconds")
double execution_time =
static_cast<double>(end_time - start_time) /
CLOCKS_PER_SEC;
std::cout << "Result: " << result << std::endl;
std::cout << "Execution Time: " <<
execution_time << " seconds" << std::endl;
return 0;
}
Comparison of Execution Speeds
Values
Python
C++
1
0.0000033 sec
0.000001 sec
6
0.0000035 sec
0.000001 sec
15
0.0000021 sec
0.000002 sec
20
0.0000026 sec
0.000001 sec
25
0.0000033 sec
0.000001 sec
Graphical Representation of Execution Time vs Values
Conclusion
•
•
•
C++ is a compiled language directly translated to machine code, providing faster
execution.
As Python is interpreted, it is executed line by line, which is generally slower than
compilation.
C++ tends to have superior performance due to its direct compilation, while Python
prioritizes simplicity over speed. [6]
2. Syntax and Code Length:
Syntax defines the rules for structuring code in a programming language. Code length refers
to the number of lines needed to implement a solution. Different languages have distinct syntax
and may vary in code length for the same task. Readability and maintainability are essential
considerations alongside code length. [7]
Linear Search in array
Python
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
my_list = [1, 5, 7, 9, 11, 13]
target_element = 9
result = linear_search(my_list,
target_element)
if result != -1:
print(f"Element {target_element}
found at index {result}")
else:
print(f"Element {target_element} not
found in the list")
C++
#include <iostream>
using namespace std;
int linear_search(int arr[], int size, int
target) {
for (int i = 0; i < size; ++i) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
int my_array[] = {1, 5, 7, 9, 11, 13};
int target_element = 9;
int array_size = sizeof(my_array) /
sizeof(my_array[0]);
int result = linear_search(my_array,
array_size, target_element);
if (result != -1) {
cout << "Element " << target_element
<< " found at index " << result << endl;
} else {
cout << "Element " << target_element
<< " not found in the array" << endl;
}
Comparison of Syntax and Code Length:
Python
C++
Implicit memory management.
Explicit Memory management.
Concise and more readable.
Less and less readable as compared to
Python.
To calculate array size:
To calculate array size:
(len(array))
(sizeof(array) / sizeof(array[0]))
Python uses libraries for most of the
Libraries are only provided for some of the
computations.
tasks.
Conclusion
•
•
Python generally offers shorter and optimized code, making rapid development and
readability preferable.
C++ provides lower-level control and performance optimizations, making it unsuitable for
tasks where code length matters a lot.
3. Memory Management:
Memory management is allocating and deallocating computer memory to optimize program
execution. It involves tracking and organizing available memory for data storage during a
program's runtime. Proper memory management prevents memory leaks and enhances system
performance. Programming languages employ various strategies to handle memory effectively,
such as manual or automatic memory management. [8]
Memory Allocation and Deallocation
Python
C++
# Memory allocation
my_list = [1, 2, 3]
#include <iostream>
using namespace std;
# Memory deallocation
del my_list
int main() {
// Memory allocation
int* myArray = new int[3];
// Memory deallocation
delete[] myArray;
return 0;
}
Comparison of Memory Management:
Python
C++
Automatic memory deallocation
No automatic memory deallocation
Use garbage collector
No use of garbage collector
Use the del keyword to deallocate memory
explicitly
Use the delete keyword to deallocate
memory explicitly
Conclusion
•
•
Python's approach is more automatic and less error-prone for memory
management.
C++ provides more control at the cost of requiring manual management.
4. Type System:
A type system in programming defines and enforces the data types used in a language,
specifying how values can be manipulated. It enhances code reliability by preventing unintended
operations on data. Type systems can be static (resolved at compile-time) or dynamic (evaluated
at runtime). Well-designed type systems help catch errors early, improving code quality and
maintainability. [9]
Dynamic Typing in Python vs. Static Typing in C++:
Python
# Python code
variable = 5 # Dynamic typing, 'variable' can
hold different types
variable = "Hello, World!" # No explicit type
declaration
print(variable)
C++
#include <iostream>
using namespace std;
int main() {
// C++ code
int number = 5; // Static typing, 'number'
must always be an integer
// number = "Hello, World!"; // Error: Type
mismatch
cout << number << endl;
return 0;
}
Comparison Table of Type System:
Python
C++
Datatype assigns dynamically
Datatype assigns statically
Variables can dynamically change their type
Variables cannot statically change their type
The same variable can hold different types of
values
The same variable cannot hold different types
of values
Conclusion
•
•
Python offers flexibility and ease of use, allowing variables to change types during
runtime.
C++ is declared at compile-time, providing type safety, and preventing the assignment of
incompatible types.
5. Readability and Code Structure:
Readability in programming refers to how easily code can be understood by developers. A
well-structured code follows a logical organization, uses meaningful names, and employs
consistent formatting.
Clear indentation and concise comments contribute to readability, making code
maintenance and collaboration more efficient. Prioritizing readability enhances code quality
and reduces the likelihood of errors. [10]
Code Clarity Sum Comparison in Python and C++:
Python
def calculate_sum(a, b):
result = a + b
return result
num1 = 5
num2 = 3
sum_result = calculate_sum(num1, num2)
print(f"Sum: {sum_result}")
C++
#include <iostream>
using namespace std;
// C++ code for readability and code
structure
int calculateSum(int a, int b) {
int result = a + b;
return result;
}
int main() {
int num1 = 5;
int num2 = 3;
int sumResult = calculateSum(num1,
num2);
cout << "Sum: " << sumResult << endl;
return 0;
}
Comparisons Table of Readability and Code Structure:
Python
Use def to declare functions
More concise use of indentation for code
blocks
Function calls are straightforward
C++
Uses explicit function declarations with return
types
Relies on explicit braces {} to denote code
blocks
Function calls include explicit type declarations
and use cout for output
Conclusion
Python is often favored for its concise syntax and simplicity, promoting readability. C++ offers
more explicit type information and control, making it suitable for performance-critical
applications where strict code structure is beneficial.
6. Variable Scope and Assess Handling:
The region where a variable in a program can be accessed or modified is referred as scope of
that specific variable. Local variables are confined to a specific block or function, while global
variables can be accessed throughout the program. A proper understanding of scope helps
prevent naming conflicts and enhances code maintainability. Exception handling involves
managing unexpected runtime errors, allowing for graceful error recovery, and preventing
abrupt program termination. [11]
Scope and Handling Comparison:
Python
C++
def example_function():
local_variable = 10
try:
print(local_variable)
# Uncomment the next line to trigger
an exception
# print(undefined_variable)
except Exception as e:
print(f"Exception: {e}")
#include <iostream>
using namespace std;
void exampleFunction() {
int localVariable = 10;
try {
cout << localVariable << endl;
// Uncomment the next line to trigger
an exception
// cout << undefinedVariable << endl;
} catch (const exception& e) {
cout << "Exception: " << e.what() <<
endl;
}
}
int main() {
exampleFunction();
return 0;
}
Comparison in Variable Scope and Assess:
Python
C++
Uses indentation to denote scope
Uses braces {} to enclose code blocks.
It uses try, except blocks for exception
handling
It uses try, catch blocks for the same purpose
Conclusion
•
•
Python offers simplicity with its indentation-based scoping and concise exception
syntax, promoting readability.
C++ provides explicit scoping with braces and more detailed exception handling, offering
fine-grained control but potentially leading to more verbose code.
7. Order of Operator and Operand Evaluation
The operator and operand evaluation order in programming languages defines the
sequence in which expressions are computed. In general, expressions are evaluated based on
operator precedence and associativity rules. The code execution order impacts the result of an
expression. [12]
Evaluation Order Comparison
Python
result = 2 + 3 * 4
print(result)
C++
#include <iostream>
using namespace std;
int main() {
int result = 2 + 3 * 4;
cout << result << endl;
return 0;
}
Comparison Table of Operator and Operand Evaluation:
Python
1. [] ( ) . ->
++ -- (postfix)
C++
1. [] ( ) . ->
++ -- (postfix)
2. sizeof & * + - ~! ++ -- (prefix) Unary
2. sizeof & * + - ~! ++ -- (prefix) Unary
3. * / %
3. * / %
4. + 4. + 5. << >> Bitwise Shift
5.<<>>
Bitwise Shift
6. < > <= >=
6. < > <= >=
7. == !=
7. == !=
8. & Bitwise AND
8. & Bitwise-AND
9. ^ Bitwise XOR
9. ^ Bitwise-exclusive-OR
10.| Bitwise OR
10.| Bitwise-inclusive-OR
11. not x
11. && Logical-AND
12. and Boolean AND
12.|| Logical-OR
13. or Boolean OR
14.= *= /= %=
+= -= <<= >>= &=
^= |=
14.= *= /= %=
+= -= <<= >>= &=
^= |=
Associativity is left to right for most operators.
Notable exceptions: Exponentiation (**) is
right-associative.
Associativity is left to right for most operators.
Notable exceptions: Assignment operators (=,
+=, -=) are right-associative.
Operand Evaluation is from left to right.
Operand Evaluation is from left to right.
Conclusion
•
•
•
•
Python follows clear rules of precedence.
Python's simplicity may be preferable for straightforward expressions.
C++ offers fine-grained control through explicit parentheses.
C++ allows more precise control over evaluation order in complex scenarios.
8. Computational Model:
A computational model is a set of principles and rules that define how a programming
language processes and executes instructions. It encompasses the language's paradigms,
structures, and mechanisms for expressing computations. The model guides programs' writing,
specifying how data is represented, manipulated, and controlled during execution. Different
languages follow distinct computational models, such as imperative, functional, or objectoriented, influencing how developers approach problem-solving and express algorithms. [13]
Python Computational Model:
1. Functional:
•
•
Use the functional model as the most dominant.
It supports the higher-order functions, immutability, and pure functions.
2. Imperative:
o It focuses on explicit sequences of commands, often changing the program's
state.
o Uses statements to describe the flow of control and modify variables.
3. Other Models:
•
•
Python allows a combination of both models, supporting a multi-paradigm
approach.
It incorporates elements of object-oriented programming as well, making it
versatile.
Functional Model in Python:
def square(x):
return x * x
numbers = [1, 2, 3, 4]
squared_numbers = list(map(square, numbers))
print(squared_numbers)
•
•
Promotes a declarative style where computation is expressed as a series of
function evaluations.
Encourages immutability and avoids side effects.
Imperative Model in Python:
numbers = [1, 2, 3, 4]
squared_numbers = []
for num in numbers:
squared_numbers.append(num * num)
print(squared_numbers)
•
•
Emphasizes explicit commands, often changing the state of the program.
Uses statements to describe the flow of control and modify variables.
C++ Computational Model:
1. Object-Oriented Model:
•
•
•
Most dominant Computational Model.
Emphasizes classes and objects for encapsulation, inheritance, and
polymorphism.
Encourages modularity and code organization using objects.
2. Imperative Model:
•
•
Focuses on explicit sequences of commands, often changing the state of the
program.
Uses statements to describe the flow of control and modify variables.
3. Generic Model:
•
•
Promotes writing code that is independent of data types.
Utilizes templates to create generic algorithms that work with different types.
4. Other Models:
•
C++ allows a combination of multiple models, supporting a multi-paradigm
approach.
Object-Oriented Model in C++:
#include <iostream>
using namespace std;
class Circle {
public:
double radius;
Circle(double r) : radius(r) {}
double calculateArea() {
return 3.14 * radius * radius;
}
};
int main() {
// Create object and use object-oriented features
Circle myCircle(5);
cout << "Area: " << myCircle.calculateArea() << endl;
return 0;
}
•
C++'s object-oriented model provides a structured and modular approach to
programming.
Conclusion
o Both languages support multi-paradigm, but for Python, functional and imperative
computational models are dominant, and for C++, the dominant computational model is
object-oriented.
9. Operator Overloading:
Operator overloading is a programming feature that allows defining custom behaviors for
operators, extending their functionality beyond their predefined operations. It enables objects
of user-defined classes to use standard operators, providing a more intuitive and expressive
syntax. This feature enhances code readability and allows for the creation of domain-specific
operations for user-defined types. Examples include overloading + for concatenation in strings
or vectors. [14]
Operator Overloading Comparison
Python
C++
# Python code for operator overloading
class Point:
def init(self, x, y):
self.x = x
self.y = y
#include <iostream>
using namespace std;
// C++ code for operator overloading
class Point {
public:
int x, y;
def add(self, other):
return Point(self.x + other.x, self.y +
other.y)
Point(int a, int b) : x(a), y(b) {}
Point operator+(const Point& other)
const {
return Point(x + other.x, y + other.y);
}
};
p1 = Point(1, 2)
p2 = Point(3, 4)
result = p1 + p2
print(result.x, result.y)
int main() {
Point p1(1, 2);
Point p2(3, 4);
Point result = p1 + p2;
cout << result.x << " " << result.y <<
endl;
return 0;
Comparison Table of Operator Overloading:
Python
C++
Uses the _add_ method for operator
overloading.
Overload operators using member functions.
More flexibility in naming methods
It requires specific operator overloading
syntax.
Conclusion
o Python's approach is more flexible with dunder methods, offering clarity in intent.
o C++ provides an explicit syntax for operator overloading, offering a more structured and
compiler-enforced approach.
o The choice depends on preference and the level of control and clarity desired in
operator overloading implementations.
10. Type casting:
Type casting refers to converting a value from one data type to another. It allows for
compatibility between different kinds of expressions or assignments. [15]
Implicit and Explicit Type Casting:
Implicit Type Casting:
• Automatically performed by the compiler when it is safe.
• No programmer intervention is needed.
Example: Converting an integer to a floating-point number in a mathematical operation.
Explicit Type Casting:
• Manually performed by the programmer.
• It involves using casting operators to convert between types.
Example: Using (int) to explicitly cast a floating-point number to an integer.
Narrowing and Widening:
Narrowing (Explicit):
▪
We are casting the type from a more significant data type to a smaller
one.
▪ May result in loss of information.
Example: Converting a double to an int.
Widening (Implicit):
• Casting from a smaller data type to a larger one.
• It is generally safe and does not result in loss of information.
Example: Converting an int to a double.
Type Casting Comparisons:
Python:
# Implicit Type Conversion (Widening)
num_int = 5
num_float = 3.14 + num_int
# Explicit Type Conversion (Narrowing)
float_to_int = int(6.78)
C++:
#include <iostream>
using namespace std;
int main() {
// Implicit Type Conversion (Widening)
int num_int = 5;
double num_double = 3.14 + num_int;
// Explicit Type Conversion (Narrowing)
double double_val = 6.78;
int double_to_int = static_cast<int>(double_val);
return 0;
}
Comparison Table in Type Casting:
Python
C++
Allow both implicit and explicit conversion.
Allow both implicit and explicit conversion.
Automatically converts between compatible
types
Use functions like int() for explicit conversion.
Implicitly converts smaller data types to larger
ones.
Use casting operators like static_cast for
explicit conversion.
Conclusion
•
•
•
Implicit conversions may lead to unexpected results.
Explicit conversions require a specific conversion technique.
Understanding the trade-offs between implicit and explicit conversions is crucial for
preventing unexpected behavior and maintaining code integrity in both languages.
11. Scope in Real Environment:
Python:
Strengths:
•
•
•
Rapid Development: Python's concise syntax and extensive libraries
facilitate quick development.
Versatility: Ideal for web development, data science, machine learning,
and scripting.
Readability: Clear and readable syntax promotes maintainability.
Real Environments:
•
•
•
Web Development: Frameworks like Django and Flask for server-side
development.
Data Science: Extensively used with libraries like NumPy, Pandas, and
TensorFlow.
Automation: Scripting for automation and system tasks. [16]
C++:
Strengths:
•
•
•
Performance: Close-to-the-hardware control allows efficient resource
utilization.
System Programming: Suitable for building operating systems,
embedded systems, and performance-critical applications.
Object-Oriented Features: Supports object-oriented programming
paradigms.
Real Environments:
•
•
•
System-Level Development: Widely used in developing operating
systems and low-level applications.
Game Development: Popular in the gaming industry for its performance.
Performance-critical Applications: Performance-critical Applications are
primarily used in applications where execution speed is crucial. [17]
Conclusion
• Excelling in ease of use, versatility, and readability, Python is well-suited for applications
with rapid development cycles, data-centric tasks, and scripting needs.
• With a focus on performance and low-level control, C++ is preferable for system-level
development, high-performance applications, and scenarios requiring explicit memory
management.
References
[1] S. Goyal, "unstop," [Online]. Available: https://unstop.com/blog/history-of-cpp. [Accessed
December 2023].
[2] Wikipedia, "Python – the language of today and tomorrow," Python Institute, [Online].
Available: https://pythoninstitute.org/about-python. [Accessed December 2023].
[3] M. Mitali, "How does Python work: A Deep Understanding of Programming," Perfect
Learning, [Online]. Available: https://perfectelearning.com/blog/how-does-python-work.
[Accessed December 2023].
[4] S. W. Smith, "dspguide," [Online]. Available: https://www.dspguide.com/ch4/5.htm.
[Accessed December 2023].
[5] A. Behery, "Python VS C++ Time Complexity Analysis," [Online]. Available:
https://www.freecodecamp.org/news/python-vs-c-plus-plus-time-complexity-analysis/.
[6] M. Lehman, "Node.js vs Python: Make The Right Choice," gmihub, [Online]. Available:
https://www.gmihub.com/blog/node-js-vs-python-make-the-right-choice/. [Accessed
December 2023].
[7] C. Jergenson, "What is syntax in a programming," educative, [Online]. Available:
https://www.educative.io/blog/what-is-syntax-in-programming. [Accessed December 2023].
[8] R. Sheldon, "memory management," TechTarget, [Online]. Available:
https://www.techtarget.com/whatis/definition/memory-management. [Accessed December
2023].
[9] Zack, "The Type System Every Programmer Should Know," towardsdatascience, [Online].
Available: https://towardsdatascience.com/the-type-system-every-programmer-shouldknow-c3134a1b9bde. [Accessed December 2023].
[10] B. Roebling, "Code Structure and Readability Part 1," medium, [Online]. Available:
https://medium.com/swift2go/code-structure-and-readability-part-1-edd3537ada11.
[Accessed December 2023].
[11] K. L. Busbee, "Scope," Logo for Rebus Press, [Online]. Available:
https://press.rebus.community/programmingfundamentals/chapter/scope/. [Accessed
December 2023].
[12] "Operator Evaluation Order," FAADOO Engineers, [Online]. Available:
http://www.faadooengineers.com/online-study/post/cse/principals-of-programminglanguage/924/operator-evaluation-order. [Accessed December 2023].
[13] Ginni, "What is Computational Model?," tutorialspoint, [Online]. Available:
https://www.tutorialspoint.com/what-is-computational-model. [Accessed December 2023].
[14] M. L. Scott, "Operator Overloading," ScienceDirect, [Online]. Available:
https://www.sciencedirect.com/topics/computer-science/operator-overloading. [Accessed
December 2023].
[15] Wikipedia, "Type conversion," Wikipedia, [Online]. Available:
https://en.wikipedia.org/wiki/Type_conversion. [Accessed December 2023].
[16] Simplilearn, "Top 7 Practical Applications of Python and Career Tips," Simplilearn,
[Online]. Available: https://www.simplilearn.com/what-is-python-used-for-article. [Accessed
December 2023].
[17] Simplilearn, "Top 7 Practical Applications of C++ and the Way to Build a Career,"
Simplilearn, [Online]. Available: https://www.simplilearn.com/c-plus-plus-programming-forbeginners-article. [Accessed December 2023].
Download