text
stringlengths
37
1.41M
#Pyg Latin is a language game, where you move the first letter of the word to the end and add "ay." So "Python" becomes "ythonpay. pyg = 'ay' #original word original = raw_input('Enter a word:') #condition to check string is empty and is onlu alphanewmeric if len(original) > 0 and original.isalpha(): word = o...
import sys import os def add_file(afile, filename='files'): """ Add file to the list of files we want to track for changes. Currently we are deciding not to add this feature. In our current security model, we want the monitoring system to be responsible for all aspects the configuartion as we ...
print('Виконав студент групи КН 42з Огорілко Роман') f = open('data', 'r') data = [] for line in f: data.append(line.split(", ")) nvoice = [] symbols =[] for element in data: nvoice.append(element[0]) element.pop(0) symbols.append(element) def methodBorda(): A =0 B =0 ...
# Finds the median of a list of numbers. def median(list): list.sort() list_length = len(list) if list_length%2==0: return (list[int(list_length/2)-1] + list[int(list_length/2)])/2 else: return list[int(list_length/2)]
# function to check string is # palindrome or not def isPalindrome(word): # Using predefined function to # reverse to string print(s) rev = ''.join(reversed(word)) # Checking if both string are # equal or not if (word == rev): return True return False # main function word= "malaya...
# 1437. Check If All 1's Are at Least Length K Places Away https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/submissions/ # https://leetcode.com/submissions/detail/539667733/ from typing import List def kLengthApart(nums: List[int], k: int) -> bool: distance = k for n in nums: ...
# Define coffee machine class CoffeeMacnhine: class Coffee: def __init__(self, name, water, milk, beans, cost): self.name = name self.water = water self.milk = milk self.beans = beans self.cost = cost # Types of coffee COFFEE = [Coffee('es...
__author__ = 'Hernan Y.Ke' # A Closer Look at the iter Function from random import randint #roll a six-sided dice until a 1 is rolled: def rolldice(): return randint(1,6) for i in iter(rolldice,1): #must callable, not rolldice() print(i)
__author__ = 'Hernan Y.Ke' import re import reprlib reg = re.compile('\w+') #put outside of class class Sentence: def __init__(self,sentence): self.sentence = sentence self.words = reg.findall(sentence) def __iter__(self): return SentenceIterator(self.words) def __repr__(self)...
__author__ = 'Hernan Y.Ke' import itertools p = list(itertools.zip_longest('ABC', range(5), fillvalue='?')) for word in p: print(word)
import pandas as pd import numpy as np # Reading the data Data ################# data = pd.read_csv("D:\\excelR\\Data science notes\\Random forest\\asgmnt\\Company_Data.csv") data.head() data.columns data=data[['CompPrice', 'Income', 'Advertising', 'Population', 'Price','Age', 'Education', 'ShelveLoc', 'Urban', '...
#TicTacToe game X = "X" O = "O" LENGTH = 3 def draw(board): for i, y in enumerate(board): #Simplify and generalize the string formatting print "{}|{}|{}".format(y[0],y[1],y[2]) if i <> 2: print "-----" def turn(players, activePlayer): active_player_info = [players.keys()[...
from nltk import pos_tag #Stopword filteration stemming are suggested before this step, Import text from Stemming.py/StopwordFilterations.py Tokenized_words = 'Tokenized Text' #Identify POS tokens_pos = pos_tag(stemmed_words) a = [tokens_pos] # Function to extract two pattern tags def match2(token_p...
import numpy as np def step(board,t): for i in range(len(board)): if board[i] == 0: break while True: randCase = np.random.randint(0,4) if randCase == 0: if i >= t: up = list(board) up[i] = board[i-t] up[i-t] = 0 ...
"""Terminal Based program to create a basic rectangle program. Depending on the machine you enter will prompt for different options. Currently supported machines are the Vantechs, Jasper and Fordsville Weeke, and the ABD. After generating the generated file will open in WoodWop for review. Inputs: Almost a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 20 09:43:38 2018 @author: abhijith """ import numpy as np n=np.array([i for i in range(-1,2)]) print(n) y=[1,2,-2] import matplotlib.pyplot as plt def x(t,l): plt.scatter(t,y) plt.plot(t,y,linestyle='dashed',label=l) x(n,'x(n)') #what sh...
from linkedlist import LinkedList def redact_words(words, banned_words): word_list = LinkedList(words) for word in banned_words: found_word = word_list.find(lambda werd: werd == word) if found_word is not None: word_list.delete(found_word) return word_list words = ['A', 'B', '...
""" Functions used to retrieve values from a ConfigNamespace. To retrieve values from the default namespace use the module level getters. .. code-block:: python max_size = staticconf.get_int('max_size', default=10) threshold = staticconf.get_float('threshold') To retrieve values from a namespace, you can cr...
import re import string from getpass import getpass from base_type.menu import BaseMenu def validate_password(key) -> bool: special = False capital = False length = len(key) >= 8 for char in key: if char in string.ascii_uppercase: capital = True if char in """ !"#$%&'()*+,...
# Martin Stevko class zoznam: def __init__(this, p=None): this.info = p this.pointer = this def __str__(this): s = '' c = this.pointer while c.info is not None: s += str(c.info)+', ' c = c.pointer return s[:-2] def add(this, *new)...
class Car: def __init__(self, length, weight): self.length = length self.weight = weight self.next = None class Train: def __init__(self): self.first = None self.last = None self.length = 0 self.weight = 0 def add(self, length, weight): ...
""" PROJECT 6 - Priority Queues and Heaps Name: """ class Node: """ This class represents a node object with k (key) and v (value) Node definition should not be changed in any way """ def __init__(self, k, v): """ Initializes node :param k: key to be stored ...
#!/usr/bin/env/python import shutil as sh import psutil as ps limit_free_space = 5 limit_cpu_percent = 50 def check_disk_usage(disk): du = sh.disk_usage(disk) free_space_percent = du.free/du.total * 100 return free_space_percent > limit_free_space def check_cpu_usage(): usage = p...
import utils import numpy as np import glob import os # Print output stats def print_stats(name, length, all_stats): """ Print the velocity stats collected (mins, maxs, means, etc.) """ print("Evaluating: ", name) print("Length: ", length) for stat in all_stats: stat_text = "" for key...
from math import sqrt import pandas as pd from matplotlib import pyplot as plt def minmax(dataset): minmax = list() for i in range(len(dataset[0])): if i == len(dataset[0]) - 1: continue value_min = dataset[:, i].min() value_max = dataset[:, i].max() minmax.append(...
""" This is a simple application for sentence embeddings: clustering Sentences are mapped to sentence embeddings and then k-mean clustering is applied. """ from sentence_transformers import SentenceTransformer from sklearn.cluster import KMeans if __name__ == '__main__': embedder = SentenceTransformer('bert-base...
# //Task # Given an integer, , perform the following conditional actions: # If is odd, print Weird # If is even and in the inclusive range of to , print Not Weird # If is even and in the inclusive range of to , print Weird # If is even and greater than , print Not Weird # Input Format # A single line...
# get the user input from index site and turn it into a variable import cgi import cgitb cgitb.enable() form = cgi.FieldStorage() print("Content-Type: text/html") print() print("<TITLE>CGI script output</TITLE>") selected_neighborhood = str(form["neighborhood"].value) # selected neighborhood #selected_ne...
edad = int(input("escribe tu edad: ")) if edad > 17: print("Mayor de edad") elif edad <= 3: print("Es un bebe") else: print("Es menor de edad")
rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) ...
''' Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1 Input: [3,0,1] Output: 2 Example 2 Input: [9,6,4,2,3,5,7,0,1] Output: 8 O(n) time O(1) space ''' class Solution(object): def missingNumber(self, nums): """ :type...
""" Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example 1: [[1,3,1], [1,5,1], [4,2,1]] Given the above grid map, return 7. Because the path 1→...
''' Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets. For example, If nums = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] Time: O(N*2**N) Space: O(2**N) ''' class Solution(...
from math import sqrt from turtle import Screen,Turtle pantalla=Screen() pantalla.setup(1025,1025) pantalla.screensize(1000,1000) pantalla.setworldcoordinates(-500,-500,500,500) pantalla.delay(0) x1=-200 y1=-200 velocidad_x1=0.1 velocidad_y1=0 m1=20 x2=200 y2=200 velocidad_x2=-0.1 velocidad_y2=0 m2=20 cuerpo1=Turt...
def side_brackets(brackets, n): for b in generate_brackets(n): yield brackets+b yield b+brackets def inner_brackets(start_bracket, end_bracket, n): for brackets in generate_brackets(n): yield start_bracket+brackets+end_bracket def generate_brackets(n): mem = set() if n==0: r...
import turtle import math sun=turtle.Turtle() sun.color("yellow") sun.shape("circle") sun.shapesize(3) mercury=turtle.Turtle() mercury.color("blue") mercury.shape("circle") mercury.shapesize(0.382) venus=turtle.Turtle() venus.color("#ffff24") venus.shape("circle") venus.shapesize(0.949) earth=turtle.Turtle() earth.c...
import os from sys import argv import hashlib def hashfile(path,blocksize = 1024): afile = open(path,'rb') hasher = hashlib.md5() buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) afile.close() return hasher.hexdigest() ...
#2. 사용자 입력과 출력 a =input() print(a) number = input('숫자를 입력하세요: ') # 출력하기 print("life" 'is' 'too short') #+와 동일 #- 띄어쓰기는 ,로 가능하다 print("life",'is','too short') for i in range(10): print(i,end=",")
#2. while 문 treeHit = 0 while treeHit< 10: treeHit = treeHit +1 print('나무를 %d 번 찍었습니다. ' %treeHit) if(treeHit==10): print('나무가 넘어갑니다') prompt =""" 1.add 2.del 3.list 4.quit Enter number:""" number =0 while number !=4: print(prompt) number = int(input()) # break ...
""" This module contains window image states (constant and temporary). """ from abc import ABC import time import pygame # State pattern. class ImageState(ABC): """ Base class of image states. """ def __init__(self, window): self.window = window def update(self): """ Is called to check...
import array import sys ''' Problem 1: Rearrange array such that a[i] = i Given an array of elements of length N, ranging from 0 to N – 1. All elements may not be present in the array. If element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is...
import urllib from BeautifulSoup import * url = raw_input('Enter - ') html = urllib.urlopen(url).read() soup = BeautifulSoup(html) print html print soup print "ending content" #retrive a list of the anchor tags #each tag is like a dictionary of HTML attributes tags = soup('a') print tags for tag in tags: print t...
__author__ = 'msaha' #any method with two underscores at beginning and end are special methods #create a class class Student(object): """Classes can have docstring too just like modules adn functions""" def __init__(self, name, id = 20001): # it is like a constructor but actually not. Since it is present right...
^ beginning of line $ end of line . matches any character * repeats zero or more number of times + repeats one or more number of times \s matches whitespace \S matches any non-white space character *? repeats zero or more times, non greedy +? repeats one or more times, non-greedy [aeiou] matches a single character in t...
user_input = raw_input("Enter palindrome string: ") isPalindrome = True; for i in range(len(user_input)/2): if user_input[i] != user_input[len(user_input) - i - 1]: # as soon as any character not matching we will break and call it not palindrome isPalindrome = False; break if isPalindrome: pr...
__author__ = 'msaha' def find_greatest(input_list): l = len(input_list); for j in range(l -1): for i in range(l-1): if input_list[i] > input_list[i+1]: temp = input_list[i+1]; input_list[i+1] = input_list[i]; input_list[i] = temp; return i...
def count_substring(string, substring): substring = list(substring) l1 = [] cnt = 0 for i in range(len(string)): for j in range(len(substring)): if i == j: print i l1.append(j) j+1 i+1 else: j+1 if len(l1) == len(substring): cnt+1 else: cnt return cnt print count_substri...
user_input = raw_input("Enter palindrome string: ") for letter in user_input: print letter for i in range(len(user_input)/2): str1 = "" str2 = "" str1 = str1 + user_input[i] str2 = str2 + user_input[len(user_input) - i - 1] if str1 == str2: True print "palindrome" else: False pr...
#Write a function that returns the elements on odd positions in a list. input = raw_input("Enter ") input_list=input.split() n=len(input_list) i=0 output_list=list() #this also works def odd_elements(input_list): for i in range(n): if i%2 == 0: output_list.append(input_list[i]) #print o...
try: inp = raw_input("Enter number: ") inp = int(inp) for i in range(1, inp): o = i * (i - 1) if i == 0: break i = i - 1 print o except: print "Error, enter number again" quit()
#RDDs into Relations (Python) #load a text file and convert each line to a dictionary. lines = sc.textFile("../../../people.txt") parts = lines.map(lambda l: l.split(",")) people = parts.map(lambda p:{"name": p[0], "age": int(p[1])}) #infer the schema, and register the schema RDD as a table peopleTable = sqlCtx.infe...
global count global shared count = 0 shared = [] class Reader: def __init__(self,number): self.number = number self.type = "Reader" def __repr__(self): return str(f"Reader {self.number}") def __str__(self): return str(f"Reader {self.number}") class Writer: def __init__(s...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: result = [] _stack = collections.deque() curr_node = r...
#!/usr/bin/env python """ Sample script that creates 'Devices' table in an SQLite database, populates it with some information about network devices, searches database and displays content of the records, and finally, removes all the records from the database. The SQLite is integrated in Python as sqlite3 module, whi...
#!/usr/bin/env python # Examples of using lambda expression # # NOTES: # Like def, lambda expression creates a function object to be called later, # but it returns the function object instead of assigning it to a name. # Since lambda is an expression (not a statement) it can appear in places # where a def is not allow...
import random def ask_yes_no(question: str) -> bool: while True: answer: str = input(question).strip().lower() if answer == "yes" or answer == "y": return True elif answer == "no" or answer == "n": return False else: print("Please enter a valid answer") def ask_rock_paper_scissors() -> chr: while T...
import os give=input("give something: ") TER_SIZE=os.get_terminal_size().columns print(give.upper()) if False: # can be True print(give.center(TER_SIZE).title()) print(give.ljust(TER_SIZE).upper()) print(give.rjust(TER_SIZE).title()) usr_cnf=input(" ok ?! type yes or no : ") if usr_cnf=="yes": prin...
"""A grammar rule is defined to be a 2-tuple in which the first item is the name of the grammar rule (a string), and the second item is a list of all of the constituents of the rule where the first item is the 'oldest' consitituent and the last item in the list is the 'newest' constituent. """ import itertools from c...
# 题目描述 # 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 # 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 # NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 # 示例1 # 输入 # [3,4,5,1,2] # 返回值 # 1 # -*- coding:utf-8 -*- class Solution: def minNumberInRotateArray(self, rotateArray): # write code here l = len(rotateArray) if l == 0: ...
# 题目描述 # 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 # 示例 # 输入 # 3 # 返回值 # 4 # -*- coding:utf-8 -*- class Solution: def jumpFloorII(self, n): # write code here if n <= 1: return 1 res = 1 for i in range(1, n): res += self.jumpFloorII(n - i) ...
#-*- coding: utf-8 -*- """ https://leetcode-cn.com/problems/goat-latin/description/ 给定一个由空格分割单词的句子 S。每个单词只包含大写或小写字母。 我们要将句子转换为 “Goat Latin”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。 山羊拉丁文的规则如下: 如果单词以元音开头(a, e, i, o, u),在单词后添加"ma"。 例如,单词"apple"变为"applema"。 如果单词以辅音字母开头(即非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"。 例如,单词"goat"变为"oatgma"。...
x = "Peter Parker" # global scope / module scope nums = [4, 7, 8] def fn(): x = "Spiderman" # local print(nums) print("inside fn()", x) def fn2(): x = "Mr. " + x # จะ error เพราะเครื่องไม่รู้จักตัวแปรนี้ print("inside fn()", x) def fn3(): global x x = "Mr. " + x print("inside fn()...
def index_of_string(string, array): array_length = len(array) middle_index = array_length / 2 median = array[middle_index] while not median: middle_index = middle_index + 1 median = array[middle_index] if string == median: return middle_index elif array_length <= 1: ...
from quick_sort import partition array = [5, 1, 4, 4, 5, 9, 7, 13, 3] class StreamInteger: def __init__(self, value): self.value = value class Stream: def __init__(self, integers): self.integers = [] for i in integers: self.track(i) def rank(self, integer): ar...
class Solution: """ @param s: an expression includes numbers, letters and brackets @return: a string """ def stack_pop(self, stack): tmp = "" while stack: if stack[-1].isdigit(): break tmp = stack.pop() + tmp return tmp def express...
class ThreeStacks: """ @param: size: An integer """ def __init__(self, size): self.size = size self.array = [None for _ in range(3*size)] self.indexs ={0:0, 1:size, 2:2*size} """ @param: stackNum: An integer @param: value: An integer @return: nothing """ ...
# -*- coding:utf-8 -*- def findMinAndMax(L): if len(L)==0: return (None,None) elif len(L)==1: return (L[0],L[0]) else: max=L[0] min=L[0] for x in L: if max<x: max=x if min>x: min=x return (min,max)
# TODO import csv from sys import argv from cs50 import SQL # Check csv file has been entered by the user if len(argv) != 2: print(f"usage:{argv[0]} infile") # Create a db by opening and closing an empty file first open(f"students.db", "w").close() db = SQL("sqlite:///students.db") # Create table called 'student...
from tkinter import Tk,Button,Label,Entry,END from time import strptime,strftime from tkinter.messagebox import showinfo def compute(): global dateEnd date=dateEnd.get() weekday = strftime('%A', strptime(date, '%b %d, %Y')) showinfo(message = '{} was a {}'.format(date, weekday)) dateEnd.delete(0,END...
from tkinter import Tk,Label,RAISED root=Tk() text =[['1','2','3'], ['4','5','6'], ['7','8','9'], ['*','0','#']] for i in range(4): for j in range(3): box = Label(root, relief = RAISED, padx=10, pady=12, tex...
''' 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 ''' # -*- coding:utf-8 -*- class Solution: def jumpFloor(self, number): # write code here if number < 3: return number j, k, l = 1, 2, 0 for i in range(3, number+1): l = j + k j = k ...
numbersTaken = [1, 2, 3, 6, 9] print("Here are the numbers that are still available:") for n in range(1, 20): if n in numbersTaken: continue print(n)
from collections import Counter text = "This is cool. Whatever. La la la. I'm up late AF on Wednesday. Woohoo! Lego! Lego my eggo!" # - Need to convert words into list words = text.split() # This is the list split into words. print(words) # - Prints out three most common words counter = Counter(words) top_three =...
class Tuna: def __init__(self): print('Blurp blurp') def swim(self): print("I am swimming.") flipper = Tuna() flipper.swim() # - Init is called before anything is called.
stocks = {'GOOG' : 520.54, 'FB' : 76.54, 'YHOO' : 39.28 , 'AMZN' : 306.21, 'AAPL' : 99.76} print(min(stocks)) # - Returns AAPL, the key minimum value, not the lowest-priced stock. We want YHOO. # - Create a new list with Zip, this switches the order of the key and value (520, GOOG) min_price = min(zip(stocks.values(...
age = 19 if age == 34: print("You are 34 years old. Jake was 34 when this program was created!") elif age > 21: print("You are of legal drinking age.") else: print("You are too young.")
#use recursion and the fact that making change for larger values is equal #one of the previous values calculated class coins: def numWays(self,n): #the coin values used coinVals = {25,10,5,1} #number of ways for each value so far prevSums = [n+1][len(coinVals)] return self.calcWays(n,coinVals,0,prevSums) d...
#stack class from http://interactivepython.org/runestone/static/pythonds/BasicDS/ImplementingaStackinPython.html #stack with the added functionality of returning the minimum element class minStack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self...
from NodeSLL import Node #if a node in one list is by reference, not by value a node #in the other list then return True, else return false def intersection(head1,head2): if head1.listLength() <= head2.listLength(): while(head2.next != None): if head1 is head2: return True head2 = head2.next else: while(hea...
from Stack import Stack class stackOfPlates: #constructor def __init__(self,cap): self.plates = [] self.cap = 4 #checks if there are no plates def isEmpty(self): return self.plates == [] #pushes onto plate or creates new plate def push(self, item): p = Stack() if ((self.isEmpty()) or (self.plates[len(...
class Node: #constructor def __init__(self,data=None,next=None): self.data = data self.next = next #add a node to the list def appendToTail(self,data): node = Node(data) n = self while(n.next != None): n = n.next n.next = node #delete a node from the list def deleteNode(self,d): h = self n ...
#count how many different ways a child can run up n stairs if they can #either hop 1 2 or 3 stairs at a time class tripleStep: def numWays(self,n): #table to store already calculated values during recursion table = [None for _ in xrange(n+1)] return self.countSteps(n,table) #recursive function to calculate num...
#returns all subsets of a set in O(n2^n) time, this set is not ordered but satisifies req class powerSet: #use the previous set to construct the next set def getSubset(self,initialSet,newSet): #base case if initialSet == []: return [newSet] #recursion, given 2 possibilities else: ret = [] for x in se...
from Node import Node #find the first common ancestors of 2 nodes in a binary tree class firstCommonAncestor: def FCA(self,root,node1,node2): if root == None: return None #if node is found return the node if root.data == node1.data or root.data == node2.data: return root #check if the node is in the le...
from bisect import insort class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: mergelst = [] while l1 != None or l2 != None: if l1: insort(mergelst, l1.val) l1 = l1.next if l2: insort(mergelst, l2.val...
class Trie: def __init__(self): self.root = dict() def build(self, arr): for n in arr: self.add(n) def add(self, number): word = "{:032b}".format(number) curr = self.root for c in word: c = int(c) if c not in curr: ...
from bisect import insort class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: sortlist = [] while head != None: insort(sortlist, head.val) head = head.next ...
############################################################################### # # 2520 is the smallest number that can be divided by each of the numbers from # 1 to 10 without any remainder. # # What is the smallest positive number that is evenly divisible by all of the # numbers from 1 to 20? # #####################...
task = int(input('Запустить задачу номер: ')) if task == 1: # 1. Реализовать класс «Дата», функция-конструктор которого должна принимать # дату в виде строки формата «день-месяц-год». В рамках класса реализовать два метода. # Первый, с декоратором @classmethod, должен извлекать число, месяц, # год и преобразовывать их ...
user_name = input('Vvedite vawe imya:\n>>>') user_age = input('Vvedite vaw vozrast: \n>>>') if user_age.isdigit(): user_age = int(user_age) else: print(user_name, 'Owibka vvoda: vvedite chislo') exit() print('Dobriy vecher', user_name, '!') sys_message = f'Polzovatel {user_name} \nv vozraste {user_age} \...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-11 17:21:04 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: None Do n...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-15 09:22:18 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-13 17:53:36 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution: def decodeString(self, s: str) -> str: if not s: return "" # 用两个栈,一个存储 mul,一个存储字符串 stri...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-11-09 18:03:08 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution: def searchInsert(self, nums, target): if not nums: return None left = 0 right = len(nums) - 1 while left <= right:...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-02-22 17:46:52 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-02 11:49:50 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os import collections class Solution(object): def findWhetherExistsPath(self, n, graph, start, target): if not graph: ret...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-02-26 06:45:06 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(obje...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-11-08 07:00:38 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(): def search(self, nums, target): if not nums: return -1 left = 0 right = len(nums) - 1 while left <= right: mid...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-06 06:37:26 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os # # The knows API is already defined for you. # @param a, person a # @param b, person b # @return a boolean, whether a knows b # def knows(a, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-13 15:19:18 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os import collections class Solution: def isPossible(self, nums: List[int]) -> bool: if not nums or len(nums) < 3: return ...