手工将C代码转换成Python

2024-10-04 03:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将下面的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)

Tags: 代码forifmainds经验sdelse
3条回答

我希望这能实现您的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

见此,已解释为:

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)

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

while j<len(a):
    #code

或者

while j<18:
    #code

将清除错误

相关问题 更多 >