text
stringlengths
37
1.41M
# 建立記帳程式專案(二維清單) # while true適合使用在使用者不知道要輸人幾次時使用,可以重複的執行的情況 # refactor 重構 import os # operating system作業系統模組 # 讀取檔案 def read_file(filename): products = [] # 建立清單,存放使用者輸入的商品名,要放在最外圈 with open(filename, 'r', encoding='utf-8') as f: for line in f: if '商品,價格' in line: continue ...
# -*- coding: utf-8 -*- ''' @author: uidq1501 ''' import threading def sum(a): print(a+6) threads = [] for i in range(3): # print i t = threading.Thread(target=sum, args=(i,)) threads.append(t) for j in threads: j.start()
def maxProfit(self, prices: List[int]) -> int: ''' prices = [7, 1, 5, 3 ,6 ,4] check for edge cases: empty array, negaive numbers, specil characters, or something like [1, 1, 1, 1, 1, 1, 1], what to return for these cases? use for loop to iterate through the prices array how do we know which is the ...
import sys def open_file(file_name,mode): """Opens file in the given mode""" try: file = open(file_name, mode) return file except IOError as e: print("Unable to open the file", file_name, "Ending program.\n", e) input("\n\nPress the enter key to exit.") sys.exit() ...
import random import sys print("Welcome the computer is going to guess your number") minrange =int(input("what number do you want to start with?")) mxrange = int(input("what do number do you want to go to?")) num = int(input("now pick a number between your previous numbers")) randnum = random.randint(minrange,mxrange...
# # bool = True # num = 200 # # # # list = [] # list.append(7) # list.append(93) # list.append(3) # list.append(45) # print (list) # print(list[2]) # if num < 100: # print('hi') # elif num == 120: # num = 10/2 # print('hello again') # else: # print('goodbye') # # print(num) # # while bool == True...
#!/usr/bin/env python # encoding: utf-8 import operator class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ for i, letter in enumerate(t): if i < len(s) and letter == s[i]: continue ...
""" Python does not generally support the concept of private variable like in Java i.e. they will still be accessible from the object. They are not hidden. But in general practice, if a attribute or a method is made private, then it means they should be accessed outside the class i.e. the developer nee...
#!/usr/bin/python def print_stars(): num_of_lines = int(input("Please enter the number of lines: ")) for j in range(num_of_lines, 0, -1): print("* "*j, end='\n') print("Finished printing") print_stars()
class Decorate: def __init__(self, function): self.f = function def __call__(self, *args, **kwargs): print("Executing the decorated function") self.f(*args, **kwargs) @Decorate def decorated_greet(name): print(f"Hello, {name}") def undecorated_greet(name): print(f"Hello, ...
#!/usr/bin/env python3 """Reads mathematical expressions from stdin and evaluates them.""" from lark import Lark, Transformer class CalcTransformer(Transformer): # pylint: disable=too-few-public-methods """Transformer for the parser.""" @staticmethod def _num(args): return float(args[0]) @s...
""" solve_netlist.py Evan Greene and Anthony Lowery 2017/03/18 """ import numpy as np from parse_netlist import parse_netlist from gaussian_elimination import gaussian_elimination def solve_netlist(V, I, R, N): """ transforms the output of parse_netlist into a solved linear system using modified nodal analysi...
# -*- coding: utf-8 -*- """ Created on Sun Jun 27 17:09:53 2021 @author: Jose Alcivar Garcia """ sueldo= float(input("ingresa el sueldo: ")) a= float(input("ingresa la venta 1 ")) b= float(input("ingresa la venta 2 ")) c= float(input("ingresa la venta 3 ")) comision= (a+b+c)*.10 print("el sueldo del tr...
# Samuel Ng 112330868 # CSE 352 Assignment 1 from TileProblem import TileProblem from Heuristics import Heuristics # Python standard library import sys from queue import PriorityQueue import math import tracemalloc import time # takes in an input file and returns a matrix of ints representing the state ...
def read_numbers(): numbers = [ int(i) for i in input().split(' ') ] return numbers def num_sum(x): sum = 0 while x > 0: sum += x % 10 x //= 10 return sum def good_time(hh, mm): hh_sum = num_sum(hh) mm_sum = num_sum(mm) return hh_sum != mm_sum def solution(hour, min...
''' Write a program to evaluate poker hands and determine the winner Read about poker hands here. https://en.wikipedia.org/wiki/List_of_poker_hands ''' def sort(hand): ''' appending face values into a list ''' newlist = [] for character in hand: if character[0] == 'A': ...
''' Document Distance - A detailed description is given in the PDF ''' import re import math FILE_NAME = "stopwords.txt" def similarity(dict1, dict2): ''' Compute the document distance as given in the PDF ''' lis = dict1.lower().split() lis1 = [] for word in lis: lis1.append(re.s...
# Write a python program to find the square root of the given number # using approximation method # testcase 1 ''' # input: 25 # output: 4.999999999999998 # testcase 2 # input: 49 # output: 6.999999999999991 ''' def main(): ''' to find out square root of a number using approximation ''' s_i = int(...
''' #Exercise : Function and Objects Exercise-3 #Implement a function that converts the given testList = [1, -4, 8, -9] into [1, 16, 64, 81] ''' def applyto_each(l_i, f_i): ''' input: int or float returns int or float ''' for i_i in range(len(l_i)): l_i[i_i] = square(l_i[i_i]) return l_i...
# Work with Pandas and data munging import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/fantasydatapros/data/master/fantasypros/fp_projections.csv') #iloc shows us which [columns, rows] to look at. In this case, all columns, and all but the first row df = df.iloc[:, 1:] #defining columns we car...
# -*- coding: utf-8 -*- import numpy def printGraph(graph): k=0 for k in range(0,len(graph)): print graph[k] t,b,f,c = raw_input("Enter t b f c: ").strip().split(' ') #Input the tree, backward, forward and cross edges t,b,f,c = [int(t),int(b),int(f),int(c)] #Convert the strings to ints. n = ...
from random import uniform from math import pi, sqrt #Using 2 random numbers from the range of 0-1 calculate/estimate pi def pi_estimate(n): x = uniform(0,1) y = uniform(0,1) distance = x**2 + y**2 total_square = 0 total_circle = 0 #Formula of square area = 4r #Formula of circle = PI r^2 ...
#MID-SESSION TAKE HOME QUIZ - DICTIONARY & FILE I/0 EXERCISES #Miranda Remmer #2.17 import string MIDSESSION_file = open ("midreviewfile2.txt") words = MIDSESSION_file.read() MIDSESSION_file.close() punctuation = string.punctuation digits = string.digits def clean_text(file): return [word.strip(punctuation) fo...
#!/usr/bin/env python # digits_overlay.py # # Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> # Licensed under MIT # Version 1.0.1 import os import cv2 from app import recognize_characters # function to filter out contours on an image def filter_contours(contour): # get rectangle bounding contour ...
# collections are of 3 types # 1. List # 2. Set - same as list, but no dupplicates # 3. Dictionary - contains list with key, value pair str1 = " this is first string " print(str1) str2 = "this is second string" print(len(str1)) # indexing print(str1[10]) # repetition print(str1*3) # slicing print(str2[0:10]) pr...
#import this """This is the data definition class for regex_list. regex_list takes a list of strings and makes it searchable. Searchable meaning you can find which elements in the list have a pattern. you could add the '+' to the add word. Remember seq is a subset of word """ import itertools import timeit ...
import numpy as np from .fastmath import inv3, matvec __all__ = [ 'normalized', 'veclen', 'sq_veclen', 'scaled', 'dot', 'project', 'homogenize', 'dehomogenize', 'hom', 'dehom', 'ensure_dim', 'hom3', 'hom4', 'transform', 'convert_3x4_to_4x4', 'to_4x4', 'assemble_4x4', 'assemble_3x4', 'inv_3x4', ] ARR ...
import pygame, sys, math from pygame.locals import * def tree(x, y, length, angle): if(length < 3): return x_top = int(x + math.cos(math.radians(angle)) * length) y_top = int( y - math.sin(math.radians(angle)) * length) pygame.draw.line(DISPLAYSURF, THE_COLOR, (x, y), (x_top, y_top), int(l...
# Quiz Quest Component 9 Introduction # To Do # - Ask user if they would like to read the instructions # - if not print introduction # - if yes then go straight to the bulk of the code def string_check(question, to_check): # Loops until a valid answer is given valid = False while not valid: # As...
# Quiz Quest Component 8 ask user if they want to play again # To Do # - Ask user if they want to play again # - if yes code loops again # - if no then code ends def string_check(question, to_check): # Loops until a valid answer is given valid = False while valid == False: # Asks question ...
import unittest from homework5.homework5_functions_to_test import check_isIntercalary, check_is_triangle, check_type_triangle class TestIsYearLeap(unittest.TestCase): def test_leap_year(self): year = 2000 res = check_isIntercalary(year) self.assertTrue(res, "True") class TestIsTriangle(un...
from homework4.homework4 import only_alphabet #5.1 Создайте список 2 в степени N, где N от 0 до 20. rez = [2**n for n in range(0, 20)] print(rez) #5.2 У вас есть список целых чисел. Создайте новый список остатков от деления на 3 чисел из исходного списка. rez = [0, 1, 3, 5, 6, 8, 9, 10, 11] new_rez = [n % 3 for n in ...
def starts_with_a_vowel(word): return word[0] in "AEIOU" x = starts_with_a_vowel("Iggi") print x names = ["Alice", "Bob", "Cara", "Editch"] namesArr = [name.lower() for name in names] print "HEY this is name ARR: " + str(namesArr) def filter_to_vowel_words(word_list): vowel_words = [] for word in wor...
# A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. # Find the largest palindrome made from the product of two 3-digit numbers. # Brute force solution s = 0 for i in range(100, 1000): for j in range(100, 1000): ...
import random as r import matplotlib.pyplot as plt class SpellingBeeContestant: _knowledge = 0 def __init__(self, percentage_knowledge): self._knowledge = percentage_knowledge def get_knowledge(self): return self._knowledge def __str__(self): return str(self._knowledge) de...
import random def sel(arr): for i in range(0,len(arr)-1): min_index=i for j in range(i+1,len(arr)): if arr[j] < arr[min_index]: min_index=j arr[i], arr[min_index] = arr[min_index],arr[i] print("정렬중",arr) arr = list() for i in range(10): arr.append(ran...
# -*- coding: utf-8 -*- """列隊""" class Queue(object): """ 列隊類別 為先進先出的資料結構 """ def __init__(self): self.items = [] def enqueue(self, item): """ 新增資料 從尾部入列資料 """ self.items.append(item) def dequeue(self): """ 移除資料 從頭部出列...
# -*- coding: utf-8 -*- """插入排序法""" def insertion_sort(original_list): """ 透過遍歷陣列中元素 並將當前元素的位置和值暫存起來 當遍歷進行時,依序比較前面的元素 如前一個元素大於當前元素,則將前一個元素放入當前的位置(當前元素依然存放在暫存中) 在遍歷結束後,將放在暫存中的當前元素放在最小的位置上(最小的位置為結束迴圈時的索引) 效率尚可 """ new_list = original_list[:] for i, val in enumerate(new_list): ...
# -*- coding: utf-8 -*- """合併排序法""" def merge_sort(original_list): """ 為分治演算法的一種 需以遞迴排列 算是常用的排序演算法 """ return merge_recursive(original_list) def merge_recursive(sub_list): """ 將陣列進行對切 直至長度為1為止,才對分割後的左右兩邊進行合併 """ list_len = len(sub_list) if list_len <= 1: return ...
import sys import csv from cs50 import SQL def main(): db = SQL("sqlite:///students.db") house = sys.argv[1] if (len(sys.argv) != 2): print("enter 1 command line argument") return 1 list = db.execute("select first, middle, last, house, birth from students where house = ? order by last...
def future_ages(): # Name name = input("What's your name? ") # Age while True: year_born = input("What year were you born? ") try: year_born = int(year_born) except ValueError: continue else: break # The Facts current_year = 201...
''' Objective: Return an array consisting of the largest number from each provided sub-array. >>> largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) [5, 27, 39, 1001] >>> largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) [27, 5, 39, 1001] >>...
class Cloud: # __setattr__: same as cloud.color='pink' def __setattr__(self, name, value): self.__dict__[name] = value.upper() cloud = Cloud() cloud.color = 'pink' print ('cloud.color:', cloud.color)
import unittest def FuncAddNumber(first, second): result = first + second return result class addTestCase(unittest.TestCase): def test_add_func1(self): result = FuncAddNumber(3,5) self.assertEqual(result, 8) def test_add_func1(self): result = FuncAddNumber(6,7) self.assertEqual(result, 13) unit...
# Importing essential packages from tkinter import * import tkinter.messagebox import sqlite3 class Add: def __init__(self, parent): # Window Initialization self.register_window = Toplevel(parent) self.register_window.title("Redline | Add Blood") self.register_window.geometry("500...
###Given a tuple of numbers, iterate through it and print only those numbers which are divisible by 5### num_tuple = (3, 5, 33, 46, 4) print("Given list is ", num_tuple) # Print elements that are divisible by 5 print("Elements that are divisible by 5:") for num in num_tuple: if (num % 5 == 0): prin...
from tkinter import * import pandas as pd data = pd.read_excel("C:/Users/user/Desktop/store-dataset.xlsx") global y global m global product_list product_list = [] global mon y,m = 2014,'Jan' SalesReport = Tk() SalesReport.title("Sales Report") SalesReport.geometry("800x600") def option_changed_year(*args): print...
# print "Hello World" # print 1234 * 1234 # a = 5 # print a # a = 6 # print a # print type(5.4) print "Welcome to the wild world of random questions!" print "Let us begin" name = raw_input ("What is your name? ") age = input ("How old are you?: ") hair = raw_input ("What color is your hair? ") age_add = input ...
__author__ = 'Beni' name_list = [] times_greeted = 0 def greeting(): name = raw_input("What is your name? ") name_list.append(name) print("Hello, {}".format(name)) print("{}, I noticed that your working hard today.".format(name)) print("Work a little less tomorrow {}".format(name)) print("The...
from PIL import Image print("\nThis program will insert a background image of your choice in a image of your choice!\n") front_number = input("What image would you like to insert in the front?\n1- A Boat\n2- A Cactus\nEnter the option number: ") while front_number < "1" or front_number > "2": front_number = inp...
import unittest from Order_Statistics import * class RandomisedSelectTestCase(unittest.TestCase): def setUp(self): self.listA = [3, 8, 1, 7, 4, 6, 2, 5, 9] # example by MM self.listB = [i + 1 for i in range(10)] self.listC = [5, 2, 9, 1, 10, 3, 4, 6, 8, 7] def test6thInA(self): ...
""" This program has been written to solve problem 2 on projecteuler.net author: Jeremiah Lantzer """ max_num = 4000000 # even fibonacci numbers under this value result = [] # stores the fibonacci sequence past, current = 0, 1 # initializes the first 2 numbers in the sequence even_sum = 0 ...
questions = ['Are you over 14?\n', 'Want to use sauna?\n', 'Are you a student?\n', 'Are you Male?\n'] while True: q1 = input(questions[0]) if q1 == 'no': print('You are underage!') break elif q1 == 'yes': q2 = input(questions[1]) if q2 == 'yes': print('Price: 150...
while True: a = (input('Enter a number (or letter to exit): ')) if str.isalpha(a): break operation = input('Enter an operation: ') b = (input('Enter another number: ')) if operation == '+': print('Result: ', int(a) + int(b), '\n') if operation == '-': print('Result: ', ...
total = 0 for number in range(1, 10 + 1): total += number print(total) # ############## print(sum(range(1, 10 + 1))) ############ factorial = 1 num = int(input("Type in a number:\n")) for i in range(1, num + 1): factorial *= i print(factorial) ############## sum = 0 prd = 1 for i in range(1, 10 + 1): ...
import copy def shooting(grid, row, column): hit = 0 if grid[row][column] == 0: grid[row][column] = "#" elif grid[row][column] == "X": grid[row][column] = "H" hit = 1 return hit def ship_placement(grid, row, column, direction, length): k = 0 if direction == 1: ...
# -*- coding: utf-8 -*- """ Created on Sun Feb 2 12:27:05 2020 @author: Chenyang """ class Node(object): def __init__(self, data, next = None): '''data为数据项 next为下一节点的链接 初始化节点默认链接为None''' self.data = data self.next = next node1 = None node2 = Node(1, None) node3 = Node('hello...
# -*- coding: utf-8 -*- """ Created on Fri Jun 26 10:21:39 2020 @author: Chenyang 该模块包含以下内容 my_book: 字符串变量 say_hi: 简单的函数 User: 代表用户的类 """ print("this is module 1") my_book = "讲义" def say_hi(user): print("%s,欢迎学习python"%user) #模块的测试函数 def test_my_book(): print(my_book) def test_say_hi(): say_hi("孙悟空") ...
import csv count = 0 dates = [] Rev = [] avg = [] goldchange = 5 loldchange = 1000000000 print("") print("Financial Analysis") print("-----------------------------") #put what ever file you want with open('budget_data_1.csv', 'r') as csvfile: csv_reader = csv.reader(csvfile, delimiter = ',') next(csv_reader) ...
""" CSE-1310 Final Exam Practice problem #24 """ """ fp = open("movies.csv", "r") MovL = fp.readlines() fp.close() MovD = {} for line in MovL: tokens = line.split(",") inList = [] inList.append(tokens[1]) inList.append(tokens[2]) MovD[tokens[0]] = inList #MovD complete find = raw_input("Please en...
""" this program will prompt the user 6 times for a number and then tell if the number is odd or even """ count = 0 #remember count started at zero and zero counts too[0,1,2,3,4,5] is six numbers while count <=5: num = input("Enter a number: ") if num%2 == 0: print print "the number is even" ...
""" James Hawley 10-03-2013 Howmwork#5a """ def countTokens(n): count = 0 tokens = List[n].split(",") for t in tokens: count = count + 1 return count def countChar(n): tokens = List[n].split(",") count = 0 for t in tokens: for c in t: count = count + 1 retur...
""" This is me using a Mac """ a = input("Enter a number: ") while a != 10000: if a: print "this evaliates to true" else: print "this is always false" a = input("Enter a number: ") print print "Remember, when dealing with logic operators, a nonzero number...
""" James Hawley 09/04/2013 Homework#2 """ num = input("Please type an integer: ") if num == 0: print "zero" elif num > 0: print "The number is positive" if num%5 ==0: print "The number is divisible by 5" else: print "The number is not divisible by 5" elif num < 0: print "The numb...
""" This is a number guessing game that will let the player guess 7 times to find the right number """ import random snum = random.randint(1,100) print snum count = 0 guess = -1 while count != 7: count = count + 1 print count count = 1 while count != 7: while guess != snum: guess = input("Ente...
class calculator: def __init__(self,a ,b, typeOfOperation): self.a = a self.b = b self.typeOfOperation = typeOfOperation if typeOfOperation == '+': print("Result obtained after adding the numbers : ", self.addition()) elif typeOfOperation == '-': print...
''' This part contains the encrypt and decrypt function of Beale Cipher. The encryption and decryption rule is that the if the book does not contain certain letter in plaintext, it will raise an error. Since the same number should not be used for the same letter throughout encryption, if the book has used out all numbe...
# How to Think Like a Computer Scientist # Chapter 4 and Chapter 5 Exercises and Lab ################################################################ ''' 4.11.6 -- (draw shape filled in with color) Write a program that asks the user for the number of sides, the length of the side, the color, and the fill ...
def count_letters_digits(sentence): letter = digit = 0 for value in sentence: if value.isalpha(): letter += 1 elif value.isdigit(): digit += 1 else: pass print("Letters : ",letter) print("Digits : ",digit) sentence = input("Enter sentence :: ") count...
def pick_odd(numbers): str1 = "" num_list = numbers.split(',') for value in num_list: if int(value)%2 != 0: str1 += value + ',' else: pass print("Odd numbers of list :: ",str1) numbers = input("Enter list of numbers : ") pick_odd(numbers)
from nltk.util import ngrams from collections import OrderedDict import re n = 0 i = 0 l = 0 data = {} gram = [] frequence = [] file = open("Apple.txt","r",encoding='UTF-8') n = input("ngram n=") def ngram(n): global i while True: line = file.readline() if line == '': break else: ...
import numpy as np #Take specific number of array my_array = np.array([1,2,3,4,5,6]) print(my_array[2:]) #Selecting values by conditions x = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(x[x > 5]) print(x[x%2 == 0]) print(x[(x > 2) & (x < 11)]) print(x[(x > 5) | (x == 5)])
import os import sqlite3 import matplotlib import matplotlib.pyplot as plt def scatterplot(cur, conn): cur.execute("SELECT * FROM 'GDP Info'") country_list = cur.fetchall() gdp_day_list = [] for country in country_list: try: cur.execute("SELECT 'GDP Info'.'GDP', Day1.day FROM 'GDP I...
# CONSOLE_GUESSING_GAME import random def test_number(): # Computer 3_digit random number sample_space = list(range(0, 10)) random.shuffle(sample_space) # shuffle the list of numbers to avoid repitition target = sample_space[:3] ''' Checks whether user- input 3-digit number is exactly the s...
#!/usr/bin/python class Person: def __init__(self,name,age): self.name,self.age = name,age def __str__(self): return 'This guy is {self.name},is {self.age} old'.format(self=self) a=Person("lei.yang","1") print str(a)
# fifth Program/Homework 5 # Programmer Lauren Cox # Date of last revision 20-01-2016 data=input('type in the data:') first_change=data.replace('a','*') print(first_change.replace('A','*'))
#thrid Program/Homework 3 # Programmer Lauren Cox # Date of last revision 20-01-2016 a=float(input("Input a floating point number :")) b=float(input("Input a floating point number :")) c=float(input("Input a floating point number :")) d=float(input("Input a floating point number :")) print('%10.2f'%a) print('%10.2f...
#Homework 27 #Programmer Lauren Cox #Date of Last Revision 28-4-2016 import turtle s=0 a=turtle.Screen() b=turtle.Turtle() b.penup() b.goto(-75,-160) b.pencolor("black") b.pensize(250) b.pendown() b.forward(150) b.left(90) b.forward(325) b.left(90) b.forward(150) b.left(90) b.forward(325) def key_color_x1(): s=...
# eighth Program/Homework 8 # Programmer Lauren Cox # Date of last revision 28-01-2016 a=int(input('Type in a integer:')) b=int(input('Type in a integer:')) c=int(input('Type in a integer:')) if (a>0) and (b>0) and (c>0): print('yes') # I put zero because, zero is not a positive or negative i...
# - 每行代码,或每个方法要求添加注释(基础不好的同学) # # 题目内容: # # 1. ⼀个回合制游戏,有两个英雄,分别以两个类进⾏定义。分别是Timo和Jinx。每个英雄都有 hp 属性和 power属性,hp 代表⾎量,power 代表攻击⼒ # 2. 每个英雄都有⼀个 fight ⽅法, fight ⽅法需要传⼊“enemy_hp”(敌⼈的⾎量),“enemy_power”(敌⼈的攻击⼒)两个参数。需要计算对打一轮过后双方的最终血量, # 英雄最终的⾎量 = 英雄hp属性-敌⼈的攻击⼒enemy_power # 敌⼈最终的⾎量 = 敌⼈的⾎量enemy_hp-英雄的power属性 # 量和敌⼈最终的⾎量,⾎量剩余多的⼈获...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 20 20:12:57 2020 @author: redhwanzaman1989 """ def calculate_mean(number): s = sum(number) l = len(number) mean = s/l print('mean is {0}'.format(mean)) return mean def calculate_median(number): number = money number1...
import re from dateutil import parser months = {'января': 'january', 'февраля': 'february', 'марта': 'march', 'апреля': 'april', 'мая': 'may', 'июня': 'june', 'июля': 'july', 'августа': 'august', 'сентября': 'september', 'октября': 'october', 'ноября': 'november', 'декабря': 'december'} ...
import numpy as np from random import shuffle from past.builtins import xrange def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape ...
def extrai_naipe (carta): divide_str = [list(letra) for letra in carta] if len(divide_str) == 3: return divide_str [2] [0] if len(divide_str) == 2: return divide_str [1] [0] def extrai_valor (carta): divide_str = [list(letra) for letra in carta] if len(divide_str) == 3: retu...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Graph: def __init__(self): self.noeuds=[] self.arretes=[] class Noeud: def __init__(self, intitule): self.intitule=intitule self.voisins=[] def __eq__(self, other): return self.intitule == other.intitule class Arrete: def __init__(self,noeud_a,no...
people = [ {"name": "Harry", "house": "Gryffindor"}, {"name": "Cho", "house": "Raveclaw"}, {"name": "Draco", "house": "Slytherin"} ] # def a function that tells the sort function how to do the sorting def f(person): # need to tell sort function how to sort these people return person["house"] # sort by ...
from itertools import chain def maximal_spanning_non_intersecting_subsets(sets): """ Finds the maximal spanning non intersecting subsets of a group of sets This is usefull for parsing out the sandboxes and figuring out how to group and calculate these for thermo documents sets (set(frozenset)): s...
#!/usr/bin/env python class Sort: def __init__(self, my_list): self.my_list = my_list def bubble_sort(self): if len(self.my_list) > 1: for i in range(len(self.my_list)-1): for j in range(len(self.my_list)-1-i): if self.my_list[j] > self.my_list...
# ** MULTIPLES ** # Part I for x in range(1, 1000, 2): print x # Part II for x in range(5, 1000000, 5): print x # ** SUM LIST ** a = [1, 2, 5, 10, 255, 3] sum = 0 for x in a: sum += x print sum # ** AVERAGE LIST ** a = [1, 2, 5, 10, 255, 3] sum = 0 for x in a: sum += x avg = sum / len(a) print avg
class product(object): def __init__(self, price, name, weight, brand, cost): self.price = price self.name = name self.weight = weight self.brand = brand self.cost = cost self.status = 'for sale' self.discount = 'none' #self.show() # optional displays all information about all products # chainable...
class bike(object): def __init__(self, price, maxSpeed): self.price = price self.maxSpeed = maxSpeed self.miles = 0 def displayInfo(self): print 'Price is', self.price, 'Top speed is', self.maxSpeed, 'Miles ridden', self.miles def ride(self): print 'Riding' self.miles += 10 return self def r...
## 1290. Convert Binary Number in a Linked List to Integer ''' Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. Exa...
import pygame import random pygame.init() # grid settings grid = 25 # px screen_width = 30 * grid screen_height = 20 * grid refresh_rate = 1 # ms # character width = grid height = grid win = pygame.display.set_mode((screen_width, screen_height)) alive = True def decide(x, y): # decide direction global length ...
#!/usr/bin/python # Rocks, Paper, Scissors ! # Written and Designed by CJ Clark & Chris Clark # No Licence or warranty expressed or implied, use however you wish! import sys, random, argparse, time def findweapon(weapon): if weapon == "s" or weapon == "scissors": print "\n[+] You Picked Scissors! ... sneaky!...
""" 127.单词接龙 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则: 每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。 说明: 如果不存在这样的转换序列,返回 0。 所有单词具有相同的长度。 所有单词只由小写字母组成。 字典中不存在重复的单词。 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。 """ from collections import defaultdict def ladderLength(beginWord, endword, wordList)...
""" 2019.06.29 判断二叉树 是否是对称的 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ## 递归 class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :r...
""" 131.分割回文串 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回 s 所有可能的分割方案。 """ def partition(s): if not s: return [] res=[] cur =[] def helper(s, start, cur): if start == len(s): res.append(cur[:]) return else: j = 1 while start+ j <= le...
""" 31.下一个排列 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 必须原地修改,只允许使用额外常数空间。 以下是一些例子,输入位于左侧列,其相应输出位于右侧列。 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 """ def nextPermutation(nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place ins...
""" 80.删除排序数组中的重复项II 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 """ def removeDuplicates(nums): flag = 1 i = 0 while i < len(nums): if i > 0 and nums[i] == nums[i-1]: flag += 1 if i>0 and nums[i] != nums[i-1]: ...
""" 148.在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。 对链表进行归并排序 先递归地分割 再merge """ class ListNode(object): def __init__(self,val): self.val = val self.next = None class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ i...