elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [Código-Python]Obtener dígito verificador del RUT en Chile - JaAViEr
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Código-Python]Obtener dígito verificador del RUT en Chile - JaAViEr  (Leído 15,907 veces)
0x5d

Desconectado Desconectado

Mensajes: 241



Ver Perfil WWW
[Código-Python]Obtener dígito verificador del RUT en Chile - JaAViEr
« en: 9 Febrero 2012, 21:03 pm »

Hola, buen día !

Tras unas merecidas vacaciones vengo de vuelta con cosas para programar, con la cabeza ya más despejada :P.

Visitando el blog del colega <a href="http://twitter.com/isseu">@isseu</a>, me encuentro con un artículo llamado "Como sacar dígito verificador de rol único tributario (RUT)". Me pareció interesante y me puse a leer atentamente su explicación y me animé a pasarlo a Python, en su blog está en javascript, pero yo como buen amante de Python lo hice en él :)

Código
  1. # -*- coding: utf-8 -*-
  2. rut = []
  3. ingresar = [rut.append(numeros) for numeros in raw_input('RUT ::>')]
  4. rut.reverse()
  5. recorrido = 2
  6. multiplicar = 0
  7. for x in rut:
  8. multiplicar+=int(x)*recorrido
  9. if recorrido==7: recorrido = 1
  10. recorrido+=1
  11. modulo = multiplicar%11
  12. resultado = 11-modulo
  13. if resultado == 11: digito=0
  14. elif resultado == 10: digito="K"
  15. else: digito=resultado
  16. print "Dígito verificador:",digito

Espero sea de su agrado ! :D

Fuente : http://rootcodes.com/pythonobtener-digito-verificador-del-rut-en-chile/

Saludos, Javier.


En línea

Karcrack


Desconectado Desconectado

Mensajes: 2.416


Se siente observado ¬¬'


Ver Perfil
Re: [Código-Python]Obtener dígito verificador del RUT en Chile - JaAViEr
« Respuesta #1 en: 10 Febrero 2012, 03:27 am »

Tenía un rato libre, así que he reformulado el algoritmo usando la información que hay en Wikipedia. Espero no te moleste :P
Código
  1. rut = reversed(map(int,raw_input('RUT ::>')))
  2. m = [2,3,4,5,6,7]
  3.  
  4. d = sum([n*m[i%6] for i,n in enumerate(rut)])
  5. d %= 11
  6.  
  7. if (d==1):
  8.    d = 'K'
  9. else:
  10.    d = 11-d
  11.  
  12. print d

Y la versión reducida: (Me encanta reducir código Python :P)
Código
  1. d=sum([int(n)*(i%6+2)for i,n in enumerate(raw_input()[::-1])])%11
  2. print'K'if(d==1)else 11-d


« Última modificación: 10 Febrero 2012, 03:35 am por Karcrack » En línea

0x5d

Desconectado Desconectado

Mensajes: 241



Ver Perfil WWW
Re: [Código-Python]Obtener dígito verificador del RUT en Chile - JaAViEr
« Respuesta #2 en: 10 Febrero 2012, 07:26 am »

Tenía un rato libre, así que he reformulado el algoritmo usando la información que hay en Wikipedia. Espero no te moleste :P
Código
  1. rut = reversed(map(int,raw_input('RUT ::>')))
  2. m = [2,3,4,5,6,7]
  3.  
  4. d = sum([n*m[i%6] for i,n in enumerate(rut)])
  5. d %= 11
  6.  
  7. if (d==1):
  8.    d = 'K'
  9. else:
  10.    d = 11-d
  11.  
  12. print d

Y la versión reducida: (Me encanta reducir código Python :P)
Código
  1. d=sum([int(n)*(i%6+2)for i,n in enumerate(raw_input()[::-1])])%11
  2. print'K'if(d==1)else 11-d
Para nada ! es genial saber que usas Python y tienes buen nivel ! :D
El primer código que has usado es también posible reducirlo :
Código
  1. # -*- coding: utf-8 -*-
  2. rut = reversed(map(int,raw_input('RUT ::>')))
  3. d = sum([n*range(2,8)[i%6] for i,n in enumerate(rut)])
  4. d %= 11
  5. if (d==1):
  6.    d = 'K'
  7. else:
  8.    d = 11-d
  9. print d
  10.  
Pero sin duda el segundo está genial ! :D

EDIT:
Ahora en QT4 para matar el tiempo :P
Código
  1. # -*- coding: utf-8 -*-
  2. from PyQt4 import QtCore, QtGui
  3. import sys
  4.  
  5. class ventana_alerta(QtGui.QWidget):
  6.  def __init__(self, parent=None):
  7.    QtGui.QWidget.__init__(self, parent)
  8.    self.resize(283, 31)
  9.    self.setWindowTitle("ALERTA!")
  10.  
  11.  def message(self, txt):
  12.    self.txt = txt
  13.    self.respuesta = QtGui.QLabel(self.txt, self)
  14.    self.respuesta.setGeometry(10, 10, 260, 17)
  15.  
  16. class formulario_rut(QtGui.QWidget):
  17.  
  18.  def __init__(self, parent=None):
  19.    QtGui.QWidget.__init__(self, parent)
  20.    self.setWindowTitle("Digito verificador")
  21.    self.resize(279, 36)
  22.    self.label_rut = QtGui.QLabel("RUT", self)
  23.    self.label_rut.setGeometry(0, 11, 59, 17)
  24.    self.rut = QtGui.QLineEdit(self)
  25.    self.rut.setGeometry(30, 7, 101, 23)
  26.    self.label_verificador = QtGui.QLabel("-", self)
  27.    self.label_verificador.setGeometry(135, 11, 16, 17)
  28.    self.digito = QtGui.QLineEdit(self)
  29.    self.digito.setGeometry(147, 7, 21, 23)
  30.    self.digito.setReadOnly(True)
  31.    self.verificar = QtGui.QPushButton("Verificar", self)
  32.    self.verificar.setGeometry(180, 7, 92, 23)
  33.    self.connect(self.verificar, QtCore.SIGNAL("clicked()"), self.operacion)
  34.  
  35.  def operacion(self):
  36.    self.rut_valor = str(self.rut.text())
  37.    if len(self.rut_valor) < 8 and len(self.rut_valor) > 9:
  38.      creacion_alerta.message("Ingresa un rut valido por favor")
  39.      creacion_alerta.show()
  40.    else:
  41.      rut = []
  42.      ingresar = [rut.append(numeros) for numeros in self.rut_valor]
  43.      rut.reverse()
  44.      recorrido = 2
  45.      multiplicar = 0
  46.      for x in rut:
  47.        multiplicar+=int(x)*recorrido
  48.        if recorrido==7: recorrido = 1
  49.        recorrido+=1
  50.      modulo = multiplicar%11
  51.      resultado = 11-modulo
  52.      if resultado == 11: digito=0
  53.      elif resultado == 10: digito="K"
  54.      else: digito=resultado
  55.      self.digito.setText(str(digito))
  56.  
  57. run = QtGui.QApplication(sys.argv)
  58. creacion_alerta = ventana_alerta()
  59. creacion_formulario = formulario_rut()
  60. creacion_formulario.show()
  61. run.exec_()
  62.  
« Última modificación: 10 Febrero 2012, 23:58 pm por 0x5d » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines