text
stringlengths
37
1.41M
""" Normal if statement. The unique difference is that no specification means if its true """ im_male = True if im_male: print("im male XD") else: print("im not male XD")
""" A function is a piece of code that will be repeated when needed. Its very useful """ def first_function(): #we have to type the colons print("Hello, you used a function! :D") def second_function(Name): #We have to tell python what variables will be using (Basically for specifying when used the function), with a comma we can specify 2 variables and so on print("Hello," +Name) first_function() second_function("Mikey")
class user: def __init__(self, name, password): self.name = name self.password = password admin = user("root", "123456") # 系统初始化用户 '*** 让用户输入功能选项,输入1启动登录功能 ***' '*** 输入2启动注册功能,输入3退出系统 ***' order = input('1:登录,2:注册(退出输入exit):') '*** 使用字典保存注册过的用户信息 ***' '*** 注意,字典元素的key是用户名,value是用户对象 ***' userInfos = {"root": admin} '*** 在下面调整你的代码 ***' '*** 修改while循环的条件,使用order变量控制循环的结束 ***' while False: '*** 在下面调整你的代码 ***' '*** 修改if的条件,根据用户的选择做决定 ***' if False: #用户登录 name = input('请输入用户名:') password = input('请输入密码:') '*** 在下面调整你的代码 ***' '*** 修改if的条件,判断用户是否存在,如果存在,则继续判断密码是否正确 ***' if False: if password == userInfos.get(name).password: print("登录成功") else: print("密码错误,登录失败!") else: print("该用户不存在,请核实登录信息") elif order == "2": #用户注册 name = input('请输入用户名:') password = input('请输入密码:') '*** 在下面调整你的代码 ***' '*** 修改if的条件,判断用户是否存在,避免注册同名用户 ***' if False: print("该用户已存在,请重新注册") else: '*** 在这里补充你的代码 ***' '*** 根据输入内容,使用自定义的类型创建对象 ***' userInfos[name] = userInfo print("注册成功!") else: print("操作类型输入有误,请重新输入!") '*** 在这里补充你的代码 ***' '*** 实现可以多次登录或者注册的功能 ***'
#This program is determining the avergae grade for the user. def read_file(scores): score_arr = [] first = 'y' file = open(scores, "r") for line in file: line = line.strip() if first == 'y': first = 'n' else: scores = get_score(line) score_arr.append(scores) file.close() return score_arr def get_score(line): index = line.find(",") score = line[index + 1:] return score def get_high(arr): size = len(arr) high = int(arr[0]) for index in range(1, size): if int(arr[index]) > high: high = int(arr[index]) high_ind = index print("High score: " +str(arr[high_ind])) def get_average(arr): size = len(arr) sum = 0 for index in range(0, size): sum = sum + int(arr[index]) average = sum / size rounded_average = round(average, 2) print("Average score: " +str(rounded_average)) def get_low(arr): size = len(arr) low = int(arr[0]) for index in range(1, size): if int(arr[index]) < low: low = int(arr[index]) low_ind = index print("Low score: " +str(arr[low_ind])) def print_scores(arr): size = len(arr) for index in range(0, size): print(arr[index]) def main(): scores = "scores.txt" score_arr = read_file(scores) print_scores(score_arr) get_high(score_arr) get_average(score_arr) get_low(score_arr) main()
#This program displays the users input in a different order the it is recieved. def get_name(): while True: print("Enter name (First Last):") name = input() error_1 = get_error_1(name) if error_1 == "n": error_2 = get_error_2(name) if error_2 == "n": return name def get_error_1(name): index = name.find(" ") check = name[index + 1:] index = check.find(" ") if index >= 0: print("Too many spaces!") error_1 = "y" else: error_1 = "n" return error_1 def get_error_2(name): last = get_last(name) if last == "error": print("No last name!") error_2 = "y" else: error_2 = "n" return error_2 def get_last(name): index = name.find(" ") if index > 0: last = name[index + 1:] else: last = "error" return last def get_first(name): index = name.find(" ") first = name[0: index] return first def display_name(first, last): print(last + ", " + first[0] + ".") def main(): name = get_name() last = get_last(name) first = get_first(name) display_name(first, last) main()
def processSize(shoeSize): size = shoeSize if size < 6: print("your shoe size is small!") else: if size < 9: print("your shoe size is medium!") else: if size < 12: print("your shoe size is large!") return size # Main print("What is your show size?") size = int(input()) if size < 4: print("your shoe size is extra small!") else: processSize(size)
# Author: Abigail Bowen aeb6095@psu.edu def getGradePoint(lettergrade): if lettergrade == "A": return 4.0 elif lettergrade == "A-": return 3.67 elif lettergrade == "B+": return 3.33 elif lettergrade == "B": return 3.0 elif lettergrade == "B-": return 2.67 elif lettergrade == "C+": return 2.33 elif lettergrade == "C": return 2.0 elif lettergrade == "D": return 1.0 elif lettergrade == "F": return 0.0 else: return 0.0 def run(): lettergrade1 = input("Enter your course 1 letter grade: ") credit1 = int(input("Enter your course 1 credit: ")) gpa1 = getGradePoint(lettergrade1) print(f"Grade point for course 1 is: {gpa1}") lettergrade2 = input("Enter your course 2 letter grade: ") credit2 = int(input("Enter your course 2 credit: ")) gpa2 = getGradePoint(lettergrade2) print(f"Grade point for course 2 is: {gpa2}") lettergrade3 = input("Enter your course 3 letter grade: ") credit3 = int(input("Enter your course 3 credit: ")) gpa3 = getGradePoint(lettergrade3) print(f"Grade point for course 3 is: {gpa3}") GPA = (gpa1 * credit1 + gpa2 * credit2 + gpa3 * credit3) / (credit1 + credit2 + credit3) print(f"Your GPA is: {GPA}") if __name__ == "__main__": run()
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import re pattern1 = 'p.*y' # 贪婪模式 pattern2 = 'p.*?y' # 懒惰模式 string = 'abcdfphp345Pythony_py' result1 = re.search(pattern1,string, re.I) result2 = re.search(pattern2,string, re.I) print(result1) print(result2)
""" Sample module to demonstrate implementation of OOP properties. 1. Abstraction. 2. Encapsulation. 3. Inheritance. 4. Methods 5. Overloading """ class BaseUser(object): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name ##################################################### ##################INHERITANCE######################## class User(BaseUser): """ Inheritance. This class can now access attributes of the base class BaseUser. usage >>> user = User('gideon', 'kimutai') >>> print(user.first_name) >>> print(user.last_name) """ ##################################################### #####################METHODS######################### class Child(BaseUser): """ This class has one method and it is only accessible via its instances. usage. >>> child = Child('innocent', 'child') >>> child.cry() aaaaaahhhhhhhhhhhh """ def cry(self): """ :return: """ return 'aaaaaahhhhhhhhhhhh' #################################################### #################### OVERLOADING#################### class Couple(BaseUser): """ Implement overloading. Overload `+` operator so that when adding two couples the result will be a statement indicating they are married. """ def __add__(self, other): man = getattr(self, 'first_name') + getattr(other, 'last_name') woman = getattr(self, 'first_name') + getattr(other, 'last_name') return woman + ' is married to' + man #################################################### #################### ENCAPSULATION ################# class Teenager(BaseUser): """ Demonstrate encapsulation. That is by using protected and private attributes and methods. Usage. >>> t = Teenager('Gideon', 'Kim', 22) >>> t.teen_info() >>> # accessing private attributes will raise an AttributeError >>> t.__age Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'Teenager' object has no attribute '__age' """ def __init__(self, first_name, last_name, age): """ Attribute _age can only be accessed via the instances of the class. """ self.__age = age super(Teenager, self).__init__(first_name, last_name) def teen_info(self): print('First Name: %s\nLast Name: %s\nAge: %s' \ % (self.first_name, self.last_name, self.__age)) #################################################### #################### ABSTRACTION ################# class Gender(BaseUser): """ Demonstrate abstraction by displaying relevant information. The instance contains the names of the user when the user calls print_gender method. Then only the gender is printed. """ def __init__(self, sex, first_name, last_name): self.sex = sex super(Gender, self).__init__(first_name, last_name) def print_gender(self): print(self.sex)
# Import matplotlib import matplotlib.pyplot as plt # Load the image data = plt.imread('bricks.png') # Set the red channel in this part of the image to 1 data[:10, :10, 0] = 1 # Set the green channel in this part of the image to 0 data[:10, :10, 2] = 0 # Set the blue channel in this part of the image to 0 data[:10, :10, 1] = 0 # Visualize the result plt.imshow(data) plt.show()
'''########################################### CS221 Final Project: Heuristic Controller Implementation Authors: Kongphop Wongpattananukul (kongw@stanford.edu) Pouya Rezazadeh Kalehbasti (pouyar@stanford.edu) Dong Hee Song (dhsong@stanford.edu) ###########################################''' # import library import sys, math import numpy as np import gym def heuristic(env, s): '''Heuristic action for LunarLander-v2 using rule-based''' # get state from LunarLander-v2 environment p_x, p_y, v_x, v_y, alpha, omega, left, right = s # initialize the action as "0:Do Nothing" a = 0 # if-else/condition-based action # centering the lander by "1:Fire Left Engine" or "3:Fire Right Engine" from absolute position from center if p_x > 0.1: a = 1 elif p_x < -0.1: a = 3 # stabilize the lander by "1:Fire Left Engine" or "3:Fire Right Engine" from abosolute angle from vertical if alpha > 0.1: a = 3 elif alpha < -0.1: a = 1 # stabilize the lander by "1:Fire Left Engine" or "3:Fire Right Engine" from abosolute angular velocity (positive and negative) if omega > 0.3: a = 3 elif omega < -0.3: a = 1 # reduce vertical velocity of the lander by "1:Fire Main Engine" if v_y < -0.1: a = 2 # stop all action when landed as "0:Do Nothing" if left == 1 or right == 1: a = 0 return a def demo_heuristic_lander(env, seed=None, render=False): for _ in range(1000): env.seed(seed) total_reward = 0 steps = 0 s = env.reset() while True: a = heuristic(env, s) s, r, done, info = env.step(a) total_reward += r if render: still_open = env.render() if still_open == False: break if steps % 20 == 0 or done: print("observations:", " ".join(["{:+0.2f}".format(x) for x in s])) print("step {} total_reward {:+0.2f}".format(steps, total_reward)) steps += 1 if done: break return total_reward if __name__ == '__main__': env = gym.make('LunarLander-v2') demo_heuristic_lander(env, render=True)
import re pattern = r"a" if re.match(pattern, "Ivan Santiago De Jesus"): print("Match") else: print("No match") if re.search(pattern, "Ivan Santiago De Jesus"): print("Search match") else: print("No search match") find_all = re.findall(pattern, "Ivan Santiago De Jesus") print(find_all, " '{}' appeared {} times".format(pattern, len(find_all)))
class Equipo(object): def __init__(self, n, c, cam, nj): #Atributos de estudiante con los valores enviados desde el archivo self.nombre = n self.ciudad = c self.campeonatos = int(cam) self.numJugadores = int(nj) #Metodos agregar y obtener def agregar_nombre(self, n): self.nombre = n def obtener_nombre(self): return self.nombre def agregar_ciudad(self, c): self.ciudad = c def obtener_ciudad(self): return self.ciudad def agregar_campeonatos(self, cam): self.campeonatos = int(cam) def obtener_campeonatos(self): return self.campeonatos def agregar_numJugadores(self, nj): self.numJugadores = int(nj) def obtener_numJugadores(self): return self.numJugadores def __str__(self): #equivalente al toString en java, para visualizar los metodos como tal return "%s - %s - %d - %d" % (self.nombre, self.ciudad, self.campeonatos, self.numJugadores) def __repr__(self): #representacion de objetos, el sorted hace referencia a este medoto return "%s - %s - %d - %d" % (self.nombre, self.ciudad, self.campeonatos, self.numJugadores) class Operaciones(object): def __init__(self, listado): #Recibe el listado self.listado_equipos = listado def ordenar(self, op): #Recibe la opcion ingresada por el usuario en op opcion = op #Se crea la variable con el valor de op """ https://docs.python.org/3/howto/sorting.html >>> sorted(student_objects, key=lambda student: student.age) # sort by age """ #Condiciones para ordenar por nombre o campeonatos if opcion == 1: return sorted(self.listado_equipos, key=lambda equipo: equipo.nombre) #poner el __repr__ if opcion == 2: return sorted(self.listado_equipos, key=lambda equipo: equipo.campeonatos)
def recursivBinarySearch(A, left, right, item): if right < left: return -1 center = (left + right) // 2 if A[center] == item: return center elif A[center] > item: return recursivBinarySearch(A, left, center - 1, item) else: return recursivBinarySearch(A, center + 1, right, item) A = [0, 10, 20, 30, 40, 50, 60, 70] print(f'Pesquisa com sucessor: {recursivBinarySearch(A, 0, len(A) - 1, 20)}') print(f'Pesquisa com sucessor: {recursivBinarySearch(A, 0, len(A) - 1, 0)}') print(f'Pesquisa com sucessor: {recursivBinarySearch(A, 0, len(A) - 1, 70)}') print(f'Pesquisa com sucessor: {recursivBinarySearch(A, 0, len(A) - 1, 100)}')
""" Created on Mon Sep 24 12:10:05 2018 @author: BrianRG """ def weird(a,b): if(not a or not b): return (a,b) if(a>=2*b): a%=(2*b) return weird(a,b) if(b>=2*a): b%=(2*a) return weird(a,b) return(a,b) """ def weirdo(a,b): while(a and b): if(a>=2*b): a%=(2*b) if(b>=2*a): b%=(2*a) else: if(a>=2*b): a-=2*b continue break return a,b """ a,b=input().split(" ") a,b=weird(int(a),int(b)) print(a,b)
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务1: 短信和通话记录中一共有多少电话号码?每个号码只统计一次。 输出信息: "There are <count> different telephone numbers in the records." """ #4个连续引号导致错误 sumnumber=[] #将texts列表中的电话号码通过for循环进行筛选判断如果未在sumnumber列表中则进行添加(发送与接受号码都进行判断)之前用elif进行判断发现当条件一满足时会忽略条件二导致数据输出错误 for textnumber in texts: if textnumber[0] not in sumnumber: sumnumber.append(textnumber[0]) if textnumber[1] not in sumnumber: sumnumber.append(textnumber[1]) #将calls列表中的电话号码通过for循环进行筛选判断如果未在sumnumber列表中则进行添加(拨打与接听号码都进行判断) for callnumber in calls: if callnumber[0] not in sumnumber: sumnumber.append(callnumber[0]) if callnumber[1] not in sumnumber: sumnumber.append(callnumber[1]) #将sumnumber列表进行统计与输出 参考网址:http://www.runoob.com/python/att-string-format.html print ('There are {0} different telephone numbers in the records.'.format(len(sumnumber)))
import requests import json import sys import argparser URL="http://api.openweathermap.org/data/2.5/weather?q=" class Weather(): def get_json(self,ciudad): r=requests.get(URL+ciudad) return r.content def print_weather(self, ciudad, unidad): j = self.get_json(ciudad) r = json.loads(j) temperatura = r["main"]["temp"] #pongo el texto jason y lo guardo en el resultado y me lo tranforma a un diccionario #temperatura viene en K unidad = unidad.lower() if (unidad == "celsius" or unidad == "c"): temperatura = temperatura -273.15 elif (unidad == "fahrenheit" or unidad == "f"): temperatura = temperatura * (9/5) - 459.67 return str(temperatura) def main(): city="London" if(len(sys.argv))<1: # city=argv[1] parser= argparser.ArgsParser() parser.get_city(sys.argv) print str(sys.argv) map=Weather() #map.get_json("Cordoba") print (map.get_json(city)) #esto devuelve el JSON como texto, por eso puedo poner print print "-----------------------------" print map.print_weather(city) return 0 if __name__ == '__main__': main()
# # @lc app=leetcode id=887 lang=python3 # # [887] Super Egg Drop # # @lc code=start import math class Solution: def superEggDrop(self, K: int, N: int) -> int: # dp[M][K]means that, given K eggs and M moves, # what is the maximum number of floor that we can check # dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1, # which means we take 1 move to a floor, # if egg breaks, then we can check dp[m - 1][k - 1] floors. # if egg doesn't breaks, then we can check dp[m - 1][k] floors. # dp = [[0] * (K + 1) for i in range(N + 1)] # for m in range(1, N + 1): # for k in range(1, K + 1): # dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1 # if dp[m][K] >= N: return m # optimize it to 1D # see https://www.kancloud.cn/kancloud/pack/70125 dp = [0]*(K+1) for m in range(1, N+1): for i in range(K, 0, -1): dp[i] = dp[i-1]+dp[i]+1 if dp[-1]>=N: return m # # https://www.youtube.com/watch?v=mLV_vOet0ss # # let m be the floor you drop first egg # solution = [[0 for _ in range(N+1)] for _ in range(K+1)] # solution_first_drop_at = [0 for _ in range(N+1)] # solution[1] = [n for n in range(N+1)] # for k in range(1, K+1): # solution[k][1] = 1 # n_max = N # for k in range(2, K): # n_max = math.ceil(n_max/2) # for k in range(2, K+1): # for n in range(2, min(n_max,N)+1): # bound = min(math.ceil(n/2),n) # for m in range(1, bound+1): # solution_first_drop_at[m] = max(solution[k-1][m-1], solution[k][n-m])+1 # solution[k][n] = min(solution_first_drop_at[1:m+1]) # n_max *= 2 # return solution[K][N] # @lc code=end
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 5 20:48:47 2019 @author: damienrigden Examples of strings encrypted using polymorph. Feel free to make more requests """ encrypt = polymorph("Hello world!") print(encrypt) [[{'%'}, ['VY]V\\\\VWVV]YVWYVU]VXWV]\\V^UV]YV\\[Y[', 101, 114, 112, 115, 111, 104, 123, 108, 119, 124, 35, 100]]] encrypt2 = polymorph("world! Hello") print(encrypt2) [(['V[XVZZ[ZZ^ZVRV[RV\\WXVYZZ^VZW[W', 101, 114, 111, 115, 110, 104, 123, 107, 118, 123, 35, 100], {'%'})] encrypt3 = polymorph("🐐") print(encrypt3) (({'%', '#'}, ['TWZ^U]', 118]),) encrypt4 = polymorph("a") print(encrypt4) [[{'#'}, ['TZV', 102]]] encrypt5 = polymorph("aa") print(encrypt5) [({'&', '%', '$', '#'}, ['\\WVYS', 114, 117])] encrypt6 = polymorph('aaaaaaaa') print(encrypt6) [[['VWT[SVYUT[SVYUT[SXUVYU', 114, 114, 111, 124, 112, 114, 116, 115], {'%', '#'}]] encrypt7 = polymorph("🂡") print(encrypt7) (({'&', '%', '$'}, ['UW]VV\\', 117]),) encrypt8 = polymorph("⟰") print(encrypt8) [[['TUX[\\', 116], {'&', '%', '#'}]] encrypt9 = polymorph("") print(encrypt9) ([['[a^', 102], {'*'}],) encrypt10 = polymorph("\x00") print(encrypt10) ([['U\\', 114], {'%', '$'}],) encrypt11 = polymorph("\x01") print(encrypt11) ([{'%'}, ['VZV', 102]],) encrypt12 = polymorph("\x00\x00") print(encrypt12) [[['ZWZW', 101, 113], {'$'}]] encrypt13 = polymorph("\x00\x01") print(encrypt13) ([['UTYU\\', 101, 114], {'$'}],) encrypt14 = polymorph("\x01\x01") print(encrypt14) ([['T^T^', 114, 113], {'&', '#'}],) encrypt15 = polymorph("A") print(encrypt15) [[{'&'}, ['WZW', 102]]] encrypt16 = polymorph("AB") print(encrypt16) [({'$', '#'}, ['YU\\]', 114, 113])] encrypt17 = polymorph("BA") print(encrypt17) [[{'&', '%', '$', '#'}, ['Z]VZT', 114, 117]]] encrypt18 = polymorph("B") print(encrypt18) [({'%'}, ['^^', 101])] encrypt19 = polymorph("1") print(encrypt19) ([['YZ', 114], {'&', '%', '$', '#'}],) encrypt20 = polymorph("\n") print(encrypt20) [({'$'}, ['XW', 101])] encrypt21 = polymorph("\n\n") print(encrypt21) [[{'&', '%'}, ['WY]\\', 114, 113]]] encrypt22 = polymorph("\r") print(encrypt22) ([['TU^', 114], {'&', '$', '#'}],) encrypt23 = polymorph("\r\n") print(encrypt23) ([['TV^U\\', 113, 102], {'&', '%', '#'}],) encrypt24 = polymorph("\r\r") print(encrypt24) ([['TT[VS', 101, 114], {'#'}],) encrypt25 = polymorph("AA") print(encrypt25) [[{'&', '%'}, ['\\^VZV', 114, 114]]]
import math a = int(input()) b = int(input()) for i in range(a, b+1): c = int(math.sqrt(i)) if c*c == i: print(i)
def min(a,b,c,d): min = float('inf') if min > a: min = a if min > b: min = b if min > c: min = c if min > d: min = d print(min) m = [] s = input() m = s.split() a = int(m[0]) b = int(m[1]) c = int(m[2]) d = int(m[3]) min(a,b,c,d)
# def unique_string(x): dict1 = {} for char in range(len(x)): if x[char] in dict1.values(): print("False") else: dict1[char] = x[char] print("True") print("unique elements in dictionary", dict1) unique_string("shikshiha")
__author__ = 'Joel' def collatz_conjecture(n): return n / 2 if n % 2 == 0 else 3 * n + 1 visited_map = {} def get_iterations_of_collatz(start_val): if start_val in visited_map: return visited_map.get(start_val) count = 1 val = start_val while val != 1: val = collatz_conjecture(val) if val in visited_map: length = count + visited_map.get(val) visited_map[start_val] = length return length count += 1 visited_map[start_val] = count return count def get_max_chain_under(limit): max = 0 starting_number = 0 for i in range(1, limit): collatz = get_iterations_of_collatz(i) if collatz > max: max = collatz starting_number = i return starting_number print(get_max_chain_under(1000000))
from sympy import symbols, sqrt, Matrix, mpmath, Line3D, Segment3D, Point3D, Plane from sympy import srepr def dist_between_points(point1, point2): """ Expects input as tuple(x,y)""" x1,x2,y1,y2= symbols("x1 x2 y1 y2") distance= sqrt( (x2-x1)**2 + (y2-y1)**2) x1,y1,z2 = point1 x2,y2,z2 = point2 return distance.subs( { "x1":x1,"x2":x2, "y1":y1, "y2":y2,"z1":z1,"z2":z2}) def vector_angles(vec1,vec2): """ Expects vectors in sympy Matrix Object """ #need magnitude of vector 1 and 2 vec1_mag = magnitude(vec1) vec2_mag = magnitude(vec2) rad=mpmath.acos( (vec1.dot(vec2))/ (vec1_mag * vec2_mag)) return mpmath.degrees(rad) def vector(first,second): """ where first and second are points in tuple(x,y) form""" x1,y1= first x2,y2=second return Matrix([[x2-x1, y2-y1]]) def is_coplaner(*points): """ accepts many points and tests if they are co planar """ return Point3D.is_coplaner(*points) def magnitude(vec): """ Expects vectors in sympy Matrix Object """ return sqrt( sum(digit**2 for digit in vec) ) def perimeter(*segments): return sum(seg.length for seg in segments).evalf(2) def area_of_quadrilateral(diag,diag2): """ diag,diag2 where both are vectors""" return (0.5)*(diag.cross(diag2)) def strike_dip(plane): """ strike is measured against the vertical plane dip is measured by the angle between horizontal plane """ normal= Matrix ( list(plane.normal_vector)) horizontal= Plane( Point3D(0,0,0),Point3D(0,1,0),Point3D(1,1,0)) vertical= make_plane((0,0,0), (0,0,1), (0,1,1)) dip_vec = Matrix(list(horizontal.normal_vector)) strike_vec = Matrix(list(vertical.normal_vector)) dip_angle= vector_angles(dip_vec, normal) strike_angle= vector_angles(strike_vec, normal) return strike_angle, dip_angle def make_plane(*args): assert( len(args) == 3) return Plane( *[Point3D(tuple_) for tuple_ in args]) def calculate_dip_strike(points): # makes sure it takes three non-coliner lines? # what happens if they input junk? faces = sort_faces(points) adict = {} for key, face in faces.items(): plane = make_plane(*face[:3]) strike, dip = strike_dip(plane) adict[key+"dip"] = dip adict[key+"direction"] = strike return adict def sort_faces(points): # returns msc faces p1,p2,p3,p4,p5,p6,p7,p8 = points faces = { "one" :[p5,p6,p7,p8], "two" : [p5, p6, p1, p2], "three" : [p6, p7, p3, p2], "four" : [p7, p8, p4, p3], "five" : [p5, p8, p1, p4]} return faces def orientation(faces): # you just need to check one face # to get the orientation of all the other faces vertical= make_plane((0,0,0), (0,0,1), (0,1,1)) plane = make_plane(faces[0][:3]) angle = vector_angles(plane.normal_vector, vertical.normal_vector) if angle == 90: return ["back", "north", "east", "south", "west"] else: return ["back", "northeast", "southeast", "southwest", "northwest"]
x = 1 x += 2 print('Value of x:') print(x)
number_one = input('Enter number one: ') number_two = input('Enter number two: ') sum_number = float(number_one) + float(number_two) if sum_number > 5: print('The sum is greater than 5') elif sum_number < 5: print('The sum is less than 5') else: print('The sum is equal to 5')
n=int(input("enter the number")) if (n>0): print("the number is possitive") else: print("the number negative")
#Bloco de importação ########################## import random # from sklearn import tree # ########################## #Criação da matriz de pacientes e da matriz com os tipos de diabetes que é nossa variável resposta pacientes = [] tipos = [] for i in range(1501): sexo = random.choice(["Homem", "Mulher"]) #print("sexo: ", sexo) #Transformar homem no número 1 e mulher no número 0 if sexo == "Homem": sexo = 1 else: sexo = 0 idade = random.randint(5,90) #print("idade: ", idade) hdl = random.randint(15,150) #print("hdl: ", hdl) hipertensao = bool(random.getrandbits(1)) #Se existe alguém com hipertensao na familia #print("hipertensao: ", hipertensao) ldl = random.randint(30,220) #print("ldl: ", ldl) glicose = random.randint(25,350) #print("glicose: ", glicose) familia_diabetes = bool(random.getrandbits(1)) #se existe alguém do diabetes na família #print("diabetes na familia: ", familia_diabetes) trigliceride = random.randint(50,700) #print("trigliceride: ", trigliceride) glicada = round(random.uniform(3,15),3) #print("glicada: ", glicada) #Definir altura if idade < 10: altura = random.randint(100,130) elif idade < 15: altura = random.randint(130, 170) elif idade >= 15: altura = random.randint(150,200) #print("altura: ", altura) #definir peso if altura < 130: peso = random.randint(20,48) elif altura < 140: peso = random.randint(27, 60) elif altura < 160: peso = random.randint(35, 80) elif altura >= 160: peso = random.randint(45,180) #print("peso: ", peso) #definir IMC imc = round((peso/(altura**2))*10000,3) #print("imc: ", imc) #DEFINIR TIPO DE DIABETES if glicose >= 126 and glicada >= 6.5 and idade <= 20: tipo_diabetes = "Diabetes tipo 1" elif glicose >= 126 and glicada >= 6.5 and idade >= 20: tipo_diabetes = "Diabetes tipo 2" else: tipo_diabetes = "Sem diabetes" #print("tipo de diabete: ", tipo_diabetes) paciente = [sexo,familia_diabetes,idade,altura,peso,imc,hdl,ldl,glicose,glicada,trigliceride,hipertensao] #Incluir o tipo de diabete do paciente gerado na matriz de tipo de diabates tipos.append(tipo_diabetes) #Incluir o paciente gerado na matriz de pacientes pacientes.append(paciente) print(i) print(paciente) #print(pacientes) #print(tipos) #Utilizando o modelo de árvore de decisão para pacientes e tipos de diabetes modelo = tree.DecisionTreeClassifier() modelo.fit(pacientes, tipos) #criando um novo paciente novo = ["Homem",True,15,197,169,43.547,55,137,172,7.328,304,True] # Transformar homem no número 1 e mulher no número 0 if novo[0] == "Homem": novo[0] = 1 else: novo[0] = 0 novo = tuple(novo) #Transforma a lista [] em tupla () novo = [novo] #Coloca a nova tupla dentro de uma lista para formar uma matriz [()] #Prevendo se o paciente têm diabetes ou não previsao = modelo.predict(novo) print("\n\n------------------------------------------------------------------------------------------------------") print("\nNovo paciente:", novo) print("\nResultado da previsão: %s" % previsao)
import math h = 0.1 t = 0.1 eps = 0.1 N = int(1/h) a = 0.5 def simpson(y): return (h/3)*(y[0] + y[-1] + 2*sum(y[2:-1:2]) + 4*sum(y[1:-1:2])) def y_f(a): y = [0, a] for i in range(2, N): y.append(h*h*h*(i-1)*math.sqrt(y[i-1])/2 + 2*y[i-1] - y[i-2]) return y def fitness(a): return simpson(y_f(a)) - 1 def deriv(f, a): return (f(a + t) - f(a))/t def newton(a): return a - fitness(a)/deriv(fitness, a) while abs(fitness(a)) > eps: a = newton(a) answer = y_f(a) print("answer = " + str(answer)) print("accuracy = " + str(abs(fitness(a))))
#Prime numbers upto a limit print("Jaswanth sai - 121910313044") lower = int(input("Enter the lower limit:")) higher = int(input("Enter the higher limit:")) #logic begins here for a in range(lower,higher): if a>1: for i in range(2,a): if(a%i==0): break else: print(a)
#To Find the Samllest among the three numbers num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) num3 = float(input("Enter third number: ")) #Logic begins here smallest = num1 if (num2 < num1) and (num2 < num3): smallest = num2 elif (num3 < num1): smallest = num3 #Display Result print("The smallest number is", smallest) #My Info print("K.Jaswanth sai - 121910313044")
i = 1 while i == 1: tanishq = input("please enter the number: ") swastik = input("please enter the operand: ") diwakar = input("please enter the number: ") pankaj = input("please enter the operand:") if '*' in swastik or pankaj: product = int(tanishq) * int(diwakar) if '/' in swastik or pankaj: quotient = int(tanishq) / int(diwakar) if '-' in swastik or pankaj: diffrence = int(tanishq) - int(diwakar) if '+' in swastik or pankaj: daksh = int(tanishq) + int(diwakar) if '=' in swastik or pankaj: print("multiplication:" , product) print("division:" , quotient) print("subtraction:" , diffrence) print("addition:" , daksh) i += 6 else: continue
# Insert Data Program import pymongo fruit_dict = { "type": "bananas", "cost": 45, "stock": 67 } # Store record in the db client = pymongo.MongoClient("mongodb://localhost:27017/") fruit_db = client["fruits2_db"] fruit_col = fruit_db["fruits"] x = fruit_col.insert_one(fruit_dict) print(x)
import os import csv # Path to collect data from the Resources folder wrestling_csv = os.path.join('Resources', 'WWE-Data-2016.csv') # Define the function and have it accept the 'wrestlerData' as its sole parameter def print_percentages(wrestler): # Find the total number of matches wrestled total = int(wrestler[1]) + int(wrestler[2]) + int(wrestler[3]) # Find the percentage of matches won won_perc = round(int(wrestler[1]) / total * 100, 2) # Find the percentage of matches lost loss_perc = round(int(wrestler[2]) / total * 100, 2) # Find the percentage of matches drawn draw_perc = round(int(wrestler[3]) / total * 100, 2) # Print out the wrestler's name and their percentage stats print(f'Wrestler: {wrestler[0]} Win%: {won_perc} Loss%: {loss_perc} Draw%: {draw_perc}') # Read in the CSV file with open(wrestling_csv, 'r') as csvfile: # Split the data on commas csvreader = csv.reader(csvfile, delimiter=',') # Prompt the user for what wrestler they would like to search for name_to_check = input("What wrestler do you want to look for? ") # Loop through the data for row in csvreader: # If the wrestler's name in a row is equal to that which the user input, run the 'print_percentages()' function if(name_to_check == row[0]): print_percentages(row)
#You are given two integer arrays of size X and X ( & are rows, and is the column). Your task is to concatenate the arrays along 0 axis . ''' Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined: import numpy array_1 = numpy.array([1,2,3]) array_2 = numpy.array([4,5,6]) array_3 = numpy.array([7,8,9]) print numpy.concatenate((array_1, array_2, array_3)) #Output [1 2 3 4 5 6 7 8 9] If an array has more than one dimension, it is possible to specify the axis along which multiple arrays are concatenated. By default, it is along the first dimension. import numpy array_1 = numpy.array([[1,2,3],[0,0,0]]) array_2 = numpy.array([[0,0,0],[7,8,9]]) print numpy.concatenate((array_1, array_2), axis = 1) #Output [[1 2 3 0 0 0] [0 0 0 7 8 9]] ''' import numpy a,b,c=[int(x) for x in input().split()] n=numpy.array([[int(x) for x in input().split()] for i in range(a)]) m=numpy.array([[int(y) for y in input().split()] for j in range(b)]) print(numpy.concatenate((n,m),axis=0)) ''' Sample Input 4 3 2 1 2 1 2 1 2 1 2 3 4 3 4 3 4 Sample Output [[1 2] [1 2] [1 2] [1 2] [3 4] [3 4] [3 4]] '''
#program to demonstrate functionality of transpose and flatten functions of numpy module import numpy list1=input().strip().split() x,y=list(map(int,list1)) list2=[input().split() for i in range(x)] list3=[i for item in list2 for i in item] nparray=numpy.array(list3,int) npshapedarray=numpy.reshape(nparray,(x,y)) nptransposearray=numpy.transpose(npshapedarray) npflattenarray=npshapedarray.flatten() print(nptransposearray) print(npflattenarray) #Sample Input #2 2 #1 2 #3 4 #Sample Output # [[1 3] # [2 4]] # [1 2 3 4
#swap the case of letters from lower to upper and vice versa def swap_case(s): new_string="" for letter in s: if letter==letter.lower(): new_string+=letter.upper() else: new_string+=letter.lower() return new_string if __name__=="__main__": s=input() result=swap_case(s) print(result)
#program to demonstrate functionality of zeros and ones functions of numpy module import numpy list1=input().strip().split() tuple1=tuple([int(x) for x in list1]) print(numpy.zeros(tuple1,dtype=numpy.int)) print(numpy.ones(tuple1,dtype=numpy.int)) ''' Sample Input 0 3 3 3 #first 3 is for number of arrays to be printed, second 3 is for number of rows in each array and third 3 is for number of columns in each array 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 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]]] '''
#program to demonstrate functionality of identity and eye functions of numpy module import numpy #print(numpy.identity(3)) #print(numpy.eye(8, 7, k = -1,dtype=numpy.int)) #Diagonal we require; k>0 means diagonal above main diagonal or vice versa. numpy.set_printoptions(legacy='1.13') list1=input().strip().split() tuple1=tuple([int(x) for x in list1]) print(numpy.eye(*tuple1,k=0)) #Sample Input # 4 5 #Sample Output # [[ 1. 0. 0. 0. 0.] # [ 0. 1. 0. 0. 0.] # [ 0. 0. 1. 0. 0.] # [ 0. 0. 0. 1. 0.]]
#program to count strings starting with vowels and consonant in a given string and deciding the winner def minion_game(string): string=string.lower() dict1={} dict2={} vowels=['a','e','i','o','u'] vcounter=0; ccounter=0; for index in range(len(string)): if string[index] in vowels: vcounter+=(len(string)-index) else: ccounter+=(len(string)-index) if vcounter<ccounter: print("Stuart",ccounter) elif vcounter==ccounter: print("Draw") else: print("Kevin",vcounter) if __name__ == '__main__': s = input() minion_game(s)
#Collier, R. "Lectures Notes for COMP1405B – Introduction to Computer Science I" [PDF document]. #Retrieved from cuLearn: https://www.carleton.ca/culearn/ (Fall 2015). #Gaddis, T. "Starting Out With Python 2nd ed"[PDF document] (Pearson, 2012) (Fall 2015). #Title and introduction print(" ⋆ ✢ ✣ ✤ ✥ ✦ ✧ ✩ ") print("~~~~~~~~~~~~~~~~~~ THE OREGON TRAIL ~~~~~~~~~~~~~~~~~~~") print(" ⋆ ✢ ✣ ✤ ✥ ✦ ✧ ✩ ") print() print("Welcome to Matt's General Store Independence, Missouri!") print("The only place in town to buy things!") print("Here is a list of what's for sale:") print() print("Oxen - 2 per yoke, $40.00 a yoke") print("Food - $0.20 per pound") print("Clothing - $10.00 a set") print("Bullets - $2.00 a box") print("Spare Parts - $10.00 each") print() #ask how many yokes user wants and calculate cost of yokes yoke=(float(input("How many yoke would you like? "))*40) #format value to two decimal places yokeF=format(yoke,'.2f') #print subtotal print("Current Bill: $",yokeF) #repeat for each item available for purchase food=(float(input("How many pounds of food would you like? "))*0.20) foodF=format(food,'.2f') sub=format(yoke+food,'.2f') print("Current Bill: $",sub) clothes=(float(input("How many sets of clothes would you like? "))*10.00) clothesF=format(clothes,'.2f') sub=format(yoke+food+clothes,'.2f') print("Current Bill: $",sub)# bullets=(float(input("How many boxes of bullets do you want? "))*2.00) bulletsF=format(bullets,'.2f') sub=format(yoke+food+clothes+bullets, '.2f') print("Current Bill: $",sub) spare=(float(input("How many spare parts do you want? "))*10.00) spareF=format(spare,'.2f') sub=format(yoke+food+clothes+bullets+spare, '.2f') print("Current Bill: $",sub) total=sub #total bill is equal to most recent subtotal print() #display final receipt print(" ~~~~~~~~~~") print(" RECEIPT") print(" ~~~~~~~~~~") print("Oxen $",yokeF)# print("Food $",foodF) print("Clothes $",clothesF) print("Bullets $",bulletsF) print("Spare Parts $",spareF) print("_______________________") print("Total: $",total)
# I'm going to integrate three files ("Crimes_-_2001_to_present.csv", # "population_by_community_area.csv", and "SelectedIndicators.csv") into one # file ("processed_data.csv"). import pandas as pd # This file is from City of Chicago Data Portal. Read the csv file into a dataframe # with selected variables. df_crime = pd.read_csv("Crimes_-_2001_to_present.csv", usecols = ["Primary Type", "Community Area", "Year", "Latitude", "Longitude"]) # Extract the data of 2015. 2015 is the latest data which is complete (2016 is still ongoing), # and drop rows with missing values. df_crime = df_crime[df_crime["Year"]==2015].dropna() # Pick up only HOMICIDES due to the speed purpose. If I pick up more crime types, # the webapp will crauh. df_crime = df_crime[df_crime["Primary Type"]=="HOMICIDE"] # Convert floats to integers. df_crime = df_crime.astype({"Primary Type":str, "Community Area":int, "Year":int, "Latitude":float, "Longitude":float}) # Output to the csv file named "processed_data.csv". df_crime.to_csv("02map.csv")
"""test for Python 2 string formatting error """ from __future__ import unicode_literals # pylint: disable=line-too-long __revision__ = 1 def pprint_bad(): """Test string format """ "{{}}".format(1) # [too-many-format-args] "{} {".format() # [bad-format-string] "{} }".format() # [bad-format-string] "{0} {}".format(1, 2) # [format-combined-specification] # +1: [missing-format-argument-key, unused-format-string-argument] "{a} {b}".format(a=1, c=2) "{} {a}".format(1, 2) # [missing-format-argument-key] "{} {}".format(1) # [too-few-format-args] "{} {}".format(1, 2, 3) # [too-many-format-args] # +1: [missing-format-argument-key,missing-format-argument-key,missing-format-argument-key] "{a} {b} {c}".format() "{} {}".format(a=1, b=2) # [too-few-format-args] # +1: [missing-format-argument-key, missing-format-argument-key] "{a} {b}".format(1, 2)
""" This a test string to work on in the labs""" name = input("What is your name?") while len(name)== 0: name = input("What is your name?") for i in range(0, len(name,2): print(name[ : :2])
# -*- coding: utf-8 -*- # neural network from abc import ABC from collections.abc import Iterable class Connectable(Iterable, ABC): def connect_to(self, other): if self == other: return for s in self: # Iterable for o in other: # Iterable s.outputs.append(o) o.inputs.append(s) class Neuron(Connectable): def __init__(self, name): self.name = name self.inputs = [] self.outputs = [] def __iter__(self): yield self def __str__(self): return f"{self.name}, {len(self.inputs)} inputs, {len(self.outputs)} outputs" class NeuronLayer(list, Connectable): def __init__(self, name, count): super(NeuronLayer, self).__init__() self.name = name for x in range(0, count): self.append(Neuron(f"{name}-{x}")) def __str__(self): return f"{self.name} with {len(self)} neurons" if __name__ == "__main__": neuron1 = Neuron("n1") neuron2 = Neuron("n2") layer1 = NeuronLayer("L1", 3) layer2 = NeuronLayer("L2", 4) neuron1.connect_to(neuron2) neuron1.connect_to(layer1) layer1.connect_to(neuron2) layer1.connect_to(layer2) print(neuron1) print(neuron2) print(layer1) print(layer2) # n1, 0 inputs, 4 outputs # n2, 4 inputs, 0 outputs # L1 with 3 neurons # L2 with 4 neurons
# -*- coding: utf-8 -*- # How to build a factory that auto increment from unittest import TestCase class Person: def __init__(self, id, name): self.id = id self.name = name class PersonFactory: id = 0 def create_person(self,name): p = Person(PersonFactory.id, name) PersonFactory.id +=1 return p class Evaluate(TestCase): def test_exercise(self): pf = PersonFactory() p1 = pf.create_person("Chris") self.assertEqual(p1.name,"Chris") self.assertEqual(p1.id,0) p2 = pf.create_person("Sarah") self.assertEqual(p2.name,"Sarah") self.assertEqual(p2.id,1)
# Hello World program in Python print "Hello World!\n" mylist = [1,2, 3, 4,5 ] print mylist print mylist[3:5] mylist[3:4] = [0,1] print mylist[:] ll = [1,3,4,4,6,10,11,8] print ll def sort(ll): for i in range(len(ll)): for j in range(len(ll) - 1): if( ll[i] < ll[j] ): t = ll[i] ll[i] = ll[j] ll[j] = t return ll ls = sort(ll) print ls
# coding = utf-8 __author__ = "LY" __time__ = "2018/5/8" class CycleQueue(object): """docstring for CircleQueue""" def __init__(self, maxsize, front=0, rear=0): '''循环队列有空间大小限制''' self.maxsize = maxsize self.items = [None] * self.maxsize self.front = 0 self.rear = 0 def inQueue(self, data): '''入队列(头出尾进)''' if (self.rear+1)%self.maxsize == self.front: print("Cycle queue is full, you can not add anything!") return self.rear = (self.rear+1) % self.maxsize self.items[self.rear] = data def isEmpty(self): '''判断队列是否为空''' return self.front == self.rear def deQueue(self): '''出队列''' if self.front == self.rear: print("Cycle queue is empty!") return self.front = (self.front+1) % self.maxsize self.items[self.front] = None def size(self): '''输出队列大小''' return (self.rear-self.front+self.maxsize) % self.maxsize def delete(self): '''销毁循环队列''' k = self.maxsize i = 0 while k > 0: del self.items[i] k -= 1 del k del i print("Delete cycle queue successfully!") if '__main__' == __name__: q = CycleQueue(5) List = [1,2,3,4] for i in List: q.inQueue(i) print("队列为:", q.items) print("队列是否为空:", "空" if q.isEmpty()==True else "非空") print("队列大小为:", q.size()) q.deQueue() print("出队列:", q.items) print("队列大小为:", q.size()) q.delete()
import datetime date = datetime.date(*[int(i) for i in input().split(" ")]) date += datetime.timedelta(int(input())) print(date.year, date.month, date.day)
#Number 1 i = 0 for x in range(10): if x % 2 != 0: i += x print(x) print(i) #Number 2 def function1(): answer1 = int(input("Give me a number")) answer2 = int(input("Give me another number")) print(answer1+answer2) #Number 3 def greetings(): print("Hello, world") greetings() display = "" while True: i = 0 i += 1 if 1 > 10: display += "?" else: display += "@" print(display) #NUmber 4 str1 = "fireflies" str2 = "another" display = "" temp = "" for letter in str1: if letter not in str2: display += letter temp += letter else: temp += letter print(temp) print(display) #Number 5 x = 10 y = 15 z = 20 while x > y: print(f"x:{x} y:{y}") x -= 1 y += 1 if x > y: print("Hello") else: if z > y and z > x: print("Wow") if y < x: print("Yes") else: print("No") else: print("Okay")
import random class RandomQueue: def __init__(self): self.items = [] def __str__(self): return str(self.items) def insert(self, item): self.items.append(item) def remove(self): # zwraca losowy element rand_idx = random.randrange(len(self.items)) self.items[rand_idx], self.items[-1] = self.items[-1], self.items[rand_idx] return self.items.pop() def is_empty(self): return not self.items def is_full(self): return False def clear(self): # czyszczenie listy self.items.clear() randQ = RandomQueue() print("is Empty? :") print(randQ.is_empty()) randQ.insert(1) randQ.insert(2) randQ.insert(3) randQ.insert(4) randQ.insert(5) print(randQ) print("is Full? :") print(randQ.is_full()) randQ.remove() print(randQ) randQ.remove() print(randQ) randQ.remove() print(randQ) randQ.clear() print(randQ)
print "Enter customer details" print "name of the customer" x= raw_input(str) print "meter number" z=raw_input(int) print"Enter the units consumed" y=raw_input(int) units=int(y)f(units<=100): print 'Dear',name print "Your Meter Number is: ",meter_no print "You have Consumed %d units" % (units) print "Total Price is :", units*10 elif (units>100 and units<=200): units1=units-100 price=(100*10)+(units1*12) print 'Dear',name print "Your Meter Number is: ",meter_no print "You have Consumed %d units" % (units) print "Total Price is :", price elif (units>200 and units<=300): units1=units-200 price=(100*10)+(100*12)+(units1*15) print 'Dear',name print "Your Meter Number is: ",meter_no print "You have Consumed %d units" % (units) print "Total Price is :", price elif (units>300 and units<=400): units1=units-300 price=(100*10)+(100*12)+(100*15)+(units1*20) print 'Dear',name print "Your Meter Number is: ",meter_no print "You have Consumed %d units" % (units) print "Total Price is :", price elif (units>400 and units<=500): units1=units-400 price=(100*10)+(100*12)+(100*15)+(100*20)+(units4*25) print 'Dear',name print "Your Meter Number is: ",meter_no print "You have Consumed %d units" % (units) print "Total Price is :", price elif (units>500 and units<=1000): units1=units-500 price=(100*10)+(100*12)+(100*15)+(100*20)+(100*25)+(units4*30) print 'Dear',name print "Your Meter Number is: ",meter_no print "You have Consu.0med %d units" % (units) print "Total Price is :", price else: print 'Dear',name print "Your Meter Number is: ",meter_no print "You have Consumed %d units" % (units) print "Total Price is :", units*50
def part_one(nums, set_nums): for num in nums: if 2020 - num in set_nums: return num * (2020 - num) def part_two(nums, set_nums): for num in nums: for num2 in nums: if (2020 - num - num2) in set_nums: return num * (2020 - num - num2) * num2 with open("input_dec01.txt") as input_file: nums = [int(line) for line in input_file] set_nums = set(nums) print(part_one(nums, set_nums)) print(part_two(nums, set_nums))
import re # start from designated index (from jump) and go through instructions until next jump when recursion is called def jump_to(start,code_list,accnum,called): for i in range(start,len(code_list)): instr = re.search("([a-z]*) ([+-][0-9]*)$",code_list[i]) if instr: if i not in called: called.append(i) comm = instr.group(1) numb = int(instr.group(2)) else: return False, accnum else: print("Error parsing command") if comm == "acc": accnum += numb elif comm == "jmp": finished, new_jmp = jump_to(i+numb,code_list,accnum,called) return finished, new_jmp return True, accnum # go through the loop's instructions and correcting them until it no longer loops def fix_loop(code_list,called): dellac = called dellac.reverse() for i in dellac: backup = code_list[i] instr = re.search("([a-z]*) ([+-][0-9]*)$",backup) if instr.group(1) == "nop": comm = "jmp" elif instr.group(1) == "jmp": comm = "nop" code_list[i] = comm+" "+instr.group(2) new_call = [] finished, accnum = jump_to(0,code_list,0,new_call) if finished: return accnum else: code_list[i] = backup # open input file and list instructions with open("../input_files/console_code.txt","r") as console_code: code_list = [] for line in console_code.readlines(): code_list.append(line) # go through first loop called = [] finsihed, accnum = jump_to(0,code_list,0,called) # then find wrong instruction, fix it and run the code accfinal = fix_loop(code_list,called) # output answers print("*----- FIRST PART -----*\nAccumulator is at %s before second loop starts\n" % accnum) print("*----- SECOND PART -----*\nAccumulator is at %s after final instruction\n" % accfinal)
import requests from bs4 import BeautifulSoup #Entra no site principal site = 'https://saryalternativestore.loja2.com.br' html_site = requests.get(site) soup = BeautifulSoup(html_site.content, "html.parser") #abre o arquivo txt arquivo = open('produtos.txt','w',encoding='utf-8') #identifica as categorias para fazer o get dos produtos categorias = soup.find("div", id="left") items_categorias = categorias.find_all('a') link_categoria ='' for item in items_categorias: try: link_categoria = item.get('href') categoria = item.get_text() print(' ') print(categoria) print(' ') arquivo.write("\n") arquivo.write(categoria+"\n") #Faz o get da pagina da categoria especifica e pega os produtos html_categoria = requests.get(site+link_categoria) soup_categoria = BeautifulSoup(html_categoria.content, "html.parser") table_produtos = soup_categoria.find("div", id="product_list") produtos = table_produtos.find_all("li") for produto in produtos: nome = produto.find("a", attrs={"class": "list_product_name"}).get_text() div_preco = produto.find("div", attrs={"class": "list_price"}) precos = div_preco.find_all("div") preco_final = '' for preco in precos: if preco_final == '': preco_final = preco_final + preco.get_text() else: preco_final = preco_final +' '+ preco.get_text() print(nome +' '+preco_final) arquivo.write(nome +' '+preco_final+'\n') except: pass arquivo.close()
import unittest from Bowling import Bowling class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.bowling_game = Bowling() @unittest.skip def test_environment(self): self.assertEqual(True, False) def test_score_zero(self): self.assertEqual(0, self.bowling_game.get_score()) def test_score_one(self): self.bowling_game.num_balls_hit(1) self.bowling_game.num_balls_hit(0) self.assertEqual(1, self.bowling_game.get_score()) def test_score_strike(self): self.bowling_game.num_balls_hit(10) # Frame 1 strike = 10 + 1 + 2 = 13 self.bowling_game.num_balls_hit(0) # Frame 1 strike self.bowling_game.num_balls_hit(1) # Frame 2 normal 1 + 2 = 3 + 13 = 16 self.bowling_game.num_balls_hit(2) self.assertEqual(16, self.bowling_game.get_score()) def test_score_spare(self): self.bowling_game.num_balls_hit(9) # Frame 1 = 9 self.bowling_game.num_balls_hit(1) # Frame 1 spare = 9 + 1 = 10 + 2 = 12 self.bowling_game.num_balls_hit(2) # Frame 2 = 12 + 2 = 14 self.bowling_game.num_balls_hit(0) # Frame 2 = 14 + 0 = 14 self.assertEqual(14, self.bowling_game.get_score()) if __name__ == '__main__': unittest.main()
#_*_coding:utf-8_*_ ''' @project: Exuding @author: exudingtao @time: 2019/12/23 11:26 下午 ''' def strStr(haystack, needle): len_n = len(needle) len_h = len(haystack) if len_h == 0 and len_n == 0: return 0 if haystack == needle: return 0 for i in range(len_h - len_n+1): print(haystack[i:i + len_n]) if haystack[i:i + len_n] == needle: return i else: continue return -1 print(strStr("mississippi","pi"))
#_*_coding:utf-8_*_ ''' @project: DailyAlgorithm @author: exudingtao @time: 2019/12/14 3:27 下午 ''' #方法一 遍历上次的组合结果,逐个合并 def letterCombinations(digits): KEY = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']} if not digits: return '' res = ['']#res就是一个逐渐添加的 又每一轮都遍历 完成了全排列 for num in digits: temp =[] for char_item in KEY[num]: for r in res: temp.append(char_item+r) res = temp return res #递归 ''' 当没有数字的时候返回空 当只有一个数字的时候,返回该数字对应的字母 当有两个数字的时候,返回第一个数字对应的字母分别加上第二个数字所对应的字母,生成字符串列表 当有三个数字的时候,返回第一个数字对应的字母分别加上后两个数字生成的字符串列表 ''' def letterCombinations1(digits): """ :type digits: str :rtype: List[str] """ dic = { '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'] } result = [] tail = [] len_d = len(digits) if len_d == 0: return tail if len_d == 1: return dic[digits] tail = letterCombinations(digits[1:]) for i in dic[digits[0]]: for j in tail: result.append(i + j) return result ''' 回溯算法(Backtracking)实际上是一个类似枚举的深度优先搜索尝试过程,主要是在搜索尝试过程中寻找问题的解, 当发现已不满足求解条件时,就“回溯”返回到上一步还能执行的状态,尝试别的路径,类似于走迷宫一样。 每次退回就是每次的回溯,所以回溯法要保存每一次的状态。 回溯算法也是一种选优搜索法,按照选优条件向前搜索,以达到目标。 但当探索到某一步时,发现原先选择并不优或者达不到目标,就退回一步重新选择, 这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。 其实就是深度优先搜索的策略,从根结点出发深度搜索。 当探索到某一节点时,要先判断该节点是否包含问题的解, 如果包含,就从该节点出发继续探索下去,若该节点不包含问题的解,则逐层向其祖先节点回溯。 若用回溯法求问题的所有解时,要回溯到根,且跟节点的所有可行的子树都要已被搜索遍才结束。 ''' print(letterCombinations1('23'))
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return "" res = "" for j in range(len(strs[0])): c = strs[0][j] for i in range(1, len(strs)): if j >= len(strs[i]) or strs[i][j] != c: return res res += c return res
#!/usr/bin/env python3 #-*- coding: utf-8 -*- def commas(N): digits = str(N) assert(digits.isdigit()) result = '' while digits: digits, last3 = digits[:-3], digits[-3:] result = (last3 + ',' + result) if result else last3 return result def money(N, width=0): sign = '-' if N < 0 else '' N = abs(N) whole = commas(int(N)) fract = ('%.2f' % N)[-2:] format = '%s%s.%s' % (sign, whole, fract) return '$%*s' % (width, format) if __name__ == '__main__': import sys if len(sys.argv) == 1: print('usage: formats.py number width') else: print(money(float(sys.argv[1]), int(sys.argv[2])))
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """ L = [1, 2, 4, 8, 16, 32, 64] X = 5 found = False i = 0 while not found and i < len(L): if 2 ** X == L[i]: found = True else: i = i+1 if found: print('at index', i) else: print(X, 'not found') """ # a. 首先,以while循环else分句重写这个代码来消除found标志位和最终的if语句。 """ L = [1, 2, 4, 8, 16, 32, 64] X = 5 i = 0 while L[i] != 2 ** X: i += 1 else: if i < len(L): print('at index', i) else: print(X, 'not found') """ # b. 接着,使用for循环和else分句重写这个例子,去掉列表索引运算逻辑。提示: # 要取得元素的索引,可以使用index方法(L.index(X)返回列表L中第一个X的 # 偏移值)。 """ L = [1, 2, 4, 8, 16, 32, 64] X = 5 for i in L: if i == 2 ** X: print('at index', L.index(i)) break; else: print(X, 'not found') """ # c. 接着,重写这个例子,改用简单的in运算符成员关系表达式,从而完全移除循环 # (参考第8章的细节,或者以这种方式来测试:2 in [1, 2, 3]) """ L = [1, 2, 4, 8, 16, 32, 64] X = 5 if 2 ** X in L: print('at index', L.index(2 ** X)) else: print(X, 'not found') """ # d. 最后, 使用for循环和列表append方法来产生2列表(L),而不是通过列表常量 # 硬编码。 """ L = [] X = 5 for i in range(7): L.append(2 ** i) print(L) if 2 ** X in L: print('at index', L.index(2 ** X)) else: print(X, 'not found') """ # e. 把2 ** X表达式移到循环外,这样能够改善性能吗?(能, 每次循环都计算一次, # 比只计算一次性能要好)如何编写代码? """ L = [1, 2, 4, 8, 16, 32, 64] X = 5 found = False target = 2**X i = 0 while not found and i < len(L): if target == L[i]: found = True else: i = i+1 if found: print('at index', i) else: print(X, 'not found') """ # f. 就像我们在练习题1中所看到过的,Python有一个map(function, list)工具也可 # 以产生2次方值的列表:map(lambda x: 2 ** x, range(7))。试着在交互模式下 # 输入这段代码;我们将会在第19章正式引入lambda。 X = 5 L = list(map(lambda x: 2 ** x, range(7))) if 2 ** X in L: print('at index', L.index(2 ** X)) else: print(X, 'not found')
# Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来,看例子: names = ['lizhenye','buxizhou','peakli'] for name in names: print(name) # 所以for x in ...循环就是把每个元素代入变量x,然后执行缩进块的语句。 sum = 0 for x in [1,2,3,4,5,6,7,8,9]: sum=sum+x print(sum) # 注意一句话 有冒号的下一行往往要缩进,该缩进就缩进 # range(start, stop[, step]) # start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5); # stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5 # step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1) sum = 0 list = list(range(101)) for i in list: print(i) sum += i print(sum) # while循环,只要条件满足,就不断循环,条件不满足时退出循环。比如我们要计算100以内所有奇数之和,可以用while循环实现: sum = 0 n = 99 while n > 0: sum += n n -= 2 print(sum) # break 在循环中,break语句可以提前退出循环。例如,本来要循环打印1~100的数字: n = 1 while n <= 100: if n > 10: # 当n = 11时,条件满足,执行break语句 break # break语句会结束当前循环 print(n) n = n + 1 print('END') # continue上面的程序可以打印出1~10。但是,如果我们想只打印奇数,可以用continue语句跳过某些循环: n = 0 while n < 10: n = n + 1 if n % 2 == 0: # 如果n是偶数,执行continue语句 continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行 print(n) # 小结 # 循环是让计算机做重复任务的有效的方法。 # break语句可以在循环过程中直接退出循环,而continue语句可以提前结束本轮循环,并直接开始下一轮循环。这两个语句通常都必须配合if语句使用。 # 要特别注意,不要滥用break和continue语句。break和continue会造成代码执行逻辑分叉过多,容易出错。大多数循环并不需要用到break和continue语句,上面的两个例子, # 都可以通过改写循环条件或者修改循环逻辑,去掉break和continue语句。 # 有些时候,如果代码写得有问题,会让程序陷入“死循环”,也就是永远循环下去。这时可以用Ctrl+C退出程序,或者强制结束Python进程。 # 请试写一个死循环程序。 n = 0 while n>=-10000: print("n:",n) n -= 1
#INPUT #1 candy name #2 price per pound #3 numbers sold #PROCESS #1 determine if is best seller #2 if candy is best seller (2000 pounds per month) #OUTPUT #display item data def main(): isValid = False while not isValid: candy = input("Please enter candy. Either Hersheys, Snickers or MilkyWay\n") if not isValidInput(candy): print("Sorry, Invalid Input") #exit(0) else: isValid = True price_per_pund = float(input("Enter price per pound")) amt_sold = float(input("Enter amt Sold")) if isBestSeller(amt_sold): print('This is a best Seller') else: print('Not a best seller, try harder') def isValidInput(candySelection): if candySelection == 'Hersheys' or candySelection == 'Snickers' or candySelection == 'MilkyWay': return True else: return False def isBestSeller(amtSold): return amtSold > 2000 main()
name = 'abc def ghi' characters = list(name) # print(name) # print(characters) a1 = 'abc,def,ghi' a2 = a1.split(",") print(a2)
items = ['14', '-46', '5', '123', '-8'] i = int(input("Enter a number") if i in items: print("found, ", position) elif not i in items: print("not found in list")
items = ['abc', 'def', 'ghi'] items = [item.capitalize() for item in items] print(items)
import os from datetime import datetime # Targil: # 1. add to file print the size of each file # 2. add to file print the last modified of each file # 3. read input file name from the user - print in which folder it exist, or not exist # *etgar read only part of file name or i.e. *.txt # 4. read extension from the user - print all files ending with this extension and their location print(os.getcwd()) os.chdir('C:/itay') def answer1_2(): for dirpath, dirnames, filenames\ in os.walk('c:/itay'): d1 = dirpath.replace('\\', '/') print(f'------- {d1}') for d in dirnames: print(f'[{d}]') for d in filenames: size = os.stat( os.path.join(dirpath, d) ).st_size l_mod = os.stat( os.path.join(dirpath, d) ).st_mtime time = datetime.fromtimestamp(l_mod) print(f'{d} {size} Bytes ... [{time}]') def answer3(searchFor): for dirpath, dirnames, filenames\ in os.walk('c:/itay'): if searchFor in filenames: return f'Found: {dirpath}' for n in filenames: if n.find(searchFor) >= 0: return f'Found: {dirpath} {n}' return "Not found" fname = 'set_exercise.py' print(answer3(fname)) fname = 'set' # etgar print(answer3(fname)) def answer4(searchForExt): for dirpath, dirnames, filenames\ in os.walk('c:/itay'): for n in filenames: if searchForExt == os.path.splitext(n)[1]: print (n) fname = 'set_exercise.py' answer4(".py")
from datetime import * class HashtagGraphEdges: """ Double linked list method is used to build the Twitter hashtag graph. The double linked list stands for the structure of the hashtags according. The keys of dictionary are the edges of two hastags(hashtage_pair in hashtage_pair_list) and the coressponding values are double linked nodes(storing the hashtage_pair and datetime) This data structure aims to get the total edges og tweets in latest 60s, the degrees of nodes in Twitter hashtag graph is 2*the number of edges. """ # Double Linked List DuLNode class DuLNode: def __init__(self, hashtag_pair, datetime): self.hashtag_pair = hashtag_pair # hashtage_pair self.datetime = datetime # datetime self.prev = None self.next = None # Double linked list initialization # Create the head and tail nodes of the double linked list # Connect the head and tail node def __init__(self): self.edges = {} # each hashtag_pair is an edge, set the hashtag_pair as the key of the dictionary self.head = self.DuLNode(None, None) # head and tail nodes are void self.tail = self.DuLNode(None, None) self.head.next = self.tail self.tail.next = self.head # Set a list of hashtag_pair to the data structure # Return a list of timeout hashtag_pair def get_edges(self, hashtag_pair_list, time): for hashtag_pair in hashtag_pair_list: self.add_node(hashtag_pair, time) return self.remove_edges(time) # Add every new DuLNode to the double linked list # Each DuLNode has value <hashtag_pair, datetime>, use hashtag_pair as the key, and the DuLNode as the value of the key def add_node(self, hashtag_pair, datetime): if None != self.check_node(hashtag_pair): self.edges.get(hashtag_pair).datetime = datetime else: current = self.DuLNode(hashtag_pair, datetime) if 0 == len(self.edges): self.head.next = current current.prev = self.head current.next = self.tail self.tail.prev = current else: self.move_node_to_tail(current) self.edges[hashtag_pair] = current # Check whether the new DuLNode is in the double linked list # If yes, move the node to the tail of double linked list def check_node(self, hashtag_pair): if hashtag_pair not in self.edges: return None else: current = self.edges[hashtag_pair] current.prev.next = current.next current.next.prev = current.prev self.move_node_to_tail(current) return current.datetime # Move the current DuLNode to tail of the double linked list def move_node_to_tail(self, current): self.tail.prev.next = current current.prev = self.tail.prev current.next = self.tail self.tail.prev = current # Remove timeout hashtag_pair in the data structure def remove_edges(self,current_time): remove_edges = [] timestamp = current_time - timedelta(seconds = 60) current = self.head.next while (current != self.tail and current.datetime < timestamp): self.head.next = current.next current.next.prev = self.head remove_edges.append(current.hashtag_pair) del self.edges[current.hashtag_pair] current = current.next return remove_edges class HashtagGraphNodes: """ This data structure aims to get the total hashtags(nodes) in the in Twitter hashtag graph in latest 60s. """ def __init__(self): self.nodes = {} # Hashtag(node) in the Hashtag Graph # Store hashtag pairs in the data structure # Each hashtag is the key of dictionary and the value is another hashtage connnected with it def get_nodes(self, hashtag_pair_list): for hashtag_pair in hashtag_pair_list: # first hashtag of hashtag_pair if hashtag_pair[0] not in self.nodes: self.nodes[hashtag_pair[0]] = set([hashtag_pair[1]]) # first edge to the hashtag else: self.nodes[hashtag_pair[0]].add(hashtag_pair[1]) # other edge to the hashtag # second hashtag of hashtag_pair if hashtag_pair[1] not in self.nodes: self.nodes[hashtag_pair[1]] = set([hashtag_pair[0]]) else: self.nodes[hashtag_pair[1]].add(hashtag_pair[0]) # Remove hashtag pairs in the data structure def remove_nodes(self, remove_edges): for edge in remove_edges: self.nodes[edge[0]].remove(edge[1]) if 0 == len(self.nodes[edge[0]]): del self.nodes[edge[0]] # when the hashtag(node) has no edge, remove this hashtage(node) in Hashtag Graph self.nodes[edge[1]].remove(edge[0]) if 0 == len(self.nodes[edge[1]]): del self.nodes[edge[1]]
def payingDebtOffInOneYear(balance, annualInterestRate, monthlyPaymentRate, months=12): """ Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. """ def pay_monthly(balance, annualInterestRate, monthlyPaymentRate): monthly_interest_rate = annualInterestRate / 12.0 minimum_monthly_payment = monthlyPaymentRate * balance monthly_unpaid_balance = balance - minimum_monthly_payment updated_balance_each_month = monthly_unpaid_balance + (monthly_interest_rate * monthly_unpaid_balance) print(updated_balance_each_month) return(updated_balance_each_month) if months == 0: return(round(balance, 2)) else: return payingDebtOffInOneYear(pay_monthly(balance, annualInterestRate, monthlyPaymentRate), annualInterestRate, monthlyPaymentRate, months-1) # print(payingDebtOffInOneYear(60000, 0.2, 0.1)) # this following line makes the edX userface work: # print(payingDebtOffInOneYear(balance, annualInterestRate, monthlyPaymentRate)) def payingDebtOffInOneYear(balance, annualInterestRate): """ Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. """ monthly_rate = annualInterestRate / 12 minimum_monthly_payment = 10 new_balance = float(balance) while balance > 0: minimum_monthly_payment += 5 balance = new_balance for month in range(12): balance -= minimum_monthly_payment balance += balance * monthly_rate return('Lowest Payment: ' + str(minimum_monthly_payment)) # print(payingDebtOffInOneYear(3310 , 0.2)) # print(payingDebtOffInOneYear(balance,annualInterestRate)) def payOffwithBisectionSearch(balance, annualInterestRate): """ 若要求已知函数 f(x) = 0 的根 (x 的解),则: 先找出一个区间 [a, b],使得f(a)与f(b)异号。根据介值定理,这个区间内一定包含着方程式的根。 求该区间的中点 m = (a+b) /2,并找出 f(m) 的值。 若 f(m) 与 f(a) 正负号相同则取 [m, b] 为新的区间, 否则取 [a, m]. 重复第2和第3步至理想精确度为止。 """ global new_balance new_balance = float(balance) start_pay = float(balance/12) end_pay = float(balance) def pay(minimum_monthly_payment): balance = new_balance monthly_rate = annualInterestRate / 12 for month in range(12): balance -= minimum_monthly_payment balance += balance * monthly_rate return(balance) def binarySearch(start, end): mid = ((start + end)/2) if -1 < pay(mid) < 1: # print('perf') return mid elif pay(mid) > 1: # print('paying too little') # print(mid,end) return(binarySearch(mid, end)) elif pay(mid) < -1: # print('paying too much') # print(start,mid) return(binarySearch(start, mid)) return(round(binarySearch(start_pay, end_pay), 2)) print(payOffwithBisectionSearch(balance, annualInterestRate)) # print(payOffwithBisectionSearch(999999, 0.18))
# ------------------------------------------------------------- # Метод подсчёта прироста def Bank(Money,Percent): return (Money / 100) * Percent # ------------------------------------------------------------- # Главный метод def main(): print("Задача с банком") # Начальные условия Money, Percent, Up, Month, = 1000, 2, 0, 0 Triger_1, Triger_2 = True, True Task_1, Task_2 = 0, 0 # Цикл программы while(Money < 1200 or Up < 30): # Счёт Up = Bank(Money, Percent) Money = Money + Up Month += 1 print("Месяц: ", Month, ";\t Счёт: ", round(Money,2),";\t Увеличение вклада: ", round(Up,2)) # Сохраняем ключевые месяцы if(Money >= 1200 and Triger_1): Task_1 = Month; Triger_1 = False if(Up >= 30 and Triger_2): Task_2 = Month; Triger_2 = False # Выводим результат print("\nИтог:") print("Через ", Task_1, " месяцев величина ежемесячного увеличения вклада превысит 30 рублей") print("Через ", Task_2, " месяцев размер вклада превысит 1200 руб") # ------------------------------------------------------------- if __name__ == "__main__": main() # -------------------------------------------------------------
from Tkinter import * ''' Author: Federico Terzi This module just display a basic window to show the output of the "start.py" module This is a work in progress.... ''' class TextWindow: def __init__(self, master): self.root = master frame = Frame(master) frame.pack() master.title("Gesture Keyboard Output") self.label = Label(master, text="Connecting...", font=("Helvetica", 80)) self.label.configure(wraplength=600) self.label.pack() self.update_clock() def update_clock(self): input_file = open("output.txt") self.label.configure(text=input_file.read()) input_file.close() self.root.after(100, self.update_clock) root = Tk() app = TextWindow(root) root.mainloop() root.destroy()
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import pygame from punto import Punto from variables import (TRAYECTORIA_COLOR, TRAYECTORIA_GROSOR) class Trayectoria: """Una Trayectoria representa la trayectoria de una partícula, almacenando los datos más relevantes de su movimiento: puntos en x e y, velocidades en esos puntos, y el tiempo en esos puntos. Attributes: puntos (:class: Dict[int, int]): las alturas registradas en la trayectoria. velocidades (:class: Dict[int, Vector]): las velocidades registradas en la trayectoria. tiempos: (:class: Dict[int, double]): Los tiempos regisrados en la trayectoria. """ def __init__(self): self._puntos = {} self._velocidades = {} self._tiempos = {} @property def puntos(self): return self._puntos @puntos.setter def puntos(self, value): self._puntos = value @property def velocidades(self): return self._velocidades @velocidades.setter def velocidades(self, value): self._velocidades = value @property def tiempos(self): return self._tiempos @tiempos.setter def tiempos(self, value): self._tiempos = value def mostrar(self): """Imprime a el registro de todos los datos capturados en la trayectoria """ for k in self.puntos.keys(): print("Punto x: ", k) print("\tAltura: ", self.puntos[k]) print("\tVelocidad: ", self.velocidades[k]) print("\tTiempo: ", self.tiempos[k]) def add_punto(self, punto): """Añade un punto a la trayectoria. Separa el punto en su coordenada en x y usa esta coordenada como la llave para el valor de su coordenada en y. Args: punto (:class: Punto): un punto para añadir a la trayectoria """ self.puntos[punto.x] = punto.y def registrar(self, punto, velocidad, tiempo): """Registra un conjunto de variables a un punto en x específico. Args: punto (:class: Punto): un punto para añadir a la trayectoria. velocidad (:class: Vector): Una velocidad para añadir a la trayectoria. tiempo (:obj:double): Un tiempo para añadir a la trayectoria. """ self.puntos[punto.x] = punto.y self.velocidades[punto.x] = velocidad self.tiempos[punto.x] = tiempo def get_punto_y(self, punto_x): return self.puntos[punto_x] def get_velocidad(self, punto_x): return self.velocidades[punto_x] def get_tiempo(self, punto_x): return self.tiempos[punto_x] def clear(self): """Borra todos los registros de la trayectoria """ self.puntos = {} self.velocidades = {} self.tiempos = {} def render(self, canvas): """Renderiza cada punto en pantalla. Si la cantidad de puntos es grande, los puntos estarán tan juntos que parecerá una línea continua Args: canvas (:class: Canvas): El canvas donde dibujar la trayectoria. """ for punto_x, punto_y in self.puntos.items(): pygame.draw.circle(canvas.superficie, TRAYECTORIA_COLOR, (punto_x, punto_y), TRAYECTORIA_GROSOR, 0)
# Scipy # Numpy provides a high-performance multidimensional array and # basic tools to compute with and manipulate these arrays. # Scipy builds on this, and provides a large number of functions # that operate on numpy arrays and are useful for different types # of scientific and engineering applications. # Image operations # Scipy provides some basic functions to work with images. # For example, it has functions to read images from disk # into numpy arrays, to write numpy arrays to disk as images, # and to resize images. Here is a simple example that # showcases these functions: from scipy.misc import imread, imsave, imresize from scipy.spatial.distance import pdist, squareform import numpy as np import matplotlib.pyplot as plt # Read an JPEG image into a numpy array img = imread('assets/cat.jpg') print img.dtype, img.shape # Prints "uint8 (400, 248, 3)" # We can tint the image by scaling each of the color channels # by a different scalar constant. The image has shape (400, 248, 3); # we multiply it by the array [1, 0.95, 0.9] of shape (3,); # numpy broadcasting means that this leaves the red channel unchanged, # and multiplies the green and blue channels by 0.95 and 0.9 # respectively. img_tinted = img * [1, 0, 0.9] # Resize the tinted image to be 300 by 300 pixels. img_tinted = imresize(img_tinted, (300, 300)) # Write the tinted image back to disk imsave('assets/cat_tinted.jpg', img_tinted) # MATLAB files # The functions scipy.io.loadmat and scipy.io.saveamat allow you # to read and write MATLAB files. # Distance between points # Scipy defines some useful functions for computing distance # between sets of points # The function scipy.spatial.distance.pdist computes the distance # between all pairs of points in a given set: # Create the following array where each row is a point in 2D space: # [[0 1] # [1 0] # [2 0]] x = np.array([[0, 1], [1, 0], [2, 0]]) print x # Compute the Euclidean distance between all rows of x. # d[i, j] is the Euclidean distance between x[i, :] and x[j, :], # and d is the following array: # [[0. 1.414 2.236] # [1.414 0. 1. ] # [2.236 1. 0. ]] d = squareform(pdist(x, 'euclidean')) print d # Matplotlib # Matplotlib is plotting library. In this section give a brief # introduction to the matplotlib.pyplot module, which provides # a plotting system similar to that of MATLAB. # Plotting # The most important function in matplotlib is plot, which # allows you to plot 2D data. Here is a simple example: # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) # Plot the points using matplotlib plt.figure(1) plt.plot(x, y) # plt.show() # You must call plt.shoe() to make graphics appear. # With just a little bit of extra work we can easily plot # multiple lines at once, and add a title, legend, and axis labels: # Compute the x and y coordinates for points on sine and cosine curves x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # Plot the points using matplotlib plt.figure(2) plt.plot(x, y_sin) plt.plot(x, y_cos) plt.xlabel('x axis label') plt.ylabel('y axis label') plt.title('Sine and Cosine') plt.legend(['Sine', 'Cosien']) # plt.show() # Subplots # You can plot different things in the same figure using the subplot # functions. Here is an example: # Compute the x and y coordinates for points on sine and cosine curves x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # Set up a subplot grid that has height 2 and width 1, # and set the first such subplot as active. plt.figure(3) plt.subplot(2, 1, 1) # Make the first plot plt.plot(x, y_sin) plt.title('Sine') # Set the second subplot as acitve, and make the second plot. plt.subplot(2, 1, 2) plt.plot(x, y_cos) plt.title('Cosine') # Show the figure # plt.show() # Images # You can use the imshow functions to show images. # Here is an example: img = imread('assets/cat.jpg') img_tinted = img * [1.5, 1.5, 1.5] # Show the original image plt.figure(4) plt.subplot(1, 2, 1) plt.imshow(img) print img_tinted.dtype # Show the tinted image plt.subplot(1, 2, 2) # A slight gotcha with imshow is that it might five strange results # if presented with data that is not uint8. To work around this, we # explicitly cast the image to uint8 before displaying it. plt.imshow(np.uint8(img_tinted)) plt.show()
import json class JsonIO: """Class Performs JSON IO""" @staticmethod def read_json_file(path) -> []: """Reads in JSON File""" with open(path) as f: return json.load(f) @staticmethod def write_json_file(path, data): """Writes Data JSON File Using Dump""" with open(path, 'w') as json_file: d = json.dumps(data) json_file.write(d) @staticmethod def write_lst(lst,file_): """Writes List to JSON File with '\n Delimiter'""" try: iterator = iter(lst) except TypeError: return else: with open(file_,'w') as f: for l in iterator: f.write(" ".join(l)) f.write('\n') @staticmethod def read_lst(file): """Reads List from JSON file with \n Delimiter""" return [line.rstrip('\n').split() for line in open(file)]
from turtle import * speed('fastest') hideturtle() # The original challenge was to make a Sierpinski drawer that was iterative # instead of recursive in order to cope with Python's recursion depth limit, # but after failing to find a way after considerable effort I conjectured that # it was impossible to convert the recursion relation into an iterative form. # So, I tried to write a program that passed every edge of the Sierpinski # triangle once which is possible since the triangle is an Euler graph and # to use the min. number of moves doing so. A move is a fd/lt/rt command. # I think my program minimizes the moves (note: I'm assuming you cannot pick up the pen). # right is a boolean denoting if the previous turn was a right or left one def draw_sierpinski_recurse(iters, side, right): if iters < 2: return half_side = side/2 left = not right if right: lt(60) else: rt(60) for i in range(3): fd(half_side) draw_sierpinski_recurse(iters-1, half_side, left) fd(half_side) # this is the last side if the triangle if i == 2: break if right: lt(120) else: rt(120) if right: lt(60) else: rt(60) # input: # iters, the number of recursive iterations to perform # side, the side length of the biggest triangle # init_x, init_y, init_angle, these are the optional initial conditions for the turtle def draw_sierpinski_triangle(iters, side, init_x=0, init_y=0, init_angle=0): if iters < 1 or side < 0: return # the initial setup up() setpos(init_x, init_y) down() lt(init_angle) # draw the big outer triangle half_side = side/2 fd(half_side) draw_sierpinski_recurse(iters, half_side, True) fd(half_side) lt(120) fd(side) lt(120) fd(side) def main(): draw_sierpinski_triangle(6, 256, 0, 0, 180) if __name__ == '__main__': main()
''' Given the root of a binary tree, return the maximum average value of a subtree of that tree. A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes. ''' from leetcode import * class Solution: # Time: O(n) # Space: O(H) where H is the height of the tree. def maximumAverageSubtree(self, root: Optional[TreeNode]) -> float: if root is None: return 0 def postorder(root): numNodes = 1 nodeSum = root.val maxAvgLeft = 0 maxAvgRight = 0 if root.left != None: numNodesLeft, nodeSumLeft, maxAvgLeft = postorder(root.left) numNodes += numNodesLeft nodeSum += nodeSumLeft if root.right != None: numNodesRight, nodeSumRight, maxAvgRight = postorder(root.right) numNodes += numNodesRight nodeSum += nodeSumRight return (numNodes, nodeSum, max(maxAvgLeft, maxAvgRight, nodeSum / numNodes)) _, _, maxAvg = postorder(root) return maxAvg
''' You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them. Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points. ''' from leetcode import * # NOTE: I went rogue here. I should use the standard Kruskal's or Prim's algorithm to get the MST. Prim's can run in O(n^2) time and O(n) space. # Time: O(n^2 * log(n)). I didn't use the union-find data structure, but I believe that determining components and joining them up is a # nearly constant operation like in union-find, so the bulk of the time is taken up by sorting the n^2 edges, O(n^2 * log(n^2)) = O(n^2 * log(n)). # Space: O(n^2 + n) = O(n^2). class Solution: def minCostConnectPoints(self, points: List[List[int]]) -> int: distancesToLines = {} for i in range(len(points) - 1): for j in range(i + 1, len(points)): dist = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) lines = distancesToLines.get(dist, []) if len(lines) == 0: distancesToLines[dist] = lines lines.append((i, j)) components = [] numLines = 0 cost = 0 for d in sorted(distancesToLines.keys()): lines = distancesToLines[d] for i, j in lines: if numLines == len(points) - 1: return cost componenti = -1 for k in range(len(components)): if i in components[k]: componenti = k break if componenti != -1 and j in components[componenti]: continue componentj = -1 for k in range(len(components)): if j in components[k]: componentj = k break numLines += 1 cost += d if componenti == -1 and componentj == -1: components.append(set([i, j])) elif componenti != -1 and componentj == -1: components[componenti].add(j) elif componenti == -1 and componentj != -1: components[componentj].add(i) else: components[componenti].update(components[componentj]) components.pop(componentj) return cost solution = Solution() # Expected: 20 print(solution.minCostConnectPoints([[0,0],[2,2],[3,10],[5,2],[7,0]])) # Expected: 18 print(solution.minCostConnectPoints([[3,12],[-2,5],[-4,1]]))
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". ''' from leetcode import * # Time: O(n * |s_min|) where |s_min| is the length of the shortest string in the array, Space: O(n * |s_min|) because # you could keep taking the substring of the prefix. def longest_common_prefix(strs: List[str]) -> str: num_strs = len(strs) if num_strs == 0: return "" # Set the longest prefix to the shortest string: longest_prefix = strs[0] for i in range(1, num_strs): if len(strs[i]) < len(longest_prefix): longest_prefix = strs[i] if len(longest_prefix) == 0: return "" for i in range(num_strs): s = strs[i] min_len = min(len(s), len(longest_prefix)) for j in range(min_len): if s[j] != longest_prefix[j]: longest_prefix = longest_prefix[:j] break if min_len < len(longest_prefix): longest_prefix = longest_prefix[:min_len] return longest_prefix print(longest_common_prefix(["flower","flow","flight"])) print(longest_common_prefix(["dog","racecar","car"])) print(longest_common_prefix(["aa","a"]))
''' Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings. ''' from leetcode import * # Time: O(nlog(n)) # Space: O(1) class Solution: def canAttendMeetings(self, intervals: List[List[int]]) -> bool: intervals.sort() for i in range(1, len(intervals)): if intervals[i][0] < intervals[i - 1][1]: return False return True solution = Solution() # Expected: False print(solution.canAttendMeetings([[0,30],[5,10],[15,20]])) # Expected: True print(solution.canAttendMeetings([[7,10],[2,4]]))
''' Return the root node of a binary search tree that matches the given preorder traversal. Note: - The values of preorder are distinct. ''' from leetcode import * # Time: O(n), Space: O(n). # I thought it might be O(n^2) in the worst case, but you do not visit a node more than twice so it's linear. def bst_from_preorder(preorder: List[int]) -> TreeNode: # Assume that there is at least one element in the preorder list. root = TreeNode(preorder[0]) stack = [root] for i in range(1, len(preorder)): val = preorder[i] new_node = TreeNode(val) # This node's value is less than the previous one (i.e. it's parent node) meaning it's to the left of it. if preorder[i - 1] > val: stack[-1].left = new_node else: parent_node = stack.pop() while len(stack) != 0: if val < stack[-1].val: break parent_node = stack.pop() parent_node.right = new_node stack.append(new_node) return root # There is also a nice recursive algorithm, but Python's recursion stack limit makes me hesitate to implement # recursion when there is a way to avoid it. print_bin_tree_bfs(bst_from_preorder([8, 5, 1, 7, 10, 12]))
from leetcode import * class Solution: # Time: O(n). # Space: O(n). def calPoints(self, ops: List[str]) -> int: record = [] for i in ops: if i == '+': record.append(record[-1] + record[-2]) elif i == 'D': record.append(2*record[-1]) elif i == 'C': record.pop() else: record.append(int(i)) return sum(record) solution = Solution() # Expected: 30 print(solution.calPoints(["5","2","C","D","+"])) # Expected: 27 print(solution.calPoints(["5","-2","4","C","D","9","+","+"])) # Expected: 1 print(solution.calPoints(["1"]))
''' Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. ''' from leetcode import * class Solution: # Space: O(n). # Time: O(n). def increasingBST(self, root: TreeNode) -> TreeNode: arr = [] def inOrderTraversal(root: TreeNode) -> None: if root.left != None: inOrderTraversal(root.left) arr.append(root) if root.right != None: inOrderTraversal(root.right) inOrderTraversal(root) for i in range(len(arr) - 1): node = arr[i] node.left = None node.right = arr[i + 1] lastNode = arr[-1] lastNode.left = lastNode.right = None return arr[0] # From Leetcode, this solution relinks the tree in one pass by using a pointer. # Time: O(n). # Space: O(H), so the height of the tree. def increasingBST2(self, root: TreeNode) -> TreeNode: dummyNode = TreeNode(None) self.currentNode = dummyNode def inOrderTraversal(root: TreeNode) -> None: if root.left != None: inOrderTraversal(root.left) root.left = None self.currentNode.right = root self.currentNode = root if root.right != None: inOrderTraversal(root.right) return inOrderTraversal(root) return dummyNode.right
''' Given a circle represented as (radius, x_center, y_center) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return True if the circle and rectangle are overlapped otherwise return False. Note: they overlap even if the circle and rectangle meet at a single point. ''' # Time: O(1), Space: O(1). def check_overlap(radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool: # Check if circle's center within left and right edges of rectangle: if x_center >= x1 and x_center <= x2: # Check if circle is within rectangle: if y_center >= y1 and y_center <= y2: return True # Otherwise, check if circle's center is at most a distance of radius away from either the top or bottom edges. return min(abs(y2 - y_center), abs(y1 - y_center)) <= radius # Check if circle's center is within top and left edges of rectangle: elif y_center >= y1 and y_center <= y2: # If so, check if circle's center is at most a distance of radius away from either the left or right edges. return min(abs(x2 - x_center), abs(x1 - x_center)) <= radius else: # Get the one of the 4 corners that is closest to the circle's center: x_corner = x1 if x_center < x1 else x2 y_corner = y1 if y_center < y1 else y2 # Check if the rectangle's closest corner is within the circle or not: return ((x_corner - x_center)**2 + (y_corner - y_center)**2) <= radius**2 # Another very clever Leetcode solution: def check_overlap_v2(radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool: # Find the nearest point on the rectangle to the center of the circle x_nearest = max(x1, min(x_center, x2)) y_nearest = max(y1, min(y_center, y2)) # Find the distance between the nearest point and the center of the circle return ((x_nearest - x_center)**2 + (y_nearest - y_center)**2) <= radius**2 # My solution does basically this but in a much more verbose and ugly way. This is beautiful! # Expected: True print(check_overlap(radius = 1, x_center = 0, y_center = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1)) # Expected: True print(check_overlap(radius = 1, x_center = 0, y_center = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1)) # Expected: True print(check_overlap(radius = 1, x_center = 1, y_center = 1, x1 = -3, y1 = -3, x2 = 3, y2 = 3)) # Expected: False print(check_overlap(radius = 1, x_center = 1, y_center = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1)) # Expected: True print(check_overlap(radius = 24, x_center = 13, y_center = 1, x1 = 0, y1 = 15, x2 = 5, y2 = 18)) print(check_overlap_v2(radius = 1, x_center = 0, y_center = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1)) print(check_overlap_v2(radius = 1, x_center = 0, y_center = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1)) print(check_overlap_v2(radius = 1, x_center = 1, y_center = 1, x1 = -3, y1 = -3, x2 = 3, y2 = 3)) print(check_overlap_v2(radius = 1, x_center = 1, y_center = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1)) print(check_overlap_v2(radius = 24, x_center = 13, y_center = 1, x1 = 0, y1 = 15, x2 = 5, y2 = 18))
from leetcode import * # Level order representation approach similar to how Leetcode represents trees. # Time: O(n) for both operations where n is the number of nodes in the tree. # Space: O(n) for both operations where n is the number of nodes in the tree. # From Leetcode, you could also do a preorder DFS representation, but I think this one is more natural. class Codec: def serialize(self, root): if root is None: return '[]' queue = deque([root]) levelOrder = [] while len(queue) != 0: levelLen = len(queue) for i in range(levelLen): node = queue.popleft() if node is None: levelOrder.append(None) continue levelOrder.append(node.val) if node.left != None: queue.append(node.left) else: queue.append(None) if node.right != None: queue.append(node.right) else: queue.append(None) # Get rid of trailing null values. while len(levelOrder) != 0 and levelOrder[-1] is None: levelOrder.pop() return str(levelOrder) def deserialize(self, data): levelOrder = data[1:-1].split(', ') if len(levelOrder[0]) == 0: return None root = TreeNode(int(levelOrder[0])) queue = deque([root]) idx = 1 while len(queue) != 0 and idx < len(levelOrder): node = queue.popleft() if levelOrder[idx] != 'None': node.left = TreeNode(int(levelOrder[idx])) queue.append(node.left) if (idx + 1) == len(levelOrder): break if levelOrder[idx + 1] != 'None': node.right = TreeNode(int(levelOrder[idx + 1])) queue.append(node.right) idx += 2 return root serializer = Codec() print_bin_tree_bfs(serializer.deserialize(serializer.serialize(construct_bin_tree_bfs_array([1,2,3,None,None,4,5])))) print_bin_tree_bfs(serializer.deserialize(serializer.serialize(construct_bin_tree_bfs_array([]))))
''' Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in O(log n) time. ''' from leetcode import * def find_min(nums: List[int]) -> int: start = 0 end = len(nums) - 1 mid = -1 while start <= end: mid = (start + end) // 2 mid_val = nums[mid] if ((mid - 1) < 0 or mid_val < nums[mid - 1]) and ((mid + 1) >= len(nums) or mid_val < nums[mid + 1]): return mid_val elif mid_val > nums[end]: start = mid + 1 else: end = mid - 1 return nums[mid] print(find_min([4,5,6,7,0,1,2])) print(find_min([0,1,2,4,5,6,7])) print(find_min([3,4,5,1,2])) print(find_min([4,5,6,7,0,1,2])) print(find_min([11,13,15,17])) print(find_min([1])) print(find_min([2,1]))
from leetcode import * class Solution: # Recursion # Time: O(H), so O(n) in worst-case and O(log(n)) in average-case. # Space: O(H) def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None: return TreeNode(val) elif root.val < val: root.right = self.insertIntoBST(root.right, val) elif root.val > val: root.left = self.insertIntoBST(root.left, val) return root # Using iteration instead of recursion brings down the space complexity to O(1).
''' Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). ''' class Solution: def hammingWeight(self, n: int) -> int: oneBits = 0 while n > 0: if n & 1: oneBits += 1 n >>= 1 return oneBits
''' You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned. Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language. ''' from leetcode import * class Solution: # Time: O(n) where n is the length of the blacklist. # Space: O(n) def __init__(self, n: int, blacklist: List[int]): blackset = set(blacklist) remapList = [] endRange = n - len(blacklist) for i in blacklist: if i < endRange: remapList.append(i) pos = 0 blackmap = {} for i in range(endRange, n): if i not in blackset: blackmap[remapList[pos]] = i pos += 1 self.n = endRange - 1 self.blackmap = blackmap # Time: O(1) # Space: O(n) where n is the length of the blacklist. def pick(self) -> int: randnum = random.randint(0, self.n) if randnum in self.blackmap: return self.blackmap[randnum] return randnum solution = Solution(7, [2, 3, 5]) print(solution.pick()) print(solution.pick()) print(solution.pick()) print(solution.pick()) print(solution.pick()) print(solution.pick()) print(solution.pick())
''' Write a function that reverses a string. The input string is given as an array of characters s. ''' from leetcode import * # Time: O(n). # Space: O(1). class Solution: # Time: O(n) # Space: O(1) def reverseString(self, s: List[str]) -> None: halfLen = len(s) // 2 i = 0 while i < halfLen: temp = s[i] s[i] = s[len(s) - 1 - i] s[len(s) - 1 - i] = temp i += 1 # Recursion approach # Time: O(n) # Space: O(n) def reverseString2(self, s: List[str]) -> None: def helper(s, start, end): if (end - start) < 1: return s[start], s[end] = s[end], s[start] helper(s, start + 1, end - 1) helper(s, 0, len(s) - 1) solution = Solution() s = ["h","e","l","l","o"] solution.reverseString(s) print(s) s = ["H","a","n","n","a","h"] solution.reverseString(s) print(s)
''' Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. ''' from leetcode import * class Solution: # Backtracking with index # Time: O(2^n) where n is the number of candidates. # Space: O(n) def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: candidates.sort() # Duplicate entries means we could get duplicate combinations. self.combos = [] def recurse(idx: int, target: int, combo: List[int]) -> None: if target == 0: self.combos.append(combo[:]) return elif target < 0: return while idx < len(candidates): newTarget = target - candidates[idx] if newTarget < 0: break combo.append(candidates[idx]) recurse(idx + 1, newTarget, combo) combo.pop() idx += 1 while idx < len(candidates) and candidates[idx] == candidates[idx - 1]: idx += 1 recurse(0, target, []) return self.combos solution = Solution() # Expected: [[1,1,6],[1,2,5],[1,7],[2,6]] print(solution.combinationSum2(candidates = [10,1,2,7,6,1,5], target = 8)) # Expected: [[1,2,2],[5]] print(solution.combinationSum2(candidates = [2,5,2,1,2], target = 5))
''' Given a roman numeral, convert it to an integer. ''' class Solution: # Time: O(n) # Space: O(1) def romanToInt(self, s: str) -> int: integer = 0 numerals = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 400, 'D': 500, 'CM': 900, 'M': 1000} index = 0 while index < len(s): if index < (len(s) - 1) and s[index:(index + 2)] in numerals: integer += numerals[s[index:(index + 2)]] index += 2 else: integer += numerals[s[index]] index += 1 return integer solution = Solution() assert solution.romanToInt("III") == 3 assert solution.romanToInt("LVIII") == 58 assert solution.romanToInt("MCMXCIV") == 1994
''' Given the root of a binary tree, invert the tree, and return its root. ''' from leetcode import * class Solution: # Recursive approach # Time: O(n) where n are the number of nodes in the tree. # Space: O(H) where H is the height of the tree. def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return None root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root solution = Solution() # Expected: [4,7,2,9,6,3,1] print_bin_tree_bfs(solution.invertTree(construct_bin_tree_bfs_array([4,2,7,1,3,6,9]))) # Expected: [2,3,1] print_bin_tree_bfs(solution.invertTree(construct_bin_tree_bfs_array([2,1,3]))) # Expected: [] print_bin_tree_bfs(solution.invertTree(construct_bin_tree_bfs_array([])))
''' Same description as word_ladder.py except: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]. ''' from leetcode import * class Solution: # Time: O(m*n + m*n + A) where m is the length of words, n is the number of words in list, and A is the number of shortest transformations. # Space: O(m*(m*n) + m*n + n) [basically, hash tables + visited/queue sets + backtracking stack] = O(m*(m*n)). def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: wordList.append(beginWord) wordToGeneric = {word: [] for word in wordList} if endWord not in wordToGeneric: return [] genericToWord = {} for i in range(len(wordList)): word = list(wordList[i]) for j in range(len(beginWord)): temp = word[j] word[j] = '*' generic = ''.join(word) wordToGeneric[wordList[i]].append(generic) words = genericToWord.get(generic, set()) words.add(wordList[i]) genericToWord[generic] = words word[j] = temp visited = {beginWord: None} queue = {beginWord} while len(queue) != 0: nextQueue = set() for wordi in queue: if wordi == endWord: break for generic in wordToGeneric[wordi]: for wordj in genericToWord[generic]: if wordj not in visited: nextQueue.add(wordj) visited[wordj] = {wordi} elif wordj in nextQueue and wordi not in visited[wordj]: visited[wordj].add(wordi) queue = nextQueue ladders = [] def dfs(startWord, path): path.append(startWord) if visited[startWord] is None: ladders.append(list(reversed(path))) else: for word in visited[startWord]: dfs(word, path) path.pop() return if endWord not in visited: return ladders dfs(endWord, []) return ladders solution = Solution() # Expected: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] print(solution.findLadders(beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"])) # Expected: [] print(solution.findLadders(beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]))
''' Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. ''' from leetcode import * class Solution: # Backtracking approach # Time: O(n*(2^n)) where n is the number of elements in nums. # Space: O(n) def subsets(self, nums: List[int]) -> List[List[int]]: self.powerset = [] def backtrack(i, subset): self.powerset.append(subset[:]) for j in range(i, len(nums)): subset.append(nums[j]) backtrack(j + 1, subset) subset.pop() return backtrack(0, []) return self.powerset solution = Solution() # Expected: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] print(solution.subsets([1,2,3])) # Expected: [[],[0]] print(solution.subsets([0]))
''' You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. Return the maximum number of points you can achieve. ''' from leetcode import * class Solution: # Bottom-up DP approach. # Original recurrence relation: dp[i][j] = max(dp[i - 1][k] - abs(k - j)) + points[i][j] for k = 0..n # This gives an O(n^3) runtime which is too slow. # For a certain index i, the maximum value for i is a index that could either come from its left, or its right. # Thus, we can build two arrays (I used just one by being clever) and focus on the maximum value only coming from its left or right. # Finding the best fit for a single index i could just cost O(1) time from then on. # # Time: O(m*n) # Space: O(n) def maxPoints(self, points: List[List[int]]) -> int: m = len(points) n = len(points[0]) dp = points[0][:] for i in range(1, m): for j in range(1, n): dp[j] = max(dp[j - 1] - 1, dp[j]) for j in reversed(range(n - 1)): dp[j] = max(dp[j + 1] - 1, dp[j]) for j in range(n): dp[j] += points[i][j] return max(dp) solution = Solution() assert solution.maxPoints([[1,2,3],[1,5,1],[3,1,1]]) == 9 assert solution.maxPoints([[1,5],[2,3],[4,2]]) == 11
''' Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. ''' from leetcode import * class Solution: # Time: O(n^2) # Space: O(1) def moveZeroes(self, nums: List[int]) -> None: nums_len = len(nums) j = 0 for i in range(nums_len): if nums[j] == 0: nums.pop(j) nums.append(0) j -= 1 j += 1 # Two pointer approach # Time: O(n) # Space: O(1) def moveZeroes2(self, nums: List[int]) -> None: left = 0 i = 0 while i < len(nums): if nums[i] != 0: nums[left] = nums[i] left += 1 i += 1 while left < len(nums): nums[left] = 0 left += 1 solution = Solution() arr = [0, 1, 0, 3, 12] solution.moveZeroes(arr) print(arr) arr = [0, 0, 1] solution.moveZeroes(arr) print(arr)
# Input: # s: a string to repeat (1 <= |s| <= 100) # n: the number of chars to consider (1 <= n <= 10^12) # Output: an integer denoting the number of letter a's in the first # n letters of the infinite string created by repeating s infinitely many times # Algorithm runs in O(1) time def repeatedString(s, n): size = len(s) if size < 1 or size > 100 or n < 1 or n > int(1e12): return None return ((n // size) * s.count("a")) + s.count("a", 0, n % size) def main(): s = input() n = int(input()) print(repeatedString(s, n)) if __name__ == '__main__': main()
''' Given a list of intervals, remove all intervals that are covered by another interval in the list. Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d. After doing so, return the number of remaining intervals. Assume there is at least one interval given. ''' from leetcode import * # Time: O(n*log(n)) # Space: Depends on sorting algorithm used but if an inplace one is used then it'll be O(1). def remove_covered_intervals(intervals: List[List[int]]) -> int: # sort by the start ascending and then by the end descending intervals.sort(key=lambda x: (x[0], -x[1])) num_uncovered_intervals = 1 prev_uncovered_interval_ind = 0 for i in range(1, len(intervals)): if intervals[i][0] == intervals[prev_uncovered_interval_ind][0]: continue elif (intervals[i][0] >= intervals[prev_uncovered_interval_ind][0]) and (intervals[i][1] <= intervals[prev_uncovered_interval_ind][1]): continue prev_uncovered_interval_ind = i num_uncovered_intervals += 1 return num_uncovered_intervals # Expected: 2 print(remove_covered_intervals([[1,4],[3,6],[2,8]])) # Expected: 1 print(remove_covered_intervals([[1,4],[2,3]])) # Expected: 2 print(remove_covered_intervals([[0,10],[5,12]])) # Expected: 2 print(remove_covered_intervals([[3,10],[4,10],[5,11]])) # Expected: 1 print(remove_covered_intervals([[1,2],[1,4],[3,4]]))
''' The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. ''' from leetcode import * class Solution: # Backtracking approach # Time: O(n!) # Analysis from Leetcode: We have n options for the first queen, n-2 options for the next one, and n-4 for the third one, and so on. # This is upper bounded by n!. We do perform n^2 for each solutions but n! dominates. # Space: O(n^2) if we ignore the space needed for output. The recursion stack is a depth of at most n, so the only space needed is to store the board. # Leetcode optimized the runtime by performing the canPlaceQueen check in O(1) time. # Basically, we can keep a set for the columns, diagonals, and anti-diagonals # and check if col in columns or (row - col) in diagonals or (row + col) in anti-diagonals. def solveNQueens(self, n: int) -> List[List[str]]: ans = [] def canPlaceQueen(row, col, board): # Check column above i = row - 1 while i >= 0: if board[i][col]: return False i -= 1 # Check "hill" diagonal i = row - 1 j = col - 1 while i >= 0 and j >= 0: if board[i][j]: return False i -= 1 j -= 1 # Check "dale" diagonal i = row - 1 j = col + 1 while i >= 0 and j < len(board[0]): if board[i][j]: return False i -= 1 j += 1 return True def backtrack(row, board): if row == n: boardStr = [''.join(['Q' if board[i][j] else '.' for j in range(len(board[0]))]) for i in range(len(board))] ans.append(boardStr) return for i in range(len(board[0])): # Check if we can place a queen at this square. if canPlaceQueen(row, i, board): board[row][i] = 1 backtrack(row + 1, board) # Remove queen and try next square board[row][i] = 0 return backtrack(0, [[0]*n for i in range(n)]) return ans solution = Solution() # Expected: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] print(solution.solveNQueens(4)) # Expected: [["Q"]] print(solution.solveNQueens(1))
''' Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. ''' from leetcode import * class Solution: # Time: O(m) where m is the length of magazine. # Space: O(1) since the counters will have at most 26 entries. def canConstruct(self, ransomNote: str, magazine: str) -> bool: if len(ransomNote) > len(magazine): return False counterMag = Counter(magazine) counterNote = Counter(ransomNote) for i in counterNote: if i not in counterMag or counterMag[i] < counterNote[i]: return False return True solution = Solution() # Expected: False print(solution.canConstruct(ransomNote = "a", magazine = "b")) # Expected: False print(solution.canConstruct(ransomNote = "aa", magazine = "ab")) # Expected: True print(solution.canConstruct(ransomNote = "aa", magazine = "aab"))