[
  {
    "path": "100+ Python challenging programming exercises for Python 3.md",
    "content": "# 100+ Python challenging programming exercises for Python 3\n\n## 1. Level description\n### Level 1\tBeginner \nBeginner 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.\n\n### Level 2\tIntermediate \nIntermediate 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.\n\n### Level 3\tAdvanced. \nHe 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.\n\n----\n\n## 2. Problem template\n\nQuestion\nHints\nSolution\n\n----\n\n## 3. Questions\n\n### Question 1\nLevel 1\n\nQuestion:\nWrite 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).\nThe numbers obtained should be printed in a comma-separated sequence on a single line.\n\nHints: \nConsider use range(#begin, #end) method\n\nSolution:\n```python\nl=[]\nfor i in range(2000, 3201):\n    if (i%7==0) and (i%5!=0):\n        l.append(str(i))\n\nprint(','.join(l))\n```\n\n### Question 2\nLevel 1\n\nQuestion:\nWrite a program which can compute the factorial of a given numbers.\nThe results should be printed in a comma-separated sequence on a single line.\nSuppose the following input is supplied to the program:\n8\nThen, the output should be:\n40320\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\ndef fact(x):\n    if x == 0:\n        return 1\n    return x * fact(x - 1)\n\nx=int(input())\nprint(fact(x))\n```\n\n### Question 3\nLevel 1\n\nQuestion:\nWith 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.\nSuppose the following input is supplied to the program:\n8\nThen, the output should be:\n{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\nConsider use dict()\n\nSolution:\n```python\nn=int(input())\nd=dict()\nfor i in range(1,n+1):\n    d[i]=i*i\n\nprint(d)\n```\n\n### Question 4\nLevel 1\n\nQuestion:\nWrite a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.\nSuppose the following input is supplied to the program:\n34,67,55,33,12,98\nThen, the output should be:\n['34', '67', '55', '33', '12', '98']\n('34', '67', '55', '33', '12', '98')\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\ntuple() method can convert list to tuple\n\nSolution:\n```python\nvalues=input()\nl=values.split(\",\")\nt=tuple(l)\nprint(l)\nprint(t)\n```\n\n### Question 5\nLevel 1\n\nQuestion:\nDefine a class which has at least two methods:\ngetString: to get a string from console input\nprintString: to print the string in upper case.\nAlso please include simple test function to test the class methods.\n\nHints:\nUse __init__ method to construct some parameters\n\nSolution:\n```python\nclass InputOutString(object):\n    def __init__(self):\n        self.s = \"\"\n\n    def getString(self):\n        self.s = input()\n    \n    def printString(self):\n        print(self.s.upper())\n\nstrObj = InputOutString()\nstrObj.getString()\nstrObj.printString()\n```\n\n### Question 6\nLevel 2\n\nQuestion:\nWrite a program that calculates and prints the value according to the given formula:\nQ = Square root of [(2 * C * D)/H]\nFollowing are the fixed values of C and H:\nC is 50. H is 30.\nD is the variable whose values should be input to your program in a comma-separated sequence.\nExample\nLet us assume the following comma separated input sequence is given to the program:\n100,150,180\nThe output of the program should be:\n18,22,24\n\nHints:\nIf 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)\nIn case of input data being supplied to the question, it should be assumed to be a console input. \n\nSolution:\n```python\nimport math\nc=50\nh=30\nvalue = []\nitems=[x for x in input().split(',')]\nfor d in items:\n    value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))\n\nprint(','.join(value))\n```\n\n### Question 7\nLevel 2\n\nQuestion:\nWrite 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.\nNote: i=0,1.., X-1; j=0,1,¡­Y-1.\nExample\nSuppose the following inputs are given to the program:\n3,5\nThen, the output of the program should be:\n[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] \n\nHints:\nNote: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form.\n\nSolution:\n```python\ninput_str = input()\ndimensions=[int(x) for x in input_str.split(',')]\nrowNum=dimensions[0]\ncolNum=dimensions[1]\nmultilist = [[0 for col in range(colNum)] for row in range(rowNum)]\n\nfor row in range(rowNum):\n    for col in range(colNum):\n        multilist[row][col]= row*col\n\nprint(multilist)\n```\n\n### Question 8\nLevel 2\n\nQuestion:\nWrite 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.\nSuppose the following input is supplied to the program:\nwithout,hello,bag,world\nThen, the output should be:\nbag,hello,without,world\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\nitems=[x for x in input().split(',')]\nitems.sort()\nprint(','.join(items))\n```\n\n### Question 9\nLevel 2\n\nQuestion£º\nWrite a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.\nSuppose the following input is supplied to the program:\nHello world\nPractice makes perfect\nThen, the output should be:\nHELLO WORLD\nPRACTICE MAKES PERFECT\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\nlines = []\nwhile True:\n    s = input()\n    if s:\n        lines.append(s.upper())\n    else:\n        break;\n\nfor sentence in lines:\n    print(sentence)\n```\n\n### Question 10\nLevel 2\n\nQuestion:\nWrite 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.\nSuppose the following input is supplied to the program:\nhello world and practice makes perfect and hello world again\nThen, the output should be:\nagain and hello makes perfect practice world\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\nWe use set container to remove duplicated data automatically and then use sorted() to sort the data.\n\nSolution:\n```python\ns = input()\nwords = [word for word in s.split(\" \")]\nprint(\" \".join(sorted(list(set(words)))))\n```\n\n### Question 11\nLevel 2\n\nQuestion:\nWrite 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.\nExample:\n0100,0011,1010,1001\nThen the output should be:\n1010\nNotes: Assume the data is input by console.\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\nvalue = []\nitems=[x for x in input().split(',')]\nfor p in items:\n    intp = int(p, 2)\n    if not intp%5:\n        value.append(p)\n\nprint(','.join(value))\n```\n\n### Question 12\nLevel 2\n\nQuestion:\nWrite 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.\nThe numbers obtained should be printed in a comma-separated sequence on a single line.\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\nvalues = []\nfor i in range(1000, 3001):\n    s = str(i)\n    if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):\n        values.append(s)\nprint(\",\".join(values))\n```\n\n### Question 13\nLevel 2\n\nQuestion:\nWrite a program that accepts a sentence and calculate the number of letters and digits.\nSuppose the following input is supplied to the program:\nhello world! 123\nThen, the output should be:\nLETTERS 10\nDIGITS 3\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\ns = input()\nd={\"DIGITS\":0, \"LETTERS\":0}\nfor c in s:\n    if c.isdigit():\n        d[\"DIGITS\"]+=1\n    elif c.isalpha():\n        d[\"LETTERS\"]+=1\n    else:\n        pass\nprint(\"LETTERS\", d[\"LETTERS\"])\nprint(\"DIGITS\", d[\"DIGITS\"])\n```\n\n### Question 14\nLevel 2\n\nQuestion:\nWrite a program that accepts a sentence and calculate the number of upper case letters and lower case letters.\nSuppose the following input is supplied to the program:\nHello world!\nThen, the output should be:\nUPPER CASE 1\nLOWER CASE 9\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\ns = input()\nd={\"UPPER CASE\":0, \"LOWER CASE\":0}\nfor c in s:\n    if c.isupper():\n        d[\"UPPER CASE\"]+=1\n    elif c.islower():\n        d[\"LOWER CASE\"]+=1\n    else:\n        pass\nprint(\"UPPER CASE\", d[\"UPPER CASE\"])\nprint(\"LOWER CASE\", d[\"LOWER CASE\"])\n```\n\n### Question 15\nLevel 2\n\nQuestion:\nWrite a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.\nSuppose the following input is supplied to the program:\n9\nThen, the output should be:\n11106\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n\n```python\na = input()\nn1 = int( \"%s\" % a )\nn2 = int( \"%s%s\" % (a,a) )\nn3 = int( \"%s%s%s\" % (a,a,a) )\nn4 = int( \"%s%s%s%s\" % (a,a,a,a) )\nprint(n1+n2+n3+n4)\n```\n\n### Question 16\nLevel 2\n\nQuestion:\nUse a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.\nSuppose the following input is supplied to the program:\n1,2,3,4,5,6,7,8,9\nThen, the output should be:\n1,3,5,7,9\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n\n```python\nvalues = input()\nnumbers = [x for x in values.split(\",\") if int(x)%2!=0]\nprint(\",\".join(numbers))\n```\n\n### Question 17\nLevel 2\n\nQuestion:\nWrite 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:\nD 100\nW 200\n\nD means deposit while W means withdrawal.\nSuppose the following input is supplied to the program:\nD 300\nD 300\nW 200\nD 100\nThen, the output should be:\n500\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n\n```python\nnetAmount = 0\nwhile True:\n    s = input()\n    if not s:\n        break\n    values = s.split(\" \")\n    operation = values[0]\n    amount = int(values[1])\n    if operation==\"D\":\n        netAmount+=amount\n    elif operation==\"W\":\n        netAmount-=amount\n    else:\n        pass\nprint(netAmount)\n```\n\n### Question 18\nLevel 3\n\nQuestion:\nA website requires the users to input username and password to register. Write a program to check the validity of password input by users.\nFollowing are the criteria for checking the password:\n1. At least 1 letter between [a-z]\n2. At least 1 number between [0-9]\n1. At least 1 letter between [A-Z]\n3. At least 1 character from [$#@]\n4. Minimum length of transaction password: 6\n5. Maximum length of transaction password: 12\nYour 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.\nExample\nIf the following passwords are given as input to the program:\nABd1234@1,a F1#,2w3E*,2We3345\nThen, the output of the program should be:\nABd1234@1\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolutions:\n\n```python\nimport re\nvalue = []\nitems=[x for x in input().split(',')]\nfor p in items:\n    if len(p)<6 or len(p)>12:\n        continue\n    else:\n        pass\n    if not re.search(\"[a-z]\",p):\n        continue\n    elif not re.search(\"[0-9]\",p):\n        continue\n    elif not re.search(\"[A-Z]\",p):\n        continue\n    elif not re.search(\"[$#@]\",p):\n        continue\n    elif re.search(\"\\s\",p):\n        continue\n    else:\n        pass\n    value.append(p)\nprint(\",\".join(value))\n```\n\n### Question 19\nLevel 3\n\nQuestion:\nYou 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:\n1: Sort based on name;\n2: Then sort based on age;\n3: Then sort by score.\nThe priority is that name > age > score.\nIf the following tuples are given as input to the program:\nTom,19,80\nJohn,20,90\nJony,17,91\nJony,17,93\nJson,21,85\nThen, the output of the program should be:\n[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\nWe use itemgetter to enable multiple sort keys.\n\nSolutions:\nfrom operator import itemgetter, attrgetter\n\n```python\nl = []\nwhile True:\n    s = input()\n    if not s:\n        break\n    l.append(tuple(s.split(\",\")))\n\nprint(sorted(l, key=itemgetter(0,1,2)))\n```\n\n### Question 20\nLevel 3\n\nQuestion:\nDefine a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.\n\nHints:\nConsider use yield\n\nSolution:\n\n```python\ndef putNumbers(n):\n    i = 0\n    while i<n:\n        j=i\n        i=i+1\n        if j%7==0:\n            yield j\n\nfor i in reverse(100):\n    print(i)\n```\n\n### Question 21\nLevel 3\n\nQuestion\nA robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:\nUP 5\nDOWN 3\nLEFT 3\nRIGHT 2\n¡­\nThe numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.\nExample:\nIf the following tuples are given as input to the program:\nUP 5\nDOWN 3\nLEFT 3\nRIGHT 2\nThen, the output of the program should be:\n2\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n\n```python\nimport math\npos = [0,0]\nwhile True:\n    s = input()\n    if not s:\n        break\n    movement = s.split(\" \")\n    direction = movement[0]\n    steps = int(movement[1])\n    if direction==\"UP\":\n        pos[0]+=steps\n    elif direction==\"DOWN\":\n        pos[0]-=steps\n    elif direction==\"LEFT\":\n        pos[1]-=steps\n    elif direction==\"RIGHT\":\n        pos[1]+=steps\n    else:\n        pass\n\nprint(int(round(math.sqrt(pos[1]**2+pos[0]**2))))\n```\n\n### Question 22\nLevel 3\n\nQuestion:\nWrite a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. \nSuppose the following input is supplied to the program:\nNew to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.\nThen, the output should be:\n2:2\n3.:1\n3?:1\nNew:1\nPython:5\nRead:1\nand:1\nbetween:1\nchoosing:1\nor:2\nto:1\n\nHints\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n\n```python\nfreq = {}   # frequency of words in text\nline = input()\nfor word in line.split():\n    freq[word] = freq.get(word,0)+1\n\nwords = freq.keys()\nwords.sort()\n\nfor w in words:\n    print(\"%s:%d\" % (w,freq[w]))\n```\n\n### Question 23\nlevel 1\n\nQuestion:\nWrite a method which can calculate square value of number\n\nHints:\nUsing the ** operator\n\nSolution:\n\n```python\ndef square(num):\n    return num ** 2\n\nprint(square(2))\nprint(square(3))\n```\n\n### Question 24\nLevel 1\n\nQuestion:\n\nPython has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.\n\nPlease write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()\n\nAnd add document for your own function\nHints:\nThe built-in document method is __doc__\n\nSolution:\n```python\nprint(abs.__doc__)\nprint(int.__doc__)\nprint(input.__doc__)\n\ndef square(num):\n    '''Return the square value of the input number.\n    \n    The input number must be integer.\n    '''\n    return num ** 2\n\nprint(square(2))\nprint(square.__doc__)\n```\n### Question 25\nLevel 1\n\nQuestion:\nDefine a class, which have a class parameter and have a same instance parameter.\n\nHints:\nDefine a instance parameter, need add it in __init__ method\nYou can init a object with construct parameter or set the value later\n\nSolution:\n```python\nclass Person:\n    # Define the class parameter \"name\"\n    name = \"Person\"\n    \n    def __init__(self, name = None):\n        # self.name is the instance parameter\n        self.name = name\n\njeffrey = Person(\"Jeffrey\")\nprint(\"%s name is %s\" % (Person.name, jeffrey.name))\n\nnico = Person()\nnico.name = \"Nico\"\nprint(\"%s name is %s\" % (Person.name, nico.name))\n```\n\n### Question 26:\nDefine a function which can compute the sum of two numbers.\n\nHints:\nDefine a function with two numbers as arguments. You can compute the sum in the function and return the value.\n\nSolution\n\n```python\ndef SumFunction(number1, number2):\n\treturn number1+number2\n\nprint(SumFunction(1,2))\n```\n\n### Question 27\nDefine a function that can convert a integer into a string and print it in console.\n\nHints:\n\nUse str() to convert a number to string.\n\nSolution\n```python\ndef printValue(n):\n    print(str(n))\n\nprintValue(3)\n```\n\n### Question 28\nDefine a function that can convert a integer into a string and print it in console.\n\nHints:\n\nUse str() to convert a number to string.\n\nSolution\n```python\ndef printValue(n):\n    print(str(n))\n\nprintValue(3)\n```\n\n### Question 29\nDefine a function that can receive two integral numbers in string form and compute their sum and then print it in console.\n\nHints:\n\nUse int() to convert a string to integer.\n\nSolution\n```python\ndef printValue(s1,s2):\n    print(int(s1)+int(s2))\n\nprintValue(\"3\",\"4\")\n```\n\n### Question 30\nDefine a function that can accept two strings as input and concatenate them and then print it in console.\n\nHints:\n\nUse + to concatenate the strings\n\nSolution\n```python\ndef printValue(s1,s2):\n    print(s1+s2)\n\nprintValue(\"3\",\"4\") #34\n```\n\n### Question 31\nDefine a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print al l strings line by line.\n\nHints:\n\nUse len() function to get the length of a string\n\nSolution\n```python\ndef printValue(s1,s2):\n    len1 = len(s1)\n    len2 = len(s2)\n    if len1>len2:\n        print(s1)\n    elif len2>len1:\n        print(s2)\n    else:\n        print(s1)\n        print(s2)\n        \nprintValue(\"one\",\"three\")\n\n```\n### Question 32\nDefine 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\".\n\nHints:\n\nUse % operator to check if a number is even or odd.\n\nSolution\n```python\ndef checkValue(n):\n    if n%2 == 0:\n        print(\"It is an even number\")\n    else:\n        print(\"It is an odd number\")\n        \ncheckValue(7)\n\n### Question 33\nDefine 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.\n\nHints:\n\nUse dict[key]=value pattern to put entry into a dictionary.\nUse ** operator to get power of a number.\n\nSolution\n​```python\ndef printDict():\n    d=dict()\n    d[1]=1\n    d[2]=2**2\n    d[3]=3**2\n    print(d)\n        \nprintDict()\n```\n### Question 34\nDefine 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.\n\nHints:\n\nUse dict[key]=value pattern to put entry into a dictionary.\nUse ** operator to get power of a number.\nUse range() for loops.\n\nSolution\n```python\ndef printDict():\n\td=dict()\n\tfor i in range(1,21):\n\t\td[i]=i**2\n\tprint(d)\n\nprintDict()\n```\n\n### Question 35\nDefine 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.\n\nHints:\n\nUse dict[key]=value pattern to put entry into a dictionary.\nUse ** operator to get power of a number.\nUse range() for loops.\nUse keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.\n\nSolution\n```python\ndef printDict():\n\td=dict()\n\tfor i in range(1,21):\n\t\td[i]=i**2\n\tfor (k,v) in d.items():\t\n\t\tprint(v)\n\nprintDict()\n```\n\n### Question 36\nDefine 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.\n\nHints:\n\nUse dict[key]=value pattern to put entry into a dictionary.\nUse ** operator to get power of a number.\nUse range() for loops.\nUse keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.\n\nSolution\n```python\ndef printDict():\n\td=dict()\n\tfor i in range(1,21):\n\t\td[i]=i**2\n\tfor k in d.keys():\t\n\t\tprint(k)\n\nprintDict()\n```\n\n### Question 37\nDefine a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).\n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\n\nSolution\n```python\ndef printList():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint(li)\n\nprintList()\n```\n### Question 38\nDefine 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.\n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\nUse [n1:n2] to slice a list\n\nSolution\n```python\ndef printList():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint(li[:5])\n\nprintList()\n```\n\n### Question 39\nDefine 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.\n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\nUse [n1:n2] to slice a list\n\nSolution\n```python\ndef printList():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint(li[-5:])\n\nprintList()\n```\n### Question 40\nDefine 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.\n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\nUse [n1:n2] to slice a list\n\nSolution\n```python\ndef printList():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint li[5:]\n\nprintList()\n```\n\n### Question 41\nDefine a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). \n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\nUse tuple() to get a tuple from a list.\n\nSolution\n```python\ndef printTuple():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint(tuple(li))\n\t\t\nprintTuple()\n```\n### Question 42\nWith 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. \n\nHints:\n\nUse [n1:n2] notation to get a slice from a tuple.\n\nSolution\n```python\ntp=(1,2,3,4,5,6,7,8,9,10)\ntp1=tp[:5]\ntp2=tp[5:]\nprint(tp1)\nprint(tp2)\n```\n\n### Question 43\nWrite 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). \n\nHints:\n\nUse \"for\" to iterate the tuple\nUse tuple() to generate a tuple from a list.\n\nSolution\n```python\ntp=(1,2,3,4,5,6,7,8,9,10)\nli=list()\nfor i in tp:\n\tif tp[i]%2==0:\n\t\tli.append(tp[i])\n\ntp2=tuple(li)\nprint(tp2)\n```\n### Question 44\nWrite a program which accepts a string as input to print \"Yes\" if the string is \"yes\" or \"YES\" or \"Yes\", otherwise print \"No\". \n\nHints:\n\nUse if statement to judge condition.\n\nSolution\n```python\ns= raw_input()\nif s==\"yes\" or s==\"YES\" or s==\"Yes\":\n    print \"Yes\"\nelse:\n    print \"No\"\n```\n### Question 45\nWrite 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].\n\nHints:\n\nUse filter() to filter some elements in a list.\nUse lambda to define anonymous functions.\n\nSolution\n```python\nli = [1,2,3,4,5,6,7,8,9,10]\nevenNumbers = filter(lambda x: x%2==0, li)\nprint(evenNumbers)\n```\n\n### Question 46\nWrite 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].\n\nHints\nUse map() to generate a list.\nUse lambda to define anonymous functions.\n\nSolution\n```python\nli = [1,2,3,4,5,6,7,8,9,10]\nsquaredNumbers = map(lambda x: x**2, li)\nprint(squaredNumbers)\n```\n\n### Question 47\nWrite 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].\n\nHints\nUse map() to generate a list.\nUse filter() to filter elements of a list.\nUse lambda to define anonymous functions.\n\nSolution\n```python\nli = [1,2,3,4,5,6,7,8,9,10]\nevenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))\nprint(evenNumbers)\n```\n### Question 48\nWrite a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).\n\nHints:\n\nUse filter() to filter elements of a list.\nUse lambda to define anonymous functions.\n\nSolution\n```python\nevenNumbers = filter(lambda x: x%2==0, range(1,21))\nprint(evenNumbers)\n```\n\n### Question 49\nWrite a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).\n\nHints\nUse map() to generate a list.\nUse lambda to define anonymous functions.\n\nSolution\n```python\nsquaredNumbers = map(lambda x: x**2, range(1,21))\nprint(squaredNumbers)\n```\n\n### Question 50\nDefine a class named American which has a static method called printNationality.\n\nHints:\nUse @staticmethod decorator to define class static method.\n\nSolution\n```python\nclass American(object):\n    @staticmethod\n    def printNationality():\n        print(\"America\")\n\nanAmerican = American()\nanAmerican.printNationality()\nAmerican.printNationality()\n```\n\n### Question 51\nDefine a class named American and its subclass NewYorker. \n\nHints:\n\nUse class Subclass(ParentClass) to define a subclass.\n\nSolution:\n```python\nclass American(object):\n    pass\n\nclass NewYorker(American):\n    pass\n\nanAmerican = American()\naNewYorker = NewYorker()\nprint(anAmerican)\nprint(aNewYorker)\n```\n\n### Question 52\nDefine a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. \n\nHints:\n\nUse def methodName(self) to define a method.\n\nSolution:\n```python\nclass Circle(object):\n    def __init__(self, r):\n        self.radius = r\n\n    def area(self):\n        return self.radius**2*3.14\n\naCircle = Circle(2)\nprint aCircle.area()\n```\n\n### Question 53\nDefine a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. \n\nHints:\n\nUse def methodName(self) to define a method.\n\nSolution:\n```python\nclass Rectangle(object):\n    def __init__(self, l, w):\n        self.length = l\n        self.width  = w\n\n    def area(self):\n        return self.length*self.width\n\naRectangle = Rectangle(2,10)\nprint(aRectangle.area())\n```\n\n### Question 54\nDefine 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.\n\nHints:\n\nTo override a method in super class, we can define a method with the same name in the super class.\n\nSolution:\n```python\nclass Shape(object):\n    def __init__(self):\n        pass\n\n    def area(self):\n        return 0\n\nclass Square(Shape):\n    def __init__(self, l):\n        Shape.__init__(self)\n        self.length = l\n\n    def area(self):\n        return self.length*self.length\n\naSquare= Square(3)\nprint(aSquare.area())\n```\n\n### Question 55\nPlease raise a RuntimeError exception.\n\nHints:\n\nUse raise() to raise an exception.\n\nSolution:\n\n```python\nraise RuntimeError('something wrong')\n```\n\n### Question 56\nWrite a function to compute 5/0 and use try/except to catch the exceptions.\n\nHints:\n\nUse try/except to catch exceptions.\n\nSolution:\n```python\ndef throws():\n    return 5/0\n\ntry:\n    throws()\nexcept ZeroDivisionError:\n    print(\"division by zero!\")\nexcept Exception, err:\n    print('Caught an exception')\nfinally:\n    print('In finally block for cleanup')\n```\n\n### Question 57\nDefine a custom exception class which takes a string message as attribute.\n\nHints:\n\nTo define a custom exception, we need to define a class inherited from Exception.\n\nSolution:\n```python\nclass MyError(Exception):\n    \"\"\"My own exception class\n\n    Attributes:\n        msg  -- explanation of the error\n    \"\"\"\n    \n    def __init__(self, msg):\n        self.msg = msg\n\nerror = MyError(\"something wrong\")\n```\n\n### Question 58\nAssuming 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.\n\nExample:\nIf the following email address is given as input to the program:\n\njohn@google.com\n\nThen, the output of the program should be:\n\njohn\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\n\nUse \\w to match letters.\n\nSolution:\n```python\nimport re\nemailAddress = raw_input()\npat2 = \"(\\w+)@((\\w+\\.)+(com))\"\nr2 = re.match(pat2,emailAddress)\nprint(r2.group(1))\n```\n\n### Question 59\nAssuming 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.\n\nExample:\nIf the following email address is given as input to the program:\n\njohn@google.com\n\nThen, the output of the program should be:\n\ngoogle\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\n\nUse \\w to match letters.\n\nSolution:\n```python\nimport re\nemailAddress = raw_input()\npat2 = \"(\\w+)@(\\w+)\\.(com)\"\nr2 = re.match(pat2,emailAddress)\nprint(r2.group(2))\n```\n\n### Question 60\nWrite a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.\n\nExample:\nIf the following words is given as input to the program:\n\n2 cats and 3 dogs.\n\nThen, the output of the program should be:\n\n['2', '3']\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\n\nUse re.findall() to find all substring using regex.\n\nSolution:\n```python\nimport re\ns = raw_input()\nprint(re.findall(\"\\d+\",s))\n```\n\n### Question 61\nPrint a unicode string \"hello world\".\n\nHints:\n\nUse u'strings' format to define unicode string.\n\nSolution:\n```python\nunicodeString = u\"hello world!\"\nprint(unicodeString)\n```\n\n### Question 62\nWrite a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.\n\nHints:\n\nUse unicode() function to convert.\n\nSolution:\n```python\ns = input()\nu = unicode( s ,\"utf-8\")\nprint(u)\n```\n\n### Question 63\n\nWrite a special comment to indicate a Python source code file is in unicode.\n\nHints:\n\nSolution:\n```python\n\n# -*- coding: utf-8 -*-\n\n#----------------------------------------#\n```\n\n### Question 64\n\nWrite a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).\n\nExample:\nIf the following n is given as input to the program:\n\n5\n\nThen, the output of the program should be:\n\n3.55\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\nUse float() to convert an integer to a float\n\nSolution:\n```python\nn=int(input())\nsum=0.0\nfor i in range(1,n+1):\n    sum += float(float(i)/(i+1))\nprint(sum)\n```\n\n### Question 65\n\nWrite a program to compute:\n\nf(n)=f(n-1)+100 when n>0\nand f(0)=1\n\nwith a given n input by console (n>0).\n\nExample:\nIf the following n is given as input to the program:\n\n5\n\nThen, the output of the program should be:\n\n500\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\nWe can define recursive function in Python.\n\nSolution:\n```python\ndef f(n):\n    if n==0:\n        return 0\n    else:\n        return f(n-1)+100\n\nn=int(input())\nprint(f(n))\n```\n\n### Question 66\nThe Fibonacci Sequence is computed based on the following formula:\n\nf(n)=0 if n=0\nf(n)=1 if n=1\nf(n)=f(n-1)+f(n-2) if n>1\n\nPlease write a program to compute the value of f(n) with a given n input by console.\n\nExample:\nIf the following n is given as input to the program:\n\n7\n\nThen, the output of the program should be:\n\n13\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\nWe can define recursive function in Python.\n\n\nSolution:\n```python\ndef f(n):\n    if n == 0: return 0\n    elif n == 1: return 1\n    else: return f(n-1)+f(n-2)\n\nn=int(input())\nprint(f(n))\n```\n\n### Question 67\nThe Fibonacci Sequence is computed based on the following formula:\n\nf(n)=0 if n=0\nf(n)=1 if n=1\nf(n)=f(n-1)+f(n-2) if n>1\n\nPlease write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console.\n\nExample:\nIf the following n is given as input to the program:\n\n7\n\nThen, the output of the program should be:\n\n0,1,1,2,3,5,8,13\n\n\nHints:\nWe can define recursive function in Python.\nUse list comprehension to generate a list from an existing list.\nUse string.join() to join a list of strings.\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\ndef f(n):\n    if n == 0: return 0\n    elif n == 1: return 1\n    else: return f(n-1)+f(n-2)\n\nn=int(input())\nvalues = [str(f(x)) for x in range(0, n+1)]\nprint(\",\".join(values))\n```\n\n### Question 68\n\nPlease write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.\n\nExample:\nIf the following n is given as input to the program:\n\n10\n\nThen, the output of the program should be:\n\n0,2,4,6,8,10\n\nHints:\nUse yield to produce the next value in generator.\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\ndef EvenGenerator(n):\n    i=0\n    while i<=n:\n        if i%2==0:\n            yield i\n        i+=1\n\n\nn=int(input())\nvalues = []\nfor i in EvenGenerator(n):\n    values.append(str(i))\n\nprint(\",\".join(values))\n```\n\n### Question 69\nPlease 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.\n\nExample:\nIf the following n is given as input to the program:\n\n100\n\nThen, the output of the program should be:\n\n0,35,70\n\nHints:\nUse yield to produce the next value in generator.\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n```python\ndef NumGenerator(n):\n    for i in range(n+1):\n        if i%5==0 and i%7==0:\n            yield i\n\nn=int(input())\nvalues = []\nfor i in NumGenerator(n):\n    values.append(str(i))\n\nprint(\",\".join(values))\n```\n\n### Question 70\nPlease write assert statements to verify that every number in the list [2,4,6,8] is even.\n\nHints:\nUse \"assert expression\" to make assertion.\n\nSolution:\n```python\nli = [2,4,6,8]\nfor i in li:\n    assert i%2==0\n```\n\n### Question 71\nPlease write a program which accepts basic mathematic expression from console and print the evaluation result.\n\nExample:\nIf the following string is given as input to the program:\n\n35+3\n\nThen, the output of the program should be:\n\n38\n\nHints:\nUse eval() to evaluate an expression.\n\n\nSolution:\n```python\nexpression = raw_input()\nprint(eval(expression))\n```\n\n### Question 72\nPlease 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.\n\nHints:\nUse if/elif to deal with conditions.\n\nSolution:\n```python\nimport math\ndef bin_search(li, element):\n    bottom = 0\n    top = len(li)-1\n    index = -1\n    while top>=bottom and index==-1:\n        mid = int(math.floor((top+bottom)/2.0))\n        if li[mid]==element:\n            index = mid\n        elif li[mid]>element:\n            top = mid-1\n        else:\n            bottom = mid+1\n\n    return index\n\nli=[2,5,7,9,11,17,222]\nprint(bin_search(li,11))\nprint(bin_search(li,12))\n```\n\n### Question 73\nPlease 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.\n\nHints:\nUse if/elif to deal with conditions.\n\nSolution:\n```python\nimport math\ndef bin_search(li, element):\n    bottom = 0\n    top = len(li)-1\n    index = -1\n    while top>=bottom and index==-1:\n        mid = int(math.floor((top+bottom)/2.0))\n        if li[mid]==element:\n            index = mid\n        elif li[mid]>element:\n            top = mid-1\n        else:\n            bottom = mid+1\n\n    return index\n\nli=[2,5,7,9,11,17,222]\nprint(bin_search(li,11))\nprint(bin_search(li,12))\n```\n\n### Question 74\nPlease generate a random float where the value is between 10 and 100 using Python math module.\n\nHints:\nUse random.random() to generate a random float in [0,1].\n\nSolution:\n```python\nimport random\nprint(random.random()*100)\n```\n\n### Question 75\nPlease generate a random float where the value is between 5 and 95 using Python math module.\n\nHints:\nUse random.random() to generate a random float in [0,1].\n\nSolution:\n```python\nimport random\nprint(random.random()*100-5)\n```\n\n### Question 76\nPlease write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.\n\nHints:\nUse random.choice() to a random element from a list.\n\nSolution:\n```python\nimport random\nprint(random.choice([i for i in range(11) if i%2==0]))\n```\n\n### Question 77\nPlease 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.\n\nHints:\nUse random.choice() to a random element from a list.\n\nSolution:\n```python\nimport random\nprint(random.choice([i for i in range(201) if i%5==0 and i%7==0]))\n```\n\n### Question 78\nPlease write a program to generate a list with 5 random numbers between 100 and 200 inclusive.\n\nHints:\nUse random.sample() to generate a list of random values.\n\nSolution:\n```python\nimport random\nprint(random.sample(range(100), 5))\n```\n\n### Question 79\nPlease write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.\n\nHints:\nUse random.sample() to generate a list of random values.\n\nSolution:\n```python\nimport random\nprint(random.sample([i for i in range(100,201) if i%2==0], 5))\n```\n\n### Question 80\nPlease write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.\n\nHints:\nUse random.sample() to generate a list of random values.\n\nSolution:\n```python\nimport random\nprint(random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5))\n```\n\n### Question 81\nPlease write a program to randomly print a integer number between 7 and 15 inclusive.\n\nHints:\nUse random.randrange() to a random integer in a given range.\n\nSolution:\n```python\nimport random\nprint(random.randrange(7,16))\n```\n\n### Question 82\nPlease write a program to compress and decompress the string \"hello world!hello world!hello world!hello world!\".\n\nHints:\nUse zlib.compress() and zlib.decompress() to compress and decompress a string.\n\nSolution:\n```python\nimport zlib\ns = b'hello world!hello world!hello world!hello world!'\nt = zlib.compress(s)\nprint(t)\nprint(zlib.decompress(t))\n```\n\n### Question 83\nPlease write a program to print the running time of execution of \"1+1\" for 100 times.\n\nHints:\nUse timeit() function to measure the running time.\n\nSolution:\n```python\nfrom timeit import Timer\nt = Timer(\"for i in range(100):1+1\")\nprint(t.timeit())\n```\n\n### Question 84\nPlease write a program to shuffle and print the list [3,6,7,8].\n\nHints:\nUse shuffle() function to shuffle a list.\n\nSolution:\n```python\nfrom random import shuffle\nli = [3,6,7,8]\nshuffle(li)\nprint(li)\n```\n\n### Question 85\nPlease write a program to shuffle and print the list [3,6,7,8].\n\nHints:\nUse shuffle() function to shuffle a list.\n\nSolution:\n```python\nfrom random import shuffle\nli = [3,6,7,8]\nshuffle(li)\nprint(li)\n```\n\n### Question 86\nPlease 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\"].\n\nHints:\nUse list[index] notation to get a element from a list.\n\nSolution:\n```python\nsubjects=[\"I\", \"You\"]\nverbs=[\"Play\", \"Love\"]\nobjects=[\"Hockey\",\"Football\"]\nfor i in range(len(subjects)):\n    for j in range(len(verbs)):\n        for k in range(len(objects)):\n            sentence = \"%s %s %s.\" % (subjects[i], verbs[j], objects[k])\n            print(sentence)\n```\n\n### Question 87\nPlease write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].\n\nHints:\nUse list comprehension to delete a bunch of element from a list.\n\nSolution:\n```\nli = [5,6,77,45,22,12,24]\nli = [x for x in li if x%2!=0]\nprint(li)\n```\n\n### Question 88\nBy 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].\n\nHints:\nUse list comprehension to delete a bunch of element from a list.\n\nSolution:\n```\nli = [12,24,35,70,88,120,155]\nli = [x for x in li if x%5!=0 and x%7!=0]\nprint(li)\n```\n\n### Question 89\nBy 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].\n\nHints:\nUse list comprehension to delete a bunch of element from a list.\nUse enumerate() to get (index, value) tuple.\n\nSolution:\n```python\nli = [12,24,35,70,88,120,155]\nli = [x for (i,x) in enumerate(li) if i%2!=0]\nprint(li)\n```\n\n### Question 90\nBy using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.\n\nHints:\nUse list comprehension to make an array.\n\nSolution:\n```\narray = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]\nprint(array)\n```\n\n### Question 91\nBy 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].\n\nHints:\nUse list comprehension to delete a bunch of element from a list.\nUse enumerate() to get (index, value) tuple.\n\nSolution:\n```python\nli = [12,24,35,70,88,120,155]\nli = [x for (i,x) in enumerate(li) if i not in (0,4,5)]\nprint(li)\n```\n\n### Question 92\nBy using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].\n\nHints:\nUse list's remove method to delete a value.\n\nSolution:\n```python\nli = [12,24,35,24,88,120,155]\nli = [x for x in li if x!=24]\nprint(li)\n```\n\n### Question 93\nWith 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.\n\nHints:\nUse set() and \"&=\" to do set intersection operation.\n\nSolution:\n```python\nset1=set([1,3,6,78,35,55])\nset2=set([12,24,35,24,88,120,155])\nset1 &= set2\nli=list(set1)\nprint(li)\n```\n\n### Question 94\nWith 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.\n\nHints:\nUse set() to store a number of values without duplicate.\n\nSolution:\n```python\ndef removeDuplicate( li ):\n    newli=[]\n    seen = set()\n    for item in li:\n        if item not in seen:\n            seen.add( item )\n            newli.append(item)\n\n    return newli\n\nli=[12,24,35,24,88,120,155,88,120,155]\nprint(removeDuplicate(li))\n```\n\n### Question 95\nDefine 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.\n\nHints:\nUse Subclass(Parentclass) to define a child class.\n\nSolution:\n```python\nclass Person(object):\n    def getGender( self ):\n        return \"Unknown\"\n\nclass Male( Person ):\n    def getGender( self ):\n        return \"Male\"\n\nclass Female( Person ):\n    def getGender( self ):\n        return \"Female\"\n\naMale = Male()\naFemale= Female()\nprint(aMale.getGender())\nprint(aFemale.getGender())\n```\n\n### Question 96\nPlease write a program which count and print the numbers of each character in a string input by console.\n\nExample:\nIf the following string is given as input to the program:\n\nabcdefgabc\n\nThen, the output of the program should be:\n\na,2\nc,2\nb,2\ne,1\nd,1\ng,1\nf,1\n\nHints:\nUse dict to store key/value pairs.\nUse dict.get() method to lookup a key with default value.\n\nSolution:\n```python\ndic = {}\ns=raw_input()\nfor s in s:\n    dic[s] = dic.get(s,0)+1\nprint('\\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]))\n```\n\n### Question 97\nPlease write a program which accepts a string from console and print it in reverse order.\n\nExample:\nIf the following string is given as input to the program:\n\nrise to vote sir\n\nThen, the output of the program should be:\n\nris etov ot esir\n\nHints:\nUse list[::-1] to iterate a list in a reverse order.\n\nSolution:\n```python\ns=raw_input()\ns = s[::-1]\nprint(s)\n```\n\n### Question 98\nPlease write a program which accepts a string from console and print the characters that have even indexes.\n\nExample:\nIf the following string is given as input to the program:\n\nH1e2l3l4o5w6o7r8l9d\n\nThen, the output of the program should be:\n\nHelloworld\n\nHints:\nUse list[::2] to iterate a list by step 2.\n\nSolution:\n```python\ns=raw_input()\ns = s[::2]\nprint(s)\n```\n\n### Question 99\nPlease write a program which prints all permutations of [1,2,3]\n\nHints:\nUse itertools.permutations() to get permutations of list.\n\nSolution:\n```python\nimport itertools\nprint(list(itertools.permutations([1,2,3])))\n```\n\n### Question 100\nWrite a program to solve a classic ancient Chinese puzzle: \nWe count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?\n\nHint:\nUse for loop to iterate all possible solutions.\n\nSolution:\n```python\ndef solve(numheads,numlegs):\n    ns='No solutions!'\n    for i in range(numheads+1):\n        j=numheads-i\n        if 2*i+4*j==numlegs:\n            return i,j\n    return ns,ns\n\nnumheads=35\nnumlegs=94\nsolutions=solve(numheads,numlegs)\nprint(solutions)\n```\n\n"
  },
  {
    "path": "100+ Python challenging programming exercises.txt",
    "content": "100+ Python challenging programming exercises\n\n1.\tLevel description\nLevel\tDescription\nLevel 1\tBeginner 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.\nLevel 2\tIntermediate 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.\nLevel 3\tAdvanced. 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.\n\n2.\tProblem template\n\n#----------------------------------------#\nQuestion\nHints\nSolution\n\n3.\tQuestions\n\n#----------------------------------------#\nQuestion 1\nLevel 1\n\nQuestion:\nWrite a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,\nbetween 2000 and 3200 (both included).\nThe numbers obtained should be printed in a comma-separated sequence on a single line.\n\nHints: \nConsider use range(#begin, #end) method\n\nSolution:\nl=[]\nfor i in range(2000, 3201):\n    if (i%7==0) and (i%5!=0):\n        l.append(str(i))\n\nprint ','.join(l)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 2\nLevel 1\n\nQuestion:\nWrite a program which can compute the factorial of a given numbers.\nThe results should be printed in a comma-separated sequence on a single line.\nSuppose the following input is supplied to the program:\n8\nThen, the output should be:\n40320\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\ndef fact(x):\n    if x == 0:\n        return 1\n    return x * fact(x - 1)\n\nx=int(raw_input())\nprint fact(x)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 3\nLevel 1\n\nQuestion:\nWith 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.\nSuppose the following input is supplied to the program:\n8\nThen, the output should be:\n{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\nConsider use dict()\n\nSolution:\nn=int(raw_input())\nd=dict()\nfor i in range(1,n+1):\n    d[i]=i*i\n\nprint d\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 4\nLevel 1\n\nQuestion:\nWrite a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.\nSuppose the following input is supplied to the program:\n34,67,55,33,12,98\nThen, the output should be:\n['34', '67', '55', '33', '12', '98']\n('34', '67', '55', '33', '12', '98')\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\ntuple() method can convert list to tuple\n\nSolution:\nvalues=raw_input()\nl=values.split(\",\")\nt=tuple(l)\nprint l\nprint t\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 5\nLevel 1\n\nQuestion:\nDefine a class which has at least two methods:\ngetString: to get a string from console input\nprintString: to print the string in upper case.\nAlso please include simple test function to test the class methods.\n\nHints:\nUse __init__ method to construct some parameters\n\nSolution:\nclass InputOutString(object):\n    def __init__(self):\n        self.s = \"\"\n\n    def getString(self):\n        self.s = raw_input()\n\n    def printString(self):\n        print self.s.upper()\n\nstrObj = InputOutString()\nstrObj.getString()\nstrObj.printString()\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 6\nLevel 2\n\nQuestion:\nWrite a program that calculates and prints the value according to the given formula:\nQ = Square root of [(2 * C * D)/H]\nFollowing are the fixed values of C and H:\nC is 50. H is 30.\nD is the variable whose values should be input to your program in a comma-separated sequence.\nExample\nLet us assume the following comma separated input sequence is given to the program:\n100,150,180\nThe output of the program should be:\n18,22,24\n\nHints:\nIf 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)\nIn case of input data being supplied to the question, it should be assumed to be a console input. \n\nSolution:\n#!/usr/bin/env python\nimport math\nc=50\nh=30\nvalue = []\nitems=[x for x in raw_input().split(',')]\nfor d in items:\n    value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))\n\nprint ','.join(value)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 7\nLevel 2\n\nQuestion:\nWrite 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.\nNote: i=0,1.., X-1; j=0,1,¡­Y-1.\nExample\nSuppose the following inputs are given to the program:\n3,5\nThen, the output of the program should be:\n[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] \n\nHints:\nNote: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form.\n\nSolution:\ninput_str = raw_input()\ndimensions=[int(x) for x in input_str.split(',')]\nrowNum=dimensions[0]\ncolNum=dimensions[1]\nmultilist = [[0 for col in range(colNum)] for row in range(rowNum)]\n\nfor row in range(rowNum):\n    for col in range(colNum):\n        multilist[row][col]= row*col\n\nprint multilist\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 8\nLevel 2\n\nQuestion:\nWrite 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.\nSuppose the following input is supplied to the program:\nwithout,hello,bag,world\nThen, the output should be:\nbag,hello,without,world\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\nitems=[x for x in raw_input().split(',')]\nitems.sort()\nprint ','.join(items)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 9\nLevel 2\n\nQuestion£º\nWrite a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.\nSuppose the following input is supplied to the program:\nHello world\nPractice makes perfect\nThen, the output should be:\nHELLO WORLD\nPRACTICE MAKES PERFECT\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\nlines = []\nwhile True:\n    s = raw_input()\n    if s:\n        lines.append(s.upper())\n    else:\n        break;\n\nfor sentence in lines:\n    print sentence\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 10\nLevel 2\n\nQuestion:\nWrite 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.\nSuppose the following input is supplied to the program:\nhello world and practice makes perfect and hello world again\nThen, the output should be:\nagain and hello makes perfect practice world\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\nWe use set container to remove duplicated data automatically and then use sorted() to sort the data.\n\nSolution:\ns = raw_input()\nwords = [word for word in s.split(\" \")]\nprint \" \".join(sorted(list(set(words))))\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 11\nLevel 2\n\nQuestion:\nWrite 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.\nExample:\n0100,0011,1010,1001\nThen the output should be:\n1010\nNotes: Assume the data is input by console.\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\nvalue = []\nitems=[x for x in raw_input().split(',')]\nfor p in items:\n    intp = int(p, 2)\n    if not intp%5:\n        value.append(p)\n\nprint ','.join(value)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 12\nLevel 2\n\nQuestion:\nWrite 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.\nThe numbers obtained should be printed in a comma-separated sequence on a single line.\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\nvalues = []\nfor i in range(1000, 3001):\n    s = str(i)\n    if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):\n        values.append(s)\nprint \",\".join(values)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 13\nLevel 2\n\nQuestion:\nWrite a program that accepts a sentence and calculate the number of letters and digits.\nSuppose the following input is supplied to the program:\nhello world! 123\nThen, the output should be:\nLETTERS 10\nDIGITS 3\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\ns = raw_input()\nd={\"DIGITS\":0, \"LETTERS\":0}\nfor c in s:\n    if c.isdigit():\n        d[\"DIGITS\"]+=1\n    elif c.isalpha():\n        d[\"LETTERS\"]+=1\n    else:\n        pass\nprint \"LETTERS\", d[\"LETTERS\"]\nprint \"DIGITS\", d[\"DIGITS\"]\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 14\nLevel 2\n\nQuestion:\nWrite a program that accepts a sentence and calculate the number of upper case letters and lower case letters.\nSuppose the following input is supplied to the program:\nHello world!\nThen, the output should be:\nUPPER CASE 1\nLOWER CASE 9\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\ns = raw_input()\nd={\"UPPER CASE\":0, \"LOWER CASE\":0}\nfor c in s:\n    if c.isupper():\n        d[\"UPPER CASE\"]+=1\n    elif c.islower():\n        d[\"LOWER CASE\"]+=1\n    else:\n        pass\nprint \"UPPER CASE\", d[\"UPPER CASE\"]\nprint \"LOWER CASE\", d[\"LOWER CASE\"]\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 15\nLevel 2\n\nQuestion:\nWrite a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.\nSuppose the following input is supplied to the program:\n9\nThen, the output should be:\n11106\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\na = raw_input()\nn1 = int( \"%s\" % a )\nn2 = int( \"%s%s\" % (a,a) )\nn3 = int( \"%s%s%s\" % (a,a,a) )\nn4 = int( \"%s%s%s%s\" % (a,a,a,a) )\nprint n1+n2+n3+n4\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 16\nLevel 2\n\nQuestion:\nUse a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.\nSuppose the following input is supplied to the program:\n1,2,3,4,5,6,7,8,9\nThen, the output should be:\n1,3,5,7,9\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\nvalues = raw_input()\nnumbers = [x for x in values.split(\",\") if int(x)%2!=0]\nprint \",\".join(numbers)\n#----------------------------------------#\n\nQuestion 17\nLevel 2\n\nQuestion:\nWrite 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:\nD 100\nW 200\n\nD means deposit while W means withdrawal.\nSuppose the following input is supplied to the program:\nD 300\nD 300\nW 200\nD 100\nThen, the output should be:\n500\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\nnetAmount = 0\nwhile True:\n    s = raw_input()\n    if not s:\n        break\n    values = s.split(\" \")\n    operation = values[0]\n    amount = int(values[1])\n    if operation==\"D\":\n        netAmount+=amount\n    elif operation==\"W\":\n        netAmount-=amount\n    else:\n        pass\nprint netAmount\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 18\nLevel 3\n\nQuestion:\nA website requires the users to input username and password to register. Write a program to check the validity of password input by users.\nFollowing are the criteria for checking the password:\n1. At least 1 letter between [a-z]\n2. At least 1 number between [0-9]\n1. At least 1 letter between [A-Z]\n3. At least 1 character from [$#@]\n4. Minimum length of transaction password: 6\n5. Maximum length of transaction password: 12\nYour 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.\nExample\nIf the following passwords are given as input to the program:\nABd1234@1,a F1#,2w3E*,2We3345\nThen, the output of the program should be:\nABd1234@1\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolutions:\nimport re\nvalue = []\nitems=[x for x in raw_input().split(',')]\nfor p in items:\n    if len(p)<6 or len(p)>12:\n        continue\n    else:\n        pass\n    if not re.search(\"[a-z]\",p):\n        continue\n    elif not re.search(\"[0-9]\",p):\n        continue\n    elif not re.search(\"[A-Z]\",p):\n        continue\n    elif not re.search(\"[$#@]\",p):\n        continue\n    elif re.search(\"\\s\",p):\n        continue\n    else:\n        pass\n    value.append(p)\nprint \",\".join(value)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 19\nLevel 3\n\nQuestion:\nYou 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:\n1: Sort based on name;\n2: Then sort based on age;\n3: Then sort by score.\nThe priority is that name > age > score.\nIf the following tuples are given as input to the program:\nTom,19,80\nJohn,20,90\nJony,17,91\nJony,17,93\nJson,21,85\nThen, the output of the program should be:\n[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\nWe use itemgetter to enable multiple sort keys.\n\nSolutions:\nfrom operator import itemgetter, attrgetter\n\nl = []\nwhile True:\n    s = raw_input()\n    if not s:\n        break\n    l.append(tuple(s.split(\",\")))\n\nprint sorted(l, key=itemgetter(0,1,2))\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 20\nLevel 3\n\nQuestion:\nDefine a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.\n\nHints:\nConsider use yield\n\nSolution:\ndef putNumbers(n):\n    i = 0\n    while i<n:\n        j=i\n        i=i+1\n        if j%7==0:\n            yield j\n\nfor i in reverse(100):\n    print i\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 21\nLevel 3\n\nQuestion£º\nA robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:\nUP 5\nDOWN 3\nLEFT 3\nRIGHT 2\n¡­\nThe numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.\nExample:\nIf the following tuples are given as input to the program:\nUP 5\nDOWN 3\nLEFT 3\nRIGHT 2\nThen, the output of the program should be:\n2\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\nimport math\npos = [0,0]\nwhile True:\n    s = raw_input()\n    if not s:\n        break\n    movement = s.split(\" \")\n    direction = movement[0]\n    steps = int(movement[1])\n    if direction==\"UP\":\n        pos[0]+=steps\n    elif direction==\"DOWN\":\n        pos[0]-=steps\n    elif direction==\"LEFT\":\n        pos[1]-=steps\n    elif direction==\"RIGHT\":\n        pos[1]+=steps\n    else:\n        pass\n\nprint int(round(math.sqrt(pos[1]**2+pos[0]**2)))\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 22\nLevel 3\n\nQuestion:\nWrite a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. \nSuppose the following input is supplied to the program:\nNew to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.\nThen, the output should be:\n2:2\n3.:1\n3?:1\nNew:1\nPython:5\nRead:1\nand:1\nbetween:1\nchoosing:1\nor:2\nto:1\n\nHints\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\nfreq = {}   # frequency of words in text\nline = raw_input()\nfor word in line.split():\n    freq[word] = freq.get(word,0)+1\n\nwords = freq.keys()\nwords.sort()\n\nfor w in words:\n    print \"%s:%d\" % (w,freq[w])\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 23\nlevel 1\n\nQuestion:\n    Write a method which can calculate square value of number\n\nHints:\n    Using the ** operator\n\nSolution:\ndef square(num):\n    return num ** 2\n\nprint square(2)\nprint square(3)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 24\nLevel 1\n\nQuestion:\n    Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.\n    Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()\n    And add document for your own function\n    \nHints:\n    The built-in document method is __doc__\n\nSolution:\nprint abs.__doc__\nprint int.__doc__\nprint raw_input.__doc__\n\ndef square(num):\n    '''Return the square value of the input number.\n    \n    The input number must be integer.\n    '''\n    return num ** 2\n\nprint square(2)\nprint square.__doc__\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion 25\nLevel 1\n\nQuestion:\n    Define a class, which have a class parameter and have a same instance parameter.\n\nHints:\n    Define a instance parameter, need add it in __init__ method\n    You can init a object with construct parameter or set the value later\n\nSolution:\nclass Person:\n    # Define the class parameter \"name\"\n    name = \"Person\"\n    \n    def __init__(self, name = None):\n        # self.name is the instance parameter\n        self.name = name\n\njeffrey = Person(\"Jeffrey\")\nprint \"%s name is %s\" % (Person.name, jeffrey.name)\n\nnico = Person()\nnico.name = \"Nico\"\nprint \"%s name is %s\" % (Person.name, nico.name)\n#----------------------------------------#\n\n#----------------------------------------#\nQuestion:\nDefine a function which can compute the sum of two numbers.\n\nHints:\nDefine a function with two numbers as arguments. You can compute the sum in the function and return the value.\n\nSolution\ndef SumFunction(number1, number2):\n\treturn number1+number2\n\nprint SumFunction(1,2)\n\n#----------------------------------------#\nQuestion:\nDefine a function that can convert a integer into a string and print it in console.\n\nHints:\n\nUse str() to convert a number to string.\n\nSolution\ndef printValue(n):\n\tprint str(n)\n\nprintValue(3)\n\t\n\n#----------------------------------------#\nQuestion:\nDefine a function that can convert a integer into a string and print it in console.\n\nHints:\n\nUse str() to convert a number to string.\n\nSolution\ndef printValue(n):\n\tprint str(n)\n\nprintValue(3)\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine a function that can receive two integral numbers in string form and compute their sum and then print it in console.\n\nHints:\n\nUse int() to convert a string to integer.\n\nSolution\ndef printValue(s1,s2):\n\tprint int(s1)+int(s2)\n\nprintValue(\"3\",\"4\") #7\n\n\n#----------------------------------------#\n2.10\n\n\nQuestion:\nDefine a function that can accept two strings as input and concatenate them and then print it in console.\n\nHints:\n\nUse + to concatenate the strings\n\nSolution\ndef printValue(s1,s2):\n\tprint s1+s2\n\nprintValue(\"3\",\"4\") #34\n\n#----------------------------------------#\n2.10\n\n\nQuestion:\nDefine a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print al l strings line by line.\n\nHints:\n\nUse len() function to get the length of a string\n\nSolution\ndef printValue(s1,s2):\n\tlen1 = len(s1)\n\tlen2 = len(s2)\n\tif len1>len2:\n\t\tprint s1\n\telif len2>len1:\n\t\tprint s2\n\telse:\n\t\tprint s1\n\t\tprint s2\n\t\t\n\nprintValue(\"one\",\"three\")\n\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine 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\".\n\nHints:\n\nUse % operator to check if a number is even or odd.\n\nSolution\ndef checkValue(n):\n\tif n%2 == 0:\n\t\tprint \"It is an even number\"\n\telse:\n\t\tprint \"It is an odd number\"\n\t\t\n\ncheckValue(7)\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine 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.\n\nHints:\n\nUse dict[key]=value pattern to put entry into a dictionary.\nUse ** operator to get power of a number.\n\nSolution\ndef printDict():\n\td=dict()\n\td[1]=1\n\td[2]=2**2\n\td[3]=3**2\n\tprint d\n\t\t\n\nprintDict()\n\n\n\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine 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.\n\nHints:\n\nUse dict[key]=value pattern to put entry into a dictionary.\nUse ** operator to get power of a number.\nUse range() for loops.\n\nSolution\ndef printDict():\n\td=dict()\n\tfor i in range(1,21):\n\t\td[i]=i**2\n\tprint d\n\t\t\n\nprintDict()\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine 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.\n\nHints:\n\nUse dict[key]=value pattern to put entry into a dictionary.\nUse ** operator to get power of a number.\nUse range() for loops.\nUse keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.\n\nSolution\ndef printDict():\n\td=dict()\n\tfor i in range(1,21):\n\t\td[i]=i**2\n\tfor (k,v) in d.items():\t\n\t\tprint v\n\t\t\n\nprintDict()\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine 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.\n\nHints:\n\nUse dict[key]=value pattern to put entry into a dictionary.\nUse ** operator to get power of a number.\nUse range() for loops.\nUse keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.\n\nSolution\ndef printDict():\n\td=dict()\n\tfor i in range(1,21):\n\t\td[i]=i**2\n\tfor k in d.keys():\t\n\t\tprint k\n\t\t\n\nprintDict()\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).\n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\n\nSolution\ndef printList():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint li\n\t\t\n\nprintList()\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine 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.\n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\nUse [n1:n2] to slice a list\n\nSolution\ndef printList():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint li[:5]\n\t\t\n\nprintList()\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine 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.\n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\nUse [n1:n2] to slice a list\n\nSolution\ndef printList():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint li[-5:]\n\t\t\n\nprintList()\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine 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.\n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\nUse [n1:n2] to slice a list\n\nSolution\ndef printList():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint li[5:]\n\t\t\n\nprintList()\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nDefine a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included). \n\nHints:\n\nUse ** operator to get power of a number.\nUse range() for loops.\nUse list.append() to add values into a list.\nUse tuple() to get a tuple from a list.\n\nSolution\ndef printTuple():\n\tli=list()\n\tfor i in range(1,21):\n\t\tli.append(i**2)\n\tprint tuple(li)\n\t\t\nprintTuple()\n\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nWith 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. \n\nHints:\n\nUse [n1:n2] notation to get a slice from a tuple.\n\nSolution\ntp=(1,2,3,4,5,6,7,8,9,10)\ntp1=tp[:5]\ntp2=tp[5:]\nprint tp1\nprint tp2\n\n\n#----------------------------------------#\n2.10\n\nQuestion:\nWrite 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). \n\nHints:\n\nUse \"for\" to iterate the tuple\nUse tuple() to generate a tuple from a list.\n\nSolution\ntp=(1,2,3,4,5,6,7,8,9,10)\nli=list()\nfor i in tp:\n\tif tp[i]%2==0:\n\t\tli.append(tp[i])\n\ntp2=tuple(li)\nprint tp2\n\n\n\n#----------------------------------------#\n2.14\n\nQuestion:\nWrite a program which accepts a string as input to print \"Yes\" if the string is \"yes\" or \"YES\" or \"Yes\", otherwise print \"No\". \n\nHints:\n\nUse if statement to judge condition.\n\nSolution\ns= raw_input()\nif s==\"yes\" or s==\"YES\" or s==\"Yes\":\n    print \"Yes\"\nelse:\n    print \"No\"\n\n\n\n#----------------------------------------#\n3.4\n\nQuestion:\nWrite 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].\n\nHints:\n\nUse filter() to filter some elements in a list.\nUse lambda to define anonymous functions.\n\nSolution\nli = [1,2,3,4,5,6,7,8,9,10]\nevenNumbers = filter(lambda x: x%2==0, li)\nprint evenNumbers\n\n\n#----------------------------------------#\n3.4\n\nQuestion:\nWrite 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].\n\nHints:\n\nUse map() to generate a list.\nUse lambda to define anonymous functions.\n\nSolution\nli = [1,2,3,4,5,6,7,8,9,10]\nsquaredNumbers = map(lambda x: x**2, li)\nprint squaredNumbers\n\n#----------------------------------------#\n3.5\n\nQuestion:\nWrite 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].\n\nHints:\n\nUse map() to generate a list.\nUse filter() to filter elements of a list.\nUse lambda to define anonymous functions.\n\nSolution\nli = [1,2,3,4,5,6,7,8,9,10]\nevenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))\nprint evenNumbers\n\n\n\n\n#----------------------------------------#\n3.5\n\nQuestion:\nWrite a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).\n\nHints:\n\nUse filter() to filter elements of a list.\nUse lambda to define anonymous functions.\n\nSolution\nevenNumbers = filter(lambda x: x%2==0, range(1,21))\nprint evenNumbers\n\n\n#----------------------------------------#\n3.5\n\nQuestion:\nWrite a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).\n\nHints:\n\nUse map() to generate a list.\nUse lambda to define anonymous functions.\n\nSolution\nsquaredNumbers = map(lambda x: x**2, range(1,21))\nprint squaredNumbers\n\n\n\n\n#----------------------------------------#\n7.2\n\nQuestion:\nDefine a class named American which has a static method called printNationality.\n\nHints:\n\nUse @staticmethod decorator to define class static method.\n\nSolution\nclass American(object):\n    @staticmethod\n    def printNationality():\n        print \"America\"\n\nanAmerican = American()\nanAmerican.printNationality()\nAmerican.printNationality()\n\n\n\n\n#----------------------------------------#\n\n7.2\n\nQuestion:\nDefine a class named American and its subclass NewYorker. \n\nHints:\n\nUse class Subclass(ParentClass) to define a subclass.\n\nSolution:\n\nclass American(object):\n    pass\n\nclass NewYorker(American):\n    pass\n\nanAmerican = American()\naNewYorker = NewYorker()\nprint anAmerican\nprint aNewYorker\n\n\n\n\n#----------------------------------------#\n\n\n7.2\n\nQuestion:\nDefine a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. \n\nHints:\n\nUse def methodName(self) to define a method.\n\nSolution:\n\nclass Circle(object):\n    def __init__(self, r):\n        self.radius = r\n\n    def area(self):\n        return self.radius**2*3.14\n\naCircle = Circle(2)\nprint aCircle.area()\n\n\n\n\n\n\n#----------------------------------------#\n\n7.2\n\nDefine a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area. \n\nHints:\n\nUse def methodName(self) to define a method.\n\nSolution:\n\nclass Rectangle(object):\n    def __init__(self, l, w):\n        self.length = l\n        self.width  = w\n\n    def area(self):\n        return self.length*self.width\n\naRectangle = Rectangle(2,10)\nprint aRectangle.area()\n\n\n\n\n#----------------------------------------#\n\n7.2\n\nDefine 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.\n\nHints:\n\nTo override a method in super class, we can define a method with the same name in the super class.\n\nSolution:\n\nclass Shape(object):\n    def __init__(self):\n        pass\n\n    def area(self):\n        return 0\n\nclass Square(Shape):\n    def __init__(self, l):\n        Shape.__init__(self)\n        self.length = l\n\n    def area(self):\n        return self.length*self.length\n\naSquare= Square(3)\nprint aSquare.area()\n\n\n\n\n\n\n\n\n#----------------------------------------#\n\n\nPlease raise a RuntimeError exception.\n\nHints:\n\nUse raise() to raise an exception.\n\nSolution:\n\nraise RuntimeError('something wrong')\n\n\n\n#----------------------------------------#\nWrite a function to compute 5/0 and use try/except to catch the exceptions.\n\nHints:\n\nUse try/except to catch exceptions.\n\nSolution:\n\ndef throws():\n    return 5/0\n\ntry:\n    throws()\nexcept ZeroDivisionError:\n    print \"division by zero!\"\nexcept Exception, err:\n    print 'Caught an exception'\nfinally:\n    print 'In finally block for cleanup'\n\n\n#----------------------------------------#\nDefine a custom exception class which takes a string message as attribute.\n\nHints:\n\nTo define a custom exception, we need to define a class inherited from Exception.\n\nSolution:\n\nclass MyError(Exception):\n    \"\"\"My own exception class\n\n    Attributes:\n        msg  -- explanation of the error\n    \"\"\"\n\n    def __init__(self, msg):\n        self.msg = msg\n\nerror = MyError(\"something wrong\")\n\n#----------------------------------------#\nQuestion:\n\nAssuming 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.\n\nExample:\nIf the following email address is given as input to the program:\n\njohn@google.com\n\nThen, the output of the program should be:\n\njohn\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\n\nUse \\w to match letters.\n\nSolution:\nimport re\nemailAddress = raw_input()\npat2 = \"(\\w+)@((\\w+\\.)+(com))\"\nr2 = re.match(pat2,emailAddress)\nprint r2.group(1)\n\n\n#----------------------------------------#\nQuestion:\n\nAssuming 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.\n\nExample:\nIf the following email address is given as input to the program:\n\njohn@google.com\n\nThen, the output of the program should be:\n\ngoogle\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\n\nUse \\w to match letters.\n\nSolution:\nimport re\nemailAddress = raw_input()\npat2 = \"(\\w+)@(\\w+)\\.(com)\"\nr2 = re.match(pat2,emailAddress)\nprint r2.group(2)\n\n\n\n\n#----------------------------------------#\nQuestion:\n\nWrite a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.\n\nExample:\nIf the following words is given as input to the program:\n\n2 cats and 3 dogs.\n\nThen, the output of the program should be:\n\n['2', '3']\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\n\nUse re.findall() to find all substring using regex.\n\nSolution:\nimport re\ns = raw_input()\nprint re.findall(\"\\d+\",s)\n\n\n#----------------------------------------#\nQuestion:\n\n\nPrint a unicode string \"hello world\".\n\nHints:\n\nUse u'strings' format to define unicode string.\n\nSolution:\n\nunicodeString = u\"hello world!\"\nprint unicodeString\n\n#----------------------------------------#\nWrite a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.\n\nHints:\n\nUse unicode() function to convert.\n\nSolution:\n\ns = raw_input()\nu = unicode( s ,\"utf-8\")\nprint u\n\n#----------------------------------------#\nQuestion:\n\nWrite a special comment to indicate a Python source code file is in unicode.\n\nHints:\n\nSolution:\n\n# -*- coding: utf-8 -*-\n\n#----------------------------------------#\nQuestion:\n\nWrite a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).\n\nExample:\nIf the following n is given as input to the program:\n\n5\n\nThen, the output of the program should be:\n\n3.55\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\nUse float() to convert an integer to a float\n\nSolution:\n\nn=int(raw_input())\nsum=0.0\nfor i in range(1,n+1):\n    sum += float(float(i)/(i+1))\nprint sum\n\n\n#----------------------------------------#\nQuestion:\n\nWrite a program to compute:\n\nf(n)=f(n-1)+100 when n>0\nand f(0)=1\n\nwith a given n input by console (n>0).\n\nExample:\nIf the following n is given as input to the program:\n\n5\n\nThen, the output of the program should be:\n\n500\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\nWe can define recursive function in Python.\n\nSolution:\n\ndef f(n):\n    if n==0:\n        return 0\n    else:\n        return f(n-1)+100\n\nn=int(raw_input())\nprint f(n)\n\n#----------------------------------------#\n\nQuestion:\n\n\nThe Fibonacci Sequence is computed based on the following formula:\n\n\nf(n)=0 if n=0\nf(n)=1 if n=1\nf(n)=f(n-1)+f(n-2) if n>1\n\nPlease write a program to compute the value of f(n) with a given n input by console.\n\nExample:\nIf the following n is given as input to the program:\n\n7\n\nThen, the output of the program should be:\n\n13\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nHints:\nWe can define recursive function in Python.\n\n\nSolution:\n\ndef f(n):\n    if n == 0: return 0\n    elif n == 1: return 1\n    else: return f(n-1)+f(n-2)\n\nn=int(raw_input())\nprint f(n)\n\n\n#----------------------------------------#\n\n#----------------------------------------#\n\nQuestion:\n\nThe Fibonacci Sequence is computed based on the following formula:\n\n\nf(n)=0 if n=0\nf(n)=1 if n=1\nf(n)=f(n-1)+f(n-2) if n>1\n\nPlease write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console.\n\nExample:\nIf the following n is given as input to the program:\n\n7\n\nThen, the output of the program should be:\n\n0,1,1,2,3,5,8,13\n\n\nHints:\nWe can define recursive function in Python.\nUse list comprehension to generate a list from an existing list.\nUse string.join() to join a list of strings.\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n\ndef f(n):\n    if n == 0: return 0\n    elif n == 1: return 1\n    else: return f(n-1)+f(n-2)\n\nn=int(raw_input())\nvalues = [str(f(x)) for x in range(0, n+1)]\nprint \",\".join(values)\n\n\n#----------------------------------------#\n\nQuestion:\n\nPlease write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.\n\nExample:\nIf the following n is given as input to the program:\n\n10\n\nThen, the output of the program should be:\n\n0,2,4,6,8,10\n\nHints:\nUse yield to produce the next value in generator.\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n\ndef EvenGenerator(n):\n    i=0\n    while i<=n:\n        if i%2==0:\n            yield i\n        i+=1\n\n\nn=int(raw_input())\nvalues = []\nfor i in EvenGenerator(n):\n    values.append(str(i))\n\nprint \",\".join(values)\n\n\n#----------------------------------------#\n\nQuestion:\n\nPlease 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.\n\nExample:\nIf the following n is given as input to the program:\n\n100\n\nThen, the output of the program should be:\n\n0,35,70\n\nHints:\nUse yield to produce the next value in generator.\n\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\nSolution:\n\ndef NumGenerator(n):\n    for i in range(n+1):\n        if i%5==0 and i%7==0:\n            yield i\n\nn=int(raw_input())\nvalues = []\nfor i in NumGenerator(n):\n    values.append(str(i))\n\nprint \",\".join(values)\n\n\n#----------------------------------------#\n\nQuestion:\n\n\nPlease write assert statements to verify that every number in the list [2,4,6,8] is even.\n\n\n\nHints:\nUse \"assert expression\" to make assertion.\n\n\nSolution:\n\nli = [2,4,6,8]\nfor i in li:\n    assert i%2==0\n\n\n#----------------------------------------#\nQuestion:\n\nPlease write a program which accepts basic mathematic expression from console and print the evaluation result.\n\nExample:\nIf the following string is given as input to the program:\n\n35+3\n\nThen, the output of the program should be:\n\n38\n\nHints:\nUse eval() to evaluate an expression.\n\n\nSolution:\n\nexpression = raw_input()\nprint eval(expression)\n\n\n#----------------------------------------#\nQuestion:\n\nPlease 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.\n\n\nHints:\nUse if/elif to deal with conditions.\n\n\nSolution:\n\nimport math\ndef bin_search(li, element):\n    bottom = 0\n    top = len(li)-1\n    index = -1\n    while top>=bottom and index==-1:\n        mid = int(math.floor((top+bottom)/2.0))\n        if li[mid]==element:\n            index = mid\n        elif li[mid]>element:\n            top = mid-1\n        else:\n            bottom = mid+1\n\n    return index\n\nli=[2,5,7,9,11,17,222]\nprint bin_search(li,11)\nprint bin_search(li,12)\n\n\n\n\n#----------------------------------------#\nQuestion:\n\nPlease 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.\n\n\nHints:\nUse if/elif to deal with conditions.\n\n\nSolution:\n\nimport math\ndef bin_search(li, element):\n    bottom = 0\n    top = len(li)-1\n    index = -1\n    while top>=bottom and index==-1:\n        mid = int(math.floor((top+bottom)/2.0))\n        if li[mid]==element:\n            index = mid\n        elif li[mid]>element:\n            top = mid-1\n        else:\n            bottom = mid+1\n\n    return index\n\nli=[2,5,7,9,11,17,222]\nprint bin_search(li,11)\nprint bin_search(li,12)\n\n\n\n\n#----------------------------------------#\nQuestion:\n\nPlease generate a random float where the value is between 10 and 100 using Python math module.\n\n\n\nHints:\nUse random.random() to generate a random float in [0,1].\n\n\nSolution:\n\nimport random\nprint random.random()*100\n\n#----------------------------------------#\nQuestion:\n\nPlease generate a random float where the value is between 5 and 95 using Python math module.\n\n\n\nHints:\nUse random.random() to generate a random float in [0,1].\n\n\nSolution:\n\nimport random\nprint random.random()*100-5\n\n\n#----------------------------------------#\nQuestion:\n\nPlease write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.\n\n\n\nHints:\nUse random.choice() to a random element from a list.\n\n\nSolution:\n\nimport random\nprint random.choice([i for i in range(11) if i%2==0])\n\n\n#----------------------------------------#\nQuestion:\n\nPlease 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.\n\n\n\nHints:\nUse random.choice() to a random element from a list.\n\n\nSolution:\n\nimport random\nprint random.choice([i for i in range(201) if i%5==0 and i%7==0])\n\n\n\n#----------------------------------------#\n\nQuestion:\n\nPlease write a program to generate a list with 5 random numbers between 100 and 200 inclusive.\n\n\n\nHints:\nUse random.sample() to generate a list of random values.\n\n\nSolution:\n\nimport random\nprint random.sample(range(100), 5)\n\n#----------------------------------------#\nQuestion:\n\nPlease write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.\n\n\n\nHints:\nUse random.sample() to generate a list of random values.\n\n\nSolution:\n\nimport random\nprint random.sample([i for i in range(100,201) if i%2==0], 5)\n\n\n#----------------------------------------#\nQuestion:\n\nPlease write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.\n\n\n\nHints:\nUse random.sample() to generate a list of random values.\n\n\nSolution:\n\nimport random\nprint random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5)\n\n#----------------------------------------#\n\nQuestion:\n\nPlease write a program to randomly print a integer number between 7 and 15 inclusive.\n\n\n\nHints:\nUse random.randrange() to a random integer in a given range.\n\n\nSolution:\n\nimport random\nprint random.randrange(7,16)\n\n#----------------------------------------#\n\nQuestion:\n\nPlease write a program to compress and decompress the string \"hello world!hello world!hello world!hello world!\".\n\n\n\nHints:\nUse zlib.compress() and zlib.decompress() to compress and decompress a string.\n\n\nSolution:\n\nimport zlib\ns = 'hello world!hello world!hello world!hello world!'\nt = zlib.compress(s)\nprint t\nprint zlib.decompress(t)\n\n#----------------------------------------#\nQuestion:\n\nPlease write a program to print the running time of execution of \"1+1\" for 100 times.\n\n\n\nHints:\nUse timeit() function to measure the running time.\n\nSolution:\n\nfrom timeit import Timer\nt = Timer(\"for i in range(100):1+1\")\nprint t.timeit()\n\n#----------------------------------------#\nQuestion:\n\nPlease write a program to shuffle and print the list [3,6,7,8].\n\n\n\nHints:\nUse shuffle() function to shuffle a list.\n\nSolution:\n\nfrom random import shuffle\nli = [3,6,7,8]\nshuffle(li)\nprint li\n\n#----------------------------------------#\nQuestion:\n\nPlease write a program to shuffle and print the list [3,6,7,8].\n\n\n\nHints:\nUse shuffle() function to shuffle a list.\n\nSolution:\n\nfrom random import shuffle\nli = [3,6,7,8]\nshuffle(li)\nprint li\n\n\n\n#----------------------------------------#\nQuestion:\n\nPlease 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\"].\n\nHints:\nUse list[index] notation to get a element from a list.\n\nSolution:\n\nsubjects=[\"I\", \"You\"]\nverbs=[\"Play\", \"Love\"]\nobjects=[\"Hockey\",\"Football\"]\nfor i in range(len(subjects)):\n    for j in range(len(verbs)):\n        for k in range(len(objects)):\n            sentence = \"%s %s %s.\" % (subjects[i], verbs[j], objects[k])\n            print sentence\n\n\n#----------------------------------------#\nPlease write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].\n\nHints:\nUse list comprehension to delete a bunch of element from a list.\n\nSolution:\n\nli = [5,6,77,45,22,12,24]\nli = [x for x in li if x%2!=0]\nprint li\n\n#----------------------------------------#\nQuestion:\n\nBy 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].\n\nHints:\nUse list comprehension to delete a bunch of element from a list.\n\nSolution:\n\nli = [12,24,35,70,88,120,155]\nli = [x for x in li if x%5!=0 and x%7!=0]\nprint li\n\n\n#----------------------------------------#\nQuestion:\n\nBy 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].\n\nHints:\nUse list comprehension to delete a bunch of element from a list.\nUse enumerate() to get (index, value) tuple.\n\nSolution:\n\nli = [12,24,35,70,88,120,155]\nli = [x for (i,x) in enumerate(li) if i%2!=0]\nprint li\n\n#----------------------------------------#\n\nQuestion:\n\nBy using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.\n\nHints:\nUse list comprehension to make an array.\n\nSolution:\n\narray = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]\nprint array\n\n#----------------------------------------#\nQuestion:\n\nBy 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].\n\nHints:\nUse list comprehension to delete a bunch of element from a list.\nUse enumerate() to get (index, value) tuple.\n\nSolution:\n\nli = [12,24,35,70,88,120,155]\nli = [x for (i,x) in enumerate(li) if i not in (0,4,5)]\nprint li\n\n\n\n#----------------------------------------#\n\nQuestion:\n\nBy using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].\n\nHints:\nUse list's remove method to delete a value.\n\nSolution:\n\nli = [12,24,35,24,88,120,155]\nli = [x for x in li if x!=24]\nprint li\n\n\n#----------------------------------------#\nQuestion:\n\nWith 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.\n\nHints:\nUse set() and \"&=\" to do set intersection operation.\n\nSolution:\n\nset1=set([1,3,6,78,35,55])\nset2=set([12,24,35,24,88,120,155])\nset1 &= set2\nli=list(set1)\nprint li\n\n#----------------------------------------#\n\nWith 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.\n\nHints:\nUse set() to store a number of values without duplicate.\n\nSolution:\n\ndef removeDuplicate( li ):\n    newli=[]\n    seen = set()\n    for item in li:\n        if item not in seen:\n            seen.add( item )\n            newli.append(item)\n\n    return newli\n\nli=[12,24,35,24,88,120,155,88,120,155]\nprint removeDuplicate(li)\n\n\n#----------------------------------------#\nQuestion:\n\nDefine 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.\n\nHints:\nUse Subclass(Parentclass) to define a child class.\n\nSolution:\n\nclass Person(object):\n    def getGender( self ):\n        return \"Unknown\"\n\nclass Male( Person ):\n    def getGender( self ):\n        return \"Male\"\n\nclass Female( Person ):\n    def getGender( self ):\n        return \"Female\"\n\naMale = Male()\naFemale= Female()\nprint aMale.getGender()\nprint aFemale.getGender()\n\n\n\n#----------------------------------------#\nQuestion:\n\nPlease write a program which count and print the numbers of each character in a string input by console.\n\nExample:\nIf the following string is given as input to the program:\n\nabcdefgabc\n\nThen, the output of the program should be:\n\na,2\nc,2\nb,2\ne,1\nd,1\ng,1\nf,1\n\nHints:\nUse dict to store key/value pairs.\nUse dict.get() method to lookup a key with default value.\n\nSolution:\n\ndic = {}\ns=raw_input()\nfor s in s:\n    dic[s] = dic.get(s,0)+1\nprint '\\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])\n\n#----------------------------------------#\n\nQuestion:\n\nPlease write a program which accepts a string from console and print it in reverse order.\n\nExample:\nIf the following string is given as input to the program:\n\nrise to vote sir\n\nThen, the output of the program should be:\n\nris etov ot esir\n\nHints:\nUse list[::-1] to iterate a list in a reverse order.\n\nSolution:\n\ns=raw_input()\ns = s[::-1]\nprint s\n\n#----------------------------------------#\n\nQuestion:\n\nPlease write a program which accepts a string from console and print the characters that have even indexes.\n\nExample:\nIf the following string is given as input to the program:\n\nH1e2l3l4o5w6o7r8l9d\n\nThen, the output of the program should be:\n\nHelloworld\n\nHints:\nUse list[::2] to iterate a list by step 2.\n\nSolution:\n\ns=raw_input()\ns = s[::2]\nprint s\n#----------------------------------------#\n\n\nQuestion:\n\nPlease write a program which prints all permutations of [1,2,3]\n\n\nHints:\nUse itertools.permutations() to get permutations of list.\n\nSolution:\n\nimport itertools\nprint list(itertools.permutations([1,2,3]))\n\n#----------------------------------------#\nQuestion:\n\nWrite a program to solve a classic ancient Chinese puzzle: \nWe count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?\n\nHint:\nUse for loop to iterate all possible solutions.\n\nSolution:\n\ndef solve(numheads,numlegs):\n    ns='No solutions!'\n    for i in range(numheads+1):\n        j=numheads-i\n        if 2*i+4*j==numlegs:\n            return i,j\n    return ns,ns\n\nnumheads=35\nnumlegs=94\nsolutions=solve(numheads,numlegs)\nprint solutions\n\n#----------------------------------------#\n\n\n"
  },
  {
    "path": "README.md",
    "content": " [<img src=\"https://devin.ai/assets/deepwiki-badge.png\" alt=\"Ask DeepWiki.com\" height=\"20\"/>](https://deepwiki.com/zhiwehu/Python-programming-exercises)\n \n# Python-programming-exercises\n\n100+ Python challenge programming exercises.\n\n## 100+ Python Projects Challenge \n\nhttps://github.com/zhiwehu/100_plus_Python_Projects_Challenge\n\n## A simple Python online IDE run in browser.\n\nHey 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.\n\n## Python comic\n\nHey guys I just created a comic for learning Python if you like you could see it from here: https://zhixinfuture.com\nFor now I just use Chinese if you like I could use English as well.\n\n![Python Comic](https://github.com/zhiwehu/Python-programming-exercises/blob/master/comic.png?raw=true)\n"
  },
  {
    "path": "python contents.txt",
    "content": "Python\nThe 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.\nNo.\tDiving into Python\tThe Python Standard Library by Example\tPython Essential Reference (4th edition)\tThe Quick Python Book\tLearning Python\nIntroductory Concepts covering installation on different OS, version history, interpreter. This section also covers questions like Why, Who, What and Where on Python.\n1\t1.\tInstalling Python\n2.\tWhich Python is right for you ?\n3.\tPython & your OS\n4.\tInteractive Shell\n5.\tSummary\t1.\tIntroduction (Text)\t1.\tTutorial Introduction\n2.\tLexical Conventions and Syntax\t1.\tAbout Python\n2.\tGetting Started\t1.\tPython Q & A Session\n1.\tWhy do people use Python ?\n2.\tDownside of using it\n3.\tWho uses Python Today ?\n4.\tWhat Can I do with Python ?\n5.\tPython vs Language X\n6.\tTest your Knowledge\n2.\tHow Python runs programs\n1.\tPython Interpreter\n2.\tProgram Execution\n1.\tProgrammer View\n2.\tPython View\n3.\tExecution Model Variations\n1.\tImplementation Alternatives\n2.\tExecution Optimization Tools\n3.\tFrozen Binaries\n3.\tHow you run programs\n1.\tInteractive prompt\n2.\tYour first script\n<snipped>\nPython Object Types, Numeric Types, Data Structures, Control Structures, Scopes and Arguments\n2\t1.\tYour first program\n2.\tDeclaring Functions\n3.\tPython Data types vs Other Languages\n4.\tDocumenting Functions\n5.\tEverything is an Object\n6.\tThe Import Search Path\n7.\tWhat is an Object ?\n8.\tIndenting Code\n9.\tTesting Modules\n10.\tNative Datatypes\n1.\tDictionaries\n2.\tList\n3.\tTuples\n11.\tVariables & referencing\t1.\tData Structures\t1.\tTypes and Objects\n2.\tOperators and Expressions\n3.\tProgram Structure and Control Flow\n4.\tFunctions and Functional Programming\n5.\tClasses and Object Oriented Programming\n6.\tModules, Packages and Distribution\n7.\tInput and Output\n8.\tExecution Environment\n9.\tTesting, Debugging, Profiling and Tuning\n<Covered further along in the book>\nData Structures, Algorithms & Code simplification\nString & Text Handling\t1.\tPython Overview\n1.\tBuilt-in Data types\n2.\tControl Structures\n3.\tModule\n4.\tOOPs\n2.\tBasics\n1.\tLists\n2.\tDictionaries\n3.\tTuple\n4.\tSets\n5.\tStrings\n6.\tControl Flow\n3.\tFunctions\n4.\tModules and Scoping Rules\n5.\tPython Programs\t1.\tIntroducing Python Object Types\n1.\tWhy use built-in Types ?\n2.\tCore data types\n3.\tNumbers, Lists, Dictionaries, Tuples, Files, Other Core Types\n4.\tUser Defined Classes\n2.\tNumeric Types\n1.\tLiterals, Built-in tools, expression operators\n2.\tFormats, Comparisons, Division, Precision\n3.\tComplex Numbers\n4.\tHexadecimal, Octal & Binary\n5.\tBitwise Operations\n6.\tDecimal, Fraction, Sets, Booleans\n<Covered further along in the book>\n1.\tStatements & Syntax\n2.\tAssignments, Expressions & Syntax\n3.\tIf Tests & Syntax Rules\n4.\tScopes\n5.\tArguments\nBuilt-in functions, Function Design, Recursive Functions, Introspection, Annotations, Lambda, Filter and Reduce\n3\t1.\tPower of Introspection\n1.\tOptional and Named Arguments\n2.\ttype, str, dir and other built-in functions\n3.\tObject References with getattr\n4.\tFiltering Lists\n5.\tLambda Functions\n6.\tReal world Lambda functions\n \tNone\t1.\tBuilt-in functions\n2.\tPython run-time services\tNone\tBuilt-in functions are covered as part of the topic above but from a numeric perspective\n1.\tAdvanced Function Topics\n1.\tFunction Design\n2.\tRecursive Functions\n3.\tAttributes and Annotation\n4.\tLambda\n5.\tMapping Functions over sequences\n6.\tFilter and Reduce\n<Covered further along in the book>\nSpecial Class Attributes\nDisplay Tool\nOOPS, Modules\n4\t1.\tObjects and Object Orientation\n1.\tImporting Modules\n2.\tDefining Classes\n3.\tInitializing and Coding Classes\n4.\tSelf & __init__\n5.\tInstantiating Classes\n6.\tGarbage Collection\n7.\tWrapper Classes\n8.\tSpecial Class Methods\n9.\tAdvanced Class Methods\n10.\tClass Attributes\n11.\tPrivate Functions\tNone\tCovered partially section 2\t1.\tPackages\n2.\tData Types and Objects\n3.\tAdvanced Object Oriented Features\t1.\tModules\n1.\tWhy use Modules ?\n2.\tProgram Architecture\n3.\tModule Search Path\n4.\tModule Creation & Usage\n5.\tNamespaces\n6.\tReloading Modules\n7.\tPackages\n2.\tAdvanced Module Topics\n1.\tData Hiding in Modules\n2.\tas Extension for import and from\n3.\tModules are Objects: Metaprograms\n4.\tTransitive Module Reloads\n5.\tModule Design Concepts\n6.\tModule Gotchas\n3.\tOOP\n1.\tWhy use classes ?\n2.\tClasses & Instances\n3.\tAttribute Inheritance Search\n4.\tClass Method Calls\n5.\tClass Trees\n6.\tClass Objects & Default Behavior\n7.\tInstance Objects are Concrete Items\n8.\tIntercepting Python Operators\n9.\tClasses Vs. Dictionaries\n10.\tClass customization by Inheritance\n11.\tOperator Overloading\n12.\tSubclasses\n13.\tPolymorphism in Action\n14.\tDesigning with Classes\n15.\tMix-in Classes\nAdvanced Class Topics\n5\tNone\tNone\tNone\tNone\t1.\tAdvanced Class Topics\n1.\tExtending Types by Embedding\n2.\tExtending Types by Subclassing\n3.\tStatic and Class Methods\n4.\tDecorators and Metaclasses\n5.\tClass Gotchas\nExceptions\n6\t1.\tExceptions and File Handling\n1.\tHandling Exceptions\n2.\tUsing exceptions for other purposes\t \t \t1.\tExceptions\t1.\tExceptions Basics\n1.\tWhy use Exceptions ?\n2.\tDefault Exception Handler\n3.\tUser-Defined Exceptions\n4.\tClass Based Exceptions\n5.\tDesigning with Exceptions\nXML, HTTP, SOAP, Network Programming, I18N, Unicode\n7\t1.\tRegular Expressions\n2.\tParsing / Processing Mark-up languages (HTML, XML)\n1.\tUnicode\n3.\tHTTP Web Services\n1.\tHeaders\n2.\tDebugging\n4.\tSOAP Web Services\t1.\tNetworking\n2.\tInternet\n3.\tEmail\n4.\tInternationalization and Localization\t1.\tNetwork Programming and Sockets\n2.\tInternet Application Programming\n3.\tWeb Programming\n4.\tInternet Data Handling & Encoding\t1.\tNetwork, web programming\t1.\tUnicode and Bytes Strings\nMiscellaneous\n8\tNone\t1.\tAlgorithms\n2.\tCryptography\n3.\tData compression and archiving\n4.\tProcesses and Threads\n5.\tData persistence & exchange\t1.\tExtending & Embedding Python\t1.\tGUI\tNone\n"
  }
]