手动将C代码转换为Python

时间:2014-01-07 20:00:53

标签: python c

我正在尝试将以下C代码转换为Python。我没有C语言的经验,但在Python中有一点经验。

main( int argc, char *argv[]) 
{ 
    char a[] = "ds dsf ds sd dsfas"; 
    unsigned char c; 
    int d, j; 

    for(d = 0; d < 26; d++) 
    { 
        printf("d = %d: ", d); 
        for (j = 0; j < 21; j++ ) 
        { 
            if( a[j] == ' ') 
            c = ' '; 
            else 
            { 
                c = a[j] + d; 
                if (c > 'z') 
                c = c - 26; 
            }    
            printf("%c", c); 
    } 
    printf("\n"); 
} 

我已经设法达到这一点:我在哪里得到列表索引超出范围异常,有什么建议吗?

d=0
a=["ds dsf ds sd dsfas"]
while (d <26):

    print("d = ",d)
    d=d+1

    j=0
    while(j<21):

        if a[j]=='':
            c =''
        else:
            c = answer[j]+str(d)
            if c>'z':
                c=c-26
        j=j+1
        print("%c",c)

3 个答案:

答案 0 :(得分:0)

循环执行直到j变为21.但我不认为你在a列表中有那么多元素。这就是为什么你得到错误。我认为len(a)是18.因此将循环更改为:

while j<len(a):
    #code

while j<18:
    #code

将清除错误

答案 1 :(得分:0)

我希望这可以解决您的C代码试图实现的目标:

#! /usr/bin/python2.7

import string

a = 'ds dsf ds sd dsfas' #input
for d in range (26): #the 26 possible Caesar's cypher keys
    shift = string.ascii_lowercase [d:] + string.ascii_lowercase [:d] #rotate the lower ase ascii with offset d
    tt = string.maketrans (string.ascii_lowercase, shift) #convenience function to create a transformation, mapping each character to its encoded counterpart
    print 'd = {}:'.format (d) #print out the key
    print a.translate (tt) #translate the plain text and print it

答案 2 :(得分:-1)

看到这个,已经用评论解释了:

d=0
a=["ds dsf ds sd dsfas"]

# this will print 1 as a is a list object 
# and it's length is 1 and a[0] is "ds dsf ds sd dsfas"
print len(a) 

# and your rest of program is like this
while (d <26):
    print("d = ",d)
    d=d+1

    #j=0
    # while(j<21): it's wrong as list length is 1
    # so it will give list index out of bound error
    # in c array does not check for whether array's index is within
    # range or not so it will not give out of bound error
    for charValue in a: 
        if charValue is '':
            c =''
        else:
            c = charValue +str(d) # here you did not initialized answer[i]
            if c>'z':
                c=c-26
        #j=j+1
        print("%c",c)