Python - Incremential chain of numbers not working fine -
i have program takes 3 numbers command line arguments. should display list of numbers differ same amount first two, length of list being third number.
my current code not work when difference between first 2 inputs negative or zero.
here 3 test cases:
this works (but sum wrong):
python suite.py 1 2 10 > 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 56
sum should
55
.this fails:
python suite.py 30 27 8 > 0
the output should
> 30 27 24 21 18 15 12 9 = 156
this fails:
python suite.py 6 6 6 > 6
the output should be
> 6 + 6 + 6 + 6 + 6 + 6 = 36
here's code:
import sys def suite(premier, second, nombre): message = "" message2 = "" if second < premier: diff = (premier - second) * -1 else: diff = second - premier maximum = premier + (diff * nombre) = premier total = premier in range(premier, maximum, diff): message += str(i) + " + " message2 = message[:-3] total += message2 += " = " + str(i) return message2 def main(): premier = int(sys.argv[1]) second = int(sys.argv[2]) nombre = int(sys.argv[3]) if premier == second: resultat = premier else: resultat = suite(premier, second, nombre) print(resultat) if __name__ == "__main__": main()
here's more pythonic alternative :
import sys def suite(premier, second, nombre): diff = second - premier if diff == 0: nombres = [premier] * nombre else: maximum = premier + diff * nombre nombres = range(premier, maximum, diff) gauche = ' + '.join(map(str, nombres)) droite = sum(nombres) return '%s = %d' % (gauche, droite) def main(): premier = int(sys.argv[1]) second = int(sys.argv[2]) nombre = int(sys.argv[3]) print(suite(premier, second, nombre)) if __name__ == "__main__": main()
for 1 2 10
, outputs:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
for 30 27 8
:
30 + 27 + 24 + 21 + 18 + 15 + 12 + 9 = 156
for 6 6 6
:
6 + 6 + 6 + 6 + 6 + 6 = 36
Comments
Post a Comment