text
stringlengths
37
1.41M
# 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 isSameTree(self, p, q): if p and q: return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSa...
def climbStairs(n): """ :type n: int :rtype: int """ steps = [1, 2] s = [0] * (n + 1) s[0] = 1 for i in range(1,n + 1): for j in [c for c in steps if c <= i]: s[i] += s[i-j] return s[n] def climbStairs2(n): if n == 1: return 1 res = [0 for i in range(n)]...
from sys import argv script ,filename = argv print "we are going ton erase %r" %filename print "if you dnt want that hit CTRL-C(^C)." print"if you do want that,hit RETURN" raw_input("?") print "opening the file: " target =open(filename,'w') print "truncating the file.goodbye" target.truncate() print "now type 3 l...
import pandas as pd heights=[59,20,62,65,63,65,64] data={'heights':heights,'sex':'M'} results = pd.DataFrame(data) print(results) results.index=['A','B','C','D','E','F','G'] print(results) dict = {"country":["brazil","russia","India","China","South Africa"], "capital":["Brasilia","Moscow","New delhi","Beijin...
people =20 cats = 30 dogs = 15 if people < cats : print "too many cats" if people > cats: print "not many cats" if people < dogs: print "too many dogs" if people > dogs: print "not many dogs" dogs+=5 if people >=dogs: print "people are greater than or equal to dogs" if people <=dogs: print "people ar...
class person: def __init__(self,f,l): self.fname=f self.lname=l def name(self): return self.fname+ " " +self.lname class emp(person): def __init__(self,f,l,no): person.__init__(self,f,l) self.sno= no def getemp(self): return self.name() + "," + self.sno...
def add(a,b): print "add %d + %d" %(a,b) return a+b def sub(a,b): print "sub %d - %d" %(a,b) return a-b def mul(a,b): print "mul %d * %d" %(a,b) return a*b def div(a,b): print"div %d / %d" %(a,b) return a/b print "lets do something fun" age= add(20,2) hg= sub(78,4) wg =mul(90,3) iq=div(100,2) pr...
a=2 print 'id(a)=',id(a) a=a+1 print 'id(a)=',id(a) print 'id(3)=',id(3) b=2 print'id(2)=',id(2) def hi(): print "HELLO" a= hi() a class Myclass: "this is my first class" a=10 def fun(self): print "HELLO" ob= Myclass() print(Myclass.a) print(Myclass.fun) ob.fun() print(Myclass.__doc__)
''' for i in range(ord('a'),ord('z')+1): print chr(i) print "********************" print "enter 10 numbers:" a=[0]*10 for i in range(0,10): a[i]= int(raw_input(">>")) for i in range (0,10): if a[i]%7 ==0: print a[i] ''' print "enter two values:" a = int(raw_input("a>>")) b = int (raw_input("b>>...
print "enter a number:" no=int(raw_input(">>")) i=1 while i!=11: print no,"*",i,"=",i*no i=i+1 for i in range(1,11): print(no,'x',i,'=',no*i)
def sum(items): no=0 for x in items: no+=x return no print sum([1,2,3,4,5,6,7,8])
import math ''' a = int(raw_input("a>>")) b = int(raw_input("b>>")) c = int(raw_input("c>>")) d = (b**2) - (4*a*c) if d>0: r1 = (-b + math.sqrt(d))/(2*a) r2 = (-b - math.sqrt(d))/(2*a) elif d==0: r = (-b)/(2*a) print "ROOTS ARE EQUAL" else: print "IMAGINARY ROOTS" no = int(raw_input(">>")) d = ...
import tkinter from PIL import Image, ImageTk import random root = tkinter.Tk() root.geometry("600x600") root.title("Simple Rolling Dice Game") BlankLine = tkinter.Label(root, text="") BlankLine.pack() HeadingLabel = tkinter.Label(root, text="This is a simulation", fg="light green", bg="dark green", font=...
""" Implement a frame to track the human descriptors and notes on each data column. """ from typing import Union import pandas as pd from .exceptions import OverlapException from .frame_to_word import frame_to_word from .word2reference.read_word import WordReader class DescriptionFrame: """ Parameters -...
# Внешний вид игрового поля field = [ [' ', '0', '1', '2'], ['0', '-', '-', '-'], ['1', '-', '-', '-'], ['2', '-', '-', '-']] move = "O" # Переменная, которая отвечает за то, чей сейчас ход, первые всегда ходят крестики Flag = False # Флаг, который будет меняться после выполнения условий в бесконечном ци...
#!/usr/bin/env python # encoding: utf-8 # qinliang@meituan.com class Solution(object): def sortList(self, head): if not head: return head res = head while res: while True: if not head.next.next: break cur_node = head...
#!/usr/bin/env python #-*- coding=utf-8 -*- ######################## def f(target): if target == 1: return 1 elif target > 1: return str(f(target-1))+str(target) else: raise ValueError('bad args') #################################### print f(3)
#!/usr/bin/env python #-*- coding=utf-8 -*- ######################## def f(target): if target == 0 or target == 1: return 1 else: return f(target-1) + f(target -2) print f(3)
#!/usr/bin/env python #-*- coding=utf-8 -*- num = 1 for i in range(1,121): num = num * i print num num = str(num) list_1 = list(num) list_1.sort() num = "".join(list_1) print num
class User: def __init__(self, name, email): self.name = name self.email = email # self.account_balance = 0 self.account = BankAccount('Checking') def make_withdrawal(self, amount): # if self.account.balance < 0: # charge overdraft fee # pass ...
myfile = open("Files/fruits.txt") content = myfile.read() print(myfile.read()) print(myfile.read()) print(content) print(content) myfile.close() #print(myfile.read()) # New way to code this file open and it will close file object in memory # so no need to explicitly mention close clause. with open("Files/frui...
""" Contains a selection of tree and graph related algorithms """ from enum import Enum from itertools import izip_longest from Queue import Queue from random import randint from algorithms import permutations from linked_list_algorithms import Node class BinaryNode(object): """ A node that's part of a bina...
import unittest from sorting_and_searching_algorithms import merge_two_sorted_lists,\ sort_by_anagram,\ search_in_rotated_array class TestSortingAndSearchingAlgorithms(unittest.TestCase): def test_merge_two_sorted_lists(self): """ Checks we can merge one list into another """ ...
import tkinter as tk """classe de la startpage : incluant des variables ou des fonctions qui permettent de definir un objet, ici tout ce qui compose la start page c'est a dire le menu principale ou l'on decide de jouer ou consulter les regles du jeu cette page est reliée a la page 1 et 2. """ class StartPage(tk.Fra...
''' Facebook_Easy 10.2 8:37pm 从1开始 1 11 21 1211 111221 循环比递归快 从空间复杂度和时间复杂度分析 ''' # 循环 class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ laststr = '1' i = 1 while i < n: s = str() v = laststr[0] ...
''' 按照一个方向走,撞到墙才能改方向 要求找到能不能最后停到destination的位置 思路: BFS Time complexity : O(mn)O(mn). Complete traversal of maze will be done in the worst case. Here, mm and nn refers to the number of rows and coloumns of the maze. Space complexity : O(mn)O(mn). visitedvisited array of size m*nm∗n is used and queuequeue size can gro...
def median(A, B): # A和B的长度 m, n = len(A), len(B) # 如果 A比B长,交换AB,保证j大于0 if m > n: A, B, m, n = B, A, n, m if n == 0: raise ValueError # 中位数左边的长度,可以包括中位数 imin, imax, half_len = 0, m, (m + n + 1) // 2 while imin <= imax: # 将A砍半 i = (imin + imax) // 2 ...
class Solution: def reverseWords(self, str): """ :type str: List[str] :rtype: void Do not return anything, modify str in-place instead. """ # 先把整个str翻转 self.reverse(str, 0, len(str) - 1) i = 0 j = 0 # 再把每个单词翻转 while i < len(str): ...
''' LinkedIn_Easy 10.12 11:33am ''' import math class Solution(object): def judgeSquareSum(self, c): """ :type c: int :rtype: bool """ i = c // 2 j = c - i (square_i, value1) = self.isSquare(i) (square_j, value2) = self.isSquare(j) if square_...
''' Uber_Medium 10.29 6:34pm ''' class Solution(object): def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ if not dict: return sentence root = Trie() for v in dict: trie = roo...
''' 题意: 给一组string 要求判断这个String matrix的每行每列是否相同 思路: 不能用zip 因为会有这种情况 Input: [ "abcd", "bnrt", "crm", "dt" ] Output: true ''' class Solution: def validWordSquare(self, words): """ :type words: List[str] :rtype: bool """ # 先判断words中最长的word的长度是否和word的总个数相等 max_l...
# 不需要相对位置 def move_zeros(l): i = 0 j = len(l)-1 while i < j: if l[i] == 0 and l[j] != 0: l[i] = l[j] l[j] = 0 if l[i] != 0: i+=1 if l[j] == 0: j-=1 print(l) # 需要相对位置 def move_zeros_origin(l): i = 0 j = 0 while i < len(l)...
''' LinkedIn_Medium 10.14 6:27pm ''' # 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 findLeaves(self, root): """ :type root: TreeNode :rtype:...
from collections import OrderedDict class LRUCache(object): def __init__(self, capacity): self.array = OrderedDict() self.capacity = capacity def get(self, key): if key in self.array: value = self.array[key] del self.array[key] self.array[key] = valu...
class TreeNode(object): def __init__(self, val): self.val = val self.neighbor = [] def solution(A, E): # write your code in Python 3.6 if not A: return 0 nodes = [TreeNode(v) for v in A] def same_value_path(node, val): if node.val == val: same_sub = 0 ...
''' 通过函数构建层级图。第一个函数是set(雇员a,雇员b)意思是令ab为同一直接manager的下属。 第二个函数是set(雇员a 经理m)意思是令m成为a的直接上属。 还有一个get(a)是要求你返回从a往上所有的管理关系链直到顶层。 沟通了输入输出,刚开始有点误解,小哥说没有input,后来搞了半天input是一堆构建图的query, 就是set函数。相当于你一般构建图 一边根据已有的图返回管理链。自己定义了类,开始实现。 复杂的地方在:如果ab同级 bc同级 cd同级,这时候get a没有一个链可以返回。但是这时候设置d的直接经理是m 那么abc都要更新。 思路: 相当于构件图 用一个employee的类存储员工的经...
''' Facebook_Medium 11.9 11:24pm ''' class Solution: def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ if len(nums) < 2: return False if k < 0: k = -k if k == 0: for i in ra...
''' 题意:看nums中有没有的3个递增的sequence ''' class Solution: def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ # 记录first和second数的index a = -1 b = -1 for i, v in enumerate(nums): # 如果没有a,或者v比a对应的位置小 if a == -1 ...
''' 题意: 找到BST中和target最接近的数字 注意这个target是float类型的 本质是遍历BST ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def closestValue(self, root, target): """ :type root: TreeN...
''' 假设有一条高速公路,路面上有n辆车,每辆车有不同的整数速度, 但是都在1-n范围内。现在给你一个数组,代表每辆车的速度。 车辆出发顺序即数组顺序,问最后可以形成几个集群,每个集群的size是多少? 可以理解为,虽然车辆速度不同,但是即使后面的车比前面的车速度快,因为不能超车, 最后肯定只能以前车的速度行驶,这就形成了一个集群。 比如[2,4,1,3],最后[2,4]是一个集群,[1,3]是一个集群。 follow-up: 假设想再加入一辆车,这个车的速度比其他车都大,但是不确定这个车的出发顺序, 让输出最后所有可能的每个集群的大小(List of List) 这辆车可以放在最前面出发,集群数目就是1+前面的结果,一个s...
''' 题意:有一个时间HH:MM;要求用之前时间里面出现的数字组成另一个时间,且这个时间在当前时间的后面,也可以是下一天 Input: "19:34" Output: "19:39" Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later. Input: "23:59" Output: "22:22" Explanation: The n...
''' Facebook_Easy 11.05 11:05pm ''' class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if not num1: return num2 if not num2: return num1 ret = '' i = -1 ...
def mul(a,b): l_a = [] l_b = [] res = 0 for i in range(len(a)): if a[i]: l_a.append((i,a[i])) if b[i]: l_b.append((i,b[i])) def find_in_b(loc): start = 0 end = len(l_b) while start<=end: mid = (start+end)//2 if ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ # 如果k=1,...
''' LinkedIn_Medium 10.12 3:08pm ''' class Solution(object): def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ i = 0 while i < len(flowerbed) and n: if flowerbed[i] == 1: i+=2 ...
''' 看过去5min内发生过多少hit 思路: binary search ''' class HitCounter(object): def __init__(self): """ Initialize your data structure here. """ self.record = [] def hit(self, timestamp): """ Record a hit. @param timestamp - The current timestamp (in seconds granul...
class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.subtrie = dict() self.isWord = False self.val = '' def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void ...
''' 题意: Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] Return 16 The two words can be "abcw", "xtfn" 要求这两个word中的字符不能有重复 思路: bit_manipulation 与运算 把每一个word转换为bit 注意一个word钟有重复字符的情况,要用set去重 ''' class Solution(object): def maxProduct(self, words): """ :type words: List[str] :rtype: int ...
class stack: def __init__(self): self.items = list() # Empty list for stack def push(self,item): self.items.insert(0,item) def pop(self): self.items.pop(0) def printstack(self): for each in self.items: print(each) stk = stack() # object of class stack ! ...
# zahlenraten import random zufallszahl = random.randint(1,2) anzahlDerVersuche = 0 title = "Willkommen beim Zahlenraten!" text = "bitte geben sie eine zahl ein die zahl ist zwischen 1-100" eingabeText = "DeinVersuch: " print(title) print(text) fertig = False while fertig == False: zahl = int(input(eingabeTe...
"""Bubble Sort Algorithm """ counter = 0 def sort(array): """Sorts an array.""" global counter for i in range(0, len(array) - 1): counter += 1 for j in range(i + 1, len(array)): counter += 1 if array[j] < array[i]: counter += 1 _swap...
""" One-Time-Pad Coder Encrypts and decrypts a text using the one-time-pad algorithm. """ from random import choice from string import ascii_letters, digits, punctuation from itertools import chain from operator import add, sub PAD = list(chain(ascii_letters, digits, punctuation, [' '])) def generate_key(text): ...
""" Heap Sort Algorithm """ from math import log2 from operator import gt, lt def sort(array): for i in range(len(array), 0, -1): heapify(array, i, min_heap=False) array[0], array[i - 1] = array[i - 1], array[0] def heapify(heap, limit=None, min_heap=True): """Inserts the elements in the hea...
#Escribir un programa que almacene el diccionario con los creditos de las asignaturas de un curso {'Matematicas': 6, 'Fisica': 4, 'Quimica': 5} y despues muestre por pantalla los creditos de cada asignatura en el formato <asignatura> tiene <creditos> creditos, # donde <asignatura> es cada una de las asignaturas del cur...
#Escribir un programa que muestre el eco de lo que el usuario introduzca hasta que el usuario escriba 'salir' que terminara palabra = "" while(palabra != "salir"): palabra = input("Escribe una palabra: ") print palabra
#Escribir un programa que pregunte al usuario su nombre, edad, direccion y telefono y lo guarde en un diccionario. Despues debe mostrar por pantalla el mensaje <nombre> tiene <edad> annos, vive en <direccion> y su numero de telefono es <telefono>. diccionarioPersona = {} nombre = str(input("Introduce tu nombre: ")) ed...
#Escribir un programa que pregunte al usuario una cantidad a invertir, el interes anual y el numero de anno, y muestre por pantalla el capital obtenido en la inversion cada anno que dira la inversion cantidad_invertir = int(input("Introduce una cantidad para invertir: ")) interes_anual = float(input("Introduce el inte...
#Ejercicio 9 txt = str(input("Write a text string ")) txt_low= txt.lower() def no_str(txt): if txt_low[0:2] == str("no"): print(txt) else: print(str("No ") + txt) no_str(txt)
from __future__ import print_function class Game2048Logic: # The board is simply a list of integers representing the cells # First element is top-left and so on left-to-right and then # top-to-bottom as a raster # Board cells contain a string which represents the tile # number or " " if the tile ...
import math """ 1. Crear una lista usando la función constructora `list(...)`. Imprimir en consola la lista """ # Usando la función constructora sería MyList = list(1,5,3,28,9) MyList = [1, 5, 3, 28, 9] print("Tarea 1.1.") print(MyList) print("\n") """ Tarea 1.2. 2. Crear una lista e imprimir en consola el tamaño...
from math import sqrt from itertools import permutations def square_root_int(x): return int(sqrt(x)) def prime(number): if number == 1: return False upper_bound = square_root_int(number) + 1 for x in range(2, upper_bound): if x == number: next if number % x == 0: ...
def prime(n): if n == 2 or n == 3: return True if n % 2 == 0 or n < 2: return False for i in range(3, int(n**0.5) + 1, 2): if n % i == 0: return False return True def factors(n): f, s = 2, set() while n > 1: if n % f == 0: n = int(n / f) s.a...
# Восстановление траектории шахматного коня # 64 вершины letters = 'abcdefgh' numbers = '12345678' graph = dict() # создаём 64 именованные вершины (8×8) for l in letters: for n in numbers: graph[l+n] = set() def add_edge(v1, v2): graph[v1].add(v2) graph[v2].add(v1) # ходим конём (1, 2) по клетка...
A = set('bqlpzlkwehrlulsdhfliuywemrlkjhsdlfjhlzxcovt') B = set('zmxcvnboaiyerjhbziuxdytvasenbriutsdvinjhgik') # for x in A: # if x not in B: # print(x) print({x for x in A if x not in B}) # ================================== A = set('0123456789') B = set('02468') C = set('12345') D = set('56789') E = A....
# Хранение графа в памяти # возьмём простейший граф: # A -- B -- C -- D # 1 список вершин + список рёбер V = {"A", "B", "C", "D"} # N — порядок графа E = {("A", "B"), ("B", "C") ("C", "D")} # M — размер графа # Быстро проверяем наличие вершины, ребра — О(1) # Перебор всех соседей вершины — О(N)...
# # подключение библиотеки под синонимом gr # import graphics as gr # # Инициализация окна с названием "Russian game" и размером 100х100 пикселей # window = gr.GraphWin("Russian Game", 100, 100) # # Инициализация окна с названием "Russian game" и размером 100х100 пикселей # # window.close() # # Создание круга с ради...
# === именованный кортеж === # точка в 3D пространстве: A = (1, 0, 3) # например найти расстояние от центра координат r = math.sqrt(A[0]**2 + A[1]**2 + A[2]**2) # не говорящие названия, не удобно использовать # хочется A.x, A.y, A.z # можно создать класс, но много возни, можно проще from collections import namedtupl...
""" Topic to be Covered - Multivariate Linear Regression @author: aly """ ''' #Step 1 - Import the necessary libraries and the dataset #Step 2 - Plot the Seaborn Pairplot #Step 3 - Plot the Seaborn Heatmap #Step 4 - Extract the Features and Labels #Step 5 - Cross Validation (train_test_split) #S...
# -*- coding:utf-8 -*- # author: pekwjw # date: 2019-01-28 class Car(object): def __init__(self,car_name = "suv"): self.name = car_name def create(self): print "create one {0}.".format(str(self.name)) class tank(Car): def __init__(self,car_name): Car.__init__(self,car_name) d...
#Author: Jasffer T. Padigdig #Date: October 14, 2020 #Assignment: Phonebook code #Description: The code is executes the CRUD using hashing #References: def linearprobing(A, location): counter = 0 #if the counter is greater than the length of the list then it means the phone book is already full w...
import random print("UP / DOWN 게임을 시작합니다.") rm = random.randrange(1,100) answer = 0 while (answer != rm) : answer = int(input("1~100중에서 숫자를 입력해주세요 : ")) if(answer > rm) : print("Down") elif(answer < rm) : print("Up") else : print("정답") break
height = float(input("키를 입력하세요 : ")) standardweight = (height - 100) * 0.9 print("당신의 표준체중은 {:.1f}".format(standardweight))
x=3 #Penulisan For Looping dalam Phyton for i in [0,1,2]: print(i) print() listAngka = [0,1,2,3] for i in listAngka: print(i) print() for huruf in "Komsi": print(huruf) print() kalimat = "For Phyton" for huruf in kalimat: print(huruf) print() for i in range( 1, 9, 2): print(i)
import ConfigSpace import numpy as np import typing def is_integer_hyperparameter(hyperparameter: ConfigSpace.hyperparameters.Hyperparameter) -> bool: """ Checks whether hyperparameter is one of the following: Integer hyperparameter, Constant Hyperparameter with integer value, Unparameterized Hyperparamet...
"""Contains the functions for making sentiment analysis.""" from detect_lang import LanguageDetector from nltk.tokenize import RegexpTokenizer import numpy as np import codecs import os def wordlist_to_dict(): """Create a dictionary from a wordlist.""" path = os.getcwd() # Runs from web app folder word_l...
print "" print "Comparisons" print "" print "4 > 3 is " + str( 4 > 3 ) # 4 greater than 3 print "4 < 3 is " + str( 4 < 3 ) # 4 less than 3 print "4 == 3 is " + str( 4 == 3 ) # 4 equal to 3 print "4 >= 3 is " + str( 4 >= 3 ) # 4 greater than or equal to 3 print "4 <= 3 is " + str( 4 <= 3 ) # 4 less than...
from tkinter import * from verticalScrollFrame import* fontStyle = "Times New Roman" class StartPage(Frame): #A frame containing widgets is created in the constructor of this class #pseudoPar and passPar are variables we would use in storing # specific numbers based on the user's input and passing it to...
x = 500 y = 600 answer = f"x={x} is greater than y={y}" if x > y else f"y={y} is greater than x={x}" print(answer)
#List comprehension examples # first one shows the matrix transposed example l=[[1,2,3],[11,22,33],[111,222,333]] l_transpose=[[a[i] for a in l ] for i in range(3)] print(l_transpose) #list comprehension example2 #this will show the list comprehension of multiple lists a=[1,2,3] b=["apple","banana","orange"] c=["I...
# While loop with else block executed n=0 while n<10: print("n is lesser than 10 and the current number is :", n) n+=1 else: print("n is greater than or equal to 10 ", n) #while loop without else block execute and break statement execute n= [1,2,3] i=0 while i <= len(n): print(n[i]) i+=1 i...
import time import matplotlib.pyplot as plt def Line(a,b): x = [b, b] y = [0, a] plt.plot(x, y, marker = 'o') def Graph(t_n, pos_t_n, xlabel, ylabel, heading): plt.axhline(0, color = 'black') plt.axis([pos_t_n[0]-1, pos_t_n[len(pos_t_n)-1]+1, min(t_n)-1, max(t_n)+1]) plt.title(heading) plt.xlabel(xlabel) pl...
# coding: utf-8 import time def tower(base, h, m): """Return base ** base ** ... ** base, where the height is h, modulo m. """ if m == 1: return 0 if base == 1: return 1 if h == 0: return 1 if h == 1: return base % m G, t = totient(m) if base in G: ...
# code: utf-8 ''' The eccentric candy-maker, Billy Bonka, is building a new candy factory to produce his new 4-flavor sugar pops. The candy is made by placing a piece of candy base onto a conveyer belt which transports the candy through four separate processing stations in sequential order. Each station adds another l...
# code: utf-8 from copy import deepcopy import time def sudoku(puzzle): puzzle_dict = parse(puzzle) # for e in puzzle_dict.items(): # print(e[0], ':', e[1]) results = guess(puzzle_dict) solution = puzzle.copy() for it in results.items(): solution[it[0][0]][it[0][1]] = it[1].pop() ...
# code: utf-8 import time class Sudoku: def __init__(self, puzzle): self.puzzle = puzzle self.solution = [] self.parse_puzzle() def solve(self): def solve_iter(fix_dict, possible_dict): # print state for each iter, largely slowdown the function # print...
# code: utf-8 import itertools def closest_pair(points): points = sorted(points) print(len(points)) # if len(points) > 1000: # return ((0, 0), (0, 0)) # print(points[0:2000]) return find_closest(points, 0, len(points))[0] pass def find_closest(points, start, end): #print('finding:...
# main_matrix = [[1,2,3],[4,5,6],[7,8,9]] # def matrix(): # return main_matrix def magic(player_place_list, each_choice_list): main_matrix = [[1,2,3],[4,5,6],[7,8,9]] if not player_place_list: main_matrix = [[1,2,3],[4,5,6],[7,8,9]] else: for ind_1,i in enumerate(main_matrix): ...
import pandas as pd # create dictionary data city = {'id': [3, 2, 1, 1], 'city': ['Toronto', 'Oakville', 'Mississauga', 'Mississauga'], 'postal': ['1111', '2222', '3333', '4444']} # create dataframe manually from Dictionary/List dfc = pd.DataFrame(city) print(dfc) # order by ID ascending, postal de...
import sys import pygame def check(a, b, c): if clicked[a] == 0: return False elif clicked[b] == 0: return False elif clicked[c] == 0: return False else: if clicked [a] % 2 == clicked[b] % 2: if clicked [a]%2 == clicked[c]%2: return True ...
#1 x = [ [5,2,3], [10,8,9] ] x[1][0] = 15 # Index 0 of index 1 in the string print(x) students = [ {'first_name': 'Michael', 'last_name': 'Jordan'}, {'first_name': 'John', 'last_name': 'Rosales'} ] students[0]['last_name'] = 'Bryant' # [0] is the first index in the string print(students) sports_direc...
#!/usr/bin/env python3 # -*- coding=utf-8 -*- from decimal import Decimal class Player(): def __init__(self): self.hands=[] self.handsValue=0 self.winRate=0 self.currentMoney=Decimal() self.name='' def __str__(self): return self.name+" "+str(self.hands[0]...
#Given a number and number of changes you can make the number to change it to a palindrom. #Using those you need to return the largestPalindome. #If not possible you need to return -1 def LargestPalindrome(s,n,num): inp=num wr,i=0,0 flag=0 while(i<s//2): if inp[i]!=inp[s-1-i] and flag...
#You are given a horizontal numbers each representing a cube side. #You need to pile them vertically such a way that,upper cube is <= lower cube. #Given you can take the horizontal cube side from either left most or from right most. #If it can be piled up vertivally retirn 'YES' or else return 'NO' #EX:3,2,1,1,5 ...
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # filename:012.py # author: shuqing # 题目:判断101-200之间有多少个素数,并输出所有素数。 num = 0 for i in range(101, 201): for j in range(2, i): if(i % j == 0): break if (j == i-1): print(i) num += 1 print(num)
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # filename:for.py # author: shuqing for num in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']: print(num) for letter in 'hello': print(letter) for numbers in range(1, 5): print(numbers)
#Point 實體物件的設計: 平面座標上的點 # class Point:#定義類別 # def __init__(self, x, y):#建立初始化函式 # self.x=x#定義實體屬性 # self.y=y#定義實體屬性 # #定義實體方法 # def show(self): # print(self.x, self.y) # def distance(self, targetX, targetY): # return((((self.x-targetX)**2)+((self.y-targetY)**2))**0.5) # p...
# 模式 匹配 # abc 找出abc # (abc) 找出abc # ab|cd 找出ab或cd # . 找出除了\n以為的任何字元(\n是換行) # ^abc 找出abc開頭的字 # abc$ 找出abc結尾的字 # abc? 找出0個或多個abc # abc* 找出0個或多個abc(越多越好) # abc*? 找出0個或多個abc(越少越好) # abc+ 找出1個或多個abc(越多越好) # abc- 找出1...
# coding: utf-8 # In[3]: def sum(n): total=0 i=1 while(i<n): if n%i==0: total+=i i+=1 return total def amc(m): i=m+1 while(1): a=sum(i) if i==sum(a): if i!=a: return i i+=1 # In[4]: amc(5)
""" This code is doing following : 1- Run softmax regression model for mnist digit classification by giving pixels values as input 2- Perform the same operation with CNN """ #Download and input mnist data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', ...
class Node(object): def __init__(self,item): self.item = item self._next = None class singleLinkList(object): def __init__(self): # 头节点 self._head = None def is_empty(self): return self._head == None def length(self): # 首先要指向头节点 cur = self._he...