I have to convert a piece of C++ code to Python. Except I can't understand what it's doing. This is the code:

#include <iostream>
using namespace std;

int calculate(int values[], int size) {
int answer = 0;
for (int 1 =0; i< size; i +=1)
answer += values[1];
return answer;

int main() {
int myArray[5] = {0, 2, 4, 8, 16};
count << "The answer is " << calculate(myArray, 5);

This is my attempt at converting it to Python:

def main():
    myArray[5] = (0, 2, 4, 8, 16)
    print "The answer is ", calculate(myArray, 5)

def intCalculate(intValues, intSize):
    intAnswer = 0
    i = 0
    if i < intSize:
        for i in intAnswer:
            intAnswer += values[i]
    return intAnswer


Thank you

Edited 6 Years Ago by jozz3: n/a

The intent of C++ code is very simple, even though it doesn't compile. It simply takes the sum of the values in an array. When you understand the purpose of a program, it's much easier to port it, since you aren't blindly translating code.

You really don't seem to show much familiarity with the syntax of Python. First of all, you aren't calling the method the way you declared it. You call calculate , but you called your method intCalculate .

Secondly, you don't define arrays like that in Python. There's no need to specify the size of the array with its definition as there is in C/C++. You would declare the array as myArray = (0, 2, 4, 8, 16) .

Finally, your for loop is not at all how a Python for loop should be implemented. Try rewriting your loop as for i in range(intSize): , and then access values in the way you declared it, as intValues .

After addressing those concerns, the program worked properly for me. I hope it helps point you in the right direction.

You're quite close.
You have a few errors in there.

First off in main you're calling calculate, but you've defined the function as intCalculate. There's one straight off the bat.

Also your for loop should be:

for i in intValues
    intAnswer += i


for i in intAnswer
    intAnswer+= values[i]

The other error in the above is you've called the 2nd parameter to the calculate function 'intValues' and then you're referencing a non-existent object ('values') in your for loop.

Also, because we're using python, the calculate function does not need to know the size of the tuple/array, that's more of a C++ thing. A simple for i in intValues will suffice, so intSize is completely unneeded.

So your port from C++ to python should look something like this:

def main():
    myArray = (0, 2, 4, 8, 16)
    print "The answer is ", Calculate(myArray)

def Calculate(values):
    answer = 0
    for i in values:
        answer += i
    return answer


Which is the python equivalent to the C++ code you posted (or at least it would be if the C++ was correct, I'll show you where you went wrong with that later in the post, mainly typos from the look of it!).
When porting code from one language to another, you need to fully understand the differences and similarities between the languages you are using.

Sometimes things do not require a literal translation.
As you've seen with my python port of the C++ code you posted, the size variable was only relevant to the C++ code, it was completely unneeded in the python code.

In the C++ version of the calculate function you have a comparatively complex statement (compared with python!) to set up the 'for' loop, which uses the passed-in size to stop the loop from stepping outside of the boundaries of the passed in array.
And then inside the loop you have to dereference each item in the array and add it to the answer.

Whereas the python 'for' loop is simple. The declaration basically says 'for each item in the array execute the body of the loop'.
and the body of the loop simply adds the value of the current item to the answer.
So in other words 'for each item in the array, add the item to the answer'...simple! We don't need to specify a size for the array, basically the python 'for..in' loop will loop until it reaches the end of the array, unlike C++ which would happily stomp past the end of an array if left unchecked.

This actually highlights how terse and concise python code can be especially when compared to other more verbose languages like C/C++.

Incidentally the C++ code should be more like this:

#include <iostream>
using namespace std;

int calculate(int values[], int size) 
	int answer = 0;
	for (int i =0; i< size; ++i) // int i=0; NOT int 1=0!
	{ // opening brace was wrong way around { NOT } !!
		answer += values[i]; // values[i] NOT values[1]!!
	return answer;

int main() 
	int myArray[5] = {0, 2, 4, 8, 16};
	cout << "The answer is " << calculate(myArray, 5); // cout NOT count!

Hope this has helped, cheers for now.

[edit] Oooops, Ishara got in there while I was composing my post!

Edited 6 Years Ago by JasonHippy: n/a

BTW: Isharas suggestion of using a 'for ... in range(...)' loop is also a good one.

It will allow the python version of the calculate function to keep exactly the same signature as the C++ version, so you could consider using that if you were worried that your teacher/professor/lecturer might mark you down for not keeping the function signatures the same.

But at the same time, they may allow for the fact that you've recognised that in the context of the python port, the size parameter is redundant and really only applicable to the C++ version. So there are two ways of looking at it!

Both solutions will work, the code will do exactly the same thing, but I guess at the end of the day it depends on what whoever is marking your work is looking for.

Cheers for now,

I would use

Calculate = sum

instead of the above code ;)

Heh heh, good point Gribouillis, that's far better! I completely forgot about sum {slaps forehead!}. That completely eliminates the need for the calculate function and brings the OPs main function down to just 2 lines of code! Well spotted, my hat's off to you sir!

def main():
    print "The answer is", sum(myArray)


Thanks heaps guys. I've never even seen C++ code before, only been working with Python. Hence the misinterpretation with the translation. Greatly apprectated, thank you.

I want to translate this python code to c++!
any help pls!

for j in range (0,patlen):
                if (txt[i+j] != pat[j]):
                if j == patlen-1:
This question has already been answered. Start a new discussion instead.