text
stringlengths
37
1.41M
''' 后裔,后裔继承了Game的hp和power,并多了护甲属性。 重新定义另外一个defense方法: final_hp = hp+defense-enemy_power enemy_final_hp = enemy_hp-power 两个hp进行对比,血量先为零的人输掉比赛 ''' import random from pythoncs.mxdx_demo.mxdx_hhgame_demo2 import Game class houyi(Game): def __init__(self,my_hp,your_hp): self.defense = 10 super().__i...
''' 两层分支结构:if else''' a = 1 if a==0: print("a=0") else: print("a != 0") ''' 多层分支结构:if elif else''' b = 1 if b==0: print("b=0") elif b==1: print("b=1") else: print("b != 0和1") ''' 实现以下分段函数 x+3 (x>1) y= x+2 (-1<=x<=1) 5*x+3 (x<-1) ''' #方案一,嵌套分支结构: # x =0 # if x>1: # y=x+3 # else: # ...
#!/usr/bin/env python3 """ This script implements code for finding the k-th element from the end of the linked list. """ from linkedlist import LinkedList class LinkedListMod(LinkedList): def __init__(self, data: list): super().__init__(data) def __str__(self): return super().__str__() ...
# Is Unique: Implement an algorithm to determine if a string has all # unique characters. What if you cannot use additional data structures? class StringChecker: def is_unique(self, string: str) -> bool: """ Checks if all chars in string is unique using a set/hashtable """ ...
#Snabb bonus! Hur vi hanterar och ser på mutables. #Vi gör ett mutable objekt av något slag - en lista blir gott nog för våra syften. mutable1 = [1,2,3,4,5] #Lägger denna i varsin lista list1 = [mutable1, 2] list2 = [mutable1, 3] #MODIFIERAR vi en mutable i en lista ändrar vi på objektet list2[0].extend([1,...
# -*- coding: utf-8 -*- """ Created on Tue Apr 6 20:14:41 2021 @author: Alec """ #Import Libraries import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures #Impor...
#Question 1 d={} for i in range(1,5): key=input("enter the key: ") value=input("enter the value: ") d[key]=value print(d) #Question 2 a={} b={} for i in range(1,4): b={} name=input("enter name") for j in range(1,4): sub=input("enter subject") marks=int(input("ent...
import turtle def square10(): for i in range(10, 110, 10): turtle.shape('turtle') turtle.pendown() turtle.forward(10 + i) turtle.left(90) turtle.forward(10 + i) turtle.left(90) turtle.forward(10 + i) turtle.left(90) turtle.forward(10 + i) turtle.left(90) turtle.pen...
# Exercise 3_1 # Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Pay # the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. # Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75...
lst = list(map(int, input().split())) text = [] temp = set() temp_length = 0 for elem in lst: temp.add(elem) text.append(('YES' if len(temp) == temp_length else 'NO')) temp_length = len(temp) print(*text, sep="\n")
n = int(input()) step = 1 maxStep = 1 while step <= n: step = step * 2 step = step // 2 if step == n: print('YES') else: print('NO')
a = int(input()) b = int(input()) c = int(input()) d = int(input()) x = -b // a if a == 0 and b == 0: print('INF') elif c == 0 and d == 0 or a == 0 or b / a == d / c: print('NO') elif c == 0: print(x) else: print(x)
import numpy as np def read_rigid_body(filename): ''' Reads in the rigid body file, and saves the number of led markers, their locations, and the tip locations. Inputs: filename -> the rigid body file Outputs: num_markers -> the number of markers on the rigid body led_markers -> the led...
# -*- coding:utf8 -*- """ 基本的装饰器的用法 """ # 带参数装饰器的用法 def deco(arg,arg2): print 'deco start' def _deco(func): print '_deco start' def __deco(*args,**kwargs): print 'args',arg,arg2 func(*args,**kwargs) print 'args',func print '_deco end' ret...
n=int(input('enter the number')) list=[] for i in range(n): list.append(input('enter the next\n')) print() for i in range(n): print(list[i],'\n')
def fib(n): a=0 b=1 print(a) print(b) for i in range(2,n): temp=a+b if temp<=100: a=b b=temp print(temp) else: break n=int(input("enter the range of fib")) if n<0: print("negative number") else: fib(n) ...
import time import curses class Screen: def __init__(self, stdscr, row=0, col=0): self.stdscr = stdscr # These are the initial coordinates of the cursor. # These will be updated as text is printed on to the screen. # init row and col should never be updated once initialised. ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Simple command that prints out the current n last levels of the CWD replacing the prefix with a horizontal ellipsis Usage pwdn [numdirs] """ from os import getcwd from sys import argv, exit try: numdir = (len(argv) > 1) and int(argv[1]) or 2 except ValueError: ...
# n个骰子的点数 ''' 把n个骰子扔在地上, 所有骰子朝上一面的点数和为s。 输入n, 打印出s的所有可能的值出现的概率 ''' class Solution: # 动态规划 # 构造两个数组来存储骰子点数的每一个总数出现的次数 # 在一次循环中, 第一个数组中的第n个数字表示骰子和为n出现的次数 # 在下次循环中, 另一个数组的第n个数字设为前一个数组对应的第n-1、n-2、n-3、n-4、n-5、n-6之和 def PrintProbability(self, number): if number < 1: return [] ...
# 替换字符串 ''' 请实现一个函数,将一个字符串中的空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 ''' class Solution: def stringReplace(self, s): init_string = '' if type(s) != str: return False for i in s: if i == ' ': init_string += '%20' el...
# 顺时针打印矩阵 ''' 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, 例如,如果输入如下矩阵: [[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]] 则依次打印出数字 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. ''' class Solution: def printmatrix(self, matrix): output_list = [] start = 0 row = len(matrix) ...
# 数组中重复的数字 ''' 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。 请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。 ''' class Solution: # 用字典保存并求解 def duplicate2(self, numbers): if numbers == None or len(numbers) <= 0: return False for i in number...
def build_person(first_name, last_name, middle_name='', age=None): """Возвращает информацию о человеке.""" person = {'first_name': first_name, 'last_name': last_name, 'middle_name': middle_name} if age: person['age'] = age return person men1 = build_person('Вася', 'Пупкин') men2 = build_person...
t=int(raw_input()) out = [] def sort(l,m): out = [] for item in l: out.append(item) for item in m: out.append(item) return sorted(out)[::-1] while t: n,m = raw_input().split() ar1 = [int(i) for i in raw_input().strip().split()] ar2 = [int(i) for i in raw_input().strip().split()] print n,m out.append(sort(...
""" This is a docstring for the module: This module demonstrates the merge functionality in the 2048 game. """ def check_merge(iterator): """ Check whether the merge has happen at a particular index or not, and returns the appropriate boolean value for the same. """ if Dictionary[iterator] == 0...
def intercambiar(a,b): a1=b b1=a return a1,b1 def primo(num): if num < 2: return False for i in range(2, num): if num % i == 0: #si el resto da 0 no es primo, por lo tanto devuelve Falso return False return True def mcd(a,b): if a<b: a,b=intercambiar(a,b) n=a d...
import random def coin_toss(repetition): print 'Starting the program...' face = '' head_count = 0 tail_count = 0 num = 1 # this is the part regarding tosisng a coin for x in range (1, repetition): coin = round(random.randint(0,1)) if coin == 0: face = 'head' ...
'''Now, create another class called Dog that inherits everything that the Animal does and has, but 1) have the default health be 150 and 2) add a new method called pet, which when invoked, increase the health by 5. Have the Dog walk() three times, run() twice, pet() once, and have it displayHealth(). Now, create anot...
class Patient(object): def __init__(self, id, name, allergies): self.id = id self.name = name self.allergies = allergies self.bedNumber = 0 class Hospital(object): def __init__(self, name, capacity): self.name = name self.capacity = capacity self.patient_...
# 物件導向的最基礎,我們定義class,然後用它宣告我們的物件/實體(instance) # class 可以定義attribute(成員)、method(方法),還有一些既定方法像是初始化__init__ # class裡的method,跟function基本上是一樣的,但第一個參數是self,會指向此實體本身 # 定義一個class叫做Person # 我們習慣把class的名稱定義成UpperCaseCamelCase,字的開頭大寫 # 如果有多個字組成則在每個字的開頭大寫連起來 class Person: # 定義class attribute,所有實體會共用它 kind = 'Person' ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from tkinter import * class Interface: # Classe que cria a interface gráfica do programa def __init__(self, maze): # Funções dos botões def move_up(): self.maze.moveMouse(1) def move_right(): self.maze.moveMouse(2) ...
# coding:utf-8 import urllib import urllib2 def main(): # 设置请求头 req_headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36" } """编码工作使用urllib的urlencode()函数,帮我们将key:value这样的键值对转换成"key=value"这样的字符串, 解码工作可以使用url...
def insertion_sort(arr): n = len(arr) for i in range(1,n): #0. indeksi listenin en büyük elemanı olarak aldık. key = arr[i] #key değişkeni temp görevinde kullanılır. j = i-1 #sıralı kısmın son indeksindeki elemanını tutmuş oluyoruz. while j >= 0 and key < arr[j]: ...
from bs4 import BeautifulSoup import lxml import urllib.request from collections import Counter from string import punctuation # Store the website input as a variable and excecute BS4 on it website = input("What is the URL you want to read faster? ") web_page = urllib.request.urlopen(website) soup = Beautiful...
#!/usr/bin/python from __future__ import print_function import use_lldb_suite import six import sys import time class ProgressBar(object): """ProgressBar class holds the options of the progress bar. The options are: start State from which start the progress. For example, if start is ...
""" As a software developer at Spotify, you've been asked to re-implement their playlist structure into a Linked List structure. You've been told that along with displaying the current song in the playlist, listeners must also be able to go back a song and skip to the next song. You'll first need to create the playlis...
import random def main(): number_of_quick_picks = int(input("How many quick picks? ")) for i in range(0, number_of_quick_picks): quick_pick = generate_quick_pick() print( "{:2} {:2} {:2} {:2} {:2}".format(quick_pick[0], quick_pick[1], quick_pick[2], quick_pick[3], ...
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? when input value is not of the correct data type during a mathematical operation making said operation impossible 2. When will a ZeroDivisionError occur? when attempting to divide by zero, as it is an indefinite number 3. Cou...
import itertools class Environment: """ This class is responsible for modelling the sample space of the problem. """ def __init__(self, a): self.address_list = a self.sample_space = list() def create(self): for item in itertools.permutations(self.address_list): ...
# 링크드리스트를 이용한 중복값 대처 class LinkedTuple: def __init__(self): self.items = list() def add(self, key, value): self.items.append((key, value)) def get(self, key): for k, v in self.items: # items for문을 돌렸을때 if key == k: # 내가 찾고자 하는값이 동일할경우 retu...
import random print("Welkom bij het raad spel") score = 0 for x in range(20): if x != 0 and x != 19: nogEens = input("Wil je nog eens raden (Y/N) ").lower() if nogEens == "n": print("Ok vaarwel") exit() print("Ronde " + str(x+1)) rndNumber = random.randint(1,10) ...
from random import randint if __name__ == '__main__': P = 23 # modulus G = 5 # base print('The Value of P is :%d'%(P)) print('The Value of G is :%d'%(G)) # Alice will choose the private key a a = randint(1,9) print('The Private Key a for Alice is :%d'%(a)) # key #pow() with three arguments (x**y) ...
#! /usr/bin/python3 from typing import List import tokenizer import parser def tokenize_orig(contents): list = [] i = 0 while(i != len(contents)-1): c = contents[i] if c == ' ' or c == '\t': i += 1 continue if c == '{' or c == '}': list.append(c...
''' 498. Diagonal Traverse Medium Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] Solution: Get the diagonal sequence as the original ...
''' 780. Reaching Points Hard A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y). Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False. Examples...
''' 518. Coin Change 2 Medium You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. Example 1: Input: amount = 5, coins = [1, 2, 5] Output: 4 E...
''' 814. Binary Tree Pruning Medium We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not containing a 1 has been removed. (Recall that the subtree of a node X is X, plus every node that is a des...
''' 1072. Flip Columns For Maximum Number of Equal Rows Medium Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0. Return the maximum number of rows that have all valu...
''' Method 1: DP algorithm with O(n) time and O(1) space For each day, there are 3 possible actions: buy, sell, nothing. Let us define buy[i] = maxProfit of prices[:i+1] with the action buy at day i, sell[i] = maxProfit of prices[:i+1] with the action sell at day i, nothing[i] = maxProfit of prices[:i+1] with the acti...
''' 846. Hand of Straights Medium Alice has a hand of cards, given as an array of integers. Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards. Return true if and only if she can. Example 1: Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 Output: true Ex...
''' 845. Longest Mountain in Array Medium Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold: B.length >= 3 There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] (Note that B could be any subarray of A, includ...
''' 538. Convert BST to Greater Tree Easy Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a Binary Search Tree like this: 5 ...
''' 1143. Longest Common Subsequence Medium Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. ...
''' 76. Minimum Window Substring Hard Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the emp...
def find_next(sudoku, i, j): for i in range(i,9): for k in range(j,9): if sudoku[i][k] == 0: return i,k return -1,-1 def isValid(sudoku, i, j): nums = all([e != grid[i][x] for x in range(9)]) print nums if __name__ == '__main__': sudoku = [[5,1,7,6,0,0,0,3,4],[2,8,9,0,0,4,0,0,0],[3,4,6,2,0,5,0,9,0],[6,...
''' 640. Solve the Equation Medium Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient. If there is no solution for the equation, return "No solution". If there are infinite solutions for the equation, r...
''' 971. Flip Binary Tree To Match Preorder Traversal Medium Given a binary tree with N nodes, each node has a different value from {1, ..., N}. A node in this binary tree can be flipped by swapping the left child and the right child of that node. Consider the sequence of N values reported by a preorder traversal s...
''' 79. Word Search Medium Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A...
''' 552. Student Attendance Record II Hard Given a positive integer n, return the number of all possible attendance records with length n, which will be regarded as rewardable. The answer may be very large, return it after mod 109 + 7. A student attendance record is a string that only contains the following three ch...
''' 3. Longest Substring Without Repeating Characters Medium Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", wi...
''' 861. Score After Flipping Matrix Medium We have a two dimensional matrix A where each value is 0 or 1. A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s. After making any number of moves, every row of this matrix is interpreted ...
''' 202. Happy Number Easy Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it ...
''' 25. Reverse Nodes in k-Group Hard Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it ...
''' 828. Unique Letter String Hard A character is unique in string S if it occurs exactly once in it. For example, in string S = "LETTER", the only unique characters are "L" and "R". Let's define UNIQ(S) as the number of unique characters in string S. For example, UNIQ("LETTER") = 2. Given a string S with only u...
''' 42. Trapping Rain Water Hard Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are be...
import random instructions = ''' Programming Assignment 2: DIRECTED ACYCLIC GRAPHS This program takes as input a directed graph and outputs information about the graph. INPUTS ====== - A positive integer n, the number of vertices in the graph: the names of the vertices will be 1, 2, 3, ..., n. - The next few li...
import math x = float(input("Ingrese valor de x: ")) cifras = float(input("Ingrese cuantas cifras significativas: ")) es = 0.5*(10**(2-cifras)) ea = es+1 n = 1 ant = x while ea>es: f = x for i in range(1,(n+1)): signo = (-1)**i f += signo*round((x**((2*i)+1))/math.factorial((2*i)+1),6) ea...
# 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите # у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. a = 15 b = a ** 2 print("a = ", a, "\na*a = ", b) number1 = int(input("Введите первое число:")) number2 = int(input("Введите второе число:")) string1 =...
# 6. Реализовать два небольших скрипта: # а) итератор, генерирующий целые числа, начиная с указанного, # б) итератор, повторяющий элементы некоторого списка, определенного заранее. # # Подсказка: использовать функцию count() и cycle() модуля itertools. # Обратите внимание, что создаваемый цикл не должен быть бесконечны...
# 3. Реализовать базовый класс Worker (работник), в котором определить атрибуты: # name, surname, position (должность), income (доход). # Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: # оклад и премия, например, {"wage": wage, "bonus": bonus}. # Создать класс Position (должность)...
# # @lc app=leetcode id=83 lang=python3 # # [83] Remove Duplicates from Sorted List # # @lc code=start # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head: Optional[ListNode]...
# test_1 print("test_1:") the_world_is_flat = True if the_world_is_flat: print("Be careful not to fall off!") # test_2 print("test_2:") # this is the first comment spam = 1 # and this is the second comment # ... and not a third! text = "# This is not a comment because it's inside quotes." if spam == 1: ...
def filp(s): ret, n, ls = [], len(s), list(s) for i in range(1, n): if ls[i] == '+' and ls[i - 1] == '+': ls[i] = ls[i - 1] = '-' ret.append(''.join(ls)) ls[i] = ls[i - 1] = '+' print ret if __name__ == '__main__': filp('++++')
''' Load, Modify (Transform Color Image to GrayScale) and Save an Image. ''' import cv2 # path of the image to load img_path = 'my_images/Halloween.png' # load the image original_img = cv2.imread(img_path) original_img = cv2.resize(original_img, (800, 800)) # Modify the image i.e tranform the imag...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 10 10:25:09 2020 @author: tushar """ import numpy as np True == 1 # Evaluates to True, similarly False is 0 'pyscript' == 'PyScript' # False list1 = [] list2 = [] list3 = list1 list1 == list2 # True - values are same list1 is list2 # False - objec...
from collections import defaultdict def count_subnode(index): def DFS(now): count = 1 if children1[now]: count += DFS(children1[now]) if children2[now]: count += DFS(children2[now]) return count return DFS(index) T = int(input()) for tc in range(1, T...
f = open('input.txt', 'r') input = lambda: f.readline().rstrip() class Node: def __init__(self, value=None): self.value = value self.after = None self.before = None class DoubleLinkedList: def __init__(self): self.length = 0 self.head = self.tail = Node(0) se...
#1717 집합의 표현 #####입력 모드 # 0 : txt모드 , 1: 제출용 INPUTMODE = 0 if not INPUTMODE: f = open("input.txt","r") input = lambda : f.readline().rstrip() else: import sys input = lambda : sys.stdin.readline().rstrip() ################################ def findParent(e): if e == parent[e]: return e ...
graph = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])} def bfs(graph, start): visited = [] queue = [start] while queue: n = queue.pop(0) if n not in visited: ...
""" This file defines a foobotweb class for polling data out of the foobot for the user making HTTP requests. It implements login, logout first and then implements the different data extraction methods. Author - bhanu13 Basic Authorization and X-AUTH-TOKEN Time - Date ISO 8601 """ import requests import json import ...
def reverse(s): str = "" for i in s: str=i+str return str string = "A man, a plan, a canal: Panama" st = string.replace(" ", "") t =st.casefold() y='' for x in t: if(((x >="a")and(x<="z"))or('0'<=x <='9')): y +=x else: continue #print("String a...
class Car: def __init__(self, name): self.name = name def carname(self): print('Hello, this car is manufactured by :: ', self.name) p = Car('Maruti') p.carname()
#function to remove all unwanted characters def fun(line): empty ="" # print(line) for x in line: if(((x >="a")and(x<="z"))or('0'<=x <='9')or(x>="A")and(x<="Z")): empty +=x else: continue return empty #program starts Here #Read a file line by line using readline() till we g...
val = str(input("Enter a word : ")); val1 =str(val[::-1]); print("\n Reversed String =",val); if val == val1: print(val, "is palyndrome") else: print(val, "not palyndrome")
""" Interface and implementation for hash functions. """ from abc import ABCMeta, abstractmethod import mmh3 import random class _Hash(object): """ Interface for Hash Object. """ @abstractmethod def hash(self, key): """ Map the given key to an integer. :param key: a hash...
def solution(arr1, arr2): answer = [] row = len(arr1) col = len(arr1[0]) for i in range(row): ans = [] for j in range(col): sum_ = arr1[i][j] + arr2[i][j] ans.append(sum_) answer.append(ans) return answer
import math def solution(n): # answer = 0 # if math.sqrt(n) == int(math.sqrt(n)): # return return (math.sqrt(n) + 1) ** 2 if math.sqrt(n) == int(math.sqrt(n)) else -1
#Uses python3 import sys import math def distance(xi, yi, xj, yj): return ((xi - xj)**2 + (yi - yj)**2)**0.5 def minimum_distance(vertices, adj, weight): result = 0. X = set() X.add(0) while len(X) != vertices: minimum=float('inf') for u in X: for v in adj[u]: ...
# python3 def max_pairwise_product(numbers): n = len(numbers) max_product = 0 for first in range(n): for second in range(first + 1, n): max_product = max(max_product, numbers[first] * numbers[second]) return max_product def max_pairwise_product_fast(numbers): n...
import os import random # export=GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials def synthesize_text(text, output_filename, output_dir, voice=None): """ Synthesizes speech from the input string of text. Female voice = 0, Male voice = 1 output filename doesn't need extension """ from google....
import numpy as np class InvalidReturnsException(Exception): '''Exception thrown when initialized with invalid returns dict''' pass class Simulator(object): '''Represents an object that runs simulations.''' def __init__(self, returns, nrows, ncols, seed=0): '''Constructor. Args: returns: a dict where the...
import sys import numpy as np ''' Asks the user to input a valid list of positions. ''' def get_positions(): try: pos_input = raw_input('Please provide a list of positions, select from 1, 10, 100, 1000.') pos_input = pos_input.replace(' ', '') except (KeyboardInterrupt,EOFError): sys...
"""defines an investment class, an instance of which consists of the number of positions to take within the given investment amount, along with a probability of the amount being lost in a single day of trading. Also contains a member method which simulates a single day of trading on our investment and returns the outco...
""" This module is the main program of hw8. It mainly deal with the user input and call other modules to generate the results """ import numpy as np import math import matplotlib.pyplot as plt from user_defined_exceptions import * from user_input_class import * import make_investment_class #author: Muhe Xie #netID...
import numpy as np class Simulation(): ''' class Simulation takes inputs postions, num_trials, and budget. It also has a function investment ''' def __init__(self, positions, num_trials, budget): self.positions = positions self.num_trials = num_trials if budget >= 0: self.budget = budget else: ...
''' Created on Nov 7, 2015 @author: jj1745 ''' import sys from simulation import writeResult, plotResult class InvalidNumTrialsException(Exception): '''exception of invalid num_trials input''' def __str__(self): return 'Your input of num_trials is not valid' class NonPositiveException(Exception)...
import numpy as np #import Simulation import Exceptions as x import sys class Interface: ''' class to take in data from user. Handles exceptions by trying to get input from user until it is good input ''' def __init__(self): self.numTrial=10000 self.pos=[] def getPositions(self): ''' sets class variab...
from __future__ import division import numpy as np import random # DS-GA 1007 # HW8 # Author: Sida Ye class Investment_account(object): """ Class Investment_account takes input purchase_value. It also has a method invest_sim to simulate the daily return based on position and number of trials. ""...
'''author: Siyi Xie(sx444)''' '''This is the main program to accept the input from users and call other modules to properly generate the results''' import numpy as np import matplotlib.pyplot as plt import investment_simulation from user_defined_exceptions import * import re def conduct_simulation(): '''this ...
import numpy as np import sys class Investment(object): '''this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user''' def __init__(self, positions, num_trials): '''Initializes the position list and number o...