text
stringlengths
37
1.41M
class Task: type = "none" def __init__(self, description): self.description = description # this method lets you use print() with Task objects def __str__(self): if self.type == "none": return self.description elif self.type == "due": return self.descrip...
def is_prime(n): '''is_prime(n) -> boolean returns True if n is prime, False otherwise''' if n < 2: return False for divisor in range(2,int(n**0.5)+1): if n % divisor == 0: return False return True def sum_of_prime_cubes(n): '''sum_of_prime_cubes(n) -> int return...
def encipher_fence(plaintext,numRails): '''encipher_fence(plaintext,numRails) -> str encodes plaintext using the railfence cipher numRails is the number of rails''' textList = list (plaintext) #maps each character to a number index = 0 railNum = 0 cipher = "" railLists = [] #create a li...
def get_base_number(num,base): '''get_base_number(num,base) -> int returns value of num as a base number in the given base''' num = list (num) #convert into a list and reverse since the values of the bases are reversed num = num [::-1] #always start counting from last digit anyways index = 0 #traver...
num1 = input("num1:") num2 = input("num2:") num3 = input("num3:") max_num = 0 if num1>num2: max_num = num1 if max_num > num3: print("max number is ",max_num) else: print("max number is ",num3) else: max_num = num2 if max_num > num3: print("max number is ",max_num) else...
# メッセージボックスの作成 import tkinter import tkinter.messagebox # messageboxモジュールをインポート # ボタンをクリックした時の関数を定義 def c_btn(): tkinter.messagebox.showinfo("情報", "再起動します……") # showinfo()命令でメッセージボックスを表示 # tkinter.messagebox.showwarning("危険!", "おしまいDETH!") # showwarningで警告表示 window = tkinter.Tk() window.title("メッセージボックス"...
# 自爆スイッチの配置 import tkinter def click_btn(): jibaku["text"] = "押してしまった……" window = tkinter.Tk() window.title("自爆スイッチ") window.geometry("1000x550") jibaku = tkinter.Button(window, text="自爆スイッチ〜絶対に押すな!と言われたら押したくなっちゃうよね〜", font=("Toppan Bunkyu Mincho", 24), command=click_btn) jibaku.place(x=60, y=200) window.mainl...
class ListNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next def insert_after(self, value): """This makes me think about some sort of while loop. where we are searching for the actual value at that point we can bre...
#!python3 """ 给定一个字符串,找出不含有重复字符的最长子串的长度。 示例: 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。 给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。 给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串。 """ class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ ...
from card_deck import * from blackjack_book import * class PlayerHand: """ Represents a hand of cards and is used to calculate the value of the hand. """ def __init__(self, cards=[]): """ :param cards: List of Card objects """ self.cards = cards self.soft = Fals...
#! python3 # email_control.py # Author: Michael Koundouros """ Write a program that checks an email account every 15 minutes for any instructions you email it and executes those instructions automatically. For example, BitTorrent is a peer-to-peer downloading system. Using free BitTorrent software such as qBittorrent, ...
#! python3 # convert_sheets.py # Author: Michael Koundouros """ You can use Google Sheets to convert a spreadsheet file into other formats. Write a script that passes a submitted file to upload(). Once the spreadsheet has uploaded to Google Sheets, download it using downloadAsExcel(), downloadAsODS(), and other such fu...
""" Ref: Chapter 5 - Dictionaries Ref: Automate the Boring Stuff with Python, Al Sweigart, 2nd Ed., 2019 Author: Michael Koundouros July 2020 Here is a short program that counts the number of occurrences of each letter in a string. """ import pprint message = 'It was a bright cold day in April, and the clocks...
""" Ref: Chapter 7 - Regular Expressions Ref: Automate the Boring Stuff with Python, Al Sweigart, 2nd Ed., 2019 Author: Michael Koundouros July 2020 Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range from 01 to 12, and the years...
#! python3 # xl2csv.py # Author: Michael Koundouros """ Excel can save a spreadsheet to a CSV file with a few mouse clicks, but if you had to convert hundreds of Excel files to CSVs, it would take hours of clicking. Using the openpyxl module from Chapter 12, write a program that reads all the Excel files in the current...
#! python3 # auto_unsubscriber.py # Author: Michael Koundouros """ Write a program that scans through your email account, finds all the unsubscribe links in all your emails, and automatically opens them in a browser. This program will have to log in to your email provider’s IMAP server and download all of your emails. ...
import turtle t = turtle.Pen() def draw_star(size,point): for x in range(1,point): t.forward(size) t.left(95)
#CS486 Assignment #2, Q2: TSP using Simulated Annealing #Justin Franchetto #20375706 #Purpose: Using Simulated Annealing, solve TSP for a given instance import sys, string, math, datetime, itertools from TSPObjects import * from random import * #GenerateRandomTour: Generate an initial random solution #for this proble...
from random import randint TITLE = "What number is missing in the progression?" def get_round(): sequence_step = randint(1, 10) sequence_start = randint(1, 50) hidden_position = randint(1, 10) return get_prog_data(sequence_start, sequence_step, hidden_position) def get_prog_data(start, step, hidde...
""" Project for Week 4 of "Python Data Representations". Find differences in file contents. Be sure to read the project description page for further information about the expected behavior of the program. """ IDENTICAL = -1 def singleline_diff(line1, line2): """ Inputs: line1 - first single line string...
import random from datetime import datetime from unit.unit import Unit class Soldier(Unit): """ Soldiers are units that have an additional property: Property | Range | Description _______________________________________________________ experience | [0-50] | Represents the soldier experience ...
# 1329. Sort the Matrix Diagonally class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: if not mat or not mat[0]: return mat n, m = len(mat), len(mat[0]) d = collections.defaultdict(list) for i, j in itertools.product(range(n)...
def frequencySort(self, s: str) -> str: c = Counter(s) s = '' for k ,v in reversed(sorted(c.items(), key=operator.itemgetter(1))): s += k*v return s
# 721. Accounts Merge from collections import defaultdict class Solution: def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]: users = defaultdict(list) # Ω(N) for acc in accounts: users[acc[0]].append(set(acc[1:])) def join_rest(cur_se...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root: TreeNode) -> bool: if not root: return True def trav(cur, minval, maxval)...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 285. Inorder Successor in BST class Solution: def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': def right_successor(cur...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # 141. Linked List Cycle class Solution: def hasCycle(self, head: ListNode) -> bool: walker, runner = head, head while runner: walker = walker.ne...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from heapq import heappush, heappop class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists: return None if not any(l...
# 1320. Minimum Distance to Type a Word Using Two Fingers class Solution: def minimumDistance(self, word: str) -> int: N = len(word) word = [*map(lambda x: ord(x) - ord('A'), word)] def distance(n1, n2): a, b = divmod(n1, 6) a2, b2 = divmod(n2, 6) ...
class Solution: def angleClock(self, hour: int, minutes: int) -> float: minute_degree = 6 * minutes * 1.0 hour_degree = 30 * hour * 1.0 additional_hour_degree_from_minute = (minutes / 2) * 1.0 hour_degree += additional_hour_degree_from_minute ...
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode: n = TreeNode(val) if not root or val > root.val: n.left = root return n par = None cur = root while cur and cur.val > val: par = cur cur = cur.right ...
from queue import SimpleQueue class Solution: def calculate(self, s: str) -> int: ss = '' for c in s: if c in '()+-': ss += ' ' + c + ' ' else: ss += c s = ss.split() num = [] operator = [] ...
# Definition for Node. # class Node: # def __init__(self, val=0, left=None, right=None, random=None): # self.val = val # self.left = left # self.right = right # self.random = random # 1485. Clone Binary Tree With Random Pointer class Solution: def copyRandomBinaryTree(self, root:...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 979. Distribute Coins in Binary Tree class Solution: def distributeCoins(self, root: TreeNode) -> int: ans = 0 def post_order(cur): ...
# 1451. Rearrange Words in a Sentence class Solution: def arrangeWords(self, text: str) -> str: if not text: return text l = sorted([(len(w),i,w) for i, w in enumerate(text.split())]) return ' '.join([v[2] for v in l]).capitalize()
# 229. Majority Element II from collections import Counter class Solution: def majorityElement(self, nums: List[int]) -> List[int]: c = Counter() N = len(nums) for n in nums: c[n] += 1 if len(c) == 3: c -= Counter(c.keys()) ...
# 1472. Design Browser History class BrowserHistory: def __init__(self, homepage: str): self.arr = [homepage] self.cur = 0 def visit(self, url: str) -> None: self.arr = self.arr[:self.cur + 1] + [url] self.cur += 1 def back(self, steps: int) -> str: self.cur = max(...
""" author: Nishaoshan email:790016602@qq.com time:2020-6-22 env:python3.6 socket,V负责界面显示 """ from socket import * class Client: def __init__(self, host="127.0.0.1", port=9999): self.host = host self.port = port self.sock = socket() self.name = "" def r(self): while Tru...
""" 通过Pymsql操作mysql pip3 install pymysql CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8_bin NOT NULL, `password` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin AUTO_INCREMENT=1 ; ...
print("""You enter a dark room with three doors. Do you go through door #1, door #2, or door #3?""") door = input("> ") if door == "1": print("There's a giant bear here eating pie.") print("What do you do?") print("1. Take his pie.") print("2. Try to run away without the bear chasing you.") bear ...
# Hangman.py # The game of Hangman. You only get 6 guesses. Have fun! # Andrew Alonso # 3/12/2021 import re import random def getWord(): ''' Finds a random word from given textfile.''' word = (random.choice(open("wordsForHangman.txt","r").read().split())) word = word.lower() pregam...
def iso_triangle(sy,blank_spc=5,draw=1): """ Objective : to draw a isosceles triangle Input parameters : sy -> symbol to be used to draw the triangle Approach : using recursion """ print(' '*blank_spc + sy*draw) if(blank_spc>0): iso_triangle(sy,blank_...
''' PYTHON VERSION 2.7.10 AUTHOR: YAN SHI UPDATED: October 9, 2016 PROMPT: Write a function or a program which returns or prints the nth Fibonacci number. Fn = Fn-1 + Fn-2 F0 = 0 and F1 = 1 ''' def fibonacci_numbers(number): f0, f1 = 0, 1 for i in range(number): f0, f1 = f1, f0 + f1 r...
## Can build up a dict by starting with the the empty dict {} ## and storing key/value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' ## By default, iterating over a dict iterates over its keys. ## Note that the keys are in a rando...
# -*- coding: utf-8 -*- """ Heuristieken: AmstelHaege Name: houseclass.py Autors: Stephan Kok, Stijn Buiteman and Tamme Thijs. Last modified: 27-05-2016 house class """ class House(): ''' The main house class. Contains the functions that all houses need. ''' def __init__(self): s...
# Project Euler Problem 47 # by Connor Halleck-Dube import time t0 = time.clock() from math import sqrt from primesmodule import isPrimeMR ## Solution 1: Generate primes alongside test # Number of prime factors of a number (distinct ones) def pfactors(num): count = 0 n = num for p in primes: if ...
import os def selectionSort(array): size = len(array) for i in range(0,size): aux = array[i] aux2 = i aux3 = array[i] for j in range(i+1,size): if(array[j] < aux ): aux = array[j] aux2 = j aux3 = array[i] array[i] = au...
import numpy as np import scipy as sc # My objective in writing this is to figure out how it works. def find_max_crossing_subarray(A, low, mid, high): left_sum = -10e5 summ = 0 max_left = 0 for i in range(mid,low-1,-1): summ += A[i] if summ > left_sum: left_sum = sum...
#5. Write a program whose input is a list ListStr of strings, all strings being #of the same length m. Let n = len(ListStr) Write a program that works #as follows. #(a) Explores all i from 0 to m − 1. #(b) For each i, the program creates a string ColStr consisting of the i-th #symbols of the elements of ListStr. Forma...
#Read two country data files, worldpop.txt and worldarea.txt. These files can be found on #Write a file world_pop_density.txt that contains country names and population densities with the #country names aligned left and the numbers aligned right. popData =open ( 'worldpop.txt','r') areaData =open ( 'worldarea.txt','r'...
# UZXVK undergraduate modules are classified by # their level and the number of credits. # In particular, there may be modules of levels 4,5,6 and modules # having 15 or 30 credits. # The *weight* of a module is computed as follows. # -The weight of any level 4 module is 0. # -The weight of a level 5 modul...
#Please write a program that will produce a report where modules are classifed according #to the class of the received marks. In particular, the program should first print the lines #for modules whose mark is first class (>=70) then modules with a 2:1 mark (60-69) then modules #with a 2:2 mark (50-59), and then failed ...
#Write a program whose input is a table with integer elements. The program #should print “YES” if in each row the elements are all different and “NO” #otherwise. #Hint: Write a function whose argument is a list and which returns 1 if the #elements of this list are all different and 0 otherwise. Then apply this function...
def main(): mynumber = int(input('Enter a number')) check = checkNum (mynumber) print(check) myListT= [4,15,12,7,9,18,11] checkMyList = checkList(myListT) print(checkMyList) #write a function that returns 1 if a number is between 10 and 20 and 0 otherwise. def checkNum (number...
from math import exp def activate(weights, inputs): activation = weights[-1] for i in range(len(weights) - 1): activation += weights[i] * inputs[i] return activation def transfer(activation): return 1.0 / (1.0 + exp(-activation)) def forward_propagate(network, row): inputs = row fo...
"""Data utils module""" import numpy as np def split_data(X, t, w=[0.7, 0.15, 0.15]): """Takes and array of N x D (N: amount of data points, D: dimension) and returns three arrays containing Training, validation and test sets """ # normalize train/val/test weights vector w = np.array(w) ...
# generate db table name def table_name(title_data) -> str: if type(title_data) == list: return ( '"' + title_data[0].replace(" ", "-") + "_" + title_data[1].replace(" ", "-") + '"' ) else: return '"' + title_data.replace(" ", "...
def mensaje(): print("Primer acercamiento a funciones en Python") mensaje() def suma(num1, num2): resultado=num1+num2 return resultado res1 = suma(5,7) print(res1) res2 = suma(7,7) print(res2) res3=suma(9,7) print(res3) #arrays firstList=["Carlos","Jaime","Indira","Juan"] firstList.append("Marco") firstL...
country = input('Where are you from?') age = input('How old are you?') age = int(age) if country == 'Taiwan': if age >= 18: print('you can get the driver licence') else: print('you can not get the licence') elif country == 'USA': if age >= 16: print('you can get the driver licence') else: print('you can no...
#Homework 1.1: The mood checker mood = input("What mood are you in (happy,nervous,sad,excited,relaxed,other)?:") if mood == "happy": print("It is great to see you happy!") elif mood == "nervous": print("Take a deep breath 3 times!") elif mood == "sad": print("Maybe one smile will help you!") e...
#Given a signed 32-bit integer x, return x with its digits reversed. #If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ z = "" ...
# Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10. # После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран. # Например, пользователь вводит число 123, вы сообщаете ему, что число не верное, # и сообщаете об диапазоне допуст...
# Задача-1: # Напишите скрипт, создающий директории dir_1 - dir_9 в папке, # из которой запущен данный скрипт. # И второй скрипт, удаляющий эти папки. from os import mkdir, rmdir, listdir, path def create_dir(dir_name): try: mkdir(dir_name) except FileExistsError: print('Папка уже существует:...
def caught_speeding(speed, is_birthday): if not is_birthday and speed <=60: return 0 elif not is_birthday and (speed >60 and speed <=80): return 1 elif not is_birthday and speed >80: return 2 elif is_birthday and speed <=65: return 0 elif is_birthday and (speed >60 an...
def strings(str1, str2): if (len(str1) < len(str2)) and (str2.remove[1]==str1): return strings print(strings("dragon", "dragoon"))
print("hello world") first_name= "misbah" last_name= "mehmood" print("hello " + first_name + last_name) number1 = float(input("Please eneter the first number: ")) number2 = float(input("Please enter the second number: ")) answer = number1 + number2 print(number1, "+", number2, "=", answer) word1 = "Time" word2 = "to...
# Tutorial: https://pygame-zero.readthedocs.io/en/stable/introduction.html import pgzrun WIDTH = 500 HEIGHT = 400 yellow = (245,245,66) ball_x_speed = 1 ball_y_speed = 1 ball = Actor("ball") paddle = Actor("paddle") paddle.left = 0 paddle.bottom = HEIGHT def draw(): screen.fill(yellow) ball.dr...
##inciso 1 n=0 ##utilizo un if para ir creando los numeros del 1 al 9 y otra variable para irlos sumando ##se usa la misma funcion por lo que es recursiva def prob1(x,n): if x<9: x=x+1 n = n+x if n==45: print(n) return prob1(x,n) prob1(0,0)
class Bass(object): def __init__(self): self.datos = [0,0,0,0,0,0,0,0,0,0] self.Front = 0 self.Rear = 0 def pushFront(self,item): if self.Front == 5: print("Limite de 5") else: self.Front += 1 self.datos[self.Front] = item def pushRear(self,item): if self.Rear == -5: print("Limit...
def factorialR(num): if num==1: return 1 else: return num*factorialR(num-1) print ("Factorial Recursivo") num=int(input("Ingresa un numero: ")) print(factorialR(num)) print ("----------------------------------------------------------------------") def factorialI(num): factor...
import re from cs50 import get_int # gets every other number starting from the second to last or last depending on the option chosen def get_numbers(option, cardnumber): if(option == 1): start = 1 end = 2 amountofincrements = int(len(str(cardnumber)) / 2) elif(option == 2): st...
import unittest from path_finding import find_path, BOMB, TRENCH class TestMethod(unittest.TestCase): def test_path_2x2(self): field = [[TRENCH, TRENCH], [0, BOMB]] solution = find_path(field) expected_list = [(0, 0), (0, 1), (1, 1)] print(solution.path) print(expected_li...
def main(): print(igualLista(input("Escriba una lista separada por comas: ").split(","), input("Escriba una lista separada por comas: ").split(","))) def igualLista(uno, dos): if uno == dos: return True else: return False main()
#Adicionar lista lista = [] def add_lista(): new_list = (dados1,dados2) lista.append(new_list) #Exibir lista def show_lista(): for data_list in show_lista: print (data_list) opcao = 0 while opcao != 3: print (''' (1) Adicionar uma lista (2) Exibir a lista (3...
from potential_gene import is_potential_gene class Genome: def __init__(self, sequence): if len(sequence) % 3 != 0: raise Exception('DNA sequence must have a length that is multiple of 3') self._sequence = sequence def __iadd__(self, codons): if len(codons) % 3 != 0: ...
import argparse import sys import random def gambler_ruin_single_trial(amount_risked, goal, prob_winning, max_bets): bets = 0 amount = amount_risked while 0 < amount < goal and bets <= max_bets: amount += 1 if random.random() <= prob_winning else 0 bets += 1 return (amount, bets) def g...
import sys import math n = int(sys.argv[1]) prod = 1 for i in range(1, n+1): prod *= i print(prod) print(math.factorial(n))
import sys n = int(sys.argv[1]) n_ = n checksum = 0 for i in range(9,0,-1): digit = int(n // 10**(i-1)) checksum += (11-i)*digit n -= digit * 10**(i-1) print(checksum%11,n_,sep='')
import argparse def are_triangular(a,b,c): a_, b_, c_ = sorted((a,b,c)) return c_ < a_ + b_ parser = argparse.ArgumentParser(description='Say if the three lengths can make a triangle') parser.add_argument('a', type=float, help='length of a triangle') parser.add_argument('b', type=float, help='length of a tri...
import random def binary_search(array, elem, start=None, end=None): if start is None: start = 0 if end is None: end = len(array) m = (start + end) // 2 if start > end: return -1 if array[m] == elem: return m if elem < array[m]: return binary_search(array...
import datetime class Time: def __init__(self, hours, minutes, seconds): self._hours = hours self._minutes = minutes self._seconds = seconds def __iter__(self): yield from (self._hours, self._minutes, self._seconds) def __str__(self): return '%s:%s:%s' % tuple(self...
import math import sys n = int(sys.argv[1]) def sieveEratoshenes(n): "calculate the sieve of Eratoshtenes for primatlity" sieve = [True] * (n+1) sieve[1] = False maxiter = int(math.sqrt(n)) for i in range(2, maxiter+1, 1): for j in range(i*2, n+1, i): sieve[j] = False retu...
a = [[1,1,1], [2,2,2], [3,3,3]] b = [[0,0,0], [0,0,0], [0,0,0]] n = len(a) for i in range(n): for j in range(n): b[i][j] = a[i][j] print(b) c = [[1,1,1], [2,2]] d = [[0,0,0], [0,0]] for i in range(len(c)): for j in range(len(c[i])): d[i][j] = c...
import argparse from Queue import Queue def josephus(nb_people, nth_kill): who_to_kill = Queue() def kill(queue, n): person = queue.dequeue() if n == 1: who_to_kill.enqueue(person) return else: queue.enqueue(person) kill(queue, n - 1) ...
import sys import random import re from strutils import words def quick_sort_(array): n = len(array) if n <= 1: return array left = [] right = [] pivot_list = [] pivot = array[0] for elem in array: if elem < pivot: left += [elem] elif elem > pivot: ...
import sys n = int(sys.argv[1]) # for i in range(1,n+1): # for j in range(1,n+1): # if(j%i==0 or i%j==0): # print('*',end='') # else: # print(' ',end='') # print(i) def gcd(a, b): "Calculates the greatest common divisor of a number" a, b = abs(a), abs(b) a...
import sys import random import re from math import radians, sin, cos, acos, degrees class Location: def __init__(self, lat, lon): self._lat = radians(lat) self._lon = radians(lon) def distance(self, other): x1, y1 = self._lat, self._lon x2, y2 = other._lat, other._lon ...
import argparse from math import cos, sin, asin, radians,sqrt, degrees def haversine(d1,a1, d2,a2): def haver(angle): return sin(angle/2)**2 d = d2 - d1 a = a2 - a1 h = haver(d) + cos(d1)*cos(d2)*haver(a) return 2*asin(sqrt(h)) parser = argparse.ArgumentParser(description='calculate the...
import argparse from permutations import combinations_of_length def flip(bit): return {'0':'1','1':'0'}[bit] def flip_bits(string, lst): new_string = "" for i, bit in enumerate(string): if i in lst: new_string += flip(string[i]) else: new_string += string[i] ret...
import matplotlib.image as mpimg import numpy as np import argparse def to_255(color01): "Converts a color defined in 0-1 to 0-255" return tuple(int(x*255) for x in color01) def to_stdout(filename): im = mpimg.imread(filename) height,width = im.shape[0:2] print(width, height) for row in im: ...
class Time: def __init__(self, hours, minutes, seconds): self._seconds_elapsed = hours * 3600 + minutes * \ 60 + seconds # seconds elapsed since midnight @property def hour(self): return self._seconds_elapsed // 3600 @property def minute(self): h = self.hour ...
import math import sys def taylor_series(x, init, step): total = init prev = init n=1 while True: # print(n, prev) curr = step(prev, x, n) if total == total + curr: return total prev = curr total += curr n+=1 def taylor_series_coeffs(init, n...
def isPowerOfFive(n): return int(n**(1/5))**5==n max_range =250 def powers(): for a in range(1,max_range+1): for b in range(a,max_range+1): for c in range(b,max_range+1): for d in range(c,max_range+1): # print(a,b,c,d) if isPowe...
import numpy as np def square(x): return x * x def integrate(f, a, b, n=1000): dx = (b - a) / n xs = np.linspace(a + dx / 2, b + dx / 2, n + 1)[0:n] return sum(dx * f(x) for x in xs) def integrate_(f, a, b, n=1000): dx = 1.0 * (b - a) / n series = (dx * f(a + (i + 0.5) * dx) for i in range...
import os # 【输入str,str】:生成的文件名,需要写入文档的文本数据 # 【功能】:创建一个文档 def text_create(savepath, filename, msg, filesuffix='.txt'): isExisted = os.path.exists(savepath) if not isExisted: print(savepath) print('上面列出的目录或文件不存在,请设置正确路径!') return else: print('目录[' + savepath + ']存在,正在创建文件[' +...
def replaceStr(value, t01, t02) : keywords = list(value) for idx, keyword in enumerate(keywords) : if keyword == t01 : keywords[idx] = t02 result = ''.join(keywords) return result if __name__ == '__main__' : replaceStr('te@xt', '@', '')
# 二叉树的叶子结点 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class BinaryTree: def __init__(self, root=None): self.root = root def is_empty(self): """ 判断二叉树是否为空 :return: """ if self.root is None: ...
# Given an array of integers that is already sorted in ascending order, # find two numbers such that they add up to a specific target number. # # The function twoSum should return indices of the two numbers such that they add up to the target, # where index1 must be less than index2. Please note that your returned ans...
# 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。 # n<=39 class Solution: def Fibonacci(self, n): """ 斐波那契数列数列 :param n: :return: """ num0 = 0 num1 = 1 num_n = 0 if n == 0: return 0 if n == 1: return 1 for i in...
# Given a binary tree, check whether it is a mirror of itself # (ie, symmetric around its center). # # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: # 判断一颗树是否是镜像的, class Solution: def isSymmetric(self, root): """ 判断一颗树是否是镜像树 :param root: TreeNode :return: bool ...