text
stringlengths
37
1.41M
def answer(s): hallway = list(s.replace("-", "")) walking_left = hallway.count("<") encounters = 0 while walking_left > 0: for i in hallway: if i == ">": encounters += walking_left else: walking_left -= 1 return encounters * 2 s = ">--...
from collections import deque def inside(n, maze): return 0 <= n[0] < len(maze) and 0 <= n[1] < len(maze[0]) def n_walls(p, maze): return sum([maze[n[0]][n[1]] for n in p]) steps = ((0, 1), (0, -1), (1, 0), (-1, 0)) def next_steps(p, maze): nodes = [(p[-1][0] + dp[0], p[-1][1] + dp[1]) for dp in ste...
def selectionsort(f, lst): if len(lst) <= 1: return lst minimum = get_min(f, lst) return [x for x in lst if x == minimum] \ + selectionsort(f, [x for x in lst if x != minimum]) def get_min(f, lst): min_list = [x for x in lst[1:] if f(x, lst[0])] return lst[0] if min_list == [] e...
class Constant: def __init__(self, val): self.value = val def __string__(self): return str(self.value) def eval(self): return self.value def simple(self): return self class Variable: def __init__(self, idnt, exp): self.id = idnt self.exp = ...
# P3.1 Write a program that reads an integer and prints whether it is negative, zero, or positive # Take the input from user i=int(input('Plase enter an integer (such as negative, zero or positive) : ')) print () if i<0: print (i, ' is a negative number.') elif i>0: print (i, 'is a positive number. ') ...
#This fourth part of code is something that I thought of near the end, after running the code multiple times. #After I ran the code multiple times, I noticed that the same beaches and files were being created over and over again (each time I ran the code). #This code prevents the creation of a file if a file of the...
num=4 row = 0 while row<num: star = row+1 while star>0: print("*",end="") star=star-1 row = row+1 print()
class Employee: def __init__(self, name, employee_id, department, title): self.name = name self.employee_id = employee_id self.department = department self.title = title def __str__(self): return '{} , id={}, is in {} and is a {}.'.format(self.name, self.employee_id, se...
# -*- coding: utf-8 -*- A,B = raw_input().split() if A < B: print '<' elif A > B: print '>' else: print '='
from typing import Tuple, Dict, Any from gptcache.similarity_evaluation import SimilarityEvaluation class SearchDistanceEvaluation(SimilarityEvaluation): """Using search distance to evaluate sentences pair similarity. :param max_distance: the bound of maximum distance. :type max_distance: float :par...
#directed graph graph = { 'a':['c','b'], 'b':['d'], 'c':['e'], 'd':['f'], 'e':[], 'f':[] } def breadthFirstSearch(graph,start): queue = [start] while len(queue) > 0: curr = queue.pop(0) print(curr, end=" ") for neighbour in graph[curr]: queue.append(n...
import logging LOG_FILENAME = 'murder.log' # this is my log file name logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO) #starting my logging def inspected(): logging.info('inside inspected') print('As we sent the blood to be inspected we have found that it directly connects to a man named Nicholas') ...
import time # 计时器 class Timer(object): def __init__(self): self.total_time = 0. self.calls = 0 self.diff = 0. self.average_time = 0. # 一共多少段时间 self.times = {} self.last_time = 0. def tic(self): current_time = time.time() self.last_time = ...
dias={1:'Domingo', 2:'Segunda',3:'Terça',4:'Quarta',5:'Quinta',6:'Sexta',7:'Sábado'} num_digitado = int(input('Digite um número de 1 à 7: ')) if num_digitado >= 1 and num_digitado <= 7: nome_dia = dias.get(num_digitado) print(nome_dia) else: print('Valor não está entre 1 e 7')
""" Util functions to solve a Sudoku grid using the backtracking algorithm Functions used in board.py """ def print_board(board): """ :param board: 2D array representing Sudoku board Prints board """ for row in range(9): r = "" for col in range(9): r += str(board[row][...
# # var="25" # # var1=121 # # var2=12.33 # # # print(int(var)+var1) # # print("Enter a number") # # a=input() # # print("you have entered a number",a) # # print("Enter 1'st Number")1 # # print("Enter 2'st Number") # # a=input() # # b=input() # # print("Sum of two numbers",int(a)+int(b)) # print("Enter a first number") ...
#!/usr/bin/python ################################################################################ # http://www.codeskulptor.org/#user40_DY5aJAiVrF_6.py ################################################################################ # Implementation of classic arcade game Pong import simplegui import random # initia...
# Michael's Calculator from tkinter import* import math import parser import tkinter.messagebox #================================================================================ # Set up the object; Object being the calculator root = Tk() root.title("Scientific Calculator") root.configure(background = "bla...
year = input("What is the year?:") year = int(year) chocolate = input("pick the number of times a week that you would like to have chocolate. Cannot be 0:") chocolate = int(chocolate) print("Multiplying the number by 2") print(str(chocolate) + " times 2") print(chocolate * 2) chocolate = chocolate * 2 print("adding 5.....
def add(a, *b): c =a for i in b: c = c+i print(c) add(5,6,7,8,9)
# Write a loop that never ends, and run it. (To end the loop, press # ctrl-C or close the window displaying the output.) x = 1 while x <= 5: print(x)
#3.8 places=['sawat','kalaam','quetta','parachinar','dIkhan'] print("original list ") print(places) print("\nthis is sorted list in alphabaical order") print(sorted(places)) print("again original list ") print(places) print("\n\nthis is sorted ...
prompt = "\nEnter the topping for pizza you like : " prompt += "\nEnter 'quit' to end the program. " topping = "" while True: topping = input(prompt) if topping=="quit": break else: print("you added " + topping.title()+ " in your toppings !!")
class Restaurant: def __init__(self,restaurant_name,cuisine_type): self.name= restaurant_name self.type=cuisine_type self.number_served = 0 # def set_number_served(self,number): # self.number_served=number # print('we served ' + str(self.number_served) + ' cu...
invitation=['sara', 'john', 'farooq', 'eric', 'ahmed', 'amjad'] print("\nsorry !! i have place for only two person .\n") #remove the extra names by using pop() function print("Sorry "+invitation.pop()+" you are not invited !! ") print("Sorry "+invitation.pop()+" you are not invited !! ") print("Sorry "+invit...
# Ex 3.5 invitation=['john','eric','ali'] print('Hello ,' +invitation[0]+" i am iniviting you at my home for a party ") print('Hello ,' +invitation[1]+" i am iniviting you at my home for a party ") print('Hello ,' +invitation[2]+" i am iniviting you at my home for a party ") print("\nali isn't coming tonight at di...
class User: def __init__(self, first_name, last_name, age): self.f_name = first_name self.l_name = last_name self.age = age self.login_attempts = 0 def describe_user(self): full_name = self.f_name.title() + ' ' + self.l_name.title() user_email = full_n...
favorite_fruits=['Apple','Apricot','Avocado'] if 'Apple' in favorite_fruits: print('i really like apple !!') if 'Apricot' in favorite_fruits: print('i really like apricot !!') if 'Avocado' in favorite_fruits: print('i really like avocado !!') if 'Bannana' in favorite_fruits: print('i really like...
#Problem number 3 ,project euler #Script contributed by Sugam Anand #Website :www.sugamanand.in #!/usr/bin/env python import math print "This script calculates the largest prime factor of the entered number" num=int(raw_input("Enter the Number\n")) for i in range(2,int(math.sqrt(num))+2): # print "*",i,"*...
import math import random import common as cm class Point: """ An immutable 2D point. """ def __init__(self, x=0., y=0., r=100., order=-1): self.x = x self.y = y self.r = r self.order = order def distance(self, A): return math.sqrt((A.x - self.x) ** 2 + (A...
from random import randint a = int(input("Введіть діапазон(мінімальне) = ")) b = int(input("Введіть діапазон(максимальне) =")) m = int(input("Скільки елементів потрібно в списку: ")) x = int(input("Введіть шукане число ")) l = [] y = 1 while y <= m: l.append(randint(a, b)) y += 1 print(l) print("---------...
n=int(input("Введіть число ")) d1 = n % 10 n = n // 10 d2 = n % 10 n = n // 10 d3 = n % 10 if d1+d2+d3==18 : print("сума чисел дорівнює 18") else : print("сума чисел не дорівнює 18")
n = int(input("Bведіть n: ")) d1 = n % 10 n = n // 10 d2 = n % 10 n = n // 10 d3 = n % 10 print("Сума цифр числа:", d1 + d2 + d3)
s = input("введіть ") if 'j' in s: i = s.replace('j', 'k') else : s.ljust(1, 'f') s.rjust(1, 'f') i = s.replace('j', 'f') print(i)
n=int(input("n= ")) if (n>9) and (n<100): if n%10 == 0: print("остання цифра 0") else: print("остання цифра не 0") else: print("не двохзначне")
n=int(input("n= ")) k=n%2 if k == 0: print("Парне") else: print("Не парне")
print("enter two numbers") x=int(input()) y=int(input()) sub=x-y print("result",sub) if sub>25: print(x*y) else: print(x/y)
number = int(input()) while number not in range(0, 10): print('Неверный ввод. Число должно быть [0, 10). Попробуйте снова') number = int(input()) else: print(number ** 2)
def sqr_but_not_thirteen(n): if n == 13: raise ValueError('number 13 is caught') elif not 1 <= n <= 100: raise ValueError('your number is out of [1-100]') else: return n ** 2 try: num = int(input("input number [1-100]: ")) print(f'the square of {num} is {sqr_but_not_thirtee...
import requests from bs4 import BeautifulSoup import csv import shutil def image_downloader(url, file_path, file_name): """download image from url to specified file path""" response = requests.get(url, stream=True) with open(file_path + "/" + file_name, 'wb') as out_file: shutil.copyfileobj(respon...
import numpy as np def interpolate_points(function_points, interp_x): """ Linearly interpolates y values between points for given x values :param function_points: list of points which define the function whose range is [a,b] :param interp_x: list of x points for which you want to get interpolated valu...
import requests from bs4 import BeautifulSoup import sys # enter the url to be scraped url_to_scrape = 'https://www.snapdeal.com/product/micromax-50z9999uhd-127-cm-50/649491902099#bcrumbLabelId:64' # send a request to the url response = requests.get(url_to_scrape) # convert it to a soup object soup = BeautifulSoup(r...
# -*- coding:utf-8 -*- from threading import Thread, Lock import time class Ob(object): def __init__(self): self.v = 0 self.lock = Lock() def count(self): with self.lock: for i in range(self.v): print i , print "" self.v += 1 class Counter(Thread): def __init__(self,share_object): super(...
nombre = input("¿Cual es su nombre?") print("Bienvenido ", nombre)
""" Martian dice impelmentation. """ import random class Cube(object): def __init__(self, up=None): self.up = up def roll(self): sides = ['tank', 'deathray', 'deathray', 'human', 'cow', 'chicken'] self.up = random.choice(sides) def __repr__(self): return str(self.up) def __str__(self): r...
import numpy as np import warnings def swapRows(A, i, j): """ interchange two rows of A operates on A in place """ tmp = A[i].copy() A[i] = A[j] A[j] = tmp def relError(a, b): """ compute the relative error of a and b """ with warnings.catch_warnings(): ...
# Supervised learning model for CAMMY (a colour-mixing cyber-physical system) # Model Y: Finding Y (yellow) label based on RGB values as features import numpy as np import matplotlib.pyplot as plt import sklearn import csv import pandas as pd import pickle # Source: https://colab.research.google.com/dri...
import torch import numpy as np from matplotlib import pyplot as plt ''' Function used to visualize the non-convex function used in our empirical evaluation: y = (3/2)*(x)**2 + np.exp(0.6-1 / (100*(x-1)**2)) - 1.5 Inputs: n_samples - number of the samples to generate n_features - dimensionality of the data t...
def solve(meal, tip, tax): x = meal * (tip / 100) y = meal * (tax / 100) total = meal + x + y print(round(total)) meal = float(input()) tip = int(input()) tax = int(input()) solve(meal, tip, tax)
class Employee: '所有员工的基类' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary #Employee.empCount += 1 def intt(self,ss): self.e1=Employee(self.name, self.salary) self.e1.name=self.name+ss Employee.empCount=Employee.e...
import sqlite3 connection = sqlite3.connect("aquarium.db") cursor = connection.cursor() end = 0 def create(): new = input("do you want to make a phone number list [y/n]: ") if new == "y" or new == "Y": name = input("enter him/her name: ") number = int(input("enter him/her num...
# Asks the user for the list of 3 friends # For each friend, will tell the user whether they are nearby # For each friend we'll save the friend to 'nearby_friends.txt' # hint: readLines() friends = input('Enter three friend names, separated by commas(no spaces, please): ').split(',') people = open('people.txt' , 'r'...
# Аннотации служат для повышения информативности исходного кода # Контроль типов без использования аннотаций # Пример: name = "Alex" # type: str name = "Alex" print(name) name = 10 print("name")
""" fit a linear regression model to a pixel vector image representation and then use the linear model to reconstruct the image. goals: 1. get familiar with tensorflow 2. see what happens with a linear model """ from PIL import Image import tensorflow as tf import numpy as np import traceback impo...
# Mersenne numbers can only be prime if their exponent p is prime. # However '11' is the prime, but for p=11, the Mersenne number isn't prime. We can test if a Mersenne number is prime using the Lucas-Lehmer test def mersenne_number(p:int): return 2**p - 1 def lucas_lehmer(p:int): M = 2**p-1 ll = [] i...
from src.route import Route def read_from_file(filename): """ Reads the lines from the file and returns an the matrix dimensions, the integer matrix, the number of routes and a list of routes from the read data :param filename: The path of the data file """ no_rows = 0 no_cols = 0 mat...
#coding:utf-8 #分类器 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from TensorFlowDemo import TFdemo5 #添加层的方法 #number 1-10 mnist = input_data.read_data_sets('MNIST_data',one_hot=True) #define placeholder for inputs to network xs = tf.placeholder(tf.float32,[None,784]) #28*28 ys = tf....
#Условие #В школе решили набрать три новых математических класса. Так как занятия по математике у них проходят в одно и то же время, было решено выделить кабинет #для каждого класса и купить в них новые парты. За каждой партой может сидеть не больше двух учеников. Известно количество учащихся в каждом из трёх классов...
input_file=open("input.txt","r") output_file=open("output.txt","w") for line_str in input_file: new_str='' for char in line_str: new_str=char+new_str print(new_str,file=output_file) print("Line:{:s} is reversed to {:s}". format(line_str,new_str)) input_file.close() output_file.close()
name=input("Enter your name please: ") rev_name=name[::-1] print(rev_name)
my_str=input("Input a string: ") index_int = 0 result_str = '' while index_int < (len(my_str) - 1): if my_str[index_int] > my_str[index_int + 1]: result_str = result_str + my_str[index_int] else: result_str = result_str * 2 index_int += 1 print(result_str)
import tkinter as tk from const import FIELD_HEIGHT, FIELD_WIDTH, PLAYER_SIZE, PLAYER_COLORS, BACKGROUND_COLOR, BULLET_SIZE, BULLET_COLORS class View: def __init__(self, canvas, data): # 描画しかしないのでcanvasだけでよい # windowオブジェクトはイベントの割り当てなどに必要だが描画クラスでは使わない self.canvas = canvas self.canvas.create_rectangle(0, 0, FIE...
import pdfkit import easygui import tkFileDialog from Tkinter import * import os import urllib2 #Made by Will Beddow for a client on fiverr.com #For more information about me go to http://willbeddow.com #To hire Will, go to http://fiverr.com/willcbeddow root = Tk() root.withdraw() def overmain(): def convert(filetype...
import pandas as pd from sklearn import preprocessing from sklearn.linear_model import LinearRegression from sklearn import model_selection label_enc = preprocessing.LabelEncoder() data=pd.read_csv("weight-height.csv") print(data.columns) data1=data['Gender'] label_enc.fit(data1) data['Gender']=label_enc.trans...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __init__(self): self.sum = 0 def sumEvenGrandparent(self, root: TreeNode) -> int: ...
#快速排序 def quick_sort(lst,start,end): if start>=end: return mid=lst[start] low=start high=end while low<high: while low<high and mid<=lst[high]: high-=1 lst[low]=lst[high] while low<high and lst[low]<mid: low+=1 lst[...
lists=[["Коля", 14],["Дэни", 16],["Максим", 15]] children=input("Введите имя и возраст ученика: ") children=children.split(' ') print(children) lists.append(children) print(lists)
for _ in xrange(input()): #testacases numOfSongs = input() #this line here is just to make online judge a fool songsUnsorted = map(int, raw_input().split())# takes input of songs uncleJhonyPosInSongsUnsorted = input()# position of UJ song in the playlist uJinUnsorted = songsUnsorted[uncleJhonyPosInSongsUnsorted-1]#...
"""В строке найдите все серии подряд идущих пробелов и замените каждую на один пробел.""" def spaces(): str = input('Введіть текст: ') list_str = str.split() newstr = '' for el in list_str: newstr += (el+" ") newstr.rstrip() print(newstr) if __name__ == '__main__': ...
v1 = float(input("Primeiro valor: ")) v2 = float (input("Segundo valor: ")) pergunta = 0 while pergunta < 5: print(""" [1] SOMAR [2] MULTIPLICAR [3] MAIOR [4] NOVOS NÚMEROS [5] SAIR DO PROGRAMA""") pergunta = int(input(">>>>> Qual é sua opção? ")) if pergunta == 4: print("Informe ...
from time import sleep from random import randint print("-----------Jogo do par ou ímpar!------------") cont = 0 while True: print("""Escolha : [0] PAR [1] ÍMPAR""") opção = int(input("Qual é sua opção? ")) while opção > 1: print("Opção inválida! Escolha [0] para 'par' e [1] para 'ímpar'.") ...
listagem = ('Lápis', 1.50, 'Borracha', 6.00, 'Caderno', 12.00, 'Estojo', 16.50, 'Lapiseira', 17.50) print('--' * 20) print(f'{"LISTAGEM DE PREÇOS":^40}') print('--' * 20) for item in range(0, len(listagem)): if item % 2 == 0: print(f'{listagem[item]:.<30}', end='') else: print(f'R$ {listagem[ite...
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] pares = [] soma = soma3 = maior = 0 for l in range(0,3): for c in range(0,3): matriz[l][c] = int(input(f'Digite um valor para [{l} e {c}]: ')) if matriz[l][c] % 2 == 0: pares.append(matriz[l][c]) for l in range(0,3): for c in range(0,3): ...
from time import sleep def contador(início, fim, passo): if passo < 0: passo *= -1 if passo == 0: passo = 1 print('Contagem de {} a {} de {} em {}: '.format(início, fim, passo, passo)) if fim > início: cont = início while cont <= fim: print(f'{cont...
print("--------CADASTRO DE PESSOAS---------") maiores = tot20 = totH = pessoas = 0 while True: pessoas += 1 idade = int(input("Digite sua idade: ")) sexo = str(input("Digite seu sexo [M/F]: ")).upper().strip()[0] while sexo not in "MFmf": sexo = str(input("Digite seu sexo [M/F]: ")).upper().stri...
## Animal is-a object (yes sort of confusing) look at the extra credit: class Animal(object): pass class Dog(Animal): def __init__(self,name): ## dog has-a name self.name = name class cat(Animal): def __init__(self,name): ## cat is-s animal, cat has-a named self.name = na...
days = "mon, tue, wed, thur, fri, sat, sun" months = "Jan\nFeb\nMar\nApril\nMay\nJune\nJuly\nAug\nsept\nOct\nNov\nDec" print("here are your days :", days) print("here are your months :", months) print(""" blah bdad fkgkngknkdngjkkgnksg fnsknf ksnfksfn nksdnfk""")
#class Parent(object): # def implicit(self): # print("Parent implicit") #class Child(Parent): # pass #dad = Parent() #son = Child() #dad.implicit() #son. implicit() #class Parent(object): # def override(self): # print("Parent override()") #class Child(Parent): # def override(self): # ...
cars = 100 space_in_a_car = 4 driver = 30 passanger = 90 cars_not_driven = cars - driver cars_driven = driver carpool_capacity = cars_driven*space_in_a_car average_passanger_per_car = passanger/cars_driven print("there are", cars, "cars available") print("there are only", driver, "drivers available") print("there will ...
S = input().rstrip() for i in range(len(S)): if S[i] == 'I' or S[i] == 'l' or S[i] == 'i': print('caution') exit() print(S)
n = len(input()) MAX = 11 if n >= MAX: print("OK") else: print(MAX - n)
print "Hello LUV!" potential_content = raw_input("Name one of your urgencies?") potential_collegues = raw_input("Who shares this urgency with you?") potential_methode = raw_input("How do you want to approach this shared urgency?") if len(potential_content) > 0 and potential_content.isalpha(): if len(potential_col...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 19 21:35:24 2018 @author: dc """ grid = [[1,0],[0,2]] top = 0 front = 0 for i in grid: top += len(i) front += max(i) ziped = list(zip(*grid)) side = 0 for i in range(len(ziped)): side += max(ziped[i]) print (top+front+side)
import numpy as np list1 = [0, 1, 2, 3, 4] # Numpy array arid = np.array(list1) ''' numpy arrays are designed to handle vectorized operation python list not, array size can not be increased once defined although list size can be increased using append''' print(arid) # adding in array is easy example: adding 2 to each e...
from collections import Counter word = input() word = word.lower() c = Counter(word) commons = c.most_common(2) if len(commons) == 1: print(commons[0][0].capitalize()) else: if commons[0][1] == commons[1][1]: print("?") else: print(commons[0][0].capitalize())
### Python program to print topological sorting of a DAG from collections import defaultdict #Class to represent a graph class Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = dict() self.Finished = dict() self.cycle ...
import math class Punto: cuadrante = 0 def __init__ (self,ejeX=0,ejeY=0): self.ejeX=ejeX self.ejeY=ejeY def __str__(self): return "x = {} y = {} ".format(self.ejeX,self.ejeY) def mostrar_cuadrante(self): if(self.ejeX > 0 and self.ejeY > 0): self.cuadr...
#Star in square class Patterns: def __init__(self): self.n = 6 self.list1 = ["A", "B", "C", "D", "E"] self.list2 = [5,4,3,2,1] self.list3 = ['E', 'D', 'C', 'B', 'A'] def star_square(self): for i in range (1, self.n): for j in range(1, self.n): ...
#Scale #Selecting the Scale scale = int(input(""" 1. Celcius to Farenheit 2.Farenheit to celcius Your Choice: """)) #Celcius to Farenheit Scale if scale == 1: celcius = float(input("Enter the celcius:")) farenheit = 0 farenheit = (celcius *...
''' import re num=input('enter the number:') def number(num): pattern=re.compile('[0/91]?[7-9][0-9]{10}') return pattern.match(num) if(isValid(num)): print('valid number') else: print('WARNING...print valid number') number(num) import re num=input('enter the p...
import re sentence='''Magesh is 22 ,Lionel is 23,Saleek is 24, and Guhan is 25''' ages=re.findall(r'\d{1,3}',sentence) Names=re.findall(r'[A-Z][a-z]*',sentence) dict={} x=0 for i in Names: dict[i]=ages[x] x+=1 print(dict)
#Binary Sort list_1 = [2,5,1,10,90,6,12,78,6] index = 0 temp = 0 #length = len(list_1) for count in list_1: if list_1[index] > list_1[index+1]: temp = list_1[count] list_1[count + 1] = list_1[count] list_1[count] = temp print(list_1)
from datetime import datetime def timeanddates(): x = datetime.now() print("start time", x) while True: try: start = int(input("enter the starting value:")) while True: try: ending = int(input("enter the ending value:")) ...
# Pseudo # def perm(n, k): # if k == n: # print array # else: # for i in range(k, n): # swap(k, i) # arr[k], arr[i] 교환 # perm(n, k+1) # n: 원소의 갯수, k: 현재까지 교환된 원소의 갯수 # swap(k, i) # 리턴할 때 원래 자리로 되돌려놔야 함 # perm(3, 0)으로 돌려보면 # [1, 2, 3]으로 시작 # swap(...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: if not head or m == n: return head root = ...
# 파이썬식 편법: 배열로 만들어버리기 def isPalindrome_1(head) -> bool: q = [] node = head while node is not None: q.append(node.val) node = node.next n = len(q) for i in range(n//2): if q[i] != q[n-i-1]: return False return True # Definition for singly-linked list. class ...
# 반복 def search(self, nums: List[int], target: int) -> int: n = len(nums) l, r = 0, n-1 mid = n // 2 while l <= r: if target < nums[mid]: r = mid - 1 elif target > nums[mid]: l = mid + 1 else: return mid mid = (l + r) // 2 return -...
from metaprogramming.dog import Dog class Fido(Dog): def __init__(self): Dog.__init__(self, breed="Labrador", name="Fido", owner="Alice", age=2) def fido_example1(): fido1 = Fido() fido2 = Fido() print(fido1) print(fido2) print(fido1.get_age()) fido1.have_birthday() print(fi...
from random import randint num = randint (1,100) print ('welcome to guess number game!') bingo = False while bingo ==False: answer = int(input ('enter your number: ')) if answer > num: print ('too big') elif answer < num: print ('too small') else: print ('bingo') break print ('Congratulation!')...
题目: Given a binary tree, return the postorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [3,2,1] Follow up: Recursive solution is trivial, could you do it iteratively? 1.Recursive # Definition for a binary tree node. # class TreeNode(object): # def __init_...