Originariamente inviato da maiosyet_2
Poniamo stringa = "abc"
a = 1
b = 2
c = 3
devo leggere la stringa ed assegnargli un valore numerico secondo lo schemino.
Primo metodo che ho usato:
codice:
value = 1
for char in String:
if char == "a":
value = 1
total = total * value
elif char == "b":
value2 = 2
total = total * value2
elif char == "c":
value3 = 3
total = total * value3
print value
Funzionare funziona, ma le stringhe "abc", "bca" e "acb" chiaramente finiscono ad avere lo stesso valore: per ovviare a questo pensavo di aggiungere al
codice:
total = total * value<x> + y
un + y dove y è la posizione del carattere nella stringa: ad esempio in "cba", "a" = 1(di value) + 3 (posizione).
Un'idea su come fare?
La prima cosa (brutta) che mi e` venuta in mente:
codice:
$ python
Python 2.3.5 (#2, Mar 27 2005, 09:43:31)
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> String = 'abc'
>>> total = 0
>>> values = dict((('a', 1), ('b',2), ('c',3)))
>>> values
{'a': 1, 'c': 3, 'b': 2}
>>> for i in range(len(String)):
... total += (i + values[String[i]])
...
>>> total
9
Vedi se puoi trovarci qualche spunto utile