├── 100+ Python challenging programming exercises for Python 3.md ├── 100+ Python challenging programming exercises.txt ├── README.md ├── comic.png ├── python contents.docx └── python contents.txt /100+ Python challenging programming exercises for Python 3.md: -------------------------------------------------------------------------------- 1 | # 100+ Python challenging programming exercises for Python 3 2 | 3 | ## 1. Level description 4 | ### Level 1 Beginner 5 | Beginner means someone who has just gone through an introductory Python course. He can solve some problems with 1 or 2 Python classes or functions. Normally, the answers could directly be found in the textbooks. 6 | 7 | ### Level 2 Intermediate 8 | Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He should be able to solve problems which may involve 3 or 3 Python classes or functions. The answers cannot be directly be found in the textbooks. 9 | 10 | ### Level 3 Advanced. 11 | He should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques. 12 | 13 | ---- 14 | 15 | ## 2. Problem template 16 | 17 | Question 18 | Hints 19 | Solution 20 | 21 | ---- 22 | 23 | ## 3. Questions 24 | 25 | ### Question 1 26 | Level 1 27 | 28 | Question: 29 | Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). 30 | The numbers obtained should be printed in a comma-separated sequence on a single line. 31 | 32 | Hints: 33 | Consider use range(#begin, #end) method 34 | 35 | Solution: 36 | ```python 37 | l=[] 38 | for i in range(2000, 3201): 39 | if (i%7==0) and (i%5!=0): 40 | l.append(str(i)) 41 | 42 | print(','.join(l)) 43 | ``` 44 | 45 | ### Question 2 46 | Level 1 47 | 48 | Question: 49 | Write a program which can compute the factorial of a given numbers. 50 | The results should be printed in a comma-separated sequence on a single line. 51 | Suppose the following input is supplied to the program: 52 | 8 53 | Then, the output should be: 54 | 40320 55 | 56 | Hints: 57 | In case of input data being supplied to the question, it should be assumed to be a console input. 58 | 59 | Solution: 60 | ```python 61 | def fact(x): 62 | if x == 0: 63 | return 1 64 | return x * fact(x - 1) 65 | 66 | x=int(input()) 67 | print(fact(x)) 68 | ``` 69 | 70 | ### Question 3 71 | Level 1 72 | 73 | Question: 74 | With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. 75 | Suppose the following input is supplied to the program: 76 | 8 77 | Then, the output should be: 78 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 79 | 80 | Hints: 81 | In case of input data being supplied to the question, it should be assumed to be a console input. 82 | Consider use dict() 83 | 84 | Solution: 85 | ```python 86 | n=int(input()) 87 | d=dict() 88 | for i in range(1,n+1): 89 | d[i]=i*i 90 | 91 | print(d) 92 | ``` 93 | 94 | ### Question 4 95 | Level 1 96 | 97 | Question: 98 | Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. 99 | Suppose the following input is supplied to the program: 100 | 34,67,55,33,12,98 101 | Then, the output should be: 102 | ['34', '67', '55', '33', '12', '98'] 103 | ('34', '67', '55', '33', '12', '98') 104 | 105 | Hints: 106 | In case of input data being supplied to the question, it should be assumed to be a console input. 107 | tuple() method can convert list to tuple 108 | 109 | Solution: 110 | ```python 111 | values=input() 112 | l=values.split(",") 113 | t=tuple(l) 114 | print(l) 115 | print(t) 116 | ``` 117 | 118 | ### Question 5 119 | Level 1 120 | 121 | Question: 122 | Define a class which has at least two methods: 123 | getString: to get a string from console input 124 | printString: to print the string in upper case. 125 | Also please include simple test function to test the class methods. 126 | 127 | Hints: 128 | Use __init__ method to construct some parameters 129 | 130 | Solution: 131 | ```python 132 | class InputOutString(object): 133 | def __init__(self): 134 | self.s = "" 135 | 136 | def getString(self): 137 | self.s = input() 138 | 139 | def printString(self): 140 | print(self.s.upper()) 141 | 142 | strObj = InputOutString() 143 | strObj.getString() 144 | strObj.printString() 145 | ``` 146 | 147 | ### Question 6 148 | Level 2 149 | 150 | Question: 151 | Write a program that calculates and prints the value according to the given formula: 152 | Q = Square root of [(2 * C * D)/H] 153 | Following are the fixed values of C and H: 154 | C is 50. H is 30. 155 | D is the variable whose values should be input to your program in a comma-separated sequence. 156 | Example 157 | Let us assume the following comma separated input sequence is given to the program: 158 | 100,150,180 159 | The output of the program should be: 160 | 18,22,24 161 | 162 | Hints: 163 | If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26) 164 | In case of input data being supplied to the question, it should be assumed to be a console input. 165 | 166 | Solution: 167 | ```python 168 | import math 169 | c=50 170 | h=30 171 | value = [] 172 | items=[x for x in input().split(',')] 173 | for d in items: 174 | value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) 175 | 176 | print(','.join(value)) 177 | ``` 178 | 179 | ### Question 7 180 | Level 2 181 | 182 | Question: 183 | Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. 184 | Note: i=0,1.., X-1; j=0,1,¡­Y-1. 185 | Example 186 | Suppose the following inputs are given to the program: 187 | 3,5 188 | Then, the output of the program should be: 189 | [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 190 | 191 | Hints: 192 | Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. 193 | 194 | Solution: 195 | ```python 196 | input_str = input() 197 | dimensions=[int(x) for x in input_str.split(',')] 198 | rowNum=dimensions[0] 199 | colNum=dimensions[1] 200 | multilist = [[0 for col in range(colNum)] for row in range(rowNum)] 201 | 202 | for row in range(rowNum): 203 | for col in range(colNum): 204 | multilist[row][col]= row*col 205 | 206 | print(multilist) 207 | ``` 208 | 209 | ### Question 8 210 | Level 2 211 | 212 | Question: 213 | Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. 214 | Suppose the following input is supplied to the program: 215 | without,hello,bag,world 216 | Then, the output should be: 217 | bag,hello,without,world 218 | 219 | Hints: 220 | In case of input data being supplied to the question, it should be assumed to be a console input. 221 | 222 | Solution: 223 | ```python 224 | items=[x for x in input().split(',')] 225 | items.sort() 226 | print(','.join(items)) 227 | ``` 228 | 229 | ### Question 9 230 | Level 2 231 | 232 | Question£º 233 | Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. 234 | Suppose the following input is supplied to the program: 235 | Hello world 236 | Practice makes perfect 237 | Then, the output should be: 238 | HELLO WORLD 239 | PRACTICE MAKES PERFECT 240 | 241 | Hints: 242 | In case of input data being supplied to the question, it should be assumed to be a console input. 243 | 244 | Solution: 245 | ```python 246 | lines = [] 247 | while True: 248 | s = input() 249 | if s: 250 | lines.append(s.upper()) 251 | else: 252 | break; 253 | 254 | for sentence in lines: 255 | print(sentence) 256 | ``` 257 | 258 | ### Question 10 259 | Level 2 260 | 261 | Question: 262 | Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. 263 | Suppose the following input is supplied to the program: 264 | hello world and practice makes perfect and hello world again 265 | Then, the output should be: 266 | again and hello makes perfect practice world 267 | 268 | Hints: 269 | In case of input data being supplied to the question, it should be assumed to be a console input. 270 | We use set container to remove duplicated data automatically and then use sorted() to sort the data. 271 | 272 | Solution: 273 | ```python 274 | s = input() 275 | words = [word for word in s.split(" ")] 276 | print(" ".join(sorted(list(set(words))))) 277 | ``` 278 | 279 | ### Question 11 280 | Level 2 281 | 282 | Question: 283 | Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. 284 | Example: 285 | 0100,0011,1010,1001 286 | Then the output should be: 287 | 1010 288 | Notes: Assume the data is input by console. 289 | 290 | Hints: 291 | In case of input data being supplied to the question, it should be assumed to be a console input. 292 | 293 | Solution: 294 | ```python 295 | value = [] 296 | items=[x for x in input().split(',')] 297 | for p in items: 298 | intp = int(p, 2) 299 | if not intp%5: 300 | value.append(p) 301 | 302 | print(','.join(value)) 303 | ``` 304 | 305 | ### Question 12 306 | Level 2 307 | 308 | Question: 309 | Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. 310 | The numbers obtained should be printed in a comma-separated sequence on a single line. 311 | 312 | Hints: 313 | In case of input data being supplied to the question, it should be assumed to be a console input. 314 | 315 | Solution: 316 | ```python 317 | values = [] 318 | for i in range(1000, 3001): 319 | s = str(i) 320 | if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): 321 | values.append(s) 322 | print(",".join(values)) 323 | ``` 324 | 325 | ### Question 13 326 | Level 2 327 | 328 | Question: 329 | Write a program that accepts a sentence and calculate the number of letters and digits. 330 | Suppose the following input is supplied to the program: 331 | hello world! 123 332 | Then, the output should be: 333 | LETTERS 10 334 | DIGITS 3 335 | 336 | Hints: 337 | In case of input data being supplied to the question, it should be assumed to be a console input. 338 | 339 | Solution: 340 | ```python 341 | s = input() 342 | d={"DIGITS":0, "LETTERS":0} 343 | for c in s: 344 | if c.isdigit(): 345 | d["DIGITS"]+=1 346 | elif c.isalpha(): 347 | d["LETTERS"]+=1 348 | else: 349 | pass 350 | print("LETTERS", d["LETTERS"]) 351 | print("DIGITS", d["DIGITS"]) 352 | ``` 353 | 354 | ### Question 14 355 | Level 2 356 | 357 | Question: 358 | Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. 359 | Suppose the following input is supplied to the program: 360 | Hello world! 361 | Then, the output should be: 362 | UPPER CASE 1 363 | LOWER CASE 9 364 | 365 | Hints: 366 | In case of input data being supplied to the question, it should be assumed to be a console input. 367 | 368 | Solution: 369 | ```python 370 | s = input() 371 | d={"UPPER CASE":0, "LOWER CASE":0} 372 | for c in s: 373 | if c.isupper(): 374 | d["UPPER CASE"]+=1 375 | elif c.islower(): 376 | d["LOWER CASE"]+=1 377 | else: 378 | pass 379 | print("UPPER CASE", d["UPPER CASE"]) 380 | print("LOWER CASE", d["LOWER CASE"]) 381 | ``` 382 | 383 | ### Question 15 384 | Level 2 385 | 386 | Question: 387 | Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. 388 | Suppose the following input is supplied to the program: 389 | 9 390 | Then, the output should be: 391 | 11106 392 | 393 | Hints: 394 | In case of input data being supplied to the question, it should be assumed to be a console input. 395 | 396 | Solution: 397 | 398 | ```python 399 | a = input() 400 | n1 = int( "%s" % a ) 401 | n2 = int( "%s%s" % (a,a) ) 402 | n3 = int( "%s%s%s" % (a,a,a) ) 403 | n4 = int( "%s%s%s%s" % (a,a,a,a) ) 404 | print(n1+n2+n3+n4) 405 | ``` 406 | 407 | ### Question 16 408 | Level 2 409 | 410 | Question: 411 | Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. 412 | Suppose the following input is supplied to the program: 413 | 1,2,3,4,5,6,7,8,9 414 | Then, the output should be: 415 | 1,3,5,7,9 416 | 417 | Hints: 418 | In case of input data being supplied to the question, it should be assumed to be a console input. 419 | 420 | Solution: 421 | 422 | ```python 423 | values = input() 424 | numbers = [x for x in values.split(",") if int(x)%2!=0] 425 | print(",".join(numbers)) 426 | ``` 427 | 428 | ### Question 17 429 | Level 2 430 | 431 | Question: 432 | Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: 433 | D 100 434 | W 200 435 | 436 | D means deposit while W means withdrawal. 437 | Suppose the following input is supplied to the program: 438 | D 300 439 | D 300 440 | W 200 441 | D 100 442 | Then, the output should be: 443 | 500 444 | 445 | Hints: 446 | In case of input data being supplied to the question, it should be assumed to be a console input. 447 | 448 | Solution: 449 | 450 | ```python 451 | netAmount = 0 452 | while True: 453 | s = input() 454 | if not s: 455 | break 456 | values = s.split(" ") 457 | operation = values[0] 458 | amount = int(values[1]) 459 | if operation=="D": 460 | netAmount+=amount 461 | elif operation=="W": 462 | netAmount-=amount 463 | else: 464 | pass 465 | print(netAmount) 466 | ``` 467 | 468 | ### Question 18 469 | Level 3 470 | 471 | Question: 472 | A website requires the users to input username and password to register. Write a program to check the validity of password input by users. 473 | Following are the criteria for checking the password: 474 | 1. At least 1 letter between [a-z] 475 | 2. At least 1 number between [0-9] 476 | 1. At least 1 letter between [A-Z] 477 | 3. At least 1 character from [$#@] 478 | 4. Minimum length of transaction password: 6 479 | 5. Maximum length of transaction password: 12 480 | Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. 481 | Example 482 | If the following passwords are given as input to the program: 483 | ABd1234@1,a F1#,2w3E*,2We3345 484 | Then, the output of the program should be: 485 | ABd1234@1 486 | 487 | Hints: 488 | In case of input data being supplied to the question, it should be assumed to be a console input. 489 | 490 | Solutions: 491 | 492 | ```python 493 | import re 494 | value = [] 495 | items=[x for x in input().split(',')] 496 | for p in items: 497 | if len(p)<6 or len(p)>12: 498 | continue 499 | else: 500 | pass 501 | if not re.search("[a-z]",p): 502 | continue 503 | elif not re.search("[0-9]",p): 504 | continue 505 | elif not re.search("[A-Z]",p): 506 | continue 507 | elif not re.search("[$#@]",p): 508 | continue 509 | elif re.search("\s",p): 510 | continue 511 | else: 512 | pass 513 | value.append(p) 514 | print(",".join(value)) 515 | ``` 516 | 517 | ### Question 19 518 | Level 3 519 | 520 | Question: 521 | You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: 522 | 1: Sort based on name; 523 | 2: Then sort based on age; 524 | 3: Then sort by score. 525 | The priority is that name > age > score. 526 | If the following tuples are given as input to the program: 527 | Tom,19,80 528 | John,20,90 529 | Jony,17,91 530 | Jony,17,93 531 | Json,21,85 532 | Then, the output of the program should be: 533 | [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] 534 | 535 | Hints: 536 | In case of input data being supplied to the question, it should be assumed to be a console input. 537 | We use itemgetter to enable multiple sort keys. 538 | 539 | Solutions: 540 | from operator import itemgetter, attrgetter 541 | 542 | ```python 543 | l = [] 544 | while True: 545 | s = input() 546 | if not s: 547 | break 548 | l.append(tuple(s.split(","))) 549 | 550 | print(sorted(l, key=itemgetter(0,1,2))) 551 | ``` 552 | 553 | ### Question 20 554 | Level 3 555 | 556 | Question: 557 | Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. 558 | 559 | Hints: 560 | Consider use yield 561 | 562 | Solution: 563 | 564 | ```python 565 | def putNumbers(n): 566 | i = 0 567 | while ilen2: 828 | print(s1) 829 | elif len2>len1: 830 | print(s2) 831 | else: 832 | print(s1) 833 | print(s2) 834 | 835 | printValue("one","three") 836 | 837 | ``` 838 | ### Question 32 839 | Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number". 840 | 841 | Hints: 842 | 843 | Use % operator to check if a number is even or odd. 844 | 845 | Solution 846 | ```python 847 | def checkValue(n): 848 | if n%2 == 0: 849 | print("It is an even number") 850 | else: 851 | print("It is an odd number") 852 | 853 | checkValue(7) 854 | 855 | ### Question 33 856 | Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. 857 | 858 | Hints: 859 | 860 | Use dict[key]=value pattern to put entry into a dictionary. 861 | Use ** operator to get power of a number. 862 | 863 | Solution 864 | ​```python 865 | def printDict(): 866 | d=dict() 867 | d[1]=1 868 | d[2]=2**2 869 | d[3]=3**2 870 | print(d) 871 | 872 | printDict() 873 | ``` 874 | ### Question 34 875 | Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. 876 | 877 | Hints: 878 | 879 | Use dict[key]=value pattern to put entry into a dictionary. 880 | Use ** operator to get power of a number. 881 | Use range() for loops. 882 | 883 | Solution 884 | ```python 885 | def printDict(): 886 | d=dict() 887 | for i in range(1,21): 888 | d[i]=i**2 889 | print(d) 890 | 891 | printDict() 892 | ``` 893 | 894 | ### Question 35 895 | Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. 896 | 897 | Hints: 898 | 899 | Use dict[key]=value pattern to put entry into a dictionary. 900 | Use ** operator to get power of a number. 901 | Use range() for loops. 902 | Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. 903 | 904 | Solution 905 | ```python 906 | def printDict(): 907 | d=dict() 908 | for i in range(1,21): 909 | d[i]=i**2 910 | for (k,v) in d.items(): 911 | print(v) 912 | 913 | printDict() 914 | ``` 915 | 916 | ### Question 36 917 | Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. 918 | 919 | Hints: 920 | 921 | Use dict[key]=value pattern to put entry into a dictionary. 922 | Use ** operator to get power of a number. 923 | Use range() for loops. 924 | Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. 925 | 926 | Solution 927 | ```python 928 | def printDict(): 929 | d=dict() 930 | for i in range(1,21): 931 | d[i]=i**2 932 | for k in d.keys(): 933 | print(k) 934 | 935 | printDict() 936 | ``` 937 | 938 | ### Question 37 939 | Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). 940 | 941 | Hints: 942 | 943 | Use ** operator to get power of a number. 944 | Use range() for loops. 945 | Use list.append() to add values into a list. 946 | 947 | Solution 948 | ```python 949 | def printList(): 950 | li=list() 951 | for i in range(1,21): 952 | li.append(i**2) 953 | print(li) 954 | 955 | printList() 956 | ``` 957 | ### Question 38 958 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. 959 | 960 | Hints: 961 | 962 | Use ** operator to get power of a number. 963 | Use range() for loops. 964 | Use list.append() to add values into a list. 965 | Use [n1:n2] to slice a list 966 | 967 | Solution 968 | ```python 969 | def printList(): 970 | li=list() 971 | for i in range(1,21): 972 | li.append(i**2) 973 | print(li[:5]) 974 | 975 | printList() 976 | ``` 977 | 978 | ### Question 39 979 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. 980 | 981 | Hints: 982 | 983 | Use ** operator to get power of a number. 984 | Use range() for loops. 985 | Use list.append() to add values into a list. 986 | Use [n1:n2] to slice a list 987 | 988 | Solution 989 | ```python 990 | def printList(): 991 | li=list() 992 | for i in range(1,21): 993 | li.append(i**2) 994 | print(li[-5:]) 995 | 996 | printList() 997 | ``` 998 | ### Question 40 999 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. 1000 | 1001 | Hints: 1002 | 1003 | Use ** operator to get power of a number. 1004 | Use range() for loops. 1005 | Use list.append() to add values into a list. 1006 | Use [n1:n2] to slice a list 1007 | 1008 | Solution 1009 | ```python 1010 | def printList(): 1011 | li=list() 1012 | for i in range(1,21): 1013 | li.append(i**2) 1014 | print li[5:] 1015 | 1016 | printList() 1017 | ``` 1018 | 1019 | ### Question 41 1020 | Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). 1021 | 1022 | Hints: 1023 | 1024 | Use ** operator to get power of a number. 1025 | Use range() for loops. 1026 | Use list.append() to add values into a list. 1027 | Use tuple() to get a tuple from a list. 1028 | 1029 | Solution 1030 | ```python 1031 | def printTuple(): 1032 | li=list() 1033 | for i in range(1,21): 1034 | li.append(i**2) 1035 | print(tuple(li)) 1036 | 1037 | printTuple() 1038 | ``` 1039 | ### Question 42 1040 | With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. 1041 | 1042 | Hints: 1043 | 1044 | Use [n1:n2] notation to get a slice from a tuple. 1045 | 1046 | Solution 1047 | ```python 1048 | tp=(1,2,3,4,5,6,7,8,9,10) 1049 | tp1=tp[:5] 1050 | tp2=tp[5:] 1051 | print(tp1) 1052 | print(tp2) 1053 | ``` 1054 | 1055 | ### Question 43 1056 | Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). 1057 | 1058 | Hints: 1059 | 1060 | Use "for" to iterate the tuple 1061 | Use tuple() to generate a tuple from a list. 1062 | 1063 | Solution 1064 | ```python 1065 | tp=(1,2,3,4,5,6,7,8,9,10) 1066 | li=list() 1067 | for i in tp: 1068 | if tp[i]%2==0: 1069 | li.append(tp[i]) 1070 | 1071 | tp2=tuple(li) 1072 | print(tp2) 1073 | ``` 1074 | ### Question 44 1075 | Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". 1076 | 1077 | Hints: 1078 | 1079 | Use if statement to judge condition. 1080 | 1081 | Solution 1082 | ```python 1083 | s= raw_input() 1084 | if s=="yes" or s=="YES" or s=="Yes": 1085 | print "Yes" 1086 | else: 1087 | print "No" 1088 | ``` 1089 | ### Question 45 1090 | Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. 1091 | 1092 | Hints: 1093 | 1094 | Use filter() to filter some elements in a list. 1095 | Use lambda to define anonymous functions. 1096 | 1097 | Solution 1098 | ```python 1099 | li = [1,2,3,4,5,6,7,8,9,10] 1100 | evenNumbers = filter(lambda x: x%2==0, li) 1101 | print(evenNumbers) 1102 | ``` 1103 | 1104 | ### Question 46 1105 | Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. 1106 | 1107 | Hints 1108 | Use map() to generate a list. 1109 | Use lambda to define anonymous functions. 1110 | 1111 | Solution 1112 | ```python 1113 | li = [1,2,3,4,5,6,7,8,9,10] 1114 | squaredNumbers = map(lambda x: x**2, li) 1115 | print(squaredNumbers) 1116 | ``` 1117 | 1118 | ### Question 47 1119 | Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. 1120 | 1121 | Hints 1122 | Use map() to generate a list. 1123 | Use filter() to filter elements of a list. 1124 | Use lambda to define anonymous functions. 1125 | 1126 | Solution 1127 | ```python 1128 | li = [1,2,3,4,5,6,7,8,9,10] 1129 | evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) 1130 | print(evenNumbers) 1131 | ``` 1132 | ### Question 48 1133 | Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). 1134 | 1135 | Hints: 1136 | 1137 | Use filter() to filter elements of a list. 1138 | Use lambda to define anonymous functions. 1139 | 1140 | Solution 1141 | ```python 1142 | evenNumbers = filter(lambda x: x%2==0, range(1,21)) 1143 | print(evenNumbers) 1144 | ``` 1145 | 1146 | ### Question 49 1147 | Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). 1148 | 1149 | Hints 1150 | Use map() to generate a list. 1151 | Use lambda to define anonymous functions. 1152 | 1153 | Solution 1154 | ```python 1155 | squaredNumbers = map(lambda x: x**2, range(1,21)) 1156 | print(squaredNumbers) 1157 | ``` 1158 | 1159 | ### Question 50 1160 | Define a class named American which has a static method called printNationality. 1161 | 1162 | Hints: 1163 | Use @staticmethod decorator to define class static method. 1164 | 1165 | Solution 1166 | ```python 1167 | class American(object): 1168 | @staticmethod 1169 | def printNationality(): 1170 | print("America") 1171 | 1172 | anAmerican = American() 1173 | anAmerican.printNationality() 1174 | American.printNationality() 1175 | ``` 1176 | 1177 | ### Question 51 1178 | Define a class named American and its subclass NewYorker. 1179 | 1180 | Hints: 1181 | 1182 | Use class Subclass(ParentClass) to define a subclass. 1183 | 1184 | Solution: 1185 | ```python 1186 | class American(object): 1187 | pass 1188 | 1189 | class NewYorker(American): 1190 | pass 1191 | 1192 | anAmerican = American() 1193 | aNewYorker = NewYorker() 1194 | print(anAmerican) 1195 | print(aNewYorker) 1196 | ``` 1197 | 1198 | ### Question 52 1199 | Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. 1200 | 1201 | Hints: 1202 | 1203 | Use def methodName(self) to define a method. 1204 | 1205 | Solution: 1206 | ```python 1207 | class Circle(object): 1208 | def __init__(self, r): 1209 | self.radius = r 1210 | 1211 | def area(self): 1212 | return self.radius**2*3.14 1213 | 1214 | aCircle = Circle(2) 1215 | print aCircle.area() 1216 | ``` 1217 | 1218 | ### Question 53 1219 | Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. 1220 | 1221 | Hints: 1222 | 1223 | Use def methodName(self) to define a method. 1224 | 1225 | Solution: 1226 | ```python 1227 | class Rectangle(object): 1228 | def __init__(self, l, w): 1229 | self.length = l 1230 | self.width = w 1231 | 1232 | def area(self): 1233 | return self.length*self.width 1234 | 1235 | aRectangle = Rectangle(2,10) 1236 | print(aRectangle.area()) 1237 | ``` 1238 | 1239 | ### Question 54 1240 | Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. 1241 | 1242 | Hints: 1243 | 1244 | To override a method in super class, we can define a method with the same name in the super class. 1245 | 1246 | Solution: 1247 | ```python 1248 | class Shape(object): 1249 | def __init__(self): 1250 | pass 1251 | 1252 | def area(self): 1253 | return 0 1254 | 1255 | class Square(Shape): 1256 | def __init__(self, l): 1257 | Shape.__init__(self) 1258 | self.length = l 1259 | 1260 | def area(self): 1261 | return self.length*self.length 1262 | 1263 | aSquare= Square(3) 1264 | print(aSquare.area()) 1265 | ``` 1266 | 1267 | ### Question 55 1268 | Please raise a RuntimeError exception. 1269 | 1270 | Hints: 1271 | 1272 | Use raise() to raise an exception. 1273 | 1274 | Solution: 1275 | 1276 | ```python 1277 | raise RuntimeError('something wrong') 1278 | ``` 1279 | 1280 | ### Question 56 1281 | Write a function to compute 5/0 and use try/except to catch the exceptions. 1282 | 1283 | Hints: 1284 | 1285 | Use try/except to catch exceptions. 1286 | 1287 | Solution: 1288 | ```python 1289 | def throws(): 1290 | return 5/0 1291 | 1292 | try: 1293 | throws() 1294 | except ZeroDivisionError: 1295 | print("division by zero!") 1296 | except Exception, err: 1297 | print('Caught an exception') 1298 | finally: 1299 | print('In finally block for cleanup') 1300 | ``` 1301 | 1302 | ### Question 57 1303 | Define a custom exception class which takes a string message as attribute. 1304 | 1305 | Hints: 1306 | 1307 | To define a custom exception, we need to define a class inherited from Exception. 1308 | 1309 | Solution: 1310 | ```python 1311 | class MyError(Exception): 1312 | """My own exception class 1313 | 1314 | Attributes: 1315 | msg -- explanation of the error 1316 | """ 1317 | 1318 | def __init__(self, msg): 1319 | self.msg = msg 1320 | 1321 | error = MyError("something wrong") 1322 | ``` 1323 | 1324 | ### Question 58 1325 | Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. 1326 | 1327 | Example: 1328 | If the following email address is given as input to the program: 1329 | 1330 | john@google.com 1331 | 1332 | Then, the output of the program should be: 1333 | 1334 | john 1335 | 1336 | In case of input data being supplied to the question, it should be assumed to be a console input. 1337 | 1338 | Hints: 1339 | 1340 | Use \w to match letters. 1341 | 1342 | Solution: 1343 | ```python 1344 | import re 1345 | emailAddress = raw_input() 1346 | pat2 = "(\w+)@((\w+\.)+(com))" 1347 | r2 = re.match(pat2,emailAddress) 1348 | print(r2.group(1)) 1349 | ``` 1350 | 1351 | ### Question 59 1352 | Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. 1353 | 1354 | Example: 1355 | If the following email address is given as input to the program: 1356 | 1357 | john@google.com 1358 | 1359 | Then, the output of the program should be: 1360 | 1361 | google 1362 | 1363 | In case of input data being supplied to the question, it should be assumed to be a console input. 1364 | 1365 | Hints: 1366 | 1367 | Use \w to match letters. 1368 | 1369 | Solution: 1370 | ```python 1371 | import re 1372 | emailAddress = raw_input() 1373 | pat2 = "(\w+)@(\w+)\.(com)" 1374 | r2 = re.match(pat2,emailAddress) 1375 | print(r2.group(2)) 1376 | ``` 1377 | 1378 | ### Question 60 1379 | Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. 1380 | 1381 | Example: 1382 | If the following words is given as input to the program: 1383 | 1384 | 2 cats and 3 dogs. 1385 | 1386 | Then, the output of the program should be: 1387 | 1388 | ['2', '3'] 1389 | 1390 | In case of input data being supplied to the question, it should be assumed to be a console input. 1391 | 1392 | Hints: 1393 | 1394 | Use re.findall() to find all substring using regex. 1395 | 1396 | Solution: 1397 | ```python 1398 | import re 1399 | s = raw_input() 1400 | print(re.findall("\d+",s)) 1401 | ``` 1402 | 1403 | ### Question 61 1404 | Print a unicode string "hello world". 1405 | 1406 | Hints: 1407 | 1408 | Use u'strings' format to define unicode string. 1409 | 1410 | Solution: 1411 | ```python 1412 | unicodeString = u"hello world!" 1413 | print(unicodeString) 1414 | ``` 1415 | 1416 | ### Question 62 1417 | Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. 1418 | 1419 | Hints: 1420 | 1421 | Use unicode() function to convert. 1422 | 1423 | Solution: 1424 | ```python 1425 | s = input() 1426 | u = unicode( s ,"utf-8") 1427 | print(u) 1428 | ``` 1429 | 1430 | ### Question 63 1431 | 1432 | Write a special comment to indicate a Python source code file is in unicode. 1433 | 1434 | Hints: 1435 | 1436 | Solution: 1437 | ```python 1438 | 1439 | # -*- coding: utf-8 -*- 1440 | 1441 | #----------------------------------------# 1442 | ``` 1443 | 1444 | ### Question 64 1445 | 1446 | Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). 1447 | 1448 | Example: 1449 | If the following n is given as input to the program: 1450 | 1451 | 5 1452 | 1453 | Then, the output of the program should be: 1454 | 1455 | 3.55 1456 | 1457 | In case of input data being supplied to the question, it should be assumed to be a console input. 1458 | 1459 | Hints: 1460 | Use float() to convert an integer to a float 1461 | 1462 | Solution: 1463 | ```python 1464 | n=int(input()) 1465 | sum=0.0 1466 | for i in range(1,n+1): 1467 | sum += float(float(i)/(i+1)) 1468 | print(sum) 1469 | ``` 1470 | 1471 | ### Question 65 1472 | 1473 | Write a program to compute: 1474 | 1475 | f(n)=f(n-1)+100 when n>0 1476 | and f(0)=1 1477 | 1478 | with a given n input by console (n>0). 1479 | 1480 | Example: 1481 | If the following n is given as input to the program: 1482 | 1483 | 5 1484 | 1485 | Then, the output of the program should be: 1486 | 1487 | 500 1488 | 1489 | In case of input data being supplied to the question, it should be assumed to be a console input. 1490 | 1491 | Hints: 1492 | We can define recursive function in Python. 1493 | 1494 | Solution: 1495 | ```python 1496 | def f(n): 1497 | if n==0: 1498 | return 0 1499 | else: 1500 | return f(n-1)+100 1501 | 1502 | n=int(input()) 1503 | print(f(n)) 1504 | ``` 1505 | 1506 | ### Question 66 1507 | The Fibonacci Sequence is computed based on the following formula: 1508 | 1509 | f(n)=0 if n=0 1510 | f(n)=1 if n=1 1511 | f(n)=f(n-1)+f(n-2) if n>1 1512 | 1513 | Please write a program to compute the value of f(n) with a given n input by console. 1514 | 1515 | Example: 1516 | If the following n is given as input to the program: 1517 | 1518 | 7 1519 | 1520 | Then, the output of the program should be: 1521 | 1522 | 13 1523 | 1524 | In case of input data being supplied to the question, it should be assumed to be a console input. 1525 | 1526 | Hints: 1527 | We can define recursive function in Python. 1528 | 1529 | 1530 | Solution: 1531 | ```python 1532 | def f(n): 1533 | if n == 0: return 0 1534 | elif n == 1: return 1 1535 | else: return f(n-1)+f(n-2) 1536 | 1537 | n=int(input()) 1538 | print(f(n)) 1539 | ``` 1540 | 1541 | ### Question 67 1542 | The Fibonacci Sequence is computed based on the following formula: 1543 | 1544 | f(n)=0 if n=0 1545 | f(n)=1 if n=1 1546 | f(n)=f(n-1)+f(n-2) if n>1 1547 | 1548 | Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. 1549 | 1550 | Example: 1551 | If the following n is given as input to the program: 1552 | 1553 | 7 1554 | 1555 | Then, the output of the program should be: 1556 | 1557 | 0,1,1,2,3,5,8,13 1558 | 1559 | 1560 | Hints: 1561 | We can define recursive function in Python. 1562 | Use list comprehension to generate a list from an existing list. 1563 | Use string.join() to join a list of strings. 1564 | 1565 | In case of input data being supplied to the question, it should be assumed to be a console input. 1566 | 1567 | Solution: 1568 | ```python 1569 | def f(n): 1570 | if n == 0: return 0 1571 | elif n == 1: return 1 1572 | else: return f(n-1)+f(n-2) 1573 | 1574 | n=int(input()) 1575 | values = [str(f(x)) for x in range(0, n+1)] 1576 | print(",".join(values)) 1577 | ``` 1578 | 1579 | ### Question 68 1580 | 1581 | Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. 1582 | 1583 | Example: 1584 | If the following n is given as input to the program: 1585 | 1586 | 10 1587 | 1588 | Then, the output of the program should be: 1589 | 1590 | 0,2,4,6,8,10 1591 | 1592 | Hints: 1593 | Use yield to produce the next value in generator. 1594 | 1595 | In case of input data being supplied to the question, it should be assumed to be a console input. 1596 | 1597 | Solution: 1598 | ```python 1599 | def EvenGenerator(n): 1600 | i=0 1601 | while i<=n: 1602 | if i%2==0: 1603 | yield i 1604 | i+=1 1605 | 1606 | 1607 | n=int(input()) 1608 | values = [] 1609 | for i in EvenGenerator(n): 1610 | values.append(str(i)) 1611 | 1612 | print(",".join(values)) 1613 | ``` 1614 | 1615 | ### Question 69 1616 | Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. 1617 | 1618 | Example: 1619 | If the following n is given as input to the program: 1620 | 1621 | 100 1622 | 1623 | Then, the output of the program should be: 1624 | 1625 | 0,35,70 1626 | 1627 | Hints: 1628 | Use yield to produce the next value in generator. 1629 | 1630 | In case of input data being supplied to the question, it should be assumed to be a console input. 1631 | 1632 | Solution: 1633 | ```python 1634 | def NumGenerator(n): 1635 | for i in range(n+1): 1636 | if i%5==0 and i%7==0: 1637 | yield i 1638 | 1639 | n=int(input()) 1640 | values = [] 1641 | for i in NumGenerator(n): 1642 | values.append(str(i)) 1643 | 1644 | print(",".join(values)) 1645 | ``` 1646 | 1647 | ### Question 70 1648 | Please write assert statements to verify that every number in the list [2,4,6,8] is even. 1649 | 1650 | Hints: 1651 | Use "assert expression" to make assertion. 1652 | 1653 | Solution: 1654 | ```python 1655 | li = [2,4,6,8] 1656 | for i in li: 1657 | assert i%2==0 1658 | ``` 1659 | 1660 | ### Question 71 1661 | Please write a program which accepts basic mathematic expression from console and print the evaluation result. 1662 | 1663 | Example: 1664 | If the following string is given as input to the program: 1665 | 1666 | 35+3 1667 | 1668 | Then, the output of the program should be: 1669 | 1670 | 38 1671 | 1672 | Hints: 1673 | Use eval() to evaluate an expression. 1674 | 1675 | 1676 | Solution: 1677 | ```python 1678 | expression = raw_input() 1679 | print(eval(expression)) 1680 | ``` 1681 | 1682 | ### Question 72 1683 | Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. 1684 | 1685 | Hints: 1686 | Use if/elif to deal with conditions. 1687 | 1688 | Solution: 1689 | ```python 1690 | import math 1691 | def bin_search(li, element): 1692 | bottom = 0 1693 | top = len(li)-1 1694 | index = -1 1695 | while top>=bottom and index==-1: 1696 | mid = int(math.floor((top+bottom)/2.0)) 1697 | if li[mid]==element: 1698 | index = mid 1699 | elif li[mid]>element: 1700 | top = mid-1 1701 | else: 1702 | bottom = mid+1 1703 | 1704 | return index 1705 | 1706 | li=[2,5,7,9,11,17,222] 1707 | print(bin_search(li,11)) 1708 | print(bin_search(li,12)) 1709 | ``` 1710 | 1711 | ### Question 73 1712 | Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. 1713 | 1714 | Hints: 1715 | Use if/elif to deal with conditions. 1716 | 1717 | Solution: 1718 | ```python 1719 | import math 1720 | def bin_search(li, element): 1721 | bottom = 0 1722 | top = len(li)-1 1723 | index = -1 1724 | while top>=bottom and index==-1: 1725 | mid = int(math.floor((top+bottom)/2.0)) 1726 | if li[mid]==element: 1727 | index = mid 1728 | elif li[mid]>element: 1729 | top = mid-1 1730 | else: 1731 | bottom = mid+1 1732 | 1733 | return index 1734 | 1735 | li=[2,5,7,9,11,17,222] 1736 | print(bin_search(li,11)) 1737 | print(bin_search(li,12)) 1738 | ``` 1739 | 1740 | ### Question 74 1741 | Please generate a random float where the value is between 10 and 100 using Python math module. 1742 | 1743 | Hints: 1744 | Use random.random() to generate a random float in [0,1]. 1745 | 1746 | Solution: 1747 | ```python 1748 | import random 1749 | print(random.random()*100) 1750 | ``` 1751 | 1752 | ### Question 75 1753 | Please generate a random float where the value is between 5 and 95 using Python math module. 1754 | 1755 | Hints: 1756 | Use random.random() to generate a random float in [0,1]. 1757 | 1758 | Solution: 1759 | ```python 1760 | import random 1761 | print(random.random()*100-5) 1762 | ``` 1763 | 1764 | ### Question 76 1765 | Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. 1766 | 1767 | Hints: 1768 | Use random.choice() to a random element from a list. 1769 | 1770 | Solution: 1771 | ```python 1772 | import random 1773 | print(random.choice([i for i in range(11) if i%2==0])) 1774 | ``` 1775 | 1776 | ### Question 77 1777 | Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. 1778 | 1779 | Hints: 1780 | Use random.choice() to a random element from a list. 1781 | 1782 | Solution: 1783 | ```python 1784 | import random 1785 | print(random.choice([i for i in range(201) if i%5==0 and i%7==0])) 1786 | ``` 1787 | 1788 | ### Question 78 1789 | Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. 1790 | 1791 | Hints: 1792 | Use random.sample() to generate a list of random values. 1793 | 1794 | Solution: 1795 | ```python 1796 | import random 1797 | print(random.sample(range(100), 5)) 1798 | ``` 1799 | 1800 | ### Question 79 1801 | Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. 1802 | 1803 | Hints: 1804 | Use random.sample() to generate a list of random values. 1805 | 1806 | Solution: 1807 | ```python 1808 | import random 1809 | print(random.sample([i for i in range(100,201) if i%2==0], 5)) 1810 | ``` 1811 | 1812 | ### Question 80 1813 | Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. 1814 | 1815 | Hints: 1816 | Use random.sample() to generate a list of random values. 1817 | 1818 | Solution: 1819 | ```python 1820 | import random 1821 | print(random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5)) 1822 | ``` 1823 | 1824 | ### Question 81 1825 | Please write a program to randomly print a integer number between 7 and 15 inclusive. 1826 | 1827 | Hints: 1828 | Use random.randrange() to a random integer in a given range. 1829 | 1830 | Solution: 1831 | ```python 1832 | import random 1833 | print(random.randrange(7,16)) 1834 | ``` 1835 | 1836 | ### Question 82 1837 | Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". 1838 | 1839 | Hints: 1840 | Use zlib.compress() and zlib.decompress() to compress and decompress a string. 1841 | 1842 | Solution: 1843 | ```python 1844 | import zlib 1845 | s = b'hello world!hello world!hello world!hello world!' 1846 | t = zlib.compress(s) 1847 | print(t) 1848 | print(zlib.decompress(t)) 1849 | ``` 1850 | 1851 | ### Question 83 1852 | Please write a program to print the running time of execution of "1+1" for 100 times. 1853 | 1854 | Hints: 1855 | Use timeit() function to measure the running time. 1856 | 1857 | Solution: 1858 | ```python 1859 | from timeit import Timer 1860 | t = Timer("for i in range(100):1+1") 1861 | print(t.timeit()) 1862 | ``` 1863 | 1864 | ### Question 84 1865 | Please write a program to shuffle and print the list [3,6,7,8]. 1866 | 1867 | Hints: 1868 | Use shuffle() function to shuffle a list. 1869 | 1870 | Solution: 1871 | ```python 1872 | from random import shuffle 1873 | li = [3,6,7,8] 1874 | shuffle(li) 1875 | print(li) 1876 | ``` 1877 | 1878 | ### Question 85 1879 | Please write a program to shuffle and print the list [3,6,7,8]. 1880 | 1881 | Hints: 1882 | Use shuffle() function to shuffle a list. 1883 | 1884 | Solution: 1885 | ```python 1886 | from random import shuffle 1887 | li = [3,6,7,8] 1888 | shuffle(li) 1889 | print(li) 1890 | ``` 1891 | 1892 | ### Question 86 1893 | Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. 1894 | 1895 | Hints: 1896 | Use list[index] notation to get a element from a list. 1897 | 1898 | Solution: 1899 | ```python 1900 | subjects=["I", "You"] 1901 | verbs=["Play", "Love"] 1902 | objects=["Hockey","Football"] 1903 | for i in range(len(subjects)): 1904 | for j in range(len(verbs)): 1905 | for k in range(len(objects)): 1906 | sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) 1907 | print(sentence) 1908 | ``` 1909 | 1910 | ### Question 87 1911 | Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. 1912 | 1913 | Hints: 1914 | Use list comprehension to delete a bunch of element from a list. 1915 | 1916 | Solution: 1917 | ``` 1918 | li = [5,6,77,45,22,12,24] 1919 | li = [x for x in li if x%2!=0] 1920 | print(li) 1921 | ``` 1922 | 1923 | ### Question 88 1924 | By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. 1925 | 1926 | Hints: 1927 | Use list comprehension to delete a bunch of element from a list. 1928 | 1929 | Solution: 1930 | ``` 1931 | li = [12,24,35,70,88,120,155] 1932 | li = [x for x in li if x%5!=0 and x%7!=0] 1933 | print(li) 1934 | ``` 1935 | 1936 | ### Question 89 1937 | By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. 1938 | 1939 | Hints: 1940 | Use list comprehension to delete a bunch of element from a list. 1941 | Use enumerate() to get (index, value) tuple. 1942 | 1943 | Solution: 1944 | ```python 1945 | li = [12,24,35,70,88,120,155] 1946 | li = [x for (i,x) in enumerate(li) if i%2!=0] 1947 | print(li) 1948 | ``` 1949 | 1950 | ### Question 90 1951 | By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0. 1952 | 1953 | Hints: 1954 | Use list comprehension to make an array. 1955 | 1956 | Solution: 1957 | ``` 1958 | array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] 1959 | print(array) 1960 | ``` 1961 | 1962 | ### Question 91 1963 | By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. 1964 | 1965 | Hints: 1966 | Use list comprehension to delete a bunch of element from a list. 1967 | Use enumerate() to get (index, value) tuple. 1968 | 1969 | Solution: 1970 | ```python 1971 | li = [12,24,35,70,88,120,155] 1972 | li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] 1973 | print(li) 1974 | ``` 1975 | 1976 | ### Question 92 1977 | By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. 1978 | 1979 | Hints: 1980 | Use list's remove method to delete a value. 1981 | 1982 | Solution: 1983 | ```python 1984 | li = [12,24,35,24,88,120,155] 1985 | li = [x for x in li if x!=24] 1986 | print(li) 1987 | ``` 1988 | 1989 | ### Question 93 1990 | With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. 1991 | 1992 | Hints: 1993 | Use set() and "&=" to do set intersection operation. 1994 | 1995 | Solution: 1996 | ```python 1997 | set1=set([1,3,6,78,35,55]) 1998 | set2=set([12,24,35,24,88,120,155]) 1999 | set1 &= set2 2000 | li=list(set1) 2001 | print(li) 2002 | ``` 2003 | 2004 | ### Question 94 2005 | With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. 2006 | 2007 | Hints: 2008 | Use set() to store a number of values without duplicate. 2009 | 2010 | Solution: 2011 | ```python 2012 | def removeDuplicate( li ): 2013 | newli=[] 2014 | seen = set() 2015 | for item in li: 2016 | if item not in seen: 2017 | seen.add( item ) 2018 | newli.append(item) 2019 | 2020 | return newli 2021 | 2022 | li=[12,24,35,24,88,120,155,88,120,155] 2023 | print(removeDuplicate(li)) 2024 | ``` 2025 | 2026 | ### Question 95 2027 | Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. 2028 | 2029 | Hints: 2030 | Use Subclass(Parentclass) to define a child class. 2031 | 2032 | Solution: 2033 | ```python 2034 | class Person(object): 2035 | def getGender( self ): 2036 | return "Unknown" 2037 | 2038 | class Male( Person ): 2039 | def getGender( self ): 2040 | return "Male" 2041 | 2042 | class Female( Person ): 2043 | def getGender( self ): 2044 | return "Female" 2045 | 2046 | aMale = Male() 2047 | aFemale= Female() 2048 | print(aMale.getGender()) 2049 | print(aFemale.getGender()) 2050 | ``` 2051 | 2052 | ### Question 96 2053 | Please write a program which count and print the numbers of each character in a string input by console. 2054 | 2055 | Example: 2056 | If the following string is given as input to the program: 2057 | 2058 | abcdefgabc 2059 | 2060 | Then, the output of the program should be: 2061 | 2062 | a,2 2063 | c,2 2064 | b,2 2065 | e,1 2066 | d,1 2067 | g,1 2068 | f,1 2069 | 2070 | Hints: 2071 | Use dict to store key/value pairs. 2072 | Use dict.get() method to lookup a key with default value. 2073 | 2074 | Solution: 2075 | ```python 2076 | dic = {} 2077 | s=raw_input() 2078 | for s in s: 2079 | dic[s] = dic.get(s,0)+1 2080 | print('\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])) 2081 | ``` 2082 | 2083 | ### Question 97 2084 | Please write a program which accepts a string from console and print it in reverse order. 2085 | 2086 | Example: 2087 | If the following string is given as input to the program: 2088 | 2089 | rise to vote sir 2090 | 2091 | Then, the output of the program should be: 2092 | 2093 | ris etov ot esir 2094 | 2095 | Hints: 2096 | Use list[::-1] to iterate a list in a reverse order. 2097 | 2098 | Solution: 2099 | ```python 2100 | s=raw_input() 2101 | s = s[::-1] 2102 | print(s) 2103 | ``` 2104 | 2105 | ### Question 98 2106 | Please write a program which accepts a string from console and print the characters that have even indexes. 2107 | 2108 | Example: 2109 | If the following string is given as input to the program: 2110 | 2111 | H1e2l3l4o5w6o7r8l9d 2112 | 2113 | Then, the output of the program should be: 2114 | 2115 | Helloworld 2116 | 2117 | Hints: 2118 | Use list[::2] to iterate a list by step 2. 2119 | 2120 | Solution: 2121 | ```python 2122 | s=raw_input() 2123 | s = s[::2] 2124 | print(s) 2125 | ``` 2126 | 2127 | ### Question 99 2128 | Please write a program which prints all permutations of [1,2,3] 2129 | 2130 | Hints: 2131 | Use itertools.permutations() to get permutations of list. 2132 | 2133 | Solution: 2134 | ```python 2135 | import itertools 2136 | print(list(itertools.permutations([1,2,3]))) 2137 | ``` 2138 | 2139 | ### Question 100 2140 | Write a program to solve a classic ancient Chinese puzzle: 2141 | We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? 2142 | 2143 | Hint: 2144 | Use for loop to iterate all possible solutions. 2145 | 2146 | Solution: 2147 | ```python 2148 | def solve(numheads,numlegs): 2149 | ns='No solutions!' 2150 | for i in range(numheads+1): 2151 | j=numheads-i 2152 | if 2*i+4*j==numlegs: 2153 | return i,j 2154 | return ns,ns 2155 | 2156 | numheads=35 2157 | numlegs=94 2158 | solutions=solve(numheads,numlegs) 2159 | print(solutions) 2160 | ``` 2161 | 2162 | -------------------------------------------------------------------------------- /100+ Python challenging programming exercises.txt: -------------------------------------------------------------------------------- 1 | 100+ Python challenging programming exercises 2 | 3 | 1. Level description 4 | Level Description 5 | Level 1 Beginner means someone who has just gone through an introductory Python course. He can solve some problems with 1 or 2 Python classes or functions. Normally, the answers could directly be found in the textbooks. 6 | Level 2 Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He should be able to solve problems which may involve 3 or 3 Python classes or functions. The answers cannot be directly be found in the textbooks. 7 | Level 3 Advanced. He should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques. 8 | 9 | 2. Problem template 10 | 11 | #----------------------------------------# 12 | Question 13 | Hints 14 | Solution 15 | 16 | 3. Questions 17 | 18 | #----------------------------------------# 19 | Question 1 20 | Level 1 21 | 22 | Question: 23 | Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, 24 | between 2000 and 3200 (both included). 25 | The numbers obtained should be printed in a comma-separated sequence on a single line. 26 | 27 | Hints: 28 | Consider use range(#begin, #end) method 29 | 30 | Solution: 31 | l=[] 32 | for i in range(2000, 3201): 33 | if (i%7==0) and (i%5!=0): 34 | l.append(str(i)) 35 | 36 | print ','.join(l) 37 | #----------------------------------------# 38 | 39 | #----------------------------------------# 40 | Question 2 41 | Level 1 42 | 43 | Question: 44 | Write a program which can compute the factorial of a given numbers. 45 | The results should be printed in a comma-separated sequence on a single line. 46 | Suppose the following input is supplied to the program: 47 | 8 48 | Then, the output should be: 49 | 40320 50 | 51 | Hints: 52 | In case of input data being supplied to the question, it should be assumed to be a console input. 53 | 54 | Solution: 55 | def fact(x): 56 | if x == 0: 57 | return 1 58 | return x * fact(x - 1) 59 | 60 | x=int(raw_input()) 61 | print fact(x) 62 | #----------------------------------------# 63 | 64 | #----------------------------------------# 65 | Question 3 66 | Level 1 67 | 68 | Question: 69 | With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. 70 | Suppose the following input is supplied to the program: 71 | 8 72 | Then, the output should be: 73 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 74 | 75 | Hints: 76 | In case of input data being supplied to the question, it should be assumed to be a console input. 77 | Consider use dict() 78 | 79 | Solution: 80 | n=int(raw_input()) 81 | d=dict() 82 | for i in range(1,n+1): 83 | d[i]=i*i 84 | 85 | print d 86 | #----------------------------------------# 87 | 88 | #----------------------------------------# 89 | Question 4 90 | Level 1 91 | 92 | Question: 93 | Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. 94 | Suppose the following input is supplied to the program: 95 | 34,67,55,33,12,98 96 | Then, the output should be: 97 | ['34', '67', '55', '33', '12', '98'] 98 | ('34', '67', '55', '33', '12', '98') 99 | 100 | Hints: 101 | In case of input data being supplied to the question, it should be assumed to be a console input. 102 | tuple() method can convert list to tuple 103 | 104 | Solution: 105 | values=raw_input() 106 | l=values.split(",") 107 | t=tuple(l) 108 | print l 109 | print t 110 | #----------------------------------------# 111 | 112 | #----------------------------------------# 113 | Question 5 114 | Level 1 115 | 116 | Question: 117 | Define a class which has at least two methods: 118 | getString: to get a string from console input 119 | printString: to print the string in upper case. 120 | Also please include simple test function to test the class methods. 121 | 122 | Hints: 123 | Use __init__ method to construct some parameters 124 | 125 | Solution: 126 | class InputOutString(object): 127 | def __init__(self): 128 | self.s = "" 129 | 130 | def getString(self): 131 | self.s = raw_input() 132 | 133 | def printString(self): 134 | print self.s.upper() 135 | 136 | strObj = InputOutString() 137 | strObj.getString() 138 | strObj.printString() 139 | #----------------------------------------# 140 | 141 | #----------------------------------------# 142 | Question 6 143 | Level 2 144 | 145 | Question: 146 | Write a program that calculates and prints the value according to the given formula: 147 | Q = Square root of [(2 * C * D)/H] 148 | Following are the fixed values of C and H: 149 | C is 50. H is 30. 150 | D is the variable whose values should be input to your program in a comma-separated sequence. 151 | Example 152 | Let us assume the following comma separated input sequence is given to the program: 153 | 100,150,180 154 | The output of the program should be: 155 | 18,22,24 156 | 157 | Hints: 158 | If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26) 159 | In case of input data being supplied to the question, it should be assumed to be a console input. 160 | 161 | Solution: 162 | #!/usr/bin/env python 163 | import math 164 | c=50 165 | h=30 166 | value = [] 167 | items=[x for x in raw_input().split(',')] 168 | for d in items: 169 | value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) 170 | 171 | print ','.join(value) 172 | #----------------------------------------# 173 | 174 | #----------------------------------------# 175 | Question 7 176 | Level 2 177 | 178 | Question: 179 | Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. 180 | Note: i=0,1.., X-1; j=0,1,¡­Y-1. 181 | Example 182 | Suppose the following inputs are given to the program: 183 | 3,5 184 | Then, the output of the program should be: 185 | [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 186 | 187 | Hints: 188 | Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. 189 | 190 | Solution: 191 | input_str = raw_input() 192 | dimensions=[int(x) for x in input_str.split(',')] 193 | rowNum=dimensions[0] 194 | colNum=dimensions[1] 195 | multilist = [[0 for col in range(colNum)] for row in range(rowNum)] 196 | 197 | for row in range(rowNum): 198 | for col in range(colNum): 199 | multilist[row][col]= row*col 200 | 201 | print multilist 202 | #----------------------------------------# 203 | 204 | #----------------------------------------# 205 | Question 8 206 | Level 2 207 | 208 | Question: 209 | Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. 210 | Suppose the following input is supplied to the program: 211 | without,hello,bag,world 212 | Then, the output should be: 213 | bag,hello,without,world 214 | 215 | Hints: 216 | In case of input data being supplied to the question, it should be assumed to be a console input. 217 | 218 | Solution: 219 | items=[x for x in raw_input().split(',')] 220 | items.sort() 221 | print ','.join(items) 222 | #----------------------------------------# 223 | 224 | #----------------------------------------# 225 | Question 9 226 | Level 2 227 | 228 | Question£º 229 | Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. 230 | Suppose the following input is supplied to the program: 231 | Hello world 232 | Practice makes perfect 233 | Then, the output should be: 234 | HELLO WORLD 235 | PRACTICE MAKES PERFECT 236 | 237 | Hints: 238 | In case of input data being supplied to the question, it should be assumed to be a console input. 239 | 240 | Solution: 241 | lines = [] 242 | while True: 243 | s = raw_input() 244 | if s: 245 | lines.append(s.upper()) 246 | else: 247 | break; 248 | 249 | for sentence in lines: 250 | print sentence 251 | #----------------------------------------# 252 | 253 | #----------------------------------------# 254 | Question 10 255 | Level 2 256 | 257 | Question: 258 | Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. 259 | Suppose the following input is supplied to the program: 260 | hello world and practice makes perfect and hello world again 261 | Then, the output should be: 262 | again and hello makes perfect practice world 263 | 264 | Hints: 265 | In case of input data being supplied to the question, it should be assumed to be a console input. 266 | We use set container to remove duplicated data automatically and then use sorted() to sort the data. 267 | 268 | Solution: 269 | s = raw_input() 270 | words = [word for word in s.split(" ")] 271 | print " ".join(sorted(list(set(words)))) 272 | #----------------------------------------# 273 | 274 | #----------------------------------------# 275 | Question 11 276 | Level 2 277 | 278 | Question: 279 | Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. 280 | Example: 281 | 0100,0011,1010,1001 282 | Then the output should be: 283 | 1010 284 | Notes: Assume the data is input by console. 285 | 286 | Hints: 287 | In case of input data being supplied to the question, it should be assumed to be a console input. 288 | 289 | Solution: 290 | value = [] 291 | items=[x for x in raw_input().split(',')] 292 | for p in items: 293 | intp = int(p, 2) 294 | if not intp%5: 295 | value.append(p) 296 | 297 | print ','.join(value) 298 | #----------------------------------------# 299 | 300 | #----------------------------------------# 301 | Question 12 302 | Level 2 303 | 304 | Question: 305 | Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. 306 | The numbers obtained should be printed in a comma-separated sequence on a single line. 307 | 308 | Hints: 309 | In case of input data being supplied to the question, it should be assumed to be a console input. 310 | 311 | Solution: 312 | values = [] 313 | for i in range(1000, 3001): 314 | s = str(i) 315 | if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): 316 | values.append(s) 317 | print ",".join(values) 318 | #----------------------------------------# 319 | 320 | #----------------------------------------# 321 | Question 13 322 | Level 2 323 | 324 | Question: 325 | Write a program that accepts a sentence and calculate the number of letters and digits. 326 | Suppose the following input is supplied to the program: 327 | hello world! 123 328 | Then, the output should be: 329 | LETTERS 10 330 | DIGITS 3 331 | 332 | Hints: 333 | In case of input data being supplied to the question, it should be assumed to be a console input. 334 | 335 | Solution: 336 | s = raw_input() 337 | d={"DIGITS":0, "LETTERS":0} 338 | for c in s: 339 | if c.isdigit(): 340 | d["DIGITS"]+=1 341 | elif c.isalpha(): 342 | d["LETTERS"]+=1 343 | else: 344 | pass 345 | print "LETTERS", d["LETTERS"] 346 | print "DIGITS", d["DIGITS"] 347 | #----------------------------------------# 348 | 349 | #----------------------------------------# 350 | Question 14 351 | Level 2 352 | 353 | Question: 354 | Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. 355 | Suppose the following input is supplied to the program: 356 | Hello world! 357 | Then, the output should be: 358 | UPPER CASE 1 359 | LOWER CASE 9 360 | 361 | Hints: 362 | In case of input data being supplied to the question, it should be assumed to be a console input. 363 | 364 | Solution: 365 | s = raw_input() 366 | d={"UPPER CASE":0, "LOWER CASE":0} 367 | for c in s: 368 | if c.isupper(): 369 | d["UPPER CASE"]+=1 370 | elif c.islower(): 371 | d["LOWER CASE"]+=1 372 | else: 373 | pass 374 | print "UPPER CASE", d["UPPER CASE"] 375 | print "LOWER CASE", d["LOWER CASE"] 376 | #----------------------------------------# 377 | 378 | #----------------------------------------# 379 | Question 15 380 | Level 2 381 | 382 | Question: 383 | Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. 384 | Suppose the following input is supplied to the program: 385 | 9 386 | Then, the output should be: 387 | 11106 388 | 389 | Hints: 390 | In case of input data being supplied to the question, it should be assumed to be a console input. 391 | 392 | Solution: 393 | a = raw_input() 394 | n1 = int( "%s" % a ) 395 | n2 = int( "%s%s" % (a,a) ) 396 | n3 = int( "%s%s%s" % (a,a,a) ) 397 | n4 = int( "%s%s%s%s" % (a,a,a,a) ) 398 | print n1+n2+n3+n4 399 | #----------------------------------------# 400 | 401 | #----------------------------------------# 402 | Question 16 403 | Level 2 404 | 405 | Question: 406 | Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. 407 | Suppose the following input is supplied to the program: 408 | 1,2,3,4,5,6,7,8,9 409 | Then, the output should be: 410 | 1,3,5,7,9 411 | 412 | Hints: 413 | In case of input data being supplied to the question, it should be assumed to be a console input. 414 | 415 | Solution: 416 | values = raw_input() 417 | numbers = [x for x in values.split(",") if int(x)%2!=0] 418 | print ",".join(numbers) 419 | #----------------------------------------# 420 | 421 | Question 17 422 | Level 2 423 | 424 | Question: 425 | Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: 426 | D 100 427 | W 200 428 | 429 | D means deposit while W means withdrawal. 430 | Suppose the following input is supplied to the program: 431 | D 300 432 | D 300 433 | W 200 434 | D 100 435 | Then, the output should be: 436 | 500 437 | 438 | Hints: 439 | In case of input data being supplied to the question, it should be assumed to be a console input. 440 | 441 | Solution: 442 | netAmount = 0 443 | while True: 444 | s = raw_input() 445 | if not s: 446 | break 447 | values = s.split(" ") 448 | operation = values[0] 449 | amount = int(values[1]) 450 | if operation=="D": 451 | netAmount+=amount 452 | elif operation=="W": 453 | netAmount-=amount 454 | else: 455 | pass 456 | print netAmount 457 | #----------------------------------------# 458 | 459 | #----------------------------------------# 460 | Question 18 461 | Level 3 462 | 463 | Question: 464 | A website requires the users to input username and password to register. Write a program to check the validity of password input by users. 465 | Following are the criteria for checking the password: 466 | 1. At least 1 letter between [a-z] 467 | 2. At least 1 number between [0-9] 468 | 1. At least 1 letter between [A-Z] 469 | 3. At least 1 character from [$#@] 470 | 4. Minimum length of transaction password: 6 471 | 5. Maximum length of transaction password: 12 472 | Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. 473 | Example 474 | If the following passwords are given as input to the program: 475 | ABd1234@1,a F1#,2w3E*,2We3345 476 | Then, the output of the program should be: 477 | ABd1234@1 478 | 479 | Hints: 480 | In case of input data being supplied to the question, it should be assumed to be a console input. 481 | 482 | Solutions: 483 | import re 484 | value = [] 485 | items=[x for x in raw_input().split(',')] 486 | for p in items: 487 | if len(p)<6 or len(p)>12: 488 | continue 489 | else: 490 | pass 491 | if not re.search("[a-z]",p): 492 | continue 493 | elif not re.search("[0-9]",p): 494 | continue 495 | elif not re.search("[A-Z]",p): 496 | continue 497 | elif not re.search("[$#@]",p): 498 | continue 499 | elif re.search("\s",p): 500 | continue 501 | else: 502 | pass 503 | value.append(p) 504 | print ",".join(value) 505 | #----------------------------------------# 506 | 507 | #----------------------------------------# 508 | Question 19 509 | Level 3 510 | 511 | Question: 512 | You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: 513 | 1: Sort based on name; 514 | 2: Then sort based on age; 515 | 3: Then sort by score. 516 | The priority is that name > age > score. 517 | If the following tuples are given as input to the program: 518 | Tom,19,80 519 | John,20,90 520 | Jony,17,91 521 | Jony,17,93 522 | Json,21,85 523 | Then, the output of the program should be: 524 | [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] 525 | 526 | Hints: 527 | In case of input data being supplied to the question, it should be assumed to be a console input. 528 | We use itemgetter to enable multiple sort keys. 529 | 530 | Solutions: 531 | from operator import itemgetter, attrgetter 532 | 533 | l = [] 534 | while True: 535 | s = raw_input() 536 | if not s: 537 | break 538 | l.append(tuple(s.split(","))) 539 | 540 | print sorted(l, key=itemgetter(0,1,2)) 541 | #----------------------------------------# 542 | 543 | #----------------------------------------# 544 | Question 20 545 | Level 3 546 | 547 | Question: 548 | Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. 549 | 550 | Hints: 551 | Consider use yield 552 | 553 | Solution: 554 | def putNumbers(n): 555 | i = 0 556 | while ilen2: 817 | print s1 818 | elif len2>len1: 819 | print s2 820 | else: 821 | print s1 822 | print s2 823 | 824 | 825 | printValue("one","three") 826 | 827 | 828 | 829 | #----------------------------------------# 830 | 2.10 831 | 832 | Question: 833 | Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number". 834 | 835 | Hints: 836 | 837 | Use % operator to check if a number is even or odd. 838 | 839 | Solution 840 | def checkValue(n): 841 | if n%2 == 0: 842 | print "It is an even number" 843 | else: 844 | print "It is an odd number" 845 | 846 | 847 | checkValue(7) 848 | 849 | 850 | #----------------------------------------# 851 | 2.10 852 | 853 | Question: 854 | Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. 855 | 856 | Hints: 857 | 858 | Use dict[key]=value pattern to put entry into a dictionary. 859 | Use ** operator to get power of a number. 860 | 861 | Solution 862 | def printDict(): 863 | d=dict() 864 | d[1]=1 865 | d[2]=2**2 866 | d[3]=3**2 867 | print d 868 | 869 | 870 | printDict() 871 | 872 | 873 | 874 | 875 | 876 | #----------------------------------------# 877 | 2.10 878 | 879 | Question: 880 | Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. 881 | 882 | Hints: 883 | 884 | Use dict[key]=value pattern to put entry into a dictionary. 885 | Use ** operator to get power of a number. 886 | Use range() for loops. 887 | 888 | Solution 889 | def printDict(): 890 | d=dict() 891 | for i in range(1,21): 892 | d[i]=i**2 893 | print d 894 | 895 | 896 | printDict() 897 | 898 | 899 | #----------------------------------------# 900 | 2.10 901 | 902 | Question: 903 | Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only. 904 | 905 | Hints: 906 | 907 | Use dict[key]=value pattern to put entry into a dictionary. 908 | Use ** operator to get power of a number. 909 | Use range() for loops. 910 | Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. 911 | 912 | Solution 913 | def printDict(): 914 | d=dict() 915 | for i in range(1,21): 916 | d[i]=i**2 917 | for (k,v) in d.items(): 918 | print v 919 | 920 | 921 | printDict() 922 | 923 | #----------------------------------------# 924 | 2.10 925 | 926 | Question: 927 | Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only. 928 | 929 | Hints: 930 | 931 | Use dict[key]=value pattern to put entry into a dictionary. 932 | Use ** operator to get power of a number. 933 | Use range() for loops. 934 | Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. 935 | 936 | Solution 937 | def printDict(): 938 | d=dict() 939 | for i in range(1,21): 940 | d[i]=i**2 941 | for k in d.keys(): 942 | print k 943 | 944 | 945 | printDict() 946 | 947 | 948 | #----------------------------------------# 949 | 2.10 950 | 951 | Question: 952 | Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). 953 | 954 | Hints: 955 | 956 | Use ** operator to get power of a number. 957 | Use range() for loops. 958 | Use list.append() to add values into a list. 959 | 960 | Solution 961 | def printList(): 962 | li=list() 963 | for i in range(1,21): 964 | li.append(i**2) 965 | print li 966 | 967 | 968 | printList() 969 | 970 | #----------------------------------------# 971 | 2.10 972 | 973 | Question: 974 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. 975 | 976 | Hints: 977 | 978 | Use ** operator to get power of a number. 979 | Use range() for loops. 980 | Use list.append() to add values into a list. 981 | Use [n1:n2] to slice a list 982 | 983 | Solution 984 | def printList(): 985 | li=list() 986 | for i in range(1,21): 987 | li.append(i**2) 988 | print li[:5] 989 | 990 | 991 | printList() 992 | 993 | 994 | #----------------------------------------# 995 | 2.10 996 | 997 | Question: 998 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list. 999 | 1000 | Hints: 1001 | 1002 | Use ** operator to get power of a number. 1003 | Use range() for loops. 1004 | Use list.append() to add values into a list. 1005 | Use [n1:n2] to slice a list 1006 | 1007 | Solution 1008 | def printList(): 1009 | li=list() 1010 | for i in range(1,21): 1011 | li.append(i**2) 1012 | print li[-5:] 1013 | 1014 | 1015 | printList() 1016 | 1017 | 1018 | #----------------------------------------# 1019 | 2.10 1020 | 1021 | Question: 1022 | Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. 1023 | 1024 | Hints: 1025 | 1026 | Use ** operator to get power of a number. 1027 | Use range() for loops. 1028 | Use list.append() to add values into a list. 1029 | Use [n1:n2] to slice a list 1030 | 1031 | Solution 1032 | def printList(): 1033 | li=list() 1034 | for i in range(1,21): 1035 | li.append(i**2) 1036 | print li[5:] 1037 | 1038 | 1039 | printList() 1040 | 1041 | 1042 | #----------------------------------------# 1043 | 2.10 1044 | 1045 | Question: 1046 | Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). 1047 | 1048 | Hints: 1049 | 1050 | Use ** operator to get power of a number. 1051 | Use range() for loops. 1052 | Use list.append() to add values into a list. 1053 | Use tuple() to get a tuple from a list. 1054 | 1055 | Solution 1056 | def printTuple(): 1057 | li=list() 1058 | for i in range(1,21): 1059 | li.append(i**2) 1060 | print tuple(li) 1061 | 1062 | printTuple() 1063 | 1064 | 1065 | 1066 | #----------------------------------------# 1067 | 2.10 1068 | 1069 | Question: 1070 | With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line. 1071 | 1072 | Hints: 1073 | 1074 | Use [n1:n2] notation to get a slice from a tuple. 1075 | 1076 | Solution 1077 | tp=(1,2,3,4,5,6,7,8,9,10) 1078 | tp1=tp[:5] 1079 | tp2=tp[5:] 1080 | print tp1 1081 | print tp2 1082 | 1083 | 1084 | #----------------------------------------# 1085 | 2.10 1086 | 1087 | Question: 1088 | Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). 1089 | 1090 | Hints: 1091 | 1092 | Use "for" to iterate the tuple 1093 | Use tuple() to generate a tuple from a list. 1094 | 1095 | Solution 1096 | tp=(1,2,3,4,5,6,7,8,9,10) 1097 | li=list() 1098 | for i in tp: 1099 | if tp[i]%2==0: 1100 | li.append(tp[i]) 1101 | 1102 | tp2=tuple(li) 1103 | print tp2 1104 | 1105 | 1106 | 1107 | #----------------------------------------# 1108 | 2.14 1109 | 1110 | Question: 1111 | Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". 1112 | 1113 | Hints: 1114 | 1115 | Use if statement to judge condition. 1116 | 1117 | Solution 1118 | s= raw_input() 1119 | if s=="yes" or s=="YES" or s=="Yes": 1120 | print "Yes" 1121 | else: 1122 | print "No" 1123 | 1124 | 1125 | 1126 | #----------------------------------------# 1127 | 3.4 1128 | 1129 | Question: 1130 | Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. 1131 | 1132 | Hints: 1133 | 1134 | Use filter() to filter some elements in a list. 1135 | Use lambda to define anonymous functions. 1136 | 1137 | Solution 1138 | li = [1,2,3,4,5,6,7,8,9,10] 1139 | evenNumbers = filter(lambda x: x%2==0, li) 1140 | print evenNumbers 1141 | 1142 | 1143 | #----------------------------------------# 1144 | 3.4 1145 | 1146 | Question: 1147 | Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. 1148 | 1149 | Hints: 1150 | 1151 | Use map() to generate a list. 1152 | Use lambda to define anonymous functions. 1153 | 1154 | Solution 1155 | li = [1,2,3,4,5,6,7,8,9,10] 1156 | squaredNumbers = map(lambda x: x**2, li) 1157 | print squaredNumbers 1158 | 1159 | #----------------------------------------# 1160 | 3.5 1161 | 1162 | Question: 1163 | Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10]. 1164 | 1165 | Hints: 1166 | 1167 | Use map() to generate a list. 1168 | Use filter() to filter elements of a list. 1169 | Use lambda to define anonymous functions. 1170 | 1171 | Solution 1172 | li = [1,2,3,4,5,6,7,8,9,10] 1173 | evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) 1174 | print evenNumbers 1175 | 1176 | 1177 | 1178 | 1179 | #----------------------------------------# 1180 | 3.5 1181 | 1182 | Question: 1183 | Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). 1184 | 1185 | Hints: 1186 | 1187 | Use filter() to filter elements of a list. 1188 | Use lambda to define anonymous functions. 1189 | 1190 | Solution 1191 | evenNumbers = filter(lambda x: x%2==0, range(1,21)) 1192 | print evenNumbers 1193 | 1194 | 1195 | #----------------------------------------# 1196 | 3.5 1197 | 1198 | Question: 1199 | Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). 1200 | 1201 | Hints: 1202 | 1203 | Use map() to generate a list. 1204 | Use lambda to define anonymous functions. 1205 | 1206 | Solution 1207 | squaredNumbers = map(lambda x: x**2, range(1,21)) 1208 | print squaredNumbers 1209 | 1210 | 1211 | 1212 | 1213 | #----------------------------------------# 1214 | 7.2 1215 | 1216 | Question: 1217 | Define a class named American which has a static method called printNationality. 1218 | 1219 | Hints: 1220 | 1221 | Use @staticmethod decorator to define class static method. 1222 | 1223 | Solution 1224 | class American(object): 1225 | @staticmethod 1226 | def printNationality(): 1227 | print "America" 1228 | 1229 | anAmerican = American() 1230 | anAmerican.printNationality() 1231 | American.printNationality() 1232 | 1233 | 1234 | 1235 | 1236 | #----------------------------------------# 1237 | 1238 | 7.2 1239 | 1240 | Question: 1241 | Define a class named American and its subclass NewYorker. 1242 | 1243 | Hints: 1244 | 1245 | Use class Subclass(ParentClass) to define a subclass. 1246 | 1247 | Solution: 1248 | 1249 | class American(object): 1250 | pass 1251 | 1252 | class NewYorker(American): 1253 | pass 1254 | 1255 | anAmerican = American() 1256 | aNewYorker = NewYorker() 1257 | print anAmerican 1258 | print aNewYorker 1259 | 1260 | 1261 | 1262 | 1263 | #----------------------------------------# 1264 | 1265 | 1266 | 7.2 1267 | 1268 | Question: 1269 | Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. 1270 | 1271 | Hints: 1272 | 1273 | Use def methodName(self) to define a method. 1274 | 1275 | Solution: 1276 | 1277 | class Circle(object): 1278 | def __init__(self, r): 1279 | self.radius = r 1280 | 1281 | def area(self): 1282 | return self.radius**2*3.14 1283 | 1284 | aCircle = Circle(2) 1285 | print aCircle.area() 1286 | 1287 | 1288 | 1289 | 1290 | 1291 | 1292 | #----------------------------------------# 1293 | 1294 | 7.2 1295 | 1296 | Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. 1297 | 1298 | Hints: 1299 | 1300 | Use def methodName(self) to define a method. 1301 | 1302 | Solution: 1303 | 1304 | class Rectangle(object): 1305 | def __init__(self, l, w): 1306 | self.length = l 1307 | self.width = w 1308 | 1309 | def area(self): 1310 | return self.length*self.width 1311 | 1312 | aRectangle = Rectangle(2,10) 1313 | print aRectangle.area() 1314 | 1315 | 1316 | 1317 | 1318 | #----------------------------------------# 1319 | 1320 | 7.2 1321 | 1322 | Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. 1323 | 1324 | Hints: 1325 | 1326 | To override a method in super class, we can define a method with the same name in the super class. 1327 | 1328 | Solution: 1329 | 1330 | class Shape(object): 1331 | def __init__(self): 1332 | pass 1333 | 1334 | def area(self): 1335 | return 0 1336 | 1337 | class Square(Shape): 1338 | def __init__(self, l): 1339 | Shape.__init__(self) 1340 | self.length = l 1341 | 1342 | def area(self): 1343 | return self.length*self.length 1344 | 1345 | aSquare= Square(3) 1346 | print aSquare.area() 1347 | 1348 | 1349 | 1350 | 1351 | 1352 | 1353 | 1354 | 1355 | #----------------------------------------# 1356 | 1357 | 1358 | Please raise a RuntimeError exception. 1359 | 1360 | Hints: 1361 | 1362 | Use raise() to raise an exception. 1363 | 1364 | Solution: 1365 | 1366 | raise RuntimeError('something wrong') 1367 | 1368 | 1369 | 1370 | #----------------------------------------# 1371 | Write a function to compute 5/0 and use try/except to catch the exceptions. 1372 | 1373 | Hints: 1374 | 1375 | Use try/except to catch exceptions. 1376 | 1377 | Solution: 1378 | 1379 | def throws(): 1380 | return 5/0 1381 | 1382 | try: 1383 | throws() 1384 | except ZeroDivisionError: 1385 | print "division by zero!" 1386 | except Exception, err: 1387 | print 'Caught an exception' 1388 | finally: 1389 | print 'In finally block for cleanup' 1390 | 1391 | 1392 | #----------------------------------------# 1393 | Define a custom exception class which takes a string message as attribute. 1394 | 1395 | Hints: 1396 | 1397 | To define a custom exception, we need to define a class inherited from Exception. 1398 | 1399 | Solution: 1400 | 1401 | class MyError(Exception): 1402 | """My own exception class 1403 | 1404 | Attributes: 1405 | msg -- explanation of the error 1406 | """ 1407 | 1408 | def __init__(self, msg): 1409 | self.msg = msg 1410 | 1411 | error = MyError("something wrong") 1412 | 1413 | #----------------------------------------# 1414 | Question: 1415 | 1416 | Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only. 1417 | 1418 | Example: 1419 | If the following email address is given as input to the program: 1420 | 1421 | john@google.com 1422 | 1423 | Then, the output of the program should be: 1424 | 1425 | john 1426 | 1427 | In case of input data being supplied to the question, it should be assumed to be a console input. 1428 | 1429 | Hints: 1430 | 1431 | Use \w to match letters. 1432 | 1433 | Solution: 1434 | import re 1435 | emailAddress = raw_input() 1436 | pat2 = "(\w+)@((\w+\.)+(com))" 1437 | r2 = re.match(pat2,emailAddress) 1438 | print r2.group(1) 1439 | 1440 | 1441 | #----------------------------------------# 1442 | Question: 1443 | 1444 | Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. 1445 | 1446 | Example: 1447 | If the following email address is given as input to the program: 1448 | 1449 | john@google.com 1450 | 1451 | Then, the output of the program should be: 1452 | 1453 | google 1454 | 1455 | In case of input data being supplied to the question, it should be assumed to be a console input. 1456 | 1457 | Hints: 1458 | 1459 | Use \w to match letters. 1460 | 1461 | Solution: 1462 | import re 1463 | emailAddress = raw_input() 1464 | pat2 = "(\w+)@(\w+)\.(com)" 1465 | r2 = re.match(pat2,emailAddress) 1466 | print r2.group(2) 1467 | 1468 | 1469 | 1470 | 1471 | #----------------------------------------# 1472 | Question: 1473 | 1474 | Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. 1475 | 1476 | Example: 1477 | If the following words is given as input to the program: 1478 | 1479 | 2 cats and 3 dogs. 1480 | 1481 | Then, the output of the program should be: 1482 | 1483 | ['2', '3'] 1484 | 1485 | In case of input data being supplied to the question, it should be assumed to be a console input. 1486 | 1487 | Hints: 1488 | 1489 | Use re.findall() to find all substring using regex. 1490 | 1491 | Solution: 1492 | import re 1493 | s = raw_input() 1494 | print re.findall("\d+",s) 1495 | 1496 | 1497 | #----------------------------------------# 1498 | Question: 1499 | 1500 | 1501 | Print a unicode string "hello world". 1502 | 1503 | Hints: 1504 | 1505 | Use u'strings' format to define unicode string. 1506 | 1507 | Solution: 1508 | 1509 | unicodeString = u"hello world!" 1510 | print unicodeString 1511 | 1512 | #----------------------------------------# 1513 | Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. 1514 | 1515 | Hints: 1516 | 1517 | Use unicode() function to convert. 1518 | 1519 | Solution: 1520 | 1521 | s = raw_input() 1522 | u = unicode( s ,"utf-8") 1523 | print u 1524 | 1525 | #----------------------------------------# 1526 | Question: 1527 | 1528 | Write a special comment to indicate a Python source code file is in unicode. 1529 | 1530 | Hints: 1531 | 1532 | Solution: 1533 | 1534 | # -*- coding: utf-8 -*- 1535 | 1536 | #----------------------------------------# 1537 | Question: 1538 | 1539 | Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). 1540 | 1541 | Example: 1542 | If the following n is given as input to the program: 1543 | 1544 | 5 1545 | 1546 | Then, the output of the program should be: 1547 | 1548 | 3.55 1549 | 1550 | In case of input data being supplied to the question, it should be assumed to be a console input. 1551 | 1552 | Hints: 1553 | Use float() to convert an integer to a float 1554 | 1555 | Solution: 1556 | 1557 | n=int(raw_input()) 1558 | sum=0.0 1559 | for i in range(1,n+1): 1560 | sum += float(float(i)/(i+1)) 1561 | print sum 1562 | 1563 | 1564 | #----------------------------------------# 1565 | Question: 1566 | 1567 | Write a program to compute: 1568 | 1569 | f(n)=f(n-1)+100 when n>0 1570 | and f(0)=1 1571 | 1572 | with a given n input by console (n>0). 1573 | 1574 | Example: 1575 | If the following n is given as input to the program: 1576 | 1577 | 5 1578 | 1579 | Then, the output of the program should be: 1580 | 1581 | 500 1582 | 1583 | In case of input data being supplied to the question, it should be assumed to be a console input. 1584 | 1585 | Hints: 1586 | We can define recursive function in Python. 1587 | 1588 | Solution: 1589 | 1590 | def f(n): 1591 | if n==0: 1592 | return 0 1593 | else: 1594 | return f(n-1)+100 1595 | 1596 | n=int(raw_input()) 1597 | print f(n) 1598 | 1599 | #----------------------------------------# 1600 | 1601 | Question: 1602 | 1603 | 1604 | The Fibonacci Sequence is computed based on the following formula: 1605 | 1606 | 1607 | f(n)=0 if n=0 1608 | f(n)=1 if n=1 1609 | f(n)=f(n-1)+f(n-2) if n>1 1610 | 1611 | Please write a program to compute the value of f(n) with a given n input by console. 1612 | 1613 | Example: 1614 | If the following n is given as input to the program: 1615 | 1616 | 7 1617 | 1618 | Then, the output of the program should be: 1619 | 1620 | 13 1621 | 1622 | In case of input data being supplied to the question, it should be assumed to be a console input. 1623 | 1624 | Hints: 1625 | We can define recursive function in Python. 1626 | 1627 | 1628 | Solution: 1629 | 1630 | def f(n): 1631 | if n == 0: return 0 1632 | elif n == 1: return 1 1633 | else: return f(n-1)+f(n-2) 1634 | 1635 | n=int(raw_input()) 1636 | print f(n) 1637 | 1638 | 1639 | #----------------------------------------# 1640 | 1641 | #----------------------------------------# 1642 | 1643 | Question: 1644 | 1645 | The Fibonacci Sequence is computed based on the following formula: 1646 | 1647 | 1648 | f(n)=0 if n=0 1649 | f(n)=1 if n=1 1650 | f(n)=f(n-1)+f(n-2) if n>1 1651 | 1652 | Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console. 1653 | 1654 | Example: 1655 | If the following n is given as input to the program: 1656 | 1657 | 7 1658 | 1659 | Then, the output of the program should be: 1660 | 1661 | 0,1,1,2,3,5,8,13 1662 | 1663 | 1664 | Hints: 1665 | We can define recursive function in Python. 1666 | Use list comprehension to generate a list from an existing list. 1667 | Use string.join() to join a list of strings. 1668 | 1669 | In case of input data being supplied to the question, it should be assumed to be a console input. 1670 | 1671 | Solution: 1672 | 1673 | def f(n): 1674 | if n == 0: return 0 1675 | elif n == 1: return 1 1676 | else: return f(n-1)+f(n-2) 1677 | 1678 | n=int(raw_input()) 1679 | values = [str(f(x)) for x in range(0, n+1)] 1680 | print ",".join(values) 1681 | 1682 | 1683 | #----------------------------------------# 1684 | 1685 | Question: 1686 | 1687 | Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console. 1688 | 1689 | Example: 1690 | If the following n is given as input to the program: 1691 | 1692 | 10 1693 | 1694 | Then, the output of the program should be: 1695 | 1696 | 0,2,4,6,8,10 1697 | 1698 | Hints: 1699 | Use yield to produce the next value in generator. 1700 | 1701 | In case of input data being supplied to the question, it should be assumed to be a console input. 1702 | 1703 | Solution: 1704 | 1705 | def EvenGenerator(n): 1706 | i=0 1707 | while i<=n: 1708 | if i%2==0: 1709 | yield i 1710 | i+=1 1711 | 1712 | 1713 | n=int(raw_input()) 1714 | values = [] 1715 | for i in EvenGenerator(n): 1716 | values.append(str(i)) 1717 | 1718 | print ",".join(values) 1719 | 1720 | 1721 | #----------------------------------------# 1722 | 1723 | Question: 1724 | 1725 | Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console. 1726 | 1727 | Example: 1728 | If the following n is given as input to the program: 1729 | 1730 | 100 1731 | 1732 | Then, the output of the program should be: 1733 | 1734 | 0,35,70 1735 | 1736 | Hints: 1737 | Use yield to produce the next value in generator. 1738 | 1739 | In case of input data being supplied to the question, it should be assumed to be a console input. 1740 | 1741 | Solution: 1742 | 1743 | def NumGenerator(n): 1744 | for i in range(n+1): 1745 | if i%5==0 and i%7==0: 1746 | yield i 1747 | 1748 | n=int(raw_input()) 1749 | values = [] 1750 | for i in NumGenerator(n): 1751 | values.append(str(i)) 1752 | 1753 | print ",".join(values) 1754 | 1755 | 1756 | #----------------------------------------# 1757 | 1758 | Question: 1759 | 1760 | 1761 | Please write assert statements to verify that every number in the list [2,4,6,8] is even. 1762 | 1763 | 1764 | 1765 | Hints: 1766 | Use "assert expression" to make assertion. 1767 | 1768 | 1769 | Solution: 1770 | 1771 | li = [2,4,6,8] 1772 | for i in li: 1773 | assert i%2==0 1774 | 1775 | 1776 | #----------------------------------------# 1777 | Question: 1778 | 1779 | Please write a program which accepts basic mathematic expression from console and print the evaluation result. 1780 | 1781 | Example: 1782 | If the following string is given as input to the program: 1783 | 1784 | 35+3 1785 | 1786 | Then, the output of the program should be: 1787 | 1788 | 38 1789 | 1790 | Hints: 1791 | Use eval() to evaluate an expression. 1792 | 1793 | 1794 | Solution: 1795 | 1796 | expression = raw_input() 1797 | print eval(expression) 1798 | 1799 | 1800 | #----------------------------------------# 1801 | Question: 1802 | 1803 | Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. 1804 | 1805 | 1806 | Hints: 1807 | Use if/elif to deal with conditions. 1808 | 1809 | 1810 | Solution: 1811 | 1812 | import math 1813 | def bin_search(li, element): 1814 | bottom = 0 1815 | top = len(li)-1 1816 | index = -1 1817 | while top>=bottom and index==-1: 1818 | mid = int(math.floor((top+bottom)/2.0)) 1819 | if li[mid]==element: 1820 | index = mid 1821 | elif li[mid]>element: 1822 | top = mid-1 1823 | else: 1824 | bottom = mid+1 1825 | 1826 | return index 1827 | 1828 | li=[2,5,7,9,11,17,222] 1829 | print bin_search(li,11) 1830 | print bin_search(li,12) 1831 | 1832 | 1833 | 1834 | 1835 | #----------------------------------------# 1836 | Question: 1837 | 1838 | Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list. 1839 | 1840 | 1841 | Hints: 1842 | Use if/elif to deal with conditions. 1843 | 1844 | 1845 | Solution: 1846 | 1847 | import math 1848 | def bin_search(li, element): 1849 | bottom = 0 1850 | top = len(li)-1 1851 | index = -1 1852 | while top>=bottom and index==-1: 1853 | mid = int(math.floor((top+bottom)/2.0)) 1854 | if li[mid]==element: 1855 | index = mid 1856 | elif li[mid]>element: 1857 | top = mid-1 1858 | else: 1859 | bottom = mid+1 1860 | 1861 | return index 1862 | 1863 | li=[2,5,7,9,11,17,222] 1864 | print bin_search(li,11) 1865 | print bin_search(li,12) 1866 | 1867 | 1868 | 1869 | 1870 | #----------------------------------------# 1871 | Question: 1872 | 1873 | Please generate a random float where the value is between 10 and 100 using Python math module. 1874 | 1875 | 1876 | 1877 | Hints: 1878 | Use random.random() to generate a random float in [0,1]. 1879 | 1880 | 1881 | Solution: 1882 | 1883 | import random 1884 | print random.random()*100 1885 | 1886 | #----------------------------------------# 1887 | Question: 1888 | 1889 | Please generate a random float where the value is between 5 and 95 using Python math module. 1890 | 1891 | 1892 | 1893 | Hints: 1894 | Use random.random() to generate a random float in [0,1]. 1895 | 1896 | 1897 | Solution: 1898 | 1899 | import random 1900 | print random.random()*100-5 1901 | 1902 | 1903 | #----------------------------------------# 1904 | Question: 1905 | 1906 | Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. 1907 | 1908 | 1909 | 1910 | Hints: 1911 | Use random.choice() to a random element from a list. 1912 | 1913 | 1914 | Solution: 1915 | 1916 | import random 1917 | print random.choice([i for i in range(11) if i%2==0]) 1918 | 1919 | 1920 | #----------------------------------------# 1921 | Question: 1922 | 1923 | Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension. 1924 | 1925 | 1926 | 1927 | Hints: 1928 | Use random.choice() to a random element from a list. 1929 | 1930 | 1931 | Solution: 1932 | 1933 | import random 1934 | print random.choice([i for i in range(201) if i%5==0 and i%7==0]) 1935 | 1936 | 1937 | 1938 | #----------------------------------------# 1939 | 1940 | Question: 1941 | 1942 | Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. 1943 | 1944 | 1945 | 1946 | Hints: 1947 | Use random.sample() to generate a list of random values. 1948 | 1949 | 1950 | Solution: 1951 | 1952 | import random 1953 | print random.sample(range(100), 5) 1954 | 1955 | #----------------------------------------# 1956 | Question: 1957 | 1958 | Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. 1959 | 1960 | 1961 | 1962 | Hints: 1963 | Use random.sample() to generate a list of random values. 1964 | 1965 | 1966 | Solution: 1967 | 1968 | import random 1969 | print random.sample([i for i in range(100,201) if i%2==0], 5) 1970 | 1971 | 1972 | #----------------------------------------# 1973 | Question: 1974 | 1975 | Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. 1976 | 1977 | 1978 | 1979 | Hints: 1980 | Use random.sample() to generate a list of random values. 1981 | 1982 | 1983 | Solution: 1984 | 1985 | import random 1986 | print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) 1987 | 1988 | #----------------------------------------# 1989 | 1990 | Question: 1991 | 1992 | Please write a program to randomly print a integer number between 7 and 15 inclusive. 1993 | 1994 | 1995 | 1996 | Hints: 1997 | Use random.randrange() to a random integer in a given range. 1998 | 1999 | 2000 | Solution: 2001 | 2002 | import random 2003 | print random.randrange(7,16) 2004 | 2005 | #----------------------------------------# 2006 | 2007 | Question: 2008 | 2009 | Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". 2010 | 2011 | 2012 | 2013 | Hints: 2014 | Use zlib.compress() and zlib.decompress() to compress and decompress a string. 2015 | 2016 | 2017 | Solution: 2018 | 2019 | import zlib 2020 | s = 'hello world!hello world!hello world!hello world!' 2021 | t = zlib.compress(s) 2022 | print t 2023 | print zlib.decompress(t) 2024 | 2025 | #----------------------------------------# 2026 | Question: 2027 | 2028 | Please write a program to print the running time of execution of "1+1" for 100 times. 2029 | 2030 | 2031 | 2032 | Hints: 2033 | Use timeit() function to measure the running time. 2034 | 2035 | Solution: 2036 | 2037 | from timeit import Timer 2038 | t = Timer("for i in range(100):1+1") 2039 | print t.timeit() 2040 | 2041 | #----------------------------------------# 2042 | Question: 2043 | 2044 | Please write a program to shuffle and print the list [3,6,7,8]. 2045 | 2046 | 2047 | 2048 | Hints: 2049 | Use shuffle() function to shuffle a list. 2050 | 2051 | Solution: 2052 | 2053 | from random import shuffle 2054 | li = [3,6,7,8] 2055 | shuffle(li) 2056 | print li 2057 | 2058 | #----------------------------------------# 2059 | Question: 2060 | 2061 | Please write a program to shuffle and print the list [3,6,7,8]. 2062 | 2063 | 2064 | 2065 | Hints: 2066 | Use shuffle() function to shuffle a list. 2067 | 2068 | Solution: 2069 | 2070 | from random import shuffle 2071 | li = [3,6,7,8] 2072 | shuffle(li) 2073 | print li 2074 | 2075 | 2076 | 2077 | #----------------------------------------# 2078 | Question: 2079 | 2080 | Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"]. 2081 | 2082 | Hints: 2083 | Use list[index] notation to get a element from a list. 2084 | 2085 | Solution: 2086 | 2087 | subjects=["I", "You"] 2088 | verbs=["Play", "Love"] 2089 | objects=["Hockey","Football"] 2090 | for i in range(len(subjects)): 2091 | for j in range(len(verbs)): 2092 | for k in range(len(objects)): 2093 | sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) 2094 | print sentence 2095 | 2096 | 2097 | #----------------------------------------# 2098 | Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. 2099 | 2100 | Hints: 2101 | Use list comprehension to delete a bunch of element from a list. 2102 | 2103 | Solution: 2104 | 2105 | li = [5,6,77,45,22,12,24] 2106 | li = [x for x in li if x%2!=0] 2107 | print li 2108 | 2109 | #----------------------------------------# 2110 | Question: 2111 | 2112 | By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155]. 2113 | 2114 | Hints: 2115 | Use list comprehension to delete a bunch of element from a list. 2116 | 2117 | Solution: 2118 | 2119 | li = [12,24,35,70,88,120,155] 2120 | li = [x for x in li if x%5!=0 and x%7!=0] 2121 | print li 2122 | 2123 | 2124 | #----------------------------------------# 2125 | Question: 2126 | 2127 | By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155]. 2128 | 2129 | Hints: 2130 | Use list comprehension to delete a bunch of element from a list. 2131 | Use enumerate() to get (index, value) tuple. 2132 | 2133 | Solution: 2134 | 2135 | li = [12,24,35,70,88,120,155] 2136 | li = [x for (i,x) in enumerate(li) if i%2!=0] 2137 | print li 2138 | 2139 | #----------------------------------------# 2140 | 2141 | Question: 2142 | 2143 | By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0. 2144 | 2145 | Hints: 2146 | Use list comprehension to make an array. 2147 | 2148 | Solution: 2149 | 2150 | array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] 2151 | print array 2152 | 2153 | #----------------------------------------# 2154 | Question: 2155 | 2156 | By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155]. 2157 | 2158 | Hints: 2159 | Use list comprehension to delete a bunch of element from a list. 2160 | Use enumerate() to get (index, value) tuple. 2161 | 2162 | Solution: 2163 | 2164 | li = [12,24,35,70,88,120,155] 2165 | li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] 2166 | print li 2167 | 2168 | 2169 | 2170 | #----------------------------------------# 2171 | 2172 | Question: 2173 | 2174 | By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155]. 2175 | 2176 | Hints: 2177 | Use list's remove method to delete a value. 2178 | 2179 | Solution: 2180 | 2181 | li = [12,24,35,24,88,120,155] 2182 | li = [x for x in li if x!=24] 2183 | print li 2184 | 2185 | 2186 | #----------------------------------------# 2187 | Question: 2188 | 2189 | With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists. 2190 | 2191 | Hints: 2192 | Use set() and "&=" to do set intersection operation. 2193 | 2194 | Solution: 2195 | 2196 | set1=set([1,3,6,78,35,55]) 2197 | set2=set([12,24,35,24,88,120,155]) 2198 | set1 &= set2 2199 | li=list(set1) 2200 | print li 2201 | 2202 | #----------------------------------------# 2203 | 2204 | With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved. 2205 | 2206 | Hints: 2207 | Use set() to store a number of values without duplicate. 2208 | 2209 | Solution: 2210 | 2211 | def removeDuplicate( li ): 2212 | newli=[] 2213 | seen = set() 2214 | for item in li: 2215 | if item not in seen: 2216 | seen.add( item ) 2217 | newli.append(item) 2218 | 2219 | return newli 2220 | 2221 | li=[12,24,35,24,88,120,155,88,120,155] 2222 | print removeDuplicate(li) 2223 | 2224 | 2225 | #----------------------------------------# 2226 | Question: 2227 | 2228 | Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class. 2229 | 2230 | Hints: 2231 | Use Subclass(Parentclass) to define a child class. 2232 | 2233 | Solution: 2234 | 2235 | class Person(object): 2236 | def getGender( self ): 2237 | return "Unknown" 2238 | 2239 | class Male( Person ): 2240 | def getGender( self ): 2241 | return "Male" 2242 | 2243 | class Female( Person ): 2244 | def getGender( self ): 2245 | return "Female" 2246 | 2247 | aMale = Male() 2248 | aFemale= Female() 2249 | print aMale.getGender() 2250 | print aFemale.getGender() 2251 | 2252 | 2253 | 2254 | #----------------------------------------# 2255 | Question: 2256 | 2257 | Please write a program which count and print the numbers of each character in a string input by console. 2258 | 2259 | Example: 2260 | If the following string is given as input to the program: 2261 | 2262 | abcdefgabc 2263 | 2264 | Then, the output of the program should be: 2265 | 2266 | a,2 2267 | c,2 2268 | b,2 2269 | e,1 2270 | d,1 2271 | g,1 2272 | f,1 2273 | 2274 | Hints: 2275 | Use dict to store key/value pairs. 2276 | Use dict.get() method to lookup a key with default value. 2277 | 2278 | Solution: 2279 | 2280 | dic = {} 2281 | s=raw_input() 2282 | for s in s: 2283 | dic[s] = dic.get(s,0)+1 2284 | print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) 2285 | 2286 | #----------------------------------------# 2287 | 2288 | Question: 2289 | 2290 | Please write a program which accepts a string from console and print it in reverse order. 2291 | 2292 | Example: 2293 | If the following string is given as input to the program: 2294 | 2295 | rise to vote sir 2296 | 2297 | Then, the output of the program should be: 2298 | 2299 | ris etov ot esir 2300 | 2301 | Hints: 2302 | Use list[::-1] to iterate a list in a reverse order. 2303 | 2304 | Solution: 2305 | 2306 | s=raw_input() 2307 | s = s[::-1] 2308 | print s 2309 | 2310 | #----------------------------------------# 2311 | 2312 | Question: 2313 | 2314 | Please write a program which accepts a string from console and print the characters that have even indexes. 2315 | 2316 | Example: 2317 | If the following string is given as input to the program: 2318 | 2319 | H1e2l3l4o5w6o7r8l9d 2320 | 2321 | Then, the output of the program should be: 2322 | 2323 | Helloworld 2324 | 2325 | Hints: 2326 | Use list[::2] to iterate a list by step 2. 2327 | 2328 | Solution: 2329 | 2330 | s=raw_input() 2331 | s = s[::2] 2332 | print s 2333 | #----------------------------------------# 2334 | 2335 | 2336 | Question: 2337 | 2338 | Please write a program which prints all permutations of [1,2,3] 2339 | 2340 | 2341 | Hints: 2342 | Use itertools.permutations() to get permutations of list. 2343 | 2344 | Solution: 2345 | 2346 | import itertools 2347 | print list(itertools.permutations([1,2,3])) 2348 | 2349 | #----------------------------------------# 2350 | Question: 2351 | 2352 | Write a program to solve a classic ancient Chinese puzzle: 2353 | We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? 2354 | 2355 | Hint: 2356 | Use for loop to iterate all possible solutions. 2357 | 2358 | Solution: 2359 | 2360 | def solve(numheads,numlegs): 2361 | ns='No solutions!' 2362 | for i in range(numheads+1): 2363 | j=numheads-i 2364 | if 2*i+4*j==numlegs: 2365 | return i,j 2366 | return ns,ns 2367 | 2368 | numheads=35 2369 | numlegs=94 2370 | solutions=solve(numheads,numlegs) 2371 | print solutions 2372 | 2373 | #----------------------------------------# 2374 | 2375 | 2376 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [Ask DeepWiki.com](https://deepwiki.com/zhiwehu/Python-programming-exercises) 2 | 3 | # Python-programming-exercises 4 | 5 | 100+ Python challenge programming exercises. 6 | 7 | ## 100+ Python Projects Challenge 8 | 9 | https://github.com/zhiwehu/100_plus_Python_Projects_Challenge 10 | 11 | ## A simple Python online IDE run in browser. 12 | 13 | Hey guys I just made a simple Python online IDE run in browser : https://github.com/zhiwehu/react-python-ide. It's free and opensource. Feel free to let me know if you have any issues. 14 | 15 | ## Python comic 16 | 17 | Hey guys I just created a comic for learning Python if you like you could see it from here: https://zhixinfuture.com 18 | For now I just use Chinese if you like I could use English as well. 19 | 20 | ![Python Comic](https://github.com/zhiwehu/Python-programming-exercises/blob/master/comic.png?raw=true) 21 | -------------------------------------------------------------------------------- /comic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/92520209b8592aab3fff0aa37834067e7ed1390c/comic.png -------------------------------------------------------------------------------- /python contents.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/92520209b8592aab3fff0aa37834067e7ed1390c/python contents.docx -------------------------------------------------------------------------------- /python contents.txt: -------------------------------------------------------------------------------- 1 | Python 2 | The below table largely covers the TOC for 5 popular books. Learning Python (Fourth Edition) has a more in-depth look at concepts than any of the other books. However this book also does not essentially cover some aspects that are covered in other books. 3 | No. Diving into Python The Python Standard Library by Example Python Essential Reference (4th edition) The Quick Python Book Learning Python 4 | Introductory Concepts covering installation on different OS, version history, interpreter. This section also covers questions like Why, Who, What and Where on Python. 5 | 1 1. Installing Python 6 | 2. Which Python is right for you ? 7 | 3. Python & your OS 8 | 4. Interactive Shell 9 | 5. Summary 1. Introduction (Text) 1. Tutorial Introduction 10 | 2. Lexical Conventions and Syntax 1. About Python 11 | 2. Getting Started 1. Python Q & A Session 12 | 1. Why do people use Python ? 13 | 2. Downside of using it 14 | 3. Who uses Python Today ? 15 | 4. What Can I do with Python ? 16 | 5. Python vs Language X 17 | 6. Test your Knowledge 18 | 2. How Python runs programs 19 | 1. Python Interpreter 20 | 2. Program Execution 21 | 1. Programmer View 22 | 2. Python View 23 | 3. Execution Model Variations 24 | 1. Implementation Alternatives 25 | 2. Execution Optimization Tools 26 | 3. Frozen Binaries 27 | 3. How you run programs 28 | 1. Interactive prompt 29 | 2. Your first script 30 | 31 | Python Object Types, Numeric Types, Data Structures, Control Structures, Scopes and Arguments 32 | 2 1. Your first program 33 | 2. Declaring Functions 34 | 3. Python Data types vs Other Languages 35 | 4. Documenting Functions 36 | 5. Everything is an Object 37 | 6. The Import Search Path 38 | 7. What is an Object ? 39 | 8. Indenting Code 40 | 9. Testing Modules 41 | 10. Native Datatypes 42 | 1. Dictionaries 43 | 2. List 44 | 3. Tuples 45 | 11. Variables & referencing 1. Data Structures 1. Types and Objects 46 | 2. Operators and Expressions 47 | 3. Program Structure and Control Flow 48 | 4. Functions and Functional Programming 49 | 5. Classes and Object Oriented Programming 50 | 6. Modules, Packages and Distribution 51 | 7. Input and Output 52 | 8. Execution Environment 53 | 9. Testing, Debugging, Profiling and Tuning 54 | 55 | Data Structures, Algorithms & Code simplification 56 | String & Text Handling 1. Python Overview 57 | 1. Built-in Data types 58 | 2. Control Structures 59 | 3. Module 60 | 4. OOPs 61 | 2. Basics 62 | 1. Lists 63 | 2. Dictionaries 64 | 3. Tuple 65 | 4. Sets 66 | 5. Strings 67 | 6. Control Flow 68 | 3. Functions 69 | 4. Modules and Scoping Rules 70 | 5. Python Programs 1. Introducing Python Object Types 71 | 1. Why use built-in Types ? 72 | 2. Core data types 73 | 3. Numbers, Lists, Dictionaries, Tuples, Files, Other Core Types 74 | 4. User Defined Classes 75 | 2. Numeric Types 76 | 1. Literals, Built-in tools, expression operators 77 | 2. Formats, Comparisons, Division, Precision 78 | 3. Complex Numbers 79 | 4. Hexadecimal, Octal & Binary 80 | 5. Bitwise Operations 81 | 6. Decimal, Fraction, Sets, Booleans 82 | 83 | 1. Statements & Syntax 84 | 2. Assignments, Expressions & Syntax 85 | 3. If Tests & Syntax Rules 86 | 4. Scopes 87 | 5. Arguments 88 | Built-in functions, Function Design, Recursive Functions, Introspection, Annotations, Lambda, Filter and Reduce 89 | 3 1. Power of Introspection 90 | 1. Optional and Named Arguments 91 | 2. type, str, dir and other built-in functions 92 | 3. Object References with getattr 93 | 4. Filtering Lists 94 | 5. Lambda Functions 95 | 6. Real world Lambda functions 96 | None 1. Built-in functions 97 | 2. Python run-time services None Built-in functions are covered as part of the topic above but from a numeric perspective 98 | 1. Advanced Function Topics 99 | 1. Function Design 100 | 2. Recursive Functions 101 | 3. Attributes and Annotation 102 | 4. Lambda 103 | 5. Mapping Functions over sequences 104 | 6. Filter and Reduce 105 | 106 | Special Class Attributes 107 | Display Tool 108 | OOPS, Modules 109 | 4 1. Objects and Object Orientation 110 | 1. Importing Modules 111 | 2. Defining Classes 112 | 3. Initializing and Coding Classes 113 | 4. Self & __init__ 114 | 5. Instantiating Classes 115 | 6. Garbage Collection 116 | 7. Wrapper Classes 117 | 8. Special Class Methods 118 | 9. Advanced Class Methods 119 | 10. Class Attributes 120 | 11. Private Functions None Covered partially section 2 1. Packages 121 | 2. Data Types and Objects 122 | 3. Advanced Object Oriented Features 1. Modules 123 | 1. Why use Modules ? 124 | 2. Program Architecture 125 | 3. Module Search Path 126 | 4. Module Creation & Usage 127 | 5. Namespaces 128 | 6. Reloading Modules 129 | 7. Packages 130 | 2. Advanced Module Topics 131 | 1. Data Hiding in Modules 132 | 2. as Extension for import and from 133 | 3. Modules are Objects: Metaprograms 134 | 4. Transitive Module Reloads 135 | 5. Module Design Concepts 136 | 6. Module Gotchas 137 | 3. OOP 138 | 1. Why use classes ? 139 | 2. Classes & Instances 140 | 3. Attribute Inheritance Search 141 | 4. Class Method Calls 142 | 5. Class Trees 143 | 6. Class Objects & Default Behavior 144 | 7. Instance Objects are Concrete Items 145 | 8. Intercepting Python Operators 146 | 9. Classes Vs. Dictionaries 147 | 10. Class customization by Inheritance 148 | 11. Operator Overloading 149 | 12. Subclasses 150 | 13. Polymorphism in Action 151 | 14. Designing with Classes 152 | 15. Mix-in Classes 153 | Advanced Class Topics 154 | 5 None None None None 1. Advanced Class Topics 155 | 1. Extending Types by Embedding 156 | 2. Extending Types by Subclassing 157 | 3. Static and Class Methods 158 | 4. Decorators and Metaclasses 159 | 5. Class Gotchas 160 | Exceptions 161 | 6 1. Exceptions and File Handling 162 | 1. Handling Exceptions 163 | 2. Using exceptions for other purposes 1. Exceptions 1. Exceptions Basics 164 | 1. Why use Exceptions ? 165 | 2. Default Exception Handler 166 | 3. User-Defined Exceptions 167 | 4. Class Based Exceptions 168 | 5. Designing with Exceptions 169 | XML, HTTP, SOAP, Network Programming, I18N, Unicode 170 | 7 1. Regular Expressions 171 | 2. Parsing / Processing Mark-up languages (HTML, XML) 172 | 1. Unicode 173 | 3. HTTP Web Services 174 | 1. Headers 175 | 2. Debugging 176 | 4. SOAP Web Services 1. Networking 177 | 2. Internet 178 | 3. Email 179 | 4. Internationalization and Localization 1. Network Programming and Sockets 180 | 2. Internet Application Programming 181 | 3. Web Programming 182 | 4. Internet Data Handling & Encoding 1. Network, web programming 1. Unicode and Bytes Strings 183 | Miscellaneous 184 | 8 None 1. Algorithms 185 | 2. Cryptography 186 | 3. Data compression and archiving 187 | 4. Processes and Threads 188 | 5. Data persistence & exchange 1. Extending & Embedding Python 1. GUI None 189 | --------------------------------------------------------------------------------