當前位置:首頁 » 編程語言 » 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-09 04:17:30 瀏覽:801
返校vlog腳本 發布:2024-05-09 04:15:53 瀏覽:618
vps雲伺服器免費租用 發布:2024-05-09 04:10:42 瀏覽:207
空調壓縮機排量 發布:2024-05-09 04:08:42 瀏覽:538
android使用靜態庫 發布:2024-05-09 04:05:40 瀏覽:213
原生安卓開機動畫在哪裡 發布:2024-05-09 03:52:19 瀏覽:394
微信收藏在哪個文件夾 發布:2024-05-09 03:47:03 瀏覽:826
ftp遠程登錄 發布:2024-05-09 03:44:40 瀏覽:227
linuxoracle配置環境變數配置 發布:2024-05-09 03:44:38 瀏覽:499
分類信息網站的源碼 發布:2024-05-09 03:31:18 瀏覽:99