text
stringlengths
37
1.41M
class TreeNode(object): def __init__(self, data = None, no = None, yes = None): """Creates a tree with specified dataand reference to the left and right children""" self.item = data self.left = no self.right = yes def addLeft(self, data = None, no = None, yes = None): self.left = TreeNode(data, no, yes) ...
""" Play tic tac toe. Players are represented by values True (o) and False (x). Spaces are represented by None. """ from copy import deepcopy O = True X = False SPACE = None CHAR_TO_PLAYER = {'o': O, 'x': X, ' ': SPACE} PLAYER_TO_CHAR = {O: 'o', X: 'x', SPACE: " "} def did_player_win(board, player)...
# https://github.com/albertauyeung/matrix-factorization-in-python import numpy as np class MF(): def __init__(self, R, K, alpha, beta, iterations): """ Perform matrix factorization to predict empty entries in a matrix. Arguments - R (ndarray) : user-item rat...
"""19. Write a Python program to create Fibonacci series upto n using Lambda.""" num=int(input("enter a number: ")) lis=[] for i in range(num+1): lis.append(i) get_Fibonacci=lambda num:num if num<=1 else get_Fibonacci(num-1)+get_Fibonacci(num-2) print(list(map(get_Fibonacci,lis)))
"""8. Write a Python program to remove the nth index character from a nonempty string.""" inp=input("enter a non empty string: ") index = int(input("enter the index of the character you want to remove: ")) print(inp[0:index] + inp[index+1:])
"""16. Write a Python program to sum all the items in a list. """ no_of_items=int(input("enter the no of items you want in a list: ")) inp_list=[] for i in range(no_of_items): inp=int(input("enter the list items of integers : ")) inp_list.append(inp) sum=0 for i in inp_list: sum=sum+i print(sum)
"""4. Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string. Sample String : 'abc', 'xyz' Expected Result : 'xyc abz' """ inp= input("enter your string: ") new_inp=inp.split(" ") str1=new_inp[0] str2=new_inp[1] new_str1=str1.replace(s...
"""11. Write a Python program to count the occurrences of each word in a given sentence.""" inp=input("enter your sentence: ") inp_list=inp.split() inp_dict={} for i in inp_list: if i in inp_dict: inp_dict[i]+=1 else: inp_dict[i]=1 print(inp_dict)
"""17. Write a Python program to multiplies all the items in a list.""" no_of_items=int(input("enter the no of items you want in a list: ")) inp_list=[] for i in range(no_of_items): inp=int(input("enter the list items of integers : ")) inp_list.append(inp) mul=1 for i in inp_list: mul=mul*i print(mul)
"""36. Write a Python program to sum all the items in a dictionary. """ sample_dict={1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225} sum=0 for i in sample_dict: sum=sum+sample_dict[i] print(sum)
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 16:09:37 2018 @author: xuyijun """ from datetime import timedelta from datetime import datetime # adate = datetime.strptime('12/12/2018','%m/%d/%Y') # print(adate.strftime('%B %d, %Y)) def interval_plan_period(): return 7 def str_date_to_date_time(str_date: 'M...
# Problem 2 # 10/10 points (graded) # Assume s is a string of lower case characters. # Write a program that prints the number of times the string 'bob' occurs in s. # For example, if s = 'azcbobobegghakl', then your program should print # Number of times bob occurs is: 2 count=0 for i in range(len(s)): if s[i]=...
# Murovanyi Andrey, KNIT16-A # По дате d, m, y определить дату следующего дня import sys days = range(1, 32) mounths = range(1, 13) years = range(1901, 2016) flag = True while flag: try: d, m, y = int(input('Day: ')), int(input('Mounth: ')), int(input('Year: ')) except ValueError: ...
# To run this, you can install BeautifulSoup # https://pypi.python.org/pypi/beautifulsoup4 # Or download the file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file from urllib.request import urlopen from bs4 import BeautifulSoup import ssl ctx = ssl.create_default_context() ctx.c...
import re def replaceLetters(ptext, ctext): j = 0 ctext = list(ctext) for i in range(len(ctext)): char = ctext[i] if re.match('[A-Z]', char): ctext[i] = ptext[j] j += 1 return ''.join(ctext)
from insert_in_DB import * class Person: def take_input(self): print("Enter your contact's information") self.id=input("enter id :") self.first_name = input("First name = ") self.last_name = input("Lastst name = ") self.age = input("Age = ") self.phone_number = in...
import argparse import socket import sys import csv """ Simple example pokerbot, written in python. This is an example of a bare bones pokerbot. It only sets up the socket necessary to connect with the engine and then always returns the same action. It is meant as an example of how a pokerbot should communicate with ...
#!/usr/bin/env python3 # usage: python3 ./baseN.py --help import math import argparse def encode(text, encodeMap, encodingBit): binary = ''.join([format(x, '08b') for x in text.encode('utf8')]) binary += (encodingBit - len(binary) % encodingBit) * '0' splittedArray = [binary[x:x + encodingBit] for x in r...
#Program to deposit and withdrawal class Operator: def add(self,a,b): return a+b def sub(self,a,b): return a-b def mul(self,a,b): return a*b def div(self,a,b): if b==0: return 0 else: return a/b class Account(Operator): def __init__(se...
num=int(input("Enter number : ")) count=0 #number of digits while num>0: count+=1 num//=10 print("The number of digits in the number is :",count)
first_number=int(input("Enter the first number: ")) second_number=int(input("Enter the second number: ")) total=first_number+second_number print("Sum of two number is :",total)
n=int(input("Enter a number : ")) total=0 while n>0: digit=n%10 total+=digit n//=10 print("The sum of the digits is :",total)
score=[73,95,80,57,99] #compute the sum of scores def func_sum(s): sum=0 for i in s: sum+=i return sum total=func_sum(score) print("Total score :",total) print("Average score :",total/len(score))
low=int(input("Enter the lower limit for the range : ")) up=int(input("Enter the upper limit for the range : ")) #if the number is odd, print it. for i in range(low,up+1): if i%2==1: print(i)
#input grades s1=int(input("Enter the score of subject 1: ")) s2=int(input("Enter the score of subject 2: ")) s3=int(input("Enter the score of subject 3: ")) s4=int(input("Enter the score of subject 4: ")) s5=int(input("Enter the score of subject 5: ")) #Calculate average avg=(s1+s2+s3+s4+s5)/5 print("Average =",avg)...
a={i for i in range(1,101) if i%3==0} b={i for i in range(1,101) if i%5==0} print(a) print(b) c=a&b print(c) print(sorted(c))
myAge=input("Enter your age:") myName=input("Enter your name:") print("** Printing type of input value **") print("type of myAge:",type(myAge)) print("type of myName:",type(myName))
a=int(input("Please Enter the First Angle of a Triangle: ")) #First angle b=int(input("Please Enter the Second Angle of a Triangle: ")) #Second angle c=int(input("Please Enter the Third Angle of a Triangle: ")) #Third angle sum=a+b+c if sum==180: print("This is a Valid Triangle") else: print("This is a Invali...
''' lets say we have a list of folder and file names that we want to join to represent a path ''' print('\\'.join(['folder1', 'folder2', 'file.jpg'])) ''' that would print out: folder1\folder2\file.jpg NOTICE that Windows uses backslashes and that the backslashes are doubled because each backslash needs to be escape...
''' You can save variables in your Python programs to binary shelf files using the shelve module. This way, your program can restore data to variables from the hard drive. The shelve module will let you add Save and Open features to your program. For example, if you ran a program and entered some configuration settings...
''' saving error messages to a file using the traceback module ''' import traceback try: raise Exception("A custom error message") except: errorFile = open('debugging\\error_log.txt', 'a') # open in append mode so we can keep all error records errorFile.write( traceback.format_exc()) # write the traceback...
''' Author: Josh Vocal Description: Convert a decimal number to binary and sum the bianry number. ''' #Main #Converts the input number into a binary number and slices it #Joins "+" into the binary number. Ex "1+0+1+1" #Uses the evaluation function to add the numbers in the string. print(eval("+".join(bin(input("Please...
''' Author: Josh Vocal Descripton: Program will talke 3 arguments. The first will be a day, followed by month, then year. The program will compute the day of the week that dat will fall on. Version: 1.0 Changes: ''' #Imports import calendar #Functions def day(): print("Pick a day from 1-31 depending on the month:...
num1= int(input("enter first num")) num2= int(input("enter second num")) rem = num1 % 2 if(rem==0): print(num1,"even integer") else: print(num1,"odd integer")
from automata import * from scanner import * #keywords keywords =['while', 'do'] #character digit="0123456789" digit= character(digit) tab=chr(9) tab= character(tab) eol=chr(10) eol= character(eol) blanco=eol+chr(13)+tab blanco= character(blanco) #tokens number=digit+" (("+digit+")*)" decnumber=digit+" (("+digit+"...
from utils import timeIt ''' Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal Pn=((n*(3*n-1))/2) 1, 5, 12, 22, 35, ... Hexagonal Hn=(n*(2*n-1)) 1, 6, 15,...
from utils import timeIt ''' A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' @timeIt def problem9(): for a in range(1,1001): ...
import networkx as nx from itertools import combinations class ACL(object): """Represent a single ACL""" def __init__ (self, grant, portmin, portmax = None): if not portmax: portmax = portmin self.grant = grant self.portmin = portmin self.portmax = portmax def allowsPort (self, port): "...
## El método de ordenamiento que se utiliza es el Bubblesort, ## debido a que se comparan los dos primeros elementos y si no estan ## en el orden que les corresponde los intercambia. Se repite el proceso ## con los dos siguientes numeros hasta llegar al final. def bubbleSortMenor(arr): for i in range(0, len(...
import time start = time.time() def negativos(lista): negativo = [] for i in lista: if i < 0: negativo.append(i) return negativo lista = [0,3,6,-1,6,-3,9,-15,-10] print(negativos(lista)) end = time.time() print( end - start ) ## El tiempo de ejecución de algortimo es ...
import random from code.hand import Hand from code.tile import Tile class MahjongTable(object): """Coordinates games of mahjong.""" def __init__(self, mahjong_player, unique_tiles): self.hand_len = 14 self.mahjong_player = mahjong_player self.tileset = self.generate_tileset(unique_til...
data = "" with open("sample1.txt", "rb") as file: data = file.read() with open("sample2.txt") as file1: with open("sample1.txt") as file2: file2.write(file1.read()) with open("sample2.txt") as file: file.write(data) print("File Replaced") del data
#Leer tres números enteros diferentes entre sí y determinar el número mayor de los tres. """Ejercicio 8""" class Mayor_3: def __init__(self): pass def NumMayor(self): print("") n1 = int(input("Ingrese primer número entero: ")) n2 = int(input("Ingrese segudo número ent...
from db import db class StoreModel(db.Model): __tablename__ = 'store' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) # ? When we use lazy = 'dynamic' it optimises the code otherwise pyhton create an object with the list of items for every store created. By doing so : sel...
target = int(input('Enter an integer: ')) answer = 0 while answer**2 < target: answer += 1 if answer**2 == target: print(f'Root square of {target} is {answer}') else: print(f'{target} does not have root square')
''' Created on Aug 23, 2020 Calculate Largest Palindrome of the product of two three digit numbers @author: Pranaw Bajracharya ''' """ Since the question is find the largest palindrome of the product of two three digit numbers, I suppose the simplest/most brute force method would be to find the minimum and maximum val...
import re print(re.search(r"[pP]ython","Python")) print(re.search(r"[a-z]way","the end of the highway")) print(re.search(r"[a-z]way","What a way to go")) print(re.search(r".way","What a way to go")) # match any character that aren;t in a group we use "^" this # Any character that is not a letter print(re.search(r"[^a...
a=[] a.append(5) print(a) a.append("Hello") print(a) print(len(a)) for x in a: print(x) a.remove(5) print(a) x=a.pop(0) print(x) print(a) print(int(3.79)+int(2.1))
with open("demo.txt") as file: for line in file: print(line.upper()) with open("demo.txt") as file: for line in file: print(line.strip().upper())
file = open("demo.txt") print(file.readline()) print(file.readline()) print(file.read()) file.close() #-------------------------------------- file = open("demo.txt") print(file.readline()) print(file.readline()) file.close() file = open("demo.txt") print(file.read()) file.close() with open("demo.txt") as file: prin...
import csv f = open("demo.txt") #open file csv_f = csv.reader(f) for row in csv_f: name,product,country=row print("Name: {}, Product: {}, Country: {}".format(name,product,country)) f.close()
class Soldier: def __init__(self): self._weapons = list() def add_weapon(self, weapon): self._weapons.append(weapon) def fight(self): print(f"Fighting with {', '.join([str(weapon) for weapon in self._weapons])}") class Sword: def __init__(self, color): self._color = c...
from oop.basic_dog_class import Dog class Pomeranian(Dog): def __init__(self, name): super().__init__(name) print("Pomeranian was created.", end="\n\n") def bark(self): #super().bark() print("I'm costly.") if __name__ == '__main__': my_dog = Pomeranian("Bolt") my_dog...
# Author: Chirag Maniar # copyright @2019 by Chirag Maniar # Execl sheet discount calculation and chart building # Importing excel required packages import openpyxl as excel def process_excel_sheet(filename): # Selecting workbook i.e. Excel sheet workbook = excel.load_workbook(filename) # Selecting the ...
numbers = range(1, 101) numbers = list(numbers) even = [x for x in numbers if x % 2 == 0] print sum(even)
def get_guess(): acceptable_input = False while not acceptable_input: try: raw_guess_numbers = [int(x) for x in input("Enter your guess: ")] if len(raw_guess_numbers) != 4: print "Your guess must be 4 numbers long!" continue ...
import random # These lists will be used as tests in your check_values function computer_list = [1,2,3,5]; user_list = [2,7,3,4]; def check_values(user, computer): colors = [] shuffled = user[:] random.shuffle(shuffled) for number in shuffled: if number in computer: input_num...
from types import StringType from collections import Iterable class MaxHeap(object): def __init__(self): self.array = [] self.cur_size = 0 def heapify(self, item_list): self.array = item_list self.cur_size = len(item_list) for i in range(self.cur_size-1, -1, -1): ...
def InsertionSort(arr,n): for i in range(1,n): temp = arr[i] j = i - 1 while j>=0 and arr[j] > temp: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = temp arr = [1,5,3,7,2,6,0] n = 7 InsertionSort(arr,n) print(arr)
a = {"apple","abc",23} a.remove('apple') a.discard(23) print(a) ## a.pop() - remove on , we dont know # functions of sets a = {1,2,3,4} b = {3,4,5,6} print(a.intersection(b)) print(a.union(b)) print(a.difference(b)) print(a.symmetric_difference(b)) # union minus intersection print(a.intersection_update(b)) a.differenc...
def powerNumber(x,n): if n == 0: return 1 smallAns = powerNumber(x,n-1) return x * smallAns x,n = input().split(' ') output = powerNumber(int(x),int(n)) print(output)
n=5 if n%2==0: for i in range((n//2)): for j in range(n): print(2*n*i+j+1,end=" ") print() for i in range((n//2),0,-1): for j in range(n): print(2*n*i+j+1-n,end=" ") print() else: for i in range((n//2)+1): for j in range(n): print(2...
def merge(arr1, arr2 , arr) : #Your code goes here index1 = 0 index2 = 0 index3 = 0 n = len(arr1) m = len(arr2) while index1 < n and index2 < m: if(arr1[index1] >= arr2[index2]): arr[index3] = arr2[index2] index2 += 1 index3 += 1 else: ...
import random #------Checking if number is even number = int(input("Enter a number: ")) if (number % 2) == 0: print("Even") else: print("Odd") #------Sum of digits num = random.randint(100, 1000) num_sum = 0 n = 0 print("Number is {}".format(num)) while num > 0: n = num%10 ...
from modules.检测录音频率 import 检测录音频率 from modules.播放随机波 import 播放随机波 from utils.波处理 import 读取wav文件 , 时域转频域 , 求主导频率 import matplotlib.pyplot as plt from 练习 import 练习 from 听音识名 import 听音识名 from 看名唱音 import 看名唱音 from 跟唱 import 跟唱 from 自由练习_唱 import 自由练习_唱 from 自由练习_唱_连续 import 自由练习_唱_连续 import os , sys while True: os.s...
def sumOfEvenFibs(sumLimit): """ Assumes sumLimit is non-negative. Returns the sum of even terms of in the Fibonacci series. >>> sumOfEvenFibs(1000) 798 """ fib = dict() fib[0] = 0 fib[1] = 1 i = 2 while (fib[i-1] + fib[i-2]) <= sumLimit: fib[i] = fib[i...
# Leetcode Problem #1130 - Minimum Cost Tree From Leaf Values # https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/submissions/ class Solution: def __init__(self): self.mem = {} def mctFromLeafValues(self, arr: List[int]) -> int: if not arr: return 0 return ...
# Leetcode Problem #112 - Path Sum # https://leetcode.com/problems/path-sum/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: ...
#! /usr/bin/env python import sys,math def hypothenuse(side1, side2): """ The algorithm the man behind the door uses is the same used to compute the hypothenuse for a triangle with catheti x and y :) """ hyp = math.sqrt(side1 * side1 + side2 * side2) return round(hyp, 2) line = sys.stdin.readline() n...
from tkinter import * from tkinter import ttk root = Tk() root.title("Function scrollbox") # Initialize our country "databases": # - the list of country codes (a subset anyway) # - a parallel list of country names, in the same order as the country codes # - a hash table mapping country code to population< ...
# Activity 8.2.5: Task 5 #File: ACT_8_2_Task5_Team256.py #Date: 18 Oct 2018 #By: Alex Tillman # Justin Kohler # Ryan Steffan # David McCoy # #Section: 021 #Team 256 # #Electronic Signature # Alex Tillman # Justin Kohler # Ryan Steffan # David McCoy #This electronic signature above indiccate...
# HW 8.1 Python Individual #File: HW8_1_Task1_functions_Tillmaaa.py #Date: 28 Oct 2018 #By: Alex Tillman # Justin Kohler # Ryan Steffen # David McCoy #Section: 021 #Team 256 # #Electronic Signature # Alex Tillman # # # #This electronic signature above indiccates the script #submitted for eval...
from dinosaur import Dinosaur class Herd: def __init__(self): self.dinosaurs = [] def create_herd(self): dinosaur_one = Dinosaur("Ken", 100) dinosaur_two = Dinosaur("Dennis", 150) dinosaur_three = Dinosaur("Oscar", 200) self.dinosaurs.append(dinosaur_one) self...
import random def tirar_dados(): dado1 = random.randint(1,6) dado2 = random.randint(1,6) suma1 = dado1 + dado2 return dado1, dado2, suma1 def juego(): numberl = [4,5,6,8,9,10] dados =tirar_dados() d1 = dados[0] d2 = dados[1] s = dados[2] gano = 0 if s == 7 or s == 11:...
from tkinter import * from tkinter import messagebox as MessageBox from tkinter import filedialog as FileDialog from tkinter import colorchooser as ColorChooser from io import open fileroute="" def aboutus(): MessageBox.showinfo('About Us', 'This is a GUI for test purposes, just have fun') def help(): Me...
# Ask how many items user wants to sell. sold = int(input("How many items are you selling? ")) print("You are selling {} items".format(sold))
class Node(): def __init__(self,data): self.data=data self.next=None class circularLinkedList(): def __init__(self): self.last = None def addToEmpty(self,data): if (self.last!=None): return temp = Node(data) self.last = temp self.last.nex...
# each item in the manifest is an item and its weight manifest = [["bananas", 15], ["mattresses", 34], ["dog kennels",42], ["machine that goes ping!", 120], ["tea chests", 10], ["cheeses", 0]] #Sorted cargo hold from heaviest to lightest #manifest.sort(key=lambda weight: weight[1], reverse=True) cargo_weight = 0 cargo...
def tag_count(xml_count): """ Function that takes as its argument a list of strings. It return a count of how many of those strings are XML tags. """ count = 0 for x in xml_count: if x[0] == '<' and x[-1] == '>': count = count + 1 return count # Test for the tag_count funct...
def html_list(input): """ This Function takes one argument, a list of strings, and returns a single string which is an HTML list. """ output = ["<ul>"] for values in input: #This works too but the one I used is cleaner. #output.append("<li>" + values + "</li>") output.append(...
""" _*_ coding:utf-8 _*_ @Auther:JeffWb @data:2018.11.22 @Version:3.6 """ """>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Chain to stack<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<""" class StackUnderFlow(ValueError): pass class Node: def __init__(self,elem,next): self.elem = elem self._next = next class CStack: def __ini...
""" _*_ coding:utf-8 _*_ @Auther:JeffWb @data:2018.11.22 @Version:3.6 """ """>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Sequence to queue<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<""" class queueError(ValueError): pass class SQueue: def __init__(self): self.elem = [] #empty? def is_empty(self): return self.elem == [] ...
def print_rangoli(size): entry=1 letters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',\ 'u','v','w','x','y','z'] constant=size+(size-1)+2*(size-1) for i in range (0,((2*size))): str1='' str2='' if i < size: for j in rang...
from _generate_site.elements import * page = Page("jit-project/progress-timeline/journal-4.html", nav_loc=["JIT Project", "Progress Timeline", "[8] Journal 4"]) page += Title("Journal 4: Weeks 14-15") page += Paragraph("February 27, 2021 - March 20, 2021") page += Heading('Goals for this Journal:') page...
import sqlite3 # 将游标获取的元组根据数据库列表转为字典表 def make_dicts(cursor, row): return dict((cursor.description[i][0], value) for i, value in enumerate(row)) class SqlHelper(object): def __init__(self): self.path = r"e:\test\test.db" # 打开数据库连接 def get_db(self): db = sqlite3.connect(self.path) ...
import turtle,time yy=turtle.Turtle() yy.color('white') yy.shape('turtle') xx=turtle.Screen() xx.bgcolor('black') num_sides=int(input('要畫幾邊形(3-10):')) side_length=70 angle=360.0/num_sides for i in range(num_sides): yy.forward(side_length) yy.right(angle) time.sleep(1) turtle.d...
import pygame from pygame.sprite import Sprite class Ammo(Sprite): """Ammunition used by spaceship""" def __init__(self, board_settings, screen, ship): """constructor for ammo super class""" super(Ammo,self).__init__() self.screen = screen self.rect = pygame.Rect(0,0,board_se...
__author__ = "Adam Najman" """ Adam Najman CSCI HW 5 Dijkstra's Algorithm using an array! Running time is O(V^2 + E) Please see input.txt for graphs The second to last graph has 12 nodes and 144 edges. This takes twice as long in the array implementation compared to the binary heap version. """ import re from c...
__author__ = "Adam Najman" __filename__ = "lcs.py" __homework_number__ = 3 from time import time from collections import defaultdict diagonal = -1 left = 0 up = 1 def topdown(s1, s2): return None def bottomup(s1, s2): print "comparing " , s1 , " and " , s2 for i in xrange(1, len(s1)): for j in xrange(1, ...
while True: print("**************************") print("1. Retrieve") print("2. Add") print("3. Update") print("4. Delete") print("5. Quit") print("**************************") input_num = int(input(">")) if input_num == 1: print("Retrieve") elif input_num == ...
class Animal(object): def drink(self): print("这是一个喝水的方法") pass def run(self): print("这是一个跑步的方法") pass def eat(self): print("这是一个吃饭的方法") pass def bark(self): print("这是一个喊叫的方法") pass class Tiger(Animal): def __init__(self, name): ...
def checkpass(p): check = 0; lower = [a.islower() for a in p] upper = [a.isupper() for a in p] digit = [a.isdigit() for a in p] for i in lower: if (i == True): check = check + 1; break for i in upper: if (i == True): check = check + 1; ...
import numpy as np # Write a function that takes as input a list of numbers, and returns # the list of values given by the softmax function. def softmax(L): prob = [] summ = 0 for i in range(len(L)): summ += np.exp(L[i]) for i in range(len(L)): prob.append(np.exp(L[i])/summ) ...
import random, re class MineSweeper: """ Beginner: 9 x 9, 10 mines Intermediate: 16 x 16, 40 mines Advanced: 30 x 16, 99 mines Customized: 9 x 9 to 30 x 24, 10 to 668 mines with max of (X-1) x (Y-1) for X x Y """ def __init__(self, nx, ny): self.__board = Board(nx, ny) ...
import re from functools import reduce import operator def swap_digits_all(s, d1, d2): d1, d2 = map(str, (d1, d2)) c_tmp = 'x' return s.replace(d1, c_tmp).replace(d2, d1).replace(c_tmp ,d2) def is_upsidedown(n): s = str(n) if re.search(r'[23457]', s): return False s_rev = ''.join(rever...
class SubseqenceFinder: def __init__(self, str): self.__str = str def is_subsequence(self, s): pos_start = 0 for c in s: pos = self.__str.find(c, pos_start) if pos == -1: return False pos_start = pos + 1 return True def l...
""" 2 3 ..# ... "" import sys, random n_blocks = int(sys.argv[1]) if len(sys.argv) >= 2 else 9 nx, ny = (9, 9) coords_blocks = [] while len(coords_blocks) < n_blocks: x = random.randrange(nx) y = random.randrange(ny) if (x, y) in ((0, 0), (nx - 1, ny - 1)): continue elif (x, y) not in coords_b...
import numpy as np from scipy import stats import matplotlib.pyplot MONTE_CARLO_SIMULATION_NUMBER = 1000 NUMBER_OF_EMPLOYEES = 1000 RETIREMENT_AGE = 65 MAX_TYPICAL_LIFESPAN = 100 # The beta distribution is defined for 0 to 1, so we need to scale to 0 to 1 NUMBER_OF_YEARS = 10000 EMPLOYEE_AGE = 45 P_VALUE_FOR_S...
#From the Computing for Biologits: Chapter 1 Chapter Problem - gcContent.pys from twoSalDNAs import * # inIsland and outsideIsland #>>> gcContent(inIsland) #0.4275 #>>> gcContent(outsideIsland) #0.5427 # This is a program used to calculate the # GC Content, now for all DNA strings of any lengh. def gcConten...
#This is ifelse.py which is the 2nd exerise of chapter 1 #from Computing For Biologists. def absolute(n) : ''' This function absolute(x) is to take input and return the absolute value as output. ''' #>>> absolute(-3) #3 #>>> absolute(5000000) #5000000 if n < 0: return (-n) ...