text
stringlengths
37
1.41M
class Jumper: """A code template for a jumper hanging a guy. The responsibility of this class of objects is to organize the display text. Stereotype: Text organizer Attributes: lives (int): The number of mistakes the player has left before they lose. drawing (list): List o...
white_prisoner = [] black_prisoner = [] def capture_piece(f): if f[-1]=="v": f = f[0:-1] if f[-1]=="c": f = f[0:-1] f= f + "^" black_prisoner.append(f) else: f= f + "^" black_prisoner.append(f) elif f[-1] =="^": f = f[0:...
# Uses python3 from sys import stdin def fibonacci_sum_squares_naive(n): if n <= 1: return n previous = 0 current = 1 total = 1 for _ in range(n - 1): previous, current = current, previous + current total += current * current return total % 10 def pisano_period(m):...
# Uses python3 import sys def merge(_arr, l_, m, r): n1 = m - l_ + 1 n2 = r - m # create temp arrays _l = [0] * n1 _r = [0] * n2 for i in range(n1): _l[i] = _arr[l_ + i] for j in range(n2): _r[j] = _arr[m + 1 + j] i, j, k = 0, 0, l_ while i < n1 and j < n2: ...
# Nombre.py # Autor: Hugo Bueno. # Fecha de creacion: 14/09/2019 nombre=input("Nombre:") apellidos=input("Apellidos:") # Se concatan los valores str, junto con la literal " " nombreCompleto=nombre+" "+apellidos #nSe asigna a la variable la representacion en mayusculas de lo que contenia. nombreCompleto=no...
# Aleatorio.py # Autor: Hugo Bueno. # Fecha de creacion: 14/09/2019 # python nos ayuda con muchas librerias listas para utilizarse. # A esas librerias les da el nombre de module # Para utilizar un modulo en un programa, primero debe importarse, usando la instruccion import. import random # Se define una vari...
class PriorityQueueIterator(): def __init__(self,queue): self.__head = queue.get_head() self.__current = self.__head if(self.__head == None): # if the head is None # there is nothing to iterate self.__stop = 1 else: self.__st...
import random NUM_ITERATIONS = 10000000 NUM_PLAYERS = 1000 strategy = [random.random() for i in range(NUM_PLAYERS)] coffee = [0.0]*NUM_PLAYERS fills = [0] * NUM_PLAYERS pot = 1.0 for i in range(NUM_ITERATIONS): player = random.randint(0,NUM_PLAYERS-1) pot -= strategy[player] if pot < 0: pot = 1....
import pygame import random def snake(): def makeapple(arr): apple = [random.randrange(0, 50), random.randrange(0, 50)] same = False for i in arr: if i == apple: same = True if same: apple = makeapple(arr) return apple x1 = 50...
''' A child plays with a ball on the nth floor of a big building the height of which is known (float parameter "h" in meters, h > 0) . He lets out the ball. The ball rebounds for example to two-thirds (float parameter "bounce", 0 < bounce < 1) of its height. His mother looks out of a window that is 1.5 meters from...
import hashlib def calculateHash(password): return hashlib.sha256(password.encode('utf-8')).hexdigest() def Subscribe(username,password): account = username + ":" + calculateHash(password) f = open('accounts.txt','w') f.write(account) f.close() print('Registration Finished') d...
print "Watch out, World!" twitter = "@hearmecode" print twitter print "twitter" print "My governor's name is Martin O'Malley" # print 'My governor's name is Martin O'Malley' print "\nLesson\t\tTopic\n1\t\t\tStrings and Conditionals\n2\t\t\tLists and Loops\n3\t\t\tDictionaries & Files\n" twitter = "@hearmecode" prin...
#encodind: utf-8 import random puntero = random.randint(0,9) oportunidades = 0 while True: numero = int(input("Elige un numero en el intervalo [0,9]\n")) if numero == puntero: print("LE ATINASTE!!!") break else: print("Introduce un numero otra vez") oportunidades += 1 print("numero de oportunidade...
""" Python Forth """ class Node: def __init__(self, data): self.data = data self.next = None self.prev = None def __repr__(self): return self.data class LinkedList: def __init__(self, nodes=None): self.head = None if (nodes is not None): node =...
''' age = 17 if age > 18: print("you are old enough to vote") print("have you registered to vote yet") else: print("sorry,you are too young to vote") print("please register to vote as soon as you turn 18!") age = 12 if age < 4: print("your admission cost is 0") elif age < 18: print("your admiss...
# Problem 3 # Largest prime factor # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? def is_prime(num): if num == 1: return False i = 2 while i*i <= num: if num % i == 0: return False i += 1 return True...
# coding: utf-8 k = int(input("")) A = input("") B = input("") len_A = len(A) len_B = len(B) class Trie: root = {} END = '#' def insert(self, word): node = self.root for c in word: node = node.setdefault(c, {}) node[self.END] = None def search(self, word): ...
# # Example file for variables # f=0 print(f) # Declare a variable and initialize it f="abc" print(f) # # re-declaring the variable works print("this is a string" + str(123)) # # ERROR: variables of different types cannot be combined # # print("this is a string" + 123) # Global vs. local variables in functions p=...
""" Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. For example, given s = "leetcode", dict = ["leet", "code"]. Re...
""" Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Notice You must not modify the array (assume the array is read only). You must use only cons...
""" Merge two given sorted integer array A and B into a new sorted integer array. """ class Solution: """ @param A: sorted integer array A @param B: sorted integer array B @return: A new sorted integer array """ # NOTE: Challenge, what is one array is very large and the other is small def m...
""" Given some points and a point origin in two dimensional space, find k points out of the some points which are nearest to origin. Return these points sorted by distance, if they are same with distance, sorted by x-axis, otherwise sorted by y-axis. Have you met this question in a real interview? Example Given points...
""" Given a string s, cut s into some substrings such that every substring is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. """ class Solution: # @param s, a string # @return an integer # NOTE: DP Versino def minCut(self, s): if s == s[::-1]: retu...
""" Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6]. Follow up: Could you solve it with constant space complexity? (No...
""" Given two Sparse Matrix A and B, return the result of AB. You may assume that A's column number is equal to B's row number. Have you met this question in a real interview? Example A = [ [ 1, 0, 0], [-1, 0, 3] ] B = [ [ 7, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ] ] | 1 0 0 | | 7 0 0 | | 7 0 0 | AB ...
""" Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" """ class Solution(object): def addBinary(self, a, b): ...
""" Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary Notice Return 0 if there is no such transformation sequence. All words have the same len...
""" Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both sour...
""" Reverse a linked list. Have you met this question in a real interview? Example For linked list 1->2->3, the reversed linked list is 3->2->1 """ class Solution: """ @param head: n @return: The new head of reversed linked list. """ def reverse(self, head): if not head or not head.next: ...
""" 给两个independent queue,每个queue都存着timestamp,只能有getNext()来取queue里面的timestamp, 每个timestamp只能被取一次,比较这两个queue里的timestamp,如果差值<1,print这两个timestamp。 例如: Q1 0.2, 1.4, 3.0 Q2 1.0 1.1, 3.5 output: (0.2, 1.0), (1.4, 1.0), (0.2, 1.1), (1.4, 1.1), (3.0, 3.5) 最后用了两个thread,两个thread-safe queue来实现. 每次call getNext(), 和另一个queue里存的 每个it...
""" Given a number n, we need to find the sum of all the elements from all possible subsets of a set formed by first n natural numbers. Have you met this question in a real interview? Example Given n = 2, return 6 Possible subsets are {{1}, {2}, {1, 2}}. Sum of elements in subsets is 1 + 2 + 1 + 2 = 6 Given n = 3, re...
""" Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Have you met this question in a real interview? Example Given binary tree {3,9,20,#,#,15,7} 3 /\ / ...
""" Reverse a linked list from position m to n. Notice Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list. Have you met this question in a real interview? Example Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. """ """ Definition of ListNode class ListNode(object): def...
""" Given two strings str1 and str2, write a function that prints all interleavings of the given two strings. You may assume that all characters in both strings are different Example: Input: str1 = "AB", str2 = "CD" Output: ABCD ACBD ACDB CABD CADB CDAB Input: str1 = "AB", str2 = "C" Output...
#! /usr/bin/env python class IRD: # Test outcomes. PASS = "PASS" FAIL = "FAIL" UNRESOLVED = "UNRESOLVED" def __init__(self): self.test_result = self.UNRESOLVED # self.outcome_cache = OutcomeCache() # self.cache_outcomes = 1 # def _test(self, c): # ...
import random print "----- First Hero -----" first_name=raw_input("Please type your hero's name:") print "----- Second Hero------" while True: second_name = raw_input("Please type your hero's name:") if second_name == first_name: print second_name,"is taken please try another" continue...
import unittest ################################### #### Write your function below! #### def get_dictionary_count(input, ignore_case=True): if input == "": return {} else: if ignore_case == True: input = input.lower() keys = input.split() dictionary...
#!/usr/bin/env python import numpy as np board = np.zeros((8, 8)) print(board) # 1. Creation of a Chess Board for i in range(0, 8): for j in range(0, 8): board[i][j] = (i+j) % 2 print() print() print(board) # 2. Place the no. of queens on the desired position print() l=[] flag = True print("Enter how ...
# cadena = 'Alejandro Upegui vivio en el Salvador' # print(f'{cadena} 25 años, ' * 10) nombre = input("Cual es tu nombre? ") print(f'Tu nombre es {nombre}') numero = input("Digita un numero ") print(f'Lo que escribiste es de tipo{type(int(numero))}') print(f'El numero que escribiste es {int(numero)}')
listBig = ["Phong", 4, 7.0, "Van", 3.0]; listTiny = [123, "Tran"]; print(listBig); print(listBig[0]); print(listBig[1:3]); print(listBig[2:]); print(listTiny * 4); print(listTiny + listBig); listBig[0] = "Phonggggg"; print(listBig);
#encoding=utf-8 # 查找最大约数 def findMaxFactor(num): count = num / 2 while count > 1: if num % count == 0: print 'largest factor of %d is %d'%(num,count) break count -= 1 else: print '%d is prime'%num #查找两个数的最大公约数 def findMaxFactorOfTwo(num1,num2): count1 = n...
score = float(input(" 학점 입력 > ")) if score == 4.5 : print(" 신 ") elif score >= 4.2 : print(" 교수님의 사랑") elif score >= 3.5 : print(" 현 체제의 수호자") elif score >= 2.8 : print(" 일반인") elif score >= 2.3 : print(" 일탈을 꿈꾸는 소시민") elif score >= 1.75 : print(" 오락문화의 선구자") elif score >= 1.0 : print(" 불가촉...
from tkinter import * window = Tk() window.title("tkinter practice") window.geometry("640x480+100+100") window.resizable(False, False) panedwindow_1 = PanedWindow(relief = 'raised', bd = 2) panedwindow_1.pack(expand = True) left = Label(panedwindow_1, text = '내부윈도우-1 (좌측)') panedwindow_1.add(left) panedwindow_2 = P...
def average(numbers): total = 0 for i in numbers: total += i return total/len(numbers) def main(): numbers = [50, 20, 44, 60] print(average(numbers)) main()
## https://www.geeksforgeeks.org/args-kwargs-python/ # 4. Napisz funkcję, która przyjmuje dowolną ilość parametrów - zaloz ze beda podawane liczbowe, funkcja ma wypisywac te parametry, uzywajac petli for in def homework4(*argv): for arg in argv: print(f'Argument: {arg}') print(homework4(1, 2, 3, 4, 5)) ...
# -*- coding: utf-8 -*- """ Created on Fri Mar 29 09:59:37 2019 @author: lefty """ class Control: def __init__(self, starting_cash, data): self.starting_cash = starting_cash self.cash = starting_cash self.data = data self.time_steps = len(data) self.inven...
print("Decision on should i go to the market or not.") decision = input("Am i out of shampoo? : ") if decision in ('yes', 'no'): if 'yes' in decision: answer = input("is it raining? : ") if answer in ('yes', 'no'): if 'no' in answer: print("Yes go to the market.") ...
import socket import time import threading class Server(): ''' Server Class to create a server and listen to client ''' def __init__(self): ''' initializing the socket, host and port ''' self.server_sock = socket.socket(socket.AF_INET, ...
class Calculator: def __init__(self, num1, sign, num2, result=0): self.num1 = num1 self.sign = sign self.num2 = num2 self.result = result def plus(self): return self.num1 + self.num2 def minus(self): return self.num1 - self.num2 def multipl...
from random import randint def roll_again(): yn = raw_input("Do you want to roll? y/n ") while yn.lower() != "y" and yn.lower() != "n": yn = raw_input("Please just use y or n, nothing else. y/n ") else: if yn.lower() == "y": return True elif yn.lower() == "n": ...
s=int(input()) for m in range(1,13): d=(s-m*31)/12 if d==int(d): if d<10: print("0"+str(int(d)),end="/") else: print(str(int(d)), end="/") if m<10: print("0" + str(m)) else: print(str(m))
def max_1(a): if len(a)==1: return a[0] else: m=max_1(a[1:]) if a[0]>m: return a[0] else: return m a=tuple(map(int,input().split())) print(max_1(a))
l1=[1,3,5,8,10] l2=[2,6,9,11,15] l=[] while len(l1)>0 and len(l2)>0: if l1[0]<l2[0]: l.append(l1.pop(0)) else: l.append(l2.pop(0)) if len(l1)==0: l=l+l2 else: l=l+l1 print(l)
def aftomorph(n): k=n*n*n if 1 <=n<10: if k%10==n: return True elif 10 <= n < 100: if k % 100 == n: return True elif 100 <=n<1000: if k%1000==n: return True else: return False for i in range(1,999): if i%10==1 or i%10==5 or i%10...
def myUpper(s): s1='' #for i in range(0, len(s)): for c in s: if c.islower(): s1+=chr(ord(c)-32) else: s1+=c return s1 print(myUpper("AbCdEf")) print(myUpper(input()))
def palindromic_date(s): s1=s[0:2]+s[3:5]+s[6:] s2=s[3:5]+s[0:2]+s[6:] if s1==s1[::-1] and s2==s2[::-1]: return True else: return False
def sum_square(n,m): if n == m : return m**2 else: return sum_square(n,m-1)+m**2 n,m=map(int,input().split()) print(sum_square(n,m))
def f(m,n): if m==0 or n==0: if m==0: return n else: return m else: if m>n: return f(m%n,n) else: return f(n%m,m) m,n=map(int,input().split()) print(f(m,n))
def gcd(a,b): if a<b: a,b=b,a if b>0: return gcd(b,a%b) else: return a a,b=map(int,input().split()) print(a//gcd(a,b)*b)
""" IF-ELSE METODLARINI ÖĞRENMEK İÇİN BİR ALIŞTIRMADIR. """ #BEDEN KİTLE İNDEKSİ HESAPLAMA #Boyunuzu metre cinsinden giriniz. (Örn: 178) boy = float(input("Boyunuzu Giriniz:")) kilo = int(input("Kilonuzu Giriniz:")) #beden kitle indeksi hesaplama bki = kilo / (boy ** 2) if (bki < 18.5): print("Zayıf") elif (bk...
## 3. Introduction to SymPy ## import sympy x,y = sympy.symbols('x y') y = (x**2) print(y) ## 4. Limits Using SymPy ## import sympy x2,y = sympy.symbols('x2 y') x2 = 2.9 limit_one = sympy.limit((-(x2**2)+3*x2-1-(-1))/(x2-3),x2,2.9) print(limit_one) ## 5. Properties Of Limits I ## import sympy x,y = sympy...
## 1. The Range ## import pandas as pd houses = pd.read_table('AmesHousing_1.txt') def range(array): return array.max()-array.min() range_by_year = {} for year in houses["Yr Sold"]: range_by_year[year] = range(houses.loc[houses["Yr Sold"] == year]["SalePrice"]) print(range_by_year) one = False two = Tr...
## 1. Reading CSV Files with Encodings ## import pandas as pd laptops = pd.read_csv("laptops.csv",encoding = "Windows_1251") laptops.info() ## 2. Cleaning Column Names ## def clean_label(col): col = col.strip() col = col.replace("Operating System","os") col = col.replace(" ","_") col = col.re...
## 1. Probability basics ## # Print the first two rows of the data. # print(flags[:2]) most_bars_country = flags[flags["bars"]==flags["bars"].max()]["name"] highest_population_country = flags[flags["population"]==flags["population"].max()]["name"] ## 2. Calculating probability ## total_countries = flags.shape[0] ...
a=int(input("ingrese primer número: ")) b=int(input("ingrese segundo número: ")) if a == b: print("los números coinciden") print("y su suma es ", a+a) else: print("los números son diferentes") if a != b: print("los números son diferentes te dije!") print("y su resta es ", a-b) else: ...
## 3. Populations and Samples ## question1 = 'population' question2 = 'population' question3 = 'sample' question4 = 'population' question5 = 'sample' ## 4. Sampling Error ## import pandas as pd wnba = pd.read_csv('wnba.csv') print(wnba.head()) print(wnba.tail()) print(wnba.shape) parameter = wnba["Games Played"].m...
def g(x): print("la VIDA ES HERMOSA"*x) g(2) def suma(u,o): print(u+o) return(u*o) a = suma(5,6) b = suma(4,7) print(a*b) def resta(x,y): return(x/y) z = resta(2,0) print(z)
##for x in range(0,11): ##print(x) ##i = -1 ##while i < 10: ##i += 1 ##print(i) ##nums = [0, 2, 8, 20, 43, 82, 195, 204, 367] ##for num in nums: ##print(num) ##for x in range(0,11): ##print(x) ##else: ##print ("done") ##ist1 = ["apple", "banana", "cherry", "durian", "elderberry", "fig"] ##lis...
a = 1 b = 2 print(a , b) print(a+b) answer = 7 # print('정답은'+ answer+'입니다.') ->TypeError: can only concatenate str (not "int") to str print('정답은' + str(answer)+'입니다.') print('정답은', str(answer),'입니다.') print(f'정답은{answer}입니다.')
import numpy as np import matplotlib.pyplot as plt f = lambda x : x**2 -4*x + 6 gradient = lambda x : 2*x -4 x0 = 5.0 #(랜덤) # epoch = 30 epoch = 100 # learning_rate = 0.1 learning_rate = 0.1 print("step\tx\tf(x)") # \ : 한탭간격 건너 뜀 for i in range(epoch): temp = x0 - learning_rate * gradient(x0) x0 = temp ...
import numpy as np f = lambda x : x**2 -4*x + 6 gradient = lambda x : 2*x -4 x0 = 5.0 #(랜덤) # epoch = 30 epoch = 100 # learning_rate = 0.1 learning_rate = 0.1 print("step\tx\tf(x)") # \ : 한탭간격 건너 뜀 # print("{:02d}\t{:6.5f}\t{:6.5f}".format(0, x0, f(x0))) # print("{:02d}\t{:6.5f}\t{:6.5f}".format(0, x0, f(x0))) #...
import numpy as np a = np.array([[3,7,5],[8,4,3],[2,4,9]]) print "Our array is: " print a print "\n" print "Applying ptp() function: " print np.ptp(a) print '\n' print "Applying ptp() function along axis 1: " print np. ptp(a, axis=1) print '\n' print "Applying ptp() function along axis 0: " print np.ptp(a, axis=0) ...
import numpy as np a = np.array([[3,7,5],[8,4,3],[2,4,9]]) print "Our array is: " print a print "/n" print "Applying amin() function: " print np.amin(a,1) print '/n' print "Applying amin() function again: " print np. amin(a,0) print '/n' print "Applying amax() functions: " print np.amax(a) print '/n' print "Applyi...
import re # re.match :尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。 # re.match(pattern,String,flags=0) # pattern:匹配的正则表达式,String:要匹配的字符串。flags:标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。 ''' content = "Hello 123 452 Word_this this is a Demo!!" print(content) # 全匹配 result = re.match('^[A-Z][a-z]{4}\s\d{3}\s\d{3}\s\w{9}.*$',...
#!/usr/bin/python # -*- coding: utf-8 -*- # Programa Cliente import socket import sys import re if len(sys.argv) != 3: print ("Agregar la IP del servidor y el puerto donde se ofrece el servicio.") sys.exit(0) IP = sys.argv[1] PUERTO = int(sys.argv[2]) print ("\nConectandose al servidor ", IP,...
""" Example of processing data from file on disk """ import luigi import pandas as pd from . import util class HtTasks(luigi.WrapperTask): """ Runs all tasks """ def requires(self): yield LoadReverseUrl() class RawFlatData(luigi.ExternalTask): """ specify that an external task has created the ...
import sys from random import randint from Implementations.Player import Player from Implementations.Labyrinth import Labyrinth class Aventure: def __init__(self,size:int): self._labyrinth=Labyrinth(size) self._player=Player(self._labyrinth.get_listRooms()[(randint(0,size-1),randint(0,size-1))]) ...
def find_missing(sequence): diff = min(sequence[1]- sequence[0], sequence[2]- sequence[1]) for i in range(len(sequence)-1): if sequence[i] + diff != sequence[i+1]: return sequence[i] + diff
def camel_case(string): res = string.split() for i in range(len(res)): res[i] = res[i].title() return ''.join(res)
def sum_dig_pow(a, b): res = [] for element in range(a, b + 1): total = 0 for j in range(len(str(element))): total += int(str(element)[j]) ** (j + 1) if total == element: res.append(total) return res
def pig_it(text): words = text.split() res = [] for word in words: if ('!' not in word) and ('?' not in word): word = word + ' ' word = word.replace(word[-1], word[0]) word = word[1:] + 'ay' res.append(word) return ' '.join(res)
def to_nato(words): s = '' for i in range(len(words)): if words[i].lower() in 'abcdefghijklmnopqrstuvwxyz': s += NATO[words[i].upper()] + ' ' elif words[i] == ' ': continue else: s += words[i] + ' ' s = s.replace(' ',' ') return s.strip()
def expanded_form(num): s = '' tens = 1 while num != 0: new_num = num % 10 * tens num = num // 10 tens *= 10 if new_num != 0: s += f'{new_num} ' return ' + '.join(s.split()[::-1])
import argparse import gzip def parse_args(): """ Parse command-line arguments """ parser = argparse.ArgumentParser(description="This script extracts statistics from vcf file.") parser.add_argument( "statistics", metavar="S", type=str, nargs="+", help = "Statistics from the vcf file to be extracte...
#!/usr/bin/env python3 from os import system from random import randint from keyboard import is_pressed # Class for individual card objects class Card: def __init__(self, value, suit, strength): self.value = value self.suit = suit self.strength = strength def __repr__(self): re...
def invert_array(arrayToInvert): arrayInverted = [] for i in arrayToInvert: i = 1 - int(i) arrayInverted.append(i) print(arrayInverted) return arrayInverted
""" This a solution for the problem from https://leetcode.com/problems/average-of-levels-in-binary-tree/ Here is the copy of the problem from leetcode: Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepte...
""" This a solution for the problem from https://leetcode.com/problems/build-binary-expression-tree-from-infix-expression/ Here is the copy of the problem from leetcode: A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or...
""" This a solution for the problem from https://leetcode.com/problems/binary-tree-maximum-path-sum/ Here is the copy of the problem from leetcode: A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at mo...
""" This a solution for the problem from https://leetcode.com/problems/delete-leaves-with-a-given-value/ Here is the copy of the problem from leetcode: Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if it's parent ...
#!/usr/bin/env python3 # # # Copyright (c) 2018, Hiroyuki Ohsaki. # All rights reserved. # # $Id: vector.py,v 1.3 2018/08/02 14:24:45 ohsaki Exp $ # import math class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y def __repr__(self): return f'Vector({self.x!r}, {self.y!r}...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int """ # Three special cases ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ pointer1 = head ...
class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ list_res=[[1]] if numRows==0: return [] if numRows==1: return list_res if numRows==2: list_res.append([1,1]) ...
class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ new_s='' for element in s: if element.isalpha() or element.isalnum(): new_s+=element.lower() return new_s==new_s[::-1]
i = 0 # while (i<35): # print(i) # i+= 1 # if i == 25: # break while True: print(i+1) i+=1 if (i==9): break while True: inp = int(input('Enter the number \n')) if inp>100: print("Number is greater than 100") else: print("Try ag...
class Nodo1: def __init__(self): print ("Constructor de Nodo1") self.dato= "null" self.Siguiente= Nodo1 def getDato(self): return self.dato def setDato(self, dato): self.dato=dato def setSiguiente(self,nodo): self.Siguiente = nodo def getSiguiente(self): return self.Siguiente class Nodo2: """doc...
def pluralize(word): # pass a word in into the fnction """ This is a way to create a "Docstring" inside your funtion to talk about your funciton specs as well as to giv documention for someone to read your code... """ if word[-1] =='y': #check the last letter for y return word[0:-1] + "ies" elif word...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Nov 16 16:33:02 2019 @author: chakra """ #A set is a collection which is unordered and unindexed. #In Python sets are written with curly brackets. thisset = {"apple", "banana", "cherry"} print(thisset) #sets are unordered so that you wont know what ...
# -*- coding:utf-8 -*- ''' 使用sqlite3数据库,python自带,不需要安装 当connect的库不存在时,自动创建一个库 将sql数据以本地文件的形式保存 ''' import sqlite3 conn = sqlite3.connect('test') cuor = conn.cursor() # cuor.execute('create table users(id INTEGER, name VARCHAR(8))') def execute(sql): data = cuor.execute(sql) print(data.fetcha...