Bottom Page

• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 Alternate solutions to cipher problem? Mark17 Silly Frenchman Posts: 46 Threads: 18 Joined: Aug 2019 Reputation: 0 Likes received: 0 #1 Oct-03-2019, 04:44 PM I coded the following program to translate a string using a cipher dictionary: ```CIPHER_DICT = {'e': 'u', 'b': 's', 'k': 'x', 'u': 'q', 'y': 'c', 'm': 'w', 'o': 'y', 'g': 'f', 'a': 'm', 'x': 'j', 'l': 'n', 's': 'o', 'r': 'g', 'i': 'i', 'j': 'z', 'c': 'k', 'f': 'p', ' ': 'b', 'q': 'r', 'z': 'e', 'p': 'v', 'v': 'l', 'h': 'h', 'd': 'd', 'n': 'a', 't': ' ', 'w': 't'} print(' This is a cipher program, which translates text as directed by cipher_dict:') print(CIPHER_DICT) print(' We will operate on:') print() str1 = 'the quick brown fox jumped over the lazy dog' #Substituted lower for upper case t as first letter print('', str1) print() count = 0 liststr1 = list(str1) #gets list of characters in string for letter in liststr1: newval = CIPHER_DICT[letter] liststr1[count] = newval count = count + 1 #using list index to rewrite list print(' Translated string list is: ',liststr1) print() print(" In English, that is:","".join(liststr1)) #converting back to list ```I'm a newbie so I'm thinking that is quite inefficient. I took a string, converted to list, and went back to string. What better ways could I have used to solve this? Thanks! stullis Minister of Silly Walks Posts: 343 Threads: 0 Joined: Sep 2018 Reputation: 39 Likes received: 61 #2 Oct-03-2019, 05:34 PM List comprehensions are faster than equivalent loops. We can remove some of the supporting assignments, conversions, and operations too. ```CIPHER_DICT = {'e': 'u', 'b': 's', 'k': 'x', 'u': 'q', 'y': 'c', 'm': 'w', 'o': 'y', 'g': 'f', 'a': 'm', 'x': 'j', 'l': 'n', 's': 'o', 'r': 'g', 'i': 'i', 'j': 'z', 'c': 'k', 'f': 'p', ' ': 'b', 'q': 'r', 'z': 'e', 'p': 'v', 'v': 'l', 'h': 'h', 'd': 'd', 'n': 'a', 't': ' ', 'w': 't', ' ': ' '} str1 = 'the quick brown fox jumped over the lazy dog' print("".join([CIPHER_DICT[x] for x in str1])) ``` newbieAuggie2019 likes this post Mark17 Silly Frenchman Posts: 46 Threads: 18 Joined: Aug 2019 Reputation: 0 Likes received: 0 #3 Oct-08-2019, 01:17 PM (Oct-03-2019, 05:34 PM)stullis Wrote: List comprehensions are faster than equivalent loops. We can remove some of the supporting assignments, conversions, and operations too. Can you give me a couple examples, Stullis? jefsummers Spam, spam, eggs, and spam Posts: 237 Threads: 1 Joined: May 2019 Reputation: 21 Likes received: 41 #4 Oct-08-2019, 01:32 PM A nice review of list comprehensions can be found at Socratica - Youtube on list comprehensions This shows several examples of varying complexity. « Next Oldest | Next Newest »

Top Page

 Possibly Related Threads... Thread Author Replies Views Last Post Problem with caesar cipher lucaron 2 953 Feb-05-2018, 05:17 PM Last Post: lucaron

Forum Jump:

Users browsing this thread: 1 Guest(s)