text
stringlengths
37
1.41M
def stringRotate(temp_str, rotate_str): if len(temp_str) == len(rotate_str): return rotate_str in (temp_str + temp_str) return False str1 = "race" str2 = "cere" print(stringRotate(str1, str2))
def findMin(nums): left,right=0,len(nums)-1 if nums[left]<nums[right]: return nums[0] while left<right: mid = left+(right-left)//2 if nums[mid]>nums[mid+1]: return nums[mid+1] elif nums[mid]>nums[right]: left=mid+1 else: right=right...
def count(s): w_count, l_count, d_count = 0, 0, 0 for c in s: if c == "W": w_count += 1 elif c == "D": d_count += 1 elif c == "L": l_count += 1 res = "" while l_count or d_count or w_count: if w_count > 0: res += "W" ...
class Node(object): def __init__(self, value): self.value = value self.next = None def insert_Node_toEnd(self, head, val_to_insert): currentNode = head while currentNode is not None: if currentNode.next is None: currentNode.next = Node(val_to_insert) ...
"""Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ class Solution: def singleNumber(self, nums: List[int]) -> int: dict1 = {} ...
def threeSumClosest(nums, target): minRes = float("inf") if not nums or len(nums) < 3: return 0 nums.sort() for i in range(len(nums)): low, high = i + 1, len(nums) - 1 while low < high: sumVal = nums[i] + nums[low] + nums[high] if sumVal == target: ...
""" Given an integer array, find three numbers whose product is maximum and output the maximum product. Input: [1,2,3,4] Output: 24 """ def maxProduct(nums): nums.sort() return max((nums[-3] * nums[-2] * nums[-1]), (nums[0] * nums[1] * nums[-1])) nums = [-4, -3, -2, -1, 60] print(maxProduct(nums))
def findMin(nums): left, right = 0, len(nums) - 1 # edge cases if nums[left] < nums[right]: return nums[left] if len(nums) == 1: return nums[0] while left <= right: mid = left + (right - left) // 2 if nums[mid] > nums[mid + 1]: return nums[mid + 1] ...
def dfs(board, i, j, word): if not word: return True if ( i < 0 or i > len(board) - 1 or j < 0 or j > len(board[0]) - 1 or board[i][j] != word[0] ): return False temp = board[i][j] board[i][j] = " " found = ( dfs(board, i + 1, j, wo...
def reverseWords(s): """ easy method that can be used in first round - please try using data structures """ # s = s.strip() # s2 = "" # lst = s.split() # return ' '.join(iter(lst[::-1])) i = 0 N = len(s) s2 = "" while i < N: while i < N and s[i] == " ": i...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isMirror(self, node1, node2): if node1 is None and node2 is None: return True ...
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def bfsHelper(node, level, levels): if node is None: return if len(levels) == level: levels.append([]) levels[level].append(node.val) if node.left:...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right def buildTreeRec(inOrder, postOrder, i1, i2, p2, p2): if i1 >= i2 or p1 >= p2: return node = TreeNode(postOrder[...
def finder(a1, a2): a1.sort() a2.sort() for i in range(0, len(a1)): if a1[i] != a2[i]: return a1[i] # x = finder([1,2,3,4,5,6,7],[3,7,2,1,4,6]) # print(x) # #Other solution # def finder2(a1,a2): # a1.sort() # k = int(len(a1)/2) + 1 # for i in range(0,len(a2)): # ...
def minCostClimbingStairs(cost): # bottom up dynamic approach/Recurrence relation n = len(cost) + 1 cost_list = [0] * (n) for i in range(2, n): cost_list[i] = min( cost_list[i - 1] + cost[i - 1], cost_list[i - 2] + cost[i - 2] ) return cost_list[n - 1] cost = [10, 15, 2...
""" LeetCode: 106 Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. inorder = [9,3,15,20,7] postorder = [9,15,7,20,3] 3 / \ 9 20 / \ 15 7 """ clas...
def run_spiral(lst, m, n, final_lst): top = 0 bottom = m - 1 left = 0 right = n - 1 direction = 0 while (top <= bottom) and (left <= right): if direction == 0: for i in range(left, right + 1): final_lst.append(lst[top][i]) top += 1 dir...
def rotate_image(matrix): n = len(matrix) for i in range(0, n): for j in range(1, n): temp = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = temp for i in range(0, n): for j in range(0, n // 2): temp = matrix[i][j] matrix[...
def strStr(haystack, needle): if len(haystack)<len(needle): return -1 if haystack == needle: return 0 n=len(needle) for i in range(len(haystack)-n): if haystack[i:i+n]==needle: return i return -1 haystack = "hello" needle = "ll" print(strStr(haystack,needle))
def defangIPaddr(address): str2 = "" for i in range(0, len(address)): if address[i] == ".": str2 += "[.]" else: str2 += address[i] return str2
def findMin(nums): def find_rotation_idx(nums): left,right = 0, len(nums)-1 if nums[left]<nums[right]: return 0 while left<right: mid = (left+right)//2 if nums[mid]>nums[mid+1]: return mid+1 else: if nums[mid]>=n...
class Node: def __init__(self, val): self.left = None self.right = None self.val = val from collections import deque def printLevelOrder(root): if root is None: return queue = [] queue.append(root) while len(queue) > 0: print(queue[0].val) node = q...
def thirdMax(nums): # easy pythonic way new_set = set(nums) if len(new_set) < 3: return max(nums) return sorted(new_set)[-3] def thirdMax2(nums): # more space optimized pythonic way using set new_set = set() for num in nums: new_set.add(num) if len(new_set) > 3: ...
def fancyRide(l, fares): max_val = 0 lst = ["UberX", "UberXL", "UberPlus", "UberBlack", "UberSUV"] for i, fare in enumerate(fares): if l * fare <= 20: max_val = i return lst[max_val] l = 30 fares = [0.3, 0.5, 0.7, 1, 1.3] print(fancyRide(l, fares))
from collections import Counter def longestPalindrome(s): if len(s) == 0: return 0 d = Counter(s) odd_count = 0 even_count = 0 odd_present = False for v in d.values(): if v % 2 == 0: even_count += int(v) else: odd_present = True odd_c...
def missingNumber(nums): nums.sort() if nums[0] != 0: return 0 if nums[-1] != len(nums): return len(nums) slow, fast = 0, 1 while fast != len(nums): if nums[slow] + 1 != nums[fast]: return nums[slow] + 1 slow += 1 fast += 1 return nums[-1] + 1 ...
def permutation(nums): nums = sorted(nums) res = [] path = [] status = [False] * len(nums) dfs(nums, res, path, status) return res def dfs(nums, res, path, status): if len(nums) == len(path): res.append(path[:]) return for i in range(len(nums)): if not status[i]...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(headA, headB): if headA is None and headB is None: return None ptr1 = headA ptr2 = headB while ...
""" Question: Based on the above employee table structure, explain how you would write a python function to read data from the above employee data and output it into a dictionary ---------------------------------------------------------------------------------------------------------------- Sample Output(Ass...
from collections import defaultdict def highFive(items): dict1 = defaultdict(list) lst3 = [] for lst in items: dict1[lst[0]].append(lst[1]) print(dict1) for key in dict1.keys(): id = key val = int(sum(sorted(dict1[id], reverse=True)[:5]) / 5) lst3.append([id, val])...
""" 26. Remove Duplicates from Sorted Array Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Given nums = [0,0,1,...
def removeDuplicates(nums): for i, c in enumerate(nums): temp = nums[i] for i in nums[i + 1 :]: if i > temp: break if temp == i: nums.remove(i) return nums nums = [1, 1, 2] print(removeDuplicates(nums))
""" In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. Input: [1,2,3,3] Output: 3 Input: [5,1,5,2,5,3,5,4] Output: 5 """ def repeatedNTimes(A): dict1 = {} for ele in A: if ele not in dict1.keys(): dict1[ele] = 1 else: ...
def max_sub_array_of_size_k(k, arr): # TODO: Write your code here sum_val,max_sum,start=0,0,0 cnt = 0 for end in range(len(arr)): sum_val+=arr[end] cnt+=1 if cnt>=k: cnt-=1 max_sum=max(max_sum,sum_val) sum_val-=arr[start] start+=1 r...
def multiply(num1, num2): if len(num1) == 0 or len(num2) == 0: return "0" n1 = len(num1) n2 = len(num2) num1 = num1[::-1] num2 = num2[::-1] res = [0] * (n1 + n2) for j in range(n2): for i in range(n1): res[i + j] = res[i + j] + (int(num1[i]) * int(num2[j])) ...
""" Binary Tree Level order traversal practice Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 / \ 9 20 / \ 15 7 [ [3], [9,20], [15,7] ] """ # Definition for a binary tree node. # class TreeNode: # def __init__(se...
class Solution: def isMirror(self, root1, root2): if root1 is None and root2 is None: return True if root1 is not None and root2 is not None and root1.val == root2.val: return self.isMirror(root1.left, root2.right) and self.isMirror( root1.right, root2.left ...
def min_heapify(array, i): left = 2 * i + 1 right = 2 * i + 2 length = len(array) - 1 smallest = i if left <= length and array[i] > array[left]: smallest = left if right <= length and array[smallest] > array[right]: smallest = right if smallest != i: array[i], array[s...
def combinationSum2(nums, target): res = [] lst = [] nums.sort() dfs(nums, res, lst, 0, target) return res def dfs(nums, res, lst, start, target): if target == 0 and lst not in res: res.append(lst[:]) return for i in range(start, len(nums)): if nums[i] > target: ...
def climbStairs(n): if n < 1: return 0 lst = [1] * (n + 1) for i in range(2, n + 1): lst[i] = lst[i - 2] + lst[i - 1] return lst[n] print(climbStairs(10))
""" Using the Greedy algorithm - piece by piece addition """ def partitionLabels(S): dict_label = {c: i for i, c in enumerate(S)} res = [] j, anchor = 0, 0 for i, c in enumerate(S): j = max(j, dict_label[c]) if i == j: res.append(i - anchor + 1) anchor = i + 1 ...
print('Contador de Una semana en dias horas y minutos') contador_dias = 1 contador_horas = 00 contador_minutos = 00 while contador_dias < 8: while contador_horas < 24: while contador_minutos <= 59: print(contador_dias, contador_horas, contador_minutos) contador_minutos += 1 ...
""" After Class Notes """ # 9/19 # skipped expressions & statements # ended with variables (msg.py) # Might be best to stay in terminal together for longer (Quicker responses) # Move from terminal when functions/oop start # 9/26 # Took way to long to configure GitHub accts # Next time, send instructions to ...
""" Problem 1 You have two strings. Put one in the middle of the other one. Example: s1 = "Environment", s2 = "Earth", result should be "EnviroEarthnment" """ s1 = "University" s2 = "Earth" new_txt = s1[:6] + s2 + s1[6:] print(new_txt) """ Problem 2 You have five strings. Create two strings, 1 containing all the...
""" Problem 3. Calculate your age using the value of the year you were born and the value of current year. """ current_year = 2021 year_i_was_born = 1999 my_age = 22 print("I am " + str(my_age) + " years old.")
import sys friend = sys.stdin.readline() friend = friend[ :-1] greeting = "Hello dogfriend" if friend == "Pants" or friend == "Joel" or friend == "Sarah": greeting = "It's the homegirl Pants! Where's the ball?" elif friend == "Lola" or friend == "Frances": greeting = "Hello Lola, sorry I can't feed you, ple...
from random import randint print("Welcome to game") user = input("Hey what's your name: ") user.capitalize() #Game Rules print("Game Rules:") print("There will be 5 rounds") print("Paper beats Rock") print("Rock beats scissor") print("Scissor beats paper") print("Winner will get 10 points for each round") #Game Desi...
def xor(plaintext, n): #plaintext = input('Input Text: ') asciiText = [] if len(plaintext) % 2 != 0: plaintext+='.' for char in plaintext: letBin = bin(ord(char))[2:] while(len(letBin) < 7): letBin = '0' + letBin asciiText.append(letBin) binText ...
import unittest from ArrangeBoardAndBoats import ArrangeBoardAndBoats from Board import Board from Boat import Boat class BattleShipTests(unittest.TestCase): """ Test class for the battleship game. This class will contain unittests for different functions implemented in the battleship code. """ emp...
import argparse import re from math import ceil, sqrrt def arg_parser(): parser = argparse.ArgumentParser() parser.add_argument('grid_fname') parser.add_argument('dict_fname') return parser.parse_args() def make_board(fname): with open(fname, 'r') as f: data = f.read() data = dat...
# -*- coding: utf8 -*- class Square(object): """Quadrados do tabuleiro""" def __init__(self,atribute=None): self.__atribute = atribute; self.__letter = None; @property def atribute(self): return self.__atribute; @atribute.setter def atribute(self,value): self.__atribute = value; @property d...
from heapq import * def find_k_largest_numbers(nums, k): min_heap = [] # if heap size is smaller than k, insert first k elements for i in range(k): heappush(min_heap, nums[i]) for j in range(k, len(nums)): if nums[j] > min_heap[0]: heappop(min_heap) heappush(min...
def search_next_letter(letters, key): # Assume array is circular start, end = 0, len(letters) - 1 if ord(letters[start]) > ord(key) or ord(key) > ord(letters[end]): return letters[start] while start <= end: mid = start + ((end - start) // 2) # since we want a higher order than t...
from heapq import * def secretString(triplets): ''' Returns the secret string synthesized through working with triplets list ''' max_heap, freq_map = [], dict() # build map, key = char, value = set of all chars that come after it for triplet in triplets: char1, char2, char3 = triplet[0...
# ========================= # Square Sorted Array Items # ========================= # PROBLEM STATEMENT # Given a sorted array, create a new array containing squares of # all the number of the input array in the sorted order. # EXAMPLE # Input: [-2, -1, 0, 2, 3] # Output: [0, 1, 4, 4, 9] # Input: [-3, -1, 0, 1, 2] #...
from os import close def generate_valid_parentheses(num): result = [] default_string = [0 for x in range(2*num)] # 1 open and 1 close bracket for each num generate_valid_parentheses_recursive(num, 0, 0, default_string, 0, result) return result def generate_valid_parentheses_recursive(num, openCount...
from heapq import * class job: def __init__(self, start, end, cpu_load): self.start = start self.end = end self.cpu_load = cpu_load def __lt__(self, other): return self.end < other.end def find_max_cpu_load(jobs): jobs.sort(key=lambda x: x.start) maxLoad = 0 curre...
# ======================== # Find All Missing Numbers # ======================== # We are given an unsorted array containing numbers taken from # the range 1 to ‘n’. The array can have duplicates, which means # some numbers will be missing. Find all those missing numbers. def find_missing_numbers(nums): missin...
# ===================================== # Longest Substring W/ Distinct K Chars # ===================================== import string # Problem Statement # ^^^^^^^^^^^^^^^^^ # Given a string, find the length of the longest substring # in it with no more than K distinct characters. # Ex: string = "araaci", for K = 2 ...
# =========================== # Unique Triplets Sum To Zero # =========================== # PROBLEM STATEMENT # Given an array of unsorted numbers, # find all unique triplets in it that add up to zero. # Input: [-3, 0, 1, 2, -1, 1, -2] # Output: [-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1] # Explanation: There are ...
# ----------------------------------------------------------------- # CALCULATOR # ----------------------------------------------------------------- class Calculator(): # NOTE: This class does allow for .plus().one().one(), which would evaluate to be 2 def __init__(self): ''' Calculate an oper...
from heapq import * from collections import deque def reorganize_string(str, k): reorganized_string = '' max_heap = [] char_frequency = dict() # build a hash map of char frequencies in str for char in str: char_frequency[char] = char_frequency.get(char, 0) + 1 # build a max heap with...
import random as dados preço = 5000 empuxo = 0 empuxo2 = empuxo chance_de_erro = 0 chance_de_erro1 = 0 chance_de_erro2 = 0 chance_de_erro3 = 0 chance_de_erro4 = 0 chance_de_erro5 = 0 contador = 1 parte = "" while (parte != "sair"): parte = input("parte do foquete: ") if parte == "motor": mortor = in...
# Uses python3 def calc_fib_slow(n): if (n <= 1): return n return calc_fib(n - 1) + calc_fib(n - 2) def calc_fib(n): a = 0 b = 1 if (n <= 1): return n for i in range(2,n+1): a, b = b, a+b return b n = int(input()) print(calc_fib(n))
# Uses python3 def evalt(a, b, op): if op == '+': return a + b elif op == '-': return a - b elif op == '*': return a * b else: assert False def MinAndMax(i,j,m,M,operators,digits): #write your code here min_val = float('inf') max_val = float('-inf') for k...
#automate the for loop to ensure it uses a for loop # Python code for the Grade students = {"John":70, "Mike":90, "Sandra":60, "Jennifer":10} for name,score in students.items(): print("Student Name: " + name + ", Score: " + str(score))
income_input = {"Alex": 500, "James": 20500, "Kinuthia": 70000} def calculate_tax(income_input): for item in income_input: income = income_input[item] # print(income) if (income >= 0) and (income <= 1000): tax = (0*income) elif (income > 1000) and (income <= ...
"""This file contains representation of different graphs as well as all the elements necessary for those graph. This file is created by Nessreddine LOUDIY.""" class Vertex: """A class to represent a Vertex.""" """Vertex initialization.""" def __init__(self, key, value=None): self.key = key ...
# Calculating conditional entropy of a text # Program expects first argument to be filename of the text file to be examined. # The script iterates over the text file and messes up the words or characters. # The script then calculates counts c(i,j), which is a number of bigrams ij. # And stores this in biGram dictionar...
import os #get file names from a folder #os.getcwd() gets current working dir #loop through each files but first change dir def rename_file(): file_list = os.listdir(r"/Users/khushali/Coding/Udacity_Programming_Foundation_with_Python/prank") saved_path = os.getcwd() os.chdir(r"/Users/khushali/Coding/Udacity...
import pandas as pd from numpy import nan from random import randint from random import choice #### A toy dataframe with some random data d2 = {'D':list(range(10)),'E':[randint(1,10) for i in range(10)], 'F':[choice(['x','y','z']) for i in range(10)]} df2 = pd.DataFrame(d2) df2 #### And one more exciting toy data...
import math def reverse(x: int) -> int: rem = abs(x) % 10 temp = int(abs(x) / 10) result = 0 while temp > 0: result = result * 10 + rem rem = temp % 10 temp = int(temp / 10) result = result * 10 + rem if x < 0: result = result * -1 if -1 * (math.pow(2, 31)) <...
"""Perform flood algorithms on numpy arrays.""" import numpy def flood_fill(array, start_pos, fill_value): """Fill contiguous region of an array with a new value""" for row, col in flood_select(array, start_pos): array[row][col] = fill_value def _valid_neighbors(array, position): """Return neigh...
def ADD(v1, v2): n = v1 + v2 return n def SUBT(v1, v2): n = v1 - v2 return n def DIVI(v1, v2): n = v1 / v2 return n def MUL(v1, v2): n = v1 * v2 return n X = int(input("Enter first value: ")) Y = int(input("Enter second value: ")) print("Press 1 to ADD.") print("Press 2 to SUB...
def displayOptions(): print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Exit") return def addData(x, y): z = x + y return z def subData(x, y): z = x - y return z def mulData(x, y): z = x * y return z def divData(x, y): z = ...
import random def gameWin(comp,you): if comp==you: return None elif comp== 's': if you=='w': return False elif you=='g': return True elif comp=='w': if you=='g': return False elif you=='s': return True elif ...
import sqlite3 conn = sqlite3.connect('dealership.sqlite') cur = conn.cursor() f = open('dealership_db.sql','r') sql = f.read() cur.executescript(sql) dealer = input("Enter dealer id") cur.execute("SELECT * FROM Dealership WHERE dealer_id = ?", (dealer)) dealership = cur.fetchone() if dealership is None: deal...
from tkinter import ttk import os class StdoutRedirect: ''' Class used to redirect stdout to widget. Used with widgets that accept text Usage: import sys sys.stdout=TextRedirect(widget) Parameters ----------------------- widget : tk.widget object ''' def __init__(self,w...
number = int(input()) for i in range(number): print(" "*(number-i),"*"*(((i+1)*2)-1))
a = 0 if a <= 10: print('menor') else: print('maior') if a == 1: print('é um') elif a > 1 and a <= 10: print('esta entre 1 e 10') elif a == 0: print('é zero') elif a < 1: print('é um numero negativo') else: print('maior q 10') teste = 'Teste 123 teste' if 'Teste' in teste: print('A...
for i in range(6): print(i) for i in range(10, 20): print(i) else: print("Acabooooooo!") x = 0 while True: print('Loop') x += 1 if x >= 10: break x = 0 y = 0 while x <= 10: print(x) y += 1 if y == 10: break
from math import * def isprime(n): if n == 1: return False for i in range(2, int(sqrt(n)+1)): if n % i == 0: return False return True def t(n): L = [] while isprime(n) == False: for i in range(2, n): if isprime(i): if n % i == 0: ...
#-- coding: utf-8 -- L = 'caayyhheehhbzbhhjhhyyaac' size = len(L) length = -1 maxup = -1 maxdown = -1 for i in range(size-1): if L[i] == L[i+1]:#中心字母有两个 down = i up = i + 1 if (L[i] != L[i+1] or (i - 1 >= 0 and L[i] == L[i-1] and L[i] == L[i+1])):#...
C = int(input()) for i in range(C): cont = 0 N = int(input()) for i in range(N): if i % 2 == 0 or i == 0: cont += 1 else: cont -= 1 print(cont)
aux1 = 0 for i in range(5): x = int(input()) if x % 2 == 0: aux1 += 1 print("%d valores pares" %aux1)
aux1 = aux2 = aux3 = 0 for i in range(6): x = float(input()) if x > 0: aux1 += 1 aux2 = aux2 + x aux3 = "%.1f" % (aux2 / aux1) print("%d valores positivos" %aux1) print(aux3)
contg = inter = gremio = emp = quem = 0 cond = 1 while cond == 1: gr1, gr2 = map(int, input().split()) contg += 1 if gr1 > gr2: inter += 1 elif gr2 > gr1: gremio += 1 else: emp += 1 cond = int(input("Novo grenal (1-sim 2-nao)\n")) if inter > gremio: quem = "Inter venc...
aux = cont = 0 X = int(input()) Z = int(input()) while Z <= X: Z = int(input()) while aux < Z: if cont == 0: aux = X else: X += 1 aux = X + aux cont += 1 print(cont)
x = float(input()) aux = i = 0 print("NOTAS:") for i in [100, 50, 20, 10, 5, 2]: while x >= i: x -= i aux += 1 print("%d nota(s) de R$ %d.00" %(aux, i)) aux = 0 x2 = int(x * 100) print("MOEDAS:") for i in [100, 50, 25, 10, 5, 1]: while x2 >= i: x2 -= i aux += 1 x3 = "...
def tip_calculator(): print("Total Price with tip: " + str(pirce * .15 + pirce)) def calculator_for_tip(): print("Tip Calculator") print("_" * 40) pirce = float(input("Please enter cost: ")) tip_calculator()
import csv import error import listGenrator def au(): print(listGenrator.addUserList()) order = str(input(" Your username:")) words = order.split() if words[0] == 'B' or words[0] == 'b': return if words[1] == 'A' or words[1] == 'a': with open('addUser.csv') as myFile: ...
def main(): # Main function from os import system, name # Imports OS to allow us to clear the console to print the ASCII text. from random import choice # Import the choice function from the random library to choose a random word from our words list. system("cls" if name == "nt" else "clear") # Clears th...
student_name = input("enter the student name: ") print("Hi " + student_name) city_name = input("enter the name of city: ") print("The city name is ",city_name,":-)") age = int(input("enter the age: ")) #every input is str but here we convert it into int print(type(age)) age2= int(age) print(int(age2)) print(type(ag...
''' cow will give born to a litter cow each year, and litter cow will do the same after four years, so when the nth year, how many cows in total? ''' def cow_story(n): if n<3: return 1 else: return cow_story(n-1)+cow_story(n-3) if __name__=="__main__": for n in range(6): pri...
import better_exceptions def binary_search(l,low,high,v): mid = int((low+high)/2) if v==l[mid]: return mid elif v>l[mid]: return binary_search(l,mid+1,high,v) else: return binary_search(l,low,mid,v) def binary_search2(l,v): low = 0 high = len(l)-1 while low<high: ...
''' find max path value for tree 1 1 10 30 1 2 the max valu path is 1-->1-->30 = 32 ''' class Node(): def __init__(self, value, row, col): self.value = value self.row = row self.col = col self.__left_child = None self.__right_child = None @property def ...
class Edge(): def __init__(self, l_node, r_node, weight = 0): self.l_node = l_node self.r_node = r_node self.weight = weight class Graph(): def __init__(self, vertices=[], edges=[]): self.vertices = vertices self.edges = [] for i in edges: print(i) ...
def diagonal(n): y=len(n0 if n==1: return n; if n>1: for i in range(0,n): x=[0,0] x[0]=x[0]+(n[i][i]) x[1]=x[1]+(n[y-i-1][y-i-1]) return(x[0]*x[1]) return 0 try: with open('Diagonal.txt') as f: data = f.read().split() num_of...
def digit_sum(n): x=[] y=str(n) for char in y: z=int(char) x.append(z) return sum(x) def is_int(x): y=int(x) if (x-y)==0: return True else: return False def is_even(x): if x%2==0: return True else: return False def factorial(x): ...
# Match score is X:Y, user prediction is A:B. # If user predicts the result of the match - user gets 10 point # If user predicts the win or lose or draw - user gets 5 point # If user make a mistake - user gets nothing def f(x, y, a, b): score = 0 if x == a and b == y: score = 10 elif x > y and a...