Converting C loops to Python

DragonMastur 0 Tallied Votes 813 Views Share

karmstrong ask in the Python chat if any one was farmilar with converting a for loop in C to Python. Here is a program in python that will do it for you!

Thank You!

Gribouillis commented: interesting attempt +14
testCLoop = "for(int a=10;a<20;a=a+1)"
cLoop = input("Enter C For Loop:\t")
#cLoop = testCLoop
cLoopStriped = cLoop.strip("for(").strip(")")
cLoopList = cLoopStriped.split(";")

print(cLoopList)

cLoopListInit = str(cLoopList[0]).split("=")
if "<" in cLoopList[1]:
	cLoopListCondition = cLoopList[1].split("<")
elif ">" in cLoopList[1]:
	cLoopListCondition = cLoopList[1].split(">")
if "+" in cLoopList[2]:
	cLoopListAdd = cLoopList[2].split("+")
	condition = "+"
elif "-" in cLoopList[2]:
	cLoopListAdd = cLoopList[2].split("-")
	condition = "-"

pythonLoop = "for x in range("
pythonLoop += str(cLoopListInit[1]+", ")
pythonLoop += str(cLoopListCondition[1]+", ")
if condition == "+":
	pythonLoop += str(cLoopListAdd[1])
if condition == "-":
	pythonLoop += str("-"+cLoopListAdd[1])
pythonLoop += ")"

print(pythonLoop)
Gribouillis 1,391 Programming Explorer Team Colleague

Instead of parsing the C code by hand, you could start from an ast produced by an existing C parser written in python: module pycparser. Here is an example, adapted from pycparser's example explore_ast.py

#-----------------------------------------------------------------
# see pycparser explore_ast.py for complete example
#-----------------------------------------------------------------
from __future__ import print_function
import sys


from pycparser import c_parser, c_ast

text = """
void foo(){
    for(int a=10;a<20;a=a+1)
        ;
}
"""

parser = c_parser.CParser()
ast = parser.parse(text, filename='<none>')

ast.show()

""" my output -->
FileAST: 
  FuncDef: 
    Decl: foo, [], [], []
      FuncDecl: 
        TypeDecl: foo, []
          IdentifierType: ['void']
    Compound: 
      For: 
        DeclList: 
          Decl: a, [], [], []
            TypeDecl: a, []
              IdentifierType: ['int']
            Constant: int, 10
        BinaryOp: <
          ID: a
          Constant: int, 20
        Assignment: =
          ID: a
          BinaryOp: +
            ID: a
            Constant: int, 1
        EmptyStatement: 
"""

Starting from an ast gives a robust base for translation to python.

DragonMastur 23 Light Poster

Thanks! Never knew about that. See you learn some thing new ever day!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In Python range() will do the work for you, no reason to go back to the medieval times. Even the newer curly brace languages have gone to on "in range" iterative approach.

megaflo 29 Newbie Poster

Note that the minute you see code like for i in range(len(items)) in Python you should sense a code smell.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You should sense a "code smell" because the code should be
for item in items

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.