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

main()

Thank you

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

NOT

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

main()

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.
Jas.

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

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,
Jas.

I would use

Calculate = sum

instead of the above code ;)

commented: well played..I forgot about sum!! +2

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():
    myArray=(0,5,10,15,20)
    print "The answer is", sum(myArray)

main()

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]):
                    break
                if j == patlen-1:
                    matchlist.append((i,txt[i:i+patlen]))

Start your own thread alemasm20.

for (int i =0; i<10 ; i++) 
for (int j=i ; j<10;j++)
{do something}

need python interpration of this code

@Robiul

for i in range(10):
    for j in range(i, 10):
        do_something()

Happy coding.

// C++ program to find minimum steps to reach to
// specific cell in minimum moves by Knight
#include <bits/stdc++.h>
using namespace std;
#define N 8

//  structure for storing a cell's data
struct cell
{
    int x, y;
    int dis;
    cell() {}
    cell(int x, int y, int dis) : x(x), y(y), dis(dis) {}
};

//  Utility method returns true if (x, y) lies inside Board
bool isInside(int x, int y)
{
    if (x >= 1 && x <= N && y >= 1 && y <= N)
        return true;
    return false;
}

//  Method returns minimum step to reach target position
int minStepToReachTarget(int x1,int y1,int x2,int y2)
{
     int knightPos[] = {x1, y1};
     int targetPos[] = {x2, y2};
    //  x and y direction, where a knight can move
    int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2};
    int dy[] = {-1, -2, -2, -1, 1, 2, 2, 1};

    //  queue for storing states of knight in board
    queue<cell> q;

    //  push starting position of knight with 0 distance
    q.push(cell(knightPos[0], knightPos[1], 0));

    cell t;
    int x, y;
    bool visit[N + 1][N + 1];

    //  make all cell unvisited
    for (int i = 1; i <= N; i++)
        for (int j = 1; j <= N; j++)
            visit[i][j] = false;

    //  visit starting state
    visit[knightPos[0]][knightPos[1]] = true;

    //  loop untill we have one element in queue
    while (!q.empty())
    {
        t = q.front();
        q.pop();
        visit[t.x][t.y] = true;

        // if current cell is equal to target cell,
        // return its distance
        if (t.x == targetPos[0] && t.y == targetPos[1])
            return t.dis;

        //  loop for all reahable states
        for (int i = 0; i < 8; i++)
        {
            x = t.x + dx[i];
            y = t.y + dy[i];

            // If rechable state is not yet visited and
            // inside board, push that state into queue
            if (isInside(x, y) && !visit[x][y])
                q.push(cell(x, y, t.dis + 1));

        }
    }
}

// Driver code to test above methods
int main()
{
    //  size of square board
    int x1,x2,y1,y2;
    cin>>x1>>y1>>x2>>y2;

    cout << minStepToReachTarget(x1,y1,x2,y2);

    return 0;
}

@Praveen_20 Please start your own thread and show the attempts you made to translate this to python. We may then help you.

Don't want to be too pedantic but the original code could be changed with a longer array of ints and lower size and a true port should include the value of the size. Using the fact that Python tuples have a known length would be equivalent of using C++ Vector and not array.

#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[15] = {0, 2, 4, 8, 16, 0, 2, 4, 8, 16, 0, 2, 4, 8, 16};      // note size of new array is 15
    cout << "The answer is " << calculate(myArray, 5); // cout NOT count!
}

The reason I wrote the above is that I was here to look for help in porting a production C++ code to Python. The code translates a binary file to a human readable (ASCII) format and there is plenty of but and byte maniplulation and precision in porting is of utmost importance.

@doctorjay This is interesting. In that case we could propose

def calculate(values, size):
    return sum(values[:size])

assuming that values allows random access (eg tuple or list). This is not perfect however because I think the C++ code segfaults if the array is too short, while the above python code doesn't see any error. How do you think we should handle this ?

Also notice that the thread is seven years old. Jozz3 may have become an expert in C++ to python translation by now.

string seguir="S";
while(seguir =="S"){
int  descuento,subtotal,total;
double num_cuadernos,num_lapices,num_resmas,num_libros,num_esferos;
cout<<"\nCuantos cuadernos desea: ";
cin>>num_cuadernos;
cout<<"\nCuantos lapices desea : ";
cin>>num_lapices;
cout<<"\nCuantas resmas desea: ";
cin>>num_resmas;
cout<<"\nCuantos libros desea : ";
cin>>num_libros;
cout<<"\nCuantos esferos desea: ";
cin>>num_esferos;

subtotal = num_cuadernos * 1.75 + num_lapices * 0.60 + num_resmas * 3.85 + num_libros * 16.00 + num_esferos * 0.40;

if( subtotal>50 && subtotal<100 ){
total = subtotal - descuento * 0.05;
total = subtotal - descuento;
cout<<"\nSu descuento es: ";
cout<<descuento;
cout<<"\nEl valor total es de:  ";
cout<<total;
}
if(subtotal>= 100){
descuento = subtotal * 0.075;
total = subtotal - descuento;
cout<<"\nSu descuento es: ";
cout<<descuento;
cout<<"\nEl valor total es de:  ";
cout<<total;
}
if(subtotal< 50){
cout<<"\nNo aplica descuento: ";
total= subtotal + descuento;
cout<<"\nEl valor total es: ";
cout<<total;

cout<<endl;
cout<<"\nDesea ingresar una nueva factura: ";
cin>>seguir;
commented: Nine years late. -3
commented: Not Python code, and... -3

Look like the C++ code is:

#include <iostream>
using namespace std;
int calculate(int values[], int size) {
  int answer = 0;
  for (int i =0; i< size; i +=1)
  {
    answer += values[i];
  }
  return answer;
}

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

which can be converted into Python as below:

MyList = [0, 2, 4, 8, 16]
print(sum(MyList))

To learn more about Python, I would suggest visiting: Learn Python

commented: 9 years late. That could be taken as spam. -3

Write a program in python with a mother class Animal. Inside it define a name and an age variables, and set_value() function.Then create two variables Tiger and Dolphin which write a message telling the age, the name and giving some extra information: place of origin.

Input:
Dolphin Dolph 10 New Zeland
Output:
The dolphin named Dolph is 10 years old. The dolphin comes from New Zeland.

commented: Sponge Bob Squarepants Narrator: "Ten years later." Be timely. -3

I've found an answer for you here

commented: Sponge Bob Squarepants Narrator: "Ten years later." Be timely. -3

In your virtualenv, introduce SeaSnake, and afterward run it, passing for the sake of a C++ source document (or records, on the off chance that you need to give the header just as the cpp document):

$ pip introduce seasnake.

$ seasnake - s way/to/MyClass.cpp.

This will yield a MyClass.py Python module to the reassure

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.