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 = ">----<" print(answer(s)) #10 # l = list(s.replace("-", "")) # if len(l) == 0: # return 0 # while l[0] == "<": # del(l[0]) # while l[-1] == ">": # del(l[-1]) # # else: # return l
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 steps] paths = [p + [tuple(n)] for n in nodes if inside(n, maze) and n not in p] return [p for p in paths if n_walls(p, maze) <= 1] def overlap(p0, p1, maze): return any(p0[-1] in p and n_walls(p0, maze) >= n_walls(p, maze) for p in p1) def answer(maze): p1 = deque([[(0, 0)]]) g = (len(maze) - 1, len(maze[0]) - 1) while True: new_p = [p for p in next_steps(p1.pop(), maze) if not overlap(p, p1, maze)] if any(p[-1] == g for p in new_p): p1 = new_p break p1.extendleft(new_p) for p in p1: if p[-1] == g: return len(p)
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 == [] else get_min(f, min_list) def bubblesort(f, lst): if len(lst) <= 1: return lst lst = bubble_aux(f, lst) return bubblesort(f, lst[:-1]) + [lst[-1]] def bubble_aux(f, lst): if len(lst) <= 1: return lst return [lst[1]] + bubble_aux(f, [lst[0]] + lst[2:]) if f(lst[1], lst[0]) \ else [lst[0]] + bubble_aux(f, lst[1:]) def quicksort(f, lst): if len(lst) <= 1: return lst return quicksort(f, [x for x in lst[1:] if f(x, lst[0])]) + [lst[0]] + \ quicksort(f, [x for x in lst[1:] if not f(x, lst[0])]) print(selectionsort(lambda x, y : x < y, [1, 2, 7, 3, 4, 1])) print(bubblesort(lambda x, y : x < y, [2, 7, 3, 1, 4, 1])) print(quicksort(lambda x, y : x < y, [2, 7, 1, 3, 4, 1]))
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 = exp def __string__(self): return self.id def eval(self): return self.exp.eval() def simple(self): return self.exp.simple() if isinstance(Constant) else self.exp class Sum: def __init__(self, exp_1, exp_2): self.exp_1 = exp_1 self.exp_2 = exp_2 def __string__(self): return str(self.exp_1) + '+' + str(self.exp_2) def eval(self): return self.exp_1.eval() + self.exp_2.eval() def simple(self): eval_1 = self.exp_1.simple() eval_2 = self.exp_2.simple() if isinstance(eval_1, Constant) and eval_1 == 0: return eval_2 if isinstance(eval_2, Constant) and eval_2 == 0: return eval_1 return self class Product: def __init__(self, exp_1, exp_2): self.exp_1 = exp_1 self.exp_2 = exp_2 def __string__(self): return str(self.exp_1) + '*' + str(self.exp_2) def eval(self): return self.exp_1.eval() * self.exp_2.eval() def simple(self): eval_1 = self.exp_1.simple() eval_2 = self.exp_2.simple() if isinstance(eval_1, Constant) and eval_1 == 1: return eval_2 if isinstance(eval_2, Constant) and eval_2 == 1: return eval_1 return self
# 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. ') else: print (i, ' ia a zero')
#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 same name already exists. #Name of the test file name = "Spiaggia_dei_Conigli-Lampedusa_Islands_of_Sicily_Sicily" #Setup import os.path #Location of the test file test = str("C:\Users\wmelinda\Documents\#JUMP Investors" + '\\' + name + ".txt") print test #If the file exists, print "yes" #If the file does not exist, print "no" #I was mainly testing to make sure that only a portion of the code continues to read next steps (e.g. if no file, code continues through) #So, because I had a test file already saved, when I ran the code = printed "no" and also printed "continue" if os.path.isfile(test): continue else: print "no" pass print "continue"
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, self.department, self.title) def get_employees(): # Create three employee objects emp1 = Employee(name='Susan Meyers', employee_id='47899', department='Accounting', title='Vice President') emp2 = Employee(name='Mark Jones', employee_id='39119', department='IT', title='Programmer') emp3 = Employee(name='Joy Rogersr', employee_id='81774', department='Manufacturing', title='Engineer') print(emp1, sep='/n/n') print(emp2, sep='/n/n') print(emp3, sep='/n/n') if __name__ == '__main__': get_employees()
# -*- 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 :param positive: if the larger distance indicates more similar of two entities, It is True. Otherwise it is False. :type positive: bool Example: .. code-block:: python from gptcache.similarity_evaluation import SearchDistanceEvaluation evaluation = SearchDistanceEvaluation() score = evaluation.evaluation( {}, { "search_result": (1, None) } ) """ def __init__(self, max_distance=4.0, positive=False): self.max_distance = max_distance self.positive = positive def evaluation( self, src_dict: Dict[str, Any], cache_dict: Dict[str, Any], **_ ) -> float: """Evaluate the similarity score of pair. :param src_dict: the query dictionary to evaluate with cache. :type src_dict: Dict :param cache_dict: the cache dictionary. :type cache_dict: Dict :return: evaluation score. """ distance, _ = cache_dict["search_result"] if distance < 0: distance = 0 elif distance > self.max_distance: distance = self.max_distance if self.positive: return distance return self.max_distance - distance def range(self) -> Tuple[float, float]: """Range of similarity score. :return: minimum and maximum of similarity score. """ return 0.0, self.max_distance
#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(neighbour) breadthFirstSearch(graph,'a')
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') chance5 =str(input('Do you want to bring him in for questioning, Yes or No: ')) if chance5 == 'Yes' or chance5 =='yes': print('You bring him in for questioning and he breaks down confessing that he murdered the earl for money.') final = str(input('Do you want to arrest him? yes or no: ')) if final == 'Yes' or final == 'yes': print('Excellent job Detective! You are promoted') else: print('Game Over') else: print('Are u crazy? You cannot be a detective')
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 = current_time def toc(self, average=True, content=""): current_time = time.time() self.diff = round(current_time - self.last_time, 2) self.last_time = current_time # 缩短不该计算的耗时 if content == '行提取图绘制' and self.diff > 0.1: self.diff = round(self.diff - 0.1, 2) self.times[content] = self.diff print("{}: {}".format(content, self.diff)) self.total_time += self.diff self.calls += 1 self.average_time = self.total_time / self.calls if average: return self.average_time else: return self.diff def __str__(self): text = "" index = 1 for key in self.times: text += " " + str(index) + ": " + key + "耗时:" + str(self.times[key]) + "s<br>" index += 1 text += "总耗时:" + str(round(self.total_time, 2)) + "s" return text
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][col]) + " " print(r) def find_vacant_cell(board): """ :param board: 2D array representing Sudoku board :return: returns cordinates of the first vacant position Searches board for a 0/vacant position. """ for row in range(9): for col in range(9): if board[row][col] == 0: vacant_position = [row, col] return vacant_position return [-1, -1] "checks if the number exists in the row, the column, and the sub 3x3 matrix" def check_position(number, row, col, board): """ :param number: number to be entered into the board :param row: number row position :param col: number col position :param board: 2D array representing Sudoku board :return: True if it number follows rule of sudoku and False if not Checks if entering the number at the row, col position into the board follows the rules of Sudoku """ for c in range(9): if board[row][c] == number: return False for r in range(9): if board[r][col] == number: return False row_start = (row // 3) * 3 col_start = (col // 3) * 3 for r in range(row_start, row_start + 3): for c in range(col_start, col_start + 3): if board[r][c] == number: return False return True def check_board(board): """ :param board: 2D array representing Sudoku board :return: True if board is filled False if not checks if the board is completely filled(no 0s) """ for row in range(9): for col in range(9): if board[row][col] == 0: return False return True def find_number(board, num): """ :param board: 2D array representing Sudoku board :param num: number to be found :return: positions of all cells that have the num in it Used to find the position of all cells with the num in it """ positions = [] for row in range(9): for col in range(9): if board[row][col] == num: positions.append((col, row)) return positions def solve(board): """ :param board: 2D array representing Sudoku board :return: True if solved, False if the board is not solvable Solves the Sudoku board using recursion and backtracking Backtracking description: Finds first vacant cells using find_vacant_cell into vacant_position then on that current cell for each number 1-9 check if it satisfies the rules of sudoku using check_position() if the rules are satisfied insert it into the board then call solve using the updated board and proceed. If number does not satisfy the rules of Sudoku reset value back to 0. """ vacant_position = find_vacant_cell(board) if vacant_position[0] == -1: return True row = vacant_position[0] col = vacant_position[1] for i in range(1, 10): if check_position(i, row, col, board): board[row][col] = i if solve(board): return True board[row][col] = 0 return False
# # 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") # a=input() # print("Enter a second number") # b=input() # print("multiple of numbers",int(a)*int(b)) a = "Hello world there is my new vlog!" # print(len(a)) # print(a[0:3]) # print(a[::-2]) # print(a.isalpha()) print(a.find("new"))
#!/usr/bin/python ################################################################################ # http://www.codeskulptor.org/#user40_DY5aJAiVrF_6.py ################################################################################ # Implementation of classic arcade game Pong import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGHT = PAD_HEIGHT / 2 LEFT = False RIGHT = True # my initialize globals time_tick = 0 scale = 100 paddle_speed = 6 ball_pos = [WIDTH / 2, HEIGHT / 2] ball_rps = [ball_pos[0]*scale, ball_pos[1]*scale] ball_vel = [int(5.55*scale), int(5.55*scale)] # pixels per update (1/60 seconds) paddle1_vel = 0 paddle1_pos = HEIGHT / 2 paddle2_vel = 0 paddle2_pos = HEIGHT / 2 # initialize ball_pos and ball_vel for new bal in middle of table # if direction is RIGHT, the ball's velocity is upper right, else upper left def spawn_ball(direction): global ball_pos, ball_vel # these are vectors stored as lists #end def spawn_ball(direction) # define event handlers def new_game(): global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers global score1, score2 # these are ints #end def new_game() def check_pos(ball_pos): global ball_vel, paddle1_pos, paddle1_pos if BALL_RADIUS > ball_pos[1] or ball_pos[1] > (HEIGHT - BALL_RADIUS - 1): ball_vel[1] = -int(ball_vel[1]*1.01) #end if BALL_RADIUS > ball_pos[1] or ball_pos[1] > (HEIGHT - BALL_RADIUS) if (BALL_RADIUS + PAD_WIDTH) > ball_pos[0]: ball_vel[0] = -int(ball_vel[0]*1.01) if ball_pos[1] > paddle1_pos + PAD_HEIGHT + 1: print "FAIL1" #end if ball_pos[1] > paddle1_pos - PAD_HEIGHT elif ball_pos[1] < paddle1_pos - PAD_HEIGHT - 1: print "FAIL2" #end if ball_pos[1] > paddle1_pos - PAD_HEIGHT #end if (BALL_RADIUS + PAD_WIDTH) > ball_pos[0] if ball_pos[0] > (WIDTH - PAD_WIDTH - BALL_RADIUS - 1): ball_vel[0] = -int(ball_vel[0]*1.01) if ball_pos[1] > paddle2_pos + PAD_HEIGHT + 1: print "FAIL1" #end if ball_pos[1] > paddle2_pos - PAD_HEIGHT elif ball_pos[1] < paddle2_pos - PAD_HEIGHT - 1: print "FAIL2" #end if ball_pos[1] > paddle2_pos - PAD_HEIGHT #end if ball_pos[0] > (WIDTH - PAD_WIDTH - BALL_RADIUS - 1) #end def check_pos(): def update_ball(): global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel ball_rps[0] += ball_vel[0] ball_rps[1] += ball_vel[1] x = int(ball_rps[0] / scale) y = int(ball_rps[1] / scale) check_pos([x, y]) ball_pos[0] = x ball_pos[1] = y #end def update_ball(canvas) def update_paddles(): global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel if (HEIGHT - PAD_HEIGHT/2 - 1) > paddle1_pos and paddle1_vel > 0: paddle1_pos += paddle1_vel elif PAD_HEIGHT/2 < paddle1_pos and paddle1_vel < 0: paddle1_pos += paddle1_vel if (HEIGHT - PAD_HEIGHT/2 - 1) > paddle2_pos and paddle2_vel > 0: paddle2_pos += paddle2_vel elif PAD_HEIGHT/2 < paddle2_pos and paddle2_vel < 0: paddle2_pos += paddle2_vel #end def update_paddles() def draw_ball(canvas): canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White") #end def draw_ball(canvas, ball_pos) def draw_paddles(canvas): global paddle1_pos, paddle_pos2 canvas.draw_polygon([(0, paddle1_pos - HALF_PAD_HEIGHT), (PAD_WIDTH, paddle1_pos - HALF_PAD_HEIGHT), (PAD_WIDTH, paddle1_pos + HALF_PAD_HEIGHT), (0, paddle1_pos + HALF_PAD_HEIGHT)], 1, "White", "White") canvas.draw_polygon([(WIDTH, paddle2_pos - HALF_PAD_HEIGHT), (WIDTH - PAD_WIDTH, paddle2_pos - HALF_PAD_HEIGHT), (WIDTH - PAD_WIDTH, paddle2_pos + HALF_PAD_HEIGHT), (WIDTH, paddle2_pos + HALF_PAD_HEIGHT)], 1, "White", "White") #end def draw paddles(canvas) def draw(canvas): global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel # draw mid line and gutters canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White") canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White") canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White") # update ball # update_ball() # draw ball draw_ball(canvas) # update paddle's vertical position, keep paddle on the screen # draw paddles draw_paddles(canvas) # determine whether paddle and ball collide # draw scores #end def draw(canvas) def keydown(key): global paddle1_vel, paddle2_vel, paddle_speed if key == simplegui.KEY_MAP["w"]: paddle1_vel -= paddle_speed elif key == simplegui.KEY_MAP["s"]: paddle1_vel += paddle_speed elif key == simplegui.KEY_MAP["down"]: paddle2_vel += paddle_speed elif key == simplegui.KEY_MAP["up"]: paddle2_vel -= paddle_speed #end def keydown(key) def keyup(key): global paddle1_vel, paddle2_vel if key == simplegui.KEY_MAP["w"]: paddle1_vel = 0 elif key == simplegui.KEY_MAP["s"]: paddle1_vel = 0 elif key == simplegui.KEY_MAP["down"]: paddle2_vel = 0 elif key == simplegui.KEY_MAP["up"]: paddle2_vel = 0 #end def keyup(key) # define event handlers def tick(): global time, ball_rps time_tick = time_tick + 1 update_ball() update_paddles() if 0 == time_tick % 10: print "%03d: pos[%d,%d], vel[%d,%d]" % (time_tick, ball_pos[0], ball_pos[1], ball_vel[0], ball_vel[1]) #end def tick() timer = simplegui.create_timer(60, tick) # create frame frame = simplegui.create_frame("Pong", WIDTH, HEIGHT) frame.set_draw_handler(draw) frame.set_keydown_handler(keydown) frame.set_keyup_handler(keyup) # start frame new_game() frame.start() # register event handlers timer.start() #EOF # vim: syntax=python:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
# 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 = "black") root.resizable(width = False, height = False) root.geometry("480x568+0+0") calc = Frame(root) calc.grid() #================================================================================ # Creating a text display for the calculator textDisplay = Entry(calc, font=('arial',20,'bold'), bg="light gray",bd=30, width=29, justify=RIGHT) textDisplay.grid(row=0, column=0, columnspan=4, pady=1) textDisplay.insert(0, "0") # Adding buttons to the calculator numberpad = "789456123" i = 0 btn = [] for j in range(2,5): for k in range(3): btn.append(Button(calc, width=6, height=2, font=('arial',20,'bold'), bd=4, bg="light gray", text=numberpad[i])) btn[i].grid(row=j, column=k, pady=1) i += 1 #================================================================================ # Creating buttons for various operations on the standard calculator btnClear = Button(calc, text=chr(67), width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=1,column=0,pady=1) btnAllClear = Button(calc, text=chr(67) + chr(69), width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=1,column=1,pady=1) btnSq = Button(calc, text="√", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=1,column=2,pady=1) btnAdd = Button(calc, text="+", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=1,column=3,pady=1) btnSub = Button(calc, text="-", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=2,column=3,pady=1) btnMult = Button(calc, text="*", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=3,column=3,pady=1) btnDiv = Button(calc, text=chr(247), width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=4,column=3,pady=1) btnPM = Button(calc, text=chr(177), width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=5,column=0,pady=1) btnZero = Button(calc, text="0", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="light gray").grid(row=5,column=1,pady=1) btnDot = Button(calc, text=".", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="light gray").grid(row=5,column=2,pady=1) btnEquals = Button(calc, text="=", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="orange").grid(row=5,column=3,pady=1) #================================================================================ # Add scientific functions to the calculator btnPi = Button(calc, text="π", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=1,column=4,pady=1) btnCos = Button(calc, text="cos", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=1,column=5,pady=1) btnTan = Button(calc, text="tan", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=1,column=6,pady=1) btnSin = Button(calc, text="sin", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=1,column=7,pady=1) btn2Pi = Button(calc, text="2π", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=2,column=4,pady=1) btnCosh = Button(calc, text="cosh", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=2,column=5,pady=1) btnTanh = Button(calc, text="tanh", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=2,column=6,pady=1) btnSinh = Button(calc, text="sinh", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=2,column=7,pady=1) btnLog = Button(calc, text="log", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=3,column=4,pady=1) btnExp = Button(calc, text="Exp", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=3,column=5,pady=1) btnMod = Button(calc, text="Mod", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=3,column=6,pady=1) btnE = Button(calc, text="e", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=3,column=7,pady=1) btnLog2 = Button(calc, text="log2", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=4,column=4,pady=1) btnDeg = Button(calc, text="deg", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=4,column=5,pady=1) btnACosh = Button(calc, text="acosh", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=4,column=6,pady=1) btnASinh = Button(calc, text="asinh", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=4,column=7,pady=1) btnLog10 = Button(calc, text="log10", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=5,column=4,pady=1) btnLoglp = Button(calc, text="log1p", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=5,column=5,pady=1) btnexpml = Button(calc, text="ecpm1", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=5,column=6,pady=1) btnlgamma = Button(calc, text="lgamma", width=6, height=2, font=('arial',20,'bold'), bd=4, bg="tan").grid(row=5,column=7,pady=1) #================================================================================ # Exit function allows the calculator to be closed by selecting File->Exit def iExit(): iExit = tkinter.messagebox.askyesno("Scientific Calculator", "Confirm if you want to exit") if iExit > 0: root.destroy() return # Scientific function will change the calculator to a Scientific layout def Scientific(): root.resizable(width=False, height=False) root.geometry("958x568+0+0") # Standard function will change the calculator to a Standard layout def Standard(): root.resizable(width=False, height=False) root.geometry("480x568+0+0") #================================================================================ # Create the menu bar menubar = Menu(calc) #================================================================================ # Arranging the 'File' menu filemenu = Menu(menubar, tearoff = 0) # Adds the 'File' option to the window menubar.add_cascade(label = "File", menu = filemenu) # The 'File' menu lets you choose standard option filemenu.add_command(label = "Standard", command = Standard) # The 'File' menu lets you choose scientific option filemenu.add_command(label = "Scientific", command = Scientific) # Seperates with a line; Exit will appear below line filemenu.add_separator() # The 'File' menu lets you choose the exit option filemenu.add_command(label = "Exit", command = iExit) #================================================================================ # Arranging the 'Edit' menu editmenu = Menu(menubar, tearoff = 0) # Adds the 'Edit' option to the window menubar.add_cascade(label = "Edit", menu = editmenu) # The 'Edit' menu lets you choose cut editmenu.add_command(label = "Cut") # The 'Edit' menu lets you choose copy editmenu.add_command(label = "Copy") # Adds separator below copy editmenu.add_separator() # The 'Edit' menu lets you paste editmenu.add_command(label = "Paste") #================================================================================ # Create a Help menu helpmenu = Menu(menubar, tearoff = 0) menubar.add_cascade(label = "Help", menu = helpmenu) helpmenu.add_command(label = "View Help") #================================================================================ # Print the menu option 'File' to the calculator window root.configure(menu = menubar) # Run a .mainloop() to start the calculator and keep it open root.mainloop()
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...") chocolate = chocolate + 5 print(chocolate) print("Multiplying " + str(chocolate) + " by 50") chocolate = chocolate * 50 print("Have you had your birthday this year? (Use 1 for yes, 0 for no please") x = input(":") if x == "1": y = -250 + year chocolate = chocolate + y elif x == "0": y = -251 + year chocolate = chocolate + y else: print("error, forcefully crashing script") print(end) age = input("What was the year you were born?:") print(str(chocolate) + " - " +str(age)) chocolate = chocolate - int(age) print(chocolate) print("Now you have a number.") print("The first is the amount of chocolate you wanted") print("The next, is your age.")
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 list in reverse alphabaical order") print(sorted(places,reverse=True)) print("again in original form !!") print(places) places.reverse() print(places) places.reverse() print(places) places.sort() print(places) places.sort(reverse=True) print(places)
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) + ' customers.') def increment_number_served(self,number): if number>=self.number_served: self.number_served += number print('we served ' + str(self.number_served) + ' customers.') else: print('your served number never reamin same') def describe_restaurant(self): print('Welcome to '+self.name+'.'+ 'We serves '+self.type) def open_restaurant(self): print('Our Restaurant is open.') my_restaurant=Restaurant('Salwa','Italian') print(my_restaurant.name) print(my_restaurant.type) my_restaurant.describe_restaurant() my_restaurant.open_restaurant() my_restaurant.increment_number_served(30) # changing num_served by call method(passing a value) # my_restaurant.set_number_served(30) # calling before change the num_served # print('we served '+str(my_restaurant.number_served)+' customers.') # after directly change the value # my_restaurant.number_served=10 # print('we served '+str(my_restaurant.number_served)+' customers.')
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 "+invitation.pop()+" you are not invited !! ") print("Sorry "+invitation.pop()+" you are not invited !! ") print("\n"+invitation[0] +" you are still invited ..") print("\n"+invitation[1] +" you are still invited ..\n\n") # now delete a list del invitation #or it can be done by this way #del invitation[0] #del invitation[1] # when program is compiled an error is occur "invitation is not defined" when we delete every elemnet of list it will become empty . print(invitation)
# 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 dinner party !!!\n") invitation[2]='ahmed' print(invitation) 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 ")
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_name+'@gmail.com' print('The user is ' + full_name) print("User's eamil address is " + user_email) print("user's age is "+str(self.age))
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 Banana !!') if 'Blackberry' in favorite_fruits: print('i really like Blackberry !!')
#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,"*" if num%i==0: flag=0 temp=i for j in range(2,int(math.sqrt(temp))+2): if temp%j==0: flag=1 if flag==0: print i else: continue
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.y - self.y) ** 2) def non_anchors_neighborhood(self, non_anchors): self.non_anchors_neibor = [s for s in non_anchors if self.distance(A=s) < self.r] class Anchor(Point): def __init__(self, x=0., y=0., r=100., order=-1): super().__init__(x, y, r, order) class NonAnchor(Point): def __init__(self, x=0., y=0., r=100., order=-1): super().__init__(x, y, r, order) class Gen: def __init__(self, x_1=-1., y_1=-1., x_2=-1., y_2=-1., type='segment'): self.x_1 = x_1 self.y_1 = y_1 self.x_2 = x_2 self.y_2 = y_2 self.type = type def generate_chromosome(self): if self.type == 'segment': x_max = max(self.x_1, self.x_2) x_min = min(self.x_1, self.x_2) y_max = max(self.y_1, self.y_2) y_min = min(self.y_1, self.y_2) x = random.uniform(x_min, x_max) y = random.uniform(y_min, y_max) return x, y elif self.type == 'circle': y = random.uniform(self.y_1 - self.x_2, self.y_1 + self.x_2) X = cm.line_circle_equation(0., y, self.x_1, self.y_1, self.x_2) x = X[0] return x, y else: return random.uniform(0., 1500.), random.uniform(0., 1000.) class Individual: def __init__(self, chromosome): self.chromosome = chromosome
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("--------------------------------------------------------------------") r = 0 if x in l: k = l.index(x) for i in l[:k]: r += i print("Сума чисел до ", x, "=", r) else: print(0) print("--------------------------------------------------------------------") n = int(input("n = ")) s = [] sumD = 0 kstD = 0 kst0 = 0 for i in range(n): z = float(input("s = ")) s.append(z) print(s) for elem in s: if elem > 0: sumD += elem kstD += 1 if elem == 0: kst0 += 1 kstV = n - kst0 - kstD print(sumD) print(kstV) print(kst0)
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_thirteen(num)}') except ValueError as e: print(f'Error: {e}')
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(response.raw, out_file) def book_rel_url_to_book_abs_url(relative_url): """get absolute url of a book from the relative url""" return "https://books.toscrape.com/catalogue/" + relative_url.removeprefix('../../../') def remove_last_part_of_url(category_url): """remove last part of category url , add href that will direct to the next page of the url""" return "/".join(category_url.split("/")[:-1]) def word_to_number(nb_word): """convert a number in words to a number as a digit""" return { "Zero": 0, "One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5, }[nb_word] def number_only(number_available): """return only the number of books available as an integer""" number_available = number_available.removeprefix('In stock (') number_available = number_available.removesuffix(' available)') return number_available def remove_suffix(image_url): """Transform relative image url to absolute image url""" image_url = image_url.removeprefix('../../') real_image_url = "https://books.toscrape.com/" + image_url return real_image_url def scrap_site_category_links(base_url): """scrap all the category links from the main site url(base url)""" response = requests.get(base_url) page = response.content soup = BeautifulSoup(page, "html.parser") category_links = [] for category_link in soup.find('ul', class_='nav nav-list').find('li').find('ul').find_all('li'): href = category_link.a.get('href') # url of the category url = "https://books.toscrape.com/{}".format(href) category_links.append(url) return category_links def get_category_name(category_link): """returns the name of a category""" response = requests.get(category_link) page = response.content soup = BeautifulSoup(page, "html.parser") category_name = soup.find("div", class_="page-header action").find("h1").text return category_name def scrap_book_links(category_link): """scrape all the book links in a category from the category link""" # list where the links of the books will be stored book_links = [] while True: # check to see if url was successfully gotten (if ok response=200,otherwise 404) response = requests.get(category_link) # get the content of the page as html and saves it in an object called page page = response.content # we use BeautifulSoup to parse(converting information into a format that's easier to work with) the html soup = BeautifulSoup(page, "html.parser") # in the parsed html all children of the parent article,because this is where all the information we need is urls_of_books = soup.find_all('article') # links are found in the a href book_links += [book_rel_url_to_book_abs_url(the_stuff.find('a')['href']) for the_stuff in urls_of_books] # check whether a next button exists if a := soup.select_one(".next > a"): category_link = remove_last_part_of_url(category_link) + "/" + a["href"] else: break return book_links def scrap_book_info(book_url): """scrap info about a book upc, price, reviews etc""" response = requests.get(book_url) page = response.content soup = BeautifulSoup(page, "html.parser") return { "product_page_url": book_url, "upc": soup.select_one("table tr:nth-child(1) > td").text, "title": soup.select_one("article div.col-sm-6.product_main > h1").text, "price_including_tax": soup.select_one("table tr:nth-child(4) > td").text, "price_excluding_tax": soup.select_one("table tr:nth-child(3) > td").text, "number_available": number_only(soup.select_one("#content_inner > article > table tr:nth-child(6) > td").text), "product_description": soup.select_one("article > p").text, "category": soup.select_one("#default > div > div > ul > li:nth-child(3) > a").text, "review_rating": word_to_number(soup.select_one(".star-rating")["class"][1]), "image_url": remove_suffix(soup.select_one("#product_gallery img")["src"]), } def main(): """Runs the program to scrap the site for the requested information""" base_url = "https://books.toscrape.com/index.html" category_links = scrap_site_category_links(base_url) for category_link in category_links: book_links = scrap_book_links(category_link) headings = ["product_page_url", "upc", "title", "price_including_tax", "price_excluding_tax", "number_available", "product_description", "category", "review_rating", "image_url"] with open(get_category_name(category_link) + ".csv", 'w', encoding="utf-8-sig") as csv_file: writer = csv.DictWriter(csv_file, delimiter=';', fieldnames=headings) writer.writeheader() for book_link in book_links: book = scrap_book_info(book_link) writer.writerow(book) image_downloader(book["image_url"], "./Books_to_Scrape_Images", book["upc"] + ".png") if __name__ == "__main__": main()
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 values :returns list of (x, y) points for interp_x values """ result = [] fcn_sorted = sorted(function_points, key=lambda point: point[0]) xp, yp = zip(*fcn_sorted) return zip(interp_x, np.interp(interp_x, xp, yp)) # Pass number of points for each character to have def interpolate_chars_uniformly(char_score_dict, num_points=200): new_dict = {} for ch, sc in char_score_dict.items(): interp_points = [float(x)/num_points for x in range(num_points)] new_dict[ch] = interpolate_points(sc, interp_points) return new_dict def test(): points = [(0,0), (2,0), (4,2), (6, -2)] interps = [0, 1, 3, 5] expected_y = [0, 0, 1, 0] x2, y2 = zip(*interpolate_points(points, interps)) print "The two following arrays should be equal:\n" + str(expected_y) + \ "\n" + str(y2)
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(response.text, 'lxml') # extract the information you want to sys.stdout.write(soup.find('h1', attrs={'itemprop': 'name'}).get('title')+'\n') sys.stdout.write(soup.find('span', attrs={'itemprop': 'price'}).text)
# -*- 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(Counter,self).__init__() self.share_object = share_object def run(self): while True: time.sleep(0.5) self.share_object.count() if self.share_object.v > 10 : break def main(): v = Ob() t1 = Counter(v) t2 = Counter(v) t1.start() t2.start() t1.join() t2.join() if __name__ == '__main__': main()
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): return self.up def __eq__(self, other): return self.up == other.up class Player(object): def __init__(self,name): self.name = name self.score = 0 def pick(self): choicedict = {'k': 'chicken', 'c': 'cow', 'h': 'human', 'd': 'deathray', 's': 'stop'} if not self.dice: return valid_choice = False while not valid_choice: selected = raw_input('Choice? k, c, d, h, s') if selected == 's': self.dice = [] return elif selected not in choicedict.keys(): print('invalid choice!') elif choicedict[selected] not in [str(x) for x in self.dice]: print('There are no %s to pick' % choicedict[selected]) elif selected in ['k', 'c', 'h']: # Check to see if they've already saved the selected type if choicedict[selected] in [str(x) for x in self.saved]: print("Sorry, you've already saved %s" % choicedict[selected]) else: for index, d in enumerate(self.dice): if d.up == choicedict[selected]: self.saved.append(d) self.dice[:] = (value for value in self.dice if value.up != choicedict[selected]) valid_choice = True elif selected == 'd': for index, d in enumerate(self.dice): if d.up == 'deathray': self.saved.append(d) self.dice[:] = (value for value in self.dice if value.up != 'deathray') valid_choice = True def take_turn(self): self.dice = [Cube() for x in range(0,13)] self.tanks = [] self.saved = [] while self.dice: for d in self.dice: d.roll() for index, d in enumerate(self.dice): if d.up == 'tank': self.tanks.append(d) # Now remove all the tanks self.dice[:] = (value for value in self.dice if value.up != 'tank') print('Rolled: %s' % self.dice) print('Saved: %s' % self.saved) print('Tanks: %s' % self.tanks) self.pick() self.score_dice() def score_dice(self): score = 0 score_dict = {'chicken': 0, 'human': 0, 'cow': 0, 'deathray': 0} for d in self.saved: score_dict[d.up] += 1 if score_dict['deathray'] < len(self.tanks): print('Too many tanks, not enough deathrays! NO SCORE!') exit(0) else: if score_dict['chicken'] and score_dict['human'] and score_dict['cow']: print('Bonus points! You got one of each type of creature! +3') score += 3 # Bonus points score += score_dict['chicken'] score += score_dict['human'] score += score_dict['cow'] print('You scored: %s' % score) exit() def main(): steve = Player('Steve') steve.take_turn() if __name__ == '__main__': main()
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(): warnings.simplefilter("error") try: return np.abs(a-b)/np.max(np.abs(np.array([a, b]))) except: return 0.0 def rowReduce(A, i, j, pivot): """ reduce row j using row i with pivot pivot, in matrix A operates on A in place """ factor = A[j][pivot] / A[i][pivot] for k in range(len(A[j])): # we allow an accumulation of error 100 times larger than a single computation # this is crude but works for computations without a large dynamic range if relError(A[j][k], factor * A[i][k]) < 100 * np.finfo('float').resolution: A[j][k] = 0.0 else: A[j][k] = A[j][k] - factor * A[i][k] # stage 1 (forward elimination) def fw(B): """ Return the row echelon form of B """ A = B.copy().astype(float) m, n = np.shape(A) for i in range(m-1): # Let lefmostNonZeroCol be the position of the leftmost nonzero value # in row i or any row below it leftmostNonZeroRow = m leftmostNonZeroCol = n ## for each row below row i (including row i) for h in range(i,m): ## search, starting from the left, for the first nonzero for k in range(i,n): if (A[h][k] != 0.0) and (k < leftmostNonZeroCol): leftmostNonZeroRow = h leftmostNonZeroCol = k break # if there is no such position, stop if leftmostNonZeroRow == m: break # If the leftmostNonZeroCol in row i is zero, swap this row # with a row below it # to make that position nonzero. This creates a pivot in that position. if (leftmostNonZeroRow > i): swapRows(A, leftmostNonZeroRow, i) # Use row reduction operations to create zeros in all positions # below the pivot. for h in range(i+1,m): rowReduce(A, i, h, leftmostNonZeroCol) return A #################### # If any operation creates a row that is all zeros except the last element, # the system is inconsistent; stop. def inconsistentSystem(A): """ B is assumed to be in echelon form; return True if it represents an inconsistent system, and False otherwise """ m, n = np.shape(A) for i in range(m): for j in range(n): if (A[i][j] != 0): if (j == n-1): return True else: break return False def bs(B): """ return the reduced row echelon form matrix of B """ A = B.copy().astype(float) m, n = np.shape(A) for i in range(m): # If row i is all zeros, or if i exceeds the number of rows in A, stop. for j in range(n): if (A[i][j] != 0.0): break if (j == n-1): return A pivot = j # If row i has a nonzero pivot value, divide row i by its pivot value. # This creates a 1 in the pivot position. A[i] = A[i] / A[i][pivot] for j in range(i): rowReduce(A, i, j, pivot) return A #####################
# 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/drive/1ubYJwGZvtSTKxc-mSpPE8iGfQjRsd2HX # 0. ABOUT THIS MODEL # This model will take RGB values and predict a 'Y percent by paint vol' value. # This is the proportion of acrylic yellow paint (by volume) required to recreate the RGB colour based on physical experiments. The data for these experiments are stored # in the file 'image-data-by-paint-percentage.csv'. # 1. OPEN DATA # Import the "image_data" dataset by reading the data from the csv file image_data = pd.read_csv('image-data-by-paint-percentage.csv') # Show first 5 rows of data (incl heading) so that we can visually inspect the data we have imported print(image_data[0:4]) # 2. FEATURE EXTRACTION # Set features as RGB features = image_data.loc[:,('R','G','B')] # Set label for 'Y percent by paint vol' labels = image_data.loc[:,'Y percent by paint vol'] # # We then convert the feature and labels dataframes to # # numpy ndarrays, which can interface with the scikit-learn models X = features.to_numpy() y = labels.to_numpy() # # Visual inspection of features and labels # print(X) # print(y) # 3. INITIALISE MODEL # Model initialised - source: https://scikit-learn.org/stable/modules/tree.html#classification from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression # 4. SPLITTING DATA INTO TEST/TRAIN SETS # Copied from https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html from sklearn.model_selection import train_test_split # Specifying data split - in this case 20% for testing, 80% for training X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Note: random_state --> the number 42 just corresponds to the seed of Randomness, you can use another number, for example 101. Each time that you run your model, the values selected will be the same, but if you change this number the values selected will be different and your accuracy could have variety but you will be sure that your model is robust if your accuracy keeps following the same. # Source: https://www.researchgate.net/post/Why_random_state_in_train_test_split_is_equal_42 # 5. TRAIN YOUR MODEL HERE # Train model using the training data - as defined in the train_test_split function above reg = LinearRegression().fit(X_train,y_train) #reg = LogisticRegression().fit(X_train,y_train) # 6. EVALUATE YOUR MODEL ON TEST SET HERE # Generate predictions on test set (predicting labels given test features) predictions = reg.predict(X_test) # Print out predicted values for visual inspection print('predictions: ',predictions) print('X train: ',len(X_train)) print('X_test:',len(X_test)) # Use clf.score() to find mean accuracy of model when makign predictions on test set score = reg.score(X_test,y_test) print('x_test',X_test) print('y_test',y_test) print("raw score: ",score) # 7. SAVE MODEL FOR LATER USE filename = 'y_guess_model_linreg.sav' pickle.dump(reg,open(filename,'wb')) loaded_model = pickle.load(open('y_guess_model_linreg.sav', 'rb')) #result = loaded_model.score([[57,121,63]], [48]) #print(result) print("model run completed") # ---------------------------------------------------------------- # # 8. CROSS VALIDATION # # Original source: https://colab.research.google.com/drive/1Fv1OPcgv_77p6ZGpzxNckka3o3G-LpOD#scrollTo=yCNO7p5xsnHs # # # More about cross validation at https://scikit-learn.org/stable/modules/cross_validation.html # # from sklearn.model_selection import cross_val_score # # Initialise list of coordinates for plotting # coord_list = [] # # Initialise iterator starting from value 1 - this is used to represent the max_depth value # n = 1 # # While iterator less than 20, assign iterator value to max_depth and calculate mean score using cross_val_score. # # Assign mean score as y-coordinate and iterator value as x-coordinate for plotting # from sklearn.model_selection import cross_val_score # while n < 10: # x_coord = n # scores = cross_val_score(reg, X, y, cv=4) # #print('y: ',y) # y_coord = scores # #print("ycoord: ",y_coord) # new_coord = (x_coord,y_coord) # coord_list.append(new_coord) # n += 1 # # Visual check of coordinate list # # print(coord_list) # # Plotting tuple coordinates (source: https://stackoverflow.com/questions/18458734/how-do-i-plot-list-of-tuples-in-python) # plt.plot(*zip(*coord_list)) # plt.show() # #scores = cross_val_score(clf, X, y, cv=4) # #print("CV Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
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 to be generated noise - standard deviation of the noise injected in the data ''' def visualize_y_locations(n_samples=10000, n_features=1, noise=1.0): np.random.seed(0) w = np.random.normal(loc=0, scale=0.25, size=n_features) X = np.random.normal(loc=0, scale=0.25, size=(n_samples, n_features)) noise = np.random.normal(0, noise, n_samples) ## Look at what the function looks like. x = np.arange(-1.5,1.5,0.01) y = (3/2)*(x)**2 + np.exp(0.6-1 / (100*(x-1)**2)) - 1.5 plt.xlabel("x = dot(w,z)") plt.ylabel("f(x)") plt.plot(x,y, 'k--') plt.show() visualize_y_locations(noise=1.0)
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.empCount+1 return self.e1 def displayCount(self): print("Total Employee %d" % Employee.empCount) def displayEmployee(self): print("Name : ", self.name, ", Salary: ", self.salary) "创建 Employee 类的第一个对象" emp1 = Employee("Zara", 2000) "创建 Employee 类的第二个对象" emp2 = Employee("Manni", 5000) print(Employee.empCount) print(emp1.intt("1").intt("22").intt("333").name) print(Employee.empCount)
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 number: ")) try: cursor.execute("CREATE TABLE num (name TEXT, number INTEGER)") except sqlite3.OperationalError: print("ok") cursor.execute("INSERT INTO num VALUES (?, ?)", (name, number),) rows = cursor.execute("SELECT 'name:',name, 'number:',number FROM num ").fetchall() print(rows) connection.commit() elif new == "n" or new == "N": print("ok") create() def see(): get = input("do you want to see someones number [y/n]: ") if get == "y" or get == "Y": print("this is what we got") show() try: name = input("enter him/her name: ") rows = cursor.execute("SELECT 'name:',name, 'number:', number FROM num WHERE name = ? ", (name,), ).fetchall() print(rows) except sqlite3.OperationalError: print("we cant find that") new = input("would you like to create it? [y/n]: ") if new == "y" or new == "Y": create() elif new == "n" or new == "N": print("ok") elif get == "n" or get == "N": print("ok") create() else: print("ok") modify_y = input("would you like to modify anything? [y/n]: ") if modify_y == "y" or modify_y == "Y": modify() else: print("ok") delete_t = input("would you like to delete anything? [y/n]: ") if delete_t == "y" or delete_t == "Y": delete() else: print("ok") ending = input("would you like to end this? [y/n]: ") if ending == "y" or ending == "Y": global end end = end + 1 else: print("ok") def modify(): name = input("enter him/her name: ") new_number = int(input("enter a new number: ")) cursor.execute("UPDATE num SET number = ? WHERE name = ?", (new_number, name)) rows = cursor.execute("SELECT 'name:',name, 'number:',number FROM num ").fetchall() print(rows) connection.commit() def delete(): name = input("enter him/her name: ") cursor.execute("DELETE FROM num Where name = ?", (name,)) rows = cursor.execute("SELECT 'name:',name, 'number:',number FROM num ").fetchall() print(rows) connection.commit() def show(): rows = cursor.execute("SELECT 'name:',name, 'number:',number FROM num ").fetchall() print(rows) while end == 0: see() connection.close()
# 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') people_nearby =[line.strip() for line in people.readlines()] people.close() friends_set = set(friends) people_nearby_set = set(people_nearby) friends_nearby_set = friends_set.intersection(people_nearby_set) nearby_friends_file = open('nearby_friends.txt', 'w') for friend in friends_nearby_set: print(f'{friend} is nearby ,meet them') nearby_friends_file.write(f'{friend}\n' f'') nearby_friends_file.close()
# Аннотации служат для повышения информативности исходного кода # Контроль типов без использования аннотаций # Пример: 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 import pdb filename_queue = tf.train.string_input_producer(['data/example_sheet.png']) reader = tf.WholeFileReader() k, v = reader.read(filename_queue) my_img = tf.image.decode_png(v) # configure our linear regression model learning_rate = 0.01 training_epochs = 10 display_step = 1 n_samples = 986135 X = tf.placeholder(tf.float32, shape=[n_samples, 5], name="features") y = tf.placeholder(tf.float32, shape=[n_samples, 1], name="regressor") W = tf.Variable(tf.zeros([5, 1]), name="weights") b = tf.Variable(0.0, name="bias") pred = tf.add(tf.matmul(X, W), b) cost = cost = tf.reduce_sum(tf.pow(pred-y, 2))/(2*n_samples) optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) init = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init) # load the image data coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1): #length of your filename list image = my_img.eval() #here is your image Tensor :) original = Image.fromarray(np.asarray(image)) greyscale_img = np.apply_along_axis(np.mean, 2, original) train_X = np.ndarray([n_samples, 5]) train_Y = np.ndarray([n_samples, 1]) for epoch in range(training_epochs): for w in range(0, 835): for h in range(0, 1181): sample_X = np.reshape(np.array([h / 1181.0, w / 835.0, (h / 1181.0) * (w / 835.0), (w / 835.0)**2, (h / 1181.0)**2 ]), [1, 5]) sample_Y = np.reshape(np.array([greyscale_img[h][w] / 255.0]), [1, 1]) # sess.run(optimizer, feed_dict={X: sample_X, y: sample_Y}) train_X[w * 1181 + h] = sample_X train_Y[w * 1181 + h] = sample_Y sess.run(optimizer, feed_dict={X: train_X, y: train_Y}) #Display logs per epoch step print("epoch %s, optimized" % epoch) if (epoch+1) % display_step == 0: c = sess.run(cost, feed_dict={X: train_X, y:train_Y}) print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \ "W=", sess.run(W), "b=", sess.run(b)) print("Optimization Finished!") training_cost = sess.run(cost, feed_dict={X: train_X, y: train_Y}) print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n') reconstructed_Y = tf.add(tf.matmul(train_X.astype(np.float32), sess.run(W)), sess.run(b)).eval() foo = np.reshape(reconstructed_Y * 255, [1181, 835], order="F") Image.fromarray(np.asarray(foo)).show() original.show()
# 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 = p-2 n = 4 for number in range (i+1): if number>0: n = (n**2-2)%M ll.append(n) return ll def is_mersenne_prime(p:int): """The Mersenne number is prime if the Lucas-Lehmer series is 0 at position p-2""" M = 2**p-1 ll = [] i = p-2 n = 4 for number in range (i+1): if number > 0: n = (n**2-2)%M ll.append(n) if ll[-1]==0: return True else: return False
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 matrix = [] no_routes = 0 routes = [] with open(filename, "r") as file: for line in file: elements = line.strip("\n").split(" ") # Save the number of routes if len(elements) == 1: no_routes = int(elements[0]) # Save the number of rows and cols elif len(elements) == 2: no_rows, no_cols = int(elements[0]), int(elements[1]) # Save the route elif len(elements) == 5: routes.append(Route(*elements)) # Replace any non-zero values with negative one, all zero values with maximum possible value # and save the line in the matrix else: matrix.append([-1 if int(number) != 0 and int(number) != 2 else no_rows * no_cols for number in elements]) return no_rows, no_cols, matrix, no_routes, routes def save_to_file(filename, solution): with open(filename, "a") as file: file.write(solution + "\n")
#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.placeholder(tf.float32,[None,10]) def computer_accuracy(v_xs,v_ys): global prediction y_pre = sess.run(prediction,feed_dict={xs:v_xs}) correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) result = sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys}) return result #add output layer prediction = TFdemo5.add_layer(xs,784,10,activation_function=tf.nn.softmax) #the error between prediction and real data cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction), reduction_indices=[1])) #loss train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess=tf.Session() # important step sess.run(tf.initialize_all_variables()) for i in range(1000): batch_xs,batch_ys = mnist.train.next_batch(100) sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys}) if i%50 == 0: print(computer_accuracy(mnist.test.images,mnist.test.labels))
#Условие #В школе решили набрать три новых математических класса. Так как занятия по математике у них проходят в одно и то же время, было решено выделить кабинет #для каждого класса и купить в них новые парты. За каждой партой может сидеть не больше двух учеников. Известно количество учащихся в каждом из трёх классов. #Сколько всего нужно закупить парт чтобы их хватило на всех учеников? Программа получает на вход три натуральных числа: количество учащихся в каждом из трех классов. a = int(input()) b = int(input()) c = int(input()) s = (a // 2 + b // 2 + c // 2 + a % 2 + b % 2 + c % 2) print (s)
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, FIELD_WIDTH, FIELD_HEIGHT, fill=BACKGROUND_COLOR) self.canvas.pack() self.data = data # プレイヤーの描写 # oval(x1,y1,x2,y2) x1y1からx2y2の長方形内に収まる円を描く # プログラム内では円の中心に座標点を置くので微修正する self.canvas.create_oval(self.data['x']-PLAYER_SIZE//2, self.data['y']-PLAYER_SIZE//2, self.data['x']+PLAYER_SIZE//2, self.data['y']+PLAYER_SIZE//2, tag=f'player{self.data["id"]}',fill=PLAYER_COLORS[self.data["id"]]) def update(self): # 一旦全て消す self.canvas.delete("all") self.canvas.create_rectangle(0, 0, FIELD_WIDTH, FIELD_HEIGHT, fill=BACKGROUND_COLOR) # self.canvas.delete(f'player{self.data["id"]}') self.player_update() self.bullet_update() def player_update(self): self.canvas.create_oval(self.data['x']-PLAYER_SIZE//2, self.data['y']-PLAYER_SIZE//2, self.data['x']+PLAYER_SIZE//2, self.data['y']+PLAYER_SIZE//2, tag=f'player{self.data["id"]}',fill=PLAYER_COLORS[self.data["id"]]) def bullet_update(self): for b in self.data['bullets']: self.canvas.create_oval(b.x-BULLET_SIZE//2, b.y-BULLET_SIZE//2, b.x+BULLET_SIZE//2, b.y+BULLET_SIZE//2 ,fill=BULLET_COLORS) if __name__ == '__main__' : print('test')
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, fileobject): if filetype=="url": finalname=(fileobject.replace(fileobject.split("://")[0], '').replace('://', '')+'.pdf') easygui.msgbox("Saving "+fileobject+" as "+finalname) pdfkit.from_url(fileobject, finalname) overmain() elif filetype=="file": finalname=(fileobject.replace(fileobject.split('.')[1], 'pdf')) easygui.msgbox("Saving "+fileobject+" as "+finalname) pdfkit.from_file(fileobject, finalname) overmain() elif filetype=="dir": os.chdir(fileobject) for i in os.listdir(fileobject): if ".html" in i or ".htm" in i: finalname=(i.replace(i.split('.')[1], 'pdf')) pdfkit.from_file(i, fileobject+finalname) else: pass overmain() def get_file(filetype): if filetype=="dir": filename = tkFileDialog.askdirectory() return filename elif filetype=="file": filename = tkFileDialog.askopenfilename() return filename def main(): urlchoice = "Supply a url to turn into a pdf" filechoice = "Pick a single file to turn into a pdf" dirchoice = "Pick a directory, all .html or .htm files within will be converted to pdf" mainchoices=[urlchoice,filechoice,dirchoice] choice=easygui.choicebox(title="Options", msg="Please select an option", choices=mainchoices) if choice==urlchoice: filetype="url" fileobject=easygui.enterbox("Please enter a url") try: if "http://" in fileobject or "https://" in fileobject: html = urllib2.urlopen(fileobject).read() convert(filetype, fileobject) else: fileobject="http://"+fileobject html = urllib2.urlopen(fileobject).read() convert(filetype, fileobject) except urllib2.HTTPError: easygui.msgbox("Invalid url") main() elif choice==filechoice: filetype="file" fileobject=get_file(filetype) convert(filetype, fileobject) elif choice==dirchoice: filetype="dir" fileobject=get_file(filetype) convert(filetype, fileobject) main() overmain()
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.transform(data['Gender']) print(data.head()) Y=data['Weight'] data.drop(['Weight'],axis=1,inplace=True) X_train,X_val,Y_train,Y_val=model_selection.train_test_split(data,Y,test_size=0.20) lr=LinearRegression() lr.fit(X_train,Y_train) print(lr.score(X_val,Y_val))
# 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: deq = deque() if root: deq.append(root) while len(deq) > 0: cur = deq.popleft() if cur.val % 2 == 0: # get grandchildren gc = self.getGrandChildren(cur) self.sum += sum(gc) if cur.left: deq.append(cur.left) if cur.right: deq.append(cur.right) return self.sum def getGrandChildren(self, root): c = [] gc = [] if root.left: c.append(root.left) if root.right: c.append(root.right) for node in c: if node.left: gc.append(node.left.val) if node.right: gc.append(node.right.val) return gc
#快速排序 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[high]=lst[low] lst[low]=mid quick_sort(lst,start,low-1) quick_sort(lst,low+1,end) if __name__ == "__main__": lst=[54, 26, 93, 17, 77, 31, 44, 55, 20] quick_sort(lst,0,len(lst)-1) print(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]# finds pos of UJ in unsorted list songsUnsorted.sort()# sorted the list print ((songsUnsorted.index(uJinUnsorted))+1)# prints out the new pos of UJ song
"""В строке найдите все серии подряд идущих пробелов и замените каждую на один пробел.""" def spaces(): str = input('Введіть текст: ') list_str = str.split() newstr = '' for el in list_str: newstr += (el+" ") newstr.rstrip() print(newstr) if __name__ == '__main__': spaces()
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 os novos valores: ") v1 = float(input("Primeiro valor: ")) v2 = float(input("Segundo valor: ")) elif pergunta == 3: if v1 > v2: print( "-" * 35) print("O primeiro valor é maior que o segundo.") print( "-" * 35) elif v1 == v2: print( "-" * 25) print("Os valores são iguais.") print( "-" * 25) else: print( "-" * 35) print("O segundo valor é maior que o primeiro.") print( "-" * 35) elif pergunta == 2: print( "-" * 40) print("Os números multiplicados equivalem a {}.".format(v1 * v2)) print( "-" * 40) elif pergunta == 1: print( "-" * 40) print("A soma entre os números é igual a {}.".format(v1 + v2)) print( "-" * 40) print("Fim do programa.")
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'.") opção = int(input("Qual é sua opção? ")) n_pc = randint(1, 5) n_jg = int(input("Escolha um número de 1 a 5: ")) while n_jg > 5: print("Número inválido! Escolha um número entre 1 e 5!") n_jg = int(input("Escolha um número de 1 a 5: ")) cont += 1 soma = n_jg + n_pc sleep(0.5) print("--" * 15) print(f"O PC escolheu {n_pc} e você escolheu {n_jg}.") if opção == 0 and soma % 2 == 0 or opção == 1 and soma % 2 != 0: print("--------VOCÊ GANHOU!--------") else: print(f"VOCÊ PERDEU! VOCÊ JOGOU {cont} VEZ(ES).") break sleep(10)
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[item]:>6.2f}')
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): print(f'[{matriz[l][c]:^5}]', end='') print() for i in pares: soma += i for c in range(0,3): soma3 += matriz[c][2] for m in range(0,3): if m == 0: maior = matriz[1][m] if matriz[1][m] > maior: maior = matriz[1][m] print(f'A soma dos pares equivale a {soma}.') print(f'A soma dos itens da 3a coluna é igual a {soma3}.') print(f'O maior valor da segunda linha é {maior}.')
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} ', end='', flush=True) cont += passo sleep(0.5) print('FIM.') else: cont = início while cont >= fim: print(f'{cont} ', end='', flush=True) cont -= passo sleep(0.5) print('FIM.') contador(1, 10, 1) contador(10, 0, 2) print('Agora é sua vez de personalizar a função: ') i = int(input('Início: ')) f = int(input('Fim: ')) p = int(input('Passo: ')) contador(i, f, p)
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().strip()[0] if idade >= 18: maiores += 1 if sexo in "F" and idade < 20: tot20 += 1 if sexo in "M": totH +=1 resp = " " while resp not in "SN": resp = str(input("QUER CONTINUAR? [S/N] ")).upper().strip()[0] if resp in "N": print("--------O PROGRAMA ENCERROU.--------") break print(f"No total, {pessoas} pessoas foram registradas, existem {maiores} pessoas maiores de idade.") print(f"Foram cadastradas {tot20} mulheres com menos de 20 anos.") print(f"Foram cadastrados {totH} homens.")
## 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 = name #persona is-a object class Person(object): def __init__(self,name): ##person is a class which takes self and name as Object ?? self.name = name # person has a pet of soe kind self.pet = None ## employee has person ( employee is-s) class Employee(Person): def __init__(self, name, salary): #what is this strange magic? super(Employee,self).__init__(name) #(employee has a salary) self.salary = salary ## fish is a object class Fish(object): pass #salmon is a fish class Salmon(Fish): pass ## halibut is a Fish class Halibut(Fish): pass ##rover is-a dog rover = Dog("rover") ##Satan is a cat satan = cat("satan") ## mary is a persona mary = Person("mary") #mary has a pet is a Satan mary.pet = satan #frank isa Employee frank = Employee("frank", 120000) ## frank has a pet frank.pet = rover # flipper is a Fish FLipper = Fish() # Crouse is a Sailmon crouse = Salmon() # harry is a Hailbut harry = Halibut()
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): # print("child override()") #dad = Parent() #son = Child() #dad.override() #son.override() #class Parent(object): # def alter(self): # print("Parent altered()") #class Child(Parent): # def alter(self): # print("child before parent altered()") # super(Child,self).alter() # print("child after parent altered") #dad = Parent() #son = Child() #dad.alter() #son.alter() class other: def override(self): print("other override") def implicit(self): print("other immplicite") def altered(self): print("other altered") class child: def __init__(self): self.other = other() def implicit(self): self.other.implicit() def override(self): print("chid overrides") def altered(self): print("Child before alter") self.other.altered() print("child after alter") son = child() son.implicit() son.override() son.altered()
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 be ", cars_not_driven ,"empty cars today") print("we can transport", carpool_capacity , "people today") print(" we have", passanger, "to carpool") print("we need to put about", average_passanger_per_car, "per car") # why m i doing this
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_collegues) > 0 and potential_collegues.isalpha(): if len(potential_methode) > 0 and potential_methode.isalpha(): print "Imagine yourself far away on top of a hill inside and around a castle with %s, envisioning the future of %s, while %s." % (potential_collegues,potential_content,potential_methode) #It may sound creepy, but trust me it's not. ;-) else: print "Try again" number_of_recurring_folks = raw_input("How many people you already know participate in luv17?") number_of_recurring_folks = int(number_of_recurring_folks) number_of_shared_urgencies = raw_input("How many common topics do you excpect at luv17?") number_of_shared_urgencies = int(number_of_shared_urgencies) def luv_approach(f,u): # f = number of recurring folks # u = number of shared urgencies if f >= 20 and u == 1: return "Tackle the shared urgency and explore it from diffrent angles for the five following days!" elif f < 20 or u >= 2: return "Getting to know the intriguing strangers and being inspired by urgencies and point of views that lay outside one's own filter-bubble..." else: return "The werewolves are watching you!" print luv_approach(number_of_recurring_folks, number_of_shared_urgencies) #add your arguments here!
#!/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 element print(arid+2) ''' Lets create a 2d array ''' list2 = [[1,1, 1], [2,2,2], [3,3,3]] arr2d = np.array(list2) print(arr2d) print(arr2d.dtype) # converting dtype to float arr2d = np.array(list2, dtype='float') print(arr2d.dtype) #converting again in integer, simmilarly to string '''Another diffrence in list and array''' # we can enter multiple datatype in list whereas numpy array can only be a single datatype '''Converting Numpy array in list''' np2list = arr2d.tolist() print(np2list) # simmliary to string and bytes, helpful in communication protocal for data recieving and data transfer '''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx''' '''How to inspect size and shape of numpy array''' print('array shape', arr2d.shape) #size print(arr2d.size) print('size : ',arid.size) # dimension print('dimension : ',arr2d.ndim) '''Extracting specific item from array''' # by indexing print('Extracting by index', arid[0]) # for 2-d array [r][c] print('2d array extracting', arr2d[2][1]) #selecting some number with condition boolean indexing boolarr = arr2d < 3 print(boolarr) print(arr2d[boolarr]) ''' row interchange andReverse the rows and columns in array''' print('Before reversing', arr2d) print(arr2d[::-1]) # transposing rows to columns print('Transpose',arr2d[::-1, ::-1]) ''' represinting infinity numbers in numnpy''' print(np.nan) # null not a number print(np.inf) #infinity stats operation cannot done on nan and inf #How to insert or manipulate number in numpy array arr2d[0][0] = np.nan arr2d[0][1] = np.inf print(arr2d) # mean of col1 and col2 can't be calculated # np.isnan to check nan in array print(np.isnan(arr2d).sum()) print(np.isinf(arr2d)) # replacing nan and inf missing_flag = np.isnan(arr2d) | np.isinf(arr2d) print(missing_flag) arr2d[missing_flag] = 0 print('nan and inf are replaced to 0',arr2d) '''Compute statistical operations on numpy array''' # find mean, s.d, variance e.t.c print('Mean : ',arr2d.mean()) print('max', arr2d.max()) print('Min : ', arr2d.min()) print('Sd : ', arr2d.std()) print('variance : ', arr2d.var()) print('squeeze', arr2d.squeeze()) # cummulative su,m adding no. by no. print('Cumulative sum : ',arr2d.cumsum()) '''Creating an array from existing array''' arr = arr2d[:2,:2] print(arr) # Reshaping, converting 3X3 in some other form print(arr2d.reshape(1,9)) # single row multiple columns print(arr2d.reshape(9,1)) # single column multiple rows # flatten the array when we don't know size or shape of array (single dim array) print('Flatten:',arr2d.flatten()) # copy of arr2d # ravel changes will affect parent whereas changes will not affect flatten print('Ravel', arr2d.ravel()) # refrence of arr2d '''Create a sequence, repetition, and random number''' # to genatare nyumpy array print(np.arange(1,5, dtype='int')) # it will include 1 but not 5 # another example with gap more than 1 print(np.arange(1,50,2)) # LAST ARGS DEFINE HOW MANY ELEMNTS #linespcae print('Line space', np.linspace(1, 50, 2)) print('Line space', np.linspace(1, 50, 100)) #logspace print('Log space', np.logspace(1, 50, 10)) #np.zeros print(np.zeros([2,2])) #np.ones print(np.ones([3,3])) a = [1, 2, 3] print('Repeat: ',np.tile(a, 3)) # repeating a list #np.repeat print(np.repeat(a, 3)) print(np.repeat(arr2d,3)) # generating a random number print('Random of size 3',np.random.rand(3)) # dimension of array in argument print('Random of size 3x3',np.random.rand(3,3)) #uniformly distributed random no. print(np.random.randn(3,3)) # random no. of integer print(np.random.randint(0,10, [3,3])) #[] defines dimesnion of number '''How we can get unique items and counts''' #unique numbers print('Unique ',np.unique(arr2d)) #count uniques, counts = np.unique(arr2d, return_counts=True) print('Uni',uniques) print('count', counts)
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 = False for v in vertices: self.V[v] = False self.Finished[v] = False # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A recursive function used by topologicalSort def topologicalSortUtil(self,v,stack): # Mark the current node as visited. self.V[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if not self.V[i]: self.topologicalSortUtil(i,stack) elif not self.Finished[i]: self.cycle = True # Push current vertex to stack which stores result self.Finished[v] = True stack.insert(0,v) # The function to do Topological Sort. It uses recursive # topologicalSortUtil() def topologicalSort(self): # Mark all the vertices as not visited stack =[] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for k,v in self.V.items(): if v != True: self.topologicalSortUtil(k,stack) # Print contents of the stack if not self.cycle: print(''.join(stack)) else: print('INVALID HYPOTHESIS') for i in range(int(input())): g = Graph(list('abcdefghijklmnopqrstuvwxyz')) words = [] for j in range(int(input())): w = str(input()) words.append(w) for i, word in enumerate(words): if(i == (len(words)-1)): break l = min(len(words[i]), len(words[i+1])) for j in range(l): char1 = words[i][j] char2 = words[i+1][j] if(char1 != char2): g.addEdge(char1,char2) break g.topologicalSort()
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.cuadrante = 1 elif (self.ejeX < 0 and self.ejeY > 0): self.cuadrante = 2 elif(self.ejeX < 0 and self.ejeY < 0): self.cuadrante = 3 elif(self.ejeX > 0 and self.ejeY < 0): self.cuadrante = 4 else: self.cuadrante = 0 print("Pertenece al cuadrante {}".format(self.cuadrante)) def vector(self,p): x = int(p.ejeX - self.ejeX) y = int(p.ejeY - self.ejeY) print("Vector es: {} {}".format(x,y)) return x, y def distancia(self,p): x, y = self.vector(p) d = math.sqrt(x**2 + y**2) print("distncia entre los puntos: {}".format(d)) a = Punto(2,3) b = Punto(5,5) c = Punto(-3,-1) d = Punto(0,0) print("Punto 1------------") print("A = ",a) print("B = ",b) print("C = ",c) print("D = ",d) print("Punto 2------------") a.mostrar_cuadrante() b.mostrar_cuadrante() d.mostrar_cuadrante() print("Punto 3------------") a.vector(b) b.vector(a) print("Punto 4------------") a.distancia(b) b.distancia(a) print("Punto 5------------")
#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): print("*", end=" ") print() print("\n") def number_square(self): for i in range(1, self.n): for j in range(1, self.n): print(i, end=" ") print() print("\n") def number_square_one(self): for i in range(1, self.n): for j in range(1, self.n): print(j, end=" ") print() print("\n") def alphabet(self): for i in self.list1: for j in self.list1: print(i, end=" ") print() print("\n") def square_alphabets(self): for i in self.list1: for j in self.list1: print(j, end=" ") print() print("\n") def number_pyramid(self): for i in range(1 , self.n): for j in range(1,i+1): print(j, end=" ") print() print("\n") def number_square_two(self): for i in self.list2: for j in self.list2: print(j, end=" ") print() print("\n") def rev_alpha_sqr(self): for i in self.list3: for j in self.list3: print(i, end=" ") print() print("\n") def rev_alpha_sqr1(self): for i in self.list3: for j in self.list3: print(j, end=" ") print() print("\n") def ascending_star(self): for i in range(1,self.n): for j in range(1, i+1): print("*",end=" ") print() print("\n") obj = Patterns() obj.star_square() obj.number_square() obj.number_square_one() obj.alphabet() obj.square_alphabets() obj.number_pyramid() obj.number_square_two() obj.rev_alpha_sqr() obj.rev_alpha_sqr1() obj.ascending_star()
#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 * 9 // 5) + 32 print(f"{farenheit}F") #Farenheit to Celcius Scale elif scale == 2: farenheit = float(input("Enter the Farenheit:")) celcius = 0 celcius = (farenheit - 32) * 5 // 9 print(f"{celcius}C") else: print("Choose a Valid Option!!!")
''' 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 phone number:') def sample(num): k=re.search(pattern="(\s)(\d)[@][gmail]+.(\s){3}",string=num) return k if (sample(num)): print(f'is the valid num:',num) else: print('WARNING...it is invalid number') ''' import re gmail=input('Enter the Gmail Id:') def demo(gmail): mail=re.search("^[a-z0-9](\.?[a-z0-9]){5,}@g(oogle)?mail\.com$",string=gmail) return mail if(demo(gmail)): print('Gmail id is valid',gmail) else: print('Gmail id is not valid',gmail)
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:")) except ValueError as e: print("invalid input ,please enter a integer value ") continue else: break except ValueError as e: print("Invalid input,please enter a integer value ") continue else: break list_1 = [] list_2 = [] list_3 = [] dic = {} for i in range(start, ending + 1): list_1.append(i) print(list_1) while True: try: start_1 = int(input("enter the starting value")) while True: try: ending_1 = int(input("enter the ending value:")) except ValueError as e: print("invalid input,please enter a integer value ") continue else: break except ValueError as e: print("invalid input,please enter a integer value ") continue else: break if ending >= start_1: for j in range(start_1, ending_1): list_2.append(j) print(list_2) else: print("the list cant be created") for k in list_2: list_3 = [] while k != 0: for l in list_1: if l // k == l % k: list_3.append(l) dic[k] = eval(f"{list_3}") k = 0 print(dic) f = open("diction.txt", 'w') f.write(f"{list_1, list_2, list_3, dic}") print("File created successfully") f.close() y = datetime.now() print("end time", y) z = y - x print("Difference is", z)
# 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(0, 0) -> [1, 2, 3] # perm(3, 1) # swap(1, 1) -> [1, 2, 3] # perm(3, 2) # swap(2, 2) -> [1, 2, 3] # perm(3, 3) # print [1, 2, 3] # swap(2, 2) -> [1, 2, 3] # swap(1, 1) -> [1, 2, 3] # swap(1, 2) -> [1, 3, 2] # perm(3, 2) # swap(2, 2) -> [1, 3, 2] # print [1, 3, 2] # swap(2, 2) -> [1, 3, 2] # 이런식으로 계속 이어진다. 그림으로 그리는 것이 더 이해하기 쉬움 # Code def permutation(n, k): if k == n: print(arr) else: for i in range(k, n): arr[k], arr[i] = arr[i], arr[k] permutation(n, k+1) arr[k], arr[i] = arr[i], arr[k] n = 3 arr = [i+1 for i in range(n)] permutation(n, 0)
# 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 = node = ListNode(None) node.next = head for _ in range(left - 1): node = node.next # 뒤집었을 때 가장 마지막이 되는 노드 end = node.next for _ in range(right - left): temp, node.next, end.next = node.next, end.next, end.next.next node.next.next = temp return head
# 파이썬식 편법: 배열로 만들어버리기 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 ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # 원래 문제가 의도한 풀이: Runner를 이용 class Solution: def isPalindrome_2(self, head: ListNode) -> bool: # head에서 출발해 2칸씩 이동하는 fast와 1칸씩 이동하는 slow slow = fast = head # head의 역순 연결리스트인 rev 작성 rev = None while fast and fast.next: fast = fast.next.next rev, rev.next, slow = slow, rev, slow.next # head의 길이가 홀수 if fast: slow = slow.next # 절반 지점에 도착해있는 slow는 head의 오른쪽으로, rev는 왼쪽으로 이동하며 비교하는 것과 같음 while rev and rev.val == slow.val: slow, rev = slow.next, rev.next return not rev head = [1,2,2,1] print(isPalindrome_2(head))
# 반복 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 -1 # 재귀 def search(self, nums: List[int], target: int) -> int: def binary_search(left, right): if left > right: return -1 mid = (left + right) // 2 if target < nums[mid]: return binary_search(left, mid-1) elif target > nums[mid]: return binary_search(mid+1, right) else: return mid return binary_search(0, len(nums)-1) # bisect 모듈 def search(self, nums: List[int], target: int) -> int: index = bisect.bisect_left(nums, target) return index if index < len(nums) and nums[index] == target else -1
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(fido2.get_age()) if __name__ == "__main__": fido_example1()
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__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ self.result = [] self.result = self.traverse(root) return self.result def traverse(self, root): if not root: return ###顺序是左右根 self.traverse(root.left) self.traverse(root.right) self.result.append(root.val) return self.result 2.Non-recursive 终于找到一个简单易懂的Non-recursive方法 利用两个栈,在s1中按照根左右的顺序push进node,然后将右node pop出,再循环;即相当于将整个结果反着push进s2,这样s2 pop时的顺序就是postorder的顺序 # 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 postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] result = [] s1 = [root] s2 = [] while s1: node = s1.pop() s2.append(node) if node.left: s1.append(node.left) if node.right: s1.append(node.right) while s2: result.append(s2.pop().val) return result