text
stringlengths
37
1.41M
import matplotlib.pyplot as plt import numpy as np import urllib2 # http_proxy enironment variable needs to be created first = http://username:password@proxyserver:proxyport proxy = urllib2.ProxyHandler() auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.ins...
# This script only works if the input file is ANSI/ASCII text. It will not work if it is UTF-16 # If the input file is UTF-16, then use codecs module: codecs.open(myFile,mode='r',encoding='UTF-16') import re # import the regular expressions package # Enter the regular expression pattern here: pattern = re.co...
import pygame from game.consts import WHITE class Ball(pygame.sprite.Sprite): def __init__(self, x, y, width=20, height=20): super(Ball, self).__init__() self.surf = pygame.Surface((width, height)) self.rect = self.surf.get_rect(left=x, top=y, width=width, height=height) pygame.dr...
class Bird : def __init__(self): self.hungry = True def eat(self): if self.hungry: print('Aaah') self.hungry =False class SongBird(Bird) : def __init__(self): # Bird.__init__(self) super().__init__() self.sound = 'kkkk' def sing(self...
while True : try : x = int (input('Enter the first number :')) y = int(input('enter the second number :')) value = x/y print('x/y is ' ,value) except Exception as e : print('invalid input . please try again ') print(e) else: break finally: ...
for letter in 'letter': print ('dang qian zi mu ' ,letter) seq = ['22','3333','4444'] # 序列 print('hanhanhan'.join(seq)) seq2 = ('22','33','44','55') #元祖 print('文茂'.join(seq2)) seq3 ={'22':1 ,'33':2 ,'44':3} # 字典 print('wenmao'.join(seq3))
#coding: utf-8 import re import urllib, os print """ =================================== Bienvenido al motor de busqueda MOS =================================== Instrucciones de uso Coloca las url de dos paginas que quieras comparar luego coloca la palabra para tu busqueda Si solo ponele recuerda que tienes ...
# This code prints the current state of the board def display_board(board): boardlist = list(board) table = f'\t|\t|\n {boardlist[6]}\t| {boardlist[7]}\t| {boardlist[8]}\n________|_______|________\n\t|\t|\n {boardlist[3]}\t| {boardlist[4]}\t| {boardlist[5]}\n________|_______|________\n\t|\t|\n ...
# -*- coding: utf-8 -*- class AlphaMode(object): """ Class for the different stages of the game AlphaMode.current_size is the size of the screen AlphaMode.client_states is the upper class calling the state """ def __init__(self, screen_size, client_states): self.current_size = screen_s...
## @file triangle_adt.py # @author Daniel Guoussev-Donskoi # @brief A class that simulates a triangle, and several related methods # @details A class simulating a triangle is initialised, with 3 variables # @details The class assumes a, b and c are valid positive integer inputs # representing it's sides # @date ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Yu Chen # # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class TreeNode: def __init__(self, x): self.val = x self.left = N...
# class Solution: # # @param {integer} x # # @return {boolean} # def isPalindrome(self, x): # source = str(x) # length = len(source) # for i in xrange(length/2): # if (source[i] == source[length-1-i]): # continue # else: # ...
import archivos opcion=0 archivo="foto.jpeg" archivos.generarClave() clave=archivos.cargarClave() while opcion !=5: print("\nSeleccione una opción\n") print("1.-Leer Archivo\n2.-Agregar texto al archivo\n3.-Encriptar\n4.-Desencriptar\n5.-Salir") opcion=int(input("Ingresa una opción: ")) if opcion==1...
a=int(input()) for b in range(1,6) print((a*b))
import sys,string def isPalin(s) : if s == s[::-1] : return True else : return False a = input() b = list(a) n = len(a) for i in range(0,n) : L2 = b[:] L2.pop(i) s2 = ''.join(L2) if isPalin(s2) : print('YES') sys.exit() print('NO')
# -*- coding: utf-8 -*- """ Created on Sat Oct 3 14:24:54 2015 @author: yys """ def threeSum(nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums = sorted(nums) res = [] i = 0 l = len(nums) if l == 0: return res while nums[i] <= 0 and i < l-1: # i ...
# -*- coding: utf-8 -*- """ Created on Sat Aug 29 22:49:27 2015 @author: yys """ class ListNode(object): def __init__(self, x): self.val = x self.next = None def mergeKLists(lists): """ :type lists: List[ListNode] :rtype: ListNode """ import heapq queue = [(l.val,...
import time import numpy as np initial_state = tuple(input('input board state in the form (1,2,3),(4,5,6),(7,8,0) : ')) start_time = time.time() goal_state = ((1,2,3),(4,5,6),(7,8,0)) moves_state = {"0": initial_state} # dictionary that pairs possible moves to game states def check_solvable(game_state): # checks if...
################################################################## # Notes: # # You can import packages when you need, such as structures. # # Feel free to write helper functions, but please don't use many # # helper functions. ...
# 用户输入的内容 person = int(input('请输入: 剪刀(0) 石头(1) 布(2):')) # 计算机输入的内容 import random # random.randint(0, 10) # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 [0, 10] 0<=x<=10 computer = random.randint(0, 2) print(computer) # 站在用户的角度上 # 用户赢: # 0 --> 2 1 ---> 0 2 ---> 1 # 假如说玩家胜利(剪刀 = 布 或者 石头 = 剪刀 或者 布 = 石头) # 用户和电脑打平: # 用...
def main(): a = "20,50,80" # 分割字符串 print(a.split(",")) # 删除尾部的字符串 print(a.rstrip("80")) # 判断一个变量的类型 # if type(a) == str: # print("123") if isinstance(a, str): print("123") if __name__ == '__main__': main()
# - del:根据下标进行删除, 也可以删除掉整个列表对象,提前释放内存 # - pop:删除最后一个元素, 也可以删除单个指定元素 把删除的元素返回回来 # - remove:根据元素的值进行删除 如果要删除的元素值不再列表,会崩溃 # - clear: 清空这个列表 把列表中的元素删除干净,但是列表还在 # del my_list = ['hello', 23, 3.14, 23, True, 23] # print(my_list[2]) del my_list[2] print(my_list) # 特殊: # del my_list # print(my_list) # pop my_list1 ...
# 类型 # int 有符号的整形 # float 浮点型 # 布尔(bool) True False # string (字符串) 简写: str # 需求: 定义一个人的信息: 姓名 年龄 身高 是否是男的 # 姓名: # 用的字符串类型: 格式: '内容部分' 或者 "内容部分" # python里面有一个内置函数, 帮我们检测变量里面存放的数据类型 # type(变量名或者数值) name = '小明' # <class 'str'> print(type(name)) # 年龄 age = 18 # <class 'int'> print(type(age)) # 身高 height = 178....
# print(num) # NameError: name 'num' is notdefined # NameError: 异常的类型 # name 'num' is notdefined 异常的描述 # NameError # FileNotFoundError # 捕获多种异常 # try: # open('hm.txt', 'r') # print(num) # except (NameError, FileNotFoundError): # print('发生异常了') # 捕获所有的异常: # try: # # open('hm.txt', 'r') # print(...
# 1) find # Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。 # mystr = 'hello world' # ret1 = mystr.find('meihao') # print(ret1) # 2) index # Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异...
# 1) 添加元素 # # append, extend, insert # 列表是可变的, 字符串是不可变的 # 定义一个列表 my_list = ['hello', 2.3, 2323, True] # append my_list.append('world') print(my_list) my_list.append(['1', '2']) print(my_list) print('='*40) # extend my_list1 = ['hello', 2.3, 2323, True] my_list1.extend('world') print(my_list1) # 下面的用法是错误的: 因为int不能...
def add2Num(a, b): result = a + b print(result) # print(a + b) num1 = add2Num(10, 12) print(num1)
# 导包 unittest、三角形函数、读取xml数据类 import unittest from UT.Day02.Code.sjx import Sjx from UT.Day02.ReadData.read_xml import Read_Xml # 实例化三角形 sjxClass=Sjx() # 实例化读取xml类 readXmlClass=Read_Xml() class Test_Xml(unittest.TestCase): def test001(self): for i in range(readXmlClass.get_len("bian")): # 目的测试三角形...
my_list = ['哈哈' for x in range(10)] print(my_list) my_list1 = ['%d' % (i + 1) for i in range(5)] my_list1 = [str(i+1) for i in range(5)] print(my_list1)
# 字典 # name age # 保存信息: # 小明: {'name':'xiaoming', 'age':23} # 小红: {'name':'xiaohong', 'age':23} dict = {'xiaoming':{'name':'xiaoming', 'age':23}, 'xiaohong':{'name':'xiaohong', 'age':23}} # 删除信息: # del # del dict['xiaoming'] # print(dict) # 修改: dict['xiaoming']['age'] = 32 # 查看 age = dict['xiaoming']['age']
def function(): print('function') def func(): print('func') # 加法的练习: def add2num(): num1 = 10 num2 = 12 result = num1 + num2 print(result) add2num() func() func() func() def hah(): name = 'wangwen' age = 19 print('名字是:%s'%name) print('年龄是:%s'%age) hah() def print_func(): ''' ...
__author__ = "Jorge Melguizo" __copyright__ = "Copyright 2018, Trolls Detector" class Node(): key = 0 def __init__(self, key): self.key = key #self.word = word self.left = None self.right = None class AVLTree(): def __init__(self, *args): self.node = None ...
# Run this code as command line code, main input: -r, -num, - o import argparse import cv2 import os import numpy # to rotate the image def rotation(img,angle,num,arg): img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) rows, cols = img.shape centre = (cols/2,rows/2) path = 'F:\GDP\G' if arg: for i...
"""Houston control station file.""" import os from control_station import ControlStation def main(): """Main script function.""" command_list = [] command = 'X' while(command.upper() != ''): command = input("Insert the command: (Empty enter to finish) \n") if command.upper() != '': ...
import pandas as pd import numpy as np data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'], 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3], 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'ye...
""" Given an array of strings, return all groups of strings that are anagrams. Represent a group by a list of integers representing the index in the original list. Look at the sample case for clarification. Anagram : a word, phrase, or name formed by rearranging the letters of another, such as 'spar', formed from 'ra...
#INFIX COMPUTATION: Enter a string like "1+2-(3/4)*5" and get the result def operation(string): #we have to use parser in this function if string[1]=='+': return str(float(string[0]) + float(string[2])) elif string[1]=='-': return str(float(string[0]) - float(string[2])) elif string[1]=='/': retur...
def sqrt1(A): if A==2 or A==1: return 1 arr = [0]*(A+2) for i in range(0,A+2): arr[i] = i*i start = 0 end = len(arr)-1 while(start+1<end): mid = start + (end+start)/2 if(arr[mid]==A): return mid if(arr[mid]>A): end = mid elif(arr[mid]<A): start = mid return start def sqrt2(A): if A == 1...
def insertion_sort(arr): for i in range(1,len(arr)): value = arr[i] hole = i while(hole > 0 and arr[hole-1] > value): arr[hole] = arr[hole-1] hole -= 1 arr[hole] = value print arr arr = [1,5,3,8,6,54,2,4,23,532] insertion_sort(arr)
# @param A : tuple of integers # @return an integer def singleNumber(A): bits = [0]*32 for i in A: C = list(bin(i)) C = C[2:] C = C[::-1] print C index = 0 for i in C: #print i,bits[index] bits[index] = bits[index]^int(i) index += 1 bits = bits[::-1] print bits result = "" for i in bits: ...
def binary_search(arr,start,end,searchItem): if (start <= end): middle = (start+end)//2 if (searchItem == arr[middle]): print "Found at: " + str(middle) elif (searchItem > arr[middle]): binary_search(arr,middle+1,end,searchItem) elif (searchItem < arr[middle]): binary_search(arr,start,middle-1,searchI...
''' COMP4290 Group Project Team: On Course Alexander Rowell (z5116848), Eleni Dimitriadis (z5191013), Emily Chen (z5098910) George Fidler (z5160384), Kevin Ni (z5025098) courseEnrollment.py Implementation of the CourseEnrollment class, which represents an enrollment in a course. This contains the course enrolled in an...
#!/usr/bin/python3 def no_c(my_string): new_string = my_string[:] for c in my_string: if (c is 'c' or c is 'C'): idx = new_string.index(c) new_string = new_string[:idx]+new_string[idx + 1:] return new_string
#!/usr/bin/python3 def complex_delete(a_dictionary, value): if a_dictionary is None: return None keys = list(a_dictionary.keys()) for k in keys: if a_dictionary[k] is value: a_dictionary.pop(k, None) return a_dictionary
#!/usr/bin/python3 def best_score(a_dictionary): if a_dictionary is None or len(a_dictionary) is 0: return None best = next(iter(a_dictionary)) max = a_dictionary[best] for k in a_dictionary.keys(): if a_dictionary[k] > max: max = a_dictionary[k] best = k retu...
#!/usr/bin/python3 """ Singly linked list class Node and class SinglyLinkedList """ class Node: """Node class""" def __init__(self, data, next_node=None): self.data = data self.next_node = next_node @property def data(self): return self.__data @data.setter def data(s...
#!/usr/bin/python3 def uppercase(str): nstr = "" for i in range(len(str)): if (str[i].islower()): nstr += chr(ord(str[i]) - 32) else: nstr += str[i] print("{}".format(nstr))
from tkinter import* root = Tk() #creating a label widget myLabel1=Label(root,text="Hello world!") #putting it onto the screen #myLabel.pack() myLabel2=Label(root,text="My name is XYZ") myLabel1.grid(row=0,column=0) myLabel2.grid(row=1,column=0) myLabel3=Label(root,text="Here we go....").grid(row=2,column=0) root.mainl...
# Thomas O'Brien ID 10354795 # Calculator UI program # this program sets up a Class called Calculator that can be called from other programs to run calculations. # The algroithm for each type of calculation is defined as a function that can be called from other programs. # The maths function is imported to program so...
#!/usr/bin/python # another toy rot toy for use with any char-replacement cipher import sys myROT = 13 if (len(sys.argv) > 1 and sys.argv[0] == '-r'): snothing = sys.argv.pop(0) myROT = sys.argv.pop(0) a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # Reversed Alphbet #b = "zyxwvutsrqponmlkjihgfe...
#!/usr/bin/env python # coding: utf-8 # In[ ]: #*--Honeywell Hackathon--* # In[280]: import numpy as np import os import queue as Q import time from IPython.display import clear_output # In[281]: MALL_SIZE = 12 # In[327]: # Random Mall Scenario def display(mall_size,route,shops,final=None,initial=None,E...
from collections import OrderedDict tc=int(input()) for i in range(tc): a=input() my_list="" for j in range(0,len(a),2): my_list+=((a[j])) my_list+=(a[len(a)-1]) print(my_list)
""" @jetou @date : 2017/12/10 @algorithms: red_black_tree """ class Node: def __init__(self, key, left=None, right=None, color=None, p=None): self.color = color self.key = key self.left = left self.right = right self.p = p if key == "Nil": self.p = self ...
"""Description: brain even game functions.""" from random import randint DESCRIPTION = 'Answer "yes" if number even otherwise answer "no".' def is_even(number): """Is even.""" return (number % 2) == 0 def make_question(): """Asks question. :return: expression, result """ number = randint(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 29 10:32:19 2020 @author: davidnelson This code attempts to adapt the following tutorial from The Programming Historian to the Beehive data set. https://programminghistorian.org/en/lessons/exploring-and-analyzing-network-data-with-python """ # ste...
def conditional_branch(abc): """ 入力文に特定の文字が含まれている場合に条件にあった文を出力する。 注意:入力文が複数の条件を満たす場合は最初に記述された条件が適用される。 例:入力文:bac ---> 出力文:aが含まれています。 """ if 'a' in abc: print("aが含まれています。") elif 'b' in abc: print("bが含まれています。") elif 'c' in abc: print("cが含まれています。") else: ...
# 简单的端口扫描工具 # 作者: Charles # 公众号: Charles的皮卡丘 import time import socket import threading # 端口扫描工具 class scanThread(threading.Thread): def __init__(self, ip, port_min=0, port_max=65535): threading.Thread.__init__(self) assert isinstance(port_max, int) and isinstance(port_min, int) self.ip = ip self.port_min = ...
class Human(): def __init__(self, name, weight): print("__init__실행") self.name = name self.weight = weight #def __str__(self): # return "{} (몸무게 {}kg)".format(self.name, self.weight) def eat(self): self.weight += 0.1 print("{}가 먹어서 {}kg이 되었습니다.").format(s...
#!/usr/bin/python3 import time import interesting_number import is_alphanumeric_only import missing_letter import move_zeros import pig_latin import valid_ip def main(): # Init Variables Used To Test letter_test = ["a", "b", "c", "e", "f"] zeros_test = ['a', 3, 5, 0, 1, 1, 3, 5, 0, 0, 0, 7, 9] interes...
class Board: ####how to access instace variables within a class def __init__(self, arr): self.state = arr def swap(self,arr,x,y): arr1 = list(arr) arr1[x], arr1[y] = arr1[y], arr1[x] return(arr1) def neighbors(self): neighbor = [] stt1 = list(self.state) ...
import sys class Node: def __init__(self, name, toll): self.name = name self.toll = int(toll) self.path = self.toll self.next = None self.visited = False self.first = 0 self.second = 0 self.parents = set() topo_list = [] def topo_sort(city_set): ...
import json __all__ = ['load_json_from_file', 'load_json_from_string'] def load_json_from_file(file_path): """Load schema from a JSON file""" try: with open(file_path) as f: json_data = json.load(f) except ValueError as e: raise ValueError('Given file {} is not a valid JSON f...
#!/usr/bin/env python # coding=utf-8 """ In order to run this program, you need to - install [tensorflow](https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#virtualenv-installation). - get an monitor to display the figure. """ import tensorflow as tf import numpy as np # Produce num_points [x_dat...
def year_balance(b, r, p): for i in range(1, 13): ub = b - p b = ub + r * ub return b b = float(balance) r = float(annualInterestRate) / 12.0 maxp = int(year_balance(b, r, 0.0) / 12) for p in range(0, maxp + 10, 10): if year_balance(b, r, p) <= 0: print "Lowest Payment: %d" % p ...
mac_os = 300 if mac_os < 200: print("you are less than 200") if mac_os < 150: print("you are less than 150") elif mac_os < 100: print("your number less than 100") else: print("your number is more") elif mac_os > 200: print("you are greater than 100") if mac_os == 40: ...
#/usr/bin/python languages = {"python":".py",'shell':'.sh',"java":".java"} print(languages,type(languages),id(languages),dict(enumerate(languages)),len(languages)) print("") print("printing only keys:",languages.keys()) print("") print("printing only values:",languages.values()) #print("calling only one key:",language...
#Note:part of elif we can check multiple expressions and conditions #Note:suppose if condition fails then go to elif condition if again fails then go to next elif condition course = input("what course are you doing ") if course == "python": print("you are doing python course and do more practise") elif course == "...
import re str = "we are staying in Bangalore,karnataka 08" test = re.findall("Bangalore",str) print(test) #search test1 = re.search("\d",str) #If no matches are found,then it will return as None print(test1) #split the string at every white-space character: test2 = re.split("\s",str) print(test2) #split the string a...
#/usr/bin/python tup1 = ("dharmala","""manohar""",1982,2010,19.5) #we can use combination of strings and numbers tup2 = 10,20,30,40,50 #need to use comma separator for tuple print(tup1,tuple(enumerate(tup1)),type(tup1),id(tup1)) print("\n") print(tup2,tuple(enumerate(tup2)),type(tup2),id(tup2)) print("\n") p...
#Iterate through the items and print the values: thistuple = ("apple","mango","guava") for x in thistuple: print(x) #Check if item exists thistuple = ("apple","mango","guava") if "apple" in thistuple: print("yes,its exists") thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets p...
""" data = int(input("enter one number:")) while data < 10: print("enter the data:",data) data = data +1 print("you are out of while loop:") """ password = "" while password != 'redhat': password = input("please enter admin password:").strip().lower() if password == 'redhat': print("you entered ...
#Default argument: Default argument is an argument and assumes a value if value not provided by function call argument #if we prpvide values in caller in will accept otherwise it will take default values #if we provide deafult value in function ,no need to call again #Example:1 #Creating a function def name1(firstname...
import re #Example-1(Find out correct format phone no's using \w) phonenos = "408-205-9015,408-215-9165,aaa-bbb-cccc" phnno = re.findall("\w{3}-\w{3}-\w{4}",phonenos) for phnno1 in phnno: print(phnno1) #Example-2(Find out correct format phone no's using \d) phone = "408-205-9015,aaa-bbb-cccc" phn = re.findall("\d{...
""" Lambda"Keyword syntax: lambda arag1 +arg2 : expression """ product = lambda arg1,arg2,arg3,arg4:arg1 + arg2 + arg3 + arg4 print(product(1,2,3,4)) #Scope of Variables """ 1. Local Variables 2. Global Variables """
""" 1. Required Arguments 2. Default Arguments 3. Keyword Arguments 4. Variable-length Arguments """ #1. Required Argument #Required Arguments which send correct positional order means function call and function definition should match exactly def name(firstname,middlename,lastname): 'Required Arguments' print(...
""" name = "Guido Van Rossum" print("Lower method:",name.lower()) #convert all chars in lower case. print("") print("Upper case method:",name.upper()) #conevrts all cahrs in upper case print() print("Replace method:",name.replace("Van","Ben")) #replace with other chars print() print("Split method:",name.split(",")) ...
""" #Method-1 #creating a function def course(parameters): print(parameters) #part of course function return parameters #No argument in return means NONE #calling a function a=course('python') print(a) #Method-2 def name(firstname): print(firstname) name('manohar') """ #Method-3 #Creating a function def...
''' Matrix Search Given a matrix of integers A of size N x M and an integer B. Write an efficient algorithm that searches for integar B in matrix A. This matrix A has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than or equal to the last integer...
''' Unique Binary Search Trees II Given an integer A, how many structurally unique BST's (binary search trees) exist that can store values 1...A? Problem Constraints 1 <= A <=18 Example Input Input 1: 1 Input 2: 2 Example Output Output 1: 1 Output 2: 2 ''' # We need to check with putting x elements on left...
''' Array 3 Pointers You are given 3 sorted arrays A, B and C. Find i, j, k such that : max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized. Return the minimum max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])). Problem Constraints 0 <= len(A), len(B), len(c) <= 106 0 <= A[i], B[i], C[i] <= ...
''' Populate Next Right Pointers Tree Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all n...
''' Fibonacci Number Given a positive integer N, write a program to find the Ath Fibonacci number. In a Fibonacci series, each term is the sum of the previous two terms and the first two terms of the series are 0 and 1. i.e. f(0) = 0 and f(1) = 1. Hence, f(2) = 1, f(3) = 2, f(4) = 3 and so on. NOTE: 0th term is 0. 1th...
''' Different Bits Sum Pairwise We define f(X, Y) as number of different corresponding bits in binary representation of X and Y. For example, f(2, 7) = 2, since binary representation of 2 and 7 are 010 and 111, respectively. The first and the third bit differ, so f(2, 7) = 2. You are given an array of N positive inte...
''' Single Element in a Sorted Array Given a sorted array of integers A where every element appears twice except for one element which appears once, find and return this single element that appears only once. NOTE: Users are expected to solve this in O(log(N)) time. Problem Constraints 1 <= |A| <= 100000 1 <= A[i] <=...
''' Sort Array in given Order Given two array of integers A and B, Sort A in such a way that the relative order among the elements will be the same as those are in B. For the elements not present in B, append them at last in sorted order. Return the array A after sorting from the above method. NOTE: Elements of B are ...
''' Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. Note: The test cases are generated in the following format (use the following format to use See Expected Output option): First integer N is the number of nodes. Then, N intgers follow denoting the label (or ...
''' Greatest Common Divisor Given 2 non negative integers A and B, find gcd(A, B) GCD of 2 integers A and B is defined as the greatest integer g such that g is a divisor of both A and B. Both A and B fit in a 32 bit signed integer. constraints: 0 <= A, B <= 109 input: A = 4 B = 6 output: 2 input: A = 6 B = 7 ou...
''' Kth Smallest Element In Tree Given a binary search tree represented by root A, write a function to find the Bth smallest element in the tree. Problem Constraints 1 <= Number of nodes in binary tree <= 100000 0 <= node values <= 10^9 Example Input Input 1: 2 / \ 1 3 B = 2 In...
''' Maximum Absolute Difference You are given an array of N integers, A1, A2, .... AN. Return the maximum value of f(i, j) for all 1 ≤ i, j ≤ N. f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x. Constraints: 1 <= N <= 100000 -109 <= A[i] <= 109 input: [1, 3, -1] output: 5 input: [...
''' Passing game There is a football event going on in your city. In this event, you are given A passes and players having ids between 1 and 106. Initially some player with a given id had the ball in his possession. You have to make a program to display the id of the player who possessed the ball after exactly A passe...
''' Vertical Order traversal Given a binary tree, return a 2-D array with vertical order traversal of it. NOTE: If 2 Tree Nodes shares the same vertical level then the one with lesser depth will come first. Problem Constraints 0 <= number of nodes <= 105 Example Input Input 1: 6 / \ 3 7 / \ ...
''' Maximum Sum You are given an array A of N integers and three integers B, C, and D. You have to find the maximum value of A[i]*B + A[j]*C + A[k]*D, where 1 <= i <= j <= k <= N. Problem Constraints 1 <= N <= 10^5 -10000 <= A[i], B, C, D <= 10000 Example Input Input 1: A = [1, 5, -3, 4, -2] B = 2 C = 1 D = -1 ...
''' Count Right Triangles Given two arrays of integers A and B of size N each, where each pair (A[i], B[i]) for 0 <= i < N represents a unique point (x, y) in 2D Cartesian plane. Find and return the number of unordered triplets (i, j, k) such that (A[i], B[i]), (A[j], B[j]) and (A[k], B[k]) form a right angled triangl...
''' Matrix and Absolute Difference Given a matrix C of integers, of dimension A x B. For any given K, you are not allowed to travel between cells that have an absolute difference greater than K. Return the minimum value of K such that it is possible to travel between any pair of cells in the grid through a path of adj...
''' Trailing Zeros in Factorial Given an integer A, return the number of trailing zeroes in A! i.e. factorial of A. Note: Your solution should run in logarithmic time complexity. Problem Constraints: 1 <= A <= 109 Input 1 A = 5 Input 2: A = 6 Output 1: 1 Output 2: 1 ''' class Solution: # we count all 5s in the...
''' Level Order Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). Problem Constraints 1 <= number of nodes <= 105 Example Input Input 1: 3 / \ 9 20 / \ 15 7 Input 2: 1 / \ 6 2 / 3 Example Output Output 1: [ ...
''' Merge Intervals Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Constraints: 1 <= |intervals| <= 105 Input: Given intervals [1, 3], [6, 9] insert and merge [2, 5] Outpu...
''' Bob and Queries Bob has an array A of N integers. Initially, all the elements of the array are zero. Bob asks you to perform Q operations on this array. You have to perform three types of query, in each query you are given three integers x, y and z. if x = 1: Update the value of A[y] to 2 * A[y] + 1. if x = 2: Upd...
import math def root2(a,b,c): t = b*b - 4*a*c t2 = math.sqrt(t) if t>0 else complex(0,math.sqrt(abs(t))) ##因為複數的英文就是 complex number,所以在Python要表示複數就可以使用:complex(x, y)來表示。x代表實部的數字,y代表虛部的數字。 return [(-b+t2)/(2*a), (-b-t2)/(2*a)] print("root of 1x^2+4x+0=", root2(1,4,0))
def raizQuadrada(num): valorRaiz = 1 while((valorRaiz*valorRaiz) <= num): if((valorRaiz*valorRaiz) == num): return valorRaiz elif((valorRaiz*valorRaiz) > num): return valorRaiz-1 else: valorRaiz+=1 print(raizQuadrada(4)) print(raizQuadrada(9)) print...