2014-01-07 116 views
-3

我正试图将以下C代码转换为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) 
+6

提示:原因是什么C程序试图做,然后在Python中进行编码。不要直译。 –

+1

codereview.stackexchange.com/可能更合适。 –

+0

关于如何强奸凯撒的密码,在这里也有很多答案。 – Hyperboreus

回答

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 
+0

感谢你们,你们能否添加评论来解释每一行的作用? –

+0

@ Pro-grammer做到了。 – Hyperboreus

+0

你为什么使用ascii号码? –

0

循环执行,直到Ĵ成为21.But我不认为你有在a列表中的许多元素。这就是为什么你会得到这个错误。我认为len(a)是18.所以改变环路为:

while j<len(a): 
    #code 

while j<18: 
    #code 

会清除错误

-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) 
+0

这没有给出正确的输出作为C程序,看到这个:http://uk.answers.yahoo.com/question/index?qid = 20130422003626AAUFGHn –

+0

因为在C程序中,您使用的值超出了char数组char a [] =“ds dsf ds sd dsfas”,它的长度是18,所以最后一个索引是17,因此[18],a [19],a [20]会给出一些垃圾值。这就是为什么你在两个方面都没有得到同样的结果 – 2014-01-07 20:39:08