{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# **Interview Questions : Basic Python**","metadata":{"id":"G-ChdzSLJwOZ"}},{"cell_type":"markdown","source":"# **Q1.Write a python program to check if a string is palindrome or not?**","metadata":{"id":"IzXzx0ulKZFl"}},{"cell_type":"markdown","source":"Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if the reverse of the string is the same as string. For example, “radar” is a palindrome, but “radix” is not a palindrome.","metadata":{"id":"2xXVGhfyKoeH"}},{"cell_type":"markdown","source":"Method #1 \n\n1. Find reverse of string\n2. Check if reverse and original are same or not.","metadata":{"id":"Dmvb5zgMK9oP"}},{"cell_type":"code","source":"# function which return reverse of a string\n \ndef isPalindrome(s):\n    return s == s[::-1]\n \n \n# Driver code\ns = \"malayalam\"\nans = isPalindrome(s)\n \nif ans:\n    print(\"Yes\")\nelse:\n    print(\"No\")","metadata":{"id":"iyKnhl_FKL6u","outputId":"558ed9ff-fc16-49ab-b701-caf72139f475","execution":{"iopub.status.busy":"2022-08-26T11:06:46.456641Z","iopub.execute_input":"2022-08-26T11:06:46.457074Z","iopub.status.idle":"2022-08-26T11:06:46.465077Z","shell.execute_reply.started":"2022-08-26T11:06:46.457040Z","shell.execute_reply":"2022-08-26T11:06:46.463780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def isPalindrome(p):\n  return p == p[::-1]\n\n\np = 'Python Is Easy'\nans = isPalindrome(p)\n\nif ans :\n  print('YES')\nelse:\n  print(\"NO\")  \n\n","metadata":{"id":"CJfWUMs3LIiX","outputId":"b2f9a8a5-d417-43af-f5a0-fd7696131ed9","execution":{"iopub.status.busy":"2022-08-26T11:06:46.467296Z","iopub.execute_input":"2022-08-26T11:06:46.468054Z","iopub.status.idle":"2022-08-26T11:06:46.481006Z","shell.execute_reply.started":"2022-08-26T11:06:46.468013Z","shell.execute_reply":"2022-08-26T11:06:46.479579Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Iterative Method: Run a loop from starting to length/2 and check the first character to the last character of the string and second to second last one and so on …. If any character mismatches, the string wouldn’t be a palindrome.","metadata":{"id":"WAWysryYQk-7"}},{"cell_type":"code","source":"  \n# function to check string is\n# palindrome or not\ndef isPalindrome(str):\n \n    # Run loop from 0 to len/2\n    for i in range(0, int(len(str)/2)):\n        if str[i] != str[len(str)-i-1]:\n            return False\n    return True\n \n# main function\ns = \"malayalam\"\nans = isPalindrome(s)\n \nif (ans):\n    print(\"Yes\")\nelse:\n    print(\"No\")","metadata":{"id":"0GSNGofyMD9K","outputId":"d5b712bf-cfe6-4b7c-df73-c0ea92535b24","execution":{"iopub.status.busy":"2022-08-26T11:06:46.482468Z","iopub.execute_input":"2022-08-26T11:06:46.482863Z","iopub.status.idle":"2022-08-26T11:06:46.497612Z","shell.execute_reply.started":"2022-08-26T11:06:46.482822Z","shell.execute_reply":"2022-08-26T11:06:46.496055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def isPalindrome(str):\n  for i in range(0,int(len(str)/2)):\n    if str[i] != str [len(str)-i-1]:\n      return False\n  return True\n\n\ns = \"Mumbai\"\n\nans = isPalindrome(s)\n\nif (ans):\n  print(\"YES\")\nelse:\n  print(\"NO\")  ","metadata":{"id":"d0UZva6bRC3d","outputId":"2733219e-27ea-4e08-e435-0f27109e7806","execution":{"iopub.status.busy":"2022-08-26T11:06:46.500906Z","iopub.execute_input":"2022-08-26T11:06:46.501686Z","iopub.status.idle":"2022-08-26T11:06:46.511737Z","shell.execute_reply.started":"2022-08-26T11:06:46.501643Z","shell.execute_reply":"2022-08-26T11:06:46.510517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Method using the inbuilt function to reverse a string: In this method, predefined function ‘ ‘.join(reversed(string)) is used to reverse string.","metadata":{"id":"2pA4enuMScFX"}},{"cell_type":"code","source":"# function to check string is\n# palindrome or not\ndef isPalindrome(s):\n \n    # Using predefined function to\n    # reverse to string print(s)\n    rev = ''.join(reversed(s))\n \n    # Checking if both string are\n    # equal or not\n    if (s == rev):\n        return True\n    return False\n \n# main function\ns = \"malayalam\"\nans = isPalindrome(s)\n \nif (ans):\n    print(\"Yes\")\nelse:\n    print(\"No\")","metadata":{"id":"8IO70Im1SBZo","outputId":"9327fbf8-8790-4551-b168-87cd46dbd620","execution":{"iopub.status.busy":"2022-08-26T11:06:46.514171Z","iopub.execute_input":"2022-08-26T11:06:46.514849Z","iopub.status.idle":"2022-08-26T11:06:46.523954Z","shell.execute_reply.started":"2022-08-26T11:06:46.514798Z","shell.execute_reply":"2022-08-26T11:06:46.522822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def isPalindrome(s):\n  rev = ''.join(reversed(s))\n\n  if (s == rev) :\n    return True \n  else:\n    return False\n\ns = \"asdfasdf\"\na =isPalindrome(s) \n\nif a :\n  print(\"yes\")\nelse :\n  print('no')  ","metadata":{"id":"H5ybMxF-S4EF","outputId":"486e8e0a-00a2-47d7-acf8-d70481769e94","execution":{"iopub.status.busy":"2022-08-26T11:06:46.525435Z","iopub.execute_input":"2022-08-26T11:06:46.526585Z","iopub.status.idle":"2022-08-26T11:06:46.540685Z","shell.execute_reply.started":"2022-08-26T11:06:46.526538Z","shell.execute_reply":"2022-08-26T11:06:46.539649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Method using one extra variable: In this method, the user takes a character of string one by one and store it in an empty variable. After storing all the characters user will compare both the string and check whether it is palindrome or not. ","metadata":{"id":"OKBZ01garIOF"}},{"cell_type":"code","source":"# Python program to check\n# if a string is palindrome\n# or not\n \nx = \"malayalam\"\n \nw = \"\"\nfor i in x:\n    w = i + w\n \nif (x == w):\n    print(\"Yes\")\nelse:\n    print(\"No\")","metadata":{"id":"Ee-FOYQ2lNAC","outputId":"de68ed67-a192-420e-9ef8-374056932e93","execution":{"iopub.status.busy":"2022-08-26T11:06:46.542253Z","iopub.execute_input":"2022-08-26T11:06:46.542856Z","iopub.status.idle":"2022-08-26T11:06:46.555057Z","shell.execute_reply.started":"2022-08-26T11:06:46.542817Z","shell.execute_reply":"2022-08-26T11:06:46.553646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n### Method using flag: In this method, the user compares each character from starting and ending in a for loop and if the character does not match then it will change the status of the flag. Then it will check the status of the flag and accordingly and print whether it is a palindrome or not. ","metadata":{"id":"sMncSmzltcKr"}},{"cell_type":"markdown","source":"### Method using recursion: \n\nThis method compares the first and the last element of the string and gives the rest of the substring to a recursive call to itself. ","metadata":{"id":"YvRb8eN8H2PH"}},{"cell_type":"code","source":"# Recursive function to check if a\n# string is palindrome\ndef isPalindrome(s):\n \n    # to change it the string is similar case\n    s = s.lower()\n    # length of s\n    l = len(s)\n \n    # if length is less than 2\n    if l < 2:\n        return True\n \n    # If s[0] and s[l-1] are equal\n    elif s[0] == s[l - 1]:\n \n        # Call is palindrome form substring(1,l-1)\n        return isPalindrome(s[1: l - 1])\n \n    else:\n        return False\n \n# Driver Code\ns = \"MalaYaLam\"\nans = isPalindrome(s)\n \nif ans:\n    print(\"Yes\")\n \nelse:\n    print(\"No\")","metadata":{"id":"JFhXSdlRtwLZ","outputId":"eb4eca99-f4c5-42cc-d3f3-3b4a6a2f5f2f","execution":{"iopub.status.busy":"2022-08-26T11:06:46.568786Z","iopub.execute_input":"2022-08-26T11:06:46.569660Z","iopub.status.idle":"2022-08-26T11:06:46.581685Z","shell.execute_reply.started":"2022-08-26T11:06:46.569610Z","shell.execute_reply":"2022-08-26T11:06:46.580213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q2.Remove all duplicates from a given string in Python**","metadata":{"id":"7ENwHl8hIhKB"}},{"cell_type":"code","source":"from collections import OrderedDict\n \n# Function to remove all duplicates from string\n# and order does not matter\ndef removeDupWithoutOrder(str):\n \n    # set() --> A Set is an unordered collection\n    #         data type that is iterable, mutable,\n    #         and has no duplicate elements.\n    # \"\".join() --> It joins two adjacent elements in\n    #             iterable with any symbol defined in\n    #             \"\" ( double quotes ) and returns a\n    #             single string\n    return \"\".join(set(str))\n \n# Function to remove all duplicates from string\n# and keep the order of characters same\ndef removeDupWithOrder(str):\n    return \"\".join(OrderedDict.fromkeys(str))\n \n# Driver program\nif __name__ == \"__main__\":\n    str = \"python is easy language\"\n    print (\"Without Order = \",removeDupWithoutOrder(str))\n    print (\"With Order = \",removeDupWithOrder(str))","metadata":{"id":"pYaYvEFjIGbX","outputId":"dd0ba72c-00ee-4e53-ad0b-84f6d9d963f5","execution":{"iopub.status.busy":"2022-08-26T11:06:46.586430Z","iopub.execute_input":"2022-08-26T11:06:46.588321Z","iopub.status.idle":"2022-08-26T11:06:46.596375Z","shell.execute_reply.started":"2022-08-26T11:06:46.588092Z","shell.execute_reply":"2022-08-26T11:06:46.595347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Method 2\n\ndef removeDuplicate(str):\n    s=set(str)\n    s=\"\".join(s)\n    print(\"Without Order:\",s)\n    t=\"\"\n    for i in str:\n        if(i in t):\n            pass\n        else:\n            t=t+i\n    print(\"With Order:\",t)\n     \nstr=\"Python is easy language\"\nremoveDuplicate(str)","metadata":{"id":"pM7KSOTFJDBR","outputId":"e524c89f-a299-4d52-fe21-a24a9db87542","execution":{"iopub.status.busy":"2022-08-26T11:06:46.598076Z","iopub.execute_input":"2022-08-26T11:06:46.598851Z","iopub.status.idle":"2022-08-26T11:06:46.616654Z","shell.execute_reply.started":"2022-08-26T11:06:46.598813Z","shell.execute_reply":"2022-08-26T11:06:46.615151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### What do OrderedDict and fromkeys() do ?\n\nAn OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.","metadata":{"id":"zrMvbzGjKTzO"}},{"cell_type":"code","source":"from collections import OrderedDict\n \nordinary_dictionary = {}\nordinary_dictionary['a'] = 1\nordinary_dictionary['b'] = 2\nordinary_dictionary['c'] = 3\nordinary_dictionary['d'] = 4\nordinary_dictionary['e'] = 5\n \n# Output = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}\nprint (ordinary_dictionary)    \n \nordered_dictionary = OrderedDict()\nordered_dictionary['a'] = 1\nordered_dictionary['b'] = 2\nordered_dictionary['c'] = 3\nordered_dictionary['d'] = 4\nordered_dictionary['e'] = 5\n \n# Output = {'a':1,'b':2,'c':3,'d':4,'e':5}\nprint (ordered_dictionary) ","metadata":{"id":"p1-asy09JuEZ","outputId":"87ed0da3-ffd7-47bb-a69c-61e111e8b3d4","execution":{"iopub.status.busy":"2022-08-26T11:06:46.618472Z","iopub.execute_input":"2022-08-26T11:06:46.619260Z","iopub.status.idle":"2022-08-26T11:06:46.630938Z","shell.execute_reply.started":"2022-08-26T11:06:46.619218Z","shell.execute_reply":"2022-08-26T11:06:46.629845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q3.Python Program for Bubble Sort**","metadata":{"id":"qYLBMdDCTAKT"}},{"cell_type":"markdown","source":"## Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.","metadata":{"id":"laoP6ZXuUQzH"}},{"cell_type":"code","source":"# Python program for implementation of Bubble Sort\n \ndef bubbleSort(arr):\n    n = len(arr)\n    # optimize code, so if the array is already sorted, it doesn't need\n    # to go through the entire process\n    swapped = False\n    # Traverse through all array elements\n    for i in range(n-1):\n        # range(n) also work but outer loop will\n        # repeat one time more than needed.\n        # Last i elements are already in place\n        for j in range(0, n-i-1):\n \n            # traverse the array from 0 to n-i-1\n            # Swap if the element found is greater\n            # than the next element\n            if arr[j] > arr[j + 1]:\n                swapped = True\n                arr[j], arr[j + 1] = arr[j + 1], arr[j]\n         \n        if not swapped:\n            # if we haven't needed to make a single swap, we\n            # can just exit the main loop.\n            return\n \n \n# Driver code to test above\narr = [64, 34, 25, 12, 22, 11, 90]\n \nbubbleSort(arr)\n \nprint(\"Sorted array is:\")\nfor i in range(len(arr)):\n    print(\"% d\" % arr[i], end=\" \")","metadata":{"id":"KoQVuxXMK1cd","outputId":"597c546c-c0a5-4369-9445-ed5efa579332","execution":{"iopub.status.busy":"2022-08-26T11:07:09.087348Z","iopub.execute_input":"2022-08-26T11:07:09.088053Z","iopub.status.idle":"2022-08-26T11:07:09.097977Z","shell.execute_reply.started":"2022-08-26T11:07:09.088014Z","shell.execute_reply":"2022-08-26T11:07:09.096215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def bubbleSort(arr):\n  n = len(arr)\n  swapped = False\n  for i in range(0,n-1):\n    for j in range(0,n-i-1):\n      if arr[j]>arr[j+1]:\n        swapped = True\n        arr[j],arr[j+1]=arr[j+1],arr[j]\n    if not swapped :\n      return\narr = [10,58,62,12,45,41,78,32,25]  \nbubbleSort(arr)\nprint(arr)               ","metadata":{"id":"baOM_80hUodB","outputId":"d59fc031-e817-47a4-cee8-664808dc6b2d","execution":{"iopub.status.busy":"2022-08-26T11:07:09.597992Z","iopub.execute_input":"2022-08-26T11:07:09.598426Z","iopub.status.idle":"2022-08-26T11:07:09.608102Z","shell.execute_reply.started":"2022-08-26T11:07:09.598390Z","shell.execute_reply":"2022-08-26T11:07:09.606638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q4.Print an Inverted Star Pattern**","metadata":{"id":"rCnxM_BTMaqs"}},{"cell_type":"code","source":"\n# python 3 code to print inverted star\n# pattern \n  \n# n is the number of rows in which\n# star is going to be printed.\nn=11\n  \n# i is going to be enabled to\n# range between n-i t 0 with a\n# decrement of 1 with each iteration.\n# and in print function, for each iteration,\n# ” ” is multiplied with n-i and ‘*’ is\n# multiplied with i to create correct\n# space before of the stars.\nfor i in range (n, 0, -1):\n    print( * ' ' + i * '*')","metadata":{"id":"1vDb88KvXYK7","outputId":"82cd9f24-0057-4041-9fa1-b30cb9d417dc","execution":{"iopub.status.busy":"2022-08-26T11:07:10.418187Z","iopub.execute_input":"2022-08-26T11:07:10.418597Z","iopub.status.idle":"2022-08-26T11:07:10.426304Z","shell.execute_reply.started":"2022-08-26T11:07:10.418563Z","shell.execute_reply":"2022-08-26T11:07:10.424842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# python 3 code to print inverted star\n# pattern \n  \n# n is the number of rows in which\n# star is going to be printed.\nn=11\n  \n# i is going to be enabled to\n# range between n-i t 0 with a\n# decrement of 1 with each iteration.\n# and in print function, for each iteration,\n# ” ” is multiplied with n-i and ‘*’ is\n# multiplied with i to create correct\n# space before of the stars.\nfor i in range (n, 0, -1):\n    print((n-i) * ' ' + i * '*')","metadata":{"id":"8yWr5UKhQ4cr","outputId":"f22f448a-4f17-45fb-8a70-c8ec08c14c60","execution":{"iopub.status.busy":"2022-08-26T11:07:10.823884Z","iopub.execute_input":"2022-08-26T11:07:10.824289Z","iopub.status.idle":"2022-08-26T11:07:10.831973Z","shell.execute_reply.started":"2022-08-26T11:07:10.824248Z","shell.execute_reply":"2022-08-26T11:07:10.830472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q.5 Remove duplicate words from Sentence using Regular Expression**\n\n## **regex** = \"\\\\b(\\\\w+)(?:\\\\W+\\\\1\\\\b)+\";\n\n1. The details of the above regular expression can be understood as: \n“\\\\b”: A word boundary. Boundaries are needed for special cases. For example, in “My thesis is great”, “is” wont be matched twice.\n“\\\\w+” A word character: [a-zA-Z_0-9] \n \n* “\\\\W+”: A non-word character: [^\\w] \n \n* “\\\\1”: Matches whatever was matched in the 1st group of parentheses, which in this case is the (\\w+) \n \n* “+”: Match whatever it’s placed after 1 or more times \n \n2. Match the sentence with the Regex. In Java, this can be done using Pattern.matcher().\n \n3. return the modified sentence.","metadata":{"id":"cSAnjq_vRrlj"}},{"cell_type":"code","source":"\n# Python program to remove duplicate words\n# using Regular Expression or ReGex.\nimport re\n \n \n# Function to validate the sentence\n# and remove the duplicate words\ndef removeDuplicateWords(input):\n \n    # Regex to matching repeated words\n    regex = r'\\b(\\w+)(?:\\W+\\1\\b)+'\n \n    return re.sub(regex, r'\\1', input, flags=re.IGNORECASE)\n \n \n# Driver Code\n \n# Test Case: 1\nstr1 = \"Good bye bye world world\"\nprint(removeDuplicateWords(str1))\n \n# Test Case: 2\nstr2 = \"Ram went went to to his home\"\nprint(removeDuplicateWords(str2))\n \n# Test Case: 3\nstr3 = \"Hello hello world world\"\nprint(removeDuplicateWords(str3))","metadata":{"id":"sPCx96tJRGfX","outputId":"054c85ea-ba9a-4ce8-cc98-f5cbecdc5943","execution":{"iopub.status.busy":"2022-08-26T11:07:12.057331Z","iopub.execute_input":"2022-08-26T11:07:12.057730Z","iopub.status.idle":"2022-08-26T11:07:12.066996Z","shell.execute_reply.started":"2022-08-26T11:07:12.057697Z","shell.execute_reply":"2022-08-26T11:07:12.065501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q6.Python program to print all Prime numbers in an Interval**\n\nDefinition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.\n\nThe idea to solve this problem is to iterate the val from start to end using a for loop and for every number, if it is greater than 1, check if it divides n. If we find any other number which divides, print that value.","metadata":{"id":"xo4H2VmWhCuL"}},{"cell_type":"code","source":"\n# Python program to print all\n# prime number in an interval\n \ndef prime(x, y):\n    prime_list = []\n    for i in range(x, y):\n        if i == 0 or i == 1:\n            continue\n        else:\n            for j in range(2, int(i/2)+1):\n                if i % j == 0:\n                    break\n            else:\n                prime_list.append(i)\n    return prime_list\n \n# Driver program\nstarting_range = 2\nending_range = 7\nlst = prime(starting_range, ending_range)\nif len(lst) == 0:\n    print(\"There are no prime numbers in this range\")\nelse:\n    print(\"The prime numbers in this range are: \", lst)","metadata":{"id":"ueZSSsl4fG1K","outputId":"d97637a7-4d16-40c8-b24f-1c52e8466211","execution":{"iopub.status.busy":"2022-08-26T11:07:12.875326Z","iopub.execute_input":"2022-08-26T11:07:12.875977Z","iopub.status.idle":"2022-08-26T11:07:12.883692Z","shell.execute_reply.started":"2022-08-26T11:07:12.875941Z","shell.execute_reply":"2022-08-26T11:07:12.882858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q7. Python Program for n-th Fibonacci number**\n\nIn mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation \n\n### **Fn = Fn-1 + Fn-2**\n\n### **With seed values**\n\n### **F0 = 0 and F1 = 1**","metadata":{"id":"8y56SzAdKxXU"}},{"cell_type":"code","source":"#Method 1 ( Use recursion ) :\n\n\n# Function for nth Fibonacci number\n \ndef Fibonacci(n):\n    if n<= 0:\n        print(\"Incorrect input\")\n    # First Fibonacci number is 0\n    elif n == 1:\n        return 0\n    # Second Fibonacci number is 1\n    elif n == 2:\n        return 1\n    else:\n        return Fibonacci(n-1)+Fibonacci(n-2)\n \n# Driver Program\n \nprint(Fibonacci(10))","metadata":{"id":"PtWru0xvhfeE","outputId":"1759067b-ec5f-469d-d934-3b24cac837f1","execution":{"iopub.status.busy":"2022-08-26T11:07:13.591912Z","iopub.execute_input":"2022-08-26T11:07:13.592327Z","iopub.status.idle":"2022-08-26T11:07:13.600732Z","shell.execute_reply.started":"2022-08-26T11:07:13.592293Z","shell.execute_reply":"2022-08-26T11:07:13.599066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def fib(n):\n  if n<0 :\n    print('Incorrect Input')\n  elif n ==1 :\n    return 0\n  elif n==2 :\n    return 1\n  else:\n    return Fibonacci(n-1)+Fibonacci(n-2)\n","metadata":{"id":"1eycowFaLXYM","execution":{"iopub.status.busy":"2022-08-26T11:07:14.308844Z","iopub.execute_input":"2022-08-26T11:07:14.309962Z","iopub.status.idle":"2022-08-26T11:07:14.315336Z","shell.execute_reply.started":"2022-08-26T11:07:14.309915Z","shell.execute_reply":"2022-08-26T11:07:14.314207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(fib(10))","metadata":{"id":"3n8WYyltL38l","outputId":"8d3fe07d-8da3-4302-a024-97b366b07a10","execution":{"iopub.status.busy":"2022-08-26T11:07:14.820707Z","iopub.execute_input":"2022-08-26T11:07:14.821155Z","iopub.status.idle":"2022-08-26T11:07:14.826540Z","shell.execute_reply.started":"2022-08-26T11:07:14.821120Z","shell.execute_reply":"2022-08-26T11:07:14.825652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Method 2 ( Use Dynamic Programming ) : \n\n\n# Function for nth fibonacci number - Dynamic Programming\n# Taking 1st two fibonacci numbers as 0 and 1\n \nFibArray = [0, 1]\n \ndef fibonacci(n):\n    if n<0:\n        print(\"Incorrect input\")\n    elif n<= len(FibArray):\n        return FibArray[n-1]\n    else:\n        temp_fib = fibonacci(n-1)+fibonacci(n-2)\n        FibArray.append(temp_fib)\n        return temp_fib\n \n# Driver Program\n \nprint(fibonacci(9))","metadata":{"id":"wPNP9MwuMlRN","outputId":"c49a945f-9942-4962-d810-255b8005323f","execution":{"iopub.status.busy":"2022-08-26T11:07:15.239180Z","iopub.execute_input":"2022-08-26T11:07:15.240400Z","iopub.status.idle":"2022-08-26T11:07:15.249321Z","shell.execute_reply.started":"2022-08-26T11:07:15.240356Z","shell.execute_reply":"2022-08-26T11:07:15.248040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Method 3 ( Use Dynamic Programming with Space Optimization) : \n\n\n# Function for nth fibonacci number - Space Optimisation\n# Taking 1st two fibonacci numbers as 0 and 1\n \ndef fibonacci(n):\n    a = 0\n    b = 1\n    if n < 0:\n        print(\"Incorrect input\")\n    elif n == 0:\n        return a\n    elif n == 1:\n        return b\n    else:\n        for i in range(2, n):\n            c = a + b\n            a = b\n            b = c\n        return b\n \n# Driver Program\n \nprint(fibonacci(9))","metadata":{"id":"AmG_iPPFPA6C","outputId":"8f8ffce3-7206-4547-e9be-240a55992c29","execution":{"iopub.status.busy":"2022-08-26T11:07:15.742397Z","iopub.execute_input":"2022-08-26T11:07:15.742848Z","iopub.status.idle":"2022-08-26T11:07:15.751137Z","shell.execute_reply.started":"2022-08-26T11:07:15.742807Z","shell.execute_reply":"2022-08-26T11:07:15.750112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Method 4 ( Using Arrays ) : \n\n\n# creating an array in the function to find the nth number in fibonacci series. [0, 1, 1, ...]\n \ndef fibonacci (n):\n   if n<= 0:\n     return \"Incorrect Output\"\n   data = [0, 1]\n   if n == 1:\n     return 1\n   if n==2:\n     return 1  \n   if n > 2:\n        for i in range (2, n):\n            data.append(data[i-1] + data[i-2])\n        return data[n-1]\n \n# Driver Program\n \nprint(fibonacci(9))","metadata":{"id":"jV0MyJevSuMS","outputId":"d5ee00b9-2f72-40d1-d6c3-a0c358ce19e4","execution":{"iopub.status.busy":"2022-08-26T11:07:16.176103Z","iopub.execute_input":"2022-08-26T11:07:16.176858Z","iopub.status.idle":"2022-08-26T11:07:16.186092Z","shell.execute_reply.started":"2022-08-26T11:07:16.176806Z","shell.execute_reply":"2022-08-26T11:07:16.184720Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(fibonacci(2))","metadata":{"id":"n827OinYTEq3","outputId":"16d13893-199d-4033-8fc8-36a339afd079","execution":{"iopub.status.busy":"2022-08-26T11:07:16.660434Z","iopub.execute_input":"2022-08-26T11:07:16.660866Z","iopub.status.idle":"2022-08-26T11:07:16.666657Z","shell.execute_reply.started":"2022-08-26T11:07:16.660830Z","shell.execute_reply":"2022-08-26T11:07:16.665479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q8. Python Program for cube sum of first n natural numbers**\n\nPrint the sum of series 13 + 23 + 33 + 43 + …….+ n3 till n-th term. Examples:\n\n\nInput : n = 5\n\nOutput : 225\n\n13 + 23 + 33 + 43 + 53 = 225\n\nInput : n = 7\n\nOutput : 784\n13 + 23 + 33 + 43 + 53 + \n63 + 73 = 784","metadata":{"id":"xpuONcq7U_7K"}},{"cell_type":"code","source":"# Simple Python program to find sum of series\n# with cubes of first n natural numbers\n \n# Returns the sum of series\ndef sumOfSeries(n):\n    x = 0\n    for i in range(1, n+1):\n        x +=i*i*i\n         \n    return x\n \n  \n# Driver Function\nn = 5\nprint(sumOfSeries(n))","metadata":{"id":"SO-4y-AzWa-n","outputId":"05112e4b-e05d-4210-a023-efa4733ecd0e","execution":{"iopub.status.busy":"2022-08-26T11:07:17.483448Z","iopub.execute_input":"2022-08-26T11:07:17.484111Z","iopub.status.idle":"2022-08-26T11:07:17.492786Z","shell.execute_reply.started":"2022-08-26T11:07:17.484064Z","shell.execute_reply":"2022-08-26T11:07:17.491632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Method: Finding cube sum of first n natural numbers using built-in function pow(). \n#The pow() function finds the cube of a number by giving the values of i and number. ex: pow(i,3). \n\n\n# Python code\n# to print cube sum of first n natural numbers\n# using inbuilt function pow()\n \nn=5\ns=0\n# iterating loop up to given number n\nfor i in range(1,n+1):\n    # adding cube sum using pow() function\n    s=s+pow(i,3)\nprint(s)   \n ","metadata":{"id":"_tDEUaLkXOnD","outputId":"4d9aa822-6e5c-44fc-c6f0-b3003939fa27","execution":{"iopub.status.busy":"2022-08-26T11:07:17.995024Z","iopub.execute_input":"2022-08-26T11:07:17.995646Z","iopub.status.idle":"2022-08-26T11:07:18.003489Z","shell.execute_reply.started":"2022-08-26T11:07:17.995602Z","shell.execute_reply":"2022-08-26T11:07:18.002303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q9. Python Program to check if given array is Monotonic**\n\nGiven an array A containing n integers. The task is to check whether the array is Monotonic or not. An array is monotonic if it is either monotone increasing or monotone decreasing.\n\nAn array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].\n\nReturn “True” if the given array A is monotonic else return “False” ","metadata":{"id":"8XPb8wWaaKio"}},{"cell_type":"markdown","source":"Approach:\n\nAn array is monotonic if and only if it is monotone increasing, or monotone decreasing. Since p <= q and q <= r implies p <= r. So we only need to check adjacent elements to determine if the array is monotone increasing (or decreasing), respectively. We can check each of these properties in one pass.\n\nTo check whether an array A is monotone increasing, we’ll check A[i] <= A[i+1] for all i indexing from 0 to len(A)-2. Similarly we can check for monotone decreasing where A[i] >= A[i+1] for all i indexing from 0 to len(A)-2.\n\nNote: Array with single element can be considered to be both monotonic increasing or decreasing, hence returns “True“","metadata":{"id":"2nExniBzbavC"}},{"cell_type":"code","source":"# Check if given array is Monotonic\ndef isMonotonic(A):\n  \n    return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or\n            all(A[i] >= A[i + 1] for i in range(len(A) - 1)))\n  \n# Driver program\nA = [6, 5, 4, 4]\n  \n# Print required result\nprint(isMonotonic(A))","metadata":{"id":"1Co1CxKzZlE4","outputId":"be6344df-6270-4b13-e2e5-e7f4b273d062","execution":{"iopub.status.busy":"2022-08-26T11:07:19.251492Z","iopub.execute_input":"2022-08-26T11:07:19.252234Z","iopub.status.idle":"2022-08-26T11:07:19.259042Z","shell.execute_reply.started":"2022-08-26T11:07:19.252193Z","shell.execute_reply":"2022-08-26T11:07:19.257969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"b = [10,11,12,15,14,12]\n\nprint(isMonotonic(b))","metadata":{"id":"hqQkA-ztbvAv","outputId":"5cd8b63f-3b5b-4fe6-e9b6-a686ed7c1c41","execution":{"iopub.status.busy":"2022-08-26T11:07:19.750856Z","iopub.execute_input":"2022-08-26T11:07:19.751496Z","iopub.status.idle":"2022-08-26T11:07:19.757338Z","shell.execute_reply.started":"2022-08-26T11:07:19.751458Z","shell.execute_reply":"2022-08-26T11:07:19.755964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Q10.Python program to find second largest number in a list**","metadata":{"id":"JY9tTkQAcDFk"}},{"cell_type":"code","source":"# Python program to find largest number\n# in a list\n \n# List of numbers\nlist1 = [10, 20, 20, 4, 45, 45, 45, 99, 99]\n \n# Removing duplicates from the list\nlist2 = list(set(list1))\n \n# Sorting the  list\nlist2.sort()\n \n# Printing the second last element\nprint(\"Second largest element is:\", list2[-2])","metadata":{"id":"aWTGlsbFb2_c","outputId":"d27f252e-d173-47ef-facc-463b05fab41b","execution":{"iopub.status.busy":"2022-08-26T11:07:20.642896Z","iopub.execute_input":"2022-08-26T11:07:20.643306Z","iopub.status.idle":"2022-08-26T11:07:20.650124Z","shell.execute_reply.started":"2022-08-26T11:07:20.643270Z","shell.execute_reply":"2022-08-26T11:07:20.648740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Python program to find second largest\n# number in a list\n \n# creating list of integer type\nlist1 = [10, 20, 4, 45, 99]\n \n'''\n# sort the list   \nlist1.sort()\n     \n# print second maximum element\nprint(\"Second largest element is:\", list1[-2])\n \n'''\n \n# print second maximum element using sorted() method\nprint(\"Second largest element is:\", sorted(list1)[-2])","metadata":{"id":"rzeCJ_pWdkTR","outputId":"dba250a8-1277-44e1-91cf-f6a6a829e482","execution":{"iopub.status.busy":"2022-08-26T11:07:21.086275Z","iopub.execute_input":"2022-08-26T11:07:21.086995Z","iopub.status.idle":"2022-08-26T11:07:21.094056Z","shell.execute_reply.started":"2022-08-26T11:07:21.086953Z","shell.execute_reply":"2022-08-26T11:07:21.092777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Thank You. Any suggestion welcome.**\n**Please upvote if you find this useful.**","metadata":{}}]}