0

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!

Edited by DragonMastur

Votes + Comments
interesting attempt
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)
4
Contributors
5
Replies
46
Views
2 Years
Discussion Span
Last Post by vegaseat
0

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.

Edited by Gribouillis

0

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.

Edited by vegaseat

0

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

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.