#! /usr/bin/env python # -*- coding: UTF-8 -*- """ PyMathIt, calcolatrice italiana in python creato da Frafra (www.frafra-eu.org francesco.it@gmail.com) col contributo di C8E This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. """ __module_name__ = "PyMathIt" __module_version__ = "0.9" __module_description__ = "Calcolatrice" from re import compile, match def put(txt, times=10): """Funzione per l'inserimento dei dati""" # Tenta per "times" volte a prendere un dato se non corrisponde ai canoni for x in range(times): a=raw_input(txt) # Inserisce il dato test1=compile("^\d+$").match(a) # Prima verifica test2=compile("^\d+/\d+$").match(a) # Seconda verifica if test1 or test2: return a else: print "Sintassi: num (oppure) num/num\nEs: 3/2 (oppure) 4" else: print "Sei troppo stupido per usare questo programma." return 0 def normalize(a, b): """Rende uniformi due numeri""" # Rende una frazione il numero if "/" not in a: a+="/1" if "/" not in b: b+="/1" a, b=a.split("/"), b.split("/") # Divide il numeratore dal denominatore a, b=[int(x) for x in a], [int(x) for x in b] # Converte in numeri interi return a, b def simply(n, d): """Semplifica due numeri""" # Cambia di segno se necessario if n==d=="-": n, d=n[1:], d[1:] # Semplifica la frazione x=2 while x<=abs(min(n, d)): while n%x==d%x==0: n/=x d/=x x+=1 # In caso di denominatore pari a 1 o di n=d viene restituito solo il numeratore if d==1 or n==d: return str(n) else: return str(n)+"/"+str(d) def add(a, b, t=1): """Somma due numeri""" a, b=normalize(a, b) # Normalizza i due numeri d=a[1]*b[1] # Calcola il denominatore # Calcola il numeratore if t: n=a[0]*b[1]+b[0]*a[1] else: n=a[0]*b[1]-b[0]*a[1] return simply(n, d) # Semplifica e ritorna def mol(a, b, t=1): """Moltiplica o divide due numeri""" a, b=normalize(a, b) # Normalizza i due numeri # Calcola il numeratore e il denominatore if t: n, d=a[0]*b[0], a[1]*b[1] else: n, d=a[0]*b[1], a[1]*b[0] return simply(n, d) # Semplifica e ritorna # Esempio di uso delle funzioni a=put("A: ") b=put("B: ") print "+ =>", add(a, b) print "- =>", add(a, b, t=0) print "x =>", mol(a, b) print ": =>", mol(a, b, t=0)