text
stringlengths
37
1.41M
import sqlite3 class DB: def __init__(self, db_file): conn = self.create_connection(db_file) pass def create_connection(self, db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connec...
def interleave (s1, s2): """ Interleave 2 strings if s1 is empty s2 else if s2 empty s1 characters in the result appear in order they appear in s1 and s2 """ if not s1: yield s2 elif not s2: yield s1 else: for str3 in interleave (s1[1:],s2 ): ...
arry = ["6", "54", "326", "48","12","12345","9","8","7","0","99"] if __name__ == "__main__": print("hello") def findlen(): i = 0 length = 0 while i < len(arry): element = arry[i] cur_len = len(element) if cur_len > length: length = cur_len i =...
''' All about decorators. Identity Function the output is the same as the input Higher-order Function receives a functions as input add/or returns a function as output Pure Function 1. always returns the same output for a fiven input 2. no side-effect (only returns a value) # Note - prin...
__author__ = 'don' def largestPrime(number, max): if (number == 1): return(max) for i in range(2,1000000): if (number % i == 0): if (max < i): max = i return(largestPrime(number / i, max)) print(largestPrime(600851475143,0))
def save_key_to_file(filename, key): with open(filename, 'wb') as f: f.write(key) def read_key_from_file(filename): with open(filename, "rb") as f: return f.read()
from tkinter import * #Uncomment the following line if you have MacOS #Ask the student to write the following line if the student has MacOS #from tkmacosx import * root=Tk() root.title("Encryption with Ascii Code") root.geometry("400x400") root.configure(background = 'lightblue1') enter_word = Entry(root) enter_word...
from random import shuffle from deuces2.card import Card class Deck: """ Class representing a deck. The first time we create, we seed the static deck with the list of unique card integers. Each object instantiated simply makes a copy of this object and shuffles it. """ _FULL_DECK_LEDUC = [1, 1,...
"""Sum a list of integers. Given a list of numbers, return the sum. Do not use the built in 'sum' method. For example:: >>> sum_list([5, 5]) 10 >>> sum_list([-5, 10, 4]) 9 >>> sum_list([20]) 20 The sum of an empty list is zero:: >>> sum_list([]) 0 """ def sum_list(num_list): ...
import random print("Jello") print("hello") #generate random numbers until number generated > .99 tracker = True counter = 0; while tracker: number = random.random() counter += 1 print(str(counter) + ": " + str(number)) tracker = number < .99
''' Conditional Expressions => We can use if … elif … else logic while quering tha database => Used within filters, annotations, aggregations, and updates. => executes series of conditions while querying the database. => checks the condition for every record of the table. => It executes the conditions one by one u...
from derivacao.derivada import derivada from derivacao.polinomio import gerarpolinomio, gerarfuncao import math #x = int(input("Insira o valor de x >> ")) grau = int(input("Insira o grau do polinômio >> ")) poli = gerarpolinomio(grau) f = gerarfuncao(poli) x_par = int(input("Insira o valor de x >> ")) z = 1 while(...
from collections import deque class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # Time: O(n) # Space: O(n) # I think using a queue here might not be a good thing. We should do it without # using additional data structures. But p...
# Definition for singly-linked list. from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # Time Complexity: O(n) # Space Complexity: O(1) # This is almost same as Official Solution. def rotateRight(self...
from typing import List class Solution: # Idea like Bubble Sort # Time: O(n^2) # Space: O(n), O(1) additional space. def pancakeSort(self, A: List[int]) -> List[int]: def flip(sublist, k): # includes k in flipping i = 0 while i < k / 2: subli...
from typing import List class OfficialSolution: """ == Approach 1: Boyer-Moore Voting Algorithm == == Intuition == To figure out a O(1) space requirement, we would need to get this simple intuition first. For an array of length n: - There can be at most one majority element, which is more...
from collections import defaultdict from typing import List class Solution: # Since the max drop location can be 1000, we can store number of people in the # car at every location in a hash map. It will take O(1) space. # We iterate over every element of trips, and update our hash map. # # Time: O...
from collections import Counter class OfficialSolution: """ == Intuition == First we should make sure we understand what "lexicographical order" means. Comparing strings doesn't work the same way as comparing numbers. Strings are compared from the first character to the last one. Which string is g...
# There are some spherical balloons spread in two-dimensional space. # For each balloon, provided input is the start and end coordinates of the horizontal # diameter. Since it's horizontal, y-coordinates don't matter, and hence the # x-coordinates of start and end of the diameter suffice. # The start is always smaller ...
from typing import Dict, Optional from unittest import TestCase class Solution: """ Recursion (Dynamic Programming) with Memoization. Time Complexity: O(n), where n is length of s. Space Complexity: O(n), where n is length of s. """ def numDecodings(self, s: str, cache: Optional[Dict] = None)...
import unittest from valid_palindrome import Solution, SolutionTwo class TestValidPalindrome(unittest.TestCase): def test_example(self): assert Solution().isPalindrome(s="A man, a plan, a canal: Panama") is True assert Solution().isPalindrome(s="race a car") is False assert Solution().isP...
from unittest import TestCase from can_place_flowers import Solution class TestCanPlaceFlowers(TestCase): def test_example_1(self): assert Solution().canPlaceFlowers(flowerbed=[1, 0, 0, 0, 1], n=1) is True def test_example_2(self): assert Solution().canPlaceFlowers(flowerbed=[1, 0, 0, 0, 1],...
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: # Straight Forward DFS. # Time Complexity: O(n). # Space Complexity: O(n). ...
import unittest from sum_of_left_leaves import Solution, TreeNode class TestSumOfLeftLeaves(unittest.TestCase): def test_example_1(self): root = TreeNode(val=3) root.left = TreeNode(val=9) root.right = TreeNode(val=20) root.right.left = TreeNode(val=15) root.right.right = ...
from unittest import TestCase from shortest_word_distance import Solution class TestShortestDistance(TestCase): def test_example_1(self): assert ( Solution().shortestDistance( words=["practice", "makes", "perfect", "coding", "makes"], word1="coding", ...
import bisect from collections import defaultdict class TwoSum: """ This is my original solution, which matches Official Solution's Approach 2. == Approach 2: Hash Table == == Intuition == As an alternative solution to the original Two Sum problem, one could employ the HashTable to index each...
from typing import Optional from unittest import TestCase # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: # Linear Scan using 3 pointers. # Time Complexity: O(n). # Space Complexity: O(1). ...
import unittest from search_a_2d_matrix import Solution class TestSearchA2DMatrix(unittest.TestCase): def test_example_1(self): assert ( Solution().searchMatrix( matrix=[[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]], target=3 ) is True ) ...
class Solution: # Straight Forward. # Time Complexity: O(n). # Space Complexity: O(1). def isOneEditDistance(self, s: str, t: str) -> bool: if abs(len(s) - len(t)) not in (1, 0) or s == t: return False i, j, found = 0, 0, False while i < len(s) and j < len(t): ...
from unittest import TestCase from search_in_rotated_sorted_array_ii import Solution class TestSearchInRotatedSortedArrayII(TestCase): def test_example_1(self): assert Solution().search(nums=[2, 5, 6, 0, 0, 1, 2], target=0) is True def test_example_2(self): assert Solution().search(nums=[2, ...
from typing import List class SubrectangleQueries: # Your SubrectangleQueries object will be instantiated and called as such: # obj = SubrectangleQueries(rectangle) # obj.updateSubrectangle(row1,col1,row2,col2,newValue) # param_2 = obj.getValue(row,col) def __init__(self, rectangle: List[List[int...
class TimeHandler: def __init__(self): self.__months = {'January':1, 'February':2, 'March':3, 'April':4, 'May':5, 'June':6, 'July':7, 'August':8, 'September':9, 'October':10, 'November':11, 'December':12} def diffMonths(self, time1, time2): #print time1, time2 try: year1 = int(time1.split(',')[...
from axelrod.action import Action from axelrod.player import Player C, D = Action.C, Action.D class Inverse(Player): """A player who defects with a probability that diminishes relative to how long ago the opponent defected. Names: - Inverse: Original Name by Karol Langner """ name = "Inver...
from typing import List from axelrod.action import Action from axelrod.player import Player C, D = Action.C, Action.D class Handshake(Player): """Starts with C, D. If the opponent plays the same way, cooperate forever, else defect forever. Names: - Handshake: [Robson1990]_ """ name = "Han...
from collections import defaultdict, namedtuple from typing import DefaultDict, Dict, Iterator, List, Set, Tuple from axelrod.action import Action C, D = Action.C, Action.D Transition = namedtuple( "Transition", ["state", "last_opponent_action", "next_state", "next_action"] ) TransitionDict = Dict[Tuple[int, Act...
# question 6 def read_file(filename): # read file of polygon and points res = [] f = open(filename, 'r') for line in f: line = line.strip() if not line: continue x, y = line.split(' ') res.append((float(x), float(y))) f.close() return res def sort_po...
def positive_sum(arr): # Your code here positive_array=[] total=0 for number in arr: if number < 0: pass else: positive_array.append(number) for positive_number in positive_array: total=total+positive_number return total positive_sum([1,-4,7,...
## this program is for learning of pandas by some list of tracking app to count steps import pandas as pd import numpy as np #reading a dataset using pandas print ("reading and displaying iris dataset using the pandas library") iris_data = pd.read_csv('F:\dissertation\python intel ML\Intel-ML101_Class1\data\Ir...
#chapter10 #no04 mencariNIM = input('Masukan NIM yang dicari : ') file = open('text2.txt', 'r') y = file.readlines() for x in range(len(y)): if (mencariNIM in y[x]): status ='Ada' break else: status = 'Tidak Ada' continue if(status == 'Ada'): z = y[x].s...
import numpy as np """ Multiply and add the values of the same position in the matrix of the same dimension """ def dot_mul2d(arr,arr1,bias=None,average=False): assert arr.shape==arr1.shape add_=0 for i in range(arr.shape[0]): for j in range(arr.shape[1]): add_+=arr[i][j]*arr1[i][j] ...
#File containing all the general sorting functions for division into site and sex based distributions def sex_sorter(sex_var, var ): '''Sorts a specified data field into different sexes''' male= list() female= list() tot_Values = sex_var.shape[0] for i in range(tot_Values): if s...
#!/usr/local/bin/python # -*- coding: UTF-8 -*- class SortedKeyDict(dict): def keys(self): return sorted(super(SortedKeyDict, self).keys()) # return sorted(self.keys()) def fibb(): fibs = [0, 1] num = input("how many fibonacci numbers do you want ?") for i in xrange(num-2): fi...
import tkinter as tk root=tk.Tk() text=tk.Text(root,height=15,width=50) text.pack() text.insert(tk.END," This is python text widget \n This is python text widget \n") tk.mainloop()
#!/usr/bin/env python import sys def argreader(): '''This function opens an unlimited amount of textfiles and reads them in order to store them into a list of lists ("listionary") before closing the files. The file names are provided in the terminal (argument vector) by the user as arguments nr. 1 a...
def song_playlist(songs, max_size): """ songs: list of tuples, ('song_name', song_len, song_size) max_size: float, maximum size of total songs that you can fit Start with the song first in the 'songs' list, then pick the next song to be the one with the lowest file size not already picked, repeat ...
import tensorflow as tf # Training Data x_data = [1.,2.,3.] y_data = [1.,2.,3.] # Try to find values for W and b that compute y_data = W * x_data + b # We know that W should be 1 and b 0 # random_uniform -> random function -1.0 ~ 1.0 W = tf.Variable(tf.random_uniform([1],-1.0,1.0)) b = tf.Variable(tf.random_uniform([1...
string = [] # input value while True: try: input_str = input() if input_str == "": # new line string.append(input_str) input_str = input() if input_str == "": break # 2 new line break else: string.append(input_str) ...
num = str(input()) # 입력 받기 temp = [] # 리스트 초기화 temp.extend(list(num)) # 리스트에 스플릿 if len(temp) == 1: # 주어진 수가 10보다 작다면 0을 붙여 두 자리수를 만듦 temp.clear() temp.append("0") temp.extend(list(num)) # 재스플릿 num = "0" + num t1 = int(temp[0]) # 변수 할당 t2 = int(temp[1]) temp.clear() # 할당 후 재사용을 위해 초기화 f_num...
# @Version : 1.0 # @Time : 2019/4/30 # @Author : 实小楼 import time print('■■■■■■■■■■ 欢迎来到地下城,送死的凡人 ■■■■■■■■■■') print(''' , _..._ , {'. .' '. .'} { ~ '. _|= __|_ .' ~} { ~ ~ '-._ (___________) _.-'~ ~ } {~ ~ ~ ~.' '. ~ ~...
# @Author: subalakshmi # @Date: 2019-09-25T18:32:14+05:30 # @Last modified by: subalakshmi # @Last modified time: 2019-09-25T18:37:54+05:30 import random import matplotlib.pyplot as plt #Account of money possesed by one account=0 x=[] y=[] for i in range(365): # Accepting for seven days # bet = int(input(...
#!/usr/bin/env python2 # How many routes through a 20x20 grid? # Start at top left # go only right or down. # 2x2 grid. Will take 4 moves to get from [0,0] to [2,2] # Two moves right and two moves down. All correct routes will be 4 # moves, consisting of 2 rights and 2 downs, but in different orders. # So, if there w...
#!/usr/bin/env python2 # find pythagorean triplet where a + b + c = 1000 # return a * b * c # 1. a2 + b2 = c2 # 2. a + b + c = 1000 # substitute 1 into 2 # a + b + sqrt(a2 + b2) = 1000 # sqrt(a2 + b2) = 1000 - a - b # square both sides # a2 + b2 = (1000 - a - b) (1000 - a - b) # a2 + b2 = 1000 * 1000 - 1000a - 10...
#!/usr/bin/env python # Copyright 2016 François 'ftiff' Levaux-Tiffreau # # Set a list of certificate names you expect to have. # This script will output the list of certs that are missing. # eg. <result>Missing certificate(s): [''MyDummyCert1]</result> import subprocess certificate_names = [ 'MyDummyCert1', ...
""" We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops. """ def make_bricks...
year=2000 if year%4 is 0: print("Year is Leap") else: print("Year is not Leap")
import math """ Return a matrix of all pairs shortest paths, given an input graph in the form of an adjacency matrix. This is the Floyd-Warshall algorithm. """ def all_pairs_shortest_paths(adjacency_matrix, number_of_locations): n = number_of_locations shortest_dist_matrix = [[math.inf] * n for _ in range(n)...
"""Using disctionary""" #Accepted on Leetcode class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.triedict = dict() def insert(self, word): """ Inserts a word into the trie. :type word: str ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1:ListNode, l2:ListNode) -> ListNode: if l1 is None: return l2 if l2 is None: return l1 if l1.val < l2.val: outpu...
# # 导入模块1 # import my_module # # celsius = float(input('Enter a temperature in Celsius: ')) # fahrenheit = my_module.c_to_f(celsius) # print("That's", fahrenheit, 'degrees Fahrenheit') # # 导入模块2 # from my_module import c_to_f # # celsius = float(input('Enter a temperature in Celsius: ')) # fahrenheit = c_to_f(celsius)...
# # 1 删除字符串中不需要的字符 # # 利用strip()方法删除开始或结尾的字符,其中lstrip()和rstrip()分别是从左和右执行 # s = ' hello world \n' # print(s.strip()) # print(s.lstrip()) # print(s.rstrip()) # t = '-----hello=====' # print(t.lstrip('-')) # print(t.strip('-=')) # # strip()无法处理字符串中间的文本 # k = ' hello world \n' # print(k.strip()) # print(k.replace(' ',...
# # 旋转数组 # def rotate(nums, k): # """ # :type nums: List[int] # :type k: int # :rtype: void Do not return anything, modify nums in-place instead. # """ # length = len(nums) # for i in range(length): # nums.append(nums[i]) # temp = len(nums) - k # for j in range(k): # ...
# # 两数相加 # def addTwoNumbers(l1, l2): # """ # :type l1: ListNode # :type l2: ListNode # :rtype: ListNode # """ # stack = [0] # dummy = ListNode(0) # cur = dummy # while l1 and l2: # value = l1.val + l2.val + stack[-1] # if value >= 10: # value = value % 10...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 11 16:56:59 2020 @author: owlthekasra """ array = [2,3,9,5,2000,3,6,10,4] newarr = [] last = None for element in array: if (last != None): if (element > last): newarr.append(element) last = element def get_highest_...
def tribonacci(signature, n): arr = signature newArr = [] for i in signature: n1 = arr[0] n2 = arr[1] n3 = arr[2] c = 0 if n == 1: newArr.append(n1) print (newArr) else: while(c < n ): newArr.append(n1) sum = n1 + n2 + n3 ...
def insertionSort(arr): n = int(len(arr)) for i in range(1,n): key = arr[i] j = i-1 while j >= 0 and key < arr[j] : arr[j+1] = arr[j] j = j-1 arr[j+1] = key arr = [12, 11, 13, 5, 6] insertionSort(arr) print(arr)
from QiuGuo_Linked_List import Linked_List class Deque: def __init__(self): self._list = Linked_List() def __str__(self): return str(self._list) def __len__(self): return len(self._list) def push_front(self, val): if len(self._list) == 0: self._list.append_element(val) else: ...
l=int(input('enter the length of rectangle')) #inputs from user b=int(input('enter breadth of rectangle')) perimeter=[2*(l+b)] #formula for perimeter print 'The perimeter of rectangle is:',perimeter #print result
''' Script for Checking the file extension [ pdf and Xlsx ] python version 2.7 ''' import sys #File extenstion check def check_ext(filename,ext): for x in filename: print "check the ext ",x #Extension check if(x.endswith(tuple(ext))): print "Success connection with files" ...
import doctest class Box: """ >>> box_a = Box([1,2,3],[4,5,6]) >>> box_b = Box([1,2,3],[4,5,6]) >>> box_a.intersects(box_b) True >>> box_a.position[0] += 4 >>> box_a.intersects(box_b) False """ position = None size = None def __init__(self, position=[0, 0, 0], size=[0...
#coding=UTF-8 import tensorflow as tf import numpy as np #create training data : y = 0.1x + 0.3 x_data = np.random.rand(1,100) # vector 1*100 x_data.astype(np.float32) # transforming the data to float32 for tensorflow y_data = 0.1*x_data + 0.3 ### create tensorflow structure start ### Weights = tf.Variable(tf.ra...
''' Happy number -- Leetcode 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 loops endlessly in a cycle which does not include 1. ...
''' Fast Modulo multiplication (Binary Exponentiation) Calculating (x^n) % m ''' # m = 10^9 + 7 m = 1000000007 def mod_exp1(x,n): if n==0: return 1 elif n==1: return x%m elif n%2==0: return mod_exp1((x%m*x%m)%m,n/2) else: return ((x%m)*(mod_exp1((x%m*x%m)%m,(n-1)/2))%m...
''' Calculate maximum sum of k-consecutive elements in array. Window Sliding technique -- O(n) ''' nums=list(map(int,input().split())) k=int(input()) if k>len(nums): print('Invalid sub-array length') else: window_sum=0 for i in range(k): window_sum+=nums[i] max_sum=window_sum n=len(nums...
''' Powerset of a set. Plus, finding the largest subset in which every pair of elements is divisible by one or other. ''' def powerset(s): n=len(s) p=pow(2,n) sub=[] for i in range(p): x=bin(i)[2:] x='0'*max(0,n-len(x))+x x=x[::-1] temp=[] for j,k in enumera...
''' Factors of a number in sqrt(n) time complexity ''' import math N=int(input('Enter n : ')) end=int(math.sqrt(N)) factors=[] for i in range(1,end+1): if N%i==0: factors.append(i)
''' Left-rotation in an array. Method-1(using temporary array) Space complexity : O(n) ''' print('Enter space-separated integers in the array : ') nums=[int(i) for i in input().split()] n=len(nums) nums=nums+nums d=int(input('Enter the left-rotation unit : ')) print(nums[d:d+n])
''' nth fibonacci number 0,1,1,2,3,.. ''' def fibonacci(n): a,b=0,1 for i in range(n): a,b=b,a+b return a n = int(input('Enter n : ')) print('{}'.format(fibonacci(n)))
''' Counting number of inversions in an array ''' def mergesort(arr): # temp_arr to store sorted array in merge function temp_arr=[0]*len(arr) return _mergesort(arr,temp_arr,0,len(arr)-1) def _mergesort(arr,temp_arr,p,r): inv_count=0 if p<r: q=(p+r)//2 inv_count+=_mergesort(arr,t...
year = int(input('Enter a year: ')) print('leap year' if year%400 == 0 or year%4 ==0 and year%100 != 0 else 'not a leap year')
class Solution: def isPrefixString(self, s: str, words: List[str]) -> bool: i, n = 0, len(s) for word in words: if i == n: return True if len(word) > n - i: return False if word != s[i:i+len(word)]: return False ...
class Solution: def isValidBST(self, root: TreeNode) -> bool: values = [] stack = [] curr = root while curr is not None: stack.append(curr) curr = curr.left while stack: curr = stack.pop() if values and values[-1] >...
class LargerNum(str): def __lt__(x, y): return x+y > y+x class Solution: def largestNumber(self, nums: List[int]) -> str: nums = sorted(map(str, nums), key=LargerNum) # print(nums) return ''.join(nums) if nums[0] != '0' else '0'
class Solution: def isStrobogrammatic(self, num: str) -> bool: dmap = {'1':'1', '6':'9', '8':'8', '9':'6', '0':'0'} newnum = '' for c in num: if c in dmap: newnum += dmap[c] else: return False newnum = newnum[::-1] # pri...
class Solution: def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: # find the point to insert list2 head1 = list1 for i in range(a-1): head1 = head1.next # find the 2nd part of list1 tail1 = head1 for i in range(b-a+2):...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # merge two lists at a time class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists: return None while len(lists) > 1: ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # recursive class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: def moveon(node): if node is None: return node ...
# brute force recursive class Solution: def removeDuplicates(self, S: str) -> str: s = '' i, n = 0, len(S) flag = True while i < n: if i < n-1 and S[i] == S[i+1]: flag = False i += 2 else: s += S[i] ...
# record all nodes and check duplicates at iteration class Solution: def hasCycle(self, head: ListNode) -> bool: nodes = set() curr = head while curr is not None: if curr in nodes: return True nodes.add(curr) curr = curr.next return...
import pygame import pathFunction class Player(pygame.sprite.Sprite): """ Inside this class i create a player object out of png images """ def __init__(self, position, images): pygame.sprite.Sprite.__init__(self) size = (32,32) self.rect = pygame.Rect(position, size) s...
""" CSCI 1200 Lab Exercise 5.0 IF STATEMENTS In this lab we will learn how to run code based on some conditions. Do all work in Geany IDE and follow instructions provided in this code file. Learning Outcomes ================= In this lab you will learn how to: - write conditional statements - declare if statements ...
""" CSCI 1200 Lab Exercise 4.0 WORKING WITH LISTS In this lab we will we will learn about for loops and indentation. Do all work in Geany IDE and follow instructions provided in this code file. Learning Outcomes ================= In this lab you will learn how to: - declare and use for loops - indent code and fix i...
from __future__ import print_function #import tensorflow as tf #import tensorflow.keras from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.optimizers import RMSprop import numpy as np import matplotlib.pypl...
import string import random def add_sequence(sequence): dict_sequence[sequence] = dict_sequence.get(sequence, 0) + 1 def check_sequence(first, second, third): if dict_sequence.get(third, 0) > 40000 - 1: return False if dict_sequence.get(second + third, 0) > 2000 - 1: return False if di...
""" Interest rate transformations =============================================================================== Overview ------------------------------------------------------------------------------- Transformations between nominal, effective and periodic interest rates can be realized using **cashflows**. This mo...
""" Economic utility functions =============================================================================== Overview ------------------------------------------------------------------------------- Functions in this module ------------------------------------------------------------------------------- """ from ...
""" Asset depreciation =============================================================================== Overview ------------------------------------------------------------------------------- This module implements the following functions to compute the depreciation of an asset: * ``depreciation_sl``: Computes the d...
from queue import Queue,PriorityQueue import copy import sys import io from typing import Callable class Direction: LEFT = (0, -1) RIGHT = (0,1 ) DOWN = (1, 0) UP = (-1, 0) def getDirectionOrder(start : tuple,goal : tuple): # start부터 goal까지 가기 위해서 우선순위대로 방향을 반환 x = [Direction.RIGHT,Direction.L...
import random def GuessingGame(): number = int(random.randint(1,10)) WhatsYourNumber=int(input("Whats your number?")) while WhatsYourNumber != number: print("keep guessing") WhatsYourNumber=int(input("Whats your number")) if WhatsYourNumber == number: print("winner") break GuessingGame()
""" ------------------------------------------------------------------------------ Name: Livehack2_problem1.py Purpose: To check the type of triangle a user inputs Author: Zhu.D Created: 18/11/2019 ------------------------------------------------------------------------------ """ print ("Welcome to the ...
print(""" ------------------------------------------------------------------------------- Name: problem2.py Purpose: To determine how many chicken pieces Mr. Fabroa and each of his students get. Author: Zhu.D Created: 02/10/2019 ------------------------------------------------------------...