text
stringlengths
37
1.41M
""" 输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。 要求时间复杂度为O(n)。   示例1: 输入: nums = [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。   提示: 1 <= arr.length <= 10^5 -100 <= arr[i] <= 100 注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/ 来源:力扣(LeetCode) 链接:https://leetcode-cn.com...
""" 1081. Smallest Subsequence of Distinct Characters Medium 271 52 Add to List Share Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once. Example 1: Input: "cdadabcc" Output: "adbc" Example 2: Input: "abcd" Output: "abcd" Example 3: Input: "e...
""" 给定两个用链表表示的整数,每个节点包含一个数位。 这些数位是反向存放的,也就是个位排在链表首部。 编写函数对这两个整数求和,并用链表形式返回结果。   示例: 输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295 输出:2 -> 1 -> 9,即912 进阶:假设这些数位是正向存放的,请再做一遍。 示例: 输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295 输出:9 -> 1 -> 2,即912 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sum-lists-lcci 著作权归领扣...
#!/usr/bin/env python3 # info # -name : zhangruochi # -email : zrc720@gmail.com """ Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". """ class Solution(object): def addBinary_1(self, a, b): """ :type a: str :type b: str ...
""" 给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。 示例: 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3 输出: [3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3...
""" Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ ...
""" Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which looks like following: 4 -> 5 -> 1 -> 9 Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5...
""" Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.   Example 1: Input: nums = [10,5,2,6], k = 100 Output: 8 Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6]...
""" Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's. You must do it in place. """ class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ visited_rows = set...
""" Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array. Follow ...
""" 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 示例 1: 输入:A = [1,2,3], B = [3,1] 输出:false 示例 2: 输入:A = [3,4,5,1,2], B = [4,1] 输出:true 限制: 0 <= 节点个数 <= 10000 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left =...
""" 实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。   示例 1: 输入: 2.00000, 10 输出: 1024.00000 示例 2: 输入: 2.10000, 3 输出: 9.26100 示例 3: 输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25   说明: -100.0 < x < 100.0 n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 来源:力扣(LeetCode) 链接:https://l...
""" Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses. Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters. So, your input will be...
""" Given a linked list, swap every two adjacent nodes and return its head. Example: Given 1->2->3->4, you should return the list as 2->1->4->3. Note: Your algorithm should use only constant extra space. You may not modify the values in the list's nodes, only nodes itself may be changed. """ #Definition for singly-...
weight = [10,20,15,8] values = [2,7,4,8] Max_ = 29 max_value = 0 max_value_path = None def backpack( path, cur_weight, cur_value, pos): global max_value, max_value_path, Max_ if pos == len(weight): if cur_weight <= Max_: if max_value < cur_value: max_value = cur_value ...
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rt...
""" 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。   示例 1: 输入:s = "We are happy." 输出:"We%20are%20happy."   限制: 0 <= s 的长度 <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def replaceSpace(self, s: str) -> str: res = "" f...
""" 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?   示例 1: 输入:m = 2, n = 3, k = 1 输出:3 示例 2: 输入:m = 3, n = 1, k = 0 输出:1 提示: 1 <= n,m <= 100 0 <= k <= 20 来...
""" Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. ...
""" Design and implement a data structure for a compressed string iterator. It should support the following operations: next and hasNext. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string. n...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque from collections import defaultdict class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: ...
""" A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. "" # Definition for singly-linked list with a random pointer. # class RandomListNode(object): # def __init__(self, x): # self.label = x #...
""" Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. Examples: Input: S = "a1b2" Output: ["a1b2", "a1B2", "A1b2", "A1B2"] Input: S = "3z4" Output: ["3z4", "3Z4"] Input: S = "12345" Output: ["123...
""" Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. Example: Input: "Hello World" Output: 5 """ cl...
""" Write a program to find the nth super ugly number. Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. Example: Input: n = 12, primes = [2,7,13,19] Output: 32 Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 sup...
from collections import defaultdict class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ ans = defaultdict(list) for word in strs: ans["".join(sorted(word))].append(word) return list(ans.val...
''' Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 ''' import operat...
""" Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. Note: The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not...
""" Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Input: matrix = [[1,3,5,7],[10,11,16,20...
""" 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。 示例1: 输入:[1, 2, 3, 3, 2, 1] 输出:[1, 2, 3] 示例2: 输入:[1, 1, 1, 1, 2] 输出:[1, 2] 提示: 链表长度在[0, 20000]范围内。 链表元素在[0, 20000]范围内。 进阶: 如果不得使用临时缓冲区,该怎么解决? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def merge(self,list1,list2): dummy = ListNode(0) cur = dummy while list1 and list2: if list1.val <= list2.val: cur.next ...
""" 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。   示例 1: 输入: s = "abcdefg", k = 2 输出: "cdefgab" 示例 2: 输入: s = "lrloseumgh", k = 6 输出: "umghlrlose"   限制: 1 <= k < s.length <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chu...
""" Given an array of integers A, consider all non-empty subsequences of A. For any sequence S, let the width of S be the difference between the maximum and minimum element of S. Return the sum of the widths of all subsequences of A. As the answer may be very large, return the answer modulo 10^9 + 7. Example 1:...
class Node: def __init__(self, val): self.val = val self.next = None class LinkedLIst: def __init__(self): self.ll = [] def add_last(self, item): node = Node(item) if self.ll != []: self.ll[-1].next = node self.ll.append(node) def remove(s...
name = input('Enter your name: ') print('hello', name) hours = input('Enter Hours: ') rate = input('Enter Rate: ') pay = float(hours) * float(rate) print(name, 'your pay is', pay)
f = float(input('Digite a temperatura em graus Fahrenheit: ')) c = 5.0 * (f - 32) / 9.0 print(f'A temperatura º{f} em Celsius é º{c}')
s = float(input('Salário atual: ')) ns = s + (s * 0.25) print(f'Novo salário: {ns}')
n = int(input('Digite um número PAR: ')) if n % 2 != 0: print(f'{n} não é PAR!') else: for i in range(0, n + 1): if i % 2 == 0: print(f'{i}')
d = int(input('Mês do ano 1 a 12: ')) if d == 1: print('Janeiro') elif d == 2: print('Fevereiro') elif d == 3: print('Março') elif d == 4: print('Abril') elif d == 5: print('Maio') elif d == 6: print('Junho') elif d == 7: print('Julho') elif d == 8: print('Agosto') elif ...
import math n = 1 while n > 0: n = int(input('Informe um número: ')) print(f'Quadrado: {n * n} \n' f'Cubo: {n * n * n} \n' f'Raiz quadrada: {round(math.sqrt(n), 2)}')
r = float(input('Valor R$: ')) d = float(input('Cotação U$: ')) print(f'Valor R${r} em U${r / d}.')
ag = int(input('Informe sua idade: ')) tt = int(input('Informe o tempo de trabalho: ')) if ag >= 65: print(f'Aposentadoria aprovada, {ag} anos de idade.') elif tt >= 30: print(f'Aposentadoria aprovada, {tt} anos trabalhados.') elif ag >= 60 and tt >= 25: print(f'Aposentadoria aprovada!\n' ...
n = int(input('Informe um número: ')) e = 1 + 1 / (1 * 1) + 1 / (2 * 2) + 1 / (3 * 3) + n + 1 / (n * n) print(f'Valor de E: {round(e, 2)}')
age = int(input('Informe a idade do nadador: ')) # noinspection PyChainedComparisons if age >= 5 and age < 8: print(f'Infantil A: {age} anos de idade.') elif age >= 8 and age < 11: print(f'Infantil B: {age} anos de idade.') elif age >= 11 and age < 14: print(f'Juvenil A: {age} anos de idade.') eli...
n = int(input('Digite um número para saber se Par ou Impar: ')) if n % 2 != 0: print(f'Número {n} é IMPAR.') else: print(f'Número {n} é PAR.')
import math a = float(input('Valor de A: ')) b = float(input('Valor de B: ')) h = math.sqrt(a * a) + math.sqrt(b * b) print(f'Teste {h}')
r1 = 0 r2 = 0 r = 1 while r != 0: r1 = int(input('Resistor 1: ')) r2 = int(input('Resistor 2: ')) r = (r1 * r2) / (r1 + r2) print(f'Resistor: {round(r, 2)}')
a = 0 b = 0 c = 0 d = 0 mArit = 0 while a < 10 or a > 20 or b < 10 or b > 20 or c < 10 or c > 20 or d < 10 or d > 20: a = int(input('A: ')) b = int(input('B: ')) c = int(input('C: ')) d = int(input('D: ')) if a < 10 or a > 20 or b < 10 or b > 20 or c < 10 or c > 20 or d < 10 or d > 20:...
#Class that communicate with database in sqlite import sqlite3 import random class Database: def __init__(self): self.conn = sqlite3.connect('lista_dan.db') self.cur = self.conn.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS dania (id INTEGER PRIMARY KEY, danie TEXT, skladniki TEXT...
import urllib from BeautifulSoup import BeautifulSoup as bs response = urllib.urlopen('http://www.jiandan.net','r') html = response.read() soup = bs(html) for a in soup('a'): print a
#coding=utf-8 ''' 定义一个集合的操作类:Setinfo 包括的方法: 1 集合元素添加: add_setinfo(keyname) [keyname:字符串或者整数类型] 2 集合的交集:get_intersection(unioninfo) [unioninfo :集合类型] 3 集合的并集: get_union(unioninfo)[unioninfo :集合类型] 4 集合的差集:del_difference(unioninfo) [unioninfo :集合类型] set_info = Setinfo(你要操作的集合) ''' a = set([1,3,4,5]) c...
#coding=utf-8 class boy(object): genous = 1 def __init__(self,name): self.name = name class girl(object): genous = 0 def __init__(self,name): self.name = name class love(): def __init__(self,first,second): self.first = first self.second = second def meet(self): return '这是%s和%s的恋爱'%...
""" Sample donors """ def get_donors(): thomas = 'Thomas', {'donations': '500', 'email': 'thomas@thomas.com', 'city': 'Athens', 'state': 'GA', 'zip': '30606'} ted = 'Ted', {'donations': '1', 'email': 'ted@ted.com', 'city': 'Memphis', 'state': 'TN', 'zip': '38104'} bailey = "Bailey", {'donations': '10...
#!/usr/bin/env python3 __author__ = "roy_t githubtater" import pandas as pd music = pd.read_csv('featuresdf.csv') def danceable_closure(): """Return a function of songs of given danceability""" def danceable(danceability=0.8): """Generator returning songs with danceability over a given value""" tracks = ((ro...
#!/usr/bin/env python3 # Lesson 03 - Context Manager """ Write a context manager class Locke to simulate the overall functioning of the system. When the locke is entered it stops the pumps, opens the doors, closes the doors, and restarts the pumps. Likewise when the locke is exited it runs through the same steps: ...
# ------------------------------------------------- # # Title: Lesson 1, pt 1, Song Assignment # Dev: Craig Morton # Date: 11/5/2018 # Change Log: CraigM, 11/5/2018, Song Assignment # ------------------------------------------------- # # !/usr/bin/env python3 import pandas as pd music = pd.read_csv("featuresdf.cs...
#!/usr/bin/env python3 import pandas as pd music = pd.read_csv("featuresdf.csv") ml = [x for x in zip(music.name, music.artists, music.danceability, music.loudness) if x[2]>0.8 and x[3]<-5] # use sort instead of sorted .. --> sort does not return a list, it sorts the list itself ml.sort(key=lambda x:x[2], reverse=T...
''' Lesson 3 Assignment #2 Recursive ''' def fact(n): if n <= 1: return 1 return n * fact(n - 1) print(fact(10))
#!/usr/bin/env python3 __author__ = "roy_t githubtater" import unittest import generators as gen class TestGenerators(unittest.TestCase): def test_sum_of_integers(self): sum_gen = gen.sum_of_integers() assert next(sum_gen) == 0 assert next(sum_gen) == 1 assert next(sum_gen) == 3 assert next(sum_gen) == 6...
"""Divides two numbers""" class Divider(): """Class for divider""" @staticmethod def calc(operand_1, operand_2): """Perform division""" try: return operand_1/operand_2 except ZeroDivisionError: return False
""" Lesson 9 submision file. Uses News API to get titles with multithreading. """ #orioginal API = "0c90527956054643acefdedb6587d07f" #alt API 1 = "74c1d999b2bb43feaabb8c3c194fe5b3" import time import requests import threading import queue WORD = "Boeing" NEWS_API_KEY = "74c1d999b2bb43feaabb8c3c194fe5b3" ...
# implements a recursive factorial function def factorial(n): return 1 if (n < 1) else n * factorial(n-1) print(factorial(0)) print(factorial(5)) print(factorial(10)) print(factorial(15))
#!/usr/bin/env python3 __author__ = 'roy_t' # this function was 'borrowed' from the following text: # Lott, S. (2015) Chapter 6. Recursions and Reductions. In Functional Python Programming. def factorial(n): """Return the factorial of n""" if n == 0: return 1 # otherwise: recurse through the function un...
""" Module to populate our sqlite database with people. """ import logging import db_printer from database_ex import * from datetime import datetime logging.basicConfig(level=logging.INFO) logger = logging.getLogger(name=__name__) database = SqliteDatabase('personjob.db') def calc_days(day_1, day_2): """ Ca...
from operations_database import * choices = {1: send_thankyou, 2: create_report, 3: send_letters, 4: close_program } def user_input(): try: action = int(input("\nChoose one of four actions: \n"+ "1. Send a Thank You \n" + ...
# ------------------------------------------------- # # Title: Lesson 3, Recursion/Factorial Assignment # Dev: Craig Morton # Date: 11/25/2018 # Change Log: CraigM, 11/25/2018, Recursion/Factorial Assignment # ------------------------------------------------- # #!/usr/bin/env python3 def factorial(n): """"Det...
''' Lesson 1 Generator Draft 1 ''' def intsum(x=0, total=0): while True: total += x yield total x += 1 def doubler(x=1): while True: yield x x *= 2 def fib(a=0, b=1): while True: a, b = b, a+b yield a def prime(x=2): while True: ...
""" Unit tests for the water-regulation module """ import unittest from unittest.mock import MagicMock from pump import Pump from sensor import Sensor from .controller import Controller from .decider import Decider class DeciderTests(unittest.TestCase): """ Unit tests for the Decider class """ def ...
#!/usr/bin/env python """ Simple iterator examples """ class IterateMe_1: """ Simple iterator - returns the sequence of numbers from zero to 4 ( like range(4) ) """ def __init__(self, stop=5): self.current = -1 self.stop = stop def __iter__(self): return self def ...
#!/usr/bin/env python3 import pandas as pd music = pd.read_csv("featuresdf.csv") def main(): string_format = "{:<20} | {:<20}" songs = drake_generator() print("{:<20} | {:<20}".format("Tracks", "Artist")) print("-"*35) for i in songs: print(string_format.format(*i)) # Generator that f...
import math def intsum(): i = sum = 0 while True: sum += i i += 1 yield sum def intsum2(): i = sum = 0 while True: sum += i i += 1 yield sum def doubler(): i = sum = 1 while True: yield i i = i * 2 def fib(): i, j = 0, 1 ...
#!/usr/bin/env python3 # Lesson 01, Comprehensions import pandas as pd music = pd.read_csv("featuresdf.csv") toptracks = sorted([x for x in zip(music.danceability, music.loudness, music.artists, music.name) if x[0] > 0.8 and x[1] < -5], reverse=True) for track in toptracks[:5]: print(track[3] + " by " + track[2]...
def factorial(num): if num <= 1: return 1 else: return num * factorial(num-1) if __name__ == "__main__": results = (1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200) for i in range(0, len(results)): assert results[i] ...
"""defines adder object""" class Adder: """adder object to be used in calculator""" @staticmethod def calc(operand_1, operand_2): """runs addtion for calc call""" return operand_1 + operand_2
#!/usr/bin/env python """ Get artists and song names for for tracks with danceability scores over 0.8 and loudness scores below -5.0. In other words, quiet yet danceable tracks. Also, these tracks should be sorted in descending order by danceability so that the most danceable tracks are up top. """ import pandas as p...
"""This is an Adder""" class Adder(object): """Do the adding""" @staticmethod def calc(operand_1, operand_2): """Add""" return operand_1 + operand_2
""" mongodb homework assignment """ import pprint import login_database import utilities log = utilities.configure_logger('default', '../logs/mongodb_assignment.log') def add_furniture(): """ mongodb assignment - add furniture items, separate the product field into two fields: product type and color...
"""Module for dividing two numbers""" class Divider(object): """Class for division of 2 numbers.""" @staticmethod def calc(operand_1, operand_2): """ Perforn the division step.""" return operand_1/operand_2
""" Student: Jared Mulholland Assignment: Calculator Unit Tests Date: 7/17/2019 """ from unittest import TestCase from unittest.mock import MagicMock from calculator.adder import Adder from calculator.subtracter import Subtracter from calculator.divider import Divider from calculator.multiplier import Multiplier from...
""" This module provides a subtraction operator """ class Subtracter(object): """ Provides a subtraction method """ @staticmethod def calc(operand_1, operand_2): """ Subtracts the second number input from the first """ return operand_1 - operand_2
"""A simple calculator.""" from .exceptions import InsufficientOperands class Calculator(object): """An object to encapsulate a simple calculator.""" def __init__(self, adder, subtracter, multiplier, divider): """Initializor for the calculator.""" self.adder = adder self.subtracter =...
import pandas as pd # Read in Spotify's top 100 songs music = pd.read_csv("featuresdf.csv") def sheeran_songs(df): """Generator returns Ed Sheeran songs from the provided dataframe.""" for title, artists in zip(df.name, df.artists): if 'Ed Sheeran' in artists: yield title # Print Ed Sheer...
"""Multiplier class""" class Multiplier(object): """perform multiplication""" @staticmethod def calc(operand_1, operand_2): """multiplication""" return operand_1*operand_2
""" This module provides a subtraction operator """ class Subtracter(object): """ Subtractor class Produces operand 1 - operand 2 """ @staticmethod def calc(operand_1, operand_2): """ method to subtract operand2 from operand1 :param operand_1: first operand (a number) ...
"""Adder Function""" class Adder(object): """Adder Class used for calculator""" @staticmethod def calc(operand_1, operand_2): """Adds two numbers""" return operand_1 + operand_2
import pandas as pd music = pd.read_csv("featuresdf.csv") """Write a closure to capture high energy tracks. High energy default is 0.8""" def high_energy(min_energy1 = 0.8): min_energy = min_energy1 def find_favorite(): for artist, song, energy in zip(music.artists, music.name, music.energy): ...
#!/usr/bin/env python3 # complicated_example.py def main(): x = 'main' one() def one(): y = 'one' two() def two(): z = 'two' long_loop() def long_loop(): z_count = 0 for i in range(2, 1001, 5): for j in range(3, 1001, 7): for k in range(12, 1001): ...
""" ORIGINAL AUTHOR: INSTRUCTOR CO-AUTHOR: Micah Braun PROJECT NAME: integrationtest.py DATE CREATED: File originally created by instructor, date unknown UPDATED: 10/18/2018 PURPOSE: Lesson 6 DESCRIPTION: Tests for Calculator class and its methods. """ from unittest import TestCase from calculator.adder import Adder f...
""" Calculator module """ from .exceptions import InsufficientOperands class Calculator(): """ Create the calculator object. """ def __init__(self, adder, subtracter, multiplier, divider): """ Initialize the calculator """ self.adder = adder self.subtracter = ...
def intsum(): isum = [0, 0] while True: yield isum[1] isum[0] += 1 isum[1] += isum[0] def intsum2(n=1): while True: yield (n*(n-1)) / 2 n += 1 def doubler(n=0): while True: yield 2 ** n n += 1 def fib(): f_n = [0, 1] while True: ...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ """ Simple iterator examples """ class IterateMe_1: """ About as simple an iterator as you can get: returns the sequence of numbers from zero to 4 ( like range(4) ) """ def __init__(self, stop=5): self.c...
# Nebiat # hw2 Generators and Closures import pandas as pd music = pd.read_csv("featuresdf.csv") # Lists favorite artists using generator def fav_artists_wGen(name): # rows that favorite artist appears rows = music.index[music.artists == name] # returns name of song in that row song_name = (music.at[...
#!/usr/bin/env python3 """ json_save metaclass based system for saving objects in a JSON format This could be useful, but it's kept simple to show the use of metaclasses The idea is that you subclass from JsonSavable, and then you get an object that be saved and reloaded to/from JSON """ import json # import * is...
#!/usr/bin/env python # Lesson1 - Aurel Perianu class IterateMe_2: """ A more complex iterator: returns the sequence of numbers from start to stop with step """ def __init__(self, start=1, stop=10, step=1): self.start = start self.stop = stop self.step = step ...
""" Assignment 1: populate the database table """ import logging from create_db import * from datetime import datetime def duration_calculator(start_date, end_date): start = datetime.strptime(''.join(start_date.split('-')), '%Y%m%d') end= datetime.strptime(''.join(end_date.split('-')), '%Y%m%d') retur...
""" 1. Create Data structure that holds Donor, Donation Amount. 2. Prompt user to Send a Thank You, Create a Report, or quit. 3. At any point, the user should be able to quit their current task and return to the original prompt 4. From the original prompt, the user should be able to quit the scipt cleanly """ import ...
""" This module compasses the Calculator class """ from .exceptions import InsufficientOperands class Calculator(object): """ This class provides the basic functionality of a calculator. Attributes: adder (object): Instance of Adder class subtracter (object): Instance of Subtracter cl...
""" Unit tests for the water-regulation module """ import unittest from unittest.mock import MagicMock from pump import Pump from sensor import Sensor from .controller import Controller from .decider import Decider class DeciderTests(unittest.TestCase): """ Unit tests for the Decider class """ act...
#!/usr/bin/env python """ Simple iterator examples """ class IterateMe_1: """ About as simple an iterator as you can get: returns the sequence of numbers from zero to 4 ( like range(4) ) """ def __init__(self, stop=5): self.current = -1 self.stop = stop def __iter__(sel...
def factorial(n): if n < 0 or not isinstance(n, int): raise ValueError('n must be a non-negative intiger') if n == 0: return 1 else: return factorial(n-1) * n if __name__ == "__main__": print('9 Factorial: {}'.format(factorial(9))) print('5 Factorial: {}'.format(factor...