text
stringlengths
37
1.41M
import unittest from tests import unit_case_example TestMethod = unit_case_example.UnitCaseExample() class RunUnitCaseExample(unittest.TestCase): def setUp(self): print('Start TensorMSA') def tearDown(self): print('Finish TensorMSA') def test_returnValue(self): self.assertEqual(...
##Problem Set 3 #Name: Arianna O'Brien Cannon #Time Spent: 20 mins #Last Modified: 9/23/19 #def main def main (): #create empty dictionary empty_dict = {} #make actual dictionary dict_1 = {'Jeff Bezos & family':160, 'Bill Gates':97, 'Warren Buffett':88.3, 'Mark Zuckerberg':61, 'Larry Ellison':58.4, 'Larry Page':5...
class SampleClass(): def __init__ (self, param2, param2): self.param1 = param1 self.param2 = param2 def some_method(self): print(self.param1) class Dog(): species = 'mammal' def __init__(self, breed, name, spots): self.breed = breed self.name = nam...
''' pyhton3 实现多进程方式: 1. Unix/Linux/MacOS 独有的方式:os模块中的fork 2. 跨平台方式:使用multiprocessing模块 ''' # os 模块中的 fork 方法来源于Unix/Linux系统中的fork系统调用,调用一次返回两次。原因是当前进程复制出一份几乎相同的子进程, # 子进程永远返回0,而当前进程(父进程)返回子进程的ID,注意不要与os.getpid()弄混淆 import os if __name__ == '__main__': print('current Process (%s) start ...' % (os.getpid())) # os....
def count_words(text): """ Count and returns the number of words in a string. The counting is performed iterating over the characters in the text and counting the number of times that an space character (space, tabs, new lines) is preceeded by a non-space character. Args: text (str)...
rango_inferior = int(input('Ingresa un rango inferior: ')) rango_superior = int(input('Ingresa un número mayor al anterior: ')) comparacion = int(input('Ingresa un número de comparación: ')) while (comparacion < rango_inferior) or (comparacion > rango_superior): print('El número ' + str(comparacion) + ' no está en...
class Polynomial: def __init__(self, coeffs): if not isinstance(coeffs, list): raise TypeError("Coeffs not list or constant") for i in coeffs: if type(i) is not int and type(i) is not float: raise TypeError("Coeffs not int or float") self.co...
import sys def anagram(string): ''' Observación clave: Si no hay anagramas de longitud uno, no hay anagramas de longitud mayor a uno con esa letra. ''' anagrams = dict() moreTone = 0 for c in string: if c in anagrams: anagrams[c] = anagrams[c] + 1 mo...
# make a closest number function to find out which two pairs have the smallest difference # Author: Wanjiru Wang'ondu # # # first, we create an array # array_one = [1, 2] # 3, 66, 77, 8, 9, 12] # array_differences = {} # # # def find_differences(array, diff_array): # for i in array: # for j in array: # ...
# -*- coding: utf-8 -*- from Conta import * conta1 = Conta(123, 'lucas', 100, 100) conta2 = Conta(113, 'luis', 120, 140) # conta1.extrato() # conta2.extrato() # conta1 = None -> Apaga a referencia entre a variavel e o objeto # conta1.extrato() Após apagar a referencia, nao existe mais esse endereco """from datas ...
''' mock 1.接口测试的测试场景比较难模拟,需要大量的工作才能做好 2.该接口的测试,依赖其他模块的接口,依赖的接口尚未开发完成 测试条件不充分,怎么开展接口测试 使用mock模拟接口的返回值 ''' import requests from unittest import mock ''' 支付接口:http://www.zhifu.com/ 方法:post 参数:{"订单号":“12345”,"支付金额":20.56,"支付方式":"支付宝/微信/余额宝/银行卡"} 返回值:{"code":200,"msg":"支付成功"}、{"code":201,"msg":"支付失败"} 接口尚未实现 ''' class Pay...
def seqSearchLast(myList, target): for i in range(len(myList)-1, -1, -1): if myList[i] == target: return i return None def trinarySearch(myList, target): low = 0 high = len(myList)-1 while low <= high: oneThird = low + (high - low)/3 twoThirds = high - (high - l...
#tuple creation bra=("CSE","IT","Mech","ECE","CSE") #print print(bra) #Data type of bra print(type(bra)) #size of tuple print("Size of tuple is: {}" .format(len(bra)))#4 #Max element max_ele=max(bra) print("Max element is %s" %(max_ele)) #Min element min_ele=min(bra) print("Min element is %s" %(min_ele)) ...
class Set: def __init__(self, value = []): # Constructor self.data = [] # Manages a list self.concat(value) def intersection(self, other): # other is any sequence res = [] # self is the subject for x in self.data: if x ...
x=raw_input y=int(x) if x=str(::-1): print("x is polindram") else: print("x is no ploindram")
#!/usr/bin/env python # coding: utf-8 # In[ ]: cars = 100 # we put a value into a variable space_in_a_car = 4.0 # we put a value into a variable drivers = 30 # we put a value into a variable passengers = 90 # we put a value into a variable cars_not_driven = cars - drivers # We define a variable using two other varia...
class Atm(object): """ Error- <bound method Atm.BalanceEnquiry of <__main__.Atm object at 0x000002BCE4ED7FA0>> """ # Ma'am pls help me with this error def __init__(self,cardNumber,pinNumber): self.cardNumber = cardNumber self.pinNumber = pinNumber def CashWithd...
shopping_list=['milk', 'bananas', 'bread', 'bread', 'books'] new_item = input('What would you like to add to your shopping list?') shopping_list.append(new_item) shopping_list.insert(0,'impulse buy') print("Items in your shopping list:\t",shopping_list) del shopping_list[0] print(shopping_list) shopping_list.pop(1) pri...
age=0 if age<2: print('baby') elif age>=2 and age<4: print('toddler') elif age>=4 and age<13: print('kid') elif age>=13 and age<20: print('teenager') elif age>=20 and age<65: print('adult') elif age>=65: print('elder')
#Python strings are very flexible, but if we try to create a string that occupies multiple lines we find ourselves face-to-face with a SyntaxError. Python offers a solution: multi-line strings. By using three quote-marks (""" or ''') instead of one, we tell the program that the string doesn’t end until the next triple-...
from __future__ import print_function, division from main import * from pylab import * ''' This file is used to test different starting conditions on the iterative algorithm. Here I was using the approach of first creating zeros, expanding them and then checking the solved zeros against the original zeros. ''' if __na...
#I'm using Python 2.x. #The following import makes division work as in Python 3. Thus 2/3=0.66666.... #rather than 2/3=0 (in Python 2 division between integers yields an integer; #Python 3 has the additional operator // for integer division) from __future__ import division from pylab import * from scipy.linalg import ...
import math x,y = map(int,input().split()) f = y*math.log(x) s = x*math.log(y) if f<s: print("<") elif f>s: print(">") else: print("=")
import sense_hat from time import sleep, time from random import randint sense = sense_hat.SenseHat() sense.clear() """ Make your Sense HAT into a Flappy HAT! Help the bird fly though the columns. Each column is one point. How many points can you get? Read through the code to learn how the game is made ...
def rec(n, i): value="" #1 BigO Runtime if i<len(b)-1: value=rec(n,i+1) return value+" "+n[i] a="awesome is This" b=a.split(' ') print(rec(b,0)) #BigO Runtime 1 value <- empty value if i < length of b then - 1 value <- REC return value a <- user input b <- function to reverse s...
# 条件分岐その2: 「もし○○なら、☆☆、そうでなければ△△」(if-else) # score = 80 # # if score >= 70: # print('Great!!') # else: # print('So so') # 条件分岐その2: 「もし○○なら、☆☆、 # そうでなくて□□なら×× # どれでもなければyy」(if-elif-else) score = 40 if score >= 70: print('Great!!') elif score >= 40: print('So so') else: ...
import matplotlib.pyplot as pyplot from sklearn.cluster import KMeans def k_means_clustering(X, k=None): pyplot.figure() #pyplot.scatter(X[:, 0], X[:, 1], label='True Position') if k is None: kmeans = KMeans() else: kmeans = KMeans(n_clusters=k) kmeans.fit_predict(X) pyplot....
# 1. Loops """ 1. for 2. while """ price_list = [] # Initialization : 0 is like i=0 i=0 #print("Break Loop") # Condition : 100 is like i<100 while(i<100): price_list = price_list + [i] # Incrementation : 1 is like i++ i = i + 1 # if (i==50): # print("Break") # break print(price_list) ...
# 1. Exception Handling """ 1. try 2. except 3. finally """ # Simple try-except block personal_details = {"name":"csk","age":25} # Error - KeyError #print(personal_details["city"]) try: print(personal_details["city"]) except(KeyError,AttributeError) as err: personal_details["city"] = "Bangalore" print("...
# array|list #element list of array with same data types element_list = ["apple","orange","grapes"] # element list of array with different data types element_list_mutiple_dt = ["apple","orange","grapes",12,2.5] # index starts from zero print(element_list[0]) print(element_list_mutiple_dt) # numeric list age_list = [...
#x^2+bx+c=0 import math as m a = int(input("Ведите значение а: ")) b = int(input("Ведите значение b: ")) c = int(input("Ведите значение c: ")) if a == a and b == b and c == c: (d) = b * b - 4 * a *c elif a == -a and b == -b and c == -c: (d) = -b *(-b) - 4 * (-a) * (-c) else: print("Ошибка!") ...
# 此处可 import 模块 """ @param string line 为单行测试数据 @return string 处理后的结果 """ def solution(line): char_list = line.split(',') #先找最大的正数 max = 0 for i in char_list: num = int(i) if num > max: max = num bucket = list(range(max+1)) for i in range(max+1): bucket[i] = 0...
def solution(line): stack = [] for char in line: if char == '(': stack.append(char) continue elif char == '[': stack.append(char) continue elif char == '{': stack.append(char) continue elif char == ')': ...
import turtle import random playrone=turtle.Turtle() playrone.color("green") playrone.shape("turtle") playrone.penup() playrone.goto(-200,100) playrtwo=playrone.clone() playrtwo.color("blue") playrtwo.penup() playrtwo.goto(-200,-100) playrone.goto(300,60) playrone.pendown() playrone.circle(40) playrone.penup() playrone...
# pygameBaseClass.py # by David Simon (dasimon@andrew.cmu.edu) # Nov 2014 # # Changes: # - Added EXIT condition to allow game to exit # - Created runAsChild method to allow for nested game objects (menu, game) import pygame from pygame.locals import * class PygameBaseClass(object): """Provides a framework for gam...
# 6.00 Problem Set 8 # # Name: # Collaborators: # Time: import numpy as np import random import matplotlib.pyplot as plt from ps7 import * # # PROBLEM 1 # class ResistantVirus(SimpleVirus): """ Representation of a virus which can have drug resistance. """ def __init__(self, maxBirthProb, cle...
import sys import math name=input("Please enter your name") while name.isalpha()==False or len(name)<4 : if ' ' in name : break else: print("THE NAME YOU ENTERED IS INCORRECT") name=input('Enter name again') print("WELCOME! NOW YOU ARE READY TO USE CALCULATOR \n YOU HAVE FOLLOWING OPTIONS") ...
""" This file presents how to create a SATModel, add variables, add constraints and solve the model using the SolveEngine python interface """ from pysolveengine import SATModel, SEStatusCode, SolverStatusCode ###################################### # create SAT model # # the token token = "#2prMEegqCAFB5eqmfuXmGufyJ+P...
#!/usr/bin/env python user_choice = "1" amount_of_choices = 1 def showMenu(): while True: print("What sorting algorithm do you want to use?") print("[1] Bubble Sort") # user_choice = input() if (user_choice == "1"): return "bubble" break
entrada = int(input("Entrada:")) p = int(input("p:")) q = int(input("q:")) n = int(input("n:")) e = int(input("e:")) d = int(input("d:")) c = (entrada ** e) % n print(entrada ** e) print("RSA: {}".format(c)) d = (c ** d) % n print(c ** d) print("Des-RSA: {}".format(d))
import matplotlib.pyplot as plt import numpy as np import pandas as ps # load data 人口与收入的关系 path = 'resource/all_work_code/exerise1/ex1data1.txt' data = ps.read_csv(path, header=None, names=['Population', 'Profit']) # print(data.head()) # 绘图 data.plot(kind='scatter', x='Population', y='Profit', figsize=(12, 8)) plt.s...
#!/usr/bin/env python3 import cards import sys import random import time deck = cards.Cards() turn = "user" faceCards = ['K', 'Q', 'J', 'A'] regCards = [2, 3, 4, 5, 6, 7, 8, 9, 10] numStrings = ['two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] faceStrings = ['King', 'Queen', 'Jack', 'Ace'] face...
import pickle class STUDENT: def __init__(self): self.RNO=0 self.NAME="" self.STREAM="" self.PERCENT=0.0 def ACCEPT(self): self.RNO=input("Enter Roll no:") self.NAME=raw_input("Enter Name:") self.STREAM=raw_input("Enter ...
while True: a=int(input("Enter a Number:")) b=int(input("Enter the multiplying limit:")) for i in range(1,b+1,1): print a,"x",i,"=",a*i
L=[] m=int(input("Rows:")) n=int(input("Columns:")) for i in range(m): l=[] for j in range(n): x=int(input("Element:")) l.append(x) L.append(l) s=0 for l in L: for x in l: s+=x print "The sum of elements of a matrix is:",s
while True: L1=[] L2=[] L3=[] m=int(input("Enter the number of rows for Matrix 1:")) n=int(input("Enter the number of columns for Matrix 1:")) print p=int(input("Enter the number of rows for Matrix 2:")) q=int(input("Enter the number of columns for Matrix 2:")) for i in range(m): ...
while True: dict1={'jayant':7860372413,'suryansh':9837407901,'yohen':8527247495,} name=raw_input("Enter the name of the Customer:") print dict1[name.lower()],"is the telephone number of",name
import matplotlib.pyplot as plt """ Function: plotLoss ============== Plots the loss and save it at the location given. ============== input: data: loss data save_location: location to save figure output: None """ def plotLoss(data, save_location): fig, ax = plt.subplots(nrows=1, ncols=1) ax.plot(d...
def maximum(dice, faces): return dice * faces def avg(dice, faces): mode = float((dice / 2)) + float((dice * faces) / 2) if mode % 1 == 0: return int(mode) else: mode -= 0.5 average = f"{int(mode)} or {int(mode + 1)}" return average def permutation_count...
import math import numpy as np import matplotlib.pyplot as plt ########################################################################## # Some Class Definitions ######################################################################### class Neuron: def __init__(self, weights, bias, layer, previous, final = Fals...
# Print lines from file try: with open(r"e:\classroom\python\june11\names.txt", "rt") as f: print(type(f)) for n in f.readlines(): print(n, len(n)) except: print("Sorry! Could not read file!")
def iseven(n): return n % 2 == 0 nums = [10, 11, 15, 20] evennums = filter(iseven, nums) oddnums = filter(lambda n: n % 2 == 1, nums) for n in evennums: print(n) for n in oddnums: print(n)
def add(*nums, display = False ): sum = 0 for n in nums: if display: print(n) sum += n return sum print(add(10, 20, 1, 2, 3, display=True)) print(add(10, 20, 1, 2, 3))
def add(n1, n2 = 0): return n1 + n2 print(add(10, 20)) print(add(10)) # print(add()) print ( add (10,n2 = 100)) print ( add (n2 = 100,n1 = 10))
# This program says hello and asks for my name. print('Hello World!') print('What is your favorite food?') food=input() print("Same here! I love " +food)
from common.iterable_tools import IterableHelper list01 = [62, 3, 9, 33, 56, 12, 332, 395] def find01(): for item in list01: print(item % 2) # find01() def find02(): for item in list01: if item % 3 == 0 or item % 5 == 0: yield item def cond01(num): return num % 2 != 0 ...
import wikipedia # https://github.com/goldsmith/Wikipedia def search_wikipedia(query): results = [] keyword = query['keyword'] wiki_pages_names = wikipedia.search(keyword) if (len(wiki_pages_names)): for wiki_page_name in wiki_pages_names: try: summary = wikipedi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 3 23:15:42 2020 @author: aaron """ # To run code in PyCharm console, highlight and press ⌥⇧E (option shift E) # Data Preprocessing import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_c...
# To run code in PyCharm console, highlight and press ⌥⇧E (option shift E) # Data Preprocessing import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Section 5 - Multiple Linear Regression/50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.ilo...
# Operation for sorting whole numbers def countingSort(arry): # O(n) time and space operation outputArray = arry.copy() # O(n) time operation maxNum = max(arry) # O(max(arry) time and space operation) countArray = [0] * (maxNum + 1) # O(n) time and space operation cumulativeArray = count...
# Author: Fionn O'Reilly # Filename: Bank_System.py # Description: Presenting the user with a menu to create/close a bank account, # withdraw or deposit from/to account, or print details of all accounts. # Program reads current bank account details from a file and separates them into lists. # ...
class Solution: def removeElement(self, nums: List[int], val: int) -> int: while val in nums: nums.remove(val) int_len = len(nums) # This is for check! print(nums) print(int_len) return int_len
import unittest import binaryLCA # inherited Node from binaryLCA to avoid typing binaryLCA again and again. Additionally it was an excuse to practice inheritance. class Node(binaryLCA.Node): def __init__(self, value): super().__init__(value) class TestLCA(unittest.TestCase): def test_BasicTree(self...
### Mortgage Calculator App ### print("|~~~~~~~~~~Mortgage Calculator App~~~~~~~~~|") print('\n') interest =(float(input('Enter your present loan interest rate: %'))/100)/12 years =float(input('Enter the term of loan (years): '))*12 amount =float(input('Enter the amount of loan after put down-payment: $')) numerator ...
# -------------- # Code starts here class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2=['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove( 'Carla Gentry') print(new_class) ...
''' List 특징 - 1차원 배열 구조 형식) 변수 = [값1, 값2, ...] - 다양한 자료형 저장 가능(R의 벡터는 한 벡터 내에 하나의 자료형만 저장 가능했음) - index 사용, 순서 존재 형식) 변수[index], index=0부터 시작 - 값 수정(추가, 삽입, 수정, 삭제) ''' # 1. 단일 list lst = [1,2,3,4,5] print(lst, type(lst), len(lst)) for i in lst : # print(i, end=' ') # 1 2 3 4 5 print(lst[i-1:]) # ...
''' 문2-1) 다음 벡터(emp)는 '입사년도이름급여'순으로 사원의 정보가 기록된 데이터 있다. 이 벡터 데이터를 이용하여 사원의 이름만 추출하는 함수를 정의하시오. # <출력 결과> names = ['홍길동', '이순신', '유관순'] ''' from re import findall, sub # <Vector data> emp = ["2014홍길동220", "2002이순신300", "2010유관순260"] ''' # 함수 정의 def name_pro(emp): names = [sub('\\d{3,}','', emp)] retu...
''' 재귀호출(recursive call) - 함수 내에서 자신의 함수를 반복적으로 호출하는 기법 - 반복적으로 변수의 값을 조정해서 연산 수행 ex) 1~n (1+2+3+4+...n) - 반드시 종료조건이 필요하다. ''' # 1.카운터 : 1~n def Counter(n): if n == 0 : # 종료조건 print("프로그램 종료") return 0 else : Counter(n-1) # 재귀호출 Counter(0) def Counter(n): if n == 0 : # 종료...
''' 제어문 : 조건문(if), 반복문(while, for) python 블럭 : 콜론과 들여쓰기 형식1) if 조건식 : 실행문 실행문 ''' var = 10 if var>= 10 : print("var =", var) print("var는 10보다 크거나 같다.") print("항상 실행되는 영역") ''' 형식2) if 조건식: 실행문1 else : 실행문2 ''' var = 2 if var >= 5 : print("var는 5보다 크거나 같다.") else : print("var는 5보다 작다...
''' <급여 계산 문제> 문) Employee 클래스를 상속하여 Permanent와 Temporary 클래스를 구현하시오. <조건> pay_pro 함수 재정의 ''' # 부모클래스 class Employee : name = None pay = 0 def __init__(self,name): self.name = name # 원형 함수 : 급여 계산 함수 def pay_pro(self): pass # 자식클래스 - 정규직 class Permanent(E...
''' step2 관련 문제 A형 문) vector 수를 키보드로 입력 받은 후, 입력 받은 수 만큼 임의 숫자를 vector에 추가하고, vector의 크기를 출력하시오. <출력 예시> vector 수 : 3 4 2 5 vector 크기 : 3 B형 문) vector 수를 키보드로 입력 받은 후, 입력 받은 수 만큼 임의 숫자를 vector에 추가한다. 이후 vector에서 찾을 값을 키보드로 입력한 후 해당 값이 vector에 있으면 "YES", 없으...
''' 문제2) 서울 지역을 대상으로 '동' 이름만 추출하여 다음과 같이 출력하시오. 단계1 : 'ooo동' 문자열 추출 : 예) '개포1동 경남아파트' -> '개포1동' 단계2 : 중복되지 않은 전체 '동' 개수 출력 : list -> set -> list <출력 예시> 서울시 전체 동 개수 = 797 ''' try : file = open("../data/zipcode.txt", mode='r', encoding='utf-8') lines = file.readline() # 첫줄 읽기 dongs = [] # 서울시 동...
class Dog: def __init__(self): self.nombre = "" self.edad = None self.peso = None def ladrar(self): if self.peso == None: print("Soy un fantasma") return if self.peso >=8: print("GUAU, WOOF") else: print("guau, woof") ...
from turtle import Turtle START_X_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] MOVE_DISTANCE = 20 UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 class Snake: def __init__(self): self.snake_segments = [] """Each snake chunk (yummy). Increases by one segment for every food piece eaten.""" self.create...
import random # HERO class. Stores the hero abilities, armors, calculates attack and defense values, how to deal damage, adding of kills class Hero: def __init__(self, name, health = 100): self.abilities = list() self.name = name self.armors = list() self.start_health = health ...
from copy import copy class Vehicle(object): def __init__(self, ID=0, vType=0, zipcode=00000, availability=True): self.ID = ID self.vType = vType self.zipcode = zipcode self.availability = availability def relocate(self, newZipcode): self.zipcode = n...
print("---Python Basic Data Type---") print("---number---") x = 3 print(type(x)) print(x) print(x ** 2) #没有x++ x--这种操作符 y = 2.5 print(type(y)) print(x, y) print("---boolean---") t = True f = False print(type(t)) print(t and f) print(t != f) print(f) print("---string---") hello = 'hello' world = "world" print(hello) pri...
''' handles direct communication with the server loggin in, fetching api data, downloading images etc. ''' import urllib import urllib2 from urllib2 import URLError, HTTPError import json import settings class Request: def __init__(self, persistence_data): pass def connect_to_server(self, username, password): ...
import random guesses_left = 10 list_word = ["gucci", "polo", "versace", "armani", "obey", "nike", "jordan", "supreme", "stussy", "bape", "addidas"] random_word = random.choice(list_word) letters_guessed = [] ranged_word = len(random_word) print(random_word) guess = "" correct = list(random_word) guess = "" while gu...
def fact(n): if n == 0: f = 1 else: f = 1 for i in range(1, n + 1): f *= i yield f for el in fact(5): print(el) #
'''SnakeGame.py By Tenzin Dophen, Adapted from Jed Yang 2017-03-15 This class contains objects which draws a body like a snake with a tail, which can be moved around by a user, using the arrows on the keyboards for direction. The snake can eat any objects(circles, supposed to be apples) also drawn in the class snake o...
def word_break(s: str, word_dict: [str]) -> bool: ok = [False] * (len(s)+1) ok[0] = True for i in range(1, len(s)+1): for w in word_dict: if i-len(w)>=0 and s[i-len(w):i] == w: ok[i] = ok[i-len(w)] if ok[i]: break return ok[-1] ####### print(word_break("catsandog", ["cats","dog","sand","and","cat"]...
def threeSumClosest(nums: [int], target: int) -> int: n = len(nums) nums.sort() minDist = float('inf') res = float('inf') for i in range(0, n-2): start, end = i+1, n-1 while start < end: tmp = target - (nums[i]+nums[start]+nums[end]) if abs(tmp) < minDist: res = nums[i]+n...
# 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: def visitTr...
# 322. Coin Change # Solution 1 - wrong answer # not valid when we don't need the biggest number to be divided first class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ coins = sorted(coins,reverse...
# 973. K Closest Points to Origin # Solution 1 # Time Complexity : O(n + nlogn) = O(nlogn) # 1, figure out each distance between origin and point.and make index & distance into dictionary. # 2, sort dictionary with values. # 3, Only pop k elements in the distance. # Beat 84.76% class Solution(object): def kCloses...
# 435.Non-overlapping Intervals #class Solution(object): # def eraseOverlapIntervals(self, intervals): def eraseOverlapIntervals(intervals): """ :type intervals: List[List[int]] :rtype: int """ if intervals == []: return 0 intervals = sorted(intervals, key=lambda i:i[1]) r...
def perm(list, start): if start == len(list)-1: #print("before append = ", perm_list) temp = [] for i in range(len(list)): temp += list[i] perm_list.append(temp) #print(list) #print("perm_list = ", perm_list) return for i in range(start, len(l...
# Two Sum """ Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. """ def twoSum(nums, target): res = [] for idx,num in enumerate(nums): for j in range(i...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- def heapAdjust(arr, s, length): temp = arr[s] child = 2 * s + 1 while child < length: if child + 1 < length and arr[child+1] < arr[child]: child = child+1 if arr[child] < arr[s]: arr[s] = arr[child] s = child...
import sys def main(): # get user input while True: # repeat while input is negative input_number = input("Enter a card number: ") length = len(input_number) if length >= 13 and length <= 16: # if input has a valid length break break elif length < 13: # length is...
# Created by: # Forrest W. Parker # 01/06/2017 # # Version 1.0 # 01/06/2017 ##### import math # Returns True if the string 'string' matches the pattern string 'patstring' # and returns False otherwise. # # Note that distinct characters of 'patstring' must correspond to # distinct substrings of 'string'. # (e.g. "a"...
import time def recursive_find(number, cur): if number > cur.value and cur.right != None: return recursive_find(number, cur.right) elif number < cur.value and cur.left != None: return recursive_find(number, cur.left) if number == cur.value: return True return False def find_r...
#Estructuras de Control #Autor: Javier Arturo Hernández Sosa #Fecha: 1/Sep/2017 #Descripcion: Curso Python FES Acatlán #sentencia IF,ELSE y ELIF edad = 10 if(edad<18): print("Eres un niño todavía") elif(edad>=18 and edad<40): print("Eres un adulto") elif(edad>=40 and edad<70): print("Ya estas viejo") e...
#Manejo de Archivos #Autor: Javier Arturo Hernández Sosa #Fecha: 24/Sep/2017 #Descripcion: Curso Python FES Acatlán ''' Los errores de sintaxis, también conocidos como errores de interpretación. ''' # prinCt("Hola") Ocurren cuando escribimos mal algo dentro del código ''' Excepciones, son errores que ocu...
#Ejercicios 1 #Autor: Javier Arturo Hernández Sosa #Fecha: 6/Sep/2017 #Descripcion: Curso Python FES Acatlán #Ver si un número es par o impar numero = int(input("Dame un número: ")) if((numero%2) == 0): print("El numero ingresado es par.") else: print("El número ingresado es impar") #Saber si una c...
from config.db import BASE ''' opcion = 1 usuarios = [] while opcion !=0: print('Selecciona una opción:') print('1. Registrar usuario') print('2. Inicio de sesión') print('0. Salir') opcion = int(input()) if opcion == 1: nombre = input('Ingrese nombres del usuario: ') ap...
#!/usr/local/bin/python3.9 def convert(T): t=T[:-2] #enlève les 2 derniers caractères donc la lettre T=T.lower() if T[-1] =="f": #récupére le dernier caractère de T c=(5/9)*(int(t)-32) print("la température est de "+str(c)+ " °C") else: f=int(t)*(9/5)+32 print("la température est de "+str(f) + " °F") ...
class GameClock(object): """Manages time in a game.""" def __init__(self, game_ticks_per_second=20): """Create a Game Clock object. game_ticks_per_second -- The number of logic frames a second. """ self.game_ticks_per_second = f...
def cities_graph(): dict_graph = {} with open('data.txt', 'r') as f: for line in f: city_a, city_b, cost = line.strip().split(',') cost = int(cost) if city_a not in dict_graph: dict_graph[city_a] = {city_b: cost} else: dict...