473,657 Members | 2,530 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to reverse lookup characters in list?

Okay so im working on a very simple encryption method using just loops.
Kind of novel i think. Okay so first i set up a list of the alphabet with
just every seperate letter, then user is prompted for a word, this is not
user friendly just for me. Ok now as you can see below this is pretty
basic, if u can follow all the loops i get to a point where I have the
letter positions in the list for the final word but i dont know of a way
to come back with the corresponding letter to output to the user. Ummm
some help would be really appreciated. Sorry about the length!
----------------------------------------------------------------------------
from time import sleep
#Alphabet list used to move letters forward for simple encryption.
alphabet =
["a","b","c","d" ,"e","f","g","h ","i","j","k"," l","m","n","o", "p","q","r","s" ,"t","u","v","w ","x","y"," z"]

word_list = []
number_list = []
number_list2 = []
new_word = []
#variable for how far you want to switch
v = 2
word = raw_input("Word : ")
a = len(word)
for x in range(0, len(word)):
print word[x],
word_list.appen d(word[x])
b = alphabet.index( word[x])
number_list.app end(b)

for x in range(0, len(number_list )):
c = number_list[x]
c = c + v
number_list2.ap pend(c)

for x in range(0, len(number_list 2)):
d = number_list2[x]
new_word.append (d)

for x in range(0,
#Stopped here because dont know of way to switch back.
----------------------------------------------------------------------------

When you see the net take the shot
When you miss your shot shoot again
When you make your shot you win!

Just remember
Offense sells tickets
But defense wins championships!

Jul 18 '05 #1
5 3498
okay, isn't the number in the list the index of the new letter? So you'd
just use alphabet[d].. though what you're doing can be done in a much
simpler manner..

for starters... check out the string module. you can do

import string
string.lowercas e

that gives you a-z, lowercase.. I think you'll be fine with a string,
rather than a list (infact, it's better since it's immutable). If you must
ahve a list, you can do

[a for a in string.lowercas e]

to get a list of characters from a to z.

Now, all you're really doing with all those lists and loops is just
mapping from one character to another. In fact, you're just doing a rotX,
where x is the value of your variable v

you could just do:

rotation = int(raw_input(' rotation value: '))
word = raw_input('word : ')
............... ......
new_word = ''
for char in word:
position = string.lowercas e.index(char)
position += rotation

# this makes it wrap around. i.e. 'z'+2 = 'b'
position = position % 26

new_word += string.lowercas e[position]

print 'your new word is', new_word
............... ......

Hope that helps some.

On Mon, 28 Jul 2003 00:15:35 -0400, tjlan wrote:
----------------------------------------------------------------------------
from time import sleep
#Alphabet list used to move letters forward for simple encryption.
alphabet =
["a","b","c","d" ,"e","f","g","h ","i","j","k"," l","m","n","o", "p","q....

word_list = []
number_list = []
number_list2 = []
new_word = []
#variable for how far you want to switch v = 2
word = raw_input("Word : ")
a = len(word)
for x in range(0, len(word)):
print word[x],
word_list.appen d(word[x])
b = alphabet.index( word[x])
number_list.app end(b)

for x in range(0, len(number_list )):
c = number_list[x]
c = c + v
number_list2.ap pend(c)

for x in range(0, len(number_list 2)):
d = number_list2[x]
new_word.append (d)

for x in range(0,
#Stopped here because dont know of way to switch back.


Jul 18 '05 #2
Keith Jones wrote:
If you must ahve a list, you can do

[a for a in string.lowercas e]

to get a list of characters from a to z.
Or simply "list(string.lo wercase)".
// Klaus

--<> unselfish actions pay back better

Jul 18 '05 #3
Keith Jones
import string
string.lowercas e

that gives you a-z, lowercase..


Actually, use 'string.ascii_l owercase' because 'string.lowerca se' depends
on your locale.

On the other hand, for this application, string.lower might be the right
thing.

Also, the tjland? You need to change the

c = c + v
into
c = (c + v) % len(alphabet)

Suppose c is 'z' and v is 2. Then 25 (the position of the 'z') + 2 is 27,
which
is beyond the list of letters. You need some way to loop around to 0 once
you go over the end, and the '%' is the loop-around operator. (It's
actually
called the mod function.) It also works the other way, so "-1 % 26" loops
around to 25.

You might find this helpful
s = "testing"
v = 2
letters = string.ascii_lo wercase
t = ""
for c in s: .... t = t + letters[(letters.index( c)+v)%len(lette rs)]
.... t 'vguvkpi' s = t
v = -2
t = ""
for c in s: .... t = t + letters[(letters.index( c)+v)%len(lette rs)]
.... t 'testing'


With a bit more experience, I think you'll find this also interesting

v = 2

# Start by mapping each letter to itself
# (There are 256 possible values in an 8-bit character.)
encoding_d = {}
for i in range(256):
c = chr(i)
encoding_d[c] = c

lc = string.ascii_lo wercase
for i in range(len(lc)):
from_char = lc[i]
to_char = lc[(i+v) % len(lc)]
encoding_d[from_char] = to_char

uc = string.ascii_up percase
for i in range(len(uc)):
from_char = uc[i]
to_char = uc[(i+v) % len(uc)]
encoding_d[from_char] = to_char

s = "This is a test."

# This is better written as:
# t = "".join([encoding_d[c] for c in s])
# but that's something to try out after you learn a
# bit more Python.

t = ""
for c in s:
t = t + encoding_d[c]

print t

# Make a decoding dictionary which is the opposite of the
# encoding dictionary
decoding_d = {}
for from_char, to_char in encoding_d.item s():
decoding_d[to_char] = from_char

# or as: u = "".join([decoding_d[c] for c in t])
u = ""
for c in t:
u = u + decoding_d[c]

print u

With some more experience beyond that, you might write it like this
(It uses a very different style and implementation)

import string

def _r(s, n):
# rotate the characters left n positions
n %= len(s) # make sure it's properly within range
return s[n:] + s[:n]

class RotEncoder:
def __init__(self, n):
from_letters = string.ascii_lo wercase + string.ascii_up percase
to_letters = _r(string.ascii _lowercase, n) + _r(string.ascii _uppercase,
n)
self.encode_tab le = string.maketran s(from_letters, to_letters)
self.decode_tab le = string.maketran s(to_letters, from_letters)
def encode(self, s):
return string.translat e(s, self.encode_tab le)
def decode(self, s):
return string.translat e(s, self.decode_tab le)

code = RotEncoder(2)
print code.encode("te sting")
print code.decode(cod e.encode("testi ng"))

Andrew
da***@dalkescie ntific.com
Jul 18 '05 #4
At 06:11 AM 7/28/2003 +0000, Keith Jones wrote:
okay, isn't the number in the list the index of the new letter? So you'd
just use alphabet[d].. though what you're doing can be done in a much
simpler manner..

for starters... check out the string module. you can do

import string
string.lowerca se

that gives you a-z, lowercase.. I think you'll be fine with a string,
rather than a list (infact, it's better since it's immutable). If you must
ahve a list, you can do

[a for a in string.lowercas e]


Or just list(string.low ercase])
[snip]

Bob Gailer
bg*****@alum.rp i.edu
303 442 2625
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003

Jul 18 '05 #5
Or just list(string.low ercase])
[snip]


Haha.. I KNEW there was a better way to do it! It was late, I was tired, I
had list comprehensions on my mind, <insert more inane excuses here>. :)
Keith
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
8342
by: Pjotr Wedersteers | last post by:
Hi PHP buddies, I want to include a reverse DNS lookup (find host/domain for a given IP) in my pagetracker scripts. Is there anything prefab in the PHP world I am overlooking I could put to use ? I know some sites that offer en Reverse Lookup function but I want a non-interactive method. My server normally runs on Linux but right now I have it on XP, as my linux server has some problems I need to address first. So I can't rely on an...
59
4300
by: Raymond Hettinger | last post by:
Please comment on the new PEP for reverse iteration methods. Basically, the idea looks like this: for i in xrange(10).iter_backwards(): # 9,8,7,6,5,4,3,2,1,0 <do something with i> The HTML version is much more readable than the ReST version. See: http://www.python.org/peps/pep-0322.html
13
3572
by: Brad Tilley | last post by:
A friend of mine wrote an algorithm that generates strings. He says that it's impossible to figure out exactly how the algorithm works. That may be true, but I think if I had enough sample strings that I could write a program to identify patterns in the strings and then produce strings with similar patterns. He disagrees with me. He gave me 100 strings to analyze. I wrote a script to read each string and build a list of characters...
12
3161
by: rudysanford | last post by:
I just started messing with programming and started with Python. Part of my first project deals with translating numerical values to letters. I would like to be able to do the reverse as well, letters to numbers, sort of a table for lookup and a table for reverse lookup. I thought that a dictionary would be the structure to use- write it once and in a second instance swap the keys for values and values for keys. However, reversing a...
8
7046
by: rh0dium | last post by:
Hi all, I have a dict which looks like this.. dict={'130nm': {'umc': }, '180nm': {'chartered': , 'tsmc': }, '250nm': {'umc': , 'tsmc': } }
10
6179
by: zahy[dot]bnaya[At]gmail[dot]com | last post by:
Hi, I am trying to come up with a c style string reverser, I want it to take 1 argument Altough I would never do this in real life. Is there a way to do it? I wrote this function that fails : Any idea why it fails? char * C_recReverse(char * str)
41
3362
by: rick | last post by:
Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x Ruby: x = 'a_string' # Reverse the string
5
12657
by: Andrus | last post by:
I'm creating a database Winforms application using VCS Express 2005 I have some large lookup tables (may be up to 500000 records) which contains name and id and are stored in sql server. I need to create single line combobox style control which: 1. Allows to type first characters in name 2. Auto-completes entered data by using first match 3. Allows to open picklist based by entered data and select name
8
5022
by: schaf | last post by:
Hi NG! I have a problem in my remote application. After calling a remote function the calculation will be done by the service. The calculation result will be sent to the caller (client) via remote event. The following behavior can be observed: 1.) Right after the start of the server the first response via remote event will take a long time.
0
8421
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8844
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8742
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1734
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.