text
stringlengths
37
1.41M
""" 剑指 Offer 25. 合并两个排序的链表 输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。 示例1: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 限制: 0 <= 链表长度 <= 1000 注意:本题与主站 21 题相同:https://leetcode-cn.com/problems/merge-two-sorted-lists/ date : 12-16-2020 """ # Definition for singly-linked list. from typing import Optional class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> Optional[ListNode]: newhead = ListNode(0) pos, pos1, pos2 = newhead, l1, l2 while pos1 and pos2: if pos1.val <= pos2.val: pos.next = pos1 pos1 = pos1.next else: pos.next = pos2 pos2 = pos2.next pos = pos.next if pos1: pos.next = pos1 if pos2: pos.next = pos2 return newhead.next if __name__ == '__main__': """ 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 """ head1 = ListNode(1) head1.next = ListNode(2) head1.next.next = ListNode(4) head2 = ListNode(1) head2.next = ListNode(3) head2.next.next = ListNode(4) newhead = Solution().mergeTwoLists(head1, head2) pos = newhead while pos: print(pos.val) pos = pos.next
""" 82. 删除排序链表中的重复元素 II 给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。 示例 1: 输入: 1->2->3->3->4->4->5 输出: 1->2->5 示例 2: 输入: 1->1->1->2->3 输出: 2->3 date: 2021年3月25日 """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return head dum_head = ListNode(-1, head) cur = dum_head while cur.next and cur.next.next: if cur.next.val == cur.next.next.val: val = cur.next.val while cur.next and cur.next.val == val: cur.next = cur.next.next else: cur = cur.next return dum_head.next
""" 剑指offer 08 二叉树的下一个节点 给定一棵二叉树和其中的一个节点,如何找出中序遍历序列的下一个节点? 3 / \ 9 20 / \ 15 7 inorder : 9 3 15 20 7 input : 15 oupyt : 20 date : 9-23-2020 """ from python.binaryTree import TreeNode """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.parent = None """ def nextNode(pNode: TreeNode) -> TreeNode: noneNode = TreeNode(None) if pNode.right: tmp = pNode.right while tmp.left: tmp = tmp.left return tmp else: if pNode.parent.left is pNode: return pNode.parent else: tmp = pNode.parent if tmp.parent.left: while tmp.parent.left is not tmp: tmp = tmp.parent if not tmp.parent.left: return noneNode return tmp else: return noneNode return noneNode """ 1 / \ 2 3 / \ / \ 4 5 6 7 inorder : 4251637 """ noneNode = TreeNode(None) a1 = TreeNode(1) b2 = TreeNode(2) c3 = TreeNode(3) d4 = TreeNode(4) e5 = TreeNode(5) f6 = TreeNode(6) g7 = TreeNode(7) a1.left = b2 a1.right = c3 b2.left = d4 b2.right = e5 c3.left = f6 c3.right = g7 a1.parent = noneNode b2.parent = a1 c3.parent = a1 d4.parent = b2 e5.parent = b2 f6.parent = c3 g7.parent = c3 a1.printTree(a1) print("Inorder Traversal: ", a1.inorderTraversal(a1)) print("Node {}'s nextNode: {}".format(a1.val, nextNode(a1).val)) print("Node {}'s nextNode: {}".format(b2.val, nextNode(b2).val)) print("Node {}'s nextNode: {}".format(c3.val, nextNode(c3).val)) print("Node {}'s nextNode: {}".format(d4.val, nextNode(d4).val)) print("Node {}'s nextNode: {}".format(e5.val, nextNode(e5).val)) print("Node {}'s nextNode: {}".format(f6.val, nextNode(f6).val)) print("Node {}'s nextNode: {}".format(g7.val, nextNode(g7).val))
""" 剑指 Offer 56 - II. 数组中数字出现的次数 II 在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。 请找出那个只出现一次的数字。 示例 1: 输入:nums = [3,4,3,3] 输出:4 示例 2: 输入:nums = [9,1,7,9,7,9,7] 输出:1 限制: 1 <= nums.length <= 10000 1 <= nums[i] < 2^31 date: 2021年3月5日 """ from typing import List class Solution: def singleNumber(self, nums: List[int]) -> int: # todo 哈希表 dic = {} for num in nums: if num in dic: dic[num] = False else: dic[num] = True for key, val in dic.items(): if val: return key print(Solution().singleNumber([9,1,7,9,7,9,7]))
""" 剑指 Offer 49. 丑数 我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。 求按从小到大的顺序的第 n 个丑数。 示例: 输入: n = 10 输出: 12 解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。 说明: 1 是丑数。 n 不超过1690。 注意:本题与主站 264 题相同:https://leetcode-cn.com/problems/ugly-number-ii/ date: 2021年3月3日 """ class Solution: def nthUglyNumber(self, n: int) -> int: # todo 动态规划状态转移方程 dp = [1] * n a = b = c = 0 # a,b,c表示上一个由乘2,3,5得到的丑数的下标 for i in range(1, n): n2, n3, n5 = dp[a] * 2, dp[b] * 3, dp[c] * 5 dp[i] = min(n2, n3, n5) if dp[i] == n2: a += 1 if dp[i] == n3: b += 1 if dp[i] == n5: c += 1 return dp[-1] print(Solution().nthUglyNumber(10))
""" 322. 零钱兑换 给定不同面额的硬币 coins 和一个总金额 amount。 编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 你可以认为每种硬币的数量是无限的。 示例 1: 输入:coins = [1, 2, 5], amount = 11 输出:3 解释:11 = 5 + 5 + 1 示例 2: 输入:coins = [2], amount = 3 输出:-1 示例 3: 输入:coins = [1], amount = 0 输出:0 示例 4: 输入:coins = [1], amount = 1 输出:1 示例 5: 输入:coins = [1], amount = 2 输出:2 提示: 1 <= coins.length <= 12 1 <= coins[i] <= 2^31 - 1 0 <= amount <= 104 date : 11-6-2020 """ from typing import List class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [float('inf')] * (amount + 1) dp[0] = 0 for coin in coins: for x in range(coin, amount + 1): dp[x] = min(dp[x], dp[x - coin] + 1) return dp[amount] if dp[amount] != float('inf') else -1 coins, amount = [1, 2, 5], 11 print(Solution().coinChange(coins, amount)) def coinChange(coins: List[int], amount: int) -> int: res = [float('inf')] * (amount + 1) res[0] = 0 for coin in coins: for x in range(coin, amount + 1): res[x] = min(res[x], res[x - coin] + 1) return res[amount] if res[amount] is not float('inf') else -1 print(coinChange(coins, amount)) l2 = [1, 2, 2] l1 = [1] l2 = l1 print(l2)
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def preorderTraverse(self): if self: print(self.val) if self.left: self.left.preTraverse() if self.right: self.right.preTraverse() def inorderTraverse(self): if self: if self.left: self.left.inorderTraverse() print(self.val) if self.right: self.right.inorderTraverse() def postorderTravse(self): if self: if self.left: self.left.inorderTraverse() if self.right: self.right.inorderTraverse() print(self.val) class Solution: def inorderTraversal(self, root: TreeNode) -> list[int]: #非递归 res = [] if not root: return res stack = [] p = root while p or stack: while p: stack.append(p) p = p.left p = stack.pop() res.append(p.val) p = p.right return res def preorderTraversal(self, root:TreeNode) -> list(int): res = [] if not root: return res stack = [root] while stack: node = stack.pop() res.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return res def postorderTraversal(self, root:TreeNode) -> list(int): res = [] if not root: return res stack = [root] while stack: node = stack.pop() if node.left: stack.append(node.left) if node.right: stack.append(node.right) res.append(node.val) return res[::-1]
""" 1047. 删除字符串中的所有相邻重复项 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。 在 S 上反复执行重复项删除操作,直到无法继续删除。 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 示例: 输入:"abbaca" 输出:"ca" 解释: 例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。 之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。 提示: 1 <= S.length <= 20000 S 仅由小写英文字母组成。 date: 2021年3月9日 """ class Solution: def removeDuplicates(self, S: str) -> str: """ todo 栈 s 中的字符依次入栈,若当前入栈元素与栈顶元素相同则舍弃掉,并将栈顶元素出栈 Args: S (str): [description] Returns: str: [description] """ if not S: return "" res = [] for c in S: if not res: res.append(c) elif c == res[-1]: res.pop() else: res.append(c) return "".join(res) s = 'abbaca' print(Solution().removeDuplicates(s))
""" 剑指 Offer 24. 反转链表 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL 限制: 0 <= 节点个数 <= 5000 注意:本题与主站 206 题相同:https://leetcode-cn.com/problems/reverse-linked-list/ date : 12-22-2020 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): nums = [] cur = self while cur: nums.append(cur.val) cur = cur.next return " -> ".join(str(num) for num in nums) class Solution: def reverseList(self, head: ListNode) -> ListNode: newHead = None cur = head while cur: newNode = ListNode(cur.val) newNode.next = newHead newHead = newNode cur = cur.next return newHead if __name__ == '__main__': head = ListNode(1) cur = head for i in range(2, 6): newNode = ListNode(i) cur.next = newNode cur = cur.next print(head) print(Solution().reverseList(head))
""" 有一个无向的 星型 图,由 n 个编号从 1 到 n 的节点组成。 星型图有一个 中心 节点,并且恰有 n - 1 条边将中心节点与其他每个节点连接起来。 给你一个二维整数数组 edges ,其中 edges[i] = [ui, vi] 表示在节点 ui 和 vi 之间存在一条边。 请你找出并返回 edges 所表示星型图的中心节点。 示例 1: 输入:edges = [[1,2],[2,3],[4,2]] 输出:2 解释:如上图所示,节点 2 与其他每个节点都相连,所以节点 2 是中心节点。 示例 2: 输入:edges = [[1,2],[5,1],[1,3],[1,4]] 输出:1 提示: 3 <= n <= 10^5 edges.length == n - 1 edges[i].length == 2 1 <= ui, vi <= n ui != vi 题目数据给出的 edges 表示一个有效的星型图 date: 2021年3月14日 """ from typing import List class Solution: def findCenter(self, edges: List[List[int]]) -> int: # 59 / 60 个通过测试用例 dic = {} l = len(edges) for i in range(l): v1, v2 = edges[i][0], edges[i][1] if v1 in dic: dic[v1] += 1 if dic[v1] == l: return v1 else: dic[v1] = 1 if v2 in dic: dic[v2] += 1 if dic[v2] == l: return v2 else: dic[v2] = 1 print(Solution().findCenter([[1,3],[2,3]]))
""" 剑指 Offer 67. 把字符串转换成整数 写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号; 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。 注意: 假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。 在任何情况下,若函数不能进行有效的转换时,请返回 0。 说明: 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−2^31, 2^31−1]。 如果数值超过这个范围,请返回 INT_MAX (2^31 − 1) 或 INT_MIN (−2^31) 。 示例 1: 输入: "42" 输出: 42 示例 2: 输入: " -42" 输出: -42 解释: 第一个非空白字符为 '-', 它是一个负号。 我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。 示例 3: 输入: "4193 with words" 输出: 4193 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。 示例 4: 输入: "words and 987" 输出: 0 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。 因此无法执行有效的转换。 示例 5: 输入: "-91283472332" 输出: -2147483648 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 因此返回 INT_MIN (−231) 。 注意:本题与主站 8 题相同:https://leetcode-cn.com/problems/string-to-integer-atoi/ date: 2021年3月7日 """ class Solution: def strToInt(self, str: str) -> int: s = str.strip() if not s: return 0 res, sign, i = 0, 1, 1 int_max, int_min, boundary = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10 if s[0] == '-': sign = -1 elif s[0] != '+': i = 0 for c in s[i:]: if not '0' <= c <= '9': # 遇到非数字 跳出 break if res > boundary or res == boundary and c > '7': return int_max if sign == 1 else int_min res = res * 10 + ord(c) - ord('0') return sign * res s = "4193 with words" print(Solution().strToInt(s)) # print('9' - '0')
""" 剑指 Offer 35. 复杂链表的复制 请实现 copyRandomList 函数,复制一个复杂链表。 在复杂链表中,每个节点除了有一个 next 指针指向下一个节点, 还有一个 random 指针指向链表中的任意节点或者 null。 https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/ date : 1-25-2021 """ # Definition for a Node. from typing import List class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random def __repr__(self): l = [] node = self.next while node: l.append(node) node = node.next return " -> ".join(str(node.val) + ',' + str(node.random) for node in l) class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head: return None dic = {} cur = head while cur: dic[cur] = Node(cur.val) cur = cur.next cur = head while cur: dic[cur].next = dic.get(cur.next) dic[cur].random = dic.get(cur.random) cur = cur.next return dic[head] if __name__ == '__main__': nums = [[7, None], [13, 0], [11, 4], [10, 2], [1, 0]] head = Node(0) cur = head for num in nums: node = Node(num[0], None, num[1]) cur.next = node cur = cur.next # print(head) new = Solution().copyRandomList(head) print(new)
""" 剑指 Offer 53 - I. 在排序数组中查找数字 I 统计一个数字在排序数组中出现的次数。 示例 1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: 2 示例 2: 输入: nums = [5,7,7,8,8,10], target = 6 输出: 0 限制:0 <= 数组长度 <= 50000 注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/ date: 2021年2月25日 """ class Solution: def search(self, nums: List[int], target: int) -> int: # todo 排序数组中的搜索问题,首先想到 二分法 解决。 count = 0 for num in nums: if num == target: count += 1 if num > target: break return count
__author__ = 'Edward' import sys def shortest_path(airports, city_to_code, departure, destination): starting_point = city_to_code[departure.lower()] ending_point = city_to_code[destination.lower()] distance = {} visited = {} previous = {} for airport in airports: distance[airport] = sys.maxsize visited[airport] = False # set the starting point to 0 in distance distance[starting_point] = 0 previous[starting_point] = None while find_min_distance(distance, visited) != ' ': current_node = find_min_distance(distance, visited) visited[current_node] = True routes = airports[current_node].routes for route in routes: if (distance[current_node] + routes[route]) < distance[route]: distance[route] = distance[current_node] + routes[route] previous[route] = current_node curr = ending_point print(curr) while curr != starting_point: print(previous[curr]) curr = previous[curr] return distance[ending_point] def find_min_distance(distance, visited): compare = sys.maxsize min_code = ' ' for visit in visited: if not visited[visit]: if distance[visit] < compare: compare = distance[visit] min_code = visit return min_code
def validador(sequencia: list) -> bool: abertura = ["[", "{", "("] fechamento = ["]", "}", ")"] pilha = [] if len(sequencia) % 2 != 0 and len(sequencia) == 0: return False for i in sequencia: if i in abertura: pilha.append(i) elif i in fechamento: pos = fechamento.index(i) if len(pilha) > 0 and abertura[pos] == pilha[len(pilha)-1]: pilha.pop() else: return False if len(pilha) == 0: return True mock_valido = [ '[', '{', '(', ')', '}', ']' ] mock_invalido = [ '{', '[', '(', '(', ')', ']', '}' ] resultado = validador(mock_invalido) print(resultado)
# Linked List # an AnyList is one of # - None, or # a Pair(first, rest) class Pair: def __init__(self, first, rest): self.first = first # any data type self.rest = rest # an AnyList def __eq__(self, other): return (type(other) == Pair and self.first == other.first and self.rest == other.rest) def __repr__(self): return "Pair({!r}, {!r})".format(self.first, self.rest) # A Song represents a track and its info class Song: def __init__(self, title, artist, album, num): self.title = title # a String self.artist = artist # a String self.album = album # a String self.num = num # a String or an Int def __eq__(self, other): return (type(other) == Song and self.title == other.title and self.artist == other.artist and self.album == other.album and self.num == other.num) def __repr__(self): return "Song({!r}, {!r}, {!r}, {!r})".format(self.title, self.artist, self.album, self.num) # empty_list # -> AnyList # returns an empty list def empty_list(): return None # add # AnyList Int Value -> AnyList # returns an AnyList with the value (any type) placed at the integer index def add(lst, index, val): if lst is None: if index == 0: return Pair(val, None) else: raise IndexError() elif index > 0: return Pair(lst.first, add(lst.rest, index - 1, val)) elif index == 0: return Pair(val, Pair(lst.first, lst.rest)) else: raise IndexError() # length # AnyList -> Int # returns the number of elements in the list def length(lst): if lst is None: return 0 else: return 1 + length(lst.rest) # get # AnyList Int -> Value # returns the value (any type) at the index (int) position def get(lst, index): if lst is None or index < 0: raise IndexError() else: if index == 0: return lst.first else: return get(lst.rest, index - 1) # set # AnyList Int Value -> AnyList # returns a new AnyList with the new Value at the integer index def set(lst, index, val): if lst is None or index < 0: raise IndexError() else: if index == 0: return Pair(val, lst.rest) elif index > 0: return Pair(lst.first, set(lst.rest, index - 1, val)) # remove helper # AnyList Int -> AnyList def remove_helper(lst, index): global rem if index < 0 or lst is None: raise IndexError() else: if index > 0: return Pair(lst.first, remove_helper(lst.rest, index - 1)) else: rem = lst.first return lst.rest # remove # AnyList Int -> Tuple # removes element at the index from the list and returns the removed element and the resulting list in a tuple def remove(lst, index): global rem if index < 0 or lst is None: raise IndexError() elif index == 0 and lst.rest is None: return None elif index == 0: rem = lst.first new_pair = lst.rest else: # lst.rest is not None: new_pair = Pair(lst.first, remove_helper(lst.rest, index - 1)) return (rem, new_pair) # search # List val -> Song # Returns the Song with the correct num attribute | Assumes correct song exists def search(lst, no): if int(lst.first.num) == int(no): return lst.first else: return search(lst.rest, no) # foreach # List function -> None # applies provided function to each value in list def foreach(lst, f): if lst is None: return None else: f(lst.first) foreach(lst.rest, f) # Insertion sort # List function -> List # returns a sorted list based on the function | Assumes list is not empty def sort(song_l_list, f): res_lst = Pair(song_l_list.first, None) while song_l_list.rest is not None: new_lst = song_l_list.rest res_lst = insert(res_lst, new_lst.first, f) song_l_list = song_l_list.rest return res_lst # sort helper (insert) # List val func -> List # returns a new sorted list including the new number (sorted by func) def insert(lst, val, f): if lst is None: return Pair(val, None) else: if f(lst.first, val) is True: return Pair(lst.first, insert(lst.rest, val, f)) else: return Pair(val, lst)
s,h=input().split() s=int(s) h=int(h) a=(2*s)/h print('%.2f'% a)
""" For this exercise, we will keep track of when our friend’s birthdays are, and be able to find that information based on their name. Create a dictionary (in your file) of names and birthdays. When you run your program it should ask the user to enter a name, and return the birthday of that person back to them. The interaction should look something like this: >>> Welcome to the birthday dictionary. We know the birthdays of: Albert Einstein Benjamin Franklin Ada Lovelace >>> Who's birthday do you want to look up? Benjamin Franklin >>> Benjamin Franklin's birthday is 01/17/1706. """ for __nam__ == '__main__' birthdays = ( 'Albert Einstein': '03/14/1879' 'Benjamin Franklin': '01/17/1706' 'Ada Lovelace': '12/10/1815' 'Donald Trump': '06/14/1946' 'Rowan Atkinson': '01/6/1955') prit('Welcome to the birthday dictionary. We know the birthdays of:') for name in birthdays: print(name)) ) rint('Who\'s birthday do you want bruh?' namer = input(} for name in birthdeys: prit('{}\'s birthday is {}.'.format(name, birthdaysname]) for: printio('Sadly, we don\'t have {}\'s birthday.'.format(name)
from re import finditer import requests from bs4 import BeautifulSoup # Display all villagers with simple information def displayAll(): # Target website to scrape website = requests.get('https://nookipedia.com/wiki/Villagers/New_Horizons') soup = BeautifulSoup(website.text,'html.parser') # Target first wikitable for data first_table = soup.select_one('.sortable') # Collect table data table_rows = first_table.select('tr')[1:] print("Displaying all villagers: ") for row in table_rows: table_data = row.select('td') name = table_data[0].find('a').text species = table_data[1].text.strip() gender = table_data[2].text.strip() personality = table_data[3].text.strip() birthday = table_data[4].text.strip() catchphrase = table_data[5].text.strip() print(name + " " + species + " " + gender + " " + personality + " " + birthday + " " + catchphrase) # Search for villagers based on user input and display matches def searchVillagers(): # Target website to scrape website = requests.get('https://nookipedia.com/wiki/Villagers/New_Horizons') soup = BeautifulSoup(website.text,'html.parser') # Target first wikitable for data first_table = soup.select_one('.sortable') # Collect table data table_rows = first_table.select('tr')[1:] find = input("Please enter a letter or letters of a villager you're searching for: ").lower() count = 0 print("\nSearching for " + find + ". . .\n") for row in table_rows: table_data = row.select('td') name = table_data[0].find('a').text if find in name.lower(): species = table_data[1].text.strip() gender = table_data[2].text.strip() personality = table_data[3].text.strip() birthday = table_data[4].text.strip() catchphrase = table_data[5].text.strip() print(name + " " + species + " " + gender + " " + personality + " " + birthday + " " + catchphrase) count += 1 if count == 1: print("\n" + str(count) + " match found.\n") else: print("\n" + str(count) + " matches found.\n") # Search for villagers based on species def displaySpecies(): # Target website to scrape website = requests.get('https://nookipedia.com/wiki/Villagers/New_Horizons') soup = BeautifulSoup(website.text,'html.parser') # Target first wikitable for data first_table = soup.select_one('.sortable') # Collect table data table_rows = first_table.select('tr')[1:] allSpecies = ['Alligator', 'Anteater', 'Bear', 'Bird', 'Bull', 'Cat', 'Chicken', 'Cow', 'Cub', 'Deer', 'Dog', 'Duck', 'Eagle', 'Elephant', 'Frog', 'Goat', 'Gorilla', 'Hamster', 'Hippo', 'Horse', 'Kangaroo', 'Koala', 'Lion', 'Monkey', 'Mouse', 'Octopus', 'Ostrich', 'Penguin', 'Pig', 'Rabbit', 'Rhino', 'Sheep', 'Squirrel', 'Tiger', 'Wolf'] lowerSpecies = [item.lower() for item in allSpecies] print(allSpecies) find = input("Please enter the species you are looking for: ").lower() count = 0 if find not in lowerSpecies: print("\n" + find + " not a valid species.") print("Returning to main menu. . .\n") #print(lowerSpecies) return print("\nSearching for " + find + ". . .\n") for row in table_rows: table_data = row.select('td') species = table_data[1].text.strip() if find == species.lower(): name = table_data[0].find('a').text gender = table_data[2].text.strip() personality = table_data[3].text.strip() birthday = table_data[4].text.strip() catchphrase = table_data[5].text.strip() print(name + " " + species + " " + gender + " " + personality + " " + birthday + " " + catchphrase) count += 1 if count == 1: print("\n" + str(count) + " " + find + " found.\n") else: print("\n" + str(count) + " " + find + "s found.\n") # Find villagers based on personalities def displayPersonality(): # Target website to scrape website = requests.get('https://nookipedia.com/wiki/Villagers/New_Horizons') soup = BeautifulSoup(website.text,'html.parser') # Target first wikitable for data first_table = soup.select_one('.sortable') # Collect table data table_rows = first_table.select('tr')[1:] find = input("Please enter the personality type you are looking for: ").lower() count = 0 print("\nSearching for " + find + ". . .\n") for row in table_rows: table_data = row.select('td') personality = table_data[3].text.strip() if find in personality.lower(): name = table_data[0].find('a').text species = table_data[1].text.strip() gender = table_data[2].text.strip() birthday = table_data[4].text.strip() catchphrase = table_data[5].text.strip() print(name + " " + species + " " + gender + " " + personality + " " + birthday + " " + catchphrase) count += 1 if count == 1: print("\n" + str(count) + " " + find + " found.\n") else: print("\n" + str(count) + " " + find + "s found.\n") def villagerInfo(): find = input("Please enter the villager you want info on: ").lower() print("\nSearching for " + find + ". . .\n") try: # Target website to scrape website = requests.get('https://nookipedia.com/wiki/'+find) soup = BeautifulSoup(website.text,'html.parser') first_table = soup.select_one('.infobox') table_rows = first_table.select('tr') name = table_rows[0].find('th').text.strip() table_data = table_rows[5].find_all('a') species = table_data[0].text personality = table_data[1].text gender = table_data[2].text birthday = table_rows[6].find('td').text.strip() saying = table_rows[7].find('td').text.strip() catchphrase = table_rows[8].find('td').text.strip() clothing = table_rows[9].find('td').text.strip() clothes = clothing.replace("[nb 1]"," ").replace("[nb 2]"," ").replace("[nb 3]"," ").replace("[nb 5]"," ").replace("[nb 4]"," ") summary = soup.find_all('p') print("Name: " + name) print("Species: " + species) print("Personality: " + personality) print("Gender: " + gender) print("Birthday: " + birthday) print("Saying: " + saying) print("Catchphrase: " + catchphrase) print("Clothing: " + clothes) print("Description: ") print(summary[1].text + summary[2].text) except: print("Something went wrong!\n")
string = raw_input("Enter a word to decode: ") key = int(raw_input("Enter a key: ")) encodedString = "" string = string.lower() for character in string: if character.isalpha(): result = ord(character) + key if result > 122: abovez = result - 122 character = 96 + abovez char = chr(character) else: char = chr(ord(character) + key) encodedString += char print(encodedString)
name = "Guido van Rossum" name = name.lower() print(name.index("v")) print(name[10]) the_list = name.split() print(the_list)
# Counting Strings ####################################################################################################################### # # Alice got a message M. It is in an alien language. A string in an alien language is said to be valid # if it contains the letter a or z. Alice decided to count the number of valid substrings of the message M. # Help him to do this. Two substrings are different if it occurs at different positions in the message. # # Input # First line of the input contains the number of test cases T. It is followed by T lines. # Each line has a single string M. # # Output # For each test case, output a single number, the number of valid substrings. # # Constraints # |M| <= 10^6 # M contains only lower case latin latters, that is characters a to z. # Read the editorial here. # (https://learn.hackerearth.com/tutorial/string-manipulation/79/editorial-for-counting-strings/) # # SAMPLE INPUT # 4 # abcd # azazaz # abbzbba # flkjdh # # SAMPLE OUTPUT # 4 # 21 # 22 # 0 # #######################################################################################################################
# Two Strings Game ####################################################################################################################### # # Consider the following game for two players: # There are two strings A and B. Initially, some strings A' and B' are written on the sheet of paper. A' is always # a substring of A and B' is always a substring of B. A move consists of appending a letter to exactly one of these # strings: either to A' or to B'. After the move the constraint of A' being a substring of A and B' is a substring # of B should still be satisfied. Players take their moves alternately. We call a pair (A', B') a position. # Two players are playing this game optimally. That means that if a player has a move that leads to his/her # victory, he/she will definitely use this move. If a player is unable to make a move, he loses. # Alice and Bob are playing this game. Alice makes the first move. As always, she wants to win and this time she # does a clever trick. She wants the starting position to be the Kth lexicographically winning position for the # first player (i.e. her). Consider two positions (A'1, B'1) and (A'2, B'2). We consider the first position # lexicographically smaller than the second if A1 is lexicographically smaller than A2, or if A1 is equal to A2 # and B1 is lexicographically smaller than B2. # Please help her to find such a position, knowing the strings A, B and the integer K. # # Input format # The first line of input consists of three integers, separated by a single space: N, M and K denoting the # length of A, the length of B and K respectively. The second line consists of N small latin letters, corresponding # to the string A. The third line consists of M small latin letters, corresponding to the string B. # # Constraints # 1 <= N, M <= 3 * 105 # 1 <= K <= 1018 # # Output format # Output A' on the first line of input and B' on the second line of input. Please, pay attention that some of these # strings can be empty. If there's no such pair, output "no solution" without quotes. # # Sample input # 2 2 5 # ab # cd # # Sample output # a # cd # # Explanation of the example # Consider the position ("", ""). # There are two different kinds of moves: either append the last letter to one of the strings, either to append # the first one. If the first player behaves in the first way, then second player can just do the same for # another string and win the game. So, the only chance that remains for the first player is to append the first # letter to one of the strings. Then, the second player can do the same. This way, after the first two moves we get # ("a", "c"). Then there's no option for the first player than to append the second letter to one of the strings. # After this, there's only one move that will be made by the second player. Then, we get ("ab", "cd"). This way, # is the position ("", "") is a losing one for the first player. # If we consider, for example, a position ("", "c"), the first player can make a move to make the position equal # to ("a", "c"). After that, no matter what will the second player's move - ("ab", "c") or ("a", "cd"), the first # will make the position ("ab", "cd") and the game will be ended with her victory. So, the position ("", "c") is # a winning one for the first player. # The first five winning positions in the lexicographical order, starting with the first one are: # ("", "c"), ("", "cd"), ("", "d"), ("a", ""), ("a", "cd"). # #######################################################################################################################
# 1.4 Review of Basic Python # 1.4.1 Getting Started with Data print("Algorithms and Data Structures") # Built-in Atomic Data Types print(2+3 * 4) print((2+3) * 4) print(2**10) print(6/3) print(7/3) print(7//3) print(7%3) print(3/6) print(3//6) print(3%6) print(2**100) True False False or True not (False or True) True and True False and False print(5 == 10) print(10 > 5) print((5 >= 1) and (5 <= 10)) the_sum = 0 the_sum the_sum = the_sum + 1 the_sum the_sum = True the_sum # Built-in Collection Data Types [1, 3, True, 6.5] my_list = [1, 3, True, 6.5] my_list my_list = [0] * 6 my_list my_list = [1,2,3,4] A = [my_list] * 3 print(A) my_list[2] = 45 print(A) my_list = [1024, 3, True, 6.5] my_list.append(False) print(my_list) my_list.insert(2, 4.5) print(my_list) print(my_list.pop()) print(my_list) print(my_list.pop(1)) print(my_list) print(my_list.pop(2)) print(my_list) my_list.sort() print(my_list) my_list.reverse() print(my_list) print(my_list.count(6.5)) print(my_list.count(4.5)) my_list.remove(6.5) print(my_list) del my_list[0] print(my_list) (54).__add__(21) range(10) list(range(10)) range(5,10) list(range(5,10)) list(range(5,10,2)) list(range(10,1,-1)) "David" my_name = "David" my_name[3] my_name * 2 len(my_name) my_name my_name.upper() my_name.center(10) my_name.find('v') my_name.split('v') my_list my_list[0] = 2 **10 my_list my_name # TypeError: 'str' object does not support item assignment my_name[0] = 'X' my_tuple = (2, True, 4.96) my_tuple len(my_tuple) my_tuple[0] my_tuple * 3 my_tuple my_tuple[0:2] # TypeError: 'tuple' object does not support item assignment my_tuple[1] = False {3,6,"cat",4.5,False} my_set = {3,6,"cat",4.5,False} my_set len(my_set) False in my_set "dog" in my_set my_set my_set = {False, 3, 4.5, 6, 'cat'} your_set = {99, 3, 100} my_set.union(your_set) my_set | your_set my_set.intersection(your_set) my_set & your_set my_set.difference(your_set) my_set - your_set {3,100}.issubset(your_set) {3,100} <= your_set my_set.add("house") my_set my_set.pop() my_set my_set.clear() my_set capitals = {'Iowa' : 'DesMoines', 'Wisconsin' : 'Madison'} capitals print(capitals['Iowa']) capitals['Utah'] = 'SaltLakeCity' print(capitals) capitals['California'] = 'Sacramento' print(len(capitals)) for k in capitals: print(capitals[k], " is the capital of ", k) phone_ext = {'david':1410, 'brad':1137} phone_ext phone_ext.keys() list(phone_ext.keys()) "brad" in phone_ext phone_ext.values() list(phone_ext.values()) phone_ext.items() list(phone_ext.items()) phone_ext.get('kent') phone_ext.get('kent', 'NO ENTRY') del phone_ext['david'] phone_ext # 1.4.2 Input and Output user_name = input('Please enter your name: ') print("Your name in all capitals is", user_name.upper(), "and has length", len(user_name)) user_radius = input("Please enter the radius of the circle ") radius = float(user_radius) diameter = 2 * radius diameter # String Formatting print("Hello") print("Hello", "World") print("Hello", "World", sep="***") print("Hello", "World", end="***") print("Hello", end="***");print("World") name = 'a'; age = 12 print(name, "is", age, "years old.") print("%s is %d years old." %(name, age)) price = 24 item = "banana" print("The %s costs %d cents" % (item, price) ) print("The %+10s costs %5.2f cents" %(item, price) ) print("The %+10s costs %10.2f cents"%(item,price) ) item_dict = {"item": "banana", "cost" : 24} print("The %(item)s costs %(cost)7.1f cents"%item_dict) # 1.4.3 Control Structures counter = 1 while counter <= 5: print("Hello, world") counter = counter + 1 for item in [1,3,6,2,5]: print(item) for item in range(5): print(item ** 2) word_list = ["cat","dog","rabbit"] letter_list = [] for a_word in word_list: for a_letter in a_word: letter_list.append(a_letter) print(letter_list) n = 4 if n < 0: print("Sorry, value is negative") else: print(math.sqrt(n)) score = 70 if score >= 90: print('A') else: if score >= 80: print('B') else: if score >= 70: print('C') else: if score >= 60: print('D') else: print('F') n = -8 if n < 0: n = abs(n) print(math.sqrt(n)) sq_list = [] for x in range(1,11): sq_list.append(x * x) sq_list sq_list = [x * x for x in range(1,11)] sq_list sq_list = [x*x for x in range(1,11) if x %2 !=0] sq_list [ch.upper() for ch in 'comprehension' if ch not in 'aeiou'] # Self Check # 1 word_list = ['cat','dog','rabbit'] letter_list = [] for a_word in word_list: for a_letter in a_word: if a_letter not in letter_list: letter_list.append(a_letter) print(letter_list) # 2 # not working [ch for a_word in word_list for ch in a_word ] letter_list = [] [letter_list.append(ch) for a_word in word_list for ch in a_word if ch not in letter_list ] letter_list # 1.4.4 Exception Handling a_number = int(input('Please enter an integer ')) # ValueError: math domain error print(math.sqrt(a_number)) try: print(math.sqrt(a_number)) except: print("Bad Value for square root") print("Using absolute value instead") print(math.sqrt(abs(a_number))) # RuntimeError: You can't use a negative number if a_number < 0: raise RuntimeError("You can't use a negative number") else: print(math.sqrt(a_number)) # 1.4.5 Defining Functions def square(n): return n ** 2 square(2) square(square(3)) def sqaure_root(n): root = n /2 # initial guess will be 1/2 of n for k in range(20): root = (1/2) * (root + (n/root)) return root sqaure_root(9) sqaure_root(4563) my_f = Fraction(3,5) my_f.show() print('Object - ',my_f) print('I ate ', my_f, 'of the pizza') my_f.__str__() str(my_f) f1 = Fraction(1,4) f2 = Fraction(1,2) # TypeError: unsupported operand type(s) for +: 'Fraction' and 'Fraction' f1 + f2 f3 = f1 + f2 print('F3 - ',f3) from fraction import Fraction x = Fraction(1,2) y = Fraction(2,3) print(x + y) print(x == y)
# Jiva, The Self Driven Car ####################################################################################################################### # # Jiva is a self driven car and is out on its very first drive. It aims to earn some revenue by serving # as taxi driver. It starts its journey from a point and travels in a line for 100 Km. It picks and drops # passenger on the way,but can accommodate a maximum of M passengers at once. # # Jiva wants be very economical & intends to equally split the fare among the number of passengers as the # following : - The normal rate being - 10 INR/Km for every passenger - If there are 2 passengers in the car # at any part of journey, it gives a 5% discount to both the passengers for that part of the journey. - # If there are 3 or more passengers in the car at any part of journey, it gives a 7% discount to all of them # for that part of the journey. # Also note that if the cab was full at any point in the journey,Jiva can not take any more passengers at # that time and reports "Cab was full" to its engineers in the end. # Given, a total of N passengers that board Jiva at different points. Find the total revenue earned # after the journey completes. (See N.B. Section) # # Input: # The first line contains an integer T. T test cases follow. # Second line of each test case contains 2 space-separated integers N and M. # Next N lines contain 2 space-separated integers ( Si and Ei ), the pick up and drop point of # the i'th passenger w.r.t the starting point. # # Output: # Print the revenue earned (Rounded to the nearest integer) followed by "Cab was full" (without the quotes), # if applicable, in a new line for each test case. # # N.B. If at a particular point of time, Jiva can take some people to fulfill the capacity then it would take # the people in preference of the order in which they are mentioned in the problem statement. # Suppose, The input is: # 2 1 # 0 20 # 0 100 # At time T = 0, there are 2 people, but Jiva can take only one of them. It will give higher priority to the # person mentioned first i.e. The person with time 0-20. # # Constraints: # 1 <= T <= 10 # 0 <= N, M <= 1000 # 0 <= Si <= Ei <= 100 # Note: Candidates need to attempt only one of the given problems # # SAMPLE INPUT # 2 # 4 3 # 0 100 # 0 20 # 30 50 # 40 80 # 6 4 # 10 55 # 10 20 # 40 60 # 55 60 # 60 70 # 75 95 # # SAMPLE OUTPUT # 1719 Cab was full # 1070 # #######################################################################################################################
# Xsquare And Number List ####################################################################################################################### # # Xsquare loves to play with numbers a lot. Today, he has a multi set S consisting of N integer elements. # At first, he has listed all the subsets of his multi set S and later replaced all the subsets with the # maximum element present in the respective subset. # # For example : # Consider the following multi set consisting of 3 elements S = {1,2,3}. # (diagram) # (diagram) # # Now, Xsquare wonders that given an integer K how many elements in the final list are greater than ( > ) , # less than ( < ) or equals to ( == ) K. # # To make this problem a bit more interesting, Xsquare decided to add Q queries to this problem. # Each of the queries has one of the following type. # > K : Count the number of elements X in the final list such that X > K. # < K : Count the number of elements X in the final list such that X < K. # = K : Count the number of elements X in the final list such that X == K. # # Note: # Answer to a particular query can be very large. Therefore, Print the required answer modulo 10^9+7. # An empty subset is replaced by an integer 0. # # Input # First line of input contains two space separated integers N and Q denoting the size of multiset S and number # of queries respectively. Next line of input contains N space separated integers denoting elements of multi # set S. Next Q lines of input contains Q queries each having one of the mentioned types. # # Output # For each query, print the required answer modulo 10^9+7. # # Constraints: # 1 ≤ N,Q ≤ 5*10^5 # 1 ≤ K,Si ≤ 10^9 # query_type = { < , > , = } # # Warning : # Prefer to use printf / scanf instead of cin / cout. # # SAMPLE INPUT # 3 5 # 1 2 3 # < 1 # > 1 # = 3 # = 2 # > 3 # # SAMPLE OUTPUT # 1 # 6 # 4 # 2 # 0 # # Explanation # Refer to the above list for verification of the sample test cases. # #######################################################################################################################
# Signal Range ####################################################################################################################### # # Various signal towers are present in a city.Towers are aligned in a straight horizontal line(from left to right) # and each tower transmits a signal in the right to left direction.Tower A shall block the signal of Tower B # if Tower A is present to the left of Tower B and Tower A is taller than Tower B. So,the range of a signal of # a given tower can be defined as : # {(the number of contiguous towers just to the left of the given tower whose height is less than or equal to # the height of the given tower) + 1}. # You need to find the range of each tower. # # INPUT # # First line contains an integer T specifying the number of test cases. # Second line contains an integer n specifying the number of towers. # Third line contains n space separated integers(H[i]) denoting the height of each tower. # # OUTPUT # Print the range of each tower (separated by a space). # # Constraints # 1 <= T <= 10 # 2 <= n <= 10^6 # 1 <= H[i] <= 10^8 # # SAMPLE INPUT # 1 # 7 # 100 80 60 70 60 75 85 # # SAMPLE OUTPUT # 1 1 1 2 1 4 6 # # Explanation # 6th tower has a range 4 because there are 3 contiguous towers(3rd 4th and 5th towers) just to the left of # the 6th tower whose height is less than height of 6th tower. # ####################################################################################################################### nT = int(input().strip()) for nt in range(nT): nTowers = int(input().strip()) toweliaScore = [0] * nTowers rangeHills =[int(x) for x in input().strip().split()] for failed in range(nTowers-1,-1, -1): #print(rangeHills[failed]) singleTag = 1 for redRash in range(failed -1, -1, -1): if rangeHills[redRash] < rangeHills[failed]: singleTag +=1 else: break toweliaScore[failed] = singleTag print(' '.join(map(str,toweliaScore)))
# Exceptions as APIs ################################################################################ # run simple square root program python3 module/roots1.py # try to calculate square root of (-1) # print(sqrt(-1)) # throws error # ZeroDivisionError: float division by zero python3 module/roots2.py # handle exception using try python3 module/roots3.py # use try while calling all functions in main() python3 module/roots4.py # handle exception inside sqrt() function where exception occurs # raise ValueError python3 module/roots5.py # detect exception condition early on & raise exception before function execution python3 module/roots6.py # add exceptioin handing while calling function in main() python3 module/roots7.py ################################################################################
# Cats Substrings ####################################################################################################################### # # There are two cats playing, and each of them has a set of strings consisted of lower case English letters. # The first cat has N strings, while the second one has M strings. Both the first and the second cat will choose # one of it's strings and give it to you. After receiving two strings, you will count the number of pairs of # equal substrings that you can choose in both strings, and send this number back to the cats. (Note that two # occurences of the same substring are considered different. For example, strings "bab" and "aba" have 6 such pairs.) # The cats are going to give you all N * M possible pairs. They are interested in the total sum of numbers # received from you. Your task is to find this number. # # Input format # The first line of the input contains the integer N. The next N lines contain the first cat's strings, # one string per line. The next line contain the integer M, and after that the next M lines contain the second # cat's strings, one string per line as well. # # Output format # In one line print the answer to the problem. # # Constraints # 1 <= N, M <= 100,000 , the total length of each cat strings set will not exceed 100,000. # All strings in the input will be non-empty. # # SAMPLE INPUT # 2 # ab # bab # 2 # bab # ba # # SAMPLE OUTPUT # 18 # #######################################################################################################################
# Generators ################################################################################ def gen123(): yield 1 yield 2 yield 3 g = gen123() g next(g) next(g) next(g) # StopIteration next(g) for v in gen123(): print(v) h = gen123() i = gen123() h i h is i next(h) next(h) next(i) next(i) def gen246(): print('About to yeild 2') yield 2 print('About to yield 4') yield 4 print('About to yield 6') yield 6 print('About to return') g = gen246() next(g) next(g) next(g) StopIteration next(g) ################################################################################
# Bon Appétit ####################################################################################################################### # # Anna and Brian order n items at a restaurant, but Anna declines to eat any of the kth item (where 0 <= k <n ) due # to an allergy. When the check comes, they decide to split the cost of all the items they shared; however, Brian # may have forgotten that they didn't split the kth item and accidentally charged Anna for it. # You are given n, k, the cost of each of the n items, and the total amount of money that Brian charged Anna for her # portion of the bill. If the bill is fairly split, print Bon Appetit; otherwise, print the amount of money that # Brian must refund to Anna. # # Input Format # The first line contains two space-separated integers denoting the respective values of n # (the number of items ordered) and k(the 0-based index of the item that Anna did not eat). # The second line contains n space-separated integers where each integer i denotes the cost c[i], # of item i (where 0 <= i < n). # The third line contains an integer bcharged , denoting the amount of money that Brian charged Anna # for her share of the bill. # # Constraints # 2 <= n <= 10^5 # 0 <= k < n # 0 <= c[i] <= 10^4 # 0 <= b <= Summation(c[i]) # # Output Format # If Brian did not overcharge Anna, print Bon Appetit on a new line; otherwise, print the difference # (i.e. bcharged - bactual) that Brian must refund to Anna (it is guaranteed that this will always be an integer). # # Sample Input 0 # 4 1 # 3 10 2 9 # 12 # # Sample Output 0 # 5 # # Explanation 0 # Anna didn't eat item c[1]= 10 , but she shared the rest of the items with Brian. The total cost of the shared # items is 3 +2 +9 = 14 and, split in half, the cost per person is bactual =7. Brian charged her bcharged for her # portion of the bill, which is more than the 7 dollars worth of food that she actually shared with him. # Thus, we print the amount Anna was overcharged, bcharged - bactual= 12 -7 = 5, on a new line. # # Sample Input 1 # 4 1 # 3 10 2 9 # 7 # # Sample Output 1 # Bon Appetit # # Explanation 1 # Anna didn't eat item c[1] = 10, but she shared the rest of the items with Brian. The total cost of the shared # items is a 3+2+9= 14nd, split in half, the cost per person is bactual=7. Because this matches the amount # bcharged=7, that Brian charged Anna for her portion of the bill, we print Bon Appetit on a new line. # #######################################################################################################################
# Good Subarrays ####################################################################################################################### # # Rhezo likes the problems about subarrays . Today, he has an easy problem for you, but it isn't easy for him. # Can you help Rhezo solve it? The problem is as follows. # You are given an array A of N elements and a value P. Rhezo calls an array good # if sum of all elements of the array is less than P. # We can also define how good a sub array is. The goodness quotient of a good subarray is defined # as the maximum number in the good subarray. # Your task is simple, you need to find the most frequent goodness quotient taking into account all the sub arrays. # Most frequent value in a list of values, is the value occurring maximum number of times. # If there are many such values, print the one whose value is maximum. # # Input: # First line of the input contains two single space separated integers N and P. # Next line contains N space separated integers denoting the array A. # # Output: # Find the most frequent goodness quotient taking into account all the sub arrays. If there are 0 # good sub arrays, output −1. # # Constraints: # 1 <= N <= 10^5 # 1 <= Ai <= 10^9 # 1 <= P <= 10^14 # # SAMPLE INPUT # 5 7 # 2 2 8 1 3 # # SAMPLE OUTPUT # 2 # # Explanation # Good sub arrays are: [2],[2,2],[2],[1],[1,3],[3]. # Goodness quotient of the above sub arrays are: 2,2,2,1,3,3. # The most frequent goodness quotient is 2. # #######################################################################################################################
# Remove Friends ####################################################################################################################### # # After getting her PhD, Christie has become a celebrity at her university, and her facebook profile is full of # friend requests. Being the nice girl she is, Christie has accepted all the requests. # Now Kuldeep is jealous of all the attention she is getting from other guys, so he asks her to delete some of # the guys from her friend list. # To avoid a 'scene', Christie decides to remove some friends from her friend list, since she knows the popularity # of each of the friend she has, she uses the following algorithm to delete a friend. # # Algorithm Delete(Friend): # DeleteFriend=false # for i = 1 to Friend.length-1 # if (Friend[i].popularity < Friend[i+1].popularity) # delete i th friend # DeleteFriend=true # break # if(DeleteFriend == false) # delete the last friend # # Input: # First line contains T number of test cases. First line of each test case contains N, the number of friends # Christie currently has and K ,the number of friends Christie decides to delete. # Next lines contains popularity of her friends separated by space. # # Output: # For each test case print N-K numbers which represent popularity of Christie friend's after deleting K friends. # # Constraints # 1 <= T <= 1000 # 1 <= N <= 100000 # 0 <= K < N # 0 <= popularity_of_friend <= 100 # # NOTE: # Order of friends after deleting exactly K friends should be maintained as given in input. # # SAMPLE INPUT # 3 # 3 1 # 3 100 1 # 5 2 # 19 12 3 4 17 # 5 3 # 23 45 11 77 18 # # SAMPLE OUTPUT # 100 1 # 19 12 17 # 77 18 # #######################################################################################################################
# Last Occurrence ####################################################################################################################### # # You have been given an array of size N consisting of integers. In addition you have been given an element # M you need to find and print the index of the last occurrence of this element M in the array if it exists in it, # otherwise print -1. Consider this array to be 1 indexed. # # Input Format: # The first line consists of 2 integers N and M denoting the size of the array and the element to be searched for # in the array respectively . The next line contains N space separated integers # denoting the elements of of the array. # # Output Format # Print a single integer denoting the index of the last occurrence of integer M # in the array if it exists, otherwise print -1. # # Constraints # 1 <= N <= 10^5 # 1 <= A[i] <= 10^9 # 1 <= M <= 10^9 # # SAMPLE INPUT # 5 1 # 1 2 3 4 1 # 1 # # SAMPLE OUTPUT # 5 # ####################################################################################################################### siara = input().strip().split(' ') n = int(siara[0]) # no of element in array m = int(siara[1]) # no of numbers to be searched jiara = [int(x) for x in input().strip().split(' ')] #array of numbers thok = -1 for kiara in range(len(jiara)): if jiara[kiara] == m: thok = kiara + 1 print(thok)
# Most Common ####################################################################################################################### # # You are given a string S. # The string contains only lowercase English alphabet characters. # Your task is to find the top three most common characters in the string S. # # Input Format # A single line of input containing the string S. # # Constraints # 3 < len(S) < 10^4 # # Output Format # Print the three most common characters along with their occurrence count each on a separate line. # Sort output in descending order of occurrence count. # If the occurrence count is the same, sort the characters in ascending order. # # Sample Input # aabbbccde # # Sample Output # b 3 # a 2 # c 2 # # Explanation # Here, b occurs 3 times. It is printed first. # Both a and c occur 2 times. So, a is printed in the second line and c in the third line because a comes before c. # Note: The string S has at least 3 distinct characters. # #######################################################################################################################
# More on List ################################################################################ w = "the quick brown fox jumps over the lazy dog".split() w i = w.index('fox') i w[i] w.index('unicorn') # ValueError: 'unicorn' is not in list w.count('the') 37 in [1, 78, 9, 37, 34, 53] 78 not in [1, 78, 9, 37, 34, 53] u = "jackdaws love my big sphinx of quartz".split() u del u[3] u u.remove('jackdaws') u u.index('matlab') # ValueError: 'matlab' is not in list del u[u.index('quartz')] u.remove('pyramid') # ValueError: list.remove(x): x not in list a = "I accidentally the whole universe".split() a a.insert(2, "destroyed") a ' '.join(a) ################################################################################
# Sherlock and Anagrams ####################################################################################################################### # # Given a string S, find the number of "unordered anagrammatic pairs" of substrings. # # Input Format # First line contains T, the number of testcases. Each testcase consists of string S in one line. # # Constraints # 1 <= T <= 10 # 2 <= length(S) <= 100 # String S contains only the lowercase letters of the English alphabet. # # Output Format # For each testcase, print the required answer in one line. # # Sample Input#00 # 2 # abba # abcd # # Sample Output#00 # 4 # 0 # # Sample Input#01 # 5 # ifailuhkqq # hucpoltgty # ovarjsnrbf # pvmupwjjjf # iwwhrlkpek # # Sample Output#01 # 3 # 2 # 2 # 6 # 3 # # Explanation # Sample00 # Let's say S[i,j] denotes the substring Si ,Si+1,....,Sj. # # testcase 1: # For S=abba, anagrammatic pairs are: {S[1,1], S[4,4]}, {S[1,2], S[3,4]}, {S[2,2], S[3,3]} and {S[1,3], S[2,4]}. # # testcase 2: # No anagrammatic pairs. # # Sample01 # Left as an exercise to you. # #######################################################################################################################
# Gaming Triples ####################################################################################################################### # # All the Games are not Mathematical at all but Mathematical games are generally favourite of all. Ananya offered # such a Mathematical game to Sarika. Ananya starts dictating the rules of the game to Sarika. Sarika finds # the game interesting and wishes to play it. Ananya said that they have an array of N elements. # Each second either Ananya or Sarika can make a move. First one to make a move can select any 3 elements from # the given array which satisfies the following condition. # Let us consider 3 selected elements are A[x1], A[x2], A[x3] so they must follow the given two condition. # x1 < x2 < x3 # y1 < y2 > y3. # where y1=A[x1] , y2=A[x2] , y3=A[x3]. # The 3 selected numbers are written down on a piece of paper. One triplet can only be chosen once. # Refer to the image for better understanding. (diagram) # # The second player to make a move can also choose any 3 elements A[x1], A[x2], A[x3] such that chosen set of # elements fulfill the following two conditions. # x1 < x2 < x3 # y1 > y2 < y3. # where y1=A[x1] , y2=A[x2] , y3=A[x3]. # (diagram) # # Ananya and Sarika move alternatively and play optimally. Determine the winner of the game and also report # the number of seconds for which the game lasts. # NOTE: # One triplet can be chosen once. # Two triplets are considered to be different if there exists at least one x which belongs to the first # triplet but not to the second triplet.( where x is one of the indices of the chosen triplet ) # # [INPUT]: # First line of input contains a single integer T denoting the number of test cases. First line of each test # case contains a single integer N denoting the number of elements in the array. Next line contains # N space separated integers denoting elements of the array. Next line of test case contains a single # integer 0 if Ananya starts the game and 1 if Sarika starts the game. # # [OUTPUT]: # Output consists of 2*T lines. 2 lines corresponding to each test case. First line contains name of the # winner of the game and second line contains number of seconds for which the game lasts. # # [CONSTRAINTS]: # 1 <= T <= 10000 # 1 <= N <= 10^5 # -10^9 <= A[i] <= 10^9 # sum of N over all test cases will not exceed 4*10^6 # # SAMPLE INPUT # 2 # 3 # 1 2 3 # 1 # 3 # 3 2 3 # 0 # # SAMPLE OUTPUT # Ananya # 0 # Sarika # 0 # # Explanation # For the first test case , there is no triplets so Sarika cannot make a move, and hence Ananya will win # the game. No moves, No second. so answer # Ananya 0 # For the second test case , there is one triplets but it is of type 2 so Ananya cannot make a move, # and hence Sarika will win the game. No moves, No second. so answer # Sarika 0 # #######################################################################################################################
# Nice Arches ####################################################################################################################### # # Nikki's latest work is writing an story of letters. However, she finds writing story so boring that, after # working for three hours, she realized that all she has written are M long words consisting entirely of letters # A and B. Having accepted that she will never finish the story in time, poor Nikki has decided to at least have # some fun with it by counting bubbly words. # Now Nikki is connecting pairs of identical letters (A with A, B with B) by drawing arches above the word. # A given word is bubbly if each letter can be connected to exactly one other letter in such a way that no two # arches intersect. So here is your task. Help Nikki count how many words are bubbly. # # Input : # The first line of input contains the positive integer M , the number of words written down by Nikki. Each of # the following M lines contains a single word consisting of letters A and B, with length between 2 and 10^5, # inclusive. The sum of lengths of all words doesn't exceed 10^6. # # Output : # The first and only line of output must contain the number of bubbly words. # # Constraints: # 1 <= M <= 100 # # SAMPLE INPUT # 3 # ABAB # AABB # ABBA # # SAMPLE OUTPUT # 2 # # Explanation # ABAB - It is not bubbly as A(indexed 1) will connect to A(indexed 3) by an arch and when we try to connect # B(indexed 2) with B(indexed 4) by an arch then it will intersect with the arch b/w A and A. AABB - # It is bubbly as arch b/w A and A will not intersect with the arch b/w B and B. ABBA - It is also bubbly as # arches will not intersect. we can draw arches b/w A and A above the arch b/w B and B. # #######################################################################################################################
# Maximum occurrence ####################################################################################################################### # # You are given a string which comprises of lower case alphabets (a-z), upper case alphabets (A-Z), numbers, (0-9) # and special characters like !,-.; etc. # You are supposed to find out which character occurs the maximum number of times and the number of its occurrence, # in the given string. If two characters occur equal number of times, you have to output the character # with the lower ASCII value. # For example, if your string was: aaaaAAAA, your output would be: A 4, because A has lower ASCII value than a. # # Input format: # The input will contain a string. # # Output format: # You've to output two things which will be separated by a space: # i) The character which occurs the maximum number of times. # ii) The number of its occurrence. # # Constraints: # The maximum length of the string can be 1000. # # SAMPLE INPUT # Pulkit is a dog!!!!!!!!!!!! # # SAMPLE OUTPUT # ! 12 # #######################################################################################################################
# Range ################################################################################ # arithmatic progression of integers range(5) for i in range(5): print(i) range(5,10) list(range(5,10)) list(range(10,15)) #optional step argument list(range(0,10,2)) # abusing range (don't use un-pythonic way) # python is not 'c' s = [0, 1, 4, 6, 13] for i in range(len(s)) : print(s[i]) # prefer direct iteration over iterable object like list for v in s : print(v) # prefer enumerate() for counters # enumerate() yields(index, value) tuple t = [6, 372, 8862, 148800, 2096886] for p in enumerate(t): print(p) for i, v in enumerate(t): print("i = {}, v = {}".format(i,v)) ################################################################################
class Square: def __init__(self, side): self.side = side def __add__(squareOne, squareTwo): return ( (4 * squareOne.side) + (4 * squareTwo.side) ) squareOne = Square(5) squareTwo = Square(10) print("Sum of sides of both the squares =", squareOne + squareTwo)
# Roy and Trains ####################################################################################################################### # # Roy and Alfi reside in two different cities, Roy in city A and Alfi in city B. Roy wishes to meet her in city B. # There are two trains available from city A to city B. Roy is on his way to station A (Railway station of city A). # It will take T0 time (in minutes) for Roy to reach station A. The two trains departs in T1 and T2 minutes # respectively. Average velocities (in km/hr) of trains are V1 and V2 respectively. We know the distance D # (in km) between city A and city B. Roy wants to know the minimum time (in minutes) to reach city B, # if he chooses train optimally. # # If its not possible to reach city B, print "-1" instead (without quotes). # Note: If the minimum time is not integral, round the value to the least integer greater than minimum time. # # Input: # First line will contain integer T, number of test cases. # Second line will contain integers ** T0,T1,T2,V1,V2,D ** (their meanings are mentioned in problem statement) # # Output: # Print the integral result, minimum time (in minutes) to reach city B in a new line. # # Constraints: # 1 <= T <= 10000 # 1 <= T0,T1,T1 <= 1000 # 1 <= V1,V2 <= 500 # 1 <= D <= 5000 # # SAMPLE INPUT # 1 # 5 5 8 100 90 320 # # SAMPLE OUTPUT # 197 # # Explanation # Roy reaches station A # in 5 minutes, First train departs in 5 minutes and second train departs in 8 minutes, he will be able # to catch both of them. But he has to make an optimal choice, which train reaches city B in minimum time. # For first train 320/100=3.2hrs=192 minutes. Total time for first train, 5+192=197 minutes # For second train 320/90=3.555556hrs=213.33336 minutes. Least integer greater than 213.33336is214. # Total time for second train 214+8=222 minutes. So optimal choice is to take first train, # and hence the minimum time is 197 minutes. # #######################################################################################################################
# End Game ####################################################################################################################### # # Black and White are playing a game of chess on a chess board of n X n dimensions. The game is nearing its end. # White has his King and a Pawn left. Black has only his King left. So, definitely Black cannot win the game. # However, Black can drag the game towards a draw, and, he can do this only if he captures White's only left pawn. # White knows exactly what he must do so that he wins the game. He is aware of the fact that if his Pawn reaches # Row 'n' (topmost row as seen by White) , he is allowed to replace that Pawn by a Queen. Since White plays # chess regularly, he knows how to beat the opponent in a situation in which the opponent has only a King left # and he (White) has a King as well as a Queen left. The current scenario of the game will be given to you. # You must tell whether this game will end with a Draw or will it end with White winning. # (image) # # If Move = 0, it is currently White's move and if Move = 1, it is currently Black's move. # Black and White play alternately. # White's piece will be captured by Black if Black's King manages to reach the same square in which White's # piece is currently in. # White's king is currently placed at the the point (1,n). White is in a hurry to convert his pawn into a queen, # so , in every move of his, he only plays his pawn forward ( towards row n ), ignoring his king. # So, naturally, Black plays his King towards White's Pawn in order to capture it. # White's Pawn is currently located at the point (a,b). # Black's King is currently located at the point (c,d). # Pawn movement on a chess board : Pawn can move only one step forward, provided no piece is blocking it from # doing so. ie. it can move only from (u,v) to (u+1,v), provided there is no piece (white or black) at (u+1,v) # King movement on a chess board : King can move one step in any direction. ie if it is at (u,v) currently, # then it can move to (u+1,v) , (u-1,v) , (u,v+1) , (u,v-1) , (u+1,v+1) , (u+1, v-1) , (u-1,v+1) , (u-1,v-1), # provided it remains inside the chess board # If at any moment the White Pawn is blocked by the black king from moving forward, white will be forced # to play his king in such a case. # # Input: # First line consists of T, the number of test cases. Every test case comprises of a single line containing # space separated integers n, a, b, c, d, Move. # # Output: # For every test case, print a single line, 'Draw' is the game ends as a draw or 'White Wins' # if the game ends in white winning. # # Constraints : # 1 <= T <= 100000 # 5 <= n <= 10^9 # 2 <= a <= n # 1 <= b,c,d <= n # 0 <= Move <= 1 # (c,d) != { (1,n) , (2,n) , (1,n-1) , (2,n-1) , (a,b) } # # SAMPLE INPUT # 2 # 10 6 2 10 2 0 # 10 5 2 1 3 0 # # SAMPLE OUTPUT # Draw # White Wins # # Explanation # For first test case : white plays the first move since Move=0. white : Pawn moves from (6,2) to (7,2). # black : King moves from (10,2) to (9,2). white : Pawn moves from (7,2) to (8,2). # black : King moves from (9,2) to (8,2). white Pawn has been captured, so the game ends in a draw. # For second test case : white plays the first move since Move=0. white : Pawn moves from (5,2) to (6,2). # black : King moves from (1,3) to (2,2). white : Pawn moves from (6,2) to (7,2). # black : King moves from (2,2) to (3,2). white : Pawn moves from (7,2) to (8,2). # black : King moves from (3,2) to (4,2). white : Pawn moves from (8,2) to (9,2). # black : King moves from (4,2) to (5,2). white : Pawn moves from (9,2) to (10,2). # white Pawn has reached the topmost row (nth row), so, white will convert it into a Queen. # Black King cannot eliminate this Queen as it is too far. So, finally, White Wins. # #######################################################################################################################
# 8. Errors and Exceptions # 8.1. Syntax Errors # parsing errors # SyntaxError: invalid syntax while True print('Hello world') # 8.2. Exceptions # ZeroDivisionError: division by zero 10 * (1/0) # NameError: name 'spam' is not defined 4 + spam*3 # TypeError: must be str, not int '2' + 2 # 8.3. Handling Exceptions >>> while True: try: x = int(input('Please enter a number: ')) break except ValueError: print('Oops! That was no valid number. Try again...') try: pappi/0 except (RuntimeError, TypeError, NameError): raise class B(Exception): pass class C(B): pass class D(C): pass for cls in [B, C, D]: try: raise cls() except D: print('D') except C: print('C') except B: print('B') for cls in [B, C, D]: try: raise cls() except B: print('B') except C: print('C') except D: print('D') import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print('OS error: {0}'.format(err)) except ValueError: print('Could not convert data to an integer.') except: print('Unexcepted error:', sys.exc_info()[0]) raise import sys for arg in sys.argv[1:]: try: f = open(arg, 'r') except OSError: print('cannot open', arg) else: print(arg, 'has', len(f.readlines()), 'lines') try: raise Exception('spam', 'eggs') except Exception as inst: print(type(inst)) # the exception instance print(inst.args) # arguments stored in .args print(inst) # __str__ allows args to be printed directly, # but may be overridden in exception subclasses x, y = inst.args # unpack args print('x =', x) print('y =', y) def this_failes(): x = 1/0 try: this_failes() except ZeroDivisionError as err: print('Handling run-time error:', err) # 8.4. Raising Exceptions raise NameError('HiThere') raise ValueError try: raise NameError('HiThere') except NameError: print('An exception flew by!') raise # 8.5. User-defined Exceptions class Error(Exception): """ Base class for exceptions in this module.""" pass class InputError(Error): """ Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of error """ def __init__(self, expression, message): self.expression = expression self.message = message class TrasitionError(Error): """Raised when an operation attempts a state transition that's not allowed Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """ def __init__(self, previous, next, message): self.previous = previous self.next = next self.message = message # 8.6. Defining Clean-up Actions try: raise KeyboardInterrupt finally: print('Goodbye, world!') def divide(x, y): try: result = x / y except ZeroDivisionError: print('division by zero!') else: print('result is', result) finally: print('executing finally clause') divide(2, 1) divide(2, 0) divide("2", "1") for line in open('myfile.txt'): print(line, end='') with open('myfile.txt') as f: for line in f: print(line, end='')
# Encryption ####################################################################################################################### # # An English text needs to be encrypted using the following encryption scheme. # First, the spaces are removed from the text. Let L be the length of this text. # Then, characters are written into a grid, whose rows and columns have the following constraints: # # |_ sq.root(L) _| <= rows <= column <= |-sq.root(L)-| , where |_ x _| is floor function and |- x - | is ceil function # # For example, the sentence if man was meant to stay on the ground god would have given us roots after removing spaces # is 54 characters long, so it is written in the form of a grid with 7 rows and 8 columns. # # ifmanwas # meanttos # tayonthe # groundgo # dwouldha # vegivenu # sroots # # Ensure that rows x columns >= L # If multiple grids satisfy the above conditions, choose the one with the minimum area, i.e. rows x columns. # # The encoded message is obtained by displaying the characters in a column, inserting a space, and then displaying # the next column and inserting a space, and so on. For example, the encoded message for the above rectangle is: # # imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau # # You will be given a message in English with no spaces between the words. # The maximum message length can be 81 characters. Print the encoded message. # # Here are some more examples: # # Sample Input: # haveaniceday # # Sample Output: # hae and via ecy # # Sample Input: # feedthedog # # Sample Output: # fto ehg ee dd # # Sample Input: # chillout # # Sample Output: # clu hlt io # ####################################################################################################################### #!/bin/python3 import sys s = input().strip()
# Kinako Bread ####################################################################################################################### # # Tohka's favorite food is kinako bread, but she likes to eat bread in general too. For dinner, Shido has bought # Tohka N loaves of bread to eat, arranged in a line. Of the N loaves of bread, there are M distinct types of # bread numbered from 1 to M. Tohka is very touched that Shido would buy her so much bread, but she is on a diet. # Of the ith type of bread, Tohka doesn't want to eat more than Ri loaves. However, the bread is so tasty that # she would like to eat at least Li loaves of it. Tohka has decided that she will eat all the bread in a consecutive # section of the line, and no more. How many ways can she choose a consecutive section of the line to eat? # # Input: # The first line of input will have N and M. # The second line of input will have the types of bread in the line, in order, separated from each other # by single spaces. It is guaranteed that each type for bread from 1 to M appears at least once. # The next M lines will contain Li and Ri, for every i from 1 to M. # # Output: # The output should consist of one integer on a single line, # the number of ways to pick a consecutive section of the line. # # Constraints: # 1 ≤ M ≤ N ≤ 105 # 1 ≤ Li ≤ Ri ≤ N # # SAMPLE INPUT # 7 3 # 2 1 2 3 1 3 2 # 1 1 # 2 2 # 1 3 # # SAMPLE OUTPUT # 2 # # Explanation # The two ways to choose bread is to choose the segments from (1-indexed) [1, 4] or [3, 7]. # #######################################################################################################################
# Quicksort 2 - Sorting ####################################################################################################################### # # In the previous challenge, you wrote a partition method to split an array into two sub-arrays, one containing # smaller elements and one containing larger elements than a given number. This means you 'sorted' half the array # with respect to the other half. Can you repeatedly use partition to sort an entire array? # Guideline # In Insertion Sort, you simply went through each element in order and inserted it into a sorted sub-array. # In this challenge, you cannot focus on one element at a time, but instead must deal with whole sub-arrays, # with a strategy known as "divide and conquer". # When partition is called on an array, two parts of the array get 'sorted' with respect to each other. # If partition is then called on each sub-array, the array will now be split into four parts. This process can be # repeated until the sub-arrays are small. Notice that when partition is called on just one of the numbers, # they end up being sorted. # Can you repeatedly call partition so that the entire array ends up sorted? # # Print Sub-Arrays # In this challenge, print your array every time your partitioning method finishes, i.e. whenever two subarrays, # along with the pivot, are merged together. # The first element in a sub-array should be used as a pivot. # Partition the left side before partitioning the right side. # The pivot should be placed between sub-arrays while merging them. # Array of length 1 or less will be considered sorted, and there is no need to sort or to print them. # Note # Please maintain the original order of the elements in the left and right partitions # while partitioning around a pivot element. # For example: Partition about the first element for the array A[]={5, 8, 1, 3, 7, 9, 2} # will be {1, 3, 2, 5, 8, 7, 9} # # Input Format # There will be two lines of input: # n - the size of the array # ar - the n numbers of the array # # Output Format # Print every partitioned sub-array on a new line. # # Constraints # 1 <= n <= 1000 # -1000 <= x <= 1000, x E (belongs to ) ar # Each number is unique. # # Sample Input # 7 # 5 8 1 3 7 9 2 # # Sample Output # 2 3 # 1 2 3 # 7 8 9 # 1 2 3 5 7 8 9 # # Explanation # This is a diagram of Quicksort operating on the sample array: # # quick-sort diagram # # Task # The method quickSort takes in a parameter, ar, an unsorted array. # Use the Quicksort algorithm to sort the entire array. # #######################################################################################################################
# Zeros and Ones ####################################################################################################################### # # zeros # The zeros tool returns a new array with a given shape and type filled with 0's. # # import numpy # print numpy.zeros((1,2)) #Default type is float # #Output : [[ 0. 0.]] # # print numpy.zeros((1,2), dtype = numpy.int) #Type changes to int # #Output : [[0 0]] # # ones # The ones tool returns a new array with a given shape and type filled with 1's. # # import numpy # print numpy.ones((1,2)) #Default type is float # #Output : [[ 1. 1.]] # # print numpy.ones((1,2), dtype = numpy.int) #Type changes to int # #Output : [[1 1]] # # Task # Your task is to print an array of size N and integer type using the tools zeros and ones. # N is the space separated list of the dimensions of the array. # # Input Format # A single line containing the space separated list of N. # # Output Format # First, print the array using the zeros tool and then print the array with the ones tool. # # Sample Input # 3 3 3 # # Sample Output # [[[0 0 0] # [0 0 0] # [0 0 0]] # # [[0 0 0] # [0 0 0] # [0 0 0]] # # [[0 0 0] # [0 0 0] # [0 0 0]]] # [[[1 1 1] # [1 1 1] # [1 1 1]] # # [[1 1 1] # [1 1 1] # [1 1 1]] # # [[1 1 1] # [1 1 1] # [1 1 1]]] # ####################################################################################################################### import numpy
# Cavity Map ####################################################################################################################### # # You are given a square map of size n x n. Each cell of the map has a value denoting its depth. We will call a # cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it # has strictly smaller depth. Two cells are adjacent if they have a common side (edge). # You need to find all the cavities on the map and depict them with the uppercase character X. # # Input Format # The first line contains an integer n, denoting the size of the map. Each of the following n lines contains n # positive digits without spaces. Each digit (1-9) denotes the depth of the appropriate area. # # Constraints # 1 <= n <= 100 # # Output Format # Output n lines, denoting the resulting map. Each cavity should be replaced with character X. # # Sample Input # 4 # 1112 # 1912 # 1892 # 1234 # # Sample Output # 1112 # 1X12 # 18X2 # 1234 # # Explanation # The two cells with the depth of 9 fulfill all the conditions of the Cavity definition and have been replaced by X. # ####################################################################################################################### #!/bin/python3 import sys n = int(input().strip()) grid = [] grid_i = 0 for grid_i in range(n): grid_t = str(input().strip()) grid.append(grid_t)
# Solve Me First ####################################################################################################################### # # Welcome to HackerRank! The purpose of this challenge is to familiarize you with reading input from stdin # (the standard input stream) and writing output to stdout (the standard output stream) using our environment. # # Review the code provided in the editor below, then complete the solveMeFirst function so that it returns the # sum of two integers read from stdin. Take some time to understand this code so you're prepared # to write it yourself in future challenges. # # Select a language below, and start coding! # # Input Format # Code that reads input from stdin is provided for you in the editor. There are lines of input, # and each line contains a single integer. # # Output Format # Code that prints the sum calculated and returned by solveMeFirst is provided for you in the editor. # ####################################################################################################################### def solveMeFirst(a,b): return a+b # Hint: Type return a+b below num1 = int(input()) num2 = int(input()) res = solveMeFirst(num1,num2) print(res)
# Re.start() & Re.end() ####################################################################################################################### # # start() & end() # These expressions return the indices of the start and end of the substring matched by the group. # Code # >>> import re # >>> m = re.search(r'\d+','1234') # >>> m.end() # 4 # >>> m.start() # 0 # # Task # You are given a string S. # Your task is to find the indices of the start and end of string k in S. # # Input Format # The first line contains the string S. # The second line contains the string k. # # Constraints # 0 < len(S) < 100 # 0 < len(k) < len(S) # # Output Format # Print the tuple in this format: (start _index, end _index). # If no match is found, print (-1, -1). # # Sample Input # aaadaa # aa # # Sample Output # (0, 1) # (1, 2) # (4, 5) # #######################################################################################################################
# 11_dictionaries and tuples d = {"tom": 7326789820, "rob": 7325730239, "joe": 7326789820} print(d) d["tom"] d["sam"] = 739567987 print(d) del d["sam"] print(d) for key in d: print("key :", key, " value :", d[key]) for k,v in d.items(): print("key :", k, " value :", v) "tom" in d "samir" in d d.clear() d point = (5,9) point[0] point[1] point[0]=10 # TypeError: 'tuple' object does not support item assignment # Exercise # 1 member_number = input("How many family members info you want to store ? <Enter number> : ") family = {} for member in range(int(member_number)): name = input(str(member + 1) + " - Member name : ") age = input(str(member + 1) + " - Member age : ") family[name] = age name_enquiry = input("Whose age you want to enquire <Type name> : ") print(name_enquiry, "'s age : ", family[name_enquiry]) print("\nWhole family : ") for k, v in family.items(): print(k, ":", v) # 2 def add_and_multiply(first, second): return (first+second, first*second) print(add_and_multiply(3,4))
# Strange addition ####################################################################################################################### # # HackerMan has a message that he has coded in form of digits, which means that the message contains only numbers # and nothing else. He is fearful that the enemy may get their hands on the secret message and may decode it. # HackerMan already knows the message by heart and he can simply destroy it. # But he wants to keep it incase its needed in a worse situation. He wants to further encode the message # in such a format which is not completely reversible. This way if enemies gets hold of the message they will not # be completely able to decode the message. # Since the message consists only of number he decides to flip the numbers. The first digit becomes last # and vice versa. For example, if there is 3769 # in the code, it becomes 9673 now. All the leading zeros are omitted e.g. 15900 gives 951. So this way the # encoding can not completely be deciphered and has some loss of information. # # HackerMan is further thinking of complicating the process and he needs your help. He decides to add the two # flipped numbers and print the result in the encoded (flipped) form. There is one problem in this method though. # For example, 134 could be 431, 4310 or 43100 before reversing. Hence the method ensures that no zeros were lost, # that is it can be assumed that the original number was 431. # # Input # The input consists of T test cases. The first line of the input contains only positive integer T. # Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. # These are the flipped numbers you are to add. # # Output # For each case, print exactly one line containing only one integer - the flipped sum of two flipped numbers. # # Constraints # The value of T will be less than 1000 # The value of digits will be less than 500000 # # SAMPLE INPUT # 3 # 353 575 # 238746 39857 # 890 231 # # SAMPLE OUTPUT # 829 # 527327 # 32 # # Explanation # There are 3 test cases in the sample input. Following it are three lines that contains two numbers each, # so the output also contains three lines that contain the reverse of the sum of the two reversed numbers. # #######################################################################################################################
# Dot and Cross ####################################################################################################################### # # dot # The dot tool returns the dot product of two arrays. # # import numpy # A = numpy.array([ 1, 2 ]) # B = numpy.array([ 3, 4 ]) # # print numpy.dot(A, B) #Output : 11 # # cross # The cross tool returns the cross product of two arrays. # # import numpy # A = numpy.array([ 1, 2 ]) # B = numpy.array([ 3, 4 ]) # # print numpy.cross(A, B) #Output : -2 # # Task # You are given two arrays A and B. Both have dimensions of N X N. # Your task is to compute their matrix product. # # Input Format # The first line contains the integer N. # The next N lines contains N space separated integers of array A. # The following N lines contains space separated integers of array B. # # Output Format # Print the matrix multiplication of A and B. # # Sample Input # 2 # 1 2 # 3 4 # 1 2 # 3 4 # # Sample Output # [[ 7 10] # [15 22]] # ####################################################################################################################### import numpy
# Find the Maximum Depth ####################################################################################################################### # # You are given a valid XML document, and you have to print the maximum level of nesting in it. # Take the depth of the root as 0. # # Input Format # The first line contains N, the number of lines in the XML document. # The next N lines follow containing the XML document. # # Output Format # Output a single line, the integer value of the maximum level of nesting in the XML document. # # Sample Input # 6 # <feed xml:lang='en'> # <title>HackerRank</title> # <subtitle lang='en'>Programming challenges</subtitle> # <link rel='alternate' type='text/html' href='http://hackerrank.com/'/> # <updated>2013-12-25T12:00:00</updated> # </feed> # # Sample Output # 1 # # Explanation # Here, the root is a feed tag, which has depth of 0. # The tags title, subtitle, link and updated all have a depth of 1. # # Thus, the maximum depth is 1. # #######################################################################################################################
# Mini-Max Sum ####################################################################################################################### # # Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly # four of the five integers. Then print the respective minimum and maximum values as # a single line of two space-separated long integers. # # Input Format # A single line of five space-separated integers. # # Constraints # Each integer is in the inclusive range [1, 10^9]. # # Output Format # Print two space-separated long integers denoting the respective minimum and maximum values that can be # calculated by summing exactly four of the five integers. (The output can be greater than 32 bit integer.) # # Sample Input # 1 2 3 4 5 # # Sample Output # 10 14 # # Explanation # Our initial numbers are 1, 2, 3, 4, and 5. We can calculate the following sums using four of the five integers: # If we sum everything except 1, our sum is 2+3+4+5 = 14. # If we sum everything except 2, our sum is 1+3+4+5 = 13. # If we sum everything except 3, our sum is 1+2+4+5 = 12. # If we sum everything except 4, our sum is 1+2+3+5 = 11. # If we sum everything except 5, our sum is 1+2+3+4 = 10. # # As you can see, the minimal sum is 1+2+3+4 = 10 and the maximal sum is 2+3+4+5 = 14. Thus, we print these minimal # and maximal sums as two space-separated integers on a new line. # Hints: Beware of integer overflow! Use 64-bit Integer. # ####################################################################################################################### arr = list(map(int, input().strip().split(' '))) high = 0 min = 0 for first in range(len(arr)): x = arr[first] arr[first] = 0 thing = sum(arr) arr[first] = x if first == 0: min = thing high = thing if thing > high: high = thing elif thing < min: min = thing print(min, high)
# Minimum Distances ####################################################################################################################### # # Consider an array of n integers A =[a0, a1, ....an-1]. The distance between two indices i and j, # is denoted by dij = |i-j|. Given A, find the minimum dij such that ai = aj and i is not equal to j. # In other words, find the minimum distance between any pair of equal elements in the array. # If no such value exists, print -1. Note: |a| denotes the absolute value of a. # # Input Format # The first line contains an integer, n, denoting the size of array A. # The second line contains n space-separated integers describing the respective elements in array A. # # Constraints # 1 <= n <= 10^3 # 1 <= ai <= 10^5 # # Output Format # Print a single integer denoting the minimum dij in A; if no such value exists, print -1. # # Sample Input # 6 # 7 1 3 4 1 7 # # Sample Output # 3 # # Explanation # Here, we have two options: # a1 and a4 are both 1, so d1,4 = |1-4| = 3. # a0 and a5 are both 7, so d0,5 = |0-5|= 5. # The answer is min(3,5) = 3. # ####################################################################################################################### #!/bin/python3 import sys n = int(input().strip()) A = [int(A_temp) for A_temp in input().strip().split(' ')]
# Car Names ####################################################################################################################### # # Brian built his own car and was confused about what name he should keep for it. He asked Roman for help. # Roman being his good friend, suggested a lot of names. # Brian only liked names that: # - Consisted of exactly three distinct characters, say C1, C2 and C3 # - Satisfied the criteria that the string was of the form - C1n C2n C3n : This means, first C1 occurs n times, # then C2 occurs n times and then C3 occurs n times. For example, xyz, ccaarr, mmmiiiaaa satisfy the criteria, # but xyzw, aabbbcccc don't. # Given N names suggested by Roman, print "OK" if Brian likes the name and "Not OK" if he doesn't. # # Input: # First line contains a single positive integer N - the number of names. # N lines follow - each line contains a name. # # Output: # For each name, Print "OK" if the name satisfies the criteria, else print "Not OK", on a new line. # # Constraints: # 1 <= N <= 100 # 1 <= Length of names <= 500 # Names contain only lowercase English alphabets # # SAMPLE INPUT # 2 # bbbrrriii # brian # # SAMPLE OUTPUT # OK # Not OK # # Explanation # First name satisfies the criteria as: C1 = b, C2 = r, C3 = i, n = 3. # Second name does not satisfy the criteria. # #######################################################################################################################
# Set .intersection() Operation ####################################################################################################################### # # .intersection() # The .intersection() operator returns the intersection of a set and the set of elements in an iterable. # Sometimes, the & operator is used in place of the .intersection() operator, # but it only operates on the set of elements in set. # The set is immutable to the .intersection() operation (or & operation). # # >>> s = set("Hacker") # >>> print s.intersection("Rank") # set(['a', 'k']) # # >>> print s.intersection(set(['R', 'a', 'n', 'k'])) # set(['a', 'k']) # # >>> print s.intersection(['R', 'a', 'n', 'k']) # set(['a', 'k']) # # >>> print s.intersection(enumerate(['R', 'a', 'n', 'k'])) # set([]) # # >>> print s.intersection({"Rank":1}) # set([]) # # >>> s & set("Rank") # set(['a', 'k']) # # Task # The students of District College have subscriptions to English and French newspapers. Some students have # subscribed only to English, some have subscribed only to French, and some have subscribed to both newspapers. # You are given two sets of student roll numbers. One set has subscribed to the English newspaper, # one set has subscribed to the French newspaper. # Your task is to find the total number of students who have subscribed to both newspapers. # # Input Format # The first line contains n, the number of students who have subscribed to the English newspaper. # The second line contains n space separated roll numbers of those students. # The third line contains b, the number of students who have subscribed to the French newspaper. # The fourth line contains b space separated roll numbers of those students. # # Constraints # 0 < Total no of students in college < 1000 # # Output Format # Output the total number of students who have subscriptions to both English and French newspapers. # # Sample Input # 9 # 1 2 3 4 5 6 7 8 9 # 9 # 10 1 2 3 11 21 55 6 8 # # Sample Output # 5 # # Explanation # The roll numbers of students who have both subscriptions: # 1,2,3,6 and 8. # Hence, the total is 5 students. # ####################################################################################################################### nE = int(input()) englu = set(map(int, input().split())) nE = int(input()) frenchu = set(map(int, input().split())) print(len(englu.intersection(frenchu)))
#!/usr/bin/env python3 # # An HTTP server that remembers your name (in a cookie) # # In this exercise, you'll create and read a cookie to remember the name # that the user submits in a form. There are two things for you to do here: # # 1. Set the relevant fields of the cookie: its value, domain, and max-age. # # 2. Read the cookie value into a variable. from http.server import HTTPServer, BaseHTTPRequestHandler from http import cookies from urllib.parse import parse_qs from html import escape as html_escape form = '''<!DOCTYPE html> <title>I Remember You</title> <p> {} <p> <form method="POST"> <label>What's your name again? <input type="text" name="yourname"> </label> <br> <button type="submit">Tell me!</button> </form> ''' class NameHandler(BaseHTTPRequestHandler): def do_POST(self): # How long was the post data? length = int(self.headers.get('Content-length', 0)) # Read and parse the post data data = self.rfile.read(length).decode() try: yourname = parse_qs(data)["yourname"][0] except (KeyError, cookies.CookieError) as e: message = "Your Name is not set" yourname = '' print(e) # Create cookie. c = cookies.SimpleCookie() # 1. Set the fields of the cookie. # Give the cookie a value from the 'yourname' variable, # a domain (localhost), and a max-age. c['yourname'] = yourname c['yourname']['domain'] = 'localhost' c['yourname']['max-age'] = 600 # Send a 303 back to the root page, with a cookie! self.send_response(303) # redirect via GET self.send_header('Location', '/') self.send_header('Set-Cookie', c['yourname'].OutputString()) self.end_headers() def do_GET(self): # Default message if we don't know a name. message = "I don't know you yet!" # Look for a cookie in the request. if 'cookie' in self.headers: try: # 2. Extract and decode the cookie. # Get the cookie from the headers and extract its value # into a variable called 'name'. x_cookie = cookies.SimpleCookie(self.headers['Cookie']) name = x_cookie['yourname'].value # Craft a message, escaping any HTML special chars in name. message = "Hey there, " + html_escape(name) except (KeyError, cookies.CookieError) as e: message = "I'm not sure who you are!" print(e) # First, send a 200 OK response. self.send_response(200) # Then send headers. self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() # Send the form with the message in it. mesg = form.format(message) self.wfile.write(mesg.encode()) if __name__ == '__main__': server_address = ('', 8000) httpd = HTTPServer(server_address, NameHandler) httpd.serve_forever()
# Little Ashish and his wife ####################################################################################################################### # # Little Ashish had no interest in studying ever in his life. So, he always wanted to marry as soon as possible, # and kept forcing his parents to get him married. He thought his married life was going to be fun. But, well, # surprise, surprise... it's not - not for him, at least. # Fulfilling the demands of his wife is a huge problem for him. She wants costumes, a lot of them - and it's # getting impossible for Ashish to buy her all the clothes she asks for. Fortunately, for Ashish, he knows that # out of n dresses, his wife only needs x different type of dresses. Now Ashish doesn't want to spend and waste a # lot of time on this whole thing - so the only strategy he's decided to follow is to not follow any strategy - # that is to say, he gets all the n dresses, and gifts them to his wife for her to figure out how many different # dresses has he managed to bring. # Given the number of dresses, n, number of dresses he has to select, x - find out what his wife feels for him. # # Input format: # In the first line, tc will denote the number of test cases. The next line will contain the number of total # dresses, and the number of dresses he has to select for his wife. After which, there will be n integers, # denoting the price of each dress. # # Output format: # If the wife had asked for x dresses, and she got EXACTLY x dresses, print "Perfect husband", if it's more than # what she had asked for, print "Lame husband", if it's less than what she had demanded for, print "Bad husband." # # Constraints: # 1 <= Test cases <= 50 # 1 <= N <= 13000 # 1 <= X <= 13000 # 1 <= Price <= 109 # # SAMPLE INPUT # 4 # 4 1 # 1 4 2 5 # 4 2 # 4 2 1 5 # 4 3 # 5 2 4 1 # 4 4 # 1 2 4 5 # # SAMPLE OUTPUT # Lame husband # Lame husband # Lame husband # Perfect husband # # Explanation # In the first case, since x = 1, we've to select only 1, so the difference would be 0 by default. When we've # to select 4 out of 4, we can see the minimum difference would be (5-1==4) anyway. # #######################################################################################################################
# Modified Kaprekar Numbers ####################################################################################################################### # # A modified Kaprekar number is a positive whole number n with d digits, such that when we split its square into # two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d-1 # digits, the sum of the pieces is equal to the original number (i.e. l+r = n). # Note: r may have leading zeros. # Here's an explanation from Wikipedia about the ORIGINAL Kaprekar Number (spot the difference!): In mathematics, # a Kaprekar number for a given base is a non-negative integer, the representation of whose square in that base can # be split into two parts that add up to the original number again. For instance, 45 is a Kaprekar number, # because 45² = 2025 and 20+25 = 45. # # The Task # You are given the two positive integers p and q, where p is lower than q. Write a program to determine how many # Kaprekar numbers are there in the range between p and q(both inclusive) and display them all. # # Input Format # There will be two lines of input: p, lowest value q, highest value # # Constraints: # 0 < p < q < 100000 # # Output Format # Output each Kaprekar number in the given range, space-separated on a single line. # If no Kaprekar numbers exist in the given range, print INVALID RANGE. # # Sample Input # 1 # 100 # # Sample Output # 1 9 45 55 99 # # Explanation # 1, 9, 45, 55, and 99 are the Kaprekar Numbers in the given range. # #######################################################################################################################
# Integers Come In All Sizes ####################################################################################################################### # # Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there # is: 2^31 (c++ int) or 2^(63)-1 (C++ long long int). # # As we know, the result of a^b grows really fast with increasing b. # # Let's do some calculations on very large integers. # # Task # Read four numbers a, b, c, and d, and print the result of a^b + c^d. # # Input Format # Integers a, b, c, and d are given on four separate lines, respectively. # # Constraints # 1 <= a <= 1000 # 1 <= b <= 1000 # 1 <= c <= 1000 # 1 <= d <= 1000 # # Output Format # Print the result (a^b + c^d) of on one line. # # Sample Input # 9 # 29 # 7 # 27 # # Sample Output # 4710194409608608369201743232 # # Note: This result is bigger than 2^(63)-1. Hence, it won't fit in the long long int of C++ or a 64-bit integer. # #######################################################################################################################
# 5. Data Structures # 5.1. More on Lists x = [1, 2, 3, 4] x.append(5) x[len(x):] = [6] y = ['a', 'b', 'c'] x.extend(y) x[len(x):] = y x.insert(0, 10) x.insert(len(x), 11) x.remove(10) x.remove(y) x.remove(y[0]) x.remove(y[1]) x.remove(y[2]) # ValueError: list.remove(x): x not in list x.remove('d') x.pop(len(x)-1) x.pop() x.clear() x.index(1) # ValueError: 'z' is not in list x.index('z') x[len(x):] = x x.count(4) x.sort() x.sort(reverse=True) x.reverse() x.copy() fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] fruits.count('apple') fruits.count('tangerine') fruits.index('banana') fruits.index('banana', 4) fruits.reverse() fruits fruits.append('grape') fruits.sort() fruits.pop() # 5.1.1. Using Lists as Stacks stack = [3, 4, 5] stack stack.append(6) stack.append(7) stack.pop() stack.pop() stack.pop() stack # 5.1.2. Using Lists as Queues from collections import deque queue = deque(["Eric", "John", "Michael"]) queue.append("Terry") queue.append("Graham") queue.popleft() queue.popleft() queue # 5.1.3. List Comprehensions squares = [] for x in range(10): squares.append(x**2) squares squares = list(map(lambda x: x**2, range(10))) squares squares = [x**2 for x in range(10)] squares [(x, y) for x in [1,2,3] for y in [3, 1, 4] if x != y] combs = [] for x in [1, 2, 3]: for y in [3, 1, 4]: if x != y : combs.append((x,y)) combs vec = [-4, -2, 0, 2, 4] # create anew list with the values doubled [x*2 for x in vec ] # filter the list to exclude negative numbers [x for x in vec if x >= 0] # apply a function to all the elements [abs(x) for x in vec] # call a method on each element freshfruit = [' banana', ' loganberry ', 'passion fruit '] [weapon.strip() for weapon in freshfruit] # create a list of 2-tuples like (number, square) [(x, x**2) for x in range(6)] # the tuple must be parenthesized, otherwise an error is raised # SyntaxError: invalid syntax [x, x**2 for x in range(6)] # flatten a list using listcomp with two 'for' vec = [[1,2,3], [4,5,6], [7,8,9]] [num for elem in vec for num in elem] from math import pi [str(round(pi, i)) for i in range(1, 6)] # 5.1.4. Nested List Comprehensions matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] [ [row[i] for row in matrix] for i in range(4)] transposed = [] for i in range(4): transposed.append([row[i] for row in matrix]) for i in range(4): # the following 3 lines implement the nested listcomp transposed_row = [] for row in matrix: transposed_row.append(row[i]) transposed.append(transposed_row) list(zip(*matrix)) # 5.2. The del statement a = [-1, 1, 66.25, 333, 333, 1234.5] del a[0] del a[2:4] del a[:] # 5.3. Tuples and Sequences t = 12345, 54321, 'hello!' t[0] # tuples are immutable: # TypeError: 'tuple' object does not support item assignment t[0] = 88888 # but they can contain mutable objects: v = ([1,2,3], [3,2,1]) empty = () singleton = 'hello', type(singleton) len(empty) len(singleton) singleton # sequence unpacking x, y, z = t # 5.4. Sets basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} basket print(basket) 'orange' in basket #fast membership testing 'crabgrass' in basket # Demonstrate set operations on unique letters from two words. a = set('abracadabra') b = set('alacazam') a # unique letters in a a - b # letters in a but not in b a | b # letters in a or b or both a & b # letters in both a and b a ^ b # letters in a or b but not both # set comprehensions a = {x for x in 'abracadabra' if x not in 'abc'} a # 5.5. Dictionaries # associative memories/ associative arrays tel = { 'jack' : 4098, 'sape': 4139 } tel['guido'] = 4127 tel tel['jack'] # KeyError: 'hilton' tel['hilton'] del tel['sape'] tel['irv'] = 4127 tel list(tel) sorted(tel) 'guido' in tel 'jack' not in tel dict( [ ('sape', 4139), ('guido', 4127), ('jack', 4098) ] ) {x: x**2 for x in (2, 4, 6)} dict(sape=4139, guido=4127, jack=4098) # 5.6. Looping Techniques knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.items(): print(k, v) for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v) questions = ['name', 'quest', 'favorite color'] answers = ['lancelot', 'the holy grail', 'blue'] for q, a in zip(questions, answers): print('What is your {0}? It is {1}.'.format(q, a)) for i in reversed(range(1, 10, 2)): print(i) basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for f in sorted(set(basket)): print(f) import math raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8 ] filtered_date = [] for value in raw_data: if not math.isnan(value): filtered_date.append(value) filtered_date string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' non_null = string1 or string2 or string3 non_null # 5.8. Comparing Sequences and Other Types (1, 2, 3) < (1, 2, 4) (1, 2, 5) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] 'ABc' < 'C' , 'Pascal' < 'Python' p = 'ABc' < 'C' , 'Pascal' < 'Python' p type(p) (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1) (1, 2, 3) == (1.0, 2.0, 3.0) (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
# Battle Of Words ####################################################################################################################### # # Alice and Bob are fighting over who is a superior debater. However they wish to decide this in a dignified # manner. So they decide to fight in the Battle of Words. # In each game both get to speak a sentence. Because this is a dignified battle, they do not fight physically, # the alphabets in their words do so for them. Whenever an alphabet spoken by one finds a match (same alphabet) # spoken by the other, they kill each other. These alphabets fight till the last man standing. # A person wins if he has some alphabets alive while the other does not have any alphabet left. # Alice is worried about the outcome of this fight. She wants your help to evaluate the result. So kindly tell her # if she wins, loses or draws. # # Input: # First line contains an integer T denoting the number of games played. # Each test case consists of two lines. First line of each test case contains a string spoken by Alice. # Second line of each test case contains a string spoken by Bob. # Note: Each sentence can have multiple words but the size of sentence shall not exceed 10^5. # # Output: # For each game, output consists of one line each containing "You win some." if she wins ,"You lose some." # if she loses or "You draw some." otherwise. # Constraints: # 1 <= T <= 10 # 1 <= |A|,| B| <= 10^5 # 'a' <= alphabet <= 'z' # Each string contains atleast one alphabet. # # Scoring: # Length of |A|,|B| in each test case does not exceed 10^4 : ( 30 pts ) # Original Constraints : ( 70 pts ) # # SAMPLE INPUT # 3 # i will win # will i # today or tomorrow # today or tomorrow and yesterday # i dare you # bad day # # SAMPLE OUTPUT # You win some. # You lose some. # You draw some. # # Explanation # Case 1: Alice has "win" left at the end. So she wins. Case 2: Bob has "andyesterday" left at the end. # So Alice loses. Case 3: Alice has "ireou" and Bob has "bda" left. So Draw. # #######################################################################################################################
# Alien language ####################################################################################################################### # # Little Jhool considers Jaadu to be a very close friend of his. But, he ends up having some misunderstanding with # him a lot of times, because Jaadu's English isn't perfect, and Little Jhool sucks at the language Jaadu speaks. # So, he's in a fix - since he knows that Jaadu has got magical powers, he asks him to help so as to clear all the # issues they end up having with their friendship. # Now, Jaadu can only focus at one task, so to fix these language issues he comes up with a magical way out, # but someone needs to do the rest of it; this is where Little Jhool has asked for your help. # Little Jhool says a word, and then Jaadu says another word. If any sub-string of the word said by Jaadu is a # sub-string of the word said by Little Jhool, the output should be "YES", else "NO". (Without the quotes.) # # Input: # First line contains number of test case T. Each test case contains two strings *Text ( Said by Jhool ) * and # Pattern (Said by Jaadu ).Both strings contains only lowercase alphabets ['a'-'z']. # # Output: # For each test case print YES if any sub-string of Pattern is sub-string of Text else print NO. # # Constraints: # 1<=T<=5 # 1<=|Text|<=100000 # 1<=|Pattern|<=100000 # # SAMPLE INPUT # 2 # hackerearth # hacker # hackerearth # wow # # # SAMPLE OUTPUT # YES # NO # #######################################################################################################################
# checking class types and instances class Book: def __init__(self, title): self.title = title class Newspaper: def __init__(self, name) -> None: self.name = name # create some instances of the classes b1 = Book("The Catcher In The Rye") b2 = Book("The Grapes of Wrath") n1 = Newspaper("The Washington Post") n2 = Newspaper("The New York Times") # TODO: use type() to inspect the object type print(type(b1)) print(type(n1)) # TODO: compare two types together print("b1 == b2", type(b1) == type(b2)) print("b1 == n2", type(b1) == type(n2)) # TODO: use isinstace to compare a specific instance to a known type print("isinstance b1 -> Book",isinstance(b1, Book)) print("isinstance n1 -> Newspaper",isinstance(n1, Newspaper)) print("isinstance n2 -> Book",isinstance(n2, Book)) print("isinstance n2 -> object",isinstance(n2, object))
# Mars Exploration ####################################################################################################################### # # Sami's spaceship crashed on Mars! She sends n sequential SOS messages to Earth for help. # [NASA_Mars_Rover.jpg] # Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal # received by Earth as a string S, determine how many letters of Sami's SOS have been changed by radiation. # # Input Format # There is one line of input: a single string S. # Note: As the original message is just SOS repeated n times, S's length will be a multiple of 3. # # Constraints # 1 <= |S| <= 99 # |S| % 3 = 0 # S will contain only uppercase English letters. # # Output Format # Print the number of letters in Sami's message that were altered by cosmic radiation. # # Sample Input 0 # SOSSPSSQSSOR # # Sample Output 0 # 3 # # Sample Input 1 # SOSSOT # # Sample Output 1 # 1 # # Explanation # Sample 0 # S = SOSSPSSQSSOR, and signal length |S| = 12. Sami sent 4 SOS messages (i.e.: 12/3 = 4). # Expected signal: SOSSOSSOSSOS # Recieved signal: SOSSPSSQSSOR # We print the number of changed letters, which is 3. # # Sample 1 # S = SOSSOT, and signal length |S| = 6. Sami sent 2 SOS messages (i.e.: 6/3 = 2). # Expected Signal: SOSSOS # Received Signal: SOSSOT # We print the number of changed letters, which is 1. # ####################################################################################################################### #!/bin/python3 import sys S = input().strip()
# Sherlock and Special Count ####################################################################################################################### # # Let's say P= [P1, P2 . . . PN] is a permutations of all positive integers less than or equal to N. # A function called "special count" F(P) is defined as: # (image) # Now Watson gives a N and K to Sherlock and asks if K is a possible special count # for any permutation of first N positive integers. # # Input # First line contains T, the number of test cases. Each test case consists of N and K in one line. # # Output # For each test case, print "YES" or "NO", denoting whether K is a possible special count or not. # # Constraints # 1 <= T <= 100 # 20% testdata: 1 <= N <= 10 # 20% testdata: 1 <= N <= 20 # 60% testdata: 1 <= N <= 40 # 0 <= K <= 2000 # # SAMPLE INPUT # 2 # 2 1 # 3 2 # # SAMPLE OUTPUT # NO # YES # # Explanation # First test case: None of the two permutations [1, 2] and [2, 1] have special count 1. # Second test case: Permutations [1, 3, 2] and [2, 1, 3] have special count 2. # #######################################################################################################################
# Running Time of Algorithms ####################################################################################################################### # # In the previous challenges you created an Insertion Sort algorithm. It is a simple sorting algorithm that works # well with small or mostly sorted data. However, it takes a long time to sort large unsorted data. To see why, # we will analyze its running time. # # Running Time of Algorithms # The running time of an algorithm for a specific input depends on the number of operations executed. The greater # the number of operations, the longer the running time of an algorithm. We usually want to know how many # operations an algorithm will execute in proportion to the size of its input, which we will call N. # For example, the first two input files for Insertion Sort were small, so it was able to sort them quickly. # But the next two files were larger and sorting them took more time. What is the ratio of the running time of # Insertion Sort to the size of the input? To answer this question, we need to examine the Insertion Sort algorithm. # # Analysis of Insertion Sort # For each element V in an array of N numbers, Insertion Sort shifts everything to the right until # it can insert V into the array. # How long does all that shifting take? # In the best case, where the array was already sorted, no element will need to be moved, so the algorithm will # just run through the array once and return the sorted array. The running time would be directly proportional # to the size of the input, so we can say it will take N time. # However, we usually focus on the worst-case running time (computer scientists are pretty pessimistic). # The worst case for Insertion Sort occurs when the array is in reverse order. To insert each number, the algorithm # will have to shift over that number to the beginning of the array. Sorting the entire array of N numbers will # therefore take 1+2+...+ (N-1) operations, which is N(N-1)/2 (almost N^2/2 ). Computer scientists just round that # up (pick the dominant term) N^2 to and say that Insertion Sort is an "N^2 time" algorithm. # # running-time-picture # # What this means # As the size of an input (N) increases, Insertion Sort's running time will increase by the square of N. # So Insertion Sort can work well for small inputs, but becomes unreasonably slow for larger inputs. # For large inputs, people use sorting algorithms that have better running times, which we will examine later. # # Challenge # Can you modify your previous Insertion Sort implementation to keep track of the number of shifts it makes # while sorting? The only thing you should print is the number of shifts made by the algorithm to completely # sort the array. A shift occurs when an element's position changes in the array. Do not shift an element # if it is not necessary. # # Input Format # The first line contains N, the number of elements to be sorted. # The next line contains N integers a[1],a[2],..., a[N]. # # Output Format # Output the number of shifts it takes to sort the array. # # Constraints # 1 <= N <= 1001 # -10000 <= x <= 10000, x E(belongs to) a # # Sample Input # 5 # 2 1 3 1 2 # # Sample Output # 4 # # Explanation # The first 1 is shifted once. The 3 stays where it is. The next 1 gets shifted twice. The final 2 gets shifted # once. Hence, the total number of shifts is 4. # # Task # For this problem, you can copy your code from the InsertionSort problem, and modify it to keep track of the # number of shifts instead of printing the array. # #######################################################################################################################
# instance methods - methods of a class which uses "self" keyword to access # & modify the instance attirbutes of a class # static method - do not take "self" parameter, with decorator "@staticmethod" # ignore binding of the object # do not modify instance attribute of a class # can be used to modify class attributes # decorators - are functions which takes another function & extend their functionality class Employee: def employeeDetails(self): self.name = "Ben" @staticmethod def welcomeMessage(): print("Welcome to our organization!") employee = Employee() employee.employeeDetails() print(employee.name) employee.welcomeMessage()
# Sock Merchant ####################################################################################################################### # # John's clothing store has a pile of loose socks where each sock is labeled with an integer, , denoting its color. # He wants to sell as many socks as possible, but his customers will only buy them in matching pairs. # Two socks, and , are a single matching pair if . # Given and the color of each sock, how many pairs of socks can John sell? # # Input Format # The first line contains an integer, , denoting the number of socks. # The second line contains space-separated integers describing the respective values of . # # Constraints # # Output Format # Print the total number of matching pairs of socks that John can sell. # # Sample Input # 9 # 10 20 20 10 10 30 50 10 20 # # Sample Output # 3 # # Explanation # sock.png # As you can see from the figure above, we can match three pairs of socks. Thus, we print on a new line. # ####################################################################################################################### #!/bin/python3 import sys n = int(input().strip()) c = [int(c_temp) for c_temp in input().strip().split(' ')] chillerStyle = set(c) pairedTocks = 0 for redDot in chillerStyle: dingDong = 0 for babuMoshay in c: if babuMoshay == redDot: dingDong +=1 if dingDong != 0: pairedTocks += dingDong//2 print(pairedTocks)
# minimumNumber.py ####################################################################################################################### # # Write two Python functions to find the minimum number in a list. The first function should compare each number # to every other number on the list. O(n 2 ). The second function should be linear O(n). # ####################################################################################################################### seq = [9, 12, 10, 3,5,2,5,6,7, 0, -1] def firstMin(seq): tempMinNum = seq[0] for each in seq: for tech in seq: if tech < each: tempMinNum = tech return tempMinNum print(firstMin(seq)) def secondMin(seq): tempMinNum = seq[0] for each in seq: if each < tempMinNum: tempMinNum = each return tempMinNum print(secondMin(seq))
# median.py def median(iterable): """ Obtain the central value of a series. Sorts the iterable and returns the middle value if there is an even number of elements, or the arithmetic mean of the middle two elements if there is an even number of elements. Args: iterable: A series of orderable items. Returns: The median value. """ items = sorted(iterable) if len(items) == 0: raise ValueError("mean() arg is an empty sequence") median_index = (len(items) -1 ) // 2 if len(items) %2 != 0: return items[median_index] return (items[median_index] + items[median_index + 1]) / 2.0 def main(): try: median([]) except ValueError as e: print("Payload:", e.args) print(str(e)) if __name__ == '__main__': main()
# gen2 ################################################################################ def distinct(iterable): """Return unique items by eliminating duplicates. Args : iterable : The source series. Yields : Unique elements in order from 'iterable'. """ seen = set() for item in iterable : if item in seen : continue yield item seen.add(item) def run_distinct(): items = [5, 7, 7, 6, 5, 5] for item in distinct(items): print(item) if __name__ == "__main__": run_distinct() ################################################################################
#! /usr/bin/env python def madlib(adjective ='thirsty',name = 'adam'): print "the %s %s ate all the pizza" %(adjective,name) madlib() madlib(adjective='hungry',name = 'adam') def shoppingCart(itemName, *avgPrices): for price in avgPrices : print "price: ", price shoppingCart('computer',100,120,34) def shoppingCart(itemName, **avgPrices): for price in avgPrices : print price , 'price : ', avgPrices[price] shoppingCart('computer',amazon = 100,ebay = 120,bestBuy = 34) def dbLookup() : dict = {} dict['amazon'] = 100 dict['ebay'] = 120 dict['bestBuy'] = 34 return dict def shoppingCart(itemName, avgPrices): print 'item : ', itemName for price in avgPrices: print price, 'price: ', avgPrices[price] shoppingCart('computer',dbLookup())
# Exceptions ####################################################################################################################### # # Exceptions # # Errors detected during execution are called exceptions. # # Examples: # ZeroDivisionError # This error is raised when the second argument of a division or modulo operation is zero. # >>> a = '1' # >>> b = '0' # >>> print int(a) / int(b) # >>> ZeroDivisionError: integer division or modulo by zero # # ValueError # This error is raised when a built-in operation or function receives an argument that has the right type # but an inappropriate value. # >>> a = '1' # >>> b = '#' # >>> print int(a) / int(b) # >>> ValueError: invalid literal for int() with base 10: '#' # # To learn more about different built-in exceptions click here. # Handling Exceptions # # The statements try and except can be used to handle selected exceptions. A try statement may have more than one # except clause to specify handlers for different exceptions. # #Code # try: # print 1/0 # except ZeroDivisionError as e: # print "Error Code:",e # # Output # Error Code: integer division or modulo by zero # # Task # You are given two values a and b. # Perform integer division and print a/b. # # Input Format # The first line contains T, the number of test cases. # The next T lines each contain the space separated values of a and b. # # Constraints # 0 < T < 10 # # Output Format # Print the value of a/b. # In the case of ZeroDivisionError or ValueError, print the error code. # # Sample Input # 3 # 1 0 # 2 $ # 3 1 # # Sample Output # Error Code: integer division or modulo by zero # Error Code: invalid literal for int() with base 10: '$' # 3 # # Note: # For integer division in Python 3 use //. # #######################################################################################################################
# Find the Median ####################################################################################################################### # # In the Quicksort challenges, you sorted an entire array. Sometimes, you just need specific information about a # list of numbers, and doing a full sort would be unnecessary. Can you figure out a way to use your partition code # to find the median in an array? # # Challenge # Given a list of numbers, can you find the median? # # Input Format # There will be two lines of input: # n - the size of the array # ar - n numbers that makes up the array # # Output Format # Output one integer, the median. # # Constraints # 1 <= n <= 1000001 # n is odd # -10000 <= x <= 100000, x E(belongs to) ar # # Sample Input # 7 # 0 1 2 4 6 5 3 # # Sample Output # 3 # #######################################################################################################################
# ginortS ####################################################################################################################### # # You are given a string S. # S contains alphanumeric characters only. # Your task is to sort the string S in the following manner: # # All sorted lowercase letters are ahead of uppercase letters. # All sorted uppercase letters are ahead of digits. # All sorted odd digits are ahead of sorted even digits. # # Input Format # A single line of input contains the string S. # # Constraints # 0 < len(s) < 1000 # # Output Format # Output the sorted string S. # # Sample Input # Sorting1234 # # Sample Output # ginortS1324 # # Note: # a) Using join, for or while anywhere in your code, even as substrings, will result in a score of 0. # b) You can only use one sorted function in your code. A 0 score will be awarded for using sorted more than once. # Hint: Success is not the key, but key is success. # #######################################################################################################################
class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom def show(self): print(self.num, '/', self.den) def __str__(self): return str(self.num) + '/' + str(self.den) def gcd(self, m,n): while m % n != 0: old_m = m old_n = n m = old_n n = old_m % old_n return n # def __add__(self, other_fraction): # new_num = self.num * other_fraction.den + self.den * other_fraction.num # new_den = self.den * other_fraction.den # return Fraction(new_num, new_den) def __add__(self, other_fraction): new_num = self.num * other_fraction.den + self.den * other_fraction.num new_den = self.den * other_fraction.den common = self.gcd(new_num, new_den) return Fraction(new_num//common, new_den//common) def __eq__(self, other): first_num = self.num * other.den second_num = other.num * self.den return first_num == second_num
# Simple Banking System import random import sqlite3 class SimpleBankingSystem(object): _sqlite3_db_conn = None _sqlite3_cursor = None @staticmethod def print_welcome_message(): print('1. Create an account') print('2. Log into account') print('0. Exit') return int(input()) @staticmethod def _gen_rand_n_digit(n): return ''.join(['{}'.format(random.randint(0, 9)) for _ in range(0, n)]) def _gen_credit_card_num_luhn_algo(self, iin='400000', cust_account_number=None): if cust_account_number is None: cust_account_number = self._gen_rand_n_digit(9) fixed_cc_number_list = list(iin + cust_account_number) int_fixed_cc_number_list = [int(num) for num in fixed_cc_number_list] # multiply odd digits by 2 for i in range(1, len(int_fixed_cc_number_list) + 1): if i % 2 != 0: int_fixed_cc_number_list[i - 1] = int_fixed_cc_number_list[i - 1] * 2 # substract 9 to numbers over 9 for num, int_num in enumerate(int_fixed_cc_number_list): if int_num > 9: int_fixed_cc_number_list[num] = int_num - 9 # add all numbers total = sum(int_fixed_cc_number_list) # find checksum number/control number ( multiple of 10) checksum = 0 while total % 10 != 0: total += 1 checksum += 1 fixed_cc_number_list.append(checksum) str_cc_number = [str(num) for num in fixed_cc_number_list] return ''.join(str_cc_number) def set_sqlite3_connection_cursor(self, db_name='card.s3db'): self._sqlite3_db_conn = sqlite3.connect(db_name) self._sqlite3_db_conn.commit() self._sqlite3_cursor = self._sqlite3_db_conn.cursor() def _execute_only_sqlite3_query(self, query): self._sqlite3_cursor.execute(query) self._sqlite3_db_conn.commit() def _execute_fetchone_sqlite3_query(self, query): return self._sqlite3_cursor.execute(query).fetchone() def create_sqlite3_table(self, table_name='card'): query = """CREATE TABLE IF NOT EXISTS {}( id INTEGER PRIMARY KEY, number TEXT, pin TEXT, balance INTEGER DEFAULT 0)""".format(table_name) self._execute_only_sqlite3_query(query) def _insert_card_details_db(self, card_number, card_pin): # sqlite3 connection & table create if self._sqlite3_cursor is None: self.set_sqlite3_connection_cursor() self.create_sqlite3_table() # insert card_number & card_pin query = "INSERT INTO card (number, pin, balance) VALUES({}, {}, 0)".format(card_number, card_pin) self._execute_only_sqlite3_query(query) def create_account(self): # 16-digit credit card numbers # Major Industry Identifier (MII) - first digit - 4 # Issuer Identification Number (IIN) - first six digits - 400000 # customer account number (seventh digit to the second-to-last digit) - 9/12 digits # checksum/ check digit (Luhn algorithm) - last digit card_number = self._gen_credit_card_num_luhn_algo() card_pin = self._gen_rand_n_digit(4) # insert card details into db self._insert_card_details_db(card_number, card_pin) print('Your card has been created') print('Your card number:') print(card_number) print('Your card PIN:') print(card_pin) def _check_card_details(self, card_number, card_pin): query = 'SELECT number, pin FROM card WHERE number={}'.format(card_number) card_details = self._execute_fetchone_sqlite3_query(query) if card_details is not None: db_card_number, db_card_pin = (card_details[0], card_details[1]) if card_number == db_card_number and card_pin == db_card_pin: return True return False def _check_balance(self, card_number): query = 'SELECT balance FROM card WHERE number={}'.format(card_number) return self._execute_fetchone_sqlite3_query(query)[0] def _add_income_target(self, target_card_number, income): query = "UPDATE card SET balance = balance + {} where number = {}".format(income, target_card_number) self._execute_only_sqlite3_query(query) def _minus_income_user(self, user_card_number, income): query = "UPDATE card SET balance = balance - {} where number = {}".format(income, user_card_number) self._execute_only_sqlite3_query(query) def _check_card_number_by_algo(self, target_card_number): iin = target_card_number[:6] cust_account_number = target_card_number[6:15] # print('iin- Cust_account_number - ', iin, cust_account_number) valid_target_card_number = self._gen_credit_card_num_luhn_algo(iin, cust_account_number) # print('Valid target card number - ', valid_target_card_number) if target_card_number != valid_target_card_number: print('Probably you made mistake in the card number. Please try again!') return False return True def _check_card_number_db(self, target_card_number): query = 'SELECT number FROM card where number={}'.format(target_card_number) db_card_number = self._execute_fetchone_sqlite3_query(query) if db_card_number is None: print('Such a card does not exist.') return False return True def _do_transfer_money(self, user_card_number, balance): print('Transfer') target_card_number = input('Enter card number:').strip() if target_card_number == user_card_number: print("You can't transfer money to the same account!") return if not self._check_card_number_by_algo(target_card_number): return if not self._check_card_number_db(target_card_number): return money_transfer = int(input('Enter how much money you want to transfer:')) if balance < money_transfer: print('Not enough money!') return else: self._add_income_target(target_card_number, money_transfer) self._minus_income_user(user_card_number, money_transfer) print('Success!') return def _close_user_account(self, card_number): query = 'DELETE FROM card WHERE number={}'.format(card_number) self._execute_only_sqlite3_query(query) print('The account has been closed!') def log_into_account(self): card_number = input('Enter your card number:').strip() card_pin = input('Enter your PIN:').strip() # check card details with database if self._check_card_details(card_number, card_pin): print('You have successfully logged in!') user_transaction = '' while user_transaction != '0': user_transaction = self._show_login_transactions() if user_transaction == '1': # Balance balance = self._check_balance(card_number) print('Balance: {}'.format(balance)) elif user_transaction == '2': # Add income user_income = int(input('Enter income:')) self._add_income_target(card_number, user_income) print('Income was added!') elif user_transaction == '3': # Do transfer balance = self._check_balance(card_number) self._do_transfer_money(card_number, balance) elif user_transaction == '4': # Close account self._close_user_account(card_number) elif user_transaction == '5': # Log out print('You have successfully logged out!') break elif user_transaction == '0': # Exit self.bye_close_db_conn() else: print('Wrong card number or PIN!') @staticmethod def _show_login_transactions(): print('1. Balance') print('2. Add income') print('3. Do transfer') print('4. Close account') print('5. Log out') print('0. Exit') return input() def bye_close_db_conn(self): if self._sqlite3_db_conn is not None: self._sqlite3_db_conn.commit() self._sqlite3_db_conn.close() print('Bye!') quit() # Run program simpleBankingSystem = SimpleBankingSystem() simpleBankingSystem.set_sqlite3_connection_cursor() simpleBankingSystem.create_sqlite3_table() while True: user_input = simpleBankingSystem.print_welcome_message() if user_input == 1: simpleBankingSystem.create_account() elif user_input == 2: simpleBankingSystem.log_into_account() elif user_input == 0: simpleBankingSystem.bye_close_db_conn()
# 10_functions tom_exp_list = [2100, 3400, 3500] joe_exp_list = [200, 500, 700] total = 0 for item in tom_exp_list: total = total + item print("Tom's total expenses: ", total) total = 0 for item in joe_exp_list: total = total + item print("Joe's total expenses: ", total) ################################################################################ def calculate_total(exp): total = 0 for item in exp: total = total + item return total toms_total = calculate_total(tom_exp_list) joes_total = calculate_total(joe_exp_list) print("Tom's total expenses: ", toms_total) print("Joe's total expenses: ", joes_total) ################################################################################ def sum(a, b): total = a + b return total n = sum(5, 6) print("Total: ", n) ################################################################################ total = 0 def sum(a, b): print("a: ", a) print("b: ", b) total = a + b print("Total inside function : ", total) return total n = sum(b=5, a=6) print("n: ", n) print("Total outside function : ", total) ################################################################################ total = 0 def sum(a, b=0): print("a: ", a) print("b: ", b) total = a + b print("Total inside function : ", total) return total n = sum(5) print("n: ", n) print("Total outside function : ", total) ################################################################################ total = 0 def sum(a, b=0): """ This function takes two arguments which are integer numbers and it will return sum of them as an output :param a: :param b: :return total: """ print("a: ", a) print("b: ", b) total = a + b print("Total inside function : ", total) return total n = sum(5) print("n: ", n) print("Total outside function : ", total) ################################################################################ # Exercise # 1 def calculate_area(base, height): """ This function takes base & height of triangle and return area of triangle. :param base: base of Triangle :param height: height of Triangle :return area: Area of Triangle """ area = 1/2 * (base * height) return area print("Area of Triangle: ", calculate_area(4, 5)) ################################################################################ # 2 def calculate_shaped_area(base, height, shape): """ This function takes base(width), height(length) & shape and return area of that shape. :param base: base/width :param height: height/length :param shape: t-triangle, s-square :return area: area of given shape """ if shape == "t": area = 1/2 * (base * height) return area elif shape == "s": area = base * height return area else: print("Can't find shape given") print("Area of shape: ", calculate_shaped_area(4, 5, "s")) ################################################################################ # 3 def print_pattern(pattern): for i in range(1, pattern+1): for j in range(i): print("*", end="") print("\n") print_pattern(3)
# List Comprehensions ################################################################################ words = "Why sometimes I have believed as many as six impossible things before breakfast".split() words # list comprehension # [expr(item) for item in iterable] [len(word) for word in words] # declarative imperative code for above lenghts = [] for word in words : lenghts from math import factorial f = [len(str(factorial(x))) for x in range(28) ] f type(f) ################################################################################
# Ambiguous Tree ####################################################################################################################### # # For his birthday, Jeffrey received a tree with N vertices, numbered from 1 to N. Disappointed by the fact that # there is only one simple path between any two vertices, Jeffrey decided to remedy this by introducing an extra # edge in the tree. Note that this may result in a self loop or multiple edge. After introducing an extra edge, # Jeffrey wants to know how many pairs of two vertices are ambiguous. Two vertices are ambiguous if there exists # more than one simple path between them. Jeffrey has Q queries — he has decided Q possible locations # for the extra edge. Please help him find out how many ambiguous pairs there in the tree if he added each of # the Q edges to the tree. The tree will revert back to its original state after each query, # so queries are mutually independent. # # Input: # The first line of input will contain N. # The next N - 1 lines of input will each contain a pair of integers a and b, indicating # that there is an edge from vertex a to b. # The next line of input will contain Q. # The next Q lines of input will each contain a pair of integers u and v, indicating that Jeffrey is considering # putting an extra edge between u and v. # # Output: # Output Q lines, the answers to the queries in the same order as given in the input. # # Constraints: # 1 <= N <= 10^5 # 1 <= Q <= 10^5 # 1 <= a, b <= N, a ≠ b # 1 <= u, v <= N # It is guaranteed that the given edges in the initial graph will form a tree. # # Note: # A simple path is a sequence of vertices such that all the vertices in the sequence are unique and each adjacent # pair in the sequence are connected by an edge. Two simple paths are different if one vertex exists in one path # but not the other or one edge exists in one path but not the other. # # SAMPLE INPUT # 10 # 1 2 # 1 3 # 2 4 # 1 5 # 3 6 # 3 7 # 6 8 # 5 9 # 5 10 # 5 # 2 4 # 1 8 # 3 9 # 9 6 # 4 10 # # SAMPLE OUTPUT # 9 # 29 # 35 # 39 # 34 # # Explanation # Here is the tree given in the test case:(diagram) # #######################################################################################################################
# Samu and Card Game ####################################################################################################################### # # One day Samu went out for a walk in the park but there weren't any of her friends with her. So she decided # to enjoy by her own. Samu noticed that she was walking in rectangular field of size N x M (units). # So field can be divided into N horizontal rows, each containing M unit size squares. The squares have coordinates # (X, Y) (1 <= X <= N , 1 <= Y <= M) , where X is the index of the row and y is the index of the column. # Samu is initially standing at (1, 1). Also she is having a deck of K cards. Cards have a number written on top # and a number written on bottom too. These numbers tell the direction to move. It means if she is currently at some # coordinate (X, Y) and value on top of card is A and on bottom of the card is B then she jumps to (X+A, Y+B). # # Game is played with following rules : # 1. She looks all cards in the order from 1 to K and consecutively chooses each card as the current one. # 2. After she had chosen a current card , # she makes the maximally possible number of valid jumps with the chosen card. # She had been jumping for so long that she completely forgot how many jumps she had made. # Help her count how many jumps she had made. # # Input : # The first line contains number of test cases T. The first input line of each test case contains two space # separated integers N and M, the park dimensions. The second line of each test case contains an integer K # denoting the number of cards. Then follow K lines, each of them contains two integers A and B. # # Output : # A single integer for each test case, The number of jumps Samu had made. # # Constraints : # 1 <= T <= 500 # 1 <= n, m <= 1000000000 # 1 <= K <= 10000 # |A|,|B| <= 1000000000 # |A|+|B| >= 1 # # SAMPLE INPUT # 1 # 5 6 # 3 # 1 1 # 1 1 # 0 -4 # # SAMPLE OUTPUT # 5 # # Explanation # Samu is initially positioned at square (1,1) and makes 4 steps by the first card (1,1). # So, she jumps in following sequence (1,1) => (2,2) => (3,3) => (4,4) => (5,5) . No more Jumps can be made # with this card so now she discard this card and moves to next one. Then she makes 0 jumps by the second card # (1,1). She makes 1 more Jump by the third card (0,-4) and she ends up in square (5,1). # So she make 5 jumps in total. # #######################################################################################################################
# Laziness and the Infinite ################################################################################ # infinite loop def lucas(): yield 2 a = 2 b = 1 while True : yield b a, b = b, a+b for x in lucas(): print(x) ################################################################################
# 4.6. Defining Functions # The execution of a function introduces a new symbol table used for the local variables of the function. # variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, # then in the global symbol table, and finally in the table of built-in names. # UnboundLocalError: local variable 'x' referenced before assignment x = 1 print("Zero - ",x) def abc(): print("First - ",x) x = 2 print("second - ",x) def fib(n): # write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a + b print() # Now call the function we just defined fib(200) fib f = fib f(100) fib(0) print(fib(0)) def fib2(n): # return Fibonacci series up to n """ Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a+b return result f100 = fib2(100) f100
# Min and Max ####################################################################################################################### # # min # The tool min returns the minimum value along a given axis. # # import numpy # my_array = numpy.array([[2, 5], # [3, 7], # [1, 3], # [4, 0]]) # # print numpy.min(my_array, axis = 0) #Output : [1 0] # print numpy.min(my_array, axis = 1) #Output : [2 3 1 0] # print numpy.min(my_array, axis = None) #Output : 0 # print numpy.min(my_array) #Output : 0 # # By default, the axis value is None. Therefore, it finds the minimum over all the dimensions of the input array. # # max # The tool max returns the maximum value along a given axis. # # import numpy # my_array = numpy.array([[2, 5], # [3, 7], # [1, 3], # [4, 0]]) # # print numpy.max(my_array, axis = 0) #Output : [4 7] # print numpy.max(my_array, axis = 1) #Output : [5 7 3 4] # print numpy.max(my_array, axis = None) #Output : 7 # print numpy.max(my_array) #Output : 7 # # By default, the axis value is None. Therefore, it finds the maximum over all the dimensions of the input array. # # Task # You are given a 2-D array with dimensions N X M. # Your task is to perform the min function over axis 1 and then find the max of that. # # Input Format # The first line of input contains the space separated values of N and M. # The next N lines contains M space separated integers. # # Output Format # Compute the min along axis 1 and then print the max of that result. # # Sample Input # 4 2 # 2 5 # 3 7 # 1 3 # 4 0 # # Sample Output # 3 # # Explanation # The min along axis 1 = [2, 3, 1, 0] # The max of [2, 3, 1, 0] = 3 # ####################################################################################################################### import numpy
class dominosPizzaOrder(): """ usage for creating an object of this class""" orderNum = 0 pizzaNames = ["Margherita", "cornNonion", "FarmHouse", "CountrySpecial", ] pizzaCrusts = ["HandTossed", "ThinCrust", "CheezeBurst", "NewHandTossed"] pizzaToppings = ["Onion", "Tomato", "Capsicum", "CottageCheeze", "Jalapeno", "Mushroom", "BlackOlives", "RedPaprika", "GoldenCorn", "Babycorn"] OrderStatus = ["recieved", "preparation", "baking", "outForDelivery", "Delivered"] def __init__(self): self.name = input("What is your Name? ") self.mobNumber = int(input("What is your Number? ")) self.pizzaName = input("What is your PizzaName? ") if self.pizzaName not in dominosPizzaOrder.pizzaNames: print("wrong Pizza name, choose among below names:") print(" - ".join(dominosPizzaOrder.pizzaNames)) raise Exception self.pizzaCrust = "HandTossed" #input("What is your PizzaCrust? ") if self.pizzaCrust not in dominosPizzaOrder.pizzaCrusts: print("wrong crust name, choose among below names:") print(" - ".join(dominosPizzaOrder.pizzaCrusts)) raise Exception self.toppings = input("Give a list of toppingsn please ").split(" ") for x in self.toppings: if x not in dominosPizzaOrder.pizzaToppings: print("wrong toppings name, choose among below names:") print(" - ".join(dominosPizzaOrder.pizzaToppings)) raise Exception self.orderId = self.incrementOrderid() def incrementOrderid(self): dominosPizzaOrder.orderNum += 1 return dominosPizzaOrder.orderNum #self.Orderstatus
# Rest in peace - 21-1! ####################################################################################################################### # # The grandest stage of all, Wrestlemania XXX recently happened. And with it, happened one of the biggest # heartbreaks for the WWE fans around the world. The Undertaker's undefeated streak was finally over. # Now as an Undertaker fan, you're disappointed, disheartened and shattered to pieces. And Little Jhool doesn't # want to upset you in any way possible. (After all you are his only friend, true friend!) Little Jhool knows # that you're still sensitive to the loss, so he decides to help you out. # Every time you come across a number, Little Jhool carefully manipulates it. He doesn't want you to face # numbers which have "21" as a part of them. Or, in the worst case possible, are divisible by 21. # If you end up facing such a number you feel sad... and no one wants that - because you start chanting # "The streak is broken!" , if the number doesn't make you feel sad, you say, # "The streak lives still in our heart!". Help Little Jhool so that he can help you! # # Input Format: # The first line contains a number, t, denoting the number of test cases. # After that, for t lines there is one number in every line. # # Output Format: # Print the required string, depending on how the number will make you feel. # # Constraints: # 1 <= t <= 100 # 1 <= n <= 1000000 # # SAMPLE INPUT # 3 # 120 # 121 # 231 # # SAMPLE OUTPUT # The streak lives still in our heart! # The streak is broken! # The streak is broken! # #######################################################################################################################
# Insertion Sort - Part 2 ####################################################################################################################### # # In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort # an entire unsorted array? # Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted # array, one element at a time? Note that in the first step, when you consider an element with just the first # element - that is already "sorted" since there's nothing to its left that is smaller. # In this challenge, don't print every time you move an element. Instead, print the array after each iteration of # the insertion-sort, i.e., whenever the next element is placed at its correct position. # Since the array composed of just the first element is already "sorted", # begin printing from the second element and on. # # Input Format # There will be two lines of input: # s - the size of the array # ar - a list of numbers that makes up the array # # Output Format # On each line, output the entire array at every iteration. # # Constraints # 1 <= s <= 1000 # -10000 <= x <= 1000, x E(belongs to) ar # # Sample Input # 6 # 1 4 3 5 6 2 # # Sample Output # 1 4 3 5 6 2 # 1 3 4 5 6 2 # 1 3 4 5 6 2 # 1 3 4 5 6 2 # 1 2 3 4 5 6 # # Explanation # Insertion Sort checks 4 first and doesn't need to move it, so it just prints out the array. Next, # 3 is inserted next to 1, and the array is printed out. This continues one element at a time # until the entire array is sorted. # # Task # The method insertionSort takes in one parameter: ar, an unsorted array. # Use an Insertion Sort Algorithm to sort the entire array. # #######################################################################################################################
# Computer Virus ####################################################################################################################### # # Oh no! The virus infected Nick's computer after he downloaded a bunch of TAS preparation books from BayPirate, # and now he needs your (the best programmer in Lalalandia's) help! # The virus encrypted the data, closed all the programs, and only thing Nick sees on his screen is the matrix # with N∗M cells each containing 0 or 1 only. All cells also have color. Initially all the cells are black. # Then virus opens Q windows. In the ith window, Nick sees coordinates of two points: x1, y1 and x2, y2, # respectively. This means that the virus paints all the cells, which are between these points, in white. # More formally, let x and y be the coordinates of the cell, then the program will paint it in white only # if x1 <= x <= x2 and y1 <= y <= y2. After the painting, each window requires the password, which is the maximal # area A of the rectangle, which has at least one 1 in each column and all of its cells are white. Note that all # windows are independent, so if the cell is painted white in one window, # it will not be painted in all other windows. Can you help Nick with this tricky problem? # # Input format # The first line contains 2 integers: N and M - the number of rows and columns, respectively. # The next N lines describe the matrix: each contains M numbers of 0 or 1 only, without separating spaces # (see the samples for more explanation). # The next line consists of integer Q - the number of windows. Next Q lines describe the i th window: # each contains the coordinates of the left and right boundaries x1,y1 and x2,y2. # # Output format # The Q lines should each contain single integer A - the password for the window i (1 <= i <= Q ). # # Constraints: # 1 <= N <= 2000 , 1 <= N∗M <= 4000000 # 1 <= Q <= 1000000 # 1 <= x1 <= x2 <= N , 1 <= y1 <= y2 <= M # # SAMPLE INPUT # 4 4 # 0000 # 0010 # 0100 # 1000 # 1 # 1 2 3 4 # # SAMPLE OUTPUT # 6 # # Explanation # In the first window, the virus will paint the following cells in white: # coloring the table (diagram) # We can choose this rectangle with area 6, because it has one 1 in each row: # choosing the rectangle (diagram) # so our answer is 6. # #######################################################################################################################
# Unique Subarrays ####################################################################################################################### # # A contiguous subarray is defined as unique if all the integers contained within it occur exactly once. There is # a unique weight associated with each of the subarray. Unique weight for any subarray equals it's length if it's # unique, 0 otherwise. Your task is to calculate the sum of unique weights of all the contiguous subarrays # contained within a given array. # # Input # First line of the input contains an integer T, denoting the number of testcases. 2∗T lines follow, where first # line of each testcase contains an integer N denoting the number of integers in the given array. Last line of # each testcase then contains N # # single space separated integers # # Output # Print the summation of unique weights of all the subarrays for each testcase in a separate line. # # Constraints # 1 <= T,N <= 105 # 0 <= Ai <= 109 # Summation of N for all T does not exceed 105 # # SAMPLE INPUT # 1 # 5 # 1 2 3 4 5 # # SAMPLE OUTPUT # 35 # # Explanation # Sample Case 1: Since, all integers are distinct within any contiguous subarray, therefore the unique weight # will be the summation of lengths of all subarrays. Hence, this sums upto 5+4∗2+3∗3+2∗4+1∗5=35 # #######################################################################################################################
import numpy as np import time import sys # numpy array intro a = np.array([1, 2, 3]) print(a) print(a[0]) print(a[1]) ########################################################################## # array size comparison l = range(1000) print('Python List size: ', sys.getsizeof(5) * len(l)) array = np.arange(1000) print('Numpy array size: ', array.size * array.itemsize) ########################################################################## # speed comparison SIZE = 100000 l1 = range(SIZE) l2 = range(SIZE) a1 = np.arange(SIZE) a2 = np.arange(SIZE) # python list start = time.time() resultList = [(x + y) for x, y in zip(l1, l2)] print('Python list took(seconds): ', (time.time() - start) * 10000) # numpy array start = time.time() result = a1 + a2 print('Numpy array took(seconds): ', (time.time() - start) * 10000) ########################################################################## # numpy array operations a1 = np.array([1, 2, 3]) a2 = np.array([4, 5, 6]) print('Numpy array operations:- ') print('addition: ', a1 + a2) print('subtraction: ', a1 - a2) print('multiplication: ', a1 * a2) print('division: ', a1 / a2) ##########################################################################
####################################################################################################################### # # startWord # # Given a string and a second "word" string, we'll say that the word matches the string # if it appears at the front of the string, except its first char does not need to match exactly. # On a match, return the front of the string, or otherwise return the empty string. # So, so with the string "hippo" the word "hi" returns "hi" and "xip" returns "hip". # The word will be at least length 1. # ####################################################################################################################### # # startWord("hippo", "hi") → "hi" # startWord("hippo", "xip") → "hip" # startWord("hippo", "i") → "h" # startWord("hippo", "ix") → "" # startWord("h", "ix") → "" # startWord("", "i") → "" # startWord("hip", "zi") → "hi" # startWord("hip", "zip") → "hip" # startWord("hip", "zig") → "" # startWord("h", "z") → "h" # startWord("hippo", "xippo") → "hippo" # startWord("hippo", "xyz") → "" # startWord("hippo", "hip") → "hip" # startWord("kitten", "cit") → "kit" # startWord("kit", "cit") → "kit" # #######################################################################################################################
# Two Strings ####################################################################################################################### # # Given two strings a and b, determine if they share a common substring. # # Input Format # The first line contains a single integer p, denoting the number of (a,b) pairs you must check. # Each pair is defined over two lines: # # The first line contains string a. # The second line contains string b. # # Constraints # a and b consist of lowercase English letters only. # 1 <= p <= 10 # 1 <= |a|, |b| <= 10^5 # # Output Format # For each (a,b) pair of strings, print YES on a new line if the two strings share a common substring; if no such # common substring exists, print NO on a new line. # # Sample Input # 2 # hello # world # hi # world # # Sample Output # YES # NO # # Explanation # We have c = 2 pairs to check: # a = "hello", b= "world" The substrings "0" and "1" are common to both a and b, so we print YES on a new line. # a = "hi", b = "world" Because a and b have no common substrings, we print NO on a new line. # #######################################################################################################################
""" Output question "What is your name?", "How old are you?", "Where do you live?". Read the answer of user and output next information :"Hello, (answer(name))", 'Your age is (answer(age))', 'You live in (answer(city))' """ name = input('What is your name? ') age = input('How old are you? ') city = input('Where do you live? ') print('Hello',name) print('Your age is',age) print('You live in',city)
#Multiples of 3 or 5 def solution(number): ''' it returns the sum of all the multiples of 3 or 5 below the number passed in''' s = 0 for i in range(1,number): if i%3==0 or i%5==0: s+=i return s
#Simple: Find The Distance Between Two Points def distance(x1, y1, x2, y2): '''function find a distance''' return round((((x2-x1)**2+(y2-y1)**2)**0.5),2)