├── CH11 ├── EX11.35.py ├── FindNearestPoints.txt ├── o.gif ├── x.gif ├── Checkpoints ├── EX11.18.py ├── test.py ├── EX11.51.py ├── EX11.29.py ├── EX11.1.py ├── EX11.2.py ├── EX11.27.py ├── EX11.28.py ├── EX11.25.py ├── EX11.4.py ├── EX11.15.py ├── EX11.26.py ├── EX11.49.py └── EX11.44.py ├── CH14 ├── key_words ├── EX14.08.py ├── EX14.11.py └── EX14.02.py ├── CH13 ├── Words ├── scores ├── graph.txt ├── address.dat ├── numbers.txt ├── EX13.6.py ├── EX13.8.py ├── EX13.1.py ├── EX13.2.py ├── EX13.5.py ├── EX13.9.py ├── EX13.3.py └── EX13.4.py ├── .gitattributes ├── CH09 ├── o.gif ├── x.gif ├── car.gif ├── EX9.4.py ├── EX9.7.py ├── EX9.8.py ├── EX9.15.py ├── EX9.11.py ├── EX9.5.py ├── EX9.33.py └── EX9.6.py ├── CH12 ├── 1.GIF ├── 2.gif ├── 3.gif ├── 4.gif ├── 5.gif ├── o.gif ├── x.gif ├── cell.GIF ├── red.GIF ├── card │ ├── 1.gif │ ├── 2.gif │ ├── 3.gif │ ├── 4.gif │ ├── 5.gif │ ├── 6.gif │ ├── 7.gif │ ├── 8.gif │ ├── 9.gif │ ├── 10.gif │ ├── 11.gif │ ├── 12.gif │ ├── 13.gif │ ├── 14.gif │ ├── 15.gif │ ├── 16.gif │ ├── 17.gif │ ├── 18.gif │ ├── 19.gif │ ├── 20.gif │ ├── 21.gif │ ├── 22.gif │ ├── 23.gif │ ├── 24.gif │ ├── 25.gif │ ├── 26.gif │ ├── 27.gif │ ├── 28.gif │ ├── 29.gif │ ├── 30.gif │ ├── 31.gif │ ├── 32.gif │ ├── 33.gif │ ├── 34.gif │ ├── 35.gif │ ├── 36.gif │ ├── 37.gif │ ├── 38.gif │ ├── 39.gif │ ├── 40.gif │ ├── 41.gif │ ├── 42.gif │ ├── 43.gif │ ├── 44.gif │ ├── 45.gif │ ├── 46.gif │ ├── 47.gif │ ├── 48.gif │ ├── 49.gif │ ├── 50.gif │ ├── 51.gif │ ├── 52.gif │ ├── 53.gif │ ├── 54.gif │ ├── b1fv.gif │ └── b2fv.gif ├── empty.gif └── yellow.GIF ├── CH10 ├── card │ ├── 1.gif │ ├── 2.gif │ ├── 3.gif │ ├── 4.gif │ ├── 5.gif │ ├── 6.gif │ ├── 7.gif │ ├── 8.gif │ ├── 9.gif │ ├── 10.gif │ ├── 11.gif │ ├── 12.gif │ ├── 13.gif │ ├── 14.gif │ ├── 15.gif │ ├── 16.gif │ ├── 17.gif │ ├── 18.gif │ ├── 19.gif │ ├── 20.gif │ ├── 21.gif │ ├── 22.gif │ ├── 23.gif │ ├── 24.gif │ ├── 25.gif │ ├── 26.gif │ ├── 27.gif │ ├── 28.gif │ ├── 29.gif │ ├── 30.gif │ ├── 31.gif │ ├── 32.gif │ ├── 33.gif │ ├── 34.gif │ ├── 35.gif │ ├── 36.gif │ ├── 37.gif │ ├── 38.gif │ ├── 39.gif │ ├── 40.gif │ ├── 41.gif │ ├── 42.gif │ ├── 43.gif │ ├── 44.gif │ ├── 45.gif │ ├── 46.gif │ ├── 47.gif │ ├── 48.gif │ ├── 49.gif │ ├── 50.gif │ ├── 51.gif │ ├── 52.gif │ ├── 53.gif │ ├── 54.gif │ ├── b1fv.gif │ └── b2fv.gif ├── EX10.2.py ├── EX10.24.py ├── EX10.30.py ├── EX10.3.py ├── EX10.7.py ├── EX10.32.py ├── EX10.4.py ├── EX10.5.py ├── Ex10.10.py ├── EX10.15.py ├── EX10.12.py ├── Ex10.11.py ├── EX10.25.py ├── EX10.27.py ├── EX10.8.py ├── EX10.13.py ├── EX10.16.py ├── EX10.1.py └── EX10.26.py ├── CH15 ├── queen.gif ├── EX15.04.py ├── EX15.05.py ├── EX15.06.py ├── EX15.01.py ├── EX15.03.py ├── EX15.11.py ├── EX15.09.py ├── EX15.08.py ├── EX15.19.py ├── EX15.14.py ├── EX15.07.py ├── EX15.24.py ├── EX15.21.py ├── EX15.12.py ├── EX15.20.py ├── EX15.13.py ├── EX15.10.py ├── EX15.02.py ├── EX15.15.py ├── EX15.16.py └── EX15.22.py ├── CH07 ├── __pycache__ │ ├── Stock.cpython-37.pyc │ ├── Time.cpython-37.pyc │ ├── Account.cpython-37.pyc │ ├── Rectangle.cpython-37.pyc │ ├── StopWatch.cpython-37.pyc │ ├── LinearEquation.cpython-37.pyc │ └── RegularPolygon.cpython-37.pyc ├── Rectangle.py ├── StopWatch.py ├── Time.py ├── Fan.py ├── Stock.py ├── QuadraticEquation.py ├── EX7.8.py ├── EX7.9.py └── RegularPolygon.py ├── CH04 ├── EX4.16.py ├── EX4.4.py ├── EX4.12.py ├── EX4.26.py ├── EX4.10.py ├── EX4.19.py ├── EX4.2.py ├── EX4.3.py ├── EX4.14.py ├── EX4.33.py ├── EX4.30.py ├── EX4.34.py ├── EX4.27.py ├── EX4.9.py ├── EX4.24.py ├── EX4.28.py ├── EX4.6.py ├── EX4.20.py ├── EX4.31.py ├── EX4.32.py ├── EX4.22.py ├── EX4.29.py ├── EX4.8.py ├── EX4.18.py └── EX4.23.py ├── CH06 Module └── __pycache__ │ └── MyFunctions.cpython-37.pyc ├── CH03 ├── EX3.7.py ├── EX3.10.py ├── EX3.6.py ├── EX3.4.py ├── EX3.11.py ├── EX3.19.py ├── EX3.13.py ├── EX3.12.py ├── EX3.1.py ├── EX3.5.py ├── EX3.8.py ├── EX3.15.py └── EX3.14.py ├── CH05 ├── EX5.37.py ├── EX5.15.py ├── EX5.14.py ├── EX5.48.py ├── EX5.44.py ├── EX5.43.py ├── EX5.27.py ├── EX5.8.py ├── EX5.17.py ├── EX5.3.py ├── EX5.4.py ├── EX5.26.py ├── EX5.21.py ├── EX5.12.py ├── EX5.29.py ├── EX5.40.py ├── EX5.13.py ├── EX5.19.py ├── EX5.45.py ├── EX5.9.py ├── EX5.35.py ├── EX5.50.py ├── EX5.18.py ├── EX5.38.py ├── EX5.51.py ├── EX5.7.py ├── EX5.16.py ├── EX5.28.py ├── EX5.10.py ├── EX5.6.py ├── EX5.42.py ├── EX5.39.py ├── EX5.20.py ├── EX5.47.py ├── EX5.11.py ├── EX5.5.py ├── EX5.23.py ├── EX5.2.py ├── EX5.25.py ├── EX5.55.py ├── EX5.46.py └── EX5.1.py ├── README.md ├── CH02 ├── EX2.3.py ├── EX2.13.py ├── EX2.15.py ├── EX2.22.py ├── EX2.1.py ├── EX2.4.py ├── EX2.12.py ├── EX2.2.py ├── EX2.7.py ├── EX2.16.py ├── EX2.5.py ├── EX2.26.py ├── EX2.10.py ├── EX2.20.py ├── EX2.6.py ├── EX2.25.py ├── EX2.17.py ├── EX2.14.py ├── EX2.18.py ├── EX2.19.py ├── EX2.23.py ├── EX2.8.py └── EX2.11.py ├── CH06 ├── EX6.33.py ├── EX6.16.py ├── EX6.10.py ├── EX6.34.py ├── EX6.20.py ├── EX6.27.py ├── EX6.13.py ├── EX6.26.py ├── EX6.4.py ├── EX6.12.py ├── EX6.14.py ├── EX6.18.py ├── EX6.38.py ├── EX6.24.py ├── EX6.25.py ├── EX6.11.py ├── EX6.39.py ├── EX6.6.py ├── EX6.1.py ├── EX6.17.py ├── EX6.35.py ├── EX6.5.py ├── EX6.2.py ├── EX6.36.py ├── EX6.23.py ├── EX6.30.py ├── EX6.46.py ├── EX6.15.py ├── EX6.9.py ├── EX6.3.py ├── EX6.45.py └── EX6.21.py └── CH08 ├── EX8.11.py ├── EX8.1.py ├── EX8.6.py ├── EX8.10.py ├── EX8.8.py ├── EX8.13.py ├── EX8.16.py ├── EX8.4.py ├── EX8.2.py ├── EX8.3.py └── EX8.5.py /CH11/EX11.35.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CH14/key_words: -------------------------------------------------------------------------------- 1 | True False and or not hello welcome -------------------------------------------------------------------------------- /CH13/Words: -------------------------------------------------------------------------------- 1 | write that program hello play animal elephant computer java python -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /CH11/FindNearestPoints.txt: -------------------------------------------------------------------------------- 1 | 8 2 | -1, 3 3 | -1, -1 4 | 1, 1 5 | 2, 0.5 6 | 2, -1 7 | 3, 3 8 | 4, 2 9 | 4, -0.5 -------------------------------------------------------------------------------- /CH13/scores: -------------------------------------------------------------------------------- 1 | 50 60 80 100 20 10 90 90 90 80 50 55 37 19 73 29 92 55 2 | 77 37.5 55.4 22.3 77.6 100 100 3 | -------------------------------------------------------------------------------- /CH13/graph.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 0 30 30 1 2 3 | 1 90 30 0 3 4 | 2 30 90 0 3 4 5 | 3 90 90 1 2 4 5 6 | 4 30 150 2 3 5 7 | 5 90 150 3 4 -------------------------------------------------------------------------------- /CH09/o.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH09/o.gif -------------------------------------------------------------------------------- /CH09/x.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH09/x.gif -------------------------------------------------------------------------------- /CH11/o.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH11/o.gif -------------------------------------------------------------------------------- /CH11/x.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH11/x.gif -------------------------------------------------------------------------------- /CH12/1.GIF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/1.GIF -------------------------------------------------------------------------------- /CH12/2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/2.gif -------------------------------------------------------------------------------- /CH12/3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/3.gif -------------------------------------------------------------------------------- /CH12/4.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/4.gif -------------------------------------------------------------------------------- /CH12/5.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/5.gif -------------------------------------------------------------------------------- /CH12/o.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/o.gif -------------------------------------------------------------------------------- /CH12/x.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/x.gif -------------------------------------------------------------------------------- /CH09/car.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH09/car.gif -------------------------------------------------------------------------------- /CH12/cell.GIF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/cell.GIF -------------------------------------------------------------------------------- /CH12/red.GIF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/red.GIF -------------------------------------------------------------------------------- /CH10/card/1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/1.gif -------------------------------------------------------------------------------- /CH10/card/2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/2.gif -------------------------------------------------------------------------------- /CH10/card/3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/3.gif -------------------------------------------------------------------------------- /CH10/card/4.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/4.gif -------------------------------------------------------------------------------- /CH10/card/5.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/5.gif -------------------------------------------------------------------------------- /CH10/card/6.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/6.gif -------------------------------------------------------------------------------- /CH10/card/7.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/7.gif -------------------------------------------------------------------------------- /CH10/card/8.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/8.gif -------------------------------------------------------------------------------- /CH10/card/9.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/9.gif -------------------------------------------------------------------------------- /CH12/card/1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/1.gif -------------------------------------------------------------------------------- /CH12/card/2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/2.gif -------------------------------------------------------------------------------- /CH12/card/3.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/3.gif -------------------------------------------------------------------------------- /CH12/card/4.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/4.gif -------------------------------------------------------------------------------- /CH12/card/5.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/5.gif -------------------------------------------------------------------------------- /CH12/card/6.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/6.gif -------------------------------------------------------------------------------- /CH12/card/7.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/7.gif -------------------------------------------------------------------------------- /CH12/card/8.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/8.gif -------------------------------------------------------------------------------- /CH12/card/9.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/9.gif -------------------------------------------------------------------------------- /CH12/empty.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/empty.gif -------------------------------------------------------------------------------- /CH12/yellow.GIF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/yellow.GIF -------------------------------------------------------------------------------- /CH15/queen.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH15/queen.gif -------------------------------------------------------------------------------- /CH10/card/10.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/10.gif -------------------------------------------------------------------------------- /CH10/card/11.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/11.gif -------------------------------------------------------------------------------- /CH10/card/12.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/12.gif -------------------------------------------------------------------------------- /CH10/card/13.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/13.gif -------------------------------------------------------------------------------- /CH10/card/14.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/14.gif -------------------------------------------------------------------------------- /CH10/card/15.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/15.gif -------------------------------------------------------------------------------- /CH10/card/16.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/16.gif -------------------------------------------------------------------------------- /CH10/card/17.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/17.gif -------------------------------------------------------------------------------- /CH10/card/18.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/18.gif -------------------------------------------------------------------------------- /CH10/card/19.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/19.gif -------------------------------------------------------------------------------- /CH10/card/20.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/20.gif -------------------------------------------------------------------------------- /CH10/card/21.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/21.gif -------------------------------------------------------------------------------- /CH10/card/22.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/22.gif -------------------------------------------------------------------------------- /CH10/card/23.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/23.gif -------------------------------------------------------------------------------- /CH10/card/24.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/24.gif -------------------------------------------------------------------------------- /CH10/card/25.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/25.gif -------------------------------------------------------------------------------- /CH10/card/26.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/26.gif -------------------------------------------------------------------------------- /CH10/card/27.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/27.gif -------------------------------------------------------------------------------- /CH10/card/28.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/28.gif -------------------------------------------------------------------------------- /CH10/card/29.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/29.gif -------------------------------------------------------------------------------- /CH10/card/30.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/30.gif -------------------------------------------------------------------------------- /CH10/card/31.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/31.gif -------------------------------------------------------------------------------- /CH10/card/32.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/32.gif -------------------------------------------------------------------------------- /CH10/card/33.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/33.gif -------------------------------------------------------------------------------- /CH10/card/34.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/34.gif -------------------------------------------------------------------------------- /CH10/card/35.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/35.gif -------------------------------------------------------------------------------- /CH10/card/36.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/36.gif -------------------------------------------------------------------------------- /CH10/card/37.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/37.gif -------------------------------------------------------------------------------- /CH10/card/38.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/38.gif -------------------------------------------------------------------------------- /CH10/card/39.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/39.gif -------------------------------------------------------------------------------- /CH10/card/40.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/40.gif -------------------------------------------------------------------------------- /CH10/card/41.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/41.gif -------------------------------------------------------------------------------- /CH10/card/42.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/42.gif -------------------------------------------------------------------------------- /CH10/card/43.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/43.gif -------------------------------------------------------------------------------- /CH10/card/44.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/44.gif -------------------------------------------------------------------------------- /CH10/card/45.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/45.gif -------------------------------------------------------------------------------- /CH10/card/46.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/46.gif -------------------------------------------------------------------------------- /CH10/card/47.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/47.gif -------------------------------------------------------------------------------- /CH10/card/48.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/48.gif -------------------------------------------------------------------------------- /CH10/card/49.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/49.gif -------------------------------------------------------------------------------- /CH10/card/50.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/50.gif -------------------------------------------------------------------------------- /CH10/card/51.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/51.gif -------------------------------------------------------------------------------- /CH10/card/52.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/52.gif -------------------------------------------------------------------------------- /CH10/card/53.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/53.gif -------------------------------------------------------------------------------- /CH10/card/54.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/54.gif -------------------------------------------------------------------------------- /CH10/card/b1fv.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/b1fv.gif -------------------------------------------------------------------------------- /CH10/card/b2fv.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH10/card/b2fv.gif -------------------------------------------------------------------------------- /CH12/card/10.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/10.gif -------------------------------------------------------------------------------- /CH12/card/11.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/11.gif -------------------------------------------------------------------------------- /CH12/card/12.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/12.gif -------------------------------------------------------------------------------- /CH12/card/13.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/13.gif -------------------------------------------------------------------------------- /CH12/card/14.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/14.gif -------------------------------------------------------------------------------- /CH12/card/15.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/15.gif -------------------------------------------------------------------------------- /CH12/card/16.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/16.gif -------------------------------------------------------------------------------- /CH12/card/17.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/17.gif -------------------------------------------------------------------------------- /CH12/card/18.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/18.gif -------------------------------------------------------------------------------- /CH12/card/19.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/19.gif -------------------------------------------------------------------------------- /CH12/card/20.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/20.gif -------------------------------------------------------------------------------- /CH12/card/21.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/21.gif -------------------------------------------------------------------------------- /CH12/card/22.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/22.gif -------------------------------------------------------------------------------- /CH12/card/23.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/23.gif -------------------------------------------------------------------------------- /CH12/card/24.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/24.gif -------------------------------------------------------------------------------- /CH12/card/25.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/25.gif -------------------------------------------------------------------------------- /CH12/card/26.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/26.gif -------------------------------------------------------------------------------- /CH12/card/27.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/27.gif -------------------------------------------------------------------------------- /CH12/card/28.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/28.gif -------------------------------------------------------------------------------- /CH12/card/29.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/29.gif -------------------------------------------------------------------------------- /CH12/card/30.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/30.gif -------------------------------------------------------------------------------- /CH12/card/31.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/31.gif -------------------------------------------------------------------------------- /CH12/card/32.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/32.gif -------------------------------------------------------------------------------- /CH12/card/33.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/33.gif -------------------------------------------------------------------------------- /CH12/card/34.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/34.gif -------------------------------------------------------------------------------- /CH12/card/35.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/35.gif -------------------------------------------------------------------------------- /CH12/card/36.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/36.gif -------------------------------------------------------------------------------- /CH12/card/37.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/37.gif -------------------------------------------------------------------------------- /CH12/card/38.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/38.gif -------------------------------------------------------------------------------- /CH12/card/39.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/39.gif -------------------------------------------------------------------------------- /CH12/card/40.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/40.gif -------------------------------------------------------------------------------- /CH12/card/41.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/41.gif -------------------------------------------------------------------------------- /CH12/card/42.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/42.gif -------------------------------------------------------------------------------- /CH12/card/43.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/43.gif -------------------------------------------------------------------------------- /CH12/card/44.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/44.gif -------------------------------------------------------------------------------- /CH12/card/45.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/45.gif -------------------------------------------------------------------------------- /CH12/card/46.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/46.gif -------------------------------------------------------------------------------- /CH12/card/47.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/47.gif -------------------------------------------------------------------------------- /CH12/card/48.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/48.gif -------------------------------------------------------------------------------- /CH12/card/49.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/49.gif -------------------------------------------------------------------------------- /CH12/card/50.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/50.gif -------------------------------------------------------------------------------- /CH12/card/51.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/51.gif -------------------------------------------------------------------------------- /CH12/card/52.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/52.gif -------------------------------------------------------------------------------- /CH12/card/53.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/53.gif -------------------------------------------------------------------------------- /CH12/card/54.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/54.gif -------------------------------------------------------------------------------- /CH12/card/b1fv.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/b1fv.gif -------------------------------------------------------------------------------- /CH12/card/b2fv.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH12/card/b2fv.gif -------------------------------------------------------------------------------- /CH13/address.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH13/address.dat -------------------------------------------------------------------------------- /CH07/__pycache__/Stock.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH07/__pycache__/Stock.cpython-37.pyc -------------------------------------------------------------------------------- /CH07/__pycache__/Time.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH07/__pycache__/Time.cpython-37.pyc -------------------------------------------------------------------------------- /CH04/EX4.16.py: -------------------------------------------------------------------------------- 1 | # 4.16 (Random character) Write a program that displays a random uppercase letter. 2 | import random 3 | 4 | n = random.randint(ord('A'), ord('Z')) 5 | print(chr(n)) 6 | -------------------------------------------------------------------------------- /CH07/__pycache__/Account.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH07/__pycache__/Account.cpython-37.pyc -------------------------------------------------------------------------------- /CH07/__pycache__/Rectangle.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH07/__pycache__/Rectangle.cpython-37.pyc -------------------------------------------------------------------------------- /CH07/__pycache__/StopWatch.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH07/__pycache__/StopWatch.cpython-37.pyc -------------------------------------------------------------------------------- /CH07/__pycache__/LinearEquation.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH07/__pycache__/LinearEquation.cpython-37.pyc -------------------------------------------------------------------------------- /CH07/__pycache__/RegularPolygon.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH07/__pycache__/RegularPolygon.cpython-37.pyc -------------------------------------------------------------------------------- /CH06 Module/__pycache__/MyFunctions.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ahtisham-1214/Introduction-to-Programming-Using-Python-Liang-1st-edtion/HEAD/CH06 Module/__pycache__/MyFunctions.cpython-37.pyc -------------------------------------------------------------------------------- /CH03/EX3.7.py: -------------------------------------------------------------------------------- 1 | # (Random character) Write a program that displays a random uppercase letter 2 | # using the time.time() function. 3 | import random 4 | import time 5 | 6 | t = int(time.time()) 7 | c = chr(ord('A') + t % (ord('Z') - ord('A') + 1)) 8 | print(c) 9 | -------------------------------------------------------------------------------- /CH05/EX5.37.py: -------------------------------------------------------------------------------- 1 | # 5.37 (Summation) Write a program that computes the following summation: 2 | import math 3 | 4 | sum = 0 5 | 6 | for i in range(1, 625): 7 | sum += 1 / (i + math.sqrt((i + 1))) 8 | 9 | print("The summation of the series is", sum) 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction-to-Programming-Using-Python-Liang-1st-edtion 2 | solutions to programming exercises of introduction to programming using python book 3 | 4 | here --> https://github.com/OmarAlmighty/Introduction-to-Programming-Using-Python-Liang-1st-edtion 5 | -------------------------------------------------------------------------------- /CH10/EX10.2.py: -------------------------------------------------------------------------------- 1 | # 10.2 (Reverse the numbers entered) Write a program that reads a list of integers and 2 | # displays them in the reverse order in which they were read. 3 | 4 | n = input("Enter numbers: ") 5 | lst = [int(s) for s in n.split()] 6 | lst.reverse() 7 | print(lst) -------------------------------------------------------------------------------- /CH02/EX2.3.py: -------------------------------------------------------------------------------- 1 | # (Convert feet into meters) Write a program that reads a number in feet, converts it 2 | # to meters, and displays the result. One foot is 0.305 meters. 3 | 4 | feet = eval(input("Enter a value for feet:")) 5 | metre = feet * 0.305 6 | print(feet, "feet is", metre, "metres") 7 | -------------------------------------------------------------------------------- /CH03/EX3.10.py: -------------------------------------------------------------------------------- 1 | # (Turtle: display Unicodes) Write a program to display Greek letters 2 | # The Unicode of these characters are \u03b1 \u03b2 \u03b3 \u03b4 \u03b5 3 | # \u03b6 \u03b7 \u03b8. 4 | import turtle 5 | 6 | turtle.write("\u03b1 \u03b2 \u03b3 \u03b4 \u03b5 \u03b6 \u03b7 \u03b8.") 7 | turtle.done() -------------------------------------------------------------------------------- /CH13/numbers.txt: -------------------------------------------------------------------------------- 1 | 50 59 20 80 75 16 5 66 36 40 87 69 80 45 26 70 93 35 9 92 9 0 43 90 20 49 26 31 24 40 57 36 75 39 80 95 86 10 41 3 63 61 15 92 99 42 97 70 65 14 3 25 59 13 32 31 85 45 0 74 40 87 73 44 35 91 48 10 94 34 22 5 59 99 43 62 47 84 62 31 63 61 79 47 32 52 78 22 79 40 18 98 7 43 67 90 5 14 41 52 -------------------------------------------------------------------------------- /CH07/Rectangle.py: -------------------------------------------------------------------------------- 1 | class Rectangle: 2 | def __init__(self,width = 1,height = 2): 3 | self.width = width 4 | self.height = height 5 | 6 | def getArea(self): 7 | return self.width * self.height 8 | 9 | def getPerimeter(self): 10 | return (self.height+self.width)*2 -------------------------------------------------------------------------------- /CH05/EX5.15.py: -------------------------------------------------------------------------------- 1 | # 5.15 (Find the largest n such that n3 12,000) Use a while loop to find the largest 2 | # integer n such that n3 is less than 12,000. 3 | 4 | n = 12000 5 | while True: 6 | if n ** 3 < 12000: 7 | break 8 | n -= 1 9 | 10 | print("the largest n such that n^3 < 12,000 is", n) 11 | -------------------------------------------------------------------------------- /CH05/EX5.14.py: -------------------------------------------------------------------------------- 1 | # 5.14 (Find the smallest n such that n2 12,000) Use a while loop to find the smallest 2 | # integer n such that n2 is greater than 12,000. 3 | 4 | n = 1 5 | while True: 6 | if n ** 2 > 12000: 7 | break 8 | n += 1 9 | 10 | print("The smallest integer n such that n^2 > 12,000 is", n) 11 | -------------------------------------------------------------------------------- /CH03/EX3.6.py: -------------------------------------------------------------------------------- 1 | # (Find the character of an ASCII code) Write a program that receives an ASCII 2 | # code (an integer between 0 and 127) and displays its character. For example, if the 3 | # user enters 97, the program displays the character a. 4 | 5 | c = int(input("Enter an ASCII code: ")) 6 | c = chr(c) 7 | print("The character is", c) 8 | -------------------------------------------------------------------------------- /CH05/EX5.48.py: -------------------------------------------------------------------------------- 1 | # 5.48 (Turtle: draw circles) Write a program that draws 10 circles with centers (0, 0), as 2 | # shown in Figure 5.3b. 3 | import turtle 4 | 5 | rad = 60 6 | for i in range(10): 7 | turtle.penup() 8 | turtle.goto(0, -rad) 9 | turtle.pendown() 10 | turtle.circle(rad) 11 | rad += 10 12 | 13 | turtle.done() 14 | -------------------------------------------------------------------------------- /CH02/EX2.13.py: -------------------------------------------------------------------------------- 1 | # (Split digits) Write a program that prompts the user to enter a four-digit integer 2 | # and displays the number in reverse order. 3 | num = int(input("Enter an integer: ")) 4 | n1 = num % 10 5 | num //= 10 6 | n2 = num % 10 7 | num //= 10 8 | n3 = num % 10 9 | num //= 10 10 | n4 = num 11 | print(n4) 12 | print(n3) 13 | print(n2) 14 | print(n1) 15 | -------------------------------------------------------------------------------- /CH02/EX2.15.py: -------------------------------------------------------------------------------- 1 | # (Geometry: area of a hexagon) Write a program that prompts the user to enter the 2 | # side of a hexagon and displays its area. The formula for computing the area of a 3 | # hexagon is Area = where s is the length of a side. 4 | 5 | side = eval(input("Enter the side: ")) 6 | area = (3 * 3 ** 0.5 * side ** 2) / 2 7 | print("The area of the hexagon is", area) 8 | -------------------------------------------------------------------------------- /CH02/EX2.22.py: -------------------------------------------------------------------------------- 1 | # (Population projection) Rewrite Exercise 1.11 to prompt the user to enter the 2 | # number of years and displays the population after that many years. 3 | 4 | numOfYears = eval(input("Enter the number of years: ")) 5 | population = int(312032486 + (((31536000 / 7) - (31536000 / 13) + (31536000 / 45)) * numOfYears)) 6 | print("The population in 5 years is", population) 7 | -------------------------------------------------------------------------------- /CH05/EX5.44.py: -------------------------------------------------------------------------------- 1 | # 5.44 (Decimal to binary) Write a program that prompts the user to enter a decimal integer 2 | # and displays its corresponding binary value. 3 | 4 | d = int(input("Enter an integer: ")) 5 | 6 | bin = "" 7 | value = d 8 | 9 | while value != 0: 10 | bin = str(value % 2) + bin 11 | value = value // 2 12 | 13 | print("The binary representation of", d, "is", bin) 14 | -------------------------------------------------------------------------------- /CH06/EX6.33.py: -------------------------------------------------------------------------------- 1 | # 6.33 (Geometry: area of a pentagon) Rewrite Exercise 3.4 using the following function 2 | # to return the area of a pentagon: 3 | # def area(s): 4 | import math 5 | 6 | 7 | def area(s): 8 | return (5 * s**2) / (4 * math.tan(math.pi / 5)) 9 | 10 | def main(): 11 | print("The area of the pentagon is", area(eval(input("Enter the side: ")))) 12 | 13 | 14 | main() -------------------------------------------------------------------------------- /CH05/EX5.43.py: -------------------------------------------------------------------------------- 1 | # 5.43 (Math: combinations) Write a program that displays all possible combinations for 2 | # picking two numbers from integers 1 to 7. Also display the total number of combinations. 3 | 4 | count = 0 5 | for i in range(1, 8): 6 | for j in range(i+1, 8): 7 | print(i, " ", j) 8 | count += 1 9 | 10 | print("The total number of all combinations is", count) 11 | -------------------------------------------------------------------------------- /CH02/EX2.1.py: -------------------------------------------------------------------------------- 1 | # (Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree from 2 | # the console and converts it to Fahrenheit and displays the result. The formula for 3 | # the conversion is as follows: 4 | # fahrenheit = (9 / 5) * celsius + 32 5 | 6 | celsius = eval(input("Enter a Celsius value: ")) 7 | fah = (9 / 5) * celsius + 32 8 | print(celsius, "Celsuis is", fah, "Fahrenheit") 9 | -------------------------------------------------------------------------------- /CH02/EX2.4.py: -------------------------------------------------------------------------------- 1 | # (Convert pounds into kilograms) Write a program that converts pounds into 2 | # kilograms. The program prompts the user to enter a value in pounds, converts it to 3 | # kilograms, and displays the result. One pound is 0.454 kilograms. Here is a 4 | # sample run: 5 | 6 | pounds = eval(input("Enter a value in pounds: ")) 7 | kg = pounds * 0.454 8 | print(pounds, "Pounds is", kg, "Kilograms") 9 | -------------------------------------------------------------------------------- /CH05/EX5.27.py: -------------------------------------------------------------------------------- 1 | # 5.27 (Compute ) You can approximate by using the following series: 2 | # Write a program that displays the value for i = 10000, 20000, . . ., and 3 | # 100000. 4 | 5 | for i in range(10000, 100001, 10000): 6 | sum = 0 7 | for j in range(1, i + 1): 8 | sum += ((-1) ** (j + 1)) / (2 * j - 1) 9 | 10 | pi = 4 * sum 11 | print("PI value for i=", i, "is", pi) 12 | -------------------------------------------------------------------------------- /CH02/EX2.12.py: -------------------------------------------------------------------------------- 1 | # (Print a table) Write a program that displays the following table: 2 | # a b a ** b 3 | # 1 2 1 4 | # 2 3 8 5 | # 3 4 81 6 | # 4 5 1024 7 | # 5 6 15625 8 | print("a b a**b") 9 | print("1 2 ", 1 ** 2) 10 | print("2 3 ", 2 ** 3) 11 | print("3 4 ", 3 ** 4) 12 | print("4 5 ", 4 ** 5) 13 | print("5 6 ", 5 ** 6) 14 | -------------------------------------------------------------------------------- /CH06/EX6.16.py: -------------------------------------------------------------------------------- 1 | # 6.16 (Number of days in a year) Write a function that returns the number of days in a 2 | # year using the following header: 3 | # def numberOfDaysInAYear(year): 4 | # Write a test program that displays the number of days in the years from 2010 to 5 | # 2020. 6 | from CH6Module import MyFunctions 7 | 8 | for year in range(2010, 2021): 9 | print(year, "has", MyFunctions.numberOfDaysInAYear(year)) -------------------------------------------------------------------------------- /CH15/EX15.04.py: -------------------------------------------------------------------------------- 1 | # 15.4 (Sum series) Write a recursive function to compute the following series: 2 | # m(i) = 1 + 1/2 + 1/3 + ... + 1/i 3 | # Write a test program that displays m(i) for i 1, 2, ..., 10. 4 | 5 | def sumSeries(i): 6 | if i == 1: 7 | return 1 8 | return 1 / i + sumSeries(i-1) 9 | 10 | 11 | for i in range(1, 11): 12 | print("The sum series for i=", i, "is", sumSeries(i)) 13 | -------------------------------------------------------------------------------- /CH03/EX3.4.py: -------------------------------------------------------------------------------- 1 | # (Geometry: area of a pentagon) The area of a pentagon can be computed using the 2 | # following formula (s is the length of a side): 3 | # Write a program that prompts the user to enter the side of a pentagon and displays 4 | # the area. 5 | import math 6 | 7 | s = eval(input("Enter the side: ")) 8 | area = (5 * s**2) / (4 * math.tan(math.pi / 5)) 9 | print("The area of the pentagon is", area) 10 | -------------------------------------------------------------------------------- /CH13/EX13.6.py: -------------------------------------------------------------------------------- 1 | # 13.6 (Count words) Write a program that counts the number of words in President 2 | # Abraham Lincoln’s Gettysburg Address from http://cs.armstrong.edu/liang/data/ 3 | # Lincoln.txt. 4 | import urllib.request 5 | 6 | file = urllib.request.urlopen("http://cs.armstrong.edu/liang/data/Lincoln.txt") 7 | data = file.read.decode() 8 | data = data.split() 9 | print("There are", len(data), "Words") 10 | -------------------------------------------------------------------------------- /CH05/EX5.8.py: -------------------------------------------------------------------------------- 1 | # 5.8 (Use the math.sqrt function) Write a program that prints the following table 2 | # using the sqrt function in the math module. 3 | # Number Square Root 4 | # 0 0.0000 5 | # 2 1.4142 6 | # ... 7 | # 18 5.2426 8 | # 20 5.4721 9 | import math 10 | 11 | print(format("Number", "12s"), "Square Root") 12 | 13 | for i in range(0, 21, 2): 14 | print(format(i, "2.0f"), format(math.sqrt(i), "16.4f")) 15 | -------------------------------------------------------------------------------- /CH05/EX5.17.py: -------------------------------------------------------------------------------- 1 | # 5.17 (Display the ASCII character table) Write a program that displays the characters 2 | # in the ASCII character table from ! to ~. Display ten characters per line. The characters 3 | # are separated by exactly one space. 4 | 5 | counter = 0 6 | for i in range(ord('!'), ord('~')): 7 | if counter == 10: 8 | print() 9 | counter = 0 10 | print(chr(i), end=" ") 11 | counter+=1 12 | -------------------------------------------------------------------------------- /CH03/EX3.11.py: -------------------------------------------------------------------------------- 1 | # (Reverse number) Write a program that prompts the user to enter a four-digit integer 2 | # and displays the number in reverse order. 3 | 4 | num = eval(input("Enter an integer: ")) 5 | n1 = num % 10 6 | num = num // 10 7 | n2 = num % 10 8 | num = num // 10 9 | n3 = num % 10 10 | num = num // 10 11 | n4 = num 12 | print(n1, end='') 13 | print(n2, end='') 14 | print(n3, end='') 15 | print(n4, end='') 16 | 17 | -------------------------------------------------------------------------------- /CH09/EX9.4.py: -------------------------------------------------------------------------------- 1 | # 9.4 (Display rectangles) Write a program that displays 20 rectangles, as shown in 2 | # Figure 9.24. 3 | 4 | from tkinter import * 5 | 6 | window = Tk() 7 | c = Canvas(window,width=300,height=200,bg="white") 8 | c.pack() 9 | x1 = 3; y1 = 3; x2=299; y2=199 10 | 11 | for i in range(20): 12 | c.create_rectangle(x1+5,y1+5,x2-5,y2-5) 13 | x1 = x1+5; y1 = y1+5; x2 = x2-5; y2 = y2-5 14 | window.mainloop() 15 | -------------------------------------------------------------------------------- /CH05/EX5.3.py: -------------------------------------------------------------------------------- 1 | # 5.3 (Conversion from kilograms to pounds) Write a program that displays the following 2 | # table (note that 1 kilogram is 2.2 pounds): 3 | # Kilograms Pounds 4 | # 1 2.2 5 | # 3 6.6 6 | # ... 7 | # 197 433.4 8 | # 199 437.8 9 | 10 | KILOGRAM_TO_POUND = 2.2 11 | print("Kilograms", format("Pounds", "8s")) 12 | for i in range(1, 200,2): 13 | pound = i * KILOGRAM_TO_POUND 14 | print(i, format(pound, "11.1f")) 15 | -------------------------------------------------------------------------------- /CH15/EX15.05.py: -------------------------------------------------------------------------------- 1 | # 15.5 (Sum series) Write a recursive function to compute the following series: 2 | # m(i) = 1/3 + 2/5 + 3/7 + 4/9 + 5/11 + 6/13 + ... + i/2i + 1 3 | # Write a test program that displays m(i) for i 1, 2, ..., 10. 4 | 5 | def sumSeries(i): 6 | if i == 1: 7 | return 1/3 8 | return i / (2 * i + 1) + sumSeries(i - 1) 9 | 10 | for i in range(1, 11): 11 | print("The sum series for i=", i, "is", sumSeries(i)) 12 | -------------------------------------------------------------------------------- /CH05/EX5.4.py: -------------------------------------------------------------------------------- 1 | # 5.4 (Conversion from miles to kilometers) Write a program that displays the following 2 | # table (note that 1 mile is 1.609 kilometers): 3 | # Miles Kilometers 4 | # 1 1.609 5 | # 2 3.218 6 | # ... 7 | # 9 15.481 8 | # 10 16.090 9 | 10 | MILES_TO_KILOMETRE = 1.609 11 | print("Mile", format("Kilometre", "8s")) 12 | for i in range(1, 11): 13 | kilometre = i * MILES_TO_KILOMETRE 14 | print(i, format(kilometre, "11.3f")) 15 | -------------------------------------------------------------------------------- /CH11/Checkpoints: -------------------------------------------------------------------------------- 1 | #11.1 2 | lst = [ 3 | [0,0,0,0], 4 | [0,0,0,0], 5 | [0,0,0,0] 6 | ] 7 | 8 | #11.2 9 | Yes 10 | 11 | #11.3 12 | [[2, 1, 1], [1, 1, 1], [1, 1, 1]] 13 | 14 | #11.4 15 | [[[1, 1, 1]], [[1, 1, 1]], [[1, 1, 1]]] 16 | [3, [[1, 1, 1]], [[1, 1, 1]]] 17 | 18 | #11.5 19 | [[1, 2, 3], [4, 5], [6, 7, 8, 9]] 20 | 21 | 22 | #11.6 23 | 00 24 | 01 25 | 11 26 | 12 27 | 28 | #11.7 29 | 0001 30 | 0001 31 | 1112 32 | 1112 -------------------------------------------------------------------------------- /CH15/EX15.06.py: -------------------------------------------------------------------------------- 1 | # 15.6 (Summing series) Write a recursive function to compute the following series: 2 | # m(i) = 1/2 + 2/3 + ... + i/i + 1 3 | # Write a test program that prompts the user to enter an integer for i and displays m(i). 4 | 5 | def sumSeries(i): 6 | if i == 1: 7 | return 1 / 2 8 | return i / (i + 1) + sumSeries(i - 1) 9 | 10 | 11 | for i in range(1, 11): 12 | print("The sum series for i=", i, "is", sumSeries(i)) 13 | -------------------------------------------------------------------------------- /CH02/EX2.2.py: -------------------------------------------------------------------------------- 1 | # (Compute the volume of a cylinder) Write a program that reads in the radius and 2 | # length of a cylinder and computes the area and volume using the following formulas: 3 | # area = radius * radius * π 4 | # volume = area * length 5 | 6 | PI = 3.1415 7 | 8 | rad, len = eval(input("Enter the radius and length of a cylinder:")) 9 | area = rad * rad * PI 10 | vol = area * len 11 | print("The area is", area) 12 | print("Thr volume is", vol) 13 | -------------------------------------------------------------------------------- /CH02/EX2.7.py: -------------------------------------------------------------------------------- 1 | # (Find the number of years and days) Write a program that prompts the user to 2 | # enter the minutes (e.g., 1 billion), and displays the number of years and days for 3 | # the minutes. 4 | 5 | min = int(input("Enter the number of minutes: ")) 6 | years = int(min / (365 * 24 * 60)) 7 | remainingMin = min % (365 * 24 * 60) 8 | days = int(remainingMin / (24 * 60)) 9 | print(min, "minutes is approximately", years, "years and", days, "days") 10 | -------------------------------------------------------------------------------- /CH06/EX6.10.py: -------------------------------------------------------------------------------- 1 | # 6.10 (Use the isPrime Function) Listing 6.7, PrimeNumberFunction.py, provides the 2 | # isPrime(number) function for testing whether a number is prime. Use this 3 | # function to find the number of prime numbers less than 10,000. 4 | from CH6Module import MyFunctions 5 | 6 | count = 0 7 | for i in range(1, 10001): 8 | if MyFunctions.isPrime(i): 9 | count += 1 10 | 11 | print("The number of primes less than 10,000 is", count) 12 | -------------------------------------------------------------------------------- /CH10/EX10.24.py: -------------------------------------------------------------------------------- 1 | # 10.24 (Math: combinations) Write a program that prompts the user to enter 10 integers 2 | # and displays all the combinations of picking two numbers from the 10. 3 | 4 | nums = [] 5 | for i in range(10): 6 | nums.append(eval(input("Enter a number:"))) 7 | 8 | for i in range(len(nums)): 9 | for j in range(len(nums)): 10 | print("(", nums[i], nums[j], ")", end=" ") 11 | if j % 5 == 0: 12 | print() 13 | -------------------------------------------------------------------------------- /CH11/EX11.18.py: -------------------------------------------------------------------------------- 1 | # 11.18 (Shuffle rows) Write a function that shuffles the rows in a two-dimensional list 2 | # using the following header: 3 | # def shuffle(m): 4 | # Write a test program that shuffles the following matrix: 5 | # m = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 6 | 7 | import random 8 | 9 | 10 | def shuffle(m): 11 | random.shuffle(m) 12 | 13 | 14 | m = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 15 | shuffle(m) 16 | 17 | print(m) 18 | -------------------------------------------------------------------------------- /CH05/EX5.26.py: -------------------------------------------------------------------------------- 1 | # 5.26 (Sum a series) Write a program to sum the following series: 2 | 3 | sum = 0 4 | # As there was a computational error because the loop is running in linear, 5 | # indeed it should increment by 2. But still you're a legend because you solved 5 years ago, 6 | # but I'm doing in this modern era where there are so tools like gpt to assure solved problem 7 | for i in range(1, 98, 2): 8 | sum += i / (i + 2) 9 | 10 | print("Sum is", sum) 11 | -------------------------------------------------------------------------------- /CH07/StopWatch.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | 4 | class StopWatch: 5 | def __init__(self): 6 | self.__startTime = time.time() 7 | 8 | def getStartTime(self): 9 | return self.__startTime 10 | 11 | def start(self): 12 | self.__startTime = time.time() 13 | 14 | def end(self): 15 | self.__endTime = time.time() 16 | 17 | def getElapsedTime(self): 18 | return int(1000 * (self.__endTime - self.__startTime)) 19 | -------------------------------------------------------------------------------- /CH05/EX5.21.py: -------------------------------------------------------------------------------- 1 | # 5.21 (Display numbers in a pyramid pattern) Write a nested for loop that displays the 2 | # following output: 3 | 4 | n = 9 5 | x = n * 2 6 | for i in range(1, n): 7 | s = n + x 8 | sp = str(s) + "s" 9 | print(format(" ", sp), end='') 10 | for j in range(0, i-1): 11 | print(format(2**j,"3d"), end='') 12 | 13 | for j in range(i-1,-1,-1): 14 | print(format(2 ** j, "3d"), end='') 15 | print() 16 | x-=3 17 | -------------------------------------------------------------------------------- /CH11/test.py: -------------------------------------------------------------------------------- 1 | def f(m): 2 | for i in range(len(m)): 3 | for j in range(len(m[i])): 4 | for k in range(len(m[j])): 5 | m[i][j][k] += 1 6 | def printM(m): 7 | for i in range(len(m)): 8 | for j in range(len(m[i])): 9 | for k in range(len(m[j])): 10 | print(m[i][j][k], end = "") 11 | print() 12 | 13 | m = [[[0, 0], [0, 1]], [[0, 0], [0, 1]]] 14 | 15 | printM(m) 16 | f(m) 17 | printM(m) -------------------------------------------------------------------------------- /CH04/EX4.4.py: -------------------------------------------------------------------------------- 1 | # (Game: learn addition) Write a program that generates two integers under 100 and 2 | # prompts the user to enter the sum of these two integers. The program then reports 3 | # true if the answer is correct, false otherwise. The program is similar to Listing 4.1. 4 | import random 5 | 6 | n1, n2 = random.randint(0, 99), random.randint(0, 99) 7 | s = "What is " + str(n1) + " + " + str(n2) + " ?" 8 | res = eval(input(s)) 9 | 10 | print((res == (n1 + n2))) 11 | -------------------------------------------------------------------------------- /CH05/EX5.12.py: -------------------------------------------------------------------------------- 1 | # 5.12 (Find numbers divisible by 5 and 6) Write a program that displays, ten numbers 2 | # per line, all the numbers from 100 to 1,000 that are divisible by 5 and 6. The numbers 3 | # are separated by exactly one space. 4 | 5 | counter = 0 6 | for i in range(100, 1000): 7 | if i % 5 == 0 and i % 6 == 0: 8 | if counter == 10: 9 | print() 10 | counter = 0 11 | 12 | print(i, end=" ") 13 | counter += 1 14 | -------------------------------------------------------------------------------- /CH06/EX6.34.py: -------------------------------------------------------------------------------- 1 | # 6.34 (Geometry: area of a regular polygon) Rewrite Exercise 3.5 using the following 2 | # function to return the area of a regular polygon: 3 | # def area(n, side): 4 | import math 5 | 6 | 7 | def area(n, side): 8 | return (n * side ** 2) / (4 * math.tan(math.pi / n)) 9 | 10 | 11 | def main(): 12 | print("The area of the polygon is", 13 | area(int(input("Enter the number of sides: ")), eval(input("Enter the side: ")))) 14 | 15 | main() -------------------------------------------------------------------------------- /CH05/EX5.29.py: -------------------------------------------------------------------------------- 1 | # 5.29 (Display leap years) Write a program that displays, ten per line, all the leap years 2 | # in the twenty-first century (from year 2001 to 2100). The years are separated by 3 | # exactly one space. 4 | 5 | counter = 0 6 | for i in range(2001, 2100): 7 | 8 | if (i % 4 == 0 and i % 100 != 0) or (i % 400 == 0): 9 | if counter == 10: 10 | print() 11 | counter = 0 12 | print(i, end=' ') 13 | counter += 1 14 | -------------------------------------------------------------------------------- /CH09/EX9.7.py: -------------------------------------------------------------------------------- 1 | # 9.7 (Display an grid ) Write a program that displays an grid, as shown in 2 | # Figure 9.25c. Use red for vertical lines and blue for horizontal lines. 3 | from tkinter import * 4 | 5 | window = Tk() 6 | c = Canvas(window,bg="white",width=570,height=570) 7 | c.pack() 8 | for i in range(11): 9 | c.create_line(10+(i*70),10,10+(i*70),570,fill="red") 10 | 11 | for i in range(11): 12 | c.create_line(10,10+(i*70),570,10+(i*70),fill="blue") 13 | 14 | window.mainloop() -------------------------------------------------------------------------------- /CH06/EX6.20.py: -------------------------------------------------------------------------------- 1 | # 6.20 (Geometry: display angles) Rewrite Listing 2.9, ComputeDistance.py, using the 2 | # following function for computing the distance between two points. 3 | # def distance(x1, y1, x2, y2): 4 | 5 | def distance(x1, y1, x2, y2): 6 | distance = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5 7 | return distance 8 | 9 | 10 | def main(): 11 | x1, y1, x2, y2 = eval(input("Enter x1,y1,x2,y2: ")) 12 | print("The distance is", distance(x1, y1, x2, y2)) 13 | 14 | main() -------------------------------------------------------------------------------- /CH08/EX8.11.py: -------------------------------------------------------------------------------- 1 | # 8.11 (Reverse a string) Write a function that reverses a string. The header of the function 2 | # is: 3 | # def reverse(s): 4 | # Write a test program that prompts the user to enter a string, invokes the reverse 5 | # function, and displays the reversed string. 6 | def reverse(s): 7 | new = s[len(s):0:-1] + s[0] 8 | return new 9 | 10 | 11 | def main(): 12 | st = input("Enter a string: ") 13 | print("The reverse of", st, "is", reverse(st)) 14 | 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /CH10/EX10.30.py: -------------------------------------------------------------------------------- 1 | # 10.30 (Culture: Chinese Zodiac) Simplify Listing 4.5, ChineseZodiac.py, using a list 2 | # of strings to store the animals’ names. 3 | 4 | temp = year = eval(input("Enter a year: ")) 5 | 6 | if year >= 1900: 7 | year -= 1900 8 | else: 9 | year = 12 - (1900 - year) % 12 10 | 11 | animals = ["rat", "ox", "tiger", "rabbit", "dragon", 12 | "snake", "horse", "sheep", "monkey", "rooster", "dog", "pig"] 13 | 14 | print(temp, "is", animals[year % 12]) 15 | 16 | 17 | -------------------------------------------------------------------------------- /CH02/EX2.16.py: -------------------------------------------------------------------------------- 1 | # (Physics: acceleration) Average acceleration is defined as the change of velocity 2 | # divided by the time taken to make the change, as shown in the following formula: 3 | # Write a program that prompts the user to enter the starting velocity in 4 | # meters/second, the ending velocity in meters/second, and the time span t in 5 | # seconds, and displays the average acceleration. 6 | v0, v1, t = eval(input("Enter v0, v1, and t: ")) 7 | a = (v1 - v0) / t 8 | print("The average acceleration is", a) 9 | -------------------------------------------------------------------------------- /CH10/EX10.3.py: -------------------------------------------------------------------------------- 1 | # 10.3 (Count occurrence of numbers) Write a program that reads some integers 2 | # between 1 and 100 and counts the occurrences of each. 3 | 4 | n = input("Enter integers between 1 and 100: ") 5 | lst = [int(x) for x in n.split()] 6 | counted = [] 7 | for x in lst: 8 | if x not in counted: 9 | c = lst.count(x) 10 | if c > 1: 11 | print(x, "occurs", c, "times") 12 | else: 13 | print(x, "occurs", c, "time") 14 | counted.append(x) 15 | -------------------------------------------------------------------------------- /CH06/EX6.27.py: -------------------------------------------------------------------------------- 1 | # 6.27 (Twin primes) Twin primes are a pair of prime numbers that differ by 2. For example, 2 | # 3 and 5, 5 and 7, and 11 and 13 are twin primes. Write a program to find all 3 | # twin primes less than 1,000. Display the output as follows: 4 | # (3, 5) 5 | # (5, 7)... 6 | 7 | from CH6Module import MyFunctions 8 | 9 | x = 3 10 | while x < 1000: 11 | if MyFunctions.isPrime(x) and MyFunctions.isPrime(x + 2): 12 | print("(" + str(x) + ", " + str(x + 2) + ")") 13 | 14 | x += 1 15 | -------------------------------------------------------------------------------- /CH05/EX5.40.py: -------------------------------------------------------------------------------- 1 | # 5.40 (Simulation: heads or tails) Write a program that simulates flipping a coin one 2 | # million times and displays the number of heads and tails. 3 | import random 4 | 5 | print("Simulating flipping a coin 1000000 times") 6 | 7 | head = 0 8 | tail = 0 9 | 10 | print("Wait....") 11 | for i in range(0, 1000000): 12 | if random.randint(0, 1) == 0: 13 | head += 1 14 | else: 15 | tail += 1 16 | 17 | print("The number of heads:", head, "and the number of tails:", tail) 18 | -------------------------------------------------------------------------------- /CH05/EX5.13.py: -------------------------------------------------------------------------------- 1 | # 5.13 (Find numbers divisible by 5 or 6, but not both) Write a program that displays, ten 2 | # numbers per line, all the numbers from 100 to 200 that are divisible by 5 or 6, but 3 | # not both. The numbers are separated by exactly one space. 4 | 5 | counter = 0 6 | for i in range(100, 200): 7 | if i % 5 == 0 or i % 6 == 0 and not (i % 5 == 0 and i % 6 == 0): 8 | if counter == 10: 9 | print() 10 | counter = 0 11 | print(i, end=" ") 12 | counter += 1 13 | -------------------------------------------------------------------------------- /CH02/EX2.5.py: -------------------------------------------------------------------------------- 1 | # (Financial application: calculate tips) Write a program that reads the subtotal and 2 | # the gratuity rate and computes the gratuity and total. For example, if the user 3 | # enters 10 for the subtotal and 15% for the gratuity rate, the program displays 1.5 4 | # as the gratuity and 11.5 as the total. 5 | 6 | subTotal, gratRate = eval(input("Enter the subtotal and a gratuity rate: ")) 7 | grat = subTotal * (gratRate / 100) 8 | total = subTotal + grat 9 | print("The gratuity is", grat, "and the total is", total) 10 | -------------------------------------------------------------------------------- /CH04/EX4.12.py: -------------------------------------------------------------------------------- 1 | # 4.12 (Check a number) Write a program that prompts the user to enter an integer and 2 | # checks whether the number is divisible by both 5 and 6, divisible by 5 or 6, or just 3 | # one of them (but not both). 4 | 5 | n = int(input("Enter an integer: ")) 6 | 7 | print("Is", n, " divisible by 5 and 6?", n % 5 == 0 and n % 6 == 0) 8 | print("Is", n, "divisible by 5 or 6?", n % 5 == 0 or n % 6 == 0) 9 | print("Is", n, "divisible by 5 or 6, but not both?", (n % 5 == 0 and n % 6 != 0) or (n % 5 != 0 and n % 6 == 0)) 10 | -------------------------------------------------------------------------------- /CH04/EX4.26.py: -------------------------------------------------------------------------------- 1 | # 4.26 (Palindrome number) Write a program that prompts the user to enter a three-digit 2 | # integer and determines whether it is a palindrome number. 3 | # A number is a palindromeif it reads the same from right to left and from left to right. 4 | 5 | num = int(input("Enter a three-digit integer: ")) 6 | N = num 7 | n1 = num // 100 8 | num %= 100 9 | n2 = num // 10 10 | num %= 10 11 | n3 = num 12 | 13 | if n1 == n3: 14 | print(str(N),"is a palindrome") 15 | else: 16 | print(str(N), "is not a palindrome") -------------------------------------------------------------------------------- /CH10/EX10.7.py: -------------------------------------------------------------------------------- 1 | # 10.7 (Count single digits) Write a program that generates 1,000 random integers 2 | # between 0 and 9 and displays the count for each number. (Hint: Use a list of ten 3 | # integers, say counts, to store the counts for the number of 0s, 1s, ..., 9s.) 4 | import random 5 | 6 | lst = [] 7 | for i in range(1000): 8 | lst.append(random.randint(0, 9)) 9 | 10 | counts = [] 11 | for i in range(10): 12 | counts.append(lst.count(lst[i])) 13 | 14 | for i in range(10): 15 | print(i, ":", counts[i], "times") 16 | -------------------------------------------------------------------------------- /CH02/EX2.26.py: -------------------------------------------------------------------------------- 1 | # (Turtle: draw a circle) Write a program that prompts the user to enter the 2 | # center and radius of a circle, and then displays the circle and its area, as shown 3 | # in Figure 2.5. 4 | import turtle 5 | 6 | centerX, centerY, rad = eval(input("Enter centerX, centerY, radius: ")) 7 | turtle.penup() 8 | turtle.goto(centerX, centerY - 0.5 * rad) 9 | turtle.pendown() 10 | turtle.circle(rad) 11 | turtle.penup() 12 | turtle.goto(centerX+20,centerY+20) 13 | area = 3.14 * rad ** 2 14 | turtle.write(area) 15 | 16 | turtle.done() -------------------------------------------------------------------------------- /CH03/EX3.19.py: -------------------------------------------------------------------------------- 1 | # (Turtle: draw a line) Write a program that prompts the user to enter two points 2 | # and draw a line to connect the points and displays the coordinates of the points, 3 | # as shown in Figure 3.7c. 4 | 5 | import turtle 6 | 7 | x1, y1, x2, y2 = eval(input("Enter two points: ")) 8 | 9 | turtle.penup() 10 | turtle.goto(x1, y1) 11 | turtle.pendown() 12 | s = "(" + str(x1) + "," + str(y1) + ")" 13 | turtle.write(s) 14 | turtle.goto(x2, y2) 15 | s = "(" + str(x2) + "," + str(y2) + ")" 16 | turtle.write(s) 17 | 18 | turtle.done() -------------------------------------------------------------------------------- /CH05/EX5.19.py: -------------------------------------------------------------------------------- 1 | # 5.19 (Display a pyramid) Write a program that prompts the user to enter an integer 2 | # from 1 to 15 and displays a pyramid, as shown in the following sample run: 3 | 4 | n = int(input("Enter number of lines: ")) 5 | x = n * 2 6 | for i in range(1, n + 1): 7 | s = n + x 8 | sp = str(s) + "s" 9 | print(format(" ", sp), end='') 10 | for j in range(i, 0, -1): 11 | print(j, end=' ') 12 | for j in range(2, i + 1): 13 | print(j, end=' ') 14 | 15 | print(format(" ", sp)) 16 | x -= 3 17 | -------------------------------------------------------------------------------- /CH03/EX3.13.py: -------------------------------------------------------------------------------- 1 | # (Turtle: display a STOP sign) Write a program that displays a STOP sign, as 2 | # shown in Figure 3.5b. The hexagon is in red and the text is in white 3 | 4 | import turtle 5 | 6 | turtle.begin_fill() 7 | turtle.left(90) 8 | turtle.circle(100, steps=6) 9 | turtle.color("red") 10 | turtle.end_fill() 11 | turtle.color("white") 12 | turtle.penup() 13 | turtle.goto(turtle.xcor() - 140, turtle.ycor() - 15) 14 | turtle.pendown() 15 | turtle.write("STOP", font=("Arial", 20, "normal")) 16 | turtle.hideturtle() 17 | 18 | turtle.done() 19 | -------------------------------------------------------------------------------- /CH04/EX4.10.py: -------------------------------------------------------------------------------- 1 | # (Game: multiplication quiz) Listing 4.4, SubtractionQuiz.py, randomly generates 2 | # a subtraction question. Revise the program to randomly generate a multiplication 3 | # question with two integers less than 100. 4 | 5 | import random 6 | 7 | n1, n2 = random.randint(0, 99), random.randint(0, 99) 8 | s = "What is " + str(n1) + " * " + str(n2) + " ? " 9 | res = eval(input(s)) 10 | 11 | if res == (n1 * n2): 12 | print("You are correct!") 13 | else: 14 | print("You are wrong") 15 | print(str(n1), "*", str(n2), "=", str(n1 * n2)) -------------------------------------------------------------------------------- /CH04/EX4.19.py: -------------------------------------------------------------------------------- 1 | # 4.19 (Compute the perimeter of a triangle) Write a program that reads three edges for a 2 | # triangle and computes the perimeter if the input is valid. Otherwise, display that 3 | # the input is invalid. The input is valid if the sum of every pair of two edges is 4 | # greater than the remaining edge. 5 | 6 | e1, e2, e3 = eval(input("Enter three edges: ")) 7 | 8 | if e1 + e2 > e3 and e1 + e3 > e2 and e2 + e3 > e1: 9 | res = e1 + e2 + e3 10 | print("The perimeter is", str(res)) 11 | else: 12 | print("The input is invalid") 13 | -------------------------------------------------------------------------------- /CH08/EX8.1.py: -------------------------------------------------------------------------------- 1 | # 8.1 (Check SSN) Write a program that prompts the user to enter a Social Security 2 | # number in the format ddd-dd-dddd, where d is a digit. The program displays 3 | # Valid SSN for a correct Social Security number or Invalid SSN otherwise. 4 | 5 | ssn = input("Enter your social security number (ddd-dd-dddd): ") 6 | s1 = ssn[0:3] 7 | s2 = ssn[4:6] 8 | s3 = ssn[7:11] 9 | 10 | if (len(s1)+len(s2)+len(s3) == 9) and s1.isdigit() and s2.isdigit() and s3.isdigit(): 11 | print("SSN is valid") 12 | else: 13 | print("SSN is not valid") 14 | -------------------------------------------------------------------------------- /CH05/EX5.45.py: -------------------------------------------------------------------------------- 1 | # 5.45 (Decimal to hex) Write a program that prompts the user to enter a decimal integer 2 | # and displays its corresponding hexadecimal value. 3 | 4 | d = int(input("Enter an integer: ")) 5 | 6 | hex = "" 7 | value = d 8 | 9 | while value != 0: 10 | h = value % 16 11 | if h >= 10: 12 | hex += chr(h + 55) 13 | else: 14 | hex += str(h) 15 | 16 | value //= 16 17 | 18 | res = "" 19 | for i in range(len(hex) - 1, -1, -1): 20 | res += hex[i] 21 | 22 | print("The hexadecimal representation of", d, "is", res) 23 | -------------------------------------------------------------------------------- /CH06/EX6.13.py: -------------------------------------------------------------------------------- 1 | # 6.13 (Sum series) Write a function to compute the following series: 2 | # Write a test program that displays the following table: 3 | # i m(i) 4 | # 1 0.5000 5 | # 2 1.1667 6 | # ... 7 | # 19 16.4023 8 | # 20 17.3546 9 | 10 | def sumSeries(i): 11 | sum = 0 12 | for i in range(1, i + 1): 13 | sum += i / (i + 1) 14 | return sum 15 | 16 | 17 | def main(): 18 | print("i\t m(i)") 19 | for i in range(1, 21): 20 | print(format(i, "-0.0f"), format(" ", "4s"), format(sumSeries(i), ".4f")) 21 | 22 | 23 | main() 24 | -------------------------------------------------------------------------------- /CH06/EX6.26.py: -------------------------------------------------------------------------------- 1 | # 6.26 (Mersenne prime) A prime number is called a Mersenne prime if it can be written 2 | # in the form for some positive integer p. Write a program that finds all 3 | # Mersenne primes with and displays the output as follows: 4 | # p 2^p - 1 5 | # 2 3 6 | # 3 7 7 | # 5 31 8 | # ... 9 | from CH6Module import MyFunctions 10 | 11 | print("P", " ", "2^p - 1") 12 | for p in range(2, 31 + 1): 13 | i = 2 ** p - 1 14 | 15 | # Display each number in five positions 16 | if MyFunctions.isPrime(i): 17 | print(str(p) + "\t\t" + str(i)) 18 | -------------------------------------------------------------------------------- /CH03/EX3.12.py: -------------------------------------------------------------------------------- 1 | # (Turtle: draw a star) Write a program that prompts the user to enter the length of 2 | # the star and draw a star, as shown in Figure 3.5a. (Hint: The inner angle of each 3 | # point in the star is 36 degrees.) 4 | import turtle 5 | 6 | l = eval(input("Enter length: ")) 7 | 8 | turtle.forward(l) 9 | turtle.right(144) 10 | 11 | turtle.forward(l) 12 | turtle.right(144) 13 | 14 | turtle.forward(l) 15 | turtle.right(144) 16 | 17 | turtle.forward(l) 18 | turtle.right(144) 19 | 20 | turtle.forward(l) 21 | turtle.right(144) 22 | 23 | turtle.done() 24 | -------------------------------------------------------------------------------- /CH05/EX5.9.py: -------------------------------------------------------------------------------- 1 | # 5.9 (Financial application: compute future tuition) Suppose that the tuition for a university 2 | # is $10,000 this year and increases 5% every year. Write a program that 3 | # computes the tuition in ten years and the total cost of four years’ worth of tuition 4 | # starting ten years from now. 5 | 6 | tuition = 10000 7 | total = 0 8 | for i in range(1, 15): 9 | tuition += tuition * 1.05 10 | if i == 10: 11 | print("The cost of tuition in 10 years is $", format(tuition, ".2f")) 12 | if i > 10: 13 | total = total + tuition 14 | -------------------------------------------------------------------------------- /CH10/EX10.32.py: -------------------------------------------------------------------------------- 1 | # 10.32 (Turtle: draw a line) Write the following function that draws a line from point 2 | # p1 ([x1, y1]) to point p2 ([x2, y2]). 3 | # # Draw a line 4 | # def drawLine(p1, p2): 5 | import math 6 | import turtle 7 | 8 | 9 | def drawLine(p1, p2): 10 | d = math.sqrt((p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1])) 11 | 12 | turtle.penup() 13 | turtle.penup() 14 | turtle.goto(p1[0], p1[1]) 15 | turtle.pendown() 16 | turtle.forward(d) 17 | turtle.done() 18 | 19 | drawLine([120, 80], [60, 20]) 20 | 21 | -------------------------------------------------------------------------------- /CH02/EX2.10.py: -------------------------------------------------------------------------------- 1 | # (Physics: find runway length) Given an airplane’s acceleration a and take-off 2 | # speed v, you can compute the minimum runway length needed for an airplane to 3 | # take off using the following formula: 4 | # Write a program that prompts the user to enter v in meters/second (m/s) and the 5 | # acceleration a in meters/second squared and displays the minimum runway 6 | # length. 7 | 8 | speed, acc = eval(input("Enter speed and acceleration: ")) 9 | len = speed ** 2 / (2 * acc) 10 | print("The minimum runway length for this airplane is", len, "meters") 11 | -------------------------------------------------------------------------------- /CH04/EX4.2.py: -------------------------------------------------------------------------------- 1 | # (Game: add three numbers) The program in Listing 4.1 generates two integers and 2 | # prompts the user to enter the sum of these two integers. Revise the program to generate 3 | # three single-digit integers and prompt the user to enter the sum of these three 4 | # integers. 5 | import random 6 | 7 | n1, n2, n3 = random.randint(0, 9), random.randint(0, 9), random.randint(0, 9) 8 | 9 | print("What is", str(n1), "+", str(n2), "+", str(n3), "?") 10 | res = eval(input()) 11 | print(str(n1), "+", str(n2), "+", str(n3), "=", res, "is", (res == (n1 + n2 + n3))) 12 | -------------------------------------------------------------------------------- /CH02/EX2.20.py: -------------------------------------------------------------------------------- 1 | # (Financial application: calculate interest) If you know the balance and the annual 2 | # percentage interest rate, you can compute the interest on the next monthly payment 3 | # using the following formula: 4 | # interest = balance * (annualInterestRate / 1200) 5 | # Write a program that reads the balance and the annual percentage interest rate 6 | # and displays the interest for the next month. 7 | 8 | balance, ir = eval(input("Enter balance and interest rate (e.g., 3 for 3%):")) 9 | intreset = balance * (ir / 1200) 10 | print("The interest is", intreset) 11 | -------------------------------------------------------------------------------- /CH05/EX5.35.py: -------------------------------------------------------------------------------- 1 | # 5.35 (Perfect number) A positive integer is called a perfect number if it is equal to the 2 | # sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect 3 | # number, because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. 4 | # There are four perfect numbers less than 10,000. Write a program to find these 5 | # four numbers. 6 | 7 | for i in range(3, 10000 + 1): 8 | sum = 0 9 | for j in range(1, (i // 2) + 1): 10 | if i % j == 0: 11 | sum += j 12 | 13 | if sum == i: 14 | print(i) 15 | -------------------------------------------------------------------------------- /CH05/EX5.50.py: -------------------------------------------------------------------------------- 1 | # 5.50 (Turtle: display numbers in a triangular pattern) Write a program that displays 2 | # numbers in a triangular pattern, as shown in Figure 5.4b. 3 | import turtle 4 | 5 | turtle.penup() 6 | turtle.goto(-170,150) 7 | turtle.pendown() 8 | 9 | for i in range(1,11): 10 | for j in range(1,i+1): 11 | turtle.write(str(j),font = ("Times", 18, "bold")) 12 | turtle.penup() 13 | turtle.forward(30) 14 | turtle.pendown() 15 | turtle.penup() 16 | turtle.goto(-170,turtle.ycor()-40) 17 | turtle.pendown() 18 | 19 | turtle.done() -------------------------------------------------------------------------------- /CH15/EX15.01.py: -------------------------------------------------------------------------------- 1 | # 15.1 (Sum the digits in an integer using recursion) Write a recursive function that computes 2 | # the sum of the digits in an integer. Use the following function header: 3 | # def sumDigits(n): 4 | # For example, sumDigits(234) returns Write a test program 5 | # that prompts the user to enter an integer and displays its sum. 6 | 7 | 8 | def sumDigits(n): 9 | if n == 0: 10 | return n 11 | 12 | return (n % 10 + sumDigits(n//10)) 13 | 14 | 15 | n = eval(input("Enter a digit: ")) 16 | 17 | print("The sum of the digits is:", sumDigits(n)) 18 | -------------------------------------------------------------------------------- /CH15/EX15.03.py: -------------------------------------------------------------------------------- 1 | # 15.3 (Compute greatest common divisor using recursion) The gcd(m, n) can also be 2 | # defined recursively as follows: 3 | # ■ If m % n is 0, gcd(m, n) is n. 4 | # ■ Otherwise, gcd(m, n) is gcd(n, m % n). 5 | # Write a recursive function to find the GCD. Write a test program that prompts the 6 | # user to enter two integers and displays their GCD. 7 | 8 | def gcd(m, n): 9 | if m % n == 0: 10 | return n 11 | return gcd(n, m % n) 12 | 13 | 14 | m, n = eval(input("Enter two numbers: ")) 15 | 16 | print("The GCD of", m, "and", n, "is", gcd(m, n)) 17 | -------------------------------------------------------------------------------- /CH02/EX2.6.py: -------------------------------------------------------------------------------- 1 | # (Sum the digits in an integer) Write a program that reads an integer between 0 and 2 | # 1000 and adds all the digits in the integer. For example, if an integer is 932, the 3 | # sum of all its digits is 14. (Hint: Use the % operator to extract digits, and use the // 4 | # operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 // 5 | # 10 = 93.) 6 | num = eval(input("Enter a number between 0 and 1000: ")) 7 | num1 = num % 10 8 | num //= 10 9 | num2 = num % 10 10 | num //= 10 11 | num3 = num 12 | print("The sum of the digits is", (num1 + num2 + num3)) 13 | -------------------------------------------------------------------------------- /CH05/EX5.18.py: -------------------------------------------------------------------------------- 1 | # 5.18 (Find the factors of an integer) Write a program that reads an integer and displays 2 | # all its smallest factors, also known as prime factors. For example, if the input integer 3 | # is 120, the output should be as follows: 4 | # 2, 2, 2, 3, 5 5 | 6 | num = int(input("Enter an integer: ")) 7 | halfNum = num // 2 8 | while num > 2: 9 | if num % halfNum == 0: 10 | print(str(num // halfNum), end='') 11 | num = halfNum 12 | halfNum = num // 2 13 | if num > 2: 14 | print(", ", end='') 15 | else: 16 | halfNum -= 1 17 | -------------------------------------------------------------------------------- /CH10/EX10.4.py: -------------------------------------------------------------------------------- 1 | # 10.4 (Analyze scores) Write a program that reads an unspecified number of scores and 2 | # determines how many scores are above or equal to the average and how many 3 | # scores are below the average. Assume the input numbers are separated by one 4 | # space in one line. 5 | 6 | s = input("Enter scores: ") 7 | lst = [int(x) for x in s.split()] 8 | avg = sum(lst) / len(lst) 9 | above = 0 10 | below = 0 11 | for x in lst: 12 | if x >= avg: 13 | above += 1 14 | else: 15 | below += 1 16 | print("There are", above, "value >= ", avg, "and", below, "<", avg) 17 | -------------------------------------------------------------------------------- /CH06/EX6.4.py: -------------------------------------------------------------------------------- 1 | # 6.4 (Display an integer reversed) Write the following function to display an integer in 2 | # reverse order: 3 | # def reverse(number): 4 | # For example, reverse(3456) displays 6543. Write a test program that prompts 5 | # the user to enter an integer and displays its reversal. 6 | 7 | def reverse(number): 8 | num = "" 9 | while number > 0: 10 | n1 = number % 10 11 | num = num + str(n1) 12 | number = number // 10 13 | 14 | return num 15 | 16 | 17 | num = eval(input("Enter a number: ")) 18 | print("The reverse of", num, "is", reverse(num)) 19 | -------------------------------------------------------------------------------- /CH08/EX8.6.py: -------------------------------------------------------------------------------- 1 | # 8.6 (Count the letters in a string) Write a function that counts the number of letters in 2 | # a string using the following header: 3 | # def countLetters(s): 4 | # Write a test program that prompts the user to enter a string and displays the number 5 | # of letters in the string. 6 | 7 | def countLetters(s): 8 | counter = 0 9 | for c in s: 10 | if c.isalpha(): 11 | counter += 1 12 | return counter 13 | 14 | 15 | def main(): 16 | s = input("Enter a string: ") 17 | n = countLetters(s) 18 | print("Number of letters is", n) 19 | 20 | main() -------------------------------------------------------------------------------- /CH02/EX2.25.py: -------------------------------------------------------------------------------- 1 | # (Turtle: draw a rectangle) Write a program that prompts the user to enter the 2 | # center of a rectangle, width, and height, and displays the rectangle, as shown in 3 | # Figure 2.4c. 4 | import turtle 5 | 6 | centerX, centerY, w, h = eval(input("Enter centerX,centerY, width, height: ")) 7 | 8 | turtle.penup() 9 | turtle.goto(centerX - 0.5 * w, centerY + 0.5 * h) 10 | turtle.pendown() 11 | turtle.forward(w) 12 | turtle.right(90) 13 | turtle.forward(h) 14 | turtle.right(90) 15 | turtle.forward(w) 16 | turtle.right(90) 17 | turtle.forward(h) 18 | 19 | turtle.done() # pause window 20 | -------------------------------------------------------------------------------- /CH13/EX13.8.py: -------------------------------------------------------------------------------- 1 | # 13.8 (Encrypt files) Encode the file by adding 5 to every byte in the file. Write a program 2 | # that prompts the user to enter an input filename and an output filename and 3 | # saves the encrypted version of the input file to the output file. 4 | 5 | infile = input("Enter input filename: ") 6 | outfile = input("Enter output filename: ") 7 | 8 | source = open(infile, 'r') 9 | destination = open(outfile, 'w') 10 | res = '' 11 | 12 | data = source.read() 13 | for i in range(len(data)): 14 | res += chr(ord(data[i])+5) 15 | 16 | 17 | destination.write(res) 18 | destination.close() -------------------------------------------------------------------------------- /CH15/EX15.11.py: -------------------------------------------------------------------------------- 1 | # 15.11 (Print the characters in a string reversely) Rewrite Exercise 15.9 using a helper 2 | # function to pass the substring for the high index to the function. The helper 3 | # function header is: 4 | # def reverseDisplayHelper(s, high): 5 | 6 | def reverseDisplay(value): 7 | reverseDisplayHelper(value, len(value) - 1) 8 | 9 | 10 | def reverseDisplayHelper(s, high): 11 | if high < 0: 12 | print() 13 | else: 14 | print(s[high], end='') 15 | reverseDisplayHelper(s, high - 1) 16 | 17 | 18 | val = input("Enter a string: ") 19 | reverseDisplay(val) 20 | -------------------------------------------------------------------------------- /CH10/EX10.5.py: -------------------------------------------------------------------------------- 1 | # 10.5 (Print distinct numbers) Write a program that reads in numbers separated by a 2 | # space in one line and displays distinct numbers (i.e., if a number appears multiple 3 | # times, it is displayed only once). (Hint: Read all the numbers and store 4 | # them in list1. Create a new list list2. Add a number in list1 to list2. 5 | # If the number is already in the list, ignore it.) 6 | 7 | n = input("Enter ten numbers: ") 8 | l1 = [int(x) for x in n.split()] 9 | l2 = [] 10 | for x in l1: 11 | if x not in l2: 12 | l2.append(x) 13 | 14 | print("The distinct numbers are:",l2) 15 | -------------------------------------------------------------------------------- /CH14/EX14.08.py: -------------------------------------------------------------------------------- 1 | # 14.8 (Display nonduplicate words in ascending order) Write a program that prompts 2 | # the user to enter a text file, reads words from the file, and displays all the nonduplicate 3 | # words in ascending order. 4 | 5 | filename = open(input("Enter text file: ")) 6 | 7 | lines = filename.readlines() 8 | lines = [line.lower() for line in lines] 9 | 10 | words = set() 11 | for line in lines: 12 | for word in line.split(): 13 | words.add(word) 14 | 15 | i = 0 16 | for x in words: 17 | print(x, end=' ') 18 | i += 1 19 | if i == 10: 20 | print() 21 | i = 0 22 | -------------------------------------------------------------------------------- /CH15/EX15.09.py: -------------------------------------------------------------------------------- 1 | # 15.9 (Print the characters in a string reversely) Write a recursive function that displays 2 | # a string reversely on the console using the following header: 3 | # def reverseDisplay(value): 4 | # For example, reverseDisplay("abcd") displays dcba. Write a test program 5 | # that prompts the user to enter a string and displays its reversal. 6 | 7 | def reverseDisplay(value): 8 | if value == '': 9 | print() 10 | else: 11 | print(value[-1], end='') 12 | reverseDisplay(value[:len(value) - 1]) 13 | 14 | 15 | val = input("Enter a string: ") 16 | reverseDisplay(val) 17 | -------------------------------------------------------------------------------- /CH04/EX4.3.py: -------------------------------------------------------------------------------- 1 | # (Algebra: solve 2*2 linear equations) You can use Cramer’s rule to solve the 2 | # following 2*2 system of linear equation: 3 | # Write a program that prompts the user to enter a, b, c, d, e, and f and display the 4 | # result. If ad – bc is 0, report that The equation has no solution. 5 | 6 | a, b, c, d, e, f = eval(input("Enter a, b, c, d, e, f: ")) 7 | 8 | if a * d - b * c == 0: 9 | print("The equation has no solution") 10 | else: 11 | x = (e * d - b * f) / (a * d - b * c) 12 | y = (a * f - e * c) / (a * d - b * c) 13 | print("x is", format(x, "0.1f"), "y is", format(y, "0.1f")) 14 | -------------------------------------------------------------------------------- /CH07/Time.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | 4 | class Time: 5 | def __init__(self): 6 | self.setTime(int(time.time())) 7 | 8 | def getHour(self): 9 | return self.__hour 10 | 11 | def getMinute(self): 12 | return self.__minute 13 | 14 | def getSecond(self): 15 | return self.__second 16 | 17 | def setTime(self, elapsedTime): 18 | self.__second = elapsedTime % 60 19 | 20 | totalMinutes = elapsedTime // 60 21 | 22 | self.__minute = totalMinutes % 60 23 | 24 | totalHours = totalMinutes // 60 25 | 26 | self.__hour = totalHours % 24 27 | -------------------------------------------------------------------------------- /CH15/EX15.08.py: -------------------------------------------------------------------------------- 1 | # 15.8 (Print the digits in an integer reversely) Write a recursive function that displays 2 | # an integer value reversely on the console using the following header: 3 | # def reverseDisplay(value): 4 | # For example, invoking reverseDisplay(12345) displays 54321. Write a test 5 | # program that prompts the user to enter an integer and displays its reversal. 6 | 7 | def reverseDisplay(value): 8 | if value == 0: 9 | print() 10 | else: 11 | print(value % 10, end='') 12 | reverseDisplay(value // 10) 13 | 14 | val = eval(input("Enter an integer: ")) 15 | reverseDisplay(val) -------------------------------------------------------------------------------- /CH04/EX4.14.py: -------------------------------------------------------------------------------- 1 | # 4.14 (Game: heads or tails) Write a program that lets the user guess whether a flipped 2 | # coin displays the head or the tail. The program randomly generates an integer 0 or 3 | # 1, which represents head or tail. The program prompts the user to enter a guess 4 | # and reports whether the guess is correct or incorrect. 5 | import random 6 | 7 | g = random.randint(0, 1) 8 | guess = int(input("Guess Head(0) or Tail(1): ")) 9 | 10 | if g == guess: 11 | print("You are right. The guess is ", end="Head" if g == 0 else "Tail") 12 | else: 13 | print("Wrong. The guess is ", end="Head" if g == 0 else "Tail") 14 | -------------------------------------------------------------------------------- /CH06/EX6.12.py: -------------------------------------------------------------------------------- 1 | # 6.12 (Display characters) Write a function that prints characters using the following 2 | # header: 3 | # def printChars(ch1, ch2, numberPerLine): 4 | # This function prints the characters between ch1 and ch2 with the specified 5 | # numbers per line. Write a test program that prints ten characters per line from 1 6 | # to Z. 7 | 8 | def printChars(ch1, ch2, numberPerLine): 9 | count = 1 10 | for i in range(ord(ch1), ord(ch2)+1): 11 | print(chr(i), end=" ") 12 | if count % numberPerLine == 0: 13 | print() 14 | count += 1 15 | 16 | 17 | printChars("1", "z", 10) 18 | -------------------------------------------------------------------------------- /CH06/EX6.14.py: -------------------------------------------------------------------------------- 1 | # 6.14 (Estimate ) can be computed using the following series: 2 | # Write a function that returns m(i) for a given i and write a test program that displays 3 | # the following table: 4 | # i m(i) 5 | # 1 4.0000 6 | # 101 3.1515 7 | # 201 3.1466 8 | # 301 3.1449 9 | # 401 3.1441 10 | # 501 3.1436 11 | # 601 3.1433 12 | # 701 3.1430 13 | # 801 3.1428 14 | # 901 3.1427 15 | from CH6Module import MyFunctions 16 | 17 | 18 | def main(): 19 | print("i\t\t\t m(i)") 20 | for i in range(1, 1001, 100): 21 | print(format(i, ".0f"), "\t\t", format(MyFunctions.computePi(i), "-3.4f")) 22 | 23 | 24 | main() 25 | -------------------------------------------------------------------------------- /CH06/EX6.18.py: -------------------------------------------------------------------------------- 1 | # 6.18 (Display matrix of 0s and 1s) Write a function that displays an n-by-n matrix using 2 | # the following header: 3 | # def printMatrix(n): 4 | # Each element is 0 or 1, which is generated randomly. Write a test program that 5 | # prompts the user to enter n and displays an n-by-n matrix. 6 | import random 7 | 8 | 9 | def printMatrix(n): 10 | for i in range(1, n * n + 1): 11 | x = random.randint(0, 1) 12 | print(x, end=' ') 13 | if i % n == 0: 14 | print() 15 | 16 | 17 | def main(): 18 | n = eval(input("Enter n: ")) 19 | printMatrix(n) 20 | 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /CH05/EX5.38.py: -------------------------------------------------------------------------------- 1 | # 5.38 (Simulation: clock countdown) You can use the time.sleep(seconds) function 2 | # in the time module to let the program pause for the specified seconds. Write a 3 | # program that prompts the user to enter the number of seconds, displays a message 4 | # at every second, and terminates when the time expires. 5 | import time 6 | 7 | seconds = eval(input("Enter the number of second: ")) 8 | 9 | while seconds > 0: 10 | time.sleep(1) 11 | if seconds > 1: 12 | print(str(seconds) + " seconds remaining") 13 | else: 14 | print("1 second remaining") 15 | seconds -= 1 16 | 17 | print("Stopped") -------------------------------------------------------------------------------- /CH05/EX5.51.py: -------------------------------------------------------------------------------- 1 | # 5.51 (Turtle: display a lattice) Write a program that displays an 18-by-18 lattice, as 2 | # shown in Figure 5.4c. 3 | import turtle 4 | 5 | turtle.penup() 6 | turtle.goto(-170,150) 7 | turtle.pendown() 8 | 9 | for i in range(18): 10 | turtle.forward(170) 11 | turtle.penup() 12 | turtle.goto(-170,turtle.ycor()-10) 13 | turtle.pendown() 14 | 15 | turtle.penup() 16 | turtle.goto(-170,150) 17 | turtle.pendown() 18 | turtle.right(90) 19 | 20 | for i in range(18): 21 | turtle.forward(170) 22 | turtle.penup() 23 | turtle.goto(turtle.xcor()+10,150) 24 | turtle.pendown() 25 | 26 | turtle.done() -------------------------------------------------------------------------------- /CH02/EX2.17.py: -------------------------------------------------------------------------------- 1 | # (Health application: compute BMI) Body mass index (BMI) is a measure of health 2 | # based on weight. It can be calculated by taking your weight in kilograms and 3 | # dividing it by the square of your height in meters. Write a program that prompts 4 | # the user to enter a weight in pounds and height in inches and displays the BMI. 5 | # Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. 6 | weight = eval(input("Enter weight in pounds:")) 7 | height = eval(input("Enter height in inches:")) 8 | weight = weight *0.45359237 9 | height = height *0.0254 10 | bmi = weight / height**2 11 | print("BMI is",bmi) -------------------------------------------------------------------------------- /CH05/EX5.7.py: -------------------------------------------------------------------------------- 1 | # 5.7 (Use trigonometric functions) Print the following table to display the sin value 2 | # and cos value of degrees from 0 to 360 with increments of 10 degrees. Round the 3 | # value to keep four digits after the decimal point. 4 | # Degree Sin Cos 5 | # 0 0.0000 1.0000 6 | # 10 0.1736 0.9848 7 | # ... 8 | # 350 -0.1736 0.9848 9 | # 360 0.0000 1.0000 10 | import math 11 | 12 | print(format("Degree","10s"), format("Sin", "8s"), "Cos") 13 | # 14 | for i in range(0, 361, 10): 15 | sin = math.sin(math.radians(i)) 16 | cos = math.cos(math.radians(i)) 17 | print(format(i,"3.0f"),format(sin,"13.4f"),format(cos,"8.4f")) 18 | -------------------------------------------------------------------------------- /CH13/EX13.1.py: -------------------------------------------------------------------------------- 1 | # 13.1 (Remove text) Write a program that removes all the occurrences of a specified 2 | # string from a text file. Your program should prompt the user to enter a filename 3 | # and a string to be removed. 4 | 5 | filename = input("Enter a filename: ").strip() 6 | string = input("Enter the string to be removed: ") 7 | file = open(filename, 'r') 8 | data = '' 9 | for line in file: 10 | data += line.replace(string, '') 11 | 12 | 13 | # I will create a new file instead of writing on the same file for future exercises usage. 14 | resFile = open('result', 'w') 15 | resFile.write(data) 16 | resFile.close() 17 | print("Done") 18 | -------------------------------------------------------------------------------- /CH02/EX2.14.py: -------------------------------------------------------------------------------- 1 | # (Geometry: area of a triangle) Write a program that prompts the user to enter the 2 | # three points (x1, y1), (x2, y2), and (x3, y3) of a triangle and displays its area. 3 | # The formula for computing the area of a triangle is 4 | 5 | x1, y1, x2, y2, x3, y3 = eval(input("Enter three points for a triangle: ")) 6 | 7 | side1 = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 8 | side2 = ((x1 - x3) ** 2 + (y1 - y3) ** 2) ** 0.5 9 | side3 = ((x2 - x3) ** 2 + (y2 - y3) ** 2) ** 0.5 10 | s = (side1 + side2 + side3) / 2 11 | area = (s * (s - side1) * (s - side2) * (s - side3)) ** 0.5 12 | print("The area of the triangle is", area) 13 | 14 | -------------------------------------------------------------------------------- /CH03/EX3.1.py: -------------------------------------------------------------------------------- 1 | # (Geometry: area of a pentagon) Write a program that prompts the user to enter the 2 | # length from the center of a pentagon to a vertex and computes the area of the pentagon, 3 | # as shown in the following figure.The formula for computing the area of a pentagon is where s is 4 | # the length of a side. The side can be computed using the formula 5 | # where r is the length from the center of a pentagon to a vertex. 6 | import math 7 | 8 | r = eval(input("Enter the length from the center to a vertex: ")) 9 | s = 2 * r * math.sin(math.pi / 5) 10 | area = 3 * math.sqrt(3) / 2 * s ** 2 11 | print("The area of the pentagon is", area) 12 | -------------------------------------------------------------------------------- /CH09/EX9.8.py: -------------------------------------------------------------------------------- 1 | # 9.8 (Display numbers in a triangular pattern) Write a program that displays numbers 2 | # in a triangular pattern, as shown in Figure 9.25d. The number of lines in the display 3 | # changes to fit the window as the window resizes. 4 | from tkinter import * 5 | 6 | window = Tk() 7 | width = 300 8 | height = 300 9 | canvas = Canvas(window, bg="white", width=width, height=height) 10 | canvas.pack() 11 | 12 | for i in range(1, 12): 13 | s = "" 14 | for j in range(1, i + 1): 15 | s += str(j) + " " 16 | canvas.create_text(width / 2, i * height / 12, text=s, fill="red") 17 | window.mainloop() # Create an event loop 18 | -------------------------------------------------------------------------------- /CH06/EX6.38.py: -------------------------------------------------------------------------------- 1 | # 6.38 (Turtle: draw a line) Write the following function that draws a line from point 2 | # (x1, y1) to (x2, y2) with color (default to black) and line size (default to 1). 3 | # def drawLine(x1, y1, x2, y2, color = "black", size = 1): 4 | import turtle 5 | 6 | 7 | def drawLine(x1, y1, x2, y2, color="black", size=1): 8 | turtle.color(color) 9 | turtle.pensize(size) 10 | turtle.penup() 11 | turtle.goto(x1, y1) 12 | turtle.pendown() 13 | turtle.goto(x2, y2) 14 | 15 | 16 | def main(): 17 | drawLine(10, 20, 70, 90, "blue", 5) 18 | drawLine(40, 20, -70, 50, "yellow", 8) 19 | turtle.done() 20 | 21 | main() -------------------------------------------------------------------------------- /CH06/EX6.24.py: -------------------------------------------------------------------------------- 1 | # 6.24 (Palindromic prime) A palindromic prime is a prime number that is also palindromic. 2 | # For example, 131 is a prime and also a palindromic prime, as are 313 and 3 | # 757. Write a program that displays the first 100 palindromic prime numbers. Display 4 | # 10 numbers per line and align the numbers properly, 5 | 6 | from CH6Module import MyFunctions 7 | 8 | counter = 1 9 | x = 2 10 | while counter < 101: 11 | if MyFunctions.isPrime(x) and MyFunctions.isPalindrome(x): 12 | if counter % 10 != 0: 13 | print(x, end=' ') 14 | else: 15 | print(x) 16 | counter += 1 17 | x += 1 18 | 19 | -------------------------------------------------------------------------------- /CH13/EX13.2.py: -------------------------------------------------------------------------------- 1 | # 13.2 (Count characters, words, and lines in a file) Write a program that will count the 2 | # number of characters, words, and lines in a file. Words are separated by a whitespace 3 | # character. Your program should prompt the user to enter a filename. 4 | 5 | filename = input("Enter a filename: ").strip() 6 | file = open(filename, 'r') 7 | 8 | lines = 0 9 | words = 0 10 | chars = 0 11 | 12 | for line in file: 13 | lines += 1 14 | words += len(line.split()) 15 | for c in line: 16 | if c != ' ': 17 | chars += 1 18 | 19 | print(chars, "characters") 20 | print(words, "words") 21 | print(lines, "Lines") 22 | -------------------------------------------------------------------------------- /CH06/EX6.25.py: -------------------------------------------------------------------------------- 1 | # 6.25 (Emirp) An emirp ( prime spelled backward) is a nonpalindromic prime number 2 | # whose reversal is also a prime. For example, both 17 and 71 are prime numbers, so 3 | # 17 and 71 are emirps. Write a program that displays the first 100 emirps. Display 4 | # 10 numbers per line and align the numbers properly, 5 | 6 | from CH6Module import MyFunctions 7 | 8 | counter = 1 9 | x = 2 10 | while counter < 101: 11 | if MyFunctions.isPrime(x) and MyFunctions.isPrime(MyFunctions.reverse(x)): 12 | if counter % 10 != 0: 13 | print(x, end=' ') 14 | else: 15 | print(x) 16 | counter += 1 17 | x += 1 -------------------------------------------------------------------------------- /CH13/EX13.5.py: -------------------------------------------------------------------------------- 1 | # 13.5 (Replace text) Write a program that replaces text in a file. Your program should 2 | # prompt the user to enter a filename, an old string, and a new string. 3 | 4 | filename = input("Enter a filename: ").strip() 5 | string = input("Enter the old string to be replaced: ") 6 | new = input("Enter the new string to replace the old string: ") 7 | file = open(filename, 'r') 8 | data = '' 9 | for line in file: 10 | data += line.replace(string, new) 11 | 12 | 13 | # I will create a new file instead of writing on the same file for future exercises usage. 14 | resFile = open('result', 'w') 15 | resFile.write(data) 16 | resFile.close() 17 | print("done") -------------------------------------------------------------------------------- /CH13/EX13.9.py: -------------------------------------------------------------------------------- 1 | # 13.9 (Decrypt files) Suppose a file is encrypted using the scheme in Exercise 13.8. 2 | # Write a program to decode an encrypted file. Your program should prompt the 3 | # user to enter an input filename and an output filename and should save the unencrypted 4 | # version of the input file to the output file. 5 | 6 | infile = input("Enter input filename: ") 7 | outfile = input("Enter output filename: ") 8 | 9 | source = open(infile, 'r') 10 | destination = open(outfile, 'w') 11 | res = '' 12 | 13 | data = source.read() 14 | for i in range(len(data)): 15 | res += chr(ord(data[i]) - 5) 16 | 17 | destination.write(res) 18 | destination.close() 19 | -------------------------------------------------------------------------------- /CH15/EX15.19.py: -------------------------------------------------------------------------------- 1 | # 15.19 (Decimal to binary) Write a recursive function that converts a decimal number 2 | # into a binary number as a string. The function header is as follows: 3 | # def decimalToBinary(value): 4 | # Write a test program that prompts the user to enter a decimal number and displays 5 | # its binary equivalent. 6 | 7 | bin = '' 8 | 9 | 10 | def decimalToBinary(value): 11 | global bin 12 | if value != 0: 13 | bin = str(value % 2) + bin 14 | value //= 2 15 | decimalToBinary(value) 16 | return bin 17 | 18 | d = int(input("Enter an integer: ")) 19 | print("The binary representation of", d, "is", decimalToBinary(d)) 20 | -------------------------------------------------------------------------------- /CH10/Ex10.10.py: -------------------------------------------------------------------------------- 1 | # 10.10 (Reverse a list) The reverse function in Section 10.8 reverses a list by copying it 2 | # to a new list. Rewrite the function that reverses the list passed in the argument and 3 | # returns this list. Write a test program that prompts the user to enter a list of numbers, 4 | # invokes the function to reverse the numbers, and displays the numbers. 5 | 6 | def reverse(lst): 7 | for i in range(len(lst)//2): 8 | lst[i], lst[len(lst) - 1 - i] = lst[len(lst) - 1 - i], lst[i] 9 | 10 | def main(): 11 | lst = input("Enter numbers: ").split() 12 | lst = [int(x) for x in lst] 13 | reverse(lst) 14 | print(lst) 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /CH04/EX4.33.py: -------------------------------------------------------------------------------- 1 | # 4.33 (Decimal to hex) Write a program that prompts the user to enter an integer 2 | # between 0 and 15 and displays its corresponding hex number. 3 | 4 | dec = int(input("Enter a decimal value (0 to 15): ")) 5 | 6 | if 0 <= dec < 10: 7 | print("The hex value is", dec) 8 | elif dec == 10: 9 | print("The hex value is A") 10 | elif dec == 11: 11 | print("The hex value is B") 12 | elif dec == 12: 13 | print("The hex value is C") 14 | elif dec == 13: 15 | print("The hex value is D") 16 | elif dec == 14: 17 | print("The hex value is E") 18 | elif dec == 15: 19 | print("The hex value is F") 20 | else: 21 | print("Invalid input") 22 | -------------------------------------------------------------------------------- /CH10/EX10.15.py: -------------------------------------------------------------------------------- 1 | # 10.15 (Sorted?) Write the following function that returns true if the list is already 2 | # sorted in increasing order: 3 | # def isSorted(lst): 4 | # Write a test program that prompts the user to enter a list and displays whether the 5 | # list is sorted or not. 6 | 7 | def isSorted(lst): 8 | for i in range(len(lst)): 9 | current = lst[i] 10 | for y in range(i + 1, len(lst)): 11 | if current > lst[y]: 12 | return False 13 | 14 | return True 15 | 16 | 17 | def main(): 18 | lst = input("Enter list: ").split() 19 | lst = [int(x) for x in lst] 20 | print(isSorted(lst)) 21 | 22 | 23 | main() 24 | -------------------------------------------------------------------------------- /CH15/EX15.14.py: -------------------------------------------------------------------------------- 1 | # 15.14 (Occurrences of a specified character in a string) Rewrite Exercise 15.10 using a 2 | # helper function to pass the substring of the high index to the function. The 3 | # helper function header is: 4 | # def countHelper(s, a, high): 5 | 6 | def count(s, a): 7 | return countHelper(s, a, len(s) - 1) 8 | 9 | 10 | def countHelper(s, a, high): 11 | result = 0 12 | if high >= 0: 13 | result = countHelper(s, a, high - 1) + (1 if s[high] == a else 0) 14 | 15 | return result 16 | 17 | 18 | s, a = input("Enter a string and a character to count: ").split() 19 | print("Character", a, "repeated", count(s.lower(), a.lower()), "times") 20 | -------------------------------------------------------------------------------- /CH06/EX6.11.py: -------------------------------------------------------------------------------- 1 | # 6.11 (Financial application: compute commissions) Write a function that computes 2 | # the commission, using the scheme in Exercise 5.39. The header of the function is: 3 | # def computeCommission(salesAmount): 4 | # Write a test program that displays the following table: 5 | # Sales Amount Commission 6 | # 10000 900.0 7 | # 15000 1500.0 8 | # ... 9 | # 95000 11100.0 10 | # 100000 11700.0 11 | from CH6Module import MyFunctions 12 | 13 | print("Sales Amount\t\tCommission") 14 | 15 | salesAmount = 10000 16 | for i in range(1, 20): 17 | print(salesAmount, format(" ", "14s"), format(MyFunctions.computeCommission(salesAmount), ".1f")) 18 | salesAmount += 5000 19 | -------------------------------------------------------------------------------- /CH11/EX11.51.py: -------------------------------------------------------------------------------- 1 | # 11.51 (Sort students) Write a program that prompts the user to enter the students’ 2 | # names and their scores on one line, and prints student names in increasing order 3 | # of their scores. (Hint: Create a list. Each element in the list is a sublist with two 4 | # elements: score and name. Apply the sort method to sort the list. This will sort 5 | # the list on scores.) 6 | 7 | lst = input("Enter students’ names and scores: ").split() 8 | studs = [] 9 | for i in range(0, len(lst), 2): 10 | studs.append([lst[i], int(lst[i + 1])]) 11 | 12 | studs.sort(key=lambda x: x[1]) 13 | for x in studs: 14 | print(format(x[0], '8s'), end='') 15 | print(x[1]) 16 | -------------------------------------------------------------------------------- /CH03/EX3.5.py: -------------------------------------------------------------------------------- 1 | # (Geometry: area of a regular polygon) A regular polygon is an n-sided polygon in 2 | # which all sides are of the same length and all angles have the same degree (i.e., the 3 | # polygon is both equilateral and equiangular). The formula for computing the area 4 | # of a regular polygon is 5 | # Here, s is the length of a side. Write a program that prompts the user to enter the 6 | # number of sides and their length of a regular polygon and displays its area. 7 | import math 8 | 9 | n = int(input("Enter the number of sides: ")) 10 | s = eval(input("Enter the side: ")) 11 | area = (n * s ** 2) / (4 * math.tan(math.pi / n)) 12 | print("The area of the polygon is", area) 13 | -------------------------------------------------------------------------------- /CH05/EX5.16.py: -------------------------------------------------------------------------------- 1 | # 5.16 (Compute the greatest common divisor) For Listing 5.8, another solution to find 2 | # the greatest common divisor of two integers n1 and n2 is as follows: First find d to 3 | # be the minimum of n1 and n2, and then check whether d, d - 1, d - 2, ..., 2, or 4 | # 1 is a divisor for both n1 and n2 in this order. The first such common divisor is the 5 | # greatest common divisor for n1 and n2. 6 | 7 | n1 = int(input("Enter first integer: ")) 8 | n2 = int(input("Enter second integer: ")) 9 | 10 | d = min(n1, n2) 11 | 12 | while True: 13 | if n1 % d == 0 and n2 % d == 0: 14 | break 15 | d -= 1 16 | 17 | print("The greatest common divisor is", d) 18 | -------------------------------------------------------------------------------- /CH15/EX15.07.py: -------------------------------------------------------------------------------- 1 | # 15.7 (Fibonacci series) Modify Listing 15.2 so that the program finds the number of 2 | # times the fib function is called. (Hint: Use a global variable and increment it 3 | # every time the function is called.) 4 | 5 | counter = 0 6 | 7 | 8 | def fib(index): 9 | global counter 10 | counter += 1 11 | if index == 0: # Base case 12 | return 0 13 | elif index == 1: # Base case 14 | return 1 15 | else: # Reduction and recursive calls 16 | return fib(index - 1) + fib(index - 2) 17 | 18 | 19 | index = eval(input("Enter an index for a Fibonacci number: ")) 20 | fib(index) 21 | print("The Fibonacci function is called", counter, "times") 22 | -------------------------------------------------------------------------------- /CH15/EX15.24.py: -------------------------------------------------------------------------------- 1 | # 15.24 (Number of files in a directory) Write a program that prompts the user to enter a 2 | # directory and displays the number of files in the directory. 3 | import os 4 | 5 | 6 | def getNumberOfFiles(path): 7 | size = 0 8 | if not os.path.isfile(path): 9 | list = os.listdir(path) 10 | for i in range(len(list)): 11 | size += getNumberOfFiles(path + "\\" + list[i]) 12 | else: 13 | size += 1 14 | 15 | return size 16 | 17 | 18 | path = input("Enter a directory or a file: ").strip() 19 | try: 20 | print("The number of files is " + str(getNumberOfFiles(path))) 21 | except: 22 | print("File or directory does not exist") 23 | -------------------------------------------------------------------------------- /CH02/EX2.18.py: -------------------------------------------------------------------------------- 1 | # (Current time) Listing 2.7, ShowCurrentTime.py, gives a program that displays the 2 | # current time in GMT. Revise the program so that it prompts the user to enter the 3 | # time zone in hours away from (offset to) GMT and displays the time in the specified 4 | # time zone. 5 | import time 6 | 7 | tzo = eval(input("Enter the time zone offset to GMT:")) 8 | currentTime = time.time() 9 | totalSeconds = int(currentTime) 10 | currentSecond = totalSeconds % 60 11 | totalMinutes = totalSeconds // 60 12 | currentMintute = totalMinutes % 60 13 | totalHours = totalMinutes // 60 14 | currentHour = totalHours % 24 15 | currentHour += tzo 16 | print(currentHour, ":", currentMintute, ":", currentSecond) 17 | -------------------------------------------------------------------------------- /CH05/EX5.28.py: -------------------------------------------------------------------------------- 1 | # 5.28 (Compute e) You can approximate e by using the following series: 2 | # Write a program that displays the e value for i = 10000, 20000, . . ., and 3 | # 100000. (Hint: Since , then is 4 | # Initialize e and item to be 1 and keep adding a new item to e. The new item is 5 | # the previous item divided by i for i = 2, 3, 4, . . . .) 6 | 7 | e = 1 8 | item = 1 9 | for i in range(1, 100000 + 1): 10 | item = item / i 11 | e += item 12 | 13 | if i == 10000 or i == 20000 or i == 30000 or i == 40000 or \ 14 | i == 50000 or i == 60000 or i == 70000 or i == 80000 or \ 15 | i == 90000 or i == 100000: 16 | print("The e is " + str(e) + " for i = " + str(i)) 17 | -------------------------------------------------------------------------------- /CH06/EX6.39.py: -------------------------------------------------------------------------------- 1 | # 6.39 (Turtle: draw a star) Write a program that draws a star, as shown in Figure 6.11b. 2 | # Use the drawLine function defined in Exercise 6.38. 3 | import turtle 4 | 5 | 6 | def drawLine(x1, y1, x2, y2, color="black", size=1): 7 | turtle.color(color) 8 | turtle.pensize(size) 9 | turtle.penup() 10 | turtle.goto(x1, y1) 11 | turtle.pendown() 12 | turtle.goto(x2, y2) 13 | 14 | 15 | def main(): 16 | drawLine(10, 50, 110, 50, "blue", 5) 17 | drawLine(110, 50, 20, 110, "blue", 5) 18 | drawLine(20, 110, 60, 20, "blue", 5) 19 | drawLine(60, 20, 100, 110, "blue", 5) 20 | drawLine(100, 110, 10, 50, "blue", 5) 21 | 22 | turtle.done() 23 | 24 | 25 | main() 26 | -------------------------------------------------------------------------------- /CH15/EX15.21.py: -------------------------------------------------------------------------------- 1 | # 15.21 (Binary to decimal) Write a recursive function that parses a binary number as a 2 | # string into a decimal integer. The function header is as follows: 3 | # def binaryToDecimal(binaryString): 4 | # Write a test program that prompts the user to enter a binary string and displays its 5 | # decimal equivalent. 6 | 7 | 8 | def binaryToDecimal(binaryString): 9 | return binaryToDecimalHelper(binaryString, 0, 0) 10 | 11 | 12 | def binaryToDecimalHelper(str, dec, i): 13 | if str != '': 14 | dec += int(str[-1]) * 2 ** i 15 | return binaryToDecimalHelper(str[:len(str) - 1], dec, i + 1) 16 | 17 | return dec 18 | 19 | 20 | print(binaryToDecimal(input("Enter binary string: "))) 21 | -------------------------------------------------------------------------------- /CH02/EX2.19.py: -------------------------------------------------------------------------------- 1 | # (Financial application: calculate future investment value) Write a program that 2 | # reads in an investment amount, the annual interest rate, and the number of years, 3 | # and displays the future investment value using the following formula: 4 | # For example, if you enter the amount 1000, an annual interest rate of 4.25%, 5 | # and the number of years as 1, the future investment value is 1043.33. 6 | 7 | investAmount = eval(input("Enter investment amount:")) 8 | annInterRate = eval(input("Enter annual interest rate:")) / (100 * 12) 9 | numOfYears = eval(input("Enter number of years:")) * 12 10 | 11 | futureVal = investAmount * (1 + annInterRate) ** numOfYears 12 | print("Accumulated value is", futureVal) 13 | -------------------------------------------------------------------------------- /CH06/EX6.6.py: -------------------------------------------------------------------------------- 1 | # 6.6 (Display patterns) Write a function to display a pattern as follows: 2 | # 1 3 | # 2 1 4 | # 3 2 1 5 | # ... 6 | # n n-1 ... 3 2 1 7 | # The function header is 8 | # def displayPattern(n): 9 | # Write a test program that prompts the user to enter a number n and invokes 10 | # displayPattern(n) to display the pattern. 11 | 12 | def displayPattern(n): 13 | for i in range(1, n + 1): 14 | for j in range(n, i - 1, -1): 15 | print(format(" ", "2s"), end=" ") 16 | for j in range(i, 0, -1): 17 | print(format(j, "2d"), end=" ") 18 | print() 19 | 20 | 21 | n = eval(input("Enter an integer: ")) 22 | displayPattern(n) 23 | -------------------------------------------------------------------------------- /CH11/EX11.29.py: -------------------------------------------------------------------------------- 1 | # 11.29 (Identical lists) The two-dimensional lists m1 and m2 are identical if they have the 2 | # same contents. Write a function that returns True if m1 and m2 are identical, using 3 | # the following header: 4 | # def equals(m1, m2): 5 | # Write a test program that prompts the user to enter two lists of integers and displays 6 | # whether the two are identical. 7 | 8 | def equals(m1, m2): 9 | for x in m1: 10 | if not(m2.__contains__(x)): 11 | return False 12 | 13 | return True 14 | 15 | m1 = input("Enter list1: ").split() 16 | m2 = input("Enter list2: ").split() 17 | 18 | if equals(m1, m2): 19 | print("Two lists are identical") 20 | else: 21 | print("Two lists are not identical") -------------------------------------------------------------------------------- /CH08/EX8.10.py: -------------------------------------------------------------------------------- 1 | # 8.10 (Decimal to binary) Write a function that parses a decimal number into a binary 2 | # number as a string. Use the function header: 3 | # def decimalToBinary(value): 4 | # Write a test program that prompts the user to enter a decimal integer value and displays 5 | # the corresponding binary value. 6 | 7 | def decimalToBinary(value): 8 | bin = '' 9 | while value > 0: 10 | if value % 2 == 0: 11 | bin = bin + '0' 12 | else: 13 | bin = bin + '1' 14 | value = value // 2 15 | bin = bin[::-1] 16 | return bin 17 | 18 | 19 | def main(): 20 | val = eval(input("Enter a decimal: ")) 21 | bin = decimalToBinary(val) 22 | print(bin) 23 | 24 | 25 | main() 26 | -------------------------------------------------------------------------------- /CH09/EX9.15.py: -------------------------------------------------------------------------------- 1 | # 9.15 (Display a still fan) Write a program that displays a still fan, as shown in 2 | # Figure 9.29a. 3 | from tkinter import * 4 | 5 | 6 | class MainGUI: 7 | def __init__(self): 8 | window = Tk() 9 | self.canvas = Canvas(window, bg="white", width=250, height=250) 10 | self.canvas.pack() 11 | self.canvas.create_arc(5, 60, 260, 220, start=20, extent=30, fill="red") 12 | self.canvas.create_arc(5, 60, 260, 220, start=100, extent=30, fill="red") 13 | self.canvas.create_arc(5, 60, 260, 220, start=200, extent=30, fill="red") 14 | self.canvas.create_arc(5, 60, 260, 220, start=280, extent=30, fill="red") 15 | 16 | window.mainloop() 17 | 18 | 19 | MainGUI() 20 | -------------------------------------------------------------------------------- /CH04/EX4.30.py: -------------------------------------------------------------------------------- 1 | # 4.30 (Current time) Revise Programming Exercise 2.18 to display the hour using a 12- 2 | # hour clock. 3 | import time 4 | 5 | offest = eval(input("Enter the time zone offset to GMT: ")) 6 | currentTime = time.time() 7 | totalSeconds = int(currentTime) 8 | currentSecond = totalSeconds % 60 9 | totalMinutes = totalSeconds // 60 10 | currentMintute = totalMinutes % 60 11 | totalHours = totalMinutes // 60 12 | currentHour = totalHours % 24 13 | currentHour += offest 14 | 15 | if currentHour > 12: 16 | currentHour %= 12 17 | print("The current time is", currentHour, ":", currentMintute, ":", currentSecond, "PM") 18 | else: 19 | print("The current time is", currentHour, ":", currentMintute, ":", currentSecond, "AM") 20 | -------------------------------------------------------------------------------- /CH04/EX4.34.py: -------------------------------------------------------------------------------- 1 | # 4.34 (Hex to heximal) Write a program that prompts the user to enter a hex character 2 | # and displays its corresponding heximal integer. 3 | 4 | hex = input("Enter a hex character: ") 5 | 6 | if '0' <= hex <= '9': 7 | print("The decimal value is", hex) 8 | elif hex.upper() == 'A': 9 | print("The decimal value is 10") 10 | elif hex.upper() == 'B': 11 | print("The decimal value is 11") 12 | elif hex.upper() == 'C': 13 | print("The decimal value is 12") 14 | elif hex.upper() == 'D': 15 | print("The decimal value is 13") 16 | elif hex.upper() == 'E': 17 | print("The decimal value is 14") 18 | elif hex.upper() == 'D': 19 | print("The decimal value is 15") 20 | else: 21 | print("Invalid input") 22 | -------------------------------------------------------------------------------- /CH14/EX14.11.py: -------------------------------------------------------------------------------- 1 | # 14.11 (Count consonants and vowels) Write a program that prompts the user to enter a 2 | # text filename and displays the number of vowels and consonants in the file. Use 3 | # a set to store the vowels A, E, I, O, and U. 4 | 5 | vowels = {'a', 'e', 'i', 'o', 'u'} 6 | count_vowels = 0 7 | count_consonants = 0 8 | file = open(input("Enter filename: ")) 9 | lines = file.readlines() 10 | for line in lines: 11 | for word in line.split(): 12 | for c in word.lower(): 13 | if c in vowels: 14 | count_vowels += 1 15 | else: 16 | count_consonants += 1 17 | 18 | print("Total number of vowels =", count_vowels) 19 | print("Total number of consonants =", count_consonants) 20 | -------------------------------------------------------------------------------- /CH11/EX11.1.py: -------------------------------------------------------------------------------- 1 | # 11.1 (Sum elements column by column) Write a function that returns the sum of all the 2 | # elements in a specified column in a matrix using the following header: 3 | # def sumColumn(m, columnIndex): 4 | # Write a test program that reads a 3*4 matrix and displays the sum of each column. 5 | 6 | def sumColumn(m, columnIndex): 7 | sum = 0 8 | for row in range(len(m)): 9 | sum += m[row][columnIndex] 10 | 11 | return sum 12 | 13 | 14 | m = [] 15 | 16 | for i in range(3): 17 | row = input("Enter a 3-by-4 matrix row for row " + str(i)+": ").split() 18 | m.append([float(x) for x in row]) 19 | 20 | for i in range(4): 21 | s = sumColumn(m, i) 22 | print("Sum of the elements for column", i, 'is', s) 23 | -------------------------------------------------------------------------------- /CH13/EX13.3.py: -------------------------------------------------------------------------------- 1 | # 13.3 (Process scores in a text file) Suppose that a text file contains an unspecified number 2 | # of scores. Write a program that reads the scores from the file and displays their 3 | # total and average. Scores are separated by blanks. Your program should prompt 4 | # the user to enter a filename. 5 | 6 | filename = input("Enter a filename: ").strip() 7 | file = open(filename, 'r') 8 | count = 0 9 | avg = 0 10 | sum = 0 11 | for line in file: 12 | scores = line.split() 13 | scores = [eval(s) for s in scores] 14 | count += len(scores) 15 | for s in scores: 16 | sum += s 17 | 18 | avg = sum / count 19 | 20 | print("There are", count, "scores") 21 | print("The total is", sum) 22 | print("The average is", avg) 23 | -------------------------------------------------------------------------------- /CH15/EX15.12.py: -------------------------------------------------------------------------------- 1 | # 15.12 (Find the largest number in a list) Write a recursive function that returns the 2 | # largest integer in a list. Write a test program that prompts the user to enter a list 3 | # of integers and displays the largest element. 4 | 5 | def getLargest(lst): 6 | max = lst[0] 7 | return getLargestHelper(lst, 0, len(lst), max) 8 | 9 | 10 | def getLargestHelper(lst, startIndx, endIndx, max): 11 | if startIndx == endIndx: 12 | return max 13 | 14 | if lst[startIndx] > max: 15 | max = lst[startIndx] 16 | 17 | return getLargestHelper(lst, startIndx + 1, endIndx, max) 18 | 19 | 20 | lst = input("Enter a list of integers: ").split() 21 | lst = [eval(x) for x in lst] 22 | 23 | print(getLargest(lst)) 24 | -------------------------------------------------------------------------------- /CH04/EX4.27.py: -------------------------------------------------------------------------------- 1 | # 4.27 (Geometry: points in triangle?) Suppose a right triangle is placed in a plane as 2 | # shown below. The right-angle point is at (0, 0), and the other two points are at 3 | # (200, 0), and (0, 100). Write a program that prompts the user to enter a point with 4 | # x- and y-coordinates and determines whether the point is inside the triangle. 5 | import math 6 | 7 | X1 = Y1 = 0 8 | X2 = 0 9 | Y2 = 100 10 | X3 = 200 11 | Y3 = 0 12 | x, y = eval(input("Enter a point's x- and y-coordinates: ")) 13 | 14 | # below hypotenuse and to the right of y axis and above x axis 15 | if x + 2 * y < X3 and 0 <= x <= X3 and 0 <= y <= Y2: 16 | print("The point is in the triangle ") 17 | else: 18 | print("The point is not in the triangle ") 19 | 20 | -------------------------------------------------------------------------------- /CH04/EX4.9.py: -------------------------------------------------------------------------------- 1 | # (Financial: compare costs) Suppose you shop for rice and find it in two differentsized 2 | # packages. You would like to write a program to compare the costs of the 3 | # packages. The program prompts the user to enter the weight and price of each 4 | # package and then displays the one with the better price. 5 | 6 | w1, p1 = eval(input("Enter weight and price for package 1: ")) 7 | w2, p2 = eval(input("Enter weight and price for package 2: ")) 8 | 9 | pricePerKilo1 = p1 / w1 10 | pricePerKilo2 = p2 / w2 11 | 12 | if pricePerKilo1 > pricePerKilo2: 13 | print("Package 1 has the better price.") 14 | elif pricePerKilo2 > pricePerKilo1: 15 | print("Package 2 has the better price.") 16 | else: 17 | print("Both have a good price") 18 | -------------------------------------------------------------------------------- /CH06/EX6.1.py: -------------------------------------------------------------------------------- 1 | # 6.1 (Math: pentagonal numbers) A pentagonal number is defined as for 2 | # and so on. So, the first few numbers are 1, 5, 12, 22, .... Write a 3 | # function with the following header that returns a pentagonal number: 4 | # def getPentagonalNumber(n): 5 | # Write a test program that uses this function to display the first 100 pentagonal 6 | # numbers with 10 numbers on each line. 7 | 8 | def getPentagonalNumber(n): 9 | num = n * (3 * n - 1) / 2 10 | return int(num) 11 | 12 | 13 | def main(): 14 | count = 1 15 | for i in range(1, 101): 16 | print(getPentagonalNumber(i), end=' ') 17 | if count % 10 == 0: 18 | print() 19 | count = 0 20 | 21 | count += 1 22 | 23 | 24 | main() 25 | -------------------------------------------------------------------------------- /CH08/EX8.8.py: -------------------------------------------------------------------------------- 1 | # 8.8 (Binary to decimal) Write a function that parses a binary number as a string into a 2 | # decimal integer. Use the function header: 3 | # def binaryToDecimal(binaryString): 4 | # For example, binary string 10001 is 17 5 | # So, binaryToDecimal("10001") returns 17. 6 | # Write a test program that prompts the user to enter a binary string and displays the 7 | # corresponding decimal integer value. 8 | 9 | def binaryToDecimal(binaryString): 10 | bin = binaryString[::-1] 11 | dec = 0 12 | for i in range(len(bin)): 13 | dec = dec + int(bin[i]) * 2 ** i 14 | return dec 15 | 16 | 17 | def main(): 18 | bin = input("Enter binary string: ") 19 | dec = binaryToDecimal(bin) 20 | print(dec) 21 | 22 | 23 | main() 24 | -------------------------------------------------------------------------------- /CH10/EX10.12.py: -------------------------------------------------------------------------------- 1 | # 10.12 (Compute GCD) Write a function that returns the greatest common divisor 2 | # (GCD) of integers in a list. Use the following function header: 3 | # def gcd(numbers): 4 | # Write a test program that prompts the user to enter five numbers, invokes the 5 | # function to find the GCD of these numbers, and displays the GCD. 6 | 7 | def gcd(numbers): 8 | gcd = min(numbers) 9 | i = 0 10 | while True: 11 | if numbers[i] % gcd != 0: 12 | gcd-=1 13 | i = 0 14 | else: i+=1 15 | if i == len(numbers): 16 | break 17 | return gcd 18 | 19 | def main(): 20 | lst = input("Enter numbers: ").split() 21 | lst = [int(x) for x in lst] 22 | print(gcd(lst)) 23 | 24 | main() -------------------------------------------------------------------------------- /CH05/EX5.10.py: -------------------------------------------------------------------------------- 1 | # 5.10 (Find the highest score) Write a program that prompts the user to enter the number 2 | # of students and each student’s score, and displays the highest score. Assume that 3 | # the input is stored in a file named score.txt, and the program obtains the input from 4 | # the file. 5 | 6 | studentName = "" 7 | studentScore = 0 8 | maxScore = -1 9 | maxName = "" 10 | while True: 11 | studentName = input("Enter a student name(x to stop): ") 12 | if studentName.lower() == "x": 13 | break 14 | studentScore = eval(input("Enter a student score: ")) 15 | 16 | if studentScore > maxScore: 17 | maxScore = studentScore 18 | maxName = studentName 19 | 20 | print("Top student is", maxName, "with score", maxScore) 21 | -------------------------------------------------------------------------------- /CH15/EX15.20.py: -------------------------------------------------------------------------------- 1 | # 15.20 (Decimal to hex) Write a recursive function that converts a decimal number into 2 | # a hex number as a string. The function header is as follows: 3 | # def decimalToHex(value): 4 | # Write a test program that prompts the user to enter a decimal number and displays 5 | # its hex equivalent. 6 | 7 | hex = '' 8 | 9 | 10 | def decimalToHex(value): 11 | global hex 12 | if value != 0: 13 | h = value % 16 14 | if h >= 10: 15 | hex = chr(h + 55) + hex 16 | else: 17 | hex = str(h) + hex 18 | 19 | value //= 16 20 | decimalToHex(value) 21 | return hex 22 | 23 | 24 | d = int(input("Enter an integer: ")) 25 | print("The hexadecimal representation of", d, "is", decimalToHex(d)) 26 | -------------------------------------------------------------------------------- /CH08/EX8.13.py: -------------------------------------------------------------------------------- 1 | # 8.13 (Longest common prefix) Write a method that returns the longest common prefix 2 | # of two strings. For example, the longest common prefix of distance and 3 | # disinfection is dis. The header of the method is: 4 | # def prefix(s1, s2) 5 | # If the two strings have no common prefix, the method returns an empty string. 6 | # Write a main method that prompts the user to enter two strings and displays their 7 | # common prefix. 8 | 9 | def prefix(s1, s2): 10 | for i in range(len(s1)): 11 | s = s1[0:len(s1) - i] 12 | if str(s2).startswith(str(s)): 13 | return s 14 | 15 | return "" 16 | 17 | 18 | def main(): 19 | s1, s2 = input("Enter two strings: ").split() 20 | print(prefix(s1, s2)) 21 | 22 | 23 | main() 24 | -------------------------------------------------------------------------------- /CH10/Ex10.11.py: -------------------------------------------------------------------------------- 1 | # 10.11 (Random number chooser) You can shuffle a list using random.shuffle(lst). 2 | # Write your own function without using random.shuffle(lst) to shuffle a list 3 | # and return the list. Use the following function header: 4 | # def shuffle(lst): 5 | # Write a test program that prompts the user to enter a list of numbers, invokes the 6 | # function to shuffle the numbers, and displays the numbers. 7 | import random 8 | 9 | 10 | def shuffle(lst): 11 | for q in range(len(lst)): 12 | i, p = random.randint(0, len(lst)-1), random.randint(0, len(lst)-1) 13 | lst[i], lst[p] = lst[p], lst[i] 14 | 15 | def main(): 16 | lst = input("Enter numbers: ").split() 17 | lst = [int(x) for x in lst] 18 | shuffle(lst) 19 | print(lst) 20 | 21 | main() -------------------------------------------------------------------------------- /CH02/EX2.23.py: -------------------------------------------------------------------------------- 1 | # (Turtle: draw four circles) Write a program that prompts the user to enter the 2 | # radius and draws four circles in the center of the screen, as shown in Figure 2.4a. 3 | import turtle 4 | 5 | radius = eval(input("Enter radius: ")) 6 | turtle.penup() 7 | turtle.goto(-radius / 2, -radius * 2 + radius) 8 | turtle.pendown() 9 | turtle.circle(radius) 10 | 11 | turtle.penup() 12 | turtle.goto(-radius / 2, -radius * 4 + radius) 13 | turtle.pendown() 14 | turtle.circle(radius) 15 | 16 | turtle.penup() 17 | turtle.goto(-radius * 2.5, -radius * 2 + radius) 18 | turtle.pendown() 19 | turtle.circle(radius) 20 | 21 | turtle.penup() 22 | turtle.goto(-radius * 2.5, -radius * 4 + radius) 23 | turtle.pendown() 24 | turtle.circle(radius) 25 | 26 | turtle.done() # pause turtle window 27 | -------------------------------------------------------------------------------- /CH10/EX10.25.py: -------------------------------------------------------------------------------- 1 | # 10.25 (Game: pick four cards) Write a program that picks four cards from a deck of 52 2 | # cards and computes their sum. An ace, king, queen, and jack represent 1, 13, 12, 3 | # and 11, respectively. Your program should display the number of picks that yield 4 | # the sum of 24. 5 | import random 6 | 7 | cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] 8 | picks = [] 9 | s = 0 10 | while True: 11 | for i in range(4): 12 | p = random.randint(1, 13) 13 | picks.append(p) 14 | 15 | s = sum(picks) 16 | if s == 24: 17 | print('The picks are', "(", cards[picks[0] - 1], ",", 18 | cards[picks[1] - 1], ",", cards[picks[2] - 1], ",", cards[picks[3] - 1], ")") 19 | break 20 | picks = [] 21 | -------------------------------------------------------------------------------- /CH05/EX5.6.py: -------------------------------------------------------------------------------- 1 | # 5.6 (Conversion from miles to kilometers and kilometers to miles) Write a program 2 | # that displays the following two tables side by side (note that 1 mile is 1.609 kilometers 3 | # and that 1 kilometer is .621 mile): 4 | 5 | MILES_TO_KILOMETRE = 1.609 6 | KILOMETRE_TO_MILE = 0.621 7 | mile = 1 8 | kilometre = 20 9 | print(format("Mile", "8s"), format("Kilometre", "8s"), format(" ", "2s"), format("|", "5s") 10 | , format("Kilometre", "12s"), "Mile") 11 | 12 | while mile < 11: 13 | miles = kilometre * KILOMETRE_TO_MILE 14 | kilometres = mile * MILES_TO_KILOMETRE 15 | 16 | print(format(mile, "-2.0f"), format(kilometres, "12.3f"), format(" ", "5s"), "|" 17 | , format(kilometre, "6.0f"), format(miles, "16.3f")) 18 | mile += 1 19 | kilometre += 5 20 | -------------------------------------------------------------------------------- /CH02/EX2.8.py: -------------------------------------------------------------------------------- 1 | # (Science: calculate energy) Write a program that calculates the energy needed to 2 | # heat water from an initial temperature to a final temperature. Your program should 3 | # prompt the user to enter the amount of water in kilograms and the initial and final 4 | # temperatures of the water. The formula to compute the energy is 5 | # Q = M * (finalTemperature – initialTemperature) * 4184 6 | # where M is the weight of water in kilograms, temperatures are in degrees Celsius, 7 | # and energy Q is measured in joules. 8 | 9 | water = eval(input("Enter the amount of water in kilograms:")) 10 | initTemp = eval(input("Enter the initial temperature:")) 11 | finTemp = eval(input("Enter the final temperature:")) 12 | q = water * (finTemp - initTemp) * 4184 13 | print("The energy needed is",q) 14 | -------------------------------------------------------------------------------- /CH04/EX4.24.py: -------------------------------------------------------------------------------- 1 | # 4.24 (Game: pick a card ) Write a program that simulates picking a card from a deck of 2 | # 52 cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3 | # Jack, Queen, King) and suit (Clubs, Diamonds, Hearts, Spades) of the card. 4 | import random 5 | 6 | shape = random.randint(1, 4) 7 | 8 | if shape == 1: 9 | shape = "Clubs" 10 | elif shape == 2: 11 | shape = "Diamonds" 12 | elif shape == 3: 13 | shape = "Hearts" 14 | elif shape == 4: 15 | shape = "Spades" 16 | 17 | rank = random.randint(1, 13) 18 | 19 | if rank == 1: 20 | rank = "Ace" 21 | elif rank == 11: 22 | rank = "Jack" 23 | elif rank == 12: 24 | rank = "Queen" 25 | elif rank == 13: 26 | rank = "King" 27 | 28 | print("The card you picked is the", rank, "of", shape) 29 | -------------------------------------------------------------------------------- /CH09/EX9.11.py: -------------------------------------------------------------------------------- 1 | # 9.11 (Display a clock) Write a program that displays a clock to show the current time, 2 | # as shown in Figure 9.27a. To obtain the current time, use the datetime class in 3 | # Supplement II.B. 4 | from datetime import datetime 5 | from tkinter import * 6 | 7 | now = datetime.now().strftime("%H:%M:%S") 8 | 9 | window = Tk() 10 | c = Canvas(window, width=500, height=500, bg="white") 11 | c.pack() 12 | c.create_oval(50, 50, 450, 450) 13 | c.create_text(250, 50, text="12") 14 | c.create_text(50, 250, text="9") 15 | c.create_text(450, 250, text="3") 16 | c.create_text(250, 450, text="6") 17 | c.create_text(250, 470, text=now) 18 | c.create_line(250,250,100,160,width=2) 19 | c.create_line(250,250,230,360,width="3") 20 | c.create_line(250,250,300,300) 21 | 22 | 23 | window.mainloop() 24 | -------------------------------------------------------------------------------- /CH15/EX15.13.py: -------------------------------------------------------------------------------- 1 | # 15.13 (Find the number of uppercase letters in a string) Write a recursive function to 2 | # return the number of uppercase letters in a string using the following function 3 | # headers: 4 | # def countUppercase(s): 5 | # def countUppercaseHelper(s, high): 6 | # Write a test program that prompts the user to enter a string and displays the number 7 | # of uppercase letters in the string. 8 | 9 | count = 0 10 | 11 | 12 | def countUppercase(s): 13 | return countUppercaseHelper(s, len(s)) 14 | 15 | 16 | def countUppercaseHelper(s, high): 17 | global count 18 | if s == '': 19 | return count 20 | 21 | if s[0].isupper(): 22 | count += 1 23 | return countUppercaseHelper(s[1:high], high) 24 | 25 | 26 | print(countUppercase(input("Enter a string: "))) 27 | -------------------------------------------------------------------------------- /CH08/EX8.16.py: -------------------------------------------------------------------------------- 1 | # 8.16 (Business: check ISBN-13) ISBN-13 is a new standard for identifying books. It 2 | # uses 13 digits: d1d2d3d4d5d6d7d8d9d10d11d12d13. The last digit, is a checksum, 3 | # which is calculated from the other digits using the following formula: 4 | # 10 - (d1 + 3d2 + d3 + 3d4 + d5 + 3d6 + d7 + 3d8 + d9 + 3d10 + d11 + 3d12) % 10 5 | # If the checksum is 10, replace it with 0. Your program should read the input as a 6 | # string. 7 | 8 | digits = input("Enter the first 12 digits of an ISBN-13 as a string: ") 9 | 10 | checksum = 0 11 | for i in range(12): 12 | checksum += int(digits[i]) * (1 if i % 2 == 0 else 3) 13 | 14 | checksum = 10 - checksum % 10 15 | if checksum == 10: 16 | digits += '0' 17 | else: 18 | digits += str(checksum) 19 | 20 | print("The ISBN-13 number is", digits) 21 | -------------------------------------------------------------------------------- /CH10/EX10.27.py: -------------------------------------------------------------------------------- 1 | # 10.27 (Pattern recognition: four consecutive equal numbers) Write the following function 2 | # that tests whether the list has four consecutive numbers with the same value: 3 | # def isConsecutiveFour(values): 4 | # Write a test program that prompts the user to enter a series of integers and reports 5 | # whether the series contains four consecutive numbers with the same value. 6 | 7 | def isConsecutiveFour(values): 8 | if len(values) != len(set(values)): # there are duplicates 9 | return False 10 | diff = values[0] - values[1] 11 | for i in range(len(values) - 1): 12 | if values[i] - values[i + 1] != diff: 13 | return False 14 | return True 15 | 16 | 17 | values = [int(x) for x in input("Enter numbers: ").split()] 18 | print(isConsecutiveFour(values)) 19 | -------------------------------------------------------------------------------- /CH15/EX15.10.py: -------------------------------------------------------------------------------- 1 | # 15.10 (Occurrences of a specified character in a string) Write a recursive function that 2 | # finds the number of occurrences of a specified letter in a string using the following 3 | # function header. 4 | # def count(s, a): 5 | # For example, count("Welcome", 'e') returns 2. Write a test program that 6 | # prompts the user to enter a string and a character, and displays the number of 7 | # occurrences for the character in the string. 8 | 9 | counter = 0 10 | 11 | 12 | def count(s, a): 13 | global counter 14 | if s == '': 15 | return counter 16 | elif s[0] == a: 17 | counter += 1 18 | return count(s[1:len(s)], a) 19 | 20 | 21 | s, a = input("Enter a string and a character to count: ").split() 22 | print("Character", a, "repeated", count(s.lower(), a.lower()), "times") 23 | -------------------------------------------------------------------------------- /CH05/EX5.42.py: -------------------------------------------------------------------------------- 1 | # 5.42 (Monte Carlo simulation) A square is divided into four smaller regions as shown in 2 | # (a). If you throw a dart into the square one million times, what is the probability for 3 | # the dart to fall into an odd-numbered region? Write a program to simulate the 4 | # process and display the result. (Hint: Place the center of the square in the center of 5 | # a coordinate system, as shown in (b). Randomly generate a point in the square and 6 | # count the number of times for a point to fall in an odd-numbered region.) 7 | import random 8 | 9 | counter = 0 10 | print("Throwing the dart....") 11 | for i in range(0, 1000000): 12 | if random.randint(1, 4) % 2 != 0: 13 | counter += 1 14 | 15 | prob = counter / 1000000 16 | print("The probability that the dart fall in an odd numbered region is", prob) 17 | -------------------------------------------------------------------------------- /CH07/Fan.py: -------------------------------------------------------------------------------- 1 | class Fan: 2 | SLOW = 1 3 | MEDIUM = 2 4 | FAST = 3 5 | 6 | def __init__(self, speed=SLOW, radius=5, color="Blue", on=False): 7 | self.__speed = speed 8 | self.__radius = radius 9 | self.__color = color 10 | self.__on = on 11 | 12 | def getSpeed(self): 13 | return self.__speed 14 | 15 | def setSpeed(self, speed): 16 | self.__speed = speed 17 | 18 | def getRadius(self): 19 | return self.__radius 20 | 21 | def setRadius(self, radius): 22 | self.__radius = radius 23 | 24 | def getColor(self): 25 | return self.__color 26 | 27 | def setColor(self, color): 28 | self.__color = color 29 | 30 | def isOn(self): 31 | return self.__on 32 | 33 | def setOn(self, on): 34 | self.__on = on 35 | -------------------------------------------------------------------------------- /CH07/Stock.py: -------------------------------------------------------------------------------- 1 | class Stock: 2 | def __init__(self, symbol, name, previousClosingPrice, currentPrice): 3 | self.__symbol = symbol 4 | self.__name = name 5 | self.__previousClosingPrice = previousClosingPrice 6 | self.__currentPrice = currentPrice 7 | 8 | def getStockName(self): 9 | return self.__name 10 | 11 | def getStockSymbol(self): 12 | return self.__symbol 13 | 14 | def getPreviousStockPrice(self): 15 | return self.__previousClosingPrice 16 | 17 | def setPreviousStockPrice(self, previousClosingPrice): 18 | self.__previousClosingPrice = previousClosingPrice 19 | 20 | def getStockCurrentPrice(self): 21 | return self.__currentPrice 22 | 23 | def setStockCurrentPrice(self, currentPrice): 24 | self.__currentPrice = currentPrice 25 | -------------------------------------------------------------------------------- /CH11/EX11.2.py: -------------------------------------------------------------------------------- 1 | # 11.2 (Sum the major diagonal in a matrix) Write a function that sums all the numbers 2 | # of the major diagonal in an matrix of integers using the following header: 3 | # def sumMajorDiagonal(m): 4 | # The major diagonal is the diagonal that runs from the top left corner to the bottom 5 | # right corner in the square matrix. Write a test program that reads a matrix and 6 | # displays the sum of all its elements on the major diagonal. 7 | 8 | def sumMajorDiagonal(m): 9 | sum = 0 10 | for i in range(len(m)): 11 | sum += m[i][i] 12 | 13 | return sum 14 | 15 | 16 | m = [] 17 | for i in range(4): 18 | row = input("Enter a 4-by-4 matrix row for row " + str(i + 1) + ": ").split() 19 | m.append([float(x) for x in row]) 20 | 21 | print("Sum of the elements in the major diagonal is", sumMajorDiagonal(m)) 22 | -------------------------------------------------------------------------------- /CH11/EX11.27.py: -------------------------------------------------------------------------------- 1 | # 11.27 (Column sorting) Implement the following function to sort the columns in a twodimensional 2 | # list. A new list is returned and the original list is intact. 3 | # def sortColumns(m): 4 | # Write a test program that prompts the user to enter a 3 * 3matrix of numbers and 5 | # displays a new column-sorted matrix. 6 | 7 | def sortColumns(m): 8 | m1 = [[x[i] for x in m] for i in range(len(m))] 9 | 10 | for col in m1: 11 | col.sort() 12 | 13 | m1 = [[x[i] for x in m1] for i in range(len(m1))] 14 | return m1 15 | 16 | 17 | print('Enter a 3-by-3 matrix row by row: ') 18 | m = [] 19 | for i in range(3): 20 | m.append(input().split()) 21 | 22 | print('The column-sorted list is ') 23 | res = sortColumns(m) 24 | for r in res: 25 | for v in r: 26 | print(v, end=' ') 27 | print() 28 | 29 | -------------------------------------------------------------------------------- /CH05/EX5.39.py: -------------------------------------------------------------------------------- 1 | # 5.39 (Financial application: find the sales amount) You have just started a sales job in a 2 | # department store. Your pay consists of a base salary plus a commission. The base 3 | # salary is $5,000. The following scheme shows how to determine the commission rate: 4 | # Your goal is to earn $30,000 a year. Write a program that finds out the minimum 5 | # amount of sales you have to generate in order to make $30,000. 6 | 7 | salesAmount = 1.01 8 | commission = 0 9 | while commission < 5000: 10 | if salesAmount > 10000: 11 | commission = 5000 * 1.08 + 5000 * 1.1 + (salesAmount - 10000) * 1.12 12 | 13 | elif salesAmount >= 5001: 14 | commission = 5000 * 1.08 + (salesAmount - 5000) * 1.10 15 | 16 | else: 17 | commission = salesAmount * 1.08 18 | salesAmount += 1.01 19 | print(salesAmount) 20 | -------------------------------------------------------------------------------- /CH06/EX6.17.py: -------------------------------------------------------------------------------- 1 | # *6.17 (The MyTriangle module) Create a module named MyTriangle that contains 2 | # the following two functions: 3 | # # Returns true if the sum of any two sides is 4 | # # greater than the third side. 5 | # def isValid(side1, side2, side3): 6 | # # Returns the area of the triangle. 7 | # def area(side1, side2, side3): 8 | # Write a test program that reads three sides for a triangle and computes the area if the 9 | # input is valid. Otherwise, it displays that the input is invalid. The formula for computing 10 | # the area of a triangle is given in Exercise 2.14. 11 | from CH6Module import MyFunctions 12 | 13 | s1, s2, s3 = eval(input("Enter three sides in double: ")) 14 | 15 | if MyFunctions.isValid(s1, s2, s3): 16 | print("The area of the triangle is", MyFunctions.area(s1, s2, s3)) 17 | else: 18 | print("Input is invalid") 19 | -------------------------------------------------------------------------------- /CH11/EX11.28.py: -------------------------------------------------------------------------------- 1 | # 11.28 (Strictly identical lists) The two-dimensional lists m1 and m2 are strictly identical 2 | # if their corresponding elements are equal. Write a function that returns True if m1 3 | # and m2 are strictly identical, using the following header: 4 | # def equals(m1, m2): 5 | # Write a test program that prompts the user to enter two lists of integers and 6 | # displays whether the two are strictly identical. 7 | 8 | def main(): 9 | m1 = input("Enter list1: ").split() 10 | m2 = input("Enter list2: ").split() 11 | 12 | if equals(m1, m2): 13 | print("Two lists are strictly identical") 14 | else: 15 | print("Two lists are not strictly identical") 16 | 17 | 18 | def equals(m1, m2): 19 | for i in range(len(m1)): 20 | if m1[i] != m2[i]: return False 21 | 22 | return True 23 | 24 | 25 | main() -------------------------------------------------------------------------------- /CH07/QuadraticEquation.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class QuadraticEquation: 4 | def __init__(self, a, b, c): 5 | self.__a = a 6 | self.__b = b 7 | self.__c = c 8 | 9 | def getA(self): 10 | return self.__a 11 | 12 | def getB(self): 13 | return self.__b 14 | 15 | def getC(self): 16 | return self.__c 17 | 18 | def getDiscriminant(self): 19 | return self.__b * self.__b - 4 * self.__a * self.__c 20 | 21 | def getRoot1(self): 22 | if self.getDiscriminant() < 0: 23 | return 0 24 | else: 25 | return (-self.__b + self.getDiscriminant()) / (2 * self.__a) 26 | 27 | def getRoot2(self): 28 | if self.getDiscriminant() < 0: 29 | return 0 30 | else: 31 | return (-self.__b - self.getDiscriminant()) / (2 * self.__a) -------------------------------------------------------------------------------- /CH10/EX10.8.py: -------------------------------------------------------------------------------- 1 | # 10.8 (Find the index of the smallest element) Write a function that returns the index of 2 | # the smallest element in a list of integers. If the number of such elements is greater 3 | # than 1, return the smallest index. Use the following header: 4 | # def indexOfSmallestElement(lst): 5 | # Write a test program that prompts the user to enter a list of numbers, invokes this 6 | # function to return the index of the smallest element, and displays the index. 7 | 8 | def indexOfSmallestElement(lst): 9 | smallest = float("inf") 10 | smallestInd = 0 11 | for x in range(len(lst)): 12 | if lst[x] < smallest: 13 | smallest = lst[x] 14 | smallestInd = x 15 | return smallestInd 16 | 17 | 18 | def main(): 19 | lst = [0, 3, 4, 5, 7, 8] 20 | print(indexOfSmallestElement(lst)) 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /CH05/EX5.20.py: -------------------------------------------------------------------------------- 1 | # 5.20 (Display four patterns using loops) Use nested loops that display the following 2 | # patterns in four separate programs: 3 | 4 | N = 7 5 | # Pattern A 6 | for i in range(1, N): 7 | for j in range(1, i + 1): 8 | print(j, end=" ") 9 | print() 10 | 11 | print("\n") 12 | 13 | # Patten B 14 | x = N 15 | for i in range(1, N): 16 | for j in range(1, x): 17 | print(j, end=" ") 18 | print() 19 | x -= 1 20 | 21 | print("\n") 22 | 23 | # Pattern C 24 | for i in range(1, N): 25 | for j in range(N, i - 1, -1): 26 | print(" ", end=' ') 27 | for k in range(i, 0, -1): 28 | print(k, end=' ') 29 | print() 30 | 31 | print("\n") 32 | 33 | # Pattern D 34 | y = N 35 | for i in range(1, N): 36 | for j in range(y - 1, 0, -1): 37 | print(j, end=" ") 38 | print() 39 | y -= 1 40 | -------------------------------------------------------------------------------- /CH06/EX6.35.py: -------------------------------------------------------------------------------- 1 | # 6.35 (Compute the probability) Use the functions in RandomCharacter in Listing 2 | # 6.11 to generate 10,000 uppercase letters and count the occurrence of A. 3 | 4 | from random import randint # import randint 5 | 6 | 7 | # Generate a random character between ch1 and ch2 8 | def getRandomCharacter(ch1, ch2): 9 | return chr(randint(ord(ch1), ord(ch2))) 10 | 11 | 12 | # Generate a random uppercase letter 13 | def getRandomUpperCaseLetter(): 14 | return getRandomCharacter('A', 'Z') 15 | 16 | 17 | def main(): 18 | counter = 0 19 | for i in range(10000): 20 | c = getRandomUpperCaseLetter() 21 | print(c, end=' ') 22 | if c == 'A': 23 | counter += 1 24 | if (i + 1) % 10 == 0: 25 | print() 26 | 27 | print("\nNumber of generated As is", counter) 28 | 29 | 30 | main() 31 | -------------------------------------------------------------------------------- /CH05/EX5.47.py: -------------------------------------------------------------------------------- 1 | # 5.47 (Turtle: draw random balls) Write a program that displays 10 random balls in 2 | # a rectangle with width 120 and height 100, centered at (0, 0), as shown in 3 | # Figure 5.3a. 4 | import random 5 | import turtle 6 | 7 | WIDTH = 120 8 | HEIGHT = 100 9 | count = 0 10 | turtle.penup() 11 | turtle.goto(0 - WIDTH / 2, 0 - HEIGHT / 2) 12 | turtle.pendown() 13 | 14 | for i in range(4): 15 | if i % 2 == 0: 16 | turtle.forward(WIDTH) 17 | 18 | else: 19 | turtle.forward(HEIGHT) 20 | turtle.left(90) 21 | 22 | while count < 10: 23 | turtle.penup() 24 | x = random.randint(-WIDTH / 2, WIDTH / 2) 25 | y = random.randint(-HEIGHT / 2, HEIGHT / 2) 26 | turtle.goto(x, y) 27 | turtle.pendown() 28 | turtle.dot(5, "red") 29 | count += 1 30 | 31 | turtle.ht() # Same as turtle.hideturtle() 32 | turtle.done() 33 | -------------------------------------------------------------------------------- /CH09/EX9.5.py: -------------------------------------------------------------------------------- 1 | # 9.5 (Game: display a checkerboard) Write a program that displays a checkerboard in 2 | # which each white and black cell is a canvas with a background of black or white, 3 | # as shown in Figure 9.25a. 4 | 5 | from tkinter import * 6 | 7 | window = Tk() 8 | c = Canvas(window, width=320, height=320) 9 | c.pack() 10 | color = 0 11 | x1 = y1 = 3 12 | x2 = y2 = 43 13 | for i in range(8): 14 | for j in range(8): 15 | if color == 0: 16 | c.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") 17 | color = 1 18 | elif color == 1: 19 | c.create_rectangle(x1, y1, x2, y2, fill="black") 20 | color = 0 21 | x1 = x2 22 | x2 = x1 + 40 23 | y1 = y2 24 | y2 = y1 + 40 25 | x1 = 3 26 | x2 = 43 27 | color = 1 if color == 0 else 0 28 | 29 | window.mainloop() 30 | -------------------------------------------------------------------------------- /CH06/EX6.5.py: -------------------------------------------------------------------------------- 1 | # 6.5 (Sort three numbers) Write the following function to display three numbers in 2 | # increasing order: 3 | # def displaySortedNumbers(num1, num2, num3): 4 | # Write a test program that prompts the user to enter three numbers and invokes the 5 | # function to display them in increasing order. 6 | 7 | 8 | def displaySortedNumbers(num1, num2, num3): 9 | max1 = max(num1, num2, num3) 10 | max2 = max3 = 0 11 | if max1 == num1: 12 | max2 = max(num2, num3) 13 | max3 = min(num2, num3) 14 | elif max1 == num2: 15 | max2 = max(num1, num3) 16 | max3 = min(num1, num3) 17 | else: 18 | max2 = max(num1, num2) 19 | max3 = min(num1, num2) 20 | 21 | print("The sorted numbers are", max3, max2, max1) 22 | 23 | 24 | n1, n2, n3 = eval(input("Enter three numbers: ")) 25 | displaySortedNumbers(n1, n2, n3) 26 | -------------------------------------------------------------------------------- /CH10/EX10.13.py: -------------------------------------------------------------------------------- 1 | # 10.13 (Eliminate duplicates) Write a function that returns a new list by eliminating the 2 | # duplicate values in the list. Use the following function header: 3 | # def eliminateDuplicates(lst): 4 | # Write a test program that reads in a list of integers, invokes the function, and displays 5 | # the result. 6 | 7 | def eliminateDuplicates(lst): 8 | size = len(lst) 9 | i = 0 10 | while i < size: 11 | current = lst[i] 12 | x = i + 1 13 | while x < size: 14 | if current == lst[x]: 15 | lst.pop(x) 16 | size = len(lst) 17 | x += 1 18 | i += 1 19 | 20 | 21 | def main(): 22 | lst = input("Enter ten numbers: ").split() 23 | lst = [int(x) for x in lst] 24 | eliminateDuplicates(lst) 25 | print("The distinct numbers are:", lst) 26 | 27 | 28 | main() 29 | -------------------------------------------------------------------------------- /CH05/EX5.11.py: -------------------------------------------------------------------------------- 1 | # 5.11 (Find the two highest scores) Write a program that prompts the user to enter the 2 | # number of students and each student’s score, and displays the highest and secondhighest 3 | # scores. 4 | 5 | maxScroe1 = 0 6 | maxScore2 = -1 7 | maxName1 = maxName2 = "" 8 | 9 | while True: 10 | name = input("Enter Student's name(x to Stop): ") 11 | if name.lower() == "x": 12 | break 13 | score = eval(input("Enter student's score: ")) 14 | 15 | if score > maxScroe1 and score > maxScore2: 16 | maxScore2 = maxScroe1 17 | maxScroe1 = score 18 | maxName2 = maxName1 19 | maxName1 = name 20 | elif score > maxScore2: 21 | maxScore2 = score 22 | maxName2 = name 23 | 24 | print("Top Student is", maxName1, "with score", maxScroe1) 25 | print("The 2nd Top student is", maxName2, "with score", maxScore2) 26 | -------------------------------------------------------------------------------- /CH07/EX7.8.py: -------------------------------------------------------------------------------- 1 | # 7.8 (Stopwatch) Design a class named StopWatch. The class contains: 2 | # ■ The private data fields startTime and endTime with get methods. 3 | # ■ A constructor that initializes startTime with the current time. 4 | # ■ A method named start() that resets the startTime to the current time. 5 | # ■ A method named stop() that sets the endTime to the current time. 6 | # ■ A method named getElapsedTime() that returns the elapsed time for the 7 | # stop watch in milliseconds. 8 | # Draw the UML diagram for the class, and then implement the class. Write a test 9 | # program that measures the execution time of adding numbers from 1 to 10 | # 1,000,000. 11 | from CH7.StopWatch import StopWatch 12 | 13 | sw = StopWatch() 14 | res = 0 15 | sw.start() 16 | for i in range(1, 1000001): 17 | res += i 18 | 19 | sw.end() 20 | print("The elapsed time is:", sw.getElapsedTime()) 21 | -------------------------------------------------------------------------------- /CH04/EX4.28.py: -------------------------------------------------------------------------------- 1 | # 4.28 (Geometry: two rectangles) Write a program that prompts the user to enter the 2 | # center x-, y-coordinates, width, and height of two rectangles and determines 3 | # whether the second rectangle is inside the first or overlaps with the first, as shown 4 | # in Figure 4.10. Test your program to cover all cases. 5 | 6 | x1, y1, w1, h1 = eval(input("Enter r1's center x-, y-coordinates, width, and height: ")) 7 | x2, y2, w2, h2 = eval(input("Enter r2's center x-, y-coordinates, width, and height: ")) 8 | 9 | xDistance = x1 - x2 if x1 - x2 >= 0 else x2 - x1 10 | yDistance = y1 - y2 if y1 - y2 >= 0 else y2 - y1 11 | 12 | if xDistance <= (w1 - w2) / 2 and yDistance <= (h1 - h2) / 2: 13 | print("r2 is inside r1") 14 | elif xDistance <= (w1 + w2) / 2 and yDistance <= (h1 + h2) / 2: 15 | print("r2 overlaps r1") 16 | else: 17 | print("r2 does not overlap r1") 18 | -------------------------------------------------------------------------------- /CH02/EX2.11.py: -------------------------------------------------------------------------------- 1 | # (Financial application: investment amount) Suppose you want to deposit a 2 | # certain amount of money into a savings account with a fixed annual interest rate. 3 | # What amount do you need to deposit in order to have $5,000 in the account after 4 | # three years? The initial deposit amount can be obtained using the following 5 | # formula: 6 | # Write a program that prompts the user to enter final account value, annual interest 7 | # rate in percent, and the number of years, and displays the initial deposit amount. 8 | 9 | finAccVal = eval(input("Enter final account value: ")) 10 | monthInterRatePerc = eval(input("Enter annual interest rate in percent: ")) / (100 * 12) 11 | numOfMonths = eval(input("Enter number of years: ")) * 12 12 | initialDepositAmount = finAccVal / (1 + monthInterRatePerc) ** numOfMonths 13 | print("Initial deposit value is", initialDepositAmount) 14 | -------------------------------------------------------------------------------- /CH07/EX7.9.py: -------------------------------------------------------------------------------- 1 | # 7.9 (Geometry: intersection) Suppose two line segments intersect. The two endpoints 2 | # for the first line segment are (x1, y1) and (x2, y2) and for the second line segment 3 | # are (x3, y3) and (x4, y4). Write a program that prompts the user to enter these 4 | # four endpoints and displays the intersecting point. (Hint: Use the 5 | # LinearEquation class from Exercise 7.7.) 6 | from CH7.LinearEquation import LinearEquation 7 | 8 | x1, y1, x2, y2 = eval(input("Enter the endpoints of the first line segment: ")) 9 | x3, y3, x4, y4 = eval(input("Enter the endpoints of the second line segment: ")) 10 | 11 | a = y1 - y2 12 | b = -x1 + x2 13 | c = y3 - y4 14 | d = -x3 + x4 15 | e = -y1 * (x1 - x2) + (y1 - y2) * x1 16 | f = -y3 * (x3 - x4) + (y3 - y4) * x3 17 | 18 | eq = LinearEquation(a, b, c, d, e, f) 19 | print("The intersecting point is: (", eq.getX(), ",", eq.getY(), ")") 20 | -------------------------------------------------------------------------------- /CH09/EX9.33.py: -------------------------------------------------------------------------------- 1 | # 9.33 (Draw an arrow line) Write a program that randomly draws an arrow line when 2 | # the Draw a Random Arrow Line button is clicked, as shown in Figure 9.40b. 3 | import random 4 | from tkinter import * 5 | 6 | 7 | class MainGUI: 8 | def __init__(self): 9 | window = Tk() 10 | self.canvas = Canvas(window, width=300, height=300, bg="white") 11 | self.canvas.pack() 12 | btn = Button(window, text="Draw a random arrow line", command=self.draw) 13 | btn.pack() 14 | 15 | window.mainloop() 16 | 17 | def draw(self): 18 | self.canvas.delete("line") 19 | x1 = random.randint(5, 290) 20 | y1 = random.randint(5, 290) 21 | x2 = random.randint(5, 290) 22 | y2 = random.randint(5, 290) 23 | self.canvas.create_line(x1, y1, x2, y2, arrow=LAST, tags="line") 24 | 25 | 26 | MainGUI() 27 | -------------------------------------------------------------------------------- /CH06/EX6.2.py: -------------------------------------------------------------------------------- 1 | # 6.2 (Sum the digits in an integer) Write a function that computes the sum of the digits 2 | # in an integer. Use the following function header: 3 | # def sumDigits(n): 4 | # For example, sumDigits(234) returns 9 (Hint: Use the % operator 5 | # to extract digits, and the // operator to remove the extracted digit. For instance, to 6 | # extract 4 from 234, use 234 % 10 To remove 4 from 234, use 234 // 10 7 | # Use a loop to repeatedly extract and remove the digits until all the digits 8 | # are extracted.) Write a test program that prompts the user to enter an integer and 9 | # displays the sum of all its digits. 10 | 11 | def sumDigits(n): 12 | sum = 0 13 | while n > 0: 14 | n1 = n % 10 15 | sum += n1 16 | n = n // 10 17 | 18 | return sum 19 | 20 | 21 | n = eval(input("Enter an integer: ")) 22 | print("The sum of the digits is", sumDigits(n)) 23 | -------------------------------------------------------------------------------- /CH08/EX8.4.py: -------------------------------------------------------------------------------- 1 | # 8.4 (Occurrences of a specified character) Write a function that finds the number of 2 | # occurrences of a specified character in a string using the following header: 3 | # def count(s, ch): 4 | # The str class has the count method. Implement your method without using the 5 | # count method. For example, count("Welcome", 'e') returns 2. Write a test 6 | # program that prompts the user to enter a string followed by a character and displays 7 | # the number of occurrences of the character in the string. 8 | 9 | def main(): 10 | str = input("Enter a string: ") 11 | ch = input("Enter a character to count: ") 12 | n = count(str, ch) 13 | print("Character", ch, "occurred", n, "times in", str) 14 | 15 | 16 | def count(s, ch): 17 | counter = 0 18 | for c in s: 19 | if c == ch: 20 | counter += 1 21 | return counter 22 | 23 | 24 | main() 25 | -------------------------------------------------------------------------------- /CH13/EX13.4.py: -------------------------------------------------------------------------------- 1 | # 13.4 (Write/read data) Write a program that writes 100 integers created randomly into 2 | # a file. Integers are separated by a space in the file. Read the data back from the file 3 | # and display the sorted data. Your program should prompt the user to enter a filename. 4 | # If the file already exists, do not override it. 5 | import os 6 | import random 7 | import sys 8 | 9 | filename = input("Enter a filename: ").strip() 10 | 11 | if os.path.isfile(filename): 12 | print("The file already exists") 13 | sys.exit() 14 | 15 | file = open(filename, 'w') 16 | 17 | for i in range(100): 18 | file.write(str(random.randint(0, 100)) + " ") 19 | 20 | file.close() 21 | 22 | file1 = open(filename, 'r') 23 | nums = [] 24 | for line in file1: 25 | nums = line.split() 26 | 27 | nums = [eval(x) for x in nums] 28 | nums.sort() 29 | for n in nums: 30 | print(n, end=' ') 31 | -------------------------------------------------------------------------------- /CH15/EX15.02.py: -------------------------------------------------------------------------------- 1 | # 15.2 (Fibonacci numbers) Rewrite the fib function in Listing 15.2 using iterations. 2 | # (Hint: To compute fib(n) without recursion, you need to obtain fib(n - 2) 3 | # and fib(n - 1) first.) Let f0 and f1 denote the two previous Fibonacci numbers. 4 | # The current Fibonacci number would then be f0 + f1. The algorithm can be 5 | # described as follows: 6 | # f0 = 0 # For fibs(0) 7 | # f1 = 1 # For fib(1) 8 | # for i in range(2, n + 1): 9 | # currentFib = f0 + f1 10 | # f0 = f1 11 | # f1 = currentFib 12 | # # After the loop, currentFib is fib(n) 13 | # Write a test program that prompts the user to enter an index and displays its 14 | # Fibonacci number. 15 | 16 | n = eval(input("Enter a number: ")) 17 | 18 | f0 = 0 19 | f1 = 1 20 | fib = 0 21 | for i in range(2, n + 1): 22 | fib = f0 + f1 23 | f0 = f1 24 | f1 = fib 25 | 26 | print("The Fibonacci of", n, "is", fib) 27 | -------------------------------------------------------------------------------- /CH15/EX15.15.py: -------------------------------------------------------------------------------- 1 | # 15.15 (Find the number of uppercase letters in a list) Write a recursive function to 2 | # return the number of uppercase letters in a list of characters. You need to define 3 | # the following two functions. The second one is a recursive helper function. 4 | # def count(chars): 5 | # def countHelper(chars, high): 6 | # Write a test program that prompts the user to enter a list of characters in one line 7 | # and displays the number of uppercase letters in the list. 8 | 9 | def count(chars): 10 | return countHelper(chars, len(chars) - 1) 11 | 12 | 13 | def countHelper(chars, high): 14 | count = 0 15 | if high >= 0: 16 | count = countHelper(chars, high - 1) + (1 if chars[high].isupper() else 0) 17 | 18 | return count 19 | 20 | 21 | chars = input("Enter a list of chars: ").split() 22 | 23 | print("The number of capital case letters is: ", count(chars)) 24 | -------------------------------------------------------------------------------- /CH04/EX4.6.py: -------------------------------------------------------------------------------- 1 | # (Health application: BMI ) Revise Listing 4.6, ComputeBMI.py, to let users enter 2 | # their weight in pounds and their height in feet and inches. For example, if a person 3 | # is 5 feet and 10 inches, you will enter 5 for feet and 10 for inches. 4 | 5 | KILOGRAMS_PER_POUND = 0.45359237 6 | METERS_PER_INCH = 0.0254 7 | 8 | weight = eval(input("Enter weight in pounds: ")) 9 | feet = eval(input("Enter feet: ")) 10 | inches = eval(input("Enter inches: ")) 11 | 12 | weightInKilograms = weight * KILOGRAMS_PER_POUND 13 | totalHeightInches = feet * 12 + inches 14 | heightInMeters = totalHeightInches * METERS_PER_INCH 15 | 16 | bmi = weightInKilograms / (heightInMeters * heightInMeters) 17 | 18 | print("BMI is", bmi) 19 | if bmi < 18.5: 20 | print("Underweight") 21 | elif bmi < 25: 22 | print("Normal") 23 | elif bmi < 30: 24 | print("Overweight") 25 | else: 26 | print("Obese") 27 | -------------------------------------------------------------------------------- /CH09/EX9.6.py: -------------------------------------------------------------------------------- 1 | # 9.6 (Game: display a tic-tac-toe board ) Write a program that displays nine labels. 2 | # Each label may display an image icon for an X or an image icon for an O, as 3 | # shown in Figure 9.25b. What to display is randomly decided. Use the 4 | # random.randint(0, 1) function to generate an integer 0 or 1, which corresponds 5 | # to displaying a cross image (X) icon or a not image (O) icon. The cross and 6 | # not images are in the files x.gif and o.gif. 7 | import random 8 | from tkinter import * 9 | 10 | window = Tk() 11 | x = PhotoImage(file="x.gif") 12 | o = PhotoImage(file="o.gif") 13 | for i in range(3): 14 | for j in range(3): 15 | r = random.randint(0, 1) 16 | if r == 0: 17 | Label(window, image=x).grid(row=i + 1, column=j + 1) 18 | elif r == 1: 19 | Label(window, image=o).grid(row=i + 1, column=j + 1) 20 | 21 | window.mainloop() 22 | -------------------------------------------------------------------------------- /CH04/EX4.20.py: -------------------------------------------------------------------------------- 1 | # 4.20 (Science: wind-chill temperature) Exercise 2.9 gives a formula to compute the 2 | # wind-chill temperature. The formula is valid for temperatures in the range 3 | # between and 41°F and for wind speed greater than or equal to 2. Write a 4 | # program that prompts the user to enter a temperature and a wind speed. The program 5 | # displays the wind-chill temperature if the input is valid; otherwise, it displays 6 | # a message indicating whether the temperature and/or wind speed is invalid. 7 | 8 | temp, windSpeed = eval(input("Enter temperature in Fahrenheit and wind speed: ")) 9 | 10 | if (temp < -58 or temp > 41) or (windSpeed < 2): 11 | print("The temperature and/or wind speed is invalid.") 12 | else: 13 | windChill = 35.74 + 0.6215 * temp - 35.75 * windSpeed ** 0.16 + 0.4275 * temp * windSpeed ** 0.16 14 | print("The wind chill temprature is", format(windChill, "0.2f")) 15 | -------------------------------------------------------------------------------- /CH05/EX5.5.py: -------------------------------------------------------------------------------- 1 | # 5.5 (Conversion from kilograms to pounds and pounds to kilograms) Write a program 2 | # that displays the following two tables side by side (note that 1 kilogram is 2.2 3 | # pounds and that 1 pound is .45 kilograms): 4 | # Kilograms Pounds | Pounds Kilograms 5 | # 1 2.2 | 20 9.09 6 | # 3 6.6 | 25 11.36 7 | # ... 8 | # 197 433.4 | 510 231.82 9 | # 199 437.8 | 515 235.09 10 | 11 | pound = 20 12 | kilogram = 1 13 | KILOGRAM_TO_POUND = 2.2 14 | POUND_TO_KILOGRAM = 0.45 15 | print(format("Kilograms", "15s"), format("Pounds", "8s"), format("|", "5s"), format("Pounds", "12s"), "Kilograms") 16 | while kilogram < 200: 17 | pounds = kilogram * KILOGRAM_TO_POUND 18 | kilograms = pound * POUND_TO_KILOGRAM 19 | print(kilogram, format(pounds, "18.1f"), format(" ", "3s"), 20 | format("|", "2s"), format(pound, "6.0f"), format(kilograms, "16.2f")) 21 | kilogram += 2 22 | pound += 5 23 | -------------------------------------------------------------------------------- /CH08/EX8.2.py: -------------------------------------------------------------------------------- 1 | # 8.2 (Check substrings) You can check whether a string is a substring of another string 2 | # by using the find method in the str class. Write your own function to implement 3 | # find. Write a program that prompts the user to enter two strings and then checks 4 | # whether the first string is a substring of the second string. 5 | 6 | def main(): 7 | s1 = input("First string: ") 8 | s2 = input("Second string: ") 9 | f = find(s1, s2) 10 | if f == -1: 11 | print(s1, "is not substring of", s2) 12 | else: 13 | print(s1, "is substring of", s2, "at index", f) 14 | 15 | 16 | def find(s1, s2): 17 | l1 = len(s1) 18 | l2 = len(s2) 19 | 20 | start = 0 21 | while l1 <= l2: 22 | if s1 != s2[start:start + l1]: 23 | start += 1 24 | l2 -= 1 25 | else: 26 | return start 27 | return -1 28 | 29 | 30 | main() 31 | -------------------------------------------------------------------------------- /CH07/RegularPolygon.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class RegularPolygon: 5 | def __init__(self,n=3,side=1,x=0,y=0,): 6 | self.__n= n 7 | self.__side = side 8 | self.__x = x 9 | self.__y = y 10 | 11 | def getN(self): 12 | return self.__n 13 | 14 | def setN(self,n): 15 | self.__n = n 16 | 17 | def getSide(self): 18 | return self.__side 19 | 20 | def setSide(self,side): 21 | self.__side = side 22 | 23 | def getX(self): 24 | return self.__x 25 | 26 | def setX(self,x): 27 | self.__x = x 28 | 29 | def getY(self): 30 | return self.__y 31 | 32 | def setY(self,y): 33 | self.__y = y 34 | 35 | def getPerimeter(self): 36 | return self.__n * self.__side 37 | 38 | def getArea(self): 39 | a = (self.__n*(self.__side ** 2)) / (4 * math.tan(math.pi/self.__n)) 40 | return a -------------------------------------------------------------------------------- /CH04/EX4.31.py: -------------------------------------------------------------------------------- 1 | # 4.31 (Geometry: point position) Given a directed line from point p0(x0, y0) to p1(x1, 2 | # y1), you can use the following condition to decide whether a point p2(x2, y2) is 3 | # on the left side of the line, on the right side of the line, or on the same line (see 4 | # Figure 4.12): 5 | # Write a program that prompts the user to enter the x- and y-coordinates for the 6 | # three points p0, p1, and p2 and displays whether p2 is on the left side of the line 7 | # from p0 to p1, on the right side, or on the same line. 8 | 9 | x0, y0, x1, y1, x2, y2 = eval(input("Enter coordinates for the three points p0, p1, and p2: ")) 10 | 11 | d = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) 12 | 13 | if d > 0: 14 | print("p2 is on the left side of the line from p0 to p1") 15 | elif d == 0: 16 | print("p2 is on the same line from p0 to p1") 17 | else: 18 | print("p2 is on the right side of the line from p0 to p1") 19 | -------------------------------------------------------------------------------- /CH11/EX11.25.py: -------------------------------------------------------------------------------- 1 | # 11.25 (Markov matrix) An n*n matrix is called a positive Markov matrix if each element 2 | # is positive and the sum of the elements in each column is 1. Write the following 3 | # function to check whether a matrix is a Markov matrix: 4 | # def isMarkovMatrix(m): 5 | # Write a test program that prompts the user to enter a 3*3 matrix of numbers and 6 | # tests whether it is a Markov matrix. 7 | 8 | def isMarkovMatrix(m): 9 | for row in m: 10 | for e in row: 11 | if e < 0: 12 | return False 13 | if sum(row) != 1: 14 | return False 15 | 16 | return True 17 | 18 | 19 | mat = [] 20 | print('Enter a 3-by-3 matrix row by row:') 21 | for i in range(3): 22 | x = input().split() 23 | x = [eval(r) for r in x] 24 | mat.append(x) 25 | 26 | 27 | transpose = [[row[i] for row in mat] for i in range(len(mat))] 28 | 29 | print(isMarkovMatrix(transpose)) -------------------------------------------------------------------------------- /CH04/EX4.32.py: -------------------------------------------------------------------------------- 1 | # 4.32 (Geometry: point on line segment) Exercise 4.31 shows how to test whether a point 2 | # is on an unbounded line. Revise Exercise 4.31 to test whether a point is on a line 3 | # segment. Write a program that prompts the user to enter the x- and y-coordinates 4 | # for the three points p0, p1, and p2 and displays whether p2 is on the line segment 5 | # from p0 to p1. 6 | x0, y0, x1, y1, x2, y2 = eval(input("Enter coordinates for the three points p0, p1, and p2: ")) 7 | 8 | d = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0) 9 | 10 | if d <= 0.0000000001 and ((x0 <= x2 and x2 <= x1) or (x0 >= x2 and x2 >= x1)): 11 | print("(", x2, ", ", y2, ") is on the line segment from" 12 | , "(", x0, ", ", y0, ") to ", "(", 13 | x1, ", ", y1, ")") 14 | else: 15 | print("(", x2, ", ", y2, ") is not on the line segment from" 16 | , "(", x0, ", ", y0, ") to ", "(" 17 | , x1, ", ", y1, ")") 18 | -------------------------------------------------------------------------------- /CH05/EX5.23.py: -------------------------------------------------------------------------------- 1 | # 5.23 (Financial application: compare loans with various interest rates) Write a program 2 | # that lets the user enter the loan amount and loan period in number of years 3 | # and displays the monthly and total payments for each interest rate starting from 4 | # 5% to 8%, with an increment of 1/8. 5 | import math 6 | 7 | loanAmount = eval(input("Loan Amount: ")) 8 | years = eval(input("Number of Years: ")) 9 | 10 | print("Interest Rate Monthly Payment Total Payment") 11 | i = years 12 | counter = 1 13 | while counter < 26: 14 | print(format(i, "-5.3f"), end='%') 15 | print(" ", end='') 16 | monthlyInterestRate = i / 1200 17 | monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / math.pow(1 + monthlyInterestRate, years * 12)) 18 | print(format(monthlyPayment, "-5.2f"), end='') 19 | print(format((monthlyPayment * 12) * years, "-24.2f")) 20 | counter += 1 21 | i += .125 22 | -------------------------------------------------------------------------------- /CH04/EX4.22.py: -------------------------------------------------------------------------------- 1 | # 4.22 (Geometry: point in a circle?) Write a program that prompts the user to enter a 2 | # point (x, y) and checks whether the point is within the circle centered at (0, 0) with 3 | # radius 10. For example, (4, 5) is inside the circle and (9, 9) is outside the circle, as 4 | # shown in Figure 4.8a. 5 | # (Hint: A point is in the circle if its distance to (0, 0) is less than or equal to 10. The 6 | # formula for computing the distance is Test your 7 | # program to cover all cases.) Two sample runs are shown next. 8 | import math 9 | RADIUS = 10 10 | X = Y = 0 11 | x, y = eval(input("Enter a point with two coordinates: ")) 12 | 13 | distance = math.sqrt((x - X) ** 2 + (y - Y) ** 2) 14 | 15 | if RADIUS >= distance >= -RADIUS: 16 | print("Point (", format(x, "0.1f"), ",", format(y, "0.1f"), ")", "is in the circle") 17 | else: 18 | print("Point (", format(x, "0.1f"), ",", format(y, "0.1f"), ")", "is not in the circle") 19 | -------------------------------------------------------------------------------- /CH08/EX8.3.py: -------------------------------------------------------------------------------- 1 | # 8.3 (Check password) Some Web sites impose certain rules for passwords. Write a 2 | # function that checks whether a string is a valid password. Suppose the password 3 | # rules are as follows: 4 | # ■ A password must have at least eight characters. 5 | # ■ A password must consist of only letters and digits. 6 | # ■ A password must contain at least two digits. 7 | # Write a program that prompts the user to enter a password and displays valid 8 | # password if the rules are followed or invalid password otherwise. 9 | 10 | digitNum = 0 11 | charNum = 0 12 | password = input("Enter a password: ") 13 | for c in password[:]: 14 | if c.isdigit(): 15 | digitNum += 1 16 | elif c.isalpha(): 17 | charNum += 1 18 | else: 19 | print("Invalid password!") 20 | exit() 21 | break 22 | if digitNum >= 2 and charNum >= 8: 23 | print("Valid password") 24 | else: 25 | print("Invalid password!") -------------------------------------------------------------------------------- /CH11/EX11.4.py: -------------------------------------------------------------------------------- 1 | # 11.4 (Compute the weekly hours for each employee) Suppose the weekly hours for all 2 | # employees are stored in a table. Each row records an employee’s seven-day work 3 | # hours with seven columns. For example, the following table stores the work hours 4 | # for eight employees. Write a program that displays employees and their total hours 5 | # in decreasing order of the total hours. 6 | 7 | workHours = [ 8 | [2, 4, 3, 4, 5, 8, 8], 9 | [7, 3, 4, 3, 3, 4, 4], 10 | [3, 3, 4, 3, 3, 2, 2], 11 | [9, 3, 4, 7, 3, 4, 1], 12 | [3, 5, 4, 3, 6, 3, 8], 13 | [3, 4, 4, 6, 3, 4, 4], 14 | [3, 7, 4, 8, 3, 8, 4], 15 | [6, 3, 5, 9, 2, 7, 9]] 16 | 17 | matrix = [] 18 | 19 | for row in range(len(workHours)): 20 | totHours = sum(workHours[row]) 21 | matrix.append([totHours, "Employee " + str(row)]) 22 | 23 | matrix.sort(reverse=True) 24 | 25 | for i in matrix: 26 | print(i[1]+"'s total hours =", i[0]) 27 | -------------------------------------------------------------------------------- /CH03/EX3.8.py: -------------------------------------------------------------------------------- 1 | # (Financial application: monetary units) Rewrite Listing 3.4, ComputeChange.py, 2 | # to fix the possible loss of accuracy when converting a float value to an int value. 3 | # Enter the input as an integer whose last two digits represent the cents. For example, 4 | # the input 1156 represents 11 dollars and 56 cents. 5 | 6 | amount = int(input("Enter an amount, for example, 1156: ")) 7 | numberOfOneDollars = amount // 100 8 | amount = amount % 100 9 | numberOfQuarters = amount // 25 10 | amount = amount % 25 11 | numberOfDimes = amount // 10 12 | amount = amount % 10 13 | numberOfNickels = amount // 5 14 | amount = amount % 5 15 | numberOfPennies = amount 16 | 17 | print("Your amount", amount, "consists of\n", 18 | "\t", numberOfOneDollars, "dollars\n", 19 | "\t", numberOfQuarters, "quarters\n", 20 | "\t", numberOfDimes, "dimes\n", 21 | "\t", numberOfNickels, "nickels\n", 22 | "\t", numberOfPennies, "pennies") 23 | -------------------------------------------------------------------------------- /CH04/EX4.29.py: -------------------------------------------------------------------------------- 1 | # 4.29 (Geometry: two circles) Write a program that prompts the user to enter the center 2 | # coordinates and radii of two circles and determines whether the second circle is 3 | # inside the first or overlaps with the first, as shown in Figure 4.11. (Hint: circle2 is 4 | # inside circle1 if the distance between the two centers <= | r1 - r2| and circle2 5 | # overlaps circle1 if the distance between the two centers <= r1 + r2. Test your 6 | # program to cover all cases.) 7 | import math 8 | 9 | x1, y1, r1 = eval(input("Enter circle1's center x-, y-coordinates, and radius: ")) 10 | x2, y2, r2 = eval(input("Enter circle2's center x-, y-coordinates, and radius: ")) 11 | 12 | distance = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) 13 | 14 | if distance <= abs(r1 - r2): 15 | print("circle2 is inside circle1") 16 | elif distance <= r1 + r2: 17 | print("circle2 overlaps circle1") 18 | else: 19 | print("circle2 does not overlap circle1") 20 | -------------------------------------------------------------------------------- /CH04/EX4.8.py: -------------------------------------------------------------------------------- 1 | # (Sort three integers) Write a program that prompts the user to enter three integers 2 | # and displays them in increasing order. 3 | import math 4 | 5 | a, b, c = eval(input("Enter a, b, c: ")) 6 | A, B, C = False, False, False 7 | s = "" 8 | 9 | if a <= b and a <= c: 10 | s += str(a) + ", " 11 | if b < c: 12 | s += str(b) + ", " 13 | C = True 14 | else: 15 | s += str(c) + ", " 16 | B = True 17 | elif b <= a and b <= c: 18 | s += str(b) + ", " 19 | if a < c: 20 | s += str(a) + ", " 21 | C = True 22 | else: 23 | s += str(c) + ", " 24 | A = True 25 | elif c <= a and c <= b: 26 | s += str(c) + ", " 27 | if b < a: 28 | s += str(b) + ", " 29 | A = True 30 | else: 31 | s += str(a) + ", " 32 | B = True 33 | 34 | if A: 35 | s += str(a) 36 | if B: 37 | s += str(b) 38 | if C: 39 | s += str(c) 40 | 41 | print(s) 42 | -------------------------------------------------------------------------------- /CH06/EX6.36.py: -------------------------------------------------------------------------------- 1 | # 6.36 (Generate random characters) Use the functions in RandomCharacter in 2 | # Listing 6.11 to print 100 uppercase letters and then 100 single digits, printing ten 3 | # per line. 4 | # Generate a random digit character 5 | from random import randint 6 | 7 | 8 | def getRandomCharacter(ch1, ch2): 9 | return chr(randint(ord(ch1), ord(ch2))) 10 | 11 | 12 | def getRandomDigitCharacter(): 13 | return getRandomCharacter('0', '9') 14 | 15 | 16 | # Generate a random uppercase letter 17 | def getRandomUpperCaseLetter(): 18 | return getRandomCharacter('A', 'Z') 19 | 20 | 21 | def main(): 22 | for i in range(100): 23 | c = getRandomUpperCaseLetter() 24 | print(c, end=' ') 25 | if (i + 1) % 10 == 0: 26 | print() 27 | print() 28 | 29 | for i in range(100): 30 | c = getRandomDigitCharacter() 31 | print(c, end=' ') 32 | if (i + 1) % 10 == 0: 33 | print() 34 | 35 | main() -------------------------------------------------------------------------------- /CH15/EX15.16.py: -------------------------------------------------------------------------------- 1 | # 15.16 (Occurrences of a specified character in a list) Write a recursive function that finds 2 | # the number of occurrences of a specified character in a list. You need to define the 3 | # following two functions. The second one is a recursive helper function. 4 | # def count(chars, ch): 5 | # def countHelper(chars, ch, high): 6 | # Write a test program that prompts the user to enter a list of characters in one line, 7 | # and a character, and displays the number of occurrences of the character in the list. 8 | 9 | def count(chars, ch): 10 | return countHelper(chars, ch, len(chars) - 1) 11 | 12 | 13 | def countHelper(chars, ch, high): 14 | count = 0 15 | if high >= 0: 16 | count = countHelper(chars, ch, high - 1) + (1 if chars[high] == ch else 0) 17 | 18 | return count 19 | 20 | 21 | s, a = input("Enter a string and a character to count: ").split() 22 | print("Character", a, "repeated", count(s.lower(), a.lower()), "times") 23 | -------------------------------------------------------------------------------- /CH15/EX15.22.py: -------------------------------------------------------------------------------- 1 | # 15.22 (Hex to decimal) Write a recursive function that parses a hex number as a string 2 | # into a decimal integer. The function header is as follows: 3 | # def hexToDecimal(hexString): 4 | # Write a test program that prompts the user to enter a hex string and displays its 5 | # decimal equivalent. 6 | 7 | hexs = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15} 8 | 9 | 10 | def hexToDecimal(hexString): 11 | return hexToDecimalHelper(hexString, 0, len(hexString) - 1) 12 | 13 | 14 | def hexToDecimalHelper(hexString, low, high): 15 | if high < low: 16 | return 0 17 | else: 18 | if hexString[high].upper() in hexs.keys(): 19 | dec = hexs[hexString[high].upper()] 20 | else: 21 | dec = int(hexString[high]) 22 | 23 | return hexToDecimalHelper(hexString, low, high - 1) * 16 + dec 24 | 25 | hex = input("Enter a hex number: ").strip() 26 | print(hex + " is decimal " + str(hexToDecimal(hex))) -------------------------------------------------------------------------------- /CH05/EX5.2.py: -------------------------------------------------------------------------------- 1 | # 5.2 (Repeat additions) Listing 5.4, SubtractionQuizLoop.py, generates five random 2 | # subtraction questions. Revise the program to generate ten random addition questions 3 | # for two integers between 1 and 15. Display the correct count and test time. 4 | import random 5 | import time 6 | 7 | correct = 0 8 | count = 0 9 | NUMBER_OF_QUESTIONS = 10 10 | startTime = time.time() 11 | while count < NUMBER_OF_QUESTIONS: 12 | n1 = random.randint(1, 15) 13 | n2 = random.randint(1, 15) 14 | ans = eval(input("What is " + str(n1) + "+" + str(n2) + " = ")) 15 | 16 | if ans == (n1 + n2): 17 | print("You are correct!") 18 | correct += 1 19 | else: 20 | print("Your answer is wrong.\n", n1, "+", n2, "=", (n1 + n2)) 21 | 22 | count += 1 23 | 24 | endTime = time.time() 25 | testTime = int(endTime - startTime) 26 | print("Correct count is", correct, "out of", 27 | NUMBER_OF_QUESTIONS, "\nTest time is", testTime, "seconds") 28 | -------------------------------------------------------------------------------- /CH06/EX6.23.py: -------------------------------------------------------------------------------- 1 | # (Convert milliseconds to hours, minutes, and seconds) Write a function that converts 2 | # milliseconds to hours, minutes, and seconds using the following header: 3 | # def convertMillis(millis): 4 | # The function returns a string as hours:minutes:seconds. For example, 5 | # convertMillis(5500) returns the string 0:0:5, convertMillis(100000) 6 | # returns the string 0:1:40, and convertMillis(555550000) returns the string 7 | # 154:19:10. 8 | # Write a test program that prompts the user to enter a value for milliseconds and 9 | # displays a string in the format of hours:minutes:seconds. 10 | 11 | def convertMillis(millis): 12 | totalSeconds = millis // 1000 13 | 14 | totalMin = totalSeconds // 60 15 | 16 | totalHours = totalMin // 60 17 | 18 | return totalSeconds % 60, totalMin % 60, totalHours 19 | 20 | 21 | def main(): 22 | s, m, h = convertMillis(int(input("Enter millis: "))) 23 | print(h, ":", m, ":", s) 24 | 25 | 26 | main() 27 | -------------------------------------------------------------------------------- /CH08/EX8.5.py: -------------------------------------------------------------------------------- 1 | # 8.5 (Occurrences of a specified string) Write a function that counts the occurrences of a 2 | # specified non-overlapping string s2 in another string s1 using the following header: 3 | # def count(s1, s2): 4 | # For example, count("system error, syntax error", "error") returns 5 | # 2. Write a test program that prompts the user to enter two strings and displays the 6 | # number of occurrences of the second string in the first string. 7 | 8 | def count(s1, s2): 9 | counter = 0 10 | s1 = s1 + ' ' 11 | while len(s1) > 0: 12 | s = s1[0: s1.index(' ')] 13 | s = s[0:len(s2)] 14 | if s == s2: 15 | counter += 1 16 | s1 = s1[s1.index(' ')+1: len(s1)] 17 | return counter 18 | 19 | 20 | def main(): 21 | str1 = input("Enter first string: ") 22 | str2 = input("Enter second string: ") 23 | c = count(str1, str2) 24 | print("String", str2, "is occurred", c, "times in", str1) 25 | 26 | 27 | main() 28 | -------------------------------------------------------------------------------- /CH10/EX10.16.py: -------------------------------------------------------------------------------- 1 | # 10.16 (Bubble sort) Write a sort function that uses the bubble-sort algorithm. The 2 | # bubble-sort algorithm makes several passes through the list. On each pass, 3 | # successive neighboring pairs are compared. If a pair is in decreasing order, 4 | # its values are swapped; otherwise, the values remain unchanged. The technique 5 | # is called a bubble sort or sinking sort because the smaller values gradually 6 | # “bubble” their way to the top and the larger values “sink” to the bottom. 7 | # Write a test program that reads in ten numbers, invokes the function, and displays 8 | # the sorted numbers. 9 | 10 | def bubbleSort(lst): 11 | for i in range(len(lst)-1): 12 | for x in range(len(lst)-1): 13 | if lst[x] > lst[x+1]: 14 | lst[x], lst[x+1] = lst[x+1], lst[x] 15 | 16 | def main(): 17 | lst = input("Enter numbers: ").split() 18 | lst = [int(x) for x in lst] 19 | bubbleSort(lst) 20 | print(lst) 21 | 22 | main() -------------------------------------------------------------------------------- /CH10/EX10.1.py: -------------------------------------------------------------------------------- 1 | # 10.1 (Assign grades) Write a program that reads a list of scores and then assigns grades 2 | # based on the following scheme: 3 | # The grade is A if score is >= best – 10. 4 | # The grade is B if score is >= best – 20. 5 | # The grade is C if score is >= best – 30. 6 | # The grade is D if score is >= best – 40. 7 | # The grade is F otherwise. 8 | 9 | scores = input("Enter scores: ") 10 | lst = [int(s) for s in scores.split()] 11 | best = max(lst) 12 | for x in range(len(lst)): 13 | if lst[x] >= best - 10: 14 | print("Student", x, "score is", lst[x], "and grade is A") 15 | elif lst[x] >= best - 20: 16 | print("Student", x, "score is", lst[x], "and grade is B") 17 | elif lst[x] >= best - 30: 18 | print("Student", x, "score is", lst[x], "and grade is C") 19 | elif lst[x] >= best - 40: 20 | print("Student", x, "score is", lst[x], "and grade is D") 21 | else: 22 | print("Student", x, "score is", lst[x], "and grade is F") 23 | -------------------------------------------------------------------------------- /CH11/EX11.15.py: -------------------------------------------------------------------------------- 1 | # 11.15 (Geometry: same line?) Exercise 6.19 gives a function for testing whether three 2 | # points are on the same line. Write the following function to test whether all the 3 | # points in the points list are on the same line: 4 | # def sameLine(points): 5 | # Write a program that prompts the user to enter five points and displays whether 6 | # they are on the same line. 7 | 8 | def sameLine(points): 9 | x0 = points[0] 10 | y0 = points[1] 11 | x4 = points[-2] 12 | y4 = points[-1] 13 | for i in range(2, len(points) - 1, 2): 14 | x = points[i] 15 | y = points[i + 1] 16 | d = (x - x0) * (y4 - y0) - (x4 - x0) * (y - y0) 17 | if d != 0: 18 | return False 19 | return True 20 | 21 | 22 | points = input("Enter five points: ").split() 23 | points = [eval(x) for x in points] 24 | if sameLine(points): 25 | print("The five points are on the same line") 26 | else: 27 | print("The five points are not on the same line") 28 | -------------------------------------------------------------------------------- /CH03/EX3.15.py: -------------------------------------------------------------------------------- 1 | # (Turtle: paint a smiley face) Write a program that paints a smiley face, as shown in 2 | # Figure 3.6a. 3 | import turtle 4 | 5 | turtle.circle(100) # face 6 | 7 | # smile 8 | turtle.penup() 9 | turtle.left(90) 10 | turtle.forward(30) 11 | turtle.right(60) 12 | turtle.pendown() 13 | turtle.forward(80) 14 | turtle.backward(80) 15 | turtle.left(120) 16 | turtle.forward(80) 17 | turtle.backward(80) 18 | 19 | # nose 20 | turtle.penup() 21 | turtle.setheading(90) 22 | turtle.forward(110) 23 | turtle.pendown() 24 | turtle.right(145) 25 | turtle.forward(80) 26 | turtle.backward(80) 27 | turtle.right(70) 28 | turtle.forward(80) 29 | turtle.backward(80) 30 | 31 | # right eye 32 | turtle.penup() 33 | turtle.setheading(0) 34 | turtle.forward(40) 35 | turtle.setheading(90) 36 | turtle.forward(20) 37 | turtle.pendown() 38 | turtle.dot(35) 39 | 40 | # left eye 41 | turtle.penup() 42 | turtle.setheading(180) 43 | turtle.forward(80) 44 | turtle.pendown() 45 | turtle.dot(35) 46 | 47 | turtle.done() 48 | -------------------------------------------------------------------------------- /CH06/EX6.30.py: -------------------------------------------------------------------------------- 1 | # 6.30 (Game: chance of winning at craps) Revise Exercise 6.28 to run it 10,000 times 2 | # and display the number of winning games. 3 | from random import random 4 | 5 | 6 | def main(): 7 | winCount = 0 8 | 9 | for i in range(10000): 10 | dice = getDice() 11 | if dice == 7 or dice == 11: 12 | winCount += 1 13 | elif dice == 2 or dice == 3 or dice == 12: 14 | winCount += 0 15 | else: 16 | point = dice 17 | dice = getDice() 18 | # print("point is " + str(point)) 19 | while dice != 7 and dice != point: 20 | dice = getDice() 21 | 22 | if dice != 7: 23 | winCount += 1 24 | 25 | print(winCount) 26 | 27 | 28 | # Get a dice 29 | def getDice(): 30 | i1 = random.randint(1, 6) 31 | i2 = random.randint(1, 6) 32 | 33 | # print("You rolled " + str(i1) + " + " + str(i2) + " = " + str(i1 + i2)) 34 | return i1 + i2 35 | 36 | 37 | main() -------------------------------------------------------------------------------- /CH06/EX6.46.py: -------------------------------------------------------------------------------- 1 | # 6.46 (Turtle: connect all points in a hexagon) Write a program that displays a hexagon 2 | # with all the points connected, as shown in Figure 6.12b. 3 | import math 4 | import turtle 5 | 6 | 7 | # Draw a line from (x1, y1) to (x2, y2) 8 | def drawLine(x1, y1, x2, y2): 9 | turtle.penup() 10 | turtle.goto(x1, y1) 11 | turtle.pendown() 12 | turtle.goto(x2, y2) 13 | 14 | 15 | def drawPolygon(x=0, y=0, radius=50, numberOfSides=3): 16 | angle = 2 * math.pi / numberOfSides 17 | 18 | # Connect points for the polygon 19 | for i in range(numberOfSides + 1): 20 | for j in range(numberOfSides + 1): 21 | drawLine(x + radius * math.cos(i * angle), 22 | y - radius * math.sin(i * angle), 23 | x + radius * math.cos(j * angle), 24 | y - radius * math.sin(j * angle)) 25 | 26 | 27 | turtle.speed(0) # Fastest 28 | 29 | drawPolygon(0, 0, 50, 6) 30 | 31 | turtle.hideturtle() 32 | 33 | turtle.done() 34 | -------------------------------------------------------------------------------- /CH11/EX11.26.py: -------------------------------------------------------------------------------- 1 | # 11.26 (Row sorting) Implement the following function to sort the rows in a twodimensional 2 | # list. A new list is returned and the original list is intact. 3 | # def sortRows(m): 4 | # Write a test program that prompts the user to enter a 3*3 matrix of numbers and 5 | # displays a new row-sorted matrix. 6 | 7 | def main(): 8 | SIZE = 3 9 | print("Enter a 3 by 3 matrix row by row: ") 10 | m = [] 11 | 12 | for i in range(SIZE): 13 | line = input().split() 14 | m.append([eval(x) for x in line]) 15 | 16 | print("The row-sorted list is ") 17 | printMatrix(sortRows(m)) 18 | 19 | 20 | def printMatrix(m): 21 | for i in range(len(m)): 22 | for j in range(len(m[i])): 23 | print(m[i][j], end=" ") 24 | print() 25 | 26 | 27 | def sortRows(m): 28 | result = [] 29 | for row in m: 30 | result.append(row) 31 | 32 | for row in result: 33 | row.sort() 34 | 35 | return result 36 | 37 | 38 | main() 39 | -------------------------------------------------------------------------------- /CH06/EX6.15.py: -------------------------------------------------------------------------------- 1 | # 6.15 (Financial application: print a tax table) Listing 4.7, ComputeTax.py, gives a 2 | # program to compute tax. Write a function for computing tax using the following 3 | # header: 4 | # def computeTax (status, taxableIncome ): 5 | # Use this function to write a program that prints a tax table for taxable income from 6 | # $50,000 to $60,000 with intervals of $50 for all four statuses, as follows: 7 | # Taxable Single Married Married Head of 8 | # Income Joint Separate a House 9 | # 50000 8688 6665 8688 7352 10 | # 50050 8700 6673 8700 7365 11 | # ... 12 | # 59950 11175 8158 11175 9840 13 | # 60000 11188 8165 11188 9852 14 | from CH6Module import MyFunctions 15 | 16 | print("Taxable\t\tSingle\t\tMarried\t\tMarried\t\tHead of") 17 | print("Income\t\t\t\t\tJoint\t\tSeparate\ta House") 18 | 19 | for i in range(50000, 60001, 50): 20 | print(i, "\t ", MyFunctions.computeTax(0, i), "\t", MyFunctions.computeTax(1, i), 21 | "\t", MyFunctions.computeTax(2, i), "\t", MyFunctions.computeTax(3, i)) 22 | -------------------------------------------------------------------------------- /CH03/EX3.14.py: -------------------------------------------------------------------------------- 1 | # (Turtle: draw the Olympic symbol ) Write a program that prompts the user to 2 | # enter the radius of the rings and draws an Olympic symbol of five rings of the 3 | # same size with the colors blue, black, red, yellow, and green, as shown in 4 | # Figure 3.5c. 5 | import turtle as t 6 | 7 | r = eval(input("Enetr radius: ")) 8 | t.speed(10) 9 | x = t.xcor() 10 | 11 | t.penup() 12 | t.backward(200) 13 | t.pendown() 14 | t.pensize(15) 15 | 16 | t.color("blue") 17 | t.circle(r) 18 | 19 | t.penup() 20 | t.forward(x + r * 2.5) 21 | t.pendown() 22 | 23 | t.color("black") 24 | t.circle(r) 25 | 26 | t.penup() 27 | t.forward(x + r * 2.5) 28 | t.pendown() 29 | 30 | t.color("red") 31 | t.circle(r) 32 | 33 | t.penup() 34 | t.backward(x + r * 4.75) 35 | t.left(-90) 36 | t.forward(x + 20) 37 | t.pendown() 38 | 39 | t.color("yellow") 40 | t.circle(r) 41 | 42 | t.penup() 43 | t.left(90) 44 | t.forward(x + r * 2.5) 45 | t.left(-90) 46 | t.forward(x) 47 | t.pendown() 48 | 49 | t.color("green") 50 | t.circle(r) 51 | t.done() 52 | -------------------------------------------------------------------------------- /CH04/EX4.18.py: -------------------------------------------------------------------------------- 1 | # 4.18 (Financials: currency exchange) Write a program that prompts the user to enter 2 | # the currency exchange rate between U.S. dollars and Chinese Renminbi (RMB). 3 | # Prompt the user to enter 0 to convert from U.S. dollars to Chinese RMB and 1 for 4 | # vice versa. Prompt the user to enter the amount in U.S. dollars or Chinese RMB to 5 | # convert it to Chinese RMB or U.S. dollars, respectively. 6 | 7 | exchngRate = eval(input("Enter the exchange rate from dollars to RMB: ")) 8 | convertion = int(input("Enter 0 to convert dollars to RMB and 1 vice versa: ")) 9 | dollars = 0 10 | rmb = 0 11 | if convertion == 0: 12 | dollars = eval(input("Enter the dollar amount: ")) 13 | rmb = dollars * exchngRate 14 | print("$" + format(dollars, "0.1f"), "is", format(rmb, "0.1f"), "Yuan") 15 | elif convertion == 1: 16 | rmb = eval(input("Enter the RMB amount: ")) 17 | dollars = rmb / exchngRate 18 | print(format(rmb, "0.1f"), "Yuan is $" + format(dollars, "0.1f")) 19 | else: 20 | print("Incorrect input") -------------------------------------------------------------------------------- /CH14/EX14.02.py: -------------------------------------------------------------------------------- 1 | # 14.2 (Count occurrences of numbers) Write a program that reads an unspecified number 2 | # of integers and finds the ones that have the most occurrences. For example, if 3 | # you enter 2 3 40 3 5 4 –3 3 3 2 0, the number 3 occurs most often. Enter all numbers 4 | # in one line. If not one but several numbers have the most occurrences, all of 5 | # them should be reported. For example, since 9 and 3 appear twice in the list 9 30 6 | # 3 9 3 2 4, both occurrences should be reported. 7 | 8 | nums = input("Enter numbers in one line: ").split() 9 | 10 | nums_dict = {} 11 | 12 | for n in nums: 13 | if n in nums_dict: 14 | nums_dict[n] += 1 15 | else: 16 | nums_dict[n] = 0 17 | 18 | pairs = list(nums_dict.items()) 19 | nums = [[x, y] for (y, x) in pairs] 20 | nums.sort(reverse=True) 21 | 22 | print(nums[0][1], end=' ') 23 | 24 | for i in range(1, len(nums)): 25 | if nums[i][0] == nums[0][0]: 26 | print(nums[i][1], end=' ') 27 | else: 28 | print() 29 | break 30 | -------------------------------------------------------------------------------- /CH06/EX6.9.py: -------------------------------------------------------------------------------- 1 | # 6.9 (Conversions between feet and meters) Write a module that contains the following 2 | # two functions: 3 | # # Converts from feet to meters 4 | # def footToMeter(foot): 5 | # # Converts from meters to feet 6 | # def meterToFoot(meter): 7 | # The formulas for the conversion are: 8 | # foot = meter / 0.305 9 | # meter = 0.305 * foot 10 | # Write a test program that invokes these functions to display the following tables: 11 | # Feet Meters | Meters Feet 12 | # 1.0 0.305 | 20.0 66.574 13 | # 2.0 0.610 | 26.0 81.967 14 | # ... 15 | # 9.0 2.745 | 60.0 196.721 16 | # 10.0 3.050 | 66.0 213.115 17 | from CH6Module import MyFunctions 18 | 19 | print("Feet\t\tMeters | Meters\t\tFeet") 20 | feet = 1 21 | meter = 20 22 | for i in range(1, 11): 23 | print(format(feet, ".1f"), format(" ", "8s"), format(MyFunctions.footToMeter(feet), ".3f"), end="\t|") 24 | print(format(" ", "2s"), format(meter, ".1f"), format(" ", "4s"), 25 | format(MyFunctions.meterToFoot(meter), ".3f")) 26 | feet += 1 27 | meter += 6 28 | -------------------------------------------------------------------------------- /CH04/EX4.23.py: -------------------------------------------------------------------------------- 1 | # 4.23 (Geometry: point in a rectangle?) Write a program that prompts the user to enter 2 | # a point (x, y) and checks whether the point is within the rectangle centered at 3 | # (0, 0) with width 10 and height 5. For example, (2, 2) is inside the rectangle and 4 | # (6, 4) is outside the rectangle, as shown in Figure 4.8b. (Hint: A point is in the 5 | # rectangle if its horizontal distance to (0, 0) is less than or equal to 10 / 2 and 6 | # its vertical distance to (0, 0) is less than or equal to 5.0 / 2. Test your program 7 | # to cover all cases.) 8 | import math 9 | 10 | HEIGHT = 5 11 | WIDTH = 10 12 | X = Y = 0 13 | x, y = eval(input("Enter a point with two coordinates: ")) 14 | 15 | distance = math.sqrt((x - X) ** 2 + (y - Y) ** 2) 16 | 17 | if WIDTH >= distance >= -WIDTH and HEIGHT >= distance >= -HEIGHT: 18 | print("Point (", format(x, "0.1f"), ",", format(y, "0.1f"), ")", "is in the rectangle") 19 | else: 20 | print("Point (", format(x, "0.1f"), ",", format(y, "0.1f"), ")", "is not in the rectangle") 21 | 22 | -------------------------------------------------------------------------------- /CH05/EX5.25.py: -------------------------------------------------------------------------------- 1 | # 5.25 (Demonstrate cancellation errors) A cancellation error occurs when you are 2 | # manipulating a very large number with a very small number. The large number 3 | # may cancel out the smaller number. For example, the result of 100000000.0 + 4 | # 0.000000001 is equal to 100000000.0. To avoid cancellation errors and obtain 5 | # more accurate results, carefully select the order of computation. For example, in 6 | # computing the following series, you will obtain more accurate results by computing 7 | # from right to left rather than from left to right: 8 | # Write a program that compares the results of the summation of the preceding 9 | # series, computing both from left to right and from right to left with n 50000. 10 | 11 | N = 50000 12 | 13 | print("From left to right, the sum is: ", end='') 14 | sum = 0 15 | for i in range(1, N + 1): 16 | sum += 1 / i 17 | 18 | print(sum) 19 | 20 | print("From right to left, the sum is: ", end='') 21 | sum = 0 22 | for i in range(N, 0, -1): 23 | sum += 1 / i 24 | 25 | print(sum) 26 | -------------------------------------------------------------------------------- /CH11/EX11.49.py: -------------------------------------------------------------------------------- 1 | # 11.49 (Game: display a tic-tac-toe board) Revise Exercise 9.6 to display a new tic-tac-toe 2 | # board with a click of the Refresh button, as shown in Figure 11.19. 3 | 4 | 5 | import random 6 | from tkinter import * 7 | 8 | window = Tk() 9 | x = PhotoImage(file="x.gif") 10 | o = PhotoImage(file="o.gif") 11 | for i in range(3): 12 | for j in range(3): 13 | r = random.randint(0, 1) 14 | if r == 0: 15 | Label(window, image=x).grid(row=i + 1, column=j + 1) 16 | elif r == 1: 17 | Label(window, image=o).grid(row=i + 1, column=j + 1) 18 | 19 | 20 | def refresh(): 21 | for i in range(3): 22 | for j in range(3): 23 | r = random.randint(0, 1) 24 | if r == 0: 25 | Label(window, image=x).grid(row=i + 1, column=j + 1) 26 | elif r == 1: 27 | Label(window, image=o).grid(row=i + 1, column=j + 1) 28 | 29 | 30 | Button(window, text='Refresh', command=refresh).grid(row=4, column=2) 31 | 32 | window.mainloop() 33 | -------------------------------------------------------------------------------- /CH05/EX5.55.py: -------------------------------------------------------------------------------- 1 | # 5.55 (Turtle: chessboard) Write a program to draw a chessboard, as shown in 2 | # Figure 5.6b. 3 | import turtle 4 | 5 | turtle.speed(0) 6 | turtle.penup() 7 | turtle.goto(-150, 120) 8 | turtle.left(45) 9 | turtle.pendown() 10 | black = False 11 | for i in range(1, 9): 12 | for j in range(1, 9): 13 | turtle.begin_fill() 14 | turtle.circle(30, steps=4) 15 | if black: 16 | turtle.color("black") 17 | black = not black 18 | else: 19 | turtle.color("white") 20 | black = not black 21 | 22 | turtle.end_fill() 23 | 24 | turtle.penup() 25 | turtle.goto(turtle.xcor() + 42, turtle.ycor()) 26 | turtle.pendown() 27 | 28 | turtle.penup() 29 | turtle.goto(-150, turtle.ycor() - 42) 30 | turtle.pendown() 31 | black = not black 32 | 33 | turtle.penup() 34 | turtle.left(180) 35 | turtle.goto(-192, 161) 36 | turtle.color("gray") 37 | turtle.pensize(6) 38 | turtle.pendown() 39 | turtle.circle(240, steps=4) 40 | turtle.done() 41 | -------------------------------------------------------------------------------- /CH06/EX6.3.py: -------------------------------------------------------------------------------- 1 | # 6.3 (Palindrome integer) Write the functions with the following headers: 2 | # # Return the reversal of an integer, e.g. reverse(456) returns 3 | # # 654 4 | # def reverse(number): 5 | # # Return true if number is a palindrome 6 | # def isPalindrome(number): 7 | # Use the reverse function to implement isPalindrome. A number is a palindrome 8 | # if its reversal is the same as itself. Write a test program that prompts the 9 | # user to enter an integer and reports whether the integer is a palindrome. 10 | 11 | # Return the reversal of an integer, e.g. reverse(456) returns 12 | # 654 13 | def reverse(number): 14 | num = "" 15 | while number > 0: 16 | n1 = number % 10 17 | num = num + str(n1) 18 | number = number // 10 19 | 20 | return int(num) 21 | 22 | 23 | # Return true if number is a palindrome 24 | def isPalindrome(number): 25 | revNumber = reverse(number) 26 | return True if revNumber == number else False 27 | 28 | 29 | num = eval(input("Enter a number: ")) 30 | print(isPalindrome(num)) 31 | -------------------------------------------------------------------------------- /CH06/EX6.45.py: -------------------------------------------------------------------------------- 1 | # 6.45 (Turtle: draw a regular polygon) Write the following function to draw a regular 2 | # polygon: 3 | # def drawPolygon(x = 0, y = 0, radius = 50, numberOfSides = 3): 4 | # The polygon is centered at (x, y) with a specified radius for the bounding circle for 5 | # the polygon and the number of sides. Write a test program that displays a triangle, 6 | # square, pentagon, hexagon, heptagon, and octagon, as shown in Figure 6.12a. 7 | import turtle 8 | 9 | 10 | def drawPolygon(x=0, y=0, radius=50, numberOfSides=3): 11 | turtle.penup() 12 | turtle.goto(x, y) 13 | turtle.pendown() 14 | turtle.circle(radius, steps=numberOfSides) 15 | 16 | 17 | def main(): 18 | drawPolygon(-200,50) # Triangle 19 | drawPolygon(-100, 50, numberOfSides=4) # Square 20 | drawPolygon(0, 50, numberOfSides=5) # Pentagon 21 | drawPolygon(100, 50, numberOfSides=6) # hexagon 22 | drawPolygon(200, 50, numberOfSides=7) # heptagon 23 | drawPolygon(300, 50, numberOfSides=8) # octagon 24 | turtle.done() 25 | 26 | 27 | main() 28 | -------------------------------------------------------------------------------- /CH10/EX10.26.py: -------------------------------------------------------------------------------- 1 | # 10.26 (Merge two sorted lists) Write the following function that merges two sorted lists 2 | # into a new sorted list: 3 | # def merge(list1, list2): 4 | # Implement the function in a way that takes len(list1) + len(list2) comparisons. 5 | # Write a test program that prompts the user to enter two sorted lists and 6 | # displays the merged list. 7 | 8 | def merge(l1, l2): 9 | res = [] 10 | c1 = 0 11 | c2 = 0 12 | while c1 < len(l1) and c2 < len(l2): 13 | m1 = l1[c1] 14 | m2 = l2[c2] 15 | if m1 < m2: 16 | res.append(m1) 17 | c1 += 1 18 | else: 19 | res.append(m2) 20 | c2 += 1 21 | 22 | while c1 < len(l1): 23 | res.append(l1[c1]) 24 | c1 += 1 25 | 26 | while c2 < len(l2): 27 | res.append(l2[c2]) 28 | c2 += 1 29 | 30 | return res 31 | 32 | 33 | l1 = [int(x) for x in input("Enter list1: ").split()] 34 | l2 = [int(x) for x in input("Enyer list2: ").split()] 35 | res = merge(l1, l2) 36 | 37 | print(res) 38 | -------------------------------------------------------------------------------- /CH11/EX11.44.py: -------------------------------------------------------------------------------- 1 | # 11.44 (Tkinter: draw a polygon) Write a program that prompts the user to enter the 2 | # coordinates of six points and fills the polygon that connects the points, as 3 | # shown in Figure 11.16a. Note that you can draw a polygon using 4 | # canvas.create_polygon(points), where points is a two-dimensional list that 5 | # stores the x- and y-coordinates of the points. 6 | from tkinter import * # Import tkinter 7 | 8 | 9 | class MainGUI: 10 | def __init__(self): 11 | coordinates = input("Enter coordinates for six points separated by spaces: ") 12 | c = coordinates.split() 13 | points = [[eval(c[i]), eval(c[i + 1])] for i in range(0, len(c), 2)] 14 | 15 | window = Tk() # Create a window 16 | window.title("Polygon") # Set title 17 | 18 | width = 400 19 | height = 250 20 | canvas = Canvas(window, width=width, height=height) 21 | canvas.pack() 22 | 23 | canvas.create_polygon(points) 24 | 25 | window.mainloop() # Create an event loop 26 | 27 | 28 | MainGUI() 29 | -------------------------------------------------------------------------------- /CH05/EX5.46.py: -------------------------------------------------------------------------------- 1 | # 5.46 (Statistics: compute mean and standard deviation) In business applications, you 2 | # are often asked to compute the mean and standard deviation of data. The mean is 3 | # simply the average of the numbers. The standard deviation is a statistic that tells 4 | # you how tightly all the various data are clustered around the mean in a set of data. 5 | # For example, what is the average age of the students in a class? How close are the 6 | # ages? If all the students are the same age, the deviation is 0. Write a program that 7 | # prompts the user to enter ten numbers, and displays the mean and standard deviations 8 | # of these numbers using the following formula: 9 | import math 10 | 11 | COUNT = 10 12 | sum = 0 13 | squareSum = 0 14 | print("Enter ten numbers: ", end='') 15 | 16 | for i in range(COUNT): 17 | n = eval(input()) 18 | sum += n 19 | squareSum += n * n 20 | 21 | mean = sum / COUNT 22 | dev = math.sqrt((squareSum - sum * sum / COUNT) / (COUNT - 1)) 23 | 24 | print("The mean is", mean) 25 | print("The standard deviation is", dev) 26 | -------------------------------------------------------------------------------- /CH06/EX6.21.py: -------------------------------------------------------------------------------- 1 | # 6.21 (Math: approximate the square root) There are several techniques for implementing 2 | # the sqrt function in the math module. One such technique is known as the 3 | # Babylonian function. It approximates the square root of a number, n, by repeatedly 4 | # performing a calculation using the following formula: 5 | # nextGuess = (lastGuess + (n / lastGuess)) / 2 6 | # When nextGuess and lastGuess are almost identical, nextGuess is the 7 | # approximated square root. The initial guess can be any positive value (e.g., 1). 8 | # This value will be the starting value for lastGuess. If the difference between 9 | # nextGuess and lastGuess is less than a very small number, such as 0.0001, 10 | # you can claim that nextGuess is the approximated square root of n. If not, 11 | # nextGuess becomes lastGuess and the approximation process continues. 12 | # Implement the following function that returns the square root of n. 13 | from CH6Module import MyFunctions 14 | 15 | n = eval(input("Enter a number: ")) 16 | print("The square root of", n, "is", MyFunctions.sqrt(n)) 17 | -------------------------------------------------------------------------------- /CH05/EX5.1.py: -------------------------------------------------------------------------------- 1 | # 5.1 (Count positive and negative numbers and compute the average of numbers) 2 | # Write a program that reads an unspecified number of integers, determines 3 | # how many positive and negative values have been read, and computes the total 4 | # and average of the input values (not counting zeros). Your program ends with the 5 | # input 0. Display the average as a floating-point number. 6 | 7 | avg = 0 8 | postives = 0 9 | negativies = 0 10 | total = 0 11 | n = int(input("Enter an integer, the input ends if it is 0: ")) 12 | 13 | if n == 0: 14 | print("You didn't enter any number") 15 | else: 16 | while n != 0: 17 | if n > 0: 18 | postives += 1 19 | else: 20 | negativies += 1 21 | total += n 22 | avg = total / (postives + negativies) 23 | n = int(input("Enter an integer, the input ends if it is 0: ")) 24 | 25 | print("The number of positives is", postives) 26 | print("The number of negatives is", negativies) 27 | print("The total is", total) 28 | print("The average is", avg) 29 | --------------------------------------------------------------------------------