Python Forum
Convert C code to Python code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert C code to Python code
#1
Hi I'm new to this forum.
I'm trying to convert an existing c program to python.
If someone can help me that'd be awesome!!!!
As of right now I'm getting the error:
Traceback (most recent call last):
File "mitnick.py", line 106, in <module>
main()
File "mitnick.py", line 76, in main
found = found | attempt_ROT(i, j)
File "mitnick.py", line 84, in attempt_ROT
currentChar = ciphered_text[cipheredIndex][i]
TypeError: string indices must be integers

I thought it would be a good challenge to convert this to python but I'm having all types of problems. I'm fairly new to programming and have only been coding since the beginning on this year 2018. I started in February. Anyways,
Here is a link to the C program which decrypt's some ciphers from the book Ghost in the wires by Kevin Mitnick.
C code

Here is my Python code so far. As you can probably tell. I've probably made several mistakes.

import string

"""This is a python version of ROT ciphers to crack ghost in the wires chapter puzzles."""

ciphered_text = [
    "yjcv ku vjg pcog qh vjg uauvgo wugf da jco qrgtcvqtu vq ocmg htgg rjqpg ecnnu ?",
    "wbth lal voe htat oy voe wxbirtn vfzbqt wagye C poh aeovsn vojgav ?",
    "Nyrk grjjnfiu uzu Z xzmv kf jvklg re rttflek fe Kyv Rib ?",
    "Flle ujw esc wexp mo xsp kjr hsm hiwwcm, \"Wplpll stq lec qma e wzerg mzkk!\" ?",
    "Bmfy ytbs ini N mnij tzy ns zsynq ymj Ozajsnqj Htzwy qtxy ozwnxinhynts tajw rj ?",
    "Kyoo olxi rzr Niyovo Cohjpcx ojy dn T apopsy ?",
    "Kvoh wg hvs boas ct hvs Doqwtwq Pszz sadzcmss kvc fsor hvs wbhsfboz asac opcih am voqywbu oqhwjwhwsq cjsf hvs voa forwc ?",
    "Iwh xwqv wpvpj fwr Vfvyj qks wf nzc ncgsoo esg psd gwc ntoqujvr ejs rypz nzfs ?",
    "Hsle td esp epcx qzc dzqehlcp mfcypo zy esp nsta esle Yzglepw dpye xp ?",
    "Bprf cup esanqneu xmm gtknv amme U biiwy krxheu Iwqt Taied ?",
    "Lwpi idlc sxs bn upiwtg axkt xc lwtc X bdkts xc lxiw wxb ?",
    "Yhlt xak tzg iytfrfad RanBfld squtpm uhst uquwd ce mswf tz wjrwtsr a wioe lhsv Ecid mwnlkoyee bmt oquwdo't ledn mp acomt ?",
    "Zkdw lv wkh qdph ri wkh SL ilup wkdw zdv zluhwdsshg eb Sdflilf Ehoo ?",
    "Plpki ytw eai rtc aaspx M llogw qj wef ms rh xq ?",
    # CH 15
    "Ituot oaybmzk ymwqe ftq pqhuoq ftmf Xqiue geqp fa buow gb mzk dmpua eusmxe zqmd Qduo ?",
    "Kwth qzrva rbq lcq rxw Svtg vxcz zm vzs lbfieerl nsem rmh dg ac oef'l cwamu ?",
    "Epib qa bpm vium wn bpm ixizbumvb kwuxtmf epmzm Q bziksml lwev Mzqk Pmqvh ?",
    # CH 18
    "Khkp wg wve kyfcqmm yb hvh TBS oeidr trwh Yhb MmCiwus Wko ogvwgxar hr ?",
    "Rcvo dn ivhz ja ocz omvinvxodji oj adiy v kzmnji'n njxdvg nzxpmdot iphwzm pndib oczdm ivhz viy yvoz ja wdmoc ?",
    # CH 20
    "Wspa wdw gae ypte rj gae dilan lbnsp loeui V tndllrhh gae awvnh \"HZO, hzl jaq M uxla nvu\"",


    # "4A 75 6E 67 20 6A 6E 66 20 62 68 65 20 61 76 70 78 61 6E 7A 72 20 74 76 69 72 61 20 67 62 20 47 72 65 65 6C 20 55 6E 65 71 6C 3F ",
    #  The above string is just Hexadecimal for character encoding, it translates to the following
    "Jung jnf bhe avpxanzr tvira gb Greel Uneql ?",

    "Gsig cof dsm fkqeoe vnss jo farj tbb epr Csyvd Nnxub mzlr ut grp lne ?",
    "Fqjc nunlcaxwrl mnerln mrm cqn OKR rwcnwcrxwjuuh kanjt fqnw cqnh bnjalqnm vh jyjacvnwc rw Ljujkjbjb ?",
    # CH 24
    "Xvof jq qis bmns lg hvq thlss ktffb J cifsok EAJ uojbthwsbhlsg ?",
    "Cngz zuct ngy znk grsg sgzkx lux znk xkgr Kxoi Ckoyy ?",
    "Aslx jst rlxi bx ns wgzzcmgw UP jnsh hlrjf nyk TT seq s cojorpdw pssx gxmyeie ao bzy glc ?",
    # CH 27
    # "85 102 121 114 32 103 113 32 114 102 99 32 108 121 107 99 32 109 100 32 114 102 99 32 122 109 105 113 114 109 112 99 32 71 32 100 112 99 111 115 99 108 114 99 98 32 103 108 32 66 99 108 116 99 112 63",
    "Ufyr gq rfc lykc md rfc zmiqrmpc G dpcosclrcb gl Bcltcp ?",

    "Phtm zvvvkci sw mhx Fmtvr VOX Ycmrt Emki vqimgv vowx hzh L cgf Ecbst ysi ?",
    "126 147 172 163 040 166 172 162 040 154 170 040 157 172 162 162 166 156 161 143 040 145 156 161 040 163 147 144 040 115 156 165 144 153 153 040 163 144 161 154 150 155 172 153 040 162 144 161 165 144 161 040 150 155 040 122 172 155 040 111 156 162 144 077",
    "Ouop lqeg gs zkds ulv V deds zq lus DS urqstsn't wwiaps ?",
    "Alex B25 rixasvo hmh M ywi xs xli HQZ qemrjveqi ?",
    "Caem alw Ymek Xptq'd tnwlchvw xz lrv lkkzxv ?",
    # CH 33
    "Ozg ojglw lzw hshwj gf AH Khggxafy lzsl BKR skcww ew stgml ?",
    "Nvbx nte hyv bqgs pj gaabv jmjmwdi whd hyv UVT'g Giuxdoc Gctcwd Hvyqbuvz hycoij ?",
    "2B 2T W 2X 2Z 26 36 2P 36 2V 3C W 3A 32 39 38 2Z W 3D 33 31 38 2V 36 3D W 2R 2Z W 3E 3C 2V 2X 2Z 2Y W 3E 39 W 2R 32 2V 2E W 2V 3A 2V 3C 3E 37 2X 38 3E W 2X 39 37  3A 36 2Z 2S 1R",
    "Lsar JSA cryoi ergiu lq wipz tnrs dq dccfunaqi zf oj wqpctkiel dpzpgp I jstcgo cu dy hgq ?",
    # CH 37
    "V2hhdCBGQkkgYWdlbnQgYXNrZWQgU3VuIE1pY3Jvc3lzdGVtcyB0byBjbGFpbSB0aGV51Gxvc3QgODAgbWlsbGlvbiBkb2xsYXJzPw==",
    # CH 38
    "100-1111-10-0 011-000-1-111 00-0100 1101-10-1110-000-101-11-0-1 \
	0111-110-00-1001-1-101 111-0-11-0101-010-1-101 111-10-0100 11-00-11"

]

alphabet = list(string.ascii_lowercase)
keywords = ['what ', 'is ', 'the ', 'of ', 'by ',
            'to ', 'did ', 'in ', 'when ', 'how ']


def main():
    numTexts = len(ciphered_text)
    found = 0
    for j in range(numTexts):
        print("%s\n" % ciphered_text[j])
        found = 0
        for i in range(26):
            found = found | attempt_ROT(i, j)
        if not found:
            print("%d: No Candidate.\n" % (j+1))


def attempt_ROT(rot, cipheredIndex):
    tmpString = []
    for i in ciphered_text[cipheredIndex]:
        currentChar = ciphered_text[cipheredIndex][i]

        if currentChar >= 65 and currentChar <= 90:
            currentChar = currentChar + 32
        elif currentChar >= 97 and currentChar <= 122:
            tmpString[i] = alphabet[(currentChar + rot) % 26]
        else:
            tmpString[i] = ciphered_text[cipheredIndex][i]

    tmpString[i] = '\0'

    # Rotation is done. Now search for keywords.

    for key in len(range(keywords)):
        if tmpString in keywords[key]:
            print("%d: Candidate (ROT%d): %s\n" %
                  (cipheredIndex+1, rot, tmpString))
            return 1
    return 0


if __name__ == '__main__':
    main()
Reply
#2
Note that for i in ciphered_text[cipheredIndex]: is going to loop through each item in ciphered_text. It's like for each i in ciphered_text in some languages. So the first time through the loop i, if cipherIndex = 0, will be equal to 'y'. You then try to use that as an index to the string. I'm assuming you want the 'y' in currentChar anyway, so you should just use for currentChar in ciphered_text[cipheredIndex]:, and delete line 83.

Note you will have problems in the next section, because you are comparing strings (currentChar) to integers. Use ord(currentChar) to get the integer value for the character. I'm also not sure that the % 26 on line 88 is going to do what you expect, but maybe I'm expecting something different.

You should use this feature that Python inherently loops over items in a sequence. Lines 96 & 97 should be:

    for key in keywords:
        if tmpString in key:
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Hey thanks for the response man I really appreciate it. I made the changes like you suggested however now I'm getting a different error. ("sigh")

line 83, in attempt_ROT
ord(currentChar) + rot) % 26]
IndexError: list assignment index out of range

Thanks for being patient with me.

here is what my updated python code looks like now:

import string

"""This is a python version of ROT ciphers to crack ghost in the wires chapter puzzles."""

ciphered_text = [
    "yjcv ku vjg pcog qh vjg uauvgo wugf da jco qrgtcvqtu vq ocmg htgg rjqpg ecnnu ?",
    "wbth lal voe htat oy voe wxbirtn vfzbqt wagye C poh aeovsn vojgav ?",
    "Nyrk grjjnfiu uzu Z xzmv kf jvklg re rttflek fe Kyv Rib ?",
    "Flle ujw esc wexp mo xsp kjr hsm hiwwcm, \"Wplpll stq lec qma e wzerg mzkk!\" ?",
    "Bmfy ytbs ini N mnij tzy ns zsynq ymj Ozajsnqj Htzwy qtxy ozwnxinhynts tajw rj ?",
    "Kyoo olxi rzr Niyovo Cohjpcx ojy dn T apopsy ?",
    "Kvoh wg hvs boas ct hvs Doqwtwq Pszz sadzcmss kvc fsor hvs wbhsfboz asac opcih am voqywbu oqhwjwhwsq cjsf hvs voa forwc ?",
    "Iwh xwqv wpvpj fwr Vfvyj qks wf nzc ncgsoo esg psd gwc ntoqujvr ejs rypz nzfs ?",
    "Hsle td esp epcx qzc dzqehlcp mfcypo zy esp nsta esle Yzglepw dpye xp ?",
    "Bprf cup esanqneu xmm gtknv amme U biiwy krxheu Iwqt Taied ?",
    "Lwpi idlc sxs bn upiwtg axkt xc lwtc X bdkts xc lxiw wxb ?",
    "Yhlt xak tzg iytfrfad RanBfld squtpm uhst uquwd ce mswf tz wjrwtsr a wioe lhsv Ecid mwnlkoyee bmt oquwdo't ledn mp acomt ?",
    "Zkdw lv wkh qdph ri wkh SL ilup wkdw zdv zluhwdsshg eb Sdflilf Ehoo ?",
    "Plpki ytw eai rtc aaspx M llogw qj wef ms rh xq ?",
    # CH 15
    "Ituot oaybmzk ymwqe ftq pqhuoq ftmf Xqiue geqp fa buow gb mzk dmpua eusmxe zqmd Qduo ?",
    "Kwth qzrva rbq lcq rxw Svtg vxcz zm vzs lbfieerl nsem rmh dg ac oef'l cwamu ?",
    "Epib qa bpm vium wn bpm ixizbumvb kwuxtmf epmzm Q bziksml lwev Mzqk Pmqvh ?",
    # CH 18
    "Khkp wg wve kyfcqmm yb hvh TBS oeidr trwh Yhb MmCiwus Wko ogvwgxar hr ?",
    "Rcvo dn ivhz ja ocz omvinvxodji oj adiy v kzmnji'n njxdvg nzxpmdot iphwzm pndib oczdm ivhz viy yvoz ja wdmoc ?",
    # CH 20
    "Wspa wdw gae ypte rj gae dilan lbnsp loeui V tndllrhh gae awvnh \"HZO, hzl jaq M uxla nvu\"",
    # "4A 75 6E 67 20 6A 6E 66 20 62 68 65 20 61 76 70 78 61 6E 7A 72 20 74 76 69 72 61 20 67 62 20 47 72 65 65 6C 20 55 6E 65 71 6C 3F ",
    #  The above string is just Hexadecimal for character encoding, it translates to the following
    "Jung jnf bhe avpxanzr tvira gb Greel Uneql ?",

    "Gsig cof dsm fkqeoe vnss jo farj tbb epr Csyvd Nnxub mzlr ut grp lne ?",
    "Fqjc nunlcaxwrl mnerln mrm cqn OKR rwcnwcrxwjuuh kanjt fqnw cqnh bnjalqnm vh jyjacvnwc rw Ljujkjbjb ?",
    # CH 24
    "Xvof jq qis bmns lg hvq thlss ktffb J cifsok EAJ uojbthwsbhlsg ?",
    "Cngz zuct ngy znk grsg sgzkx lux znk xkgr Kxoi Ckoyy ?",
    "Aslx jst rlxi bx ns wgzzcmgw UP jnsh hlrjf nyk TT seq s cojorpdw pssx gxmyeie ao bzy glc ?",
    # CH 27
    # "85 102 121 114 32 103 113 32 114 102 99 32 108 121 107 99 32 109 100 32 114 102 99 32 122 109 105 113 114 109 112 99 32 71 32 100 112 99 111 115 99 108 114 99 98 32 103 108 32 66 99 108 116 99 112 63",
    "Ufyr gq rfc lykc md rfc zmiqrmpc G dpcosclrcb gl Bcltcp ?",
    "Phtm zvvvkci sw mhx Fmtvr VOX Ycmrt Emki vqimgv vowx hzh L cgf Ecbst ysi ?",
    "126 147 172 163 040 166 172 162 040 154 170 040 157 172 162 162 166 156 161 143 040 145 156 161 040 163 147 144 040 115 156 165 144 153 153 040 163 144 161 154 150 155 172 153 040 162 144 161 165 144 161 040 150 155 040 122 172 155 040 111 156 162 144 077",
    "Ouop lqeg gs zkds ulv V deds zq lus DS urqstsn't wwiaps ?",
    "Alex B25 rixasvo hmh M ywi xs xli HQZ qemrjveqi ?",
    "Caem alw Ymek Xptq'd tnwlchvw xz lrv lkkzxv ?",
    # CH 33
    "Ozg ojglw lzw hshwj gf AH Khggxafy lzsl BKR skcww ew stgml ?",
    "Nvbx nte hyv bqgs pj gaabv jmjmwdi whd hyv UVT'g Giuxdoc Gctcwd Hvyqbuvz hycoij ?",
    "2B 2T W 2X 2Z 26 36 2P 36 2V 3C W 3A 32 39 38 2Z W 3D 33 31 38 2V 36 3D W 2R 2Z W 3E 3C 2V 2X 2Z 2Y W 3E 39 W 2R 32 2V 2E W 2V 3A 2V 3C 3E 37 2X 38 3E W 2X 39 37  3A 36 2Z 2S 1R",
    "Lsar JSA cryoi ergiu lq wipz tnrs dq dccfunaqi zf oj wqpctkiel dpzpgp I jstcgo cu dy hgq ?",
    # CH 37
    "V2hhdCBGQkkgYWdlbnQgYXNrZWQgU3VuIE1pY3Jvc3lzdGVtcyB0byBjbGFpbSB0aGV51Gxvc3QgODAgbWlsbGlvbiBkb2xsYXJzPw==",
    # CH 38
    "100-1111-10-0 011-000-1-111 00-0100 1101-10-1110-000-101-11-0-1 \
	0111-110-00-1001-1-101 111-0-11-0101-010-1-101 111-10-0100 11-00-11"
]

alphabet = list(string.ascii_lowercase)
keywords = ['what ', 'is ', 'the ', 'of ', 'by ',
            'to ', 'did ', 'in ', 'when ', 'how ']


def main():
    numTexts = len(ciphered_text)
    found = 0
    for j in range(numTexts):
        print("%s\n" % ciphered_text[j])
        found = 0
        for i in range(26):
            found = found | attempt_ROT(i, j)
        if not found:
            print("%d: No Candidate.\n" % (j+1))


def attempt_ROT(rot, cipheredIndex):
    tmpString = []
    for currentChar in ciphered_text[cipheredIndex]:
        if ord(currentChar) >= 65 and ord(currentChar) <= 90:
            currentChar = ord(currentChar) + 32
        elif ord(currentChar) >= 97 and ord(currentChar) <= 122:
            tmpString[ord(currentChar)] = alphabet[(
                ord(currentChar) + rot) % 26]
        else:
            tmpString[ord(currentChar)
                      ] = ciphered_text[cipheredIndex][ord(currentChar)]

    tmpString[ord(currentChar)] = '\0'

    # Rotation is done. Now search for keywords.

    for key in keywords:
        if tmpString in key:
            print("%d: Candidate (ROT%d): %s\n" %
                  (cipheredIndex+1, rot, tmpString))
            return 1
    return 0


if __name__ == '__main__':
    main()

Also,
Are you familiar with ICHABOD aka ICH the freight train graffiti artist?
That would be cool. I also like to paint trains. Although it's been years since the last time i painted one.
Reply
#4
The error is on the index of tmpString. Think about that for loop. Assume the first character has an ord between 97 and 122, say 108. It will go to line 82/83, and try to set tmpString[108]. But tmpString is empty at the start of the loop. You can't set an index beyond the end of the list so you get an error.

I'm not sure what you're doing there, or what you want to do there, so I'm not sure how to fix it. If tmpString is meant to be built character by character in order, you want to append there. If you do want to assign to different places in a long list, you need to fill the list with dummy or default values to start, at least 122 of them.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Thanks for getting back to me again. I'm going to put this mini project on the back burner for now and focus on some other projects. Eventually I will come back and try again to figure out my how to solve the tmpString index error.
Basically the purpose of this relatively small program is to decrypt various ROT encryption algorithms.
This is what the correct output is from the C program that I was trying to convert to python.

[1]: Candidate (ROT5): what is the name of the system used by ham operators to make free phone calls ?
[2]: Candidate (ROT1): qvnb fuf piy bnun is piy qrvclnh pztvkn quasy w jib uyipmh pidaup ?
[3]: Candidate (ROT16): what password did i give to setup an account on the ark ?
[4]: No Candidate.
[5]: Candidate (ROT2): what town did i hide out in until the juvenile court lost jurisdiction over me ?
[6]: Candidate (ROT12): pdtt tqcn wew sndtat htmouhc tod is y futuxd ?
[7]: Candidate (ROT19): what is the name of the pacific bell employee who read the internal memo about my hacking activitiec over the ham radio ?
[8]: No Candidate.
[9]: Candidate (ROT22): what is the term for software burned on the chip that novatel sent me ?
[10]: No Candidate.
[11]: Candidate (ROT18): what town did my father live in when i moved in with him ?
[12]: No Candidate.
[13]: Candidate (ROT4): what is the name of the pi firm that was wiretapped by pacific bell ?
[14]: No Candidate.
[15]: Candidate (ROT20): vghbg bnlozmx lzjdr sgd cduhbd sgzs kdvhr trdc sn ohbj to zmx qzchn rhfzkr mdzq dqhb ?
[15]: Candidate (ROT21): which company makes the device that lewis used to pick up any radio sigals near eric ?
[16]: No Candidate.
[17]: Candidate (ROT25): what is the name of the apartment complex where i tracked down eric heinz ?
[18]: Candidate (ROT8): lilq xh xwf lzgdrnn zc iwi uct pfjes usxi zic nndjxvt xlp phwxhybs is ?
[18]: Candidate (ROT19): wtwb is ihq wkrocyy kn tht fne aqupd fdit ktn yyouige iwa ashisjmd td ?
[19]: Candidate (ROT12): what is name of the transaction to find a person's social security number using their name and date of birth ?
[20]: No Candidate.
[21]: Candidate (ROT20): what was our nickname given to terry hardy ?
[22]: Candidate (ROT6): frhf bne crl ejpdnd umrr in ezqi saa doq brxuc mmwta lykq ts fqo kmd ?
[23]: Candidate (ROT24): what electronic device did the fbi intentionally break when they searched my apartment in calabasas ?
[24]: Candidate (ROT15): fdwn ry yqa juva to pdy bptaa sbnnj r kqnaws mir cwrjbpeajptao ?
[25]: Candidate (ROT1): what town has the alma mater for the real eric weiss ?
[26]: Candidate (ROT2): vngs eno mgsd ws in rbuuxhbr pk einc cgmea itf oo nzl n xjejmkyr knns bshtzdz vj wut bgx ?
[26]: Candidate (ROT6): zrkw irs qkwh aw mr vfyyblfv to imrg gkqie mxj ss rdp r bninqocv orrw fwlxdhd zn ayx fkb ?
[27]: Candidate (ROT9): what is the name of the bokstore i frequented in denver ?
[28]: No Candidate.
[29]: No Candidate.
[30]: Candidate (ROT22): djde aftv vh ozsh jak k stsh of ajh sh jgfhihc'i llxpeh ?
[31]: Candidate (ROT3): what x25 network did i use to the dmv mainframe ?
[32]: No Candidate.
[33]: Candidate (ROT15): who wrote the paper on ip spoofing that jsz askee me about ?
[34]: No Candidate.
[35]: No Candidate.
[36]: Candidate (ROT4): ipxo gpx zovlf bodfr in tfmw qkop an azzcrkxnf wc lg tnmzqhfbi amwmdm f gpqzdl zr av edn ?
[36]: Candidate (ROT12): qxfw oxf hwdtn jwlnz qv bnue yswx iv ihhkzsfvn ek to bvuhypnjq iueulu n oxyhlt hz id mlv ?
[36]: Candidate (ROT23): biqh ziq shoey uhwyk bg myfp jdhi tg tssvkdqgy pv ez mgfsjayub tfpfwf y zijswe sk to xwg ?
[37]: No Candidate.
[38]: No Candidate.
Thanks again for the advice and may the force be with you.
Peace
Reply
#6
I see. Here's what I came up given your description of the goal, just writing it from scratch. I'm not getting the same rotations, but I am getting the same decodings, except in some of the false positives. It's no clear why I'm getting different rotations. I thought it might be encoding rotation vs. decoding rotation, but then my rotations and the given rotations should add to 26, which isn't the case.

"""
rot_decoder.py

Decode text encoded by a simple rot.

Constants:
TEST_CASES: Sample texts encoded using rotations. (str)

Functions:
find_rotation: Find a possible decoding of a text assuming ROTX encoding. (int)
rotate: Perform a ROTX transformation of the text. (str)
"""

import string

TEST_CASES = ["yjcv ku vjg pcog qh vjg uauvgo wugf da jco qrgtcvqtu vq ocmg htgg rjqpg ecnnu ?",
    "wbth lal voe htat oy voe wxbirtn vfzbqt wagye C poh aeovsn vojgav ?",
    "Nyrk grjjnfiu uzu Z xzmv kf jvklg re rttflek fe Kyv Rib ?",
    "Flle ujw esc wexp mo xsp kjr hsm hiwwcm, \"Wplpll stq lec qma e wzerg mzkk!\" ?",
    "Bmfy ytbs ini N mnij tzy ns zsynq ymj Ozajsnqj Htzwy qtxy ozwnxinhynts tajw rj ?",
    "Kyoo olxi rzr Niyovo Cohjpcx ojy dn T apopsy ?",
    "Kvoh wg hvs boas ct hvs Doqwtwq Pszz sadzcmss kvc fsor hvs wbhsfboz asac opcih am voqywbu oqhwjwhwsq cjsf hvs voa forwc ?",
    "Iwh xwqv wpvpj fwr Vfvyj qks wf nzc ncgsoo esg psd gwc ntoqujvr ejs rypz nzfs ?",
    "Hsle td esp epcx qzc dzqehlcp mfcypo zy esp nsta esle Yzglepw dpye xp ?",
    "Bprf cup esanqneu xmm gtknv amme U biiwy krxheu Iwqt Taied ?",
    "Lwpi idlc sxs bn upiwtg axkt xc lwtc X bdkts xc lxiw wxb ?",
    "Yhlt xak tzg iytfrfad RanBfld squtpm uhst uquwd ce mswf tz wjrwtsr a wioe lhsv Ecid mwnlkoyee bmt oquwdo't ledn mp acomt ?",
    "Zkdw lv wkh qdph ri wkh SL ilup wkdw zdv zluhwdsshg eb Sdflilf Ehoo ?",
    "Plpki ytw eai rtc aaspx M llogw qj wef ms rh xq ?",
    # CH 15
    "Ituot oaybmzk ymwqe ftq pqhuoq ftmf Xqiue geqp fa buow gb mzk dmpua eusmxe zqmd Qduo ?",
    "Kwth qzrva rbq lcq rxw Svtg vxcz zm vzs lbfieerl nsem rmh dg ac oef'l cwamu ?",
    "Epib qa bpm vium wn bpm ixizbumvb kwuxtmf epmzm Q bziksml lwev Mzqk Pmqvh ?",
    # CH 18
    "Khkp wg wve kyfcqmm yb hvh TBS oeidr trwh Yhb MmCiwus Wko ogvwgxar hr ?",
    "Rcvo dn ivhz ja ocz omvinvxodji oj adiy v kzmnji'n njxdvg nzxpmdot iphwzm pndib oczdm ivhz viy yvoz ja wdmoc ?",
    # CH 20
    "Wspa wdw gae ypte rj gae dilan lbnsp loeui V tndllrhh gae awvnh \"HZO, hzl jaq M uxla nvu\"",
    "Jung jnf bhe avpxanzr tvira gb Greel Uneql ?",
    "Gsig cof dsm fkqeoe vnss jo farj tbb epr Csyvd Nnxub mzlr ut grp lne ?",
    "Fqjc nunlcaxwrl mnerln mrm cqn OKR rwcnwcrxwjuuh kanjt fqnw cqnh bnjalqnm vh jyjacvnwc rw Ljujkjbjb ?",
    # CH 24
    "Xvof jq qis bmns lg hvq thlss ktffb J cifsok EAJ uojbthwsbhlsg ?",
    "Cngz zuct ngy znk grsg sgzkx lux znk xkgr Kxoi Ckoyy ?",
    "Aslx jst rlxi bx ns wgzzcmgw UP jnsh hlrjf nyk TT seq s cojorpdw pssx gxmyeie ao bzy glc ?",
    # CH 27
    "Ufyr gq rfc lykc md rfc zmiqrmpc G dpcosclrcb gl Bcltcp ?",
    "Phtm zvvvkci sw mhx Fmtvr VOX Ycmrt Emki vqimgv vowx hzh L cgf Ecbst ysi ?",
    "126 147 172 163 040 166 172 162 040 154 170 040 157 172 162 162 166 156 161 143 040 145 156 161 040 163 147 144 040 115 156 165 144 153 153 040 163 144 161 154 150 155 172 153 040 162 144 161 165 144 161 040 150 155 040 122 172 155 040 111 156 162 144 077",
    "Ouop lqeg gs zkds ulv V deds zq lus DS urqstsn't wwiaps ?",
    "Alex B25 rixasvo hmh M ywi xs xli HQZ qemrjveqi ?",
    "Caem alw Ymek Xptq'd tnwlchvw xz lrv lkkzxv ?",
    # CH 33
    "Ozg ojglw lzw hshwj gf AH Khggxafy lzsl BKR skcww ew stgml ?",
    "Nvbx nte hyv bqgs pj gaabv jmjmwdi whd hyv UVT'g Giuxdoc Gctcwd Hvyqbuvz hycoij ?",
    "2B 2T W 2X 2Z 26 36 2P 36 2V 3C W 3A 32 39 38 2Z W 3D 33 31 38 2V 36 3D W 2R 2Z W 3E 3C 2V 2X 2Z 2Y W 3E 39 W 2R 32 2V 2E W 2V 3A 2V 3C 3E 37 2X 38 3E W 2X 39 37  3A 36 2Z 2S 1R",
    "Lsar JSA cryoi ergiu lq wipz tnrs dq dccfunaqi zf oj wqpctkiel dpzpgp I jstcgo cu dy hgq ?",
    # CH 37
    "V2hhdCBGQkkgYWdlbnQgYXNrZWQgU3VuIE1pY3Jvc3lzdGVtcyB0byBjbGFpbSB0aGV51Gxvc3QgODAgbWlsbGlvbiBkb2xsYXJzPw==",
    # CH 38
    "100-1111-10-0 011-000-1-111 00-0100 1101-10-1110-000-101-11-0-1 0111-110-00-1001-1-101 111-0-11-0101-010-1-101 111-10-0100 11-00-11"]


def find_rotation(text, keywords):
	"""
	Find a possible decoding of a text assuming ROTX encoding. (int)

	A return value of 0 means no rotation was found. Any other return value
	indicates one of the keywords was found when decoding with that rotation.

	Parameters:
	text: The encoded text. (str)
	keywords: Keywords to check for in the rotations. (set of str)
	"""
	# check all possible rotations.
	for rotation in range(1, 26):
		rotated = rotate(text, rotation)
		# Check each on for a keyword match.
		words = set(rotated.lower().split())
		if words.intersection(keywords):
			break
	else:
		# Return zero if no match founds.
		return 0
	return rotation


def rotate(text, n):
	"""
	Perform a ROTX transformation of the text. (str)

	Parameters:
	text: The text to rotate. (str)
	n: The distance of the rotation. (int)
	"""
	# Translate each character.
	new_text = ''
	for char in text:
		# Get the appropriate letter set.
		if char.islower():
			letters = string.ascii_lowercase
		elif char.isupper():
			letters = string.ascii_uppercase
		else:
			# Do not transform non-letter characters.
			new_text += char
			continue
		# Perform the transfomation.
		new_text += letters[(letters.index(char) + n) % 26]
	return new_text


if __name__ == '__main__':
	# Run the test cases with sample keywords.
	keywords = set('what is the of by to did in when how'.split())
	#keywords = set('who what why when where how'.split())
	for text in TEST_CASES:
		rotation = find_rotation(text, keywords)
		if rotation:
			print('Candidate (ROT {}): {}'.format(rotation, rotate(text, rotation)))
		else:
			print('No Candidate.')
Until you get the hang of translating C, writing from scratch can often be a better way to do it.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#7
This any help?

Making your C library callable from Python by wrapping it with Cython

Phil
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Equivalent Python code from VBA Mishal0488 2 696 7 hours ago
Last Post: masonsbore
  Why can I not see the code correctly in Python IDLE.? Trump 8 666 Apr-04-2024, 07:47 AM
Last Post: jonesphedra
Sad Selenium update broke python code genericusername12414 1 232 Mar-16-2024, 07:33 PM
Last Post: snippsat
  Algorithm for extracting comments from Python source code Pavel1982 6 512 Feb-28-2024, 09:52 PM
Last Post: Pavel1982
  Python best library for Excel reports & review of existing code MasterOfDestr 4 609 Feb-14-2024, 03:39 PM
Last Post: MasterOfDestr
Lightbulb python code debuging yunus 1 331 Feb-11-2024, 03:48 PM
Last Post: deanhystad
  Python code to set column width 1418 11 1,176 Jan-20-2024, 07:20 AM
Last Post: Pedroski55
  Python code for alignment and font size 1418 0 310 Jan-14-2024, 03:56 AM
Last Post: 1418
  My code works on Jupyter Lab/Notebook, but NOT on Visual Code Editor jst 4 989 Nov-15-2023, 06:56 PM
Last Post: jst
  How to run detectron2, as python embedded code in C++, on GPU? hassaniqbal931 3 1,083 Nov-02-2023, 04:45 PM
Last Post: blabling2

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020