5 Replies - 418 Views - Last Post: 21 October 2019 - 09:18 AM Rate Topic: -----

#1 hansford   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 25-August 19

Attempting to translate C code into Python

Posted 27 August 2019 - 02:49 PM

Hi all, need your expertise.
I am attempting to translate a simple C program into Python, but the hard way.
I know it works in much simpler ways, but I'm attempting the bare bones way of doing it so I can better understand how a for loop in C translates in Python. The code I attempted has always ended up with an IndexError: list index out of range
Thanks in advance.

C code
/***
* Remove duplicates from an array 
*
* Language: C
* O/S: Windows 10
* Compiler: Sublime Text 3
* The following code compiles and runs successfully on Windows 10
***/
#include <stdio.h>

void main()
{
    int i, j, k;
    int a[] = {1,3,5,8,3,1,9,8,3};
    size_t n = sizeof(a) / sizeof(a[0]); 

    printf("\nOriginal array is: ");
    for(i = 0; i < n; i++)
    {
        printf(" %d", a[i]);
    }

    printf("\nNew array is: ");
    for(i = 0; i < n; i++)
    {
        for(j = i+1; j < n; )
        {
            if(a[j] == a[i])
            {
                for(k = j; k < n; k++)
                {
                    a[k] = a[k+1];
                }
                n--;
            }
            else
            {
                j++;
            }
        }
    }
 for(i = 0; i < n; i++)
    {
        printf("%d ", a[i]);
    }
}



Python code
# remove duplicates from a list

li = [1,3,5,8,3,1,9,8,3]


for i in range(len(li)): 
 j = i 
 for j in li:
  if li[j] == li[i]:
   k = j
   for k in li:
     li[k] = li[k+1]
     k += 1
   n -= 1
  else:
   j += 1
 i += 1

print(li)

:code:/>

This post has been edited by modi123_1: 27 August 2019 - 02:52 PM
Reason for edit:: In the future, please use the [code] tag button in the editor.


Is This A Good Question/Topic? 0
  • +

Replies To: Attempting to translate C code into Python

#2 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15277
  • View blog
  • Posts: 61,238
  • Joined: 12-June 08

Re: Attempting to translate C code into Python

Posted 27 August 2019 - 02:53 PM

Please copy/paste the full error. Also, if you could, indicate which line it is happening on.

My immediate speculation is your line 12 of the second part. You are adding 1 to the index without checking if it is in bounds or not.

As in if you have three items in an array and are checking the last one, index 2, then your index + 1 would attempt to find index 3.. which is out of bounds.
Was This Post Helpful? 0
  • +
  • -

#3 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5466
  • View blog
  • Posts: 14,421
  • Joined: 18-April 07

Re: Attempting to translate C code into Python

Posted 27 August 2019 - 04:23 PM

Well there are some problems in the Python as it sits now. For instance you set n, but never use it anywhere else. Also you have to know that the for loop in Python is much like foreach in other languages. It doesn't start at "k" and go to the end of the list. It starts at the beginning and sets "k" to the current value it is pointing to during iteration. So you can't just simply manipulate the "k" value as you would an index because it actually holds the values in the list. Lastly, as Modi pointed out, you are going too far in your list index.

Now one thing you probably also want to take note of, is that this isn't exactly the best way to understand Python. Trying to do direct translations like this is what many in the industry call an "accent". You are writing Python that stinks of C++ ideas. It works, but you are bending Python to be like C++ instead of understanding the concept you are trying to do and then implementing the concept in Python's terms, taking advantage of its structures and patterns.

But if you insist on seeing what it may look like with this accent, you would get a bigger advantage out of using a while loop...

li = [1,3,5,8,3,1,9,8,3]

n = len(li)

for i in range(len(li)):
  j = i + 1
  while j < n:
    if li[j] == li[i]:
      k = j;
      while k < (n - 1):
        li[k] = li[k+1]
        k += 1
      n -= 1
    else:
      j += 1

print(li[:n])



1) We are using while loops to manage our indexes.
2) We are making use of "n"
3) Where C++ can chop off arrays by moving the terminator, here we are just slicing off the end of the list.
4) We make sure that "k" doesn't go past the end of the array by making sure we loop one less than "n"
5) This is ridiculously slow because of the loops. We can certainly work with Python and slice out duplicates which will probably be faster.

This post has been edited by Martyr2: 27 August 2019 - 04:24 PM

Was This Post Helpful? 1
  • +
  • -

#4 hansford   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 25-August 19

Re: Attempting to translate C code into Python

Posted 27 August 2019 - 05:42 PM

Thanks so much Martyr2. That is exactly what I was looking for.
My intention is to understand Python fully; To be able to code things the simple way, but also the hard way as you just did.

Troy
Was This Post Helpful? 0
  • +
  • -

#5 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5466
  • View blog
  • Posts: 14,421
  • Joined: 18-April 07

Re: Attempting to translate C code into Python

Posted 27 August 2019 - 09:17 PM

Yes but what I am also saying is that the hard way in this case is actually not a good example of doing things in the "pythonic" way and may actually be teaching you bad habits. Just be mindful of that.
Was This Post Helpful? 0
  • +
  • -

#6 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 833
  • View blog
  • Posts: 2,259
  • Joined: 23-December 08

Re: Attempting to translate C code into Python

Posted 21 October 2019 - 09:18 AM

Your problem is from the line li[k] = li[k+1]. k+1 puts you outside the range of the list.

You can do these sorts of exercises for learning Python, but translating code from one language directly to another isn't a great approach. You're basically trying to solve the problem "The C Way" While using Python. Instead, why not try to figure out a method for accomplishing the same task that leverages the advantages of Python?

Here's a simple way to reduce a list in Python. Simply convert it to a set which automatically removes duplicates, then convert it back to a list.

# remove duplicates from a list

def main(inputList):
    return list(set(inputList))


if __name__ == "__main__":
    print(main([1,3,5,8,3,1,9,8,3]))


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1