当前位置:首页 » 编程语言 » c转python

c转python

发布时间: 2022-12-15 17:33:36

㈠ 怎么把这个c语言转换成python

C语言不能转化为python,它们之间没有之间联系,只能说算法是可以转化实现的。

㈡ C语言怎么转化成python

score={'a':5,'b':4,'c':3,'d':2,'e':1}
N=40
sum=0
foriinrange(N):
answer=raw_input("请输入你第%d题的选择(a-e):"%(i+1))
answer=answer.lower()
whileanswernotinscore:
answer=raw_input("请输入正确的选项!:")
answer=answer.lower()
sum+=score[answer]
print("你的总分为%d"%sum)
ifsum>=168:
print("A")
elif136<sum<168:
print("B")
elif104<sum<=136:
print("C")
elif72<sum<=104:
print("D")
else:
print("E")

这个python 程序肯定 和上面的C结果不一样

else if (136<sum<168) 在C中肯定为真,所以上面的C程序只会打印 A或者 B,CDE任何情况下都不会打印 ,Pytyhon会完全打印

直接说出程序要求

㈢ 求帮忙将C++代码转换成Python语言

# coding=gb2312
def Decrypt(s):
newlen=len(s)
lpTargetData=[0]*int(newlen/2)
lpSourceData =s.encode(encoding="gb2312")
newlen=int(newlen/2)
result=""
try:
for i in range(0,newlen):
lpTargetData[i]=bytes(((lpSourceData[i*2]-ord('A'))*16)+(lpSourceData[i*2]|1-ord('A')))
result=''.join(bytes.decode(lpTargetData[i],"gb2312"))
except e:
print(e)
return "decode error"
else:
return result
print(Decrypt('hello'))

㈣ 求大神将c++语言转换成Python语言

#!/usr/bin/env python
# -*- coding:utf-8 -*-

c = ['m', 'n', 'p', 'i', 'j', 'k']
a = [] #存储输入的数字,总共7个数字
t = 7
while t:
num = input('请输入一个数字')
if num.isdigit():
a.append(int(num))
t -= 1
else:
print('输入的不是数字,请重新输入')
continue
# print(a)
flag = 0
for i in range(6):
if a[0] == 0:
continue
if a[0] > 0:
if flag == 0: #作用第一次不能直接输出加号
flag = 1
if a[i] * c[i] == c[i]: # 处理1*'m' 只输出'm'
print(f'{c[i]}', end='')
else:
print(f'{a[i]}{c[i]}', end='')
else:
print('+', end='')
if a[i] == 1:
print(f'{c[i]}', end='')
else:
print(f'{a[i]}{c[i]}', end='')
else:
if flag == 0: #作用第一次不能直接输出加号
flag = 1
if '-' + -a[i] * c[i] == c[i]: # 处理-1*'m' 只输出'-m'
print(f'-{c[i]}', end='')
else:
print(f'{a[i]}{c[i]}', end='')
else:
print('+', end='')
if a[i] == -1:
print(f'-{c[i]}', end='')
else:
print(f'{a[i]}{c[i]}', end='')
if a[6] == 0:
if flag == 0: #这里说明一直没有任何输入,最后一个值也是0,运算结果是0
print("0")
elif a[6] > 0:
if flag == 1:
print(f'+{a[6]}', end='')
else: #flag这里说明一直没有任何输入,最后一个值不是0,运算结果是最后一个值,不使用+
print(f'{a[6]}', end='')
else:
print(f'{a[6]}', end='')

print()

㈤ 关于python和c

还是先学习2吧,因为现在大部分的python项目还是使用python2来实现的,等你python2熟悉之后迁移到python3也很方便。

官方有一个python2到python3所有修改的模块和方法列表,很方便的就能将python2的项目修改成python3的,同时使用six这个第三方库,也可以很方便的写出兼容python2和python3的代码。

如果解决了您的问题请采纳!
如果未解决请继续追问!

㈥ 怎样在oc代码中导入python的头文件

1. 安装Python开发包 由于需要访问Python/C API,首先安装Python开发包。 在Debian,Ubuntu或Linux Mint中: 在CentOS,Fedora或RHEL中: 安装成功后,Python头
2. 初始化解释器并设置路径 C中嵌入Python的第一步是初始化Python解释器,这可以用以下C函数完成。 初始化解释器后,需要设置你的C程序中要导入的Python模块
3. 数据转换 C中嵌入Python最重要的方面之一是数据转换。

㈦ 如何实现 C/C++ 与 Python 的通信

属于混合编程的问题。较全面的介绍一下,不仅限于题主提出的问题。
以下讨论中,Python指它的标准实现,即CPython(虽然不是很严格)

本文分4个部分

C/C++ 调用 Python (基础篇)— 仅讨论Python官方提供的实现方式
Python 调用 C/C++ (基础篇)— 仅讨论Python官方提供的实现方式
C/C++ 调用 Python (高级篇)— 使用 Cython
Python 调用 C/C++ (高级篇)— 使用 SWIG

练习本文中的例子,需要搭建Python扩展开发环境。具体细节见搭建Python扩展开发环境 - 蛇之魅惑 - 知乎专栏

1 C/C++ 调用 Python(基础篇)
Python 本身就是一个C库。你所看到的可执行体python只不过是个stub。真正的python实体在动态链接库里实现,在Windows平台上,这个文件位于 %SystemRoot%\System32\python27.dll。

你也可以在自己的程序中调用Python,看起来非常容易:

//my_python.c
#include <Python.h>

int main(int argc, char *argv[])
{
Py_SetProgramName(argv[0]);
Py_Initialize();
PyRun_SimpleString("print 'Hello Python!'\n");
Py_Finalize();
return 0;
}

在Windows平台下,打开Visual Studio命令提示符,编译命令为
cl my_python.c -IC:\Python27\include C:\Python27\libs\python27.lib

在Linux下编译命令为
gcc my_python.c -o my_python -I/usr/include/python2.7/ -lpython2.7

在Mac OS X 下的编译命令同上

产生可执行文件后,直接运行,结果为输出
Hello Python!

Python库函数PyRun_SimpleString可以执行字符串形式的Python代码。

虽然非常简单,但这段代码除了能用C语言动态生成一些Python代码之外,并没有什么用处。我们需要的是C语言的数据结构能够和Python交互。

下面举个例子,比如说,有一天我们用Python写了一个功能特别强大的函数:

def great_function(a):
return a + 1

接下来要把它包装成C语言的函数。我们期待的C语言的对应函数应该是这样的:

int great_function_from_python(int a) {
int res;
// some magic
return res;
}

首先,复用Python模块得做‘import’,这里也不例外。所以我们把great_function放到一个mole里,比如说,这个mole名字叫 great_mole.py

接下来就要用C来调用Python了,完整的代码如下:
#include <Python.h>

int great_function_from_python(int a) {
int res;
PyObject *pMole,*pFunc;
PyObject *pArgs, *pValue;

/* import */
pMole = PyImport_Import(PyString_FromString("great_mole"));

/* great_mole.great_function */
pFunc = PyObject_GetAttrString(pMole, "great_function");

/* build args */
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0, PyInt_FromLong(a));

/* call */
pValue = PyObject_CallObject(pFunc, pArgs);

res = PyInt_AsLong(pValue);
return res;
}

从上述代码可以窥见Python内部运行的方式:

所有Python元素,mole、function、tuple、string等等,实际上都是PyObject。C语言里操纵它们,一律使用PyObject *。
Python的类型与C语言类型可以相互转换。Python类型XXX转换为C语言类型YYY要使用PyXXX_AsYYY函数;C类型YYY转换为Python类型XXX要使用PyXXX_FromYYY函数。
也可以创建Python类型的变量,使用PyXXX_New可以创建类型为XXX的变量。
若a是Tuple,则a[i] = b对应于 PyTuple_SetItem(a,i,b),有理由相信还有一个函数PyTuple_GetItem完成取得某一项的值。
不仅Python语言很优雅,Python的库函数API也非常优雅。

现在我们得到了一个C语言的函数了,可以写一个main测试它
#include <Python.h>

int great_function_from_python(int a);

int main(int argc, char *argv[]) {
Py_Initialize();
printf("%d",great_function_from_python(2));
Py_Finalize();
}

编译的方式就用本节开头使用的方法。
在Linux/Mac OSX运行此示例之前,可能先需要设置环境变量:
bash:
export PYTHONPATH=.:$PYTHONPATH

csh:
setenv PYTHONPATH .:$PYTHONPATH

2 Python 调用 C/C++(基础篇)
这种做法称为Python扩展。
比如说,我们有一个功能强大的C函数:
int great_function(int a) {
return a + 1;
}

期望在Python里这样使用:
>>> from great_mole import great_function
>>> great_function(2)
3

考虑最简单的情况。我们把功能强大的函数放入C文件 great_mole.c 中。
#include <Python.h>

int great_function(int a) {
return a + 1;
}

static PyObject * _great_function(PyObject *self, PyObject *args)
{
int _a;
int res;

if (!PyArg_ParseTuple(args, "i", &_a))
return NULL;
res = great_function(_a);
return PyLong_FromLong(res);
}

static PyMethodDef GreateMoleMethods[] = {
{
"great_function",
_great_function,
METH_VARARGS,
""
},
{NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initgreat_mole(void) {
(void) Py_InitMole("great_mole", GreateMoleMethods);
}

除了功能强大的函数great_function外,这个文件中还有以下部分:

包裹函数_great_function。它负责将Python的参数转化为C的参数(PyArg_ParseTuple),调用实际的great_function,并处理great_function的返回值,最终返回给Python环境。

出表GreateMoleMethods。它负责告诉Python这个模块里有哪些函数可以被Python调用。导出表的名字可以随便起,每一项有4
个参数:第一个参数是提供给Python环境的函数名称,第二个参数是_great_function,即包裹函数。第三个参数的含义是参数变长,第四个
参数是一个说明性的字符串。导出表总是以{NULL, NULL, 0, NULL}结束。
导出函数initgreat_mole。这个的名字不是任取的,是你的mole名称添加前缀init。导出函数中将模块名称与导出表进行连接。

在Windows下面,在Visual Studio命令提示符下编译这个文件的命令是
cl /LD great_mole.c /o great_mole.pyd -IC:\Python27\include C:\Python27\libs\python27.lib

/LD 即生成动态链接库。编译成功后在当前目录可以得到 great_mole.pyd(实际上是dll)。这个pyd可以在Python环境下直接当作mole使用。

在Linux下面,则用gcc编译:
gcc -fPIC -shared great_mole.c -o great_mole.so -I/usr/include/python2.7/ -lpython2.7

在当前目录下得到great_mole.so,同理可以在Python中直接使用。

本部分参考资料

《Python源码剖析-深度探索动态语言核心技术》是系统介绍CPython实现以及运行原理的优秀教程。
Python 官方文档的这一章详细介绍了C/C++与Python的双向互动Extending and Embedding the Python Interpreter
关于编译环境,本文所述方法仅为出示原理所用。规范的方式如下:3. Building C and C++ Extensions with distutils
作为字典使用的官方参考文档 Python/C API Reference Manual

用以上的方法实现C/C++与Python的混合编程,需要对Python的内部实现有相当的了解。接下来介绍当前较为成熟的技术Cython和SWIG。

3 C/C++ 调用 Python(使用Cython)


前面的小节中谈到,Python的数据类型和C的数据类型貌似是有某种“一一对应”的关系的,此外,由于Python(确切的说是CPython)本身是
由C语言实现的,故Python数据类型之间的函数运算也必然与C语言有对应关系。那么,有没有可能“自动”的做替换,把Python代码直接变成C代码
呢?答案是肯定的,这就是Cython主要解决的问题。

安装Cython非常简单。Python 2.7.9以上的版本已经自带easy_install:
easy_install -U cython

在Windows环境下依然需要Visual
Studio,由于安装的过程需要编译Cython的源代码,故上述命令需要在Visual
Studio命令提示符下完成。一会儿使用Cython的时候,也需要在Visual
Studio命令提示符下进行操作,这一点和第一部分的要求是一样的。

继续以例子说明:
#great_mole.pyx
cdef public great_function(a,index):
return a[index]

这其中有非Python关键字cdef和public。这些关键字属于Cython。由于我们需要在C语言中使用
“编译好的Python代码”,所以得让great_function从外面变得可见,方法就是以“public”修饰。而cdef类似于Python的
def,只有使用cdef才可以使用Cython的关键字public。

这个函数中其他的部分与正常的Python代码是一样的。

接下来编译 great_mole.pyx
cython great_mole.pyx

得到great_mole.h和great_mole.c。打开great_mole.h可以找到这样一句声明:
__PYX_EXTERN_C DL_IMPORT(PyObject) *great_function(PyObject *, PyObject *)

写一个main使用great_function。注意great_function并不规定a是何种类型,它的
功能只是提取a的第index的成员而已,故使用great_function的时候,a可以传入Python
String,也可以传入tuple之类的其他可迭代类型。仍然使用之前提到的类型转换函数PyXXX_FromYYY和PyXXX_AsYYY。

//main.c
#include <Python.h>
#include "great_mole.h"

int main(int argc, char *argv[]) {
PyObject *tuple;
Py_Initialize();
initgreat_mole();
printf("%s\n",PyString_AsString(
great_function(
PyString_FromString("hello"),
PyInt_FromLong(1)
)
));
tuple = Py_BuildValue("(iis)", 1, 2, "three");
printf("%d\n",PyInt_AsLong(
great_function(
tuple,
PyInt_FromLong(1)
)
));
printf("%s\n",PyString_AsString(
great_function(
tuple,
PyInt_FromLong(2)
)
));
Py_Finalize();
}

编译命令和第一部分相同:
在Windows下编译命令为
cl main.c great_mole.c -IC:\Python27\include C:\Python27\libs\python27.lib

在Linux下编译命令为
gcc main.c great_mole.c -o main -I/usr/include/python2.7/ -lpython2.7

这个例子中我们使用了Python的动态类型特性。如果你想指定类型,可以利用Cython的静态类型关键字。例子如下:

#great_mole.pyx
cdef public char great_function(const char * a,int index):
return a[index]

cython编译后得到的.h里,great_function的声明是这样的:
__PYX_EXTERN_C DL_IMPORT(char) great_function(char const *, int);

很开心对不对!
这样的话,我们的main函数已经几乎看不到Python的痕迹了:
//main.c
#include <Python.h>
#include "great_mole.h"

int main(int argc, char *argv[]) {
Py_Initialize();
initgreat_mole();
printf("%c",great_function("Hello",2));
Py_Finalize();
}

在这一部分的最后我们给一个看似实用的应用(仅限于Windows):
还是利用刚才的great_mole.pyx,准备一个dllmain.c:
#include <Python.h>
#include <Windows.h>
#include "great_mole.h"

extern __declspec(dllexport) int __stdcall _great_function(const char * a, int b) {
return great_function(a,b);
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpReserved) {
switch( fdwReason ) {
case DLL_PROCESS_ATTACH:
Py_Initialize();
initgreat_mole();
break;
case DLL_PROCESS_DETACH:
Py_Finalize();
break;
}
return TRUE;
}

在Visual Studio命令提示符下编译:
cl /LD dllmain.c great_mole.c -IC:\Python27\include C:\Python27\libs\python27.lib

会得到一个dllmain.dll。我们在Excel里面使用它,没错,传说中的Excel与Python混合编程:

参考资料:Cython的官方文档,质量非常高:
Welcome to Cython’s Documentation

出自:Jerry Jho

㈧ 有没有大神 帮我从c语言转到python语言

#四色问题可以用这个嘛 记住解决问题的重点是算法,不是语言哦

#-*-coding:cp936-*-
defFourColorLabel(GuanXiJuZheng):
<ahref="https://www..com/s?wd=Num&tn=44039180_cpr&fenlei=-bIi4WUvYETgN-"target="_blank"class="-highlight">Num</a>=len(GuanXiJuZheng)
Color=[-1foriinrange(<ahref="https://www..com/s?wd=Num&tn=44039180_cpr&fenlei=-bIi4WUvYETgN-"target="_blank"class="-highlight">Num</a>)]
n=m=1
#染色第一个区域,先设置为1
whilem<=<ahref="https://www..com/s?wd=Num&tn=44039180_cpr&fenlei=-bIi4WUvYETgN-"target="_blank"class="-highlight">Num</a>:
whilen<=4andm<=Num:
flag=True
forkinrange(<ahref="https://www..com/s?wd=m-1&tn=44039180_cpr&fenlei=-bIi4WUvYETgN-"target="_blank"class="-highlight">m-1</a>):
ifGuanXiJuZheng[<ahref="https://www..com/s?wd=m-1&tn=44039180_cpr&fenlei=-bIi4WUvYETgN-"target="_blank"class="-highlight">m-1</a>][k]==1andColor[k]==n:
flag=False#染色有冲突
n+=1
break
ifflag:
Color[<ahref="https://www..com/s?wd=m-1&tn=44039180_cpr&fenlei=-bIi4WUvYETgN-"target="_blank"class="-highlight">m-1</a>]=n;
m+=1
n=1
ifn>4:#超出标记范围必须回退
m-=1
n=Color[m-1]+1
returnColor

GuanXiJuZheng=[
[0,1,1,1,0,0,0],
[1,0,0,0,1,0,0],
[1,0,0,1,0,1,0],
[1,0,1,0,1,1,1],
[0,1,0,1,0,0,1],
[0,0,1,1,0,0,1],
[0,0,0,1,1,1,0]
]
foriinFourColorLabel(GuanXiJuZheng):
printi

㈨ 求助 关于c程序中嵌入Python的问题

嵌入
与python的扩展相对,嵌入是把Python解释器包装到C的程序中。这样做可以给大型的,单一的,要求严格的,私有的并且(或者)极其重要的应用程序内嵌Python解释器的能力。一旦内嵌了Python,世界完全不一样了。

C调用python中的函数:
hw.py:

#coding=utf8

def hw_hs(canshu):
return canshu

if __name__ == "__main__":
ccss = "I am hw"
print hw_hs(ccss)

helloWorld.py:

#coding=utf8
import hw

def hello():
ccss = "I am helloWorld"
return hw.hw_hs(ccss)

if __name__ == "__main__":
print hello()

testcpypy.c:

//#include "testcpypy.h"
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
//初始化Python
Py_Initialize();
if (!Py_IsInitialized()) {
printf("Py_Initialize");
getchar();
return -1;
}

//执行python语句
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");

PyObject *pMole = NULL;
PyObject *pFunc = NULL;
PyObject *reslt =NULL;

//载入python模块
if(!(pMole = PyImport_ImportMole("helloWorld"))) {
printf("PyImport_ImportMole");
getchar();
return -1;
}

//查找函数
pFunc = PyObject_GetAttrString(pMole, "hello");
if ( !pFunc || !PyCallable_Check(pFunc) )
{
printf("can't find function [hello]");
getchar();
return -1;
}

//调用python中的函数
reslt = (PyObject*)PyEval_CallObject(pFunc, NULL);
//printf("function return value : %d\r\n", PyInt_AsLong(reslt));

//将python返回的对象转换为C的字符串
char *resltc=NULL;
int res;
res = PyArg_Parse(reslt, "s", &resltc);
if (!res) {
printf("PyArg_Parse");
getchar();
return -1;
}
printf("resltc is %s", resltc);
getchar();

//释放内存
Py_DECREF(reslt);
Py_DECREF(pFunc);
Py_DECREF(pMole);

//关闭python
Py_Finalize();

return 0;
}

编译:
gcc -o testcpypy testcpypy.c -IC:\Python27\include -LC:\Python27\libs -lpython27 ---C:\Python27为python安装目录
或:
gcc -c testcpypy.c -IC:\Python27\include
gcc -o testcpypy.exe testcpypy.o -LC:\Python27\libs -lpython27
执行结果:

带参数的情况:

#include "callpydll.h"
#include "Python.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

int callhello(char *instr, char *outstr)
{

PyObject *pMole = NULL;
PyObject *pFunc = NULL;
PyObject *reslt = NULL;
PyObject *pParm = NULL;

char *resltc = NULL;
int resltn;
int res;

char *helloWorld = "TestIM_ProtocBuf";

char *im_account = "aaaa";
char *auth_code = "aaaa";
char *im_uid = "aaaa";
char *proxy_topic = "";

//初始化Python
Py_Initialize();
if (!Py_IsInitialized()) {
printf("Py_Initialize");
getchar();
return -1;
}

//执行python语句
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");

//载入python模块
if(!(pMole = PyImport_ImportMole(helloWorld))) {
printf("PyImport_ImportMole");
getchar();
return -2;
}

//查找函数
pFunc = PyObject_GetAttrString(pMole, "login_proxy_body_serialize");
if ( !pFunc || !PyCallable_Check(pFunc) )
{
printf("can't find function [hello]");
getchar();
return -3;
}

//参数转换C --> python, 参数必须是元组(一个参数也是,否则会失败!!!坑啊)
pParm = Py_BuildValue("(ssss)", im_account, auth_code, im_uid, proxy_topic);

//调用python中的函数
reslt = (PyObject*)PyEval_CallObject(pFunc, pParm);

//将python返回的对象转换为C的字符串
res = PyArg_ParseTuple(reslt, "si", &resltc, &resltn);
if (!res) {
printf("PyArg_Parse");
getchar();
return -4;
}

printf("resltn is %d", resltn);
memcpy(outstr, resltc, strlen(resltc)+1);

//释放内存
Py_DECREF(reslt);
Py_DECREF(pFunc);
Py_DECREF(pMole);
Py_DECREF(pParm);

//关闭python
Py_Finalize();

return 0;
}

int main() {
int i;
char *dais = "iammain";
char res[10240];
memset(res,'\0',sizeof(res));

i = callhello(dais, res);
if(0 != i) {
printf("Notify:error");
getchar();
return -1;
}
printf("result is %s", res);
getchar();
return 0;
}

㈩ 这个c语言怎么转化为Python

按照你的要求把C++程序转为Python程序的Python程序如下

n=1

i=1

m=int(input("输入大于1的正整数m:"))

while i<=m:

n+=1

i=i*n

print("输出n的值:{} ".format(n))

源代码(注意源代码的缩进)

热点内容
怎么把电脑锁上密码 发布:2024-05-20 05:19:09 浏览:982
安卓为什么连上wifi后没有网络 发布:2024-05-20 05:17:50 浏览:417
安卓usb在设置哪里 发布:2024-05-20 05:03:03 浏览:185
绥化编程 发布:2024-05-20 04:59:44 浏览:989
基本原理和从头计算法 发布:2024-05-20 04:50:32 浏览:28
配置情况指的是什么 发布:2024-05-20 04:48:14 浏览:495
那个程序用来编译源文件 发布:2024-05-20 04:46:45 浏览:549
小程序需要数据库吗 发布:2024-05-20 04:35:14 浏览:337
链接sqlserver 发布:2024-05-20 04:27:53 浏览:209
ftp文件服务器扩容 发布:2024-05-20 04:22:21 浏览:646