text
stringlengths
37
1.41M
# Given the names and grades for each student in a Physics class of n students, store them in a nested list # and print the name(s) of any student(s) having the second lowest grade. # Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. # Input Format # The first line contains an integer, n, the number of students. # The 2n subsequent lines describe each student over 2 lines; the first line contains a student's name, and the second line contains their grade. if __name__ == '__main__': physics = [] for _ in range(int(input())): name = input() score = float(input()) physics.append([name,score]) grades = [] students = [] for i in physics: grades.append(i[1]) second_grade = 0 grades.sort() lowest_grade = grades[0] for i in grades: if i > lowest_grade: second_grade = i break for i in physics: if i[1] == second_grade: students.append(i[0]) students.sort() for i in students: print(i)
grid=[] for i in range(3): temp=[] for j in range(3): temp.append(" ") grid.append(temp) def win(grid,char): # Horizontal for i in range(3): j=0 while( j!= 3 and grid[i][j]==char): j=j+1 if(j==3): return True # for i in range(3): # bool = True # for j in range(3): # if grid[i][j]!=char: # bool=False # Vertical for i in range(3): j=0 while(j != 3 and grid[j][i]==char): j=j+1 if(j==3): return True # Diagnol 1 bool=True for i in range(3): if grid[i][i]!=char: bool=False if bool==True: return True # Diagnol 2 bool=True for i in range(3): if grid[i][2-i]!=char: bool=False if bool==True: return True return False def show(grid): for i in grid: print(*i, sep=" | ") print("--------") print("") # for i in range(3): # for j in range(3): # print(grid[i][j],end=" | ") # print("") # print("-------------") def minimax(grid, minmax): if win(grid,'X'): return 1 if win(grid,'O'): return -1 bool = False for i in range(3): for j in range(3): if grid[i][j] == " ": bool = True break if bool == False: return 0 blanks=[] # Maximize if minmax == True: best = -2 for i in range(3): for j in range(3): if grid[i][j]==" ": blanks.append([i,j]) for i in blanks: grid_cpy = [row[:] for row in grid] grid_cpy[i[0]][i[1]] = 'X' temp = minimax(grid_cpy, False) if(temp > best): best = temp return best # Minimize else: best = 2 for i in range(3): for j in range(3): if grid[i][j]==" ": blanks.append([i,j]) for i in blanks: grid_cpy = [row[:] for row in grid] grid_cpy[i[0]][i[1]] = 'O' temp = minimax(grid_cpy, True) if(temp < best): best = temp return best turn = 0 while(not win(grid, 'X') and not win(grid, 'O')): if(turn == 9): print("It's a Draw ㄟ( ▔, ▔ )ㄏ") break # Human if turn%2==0: x,y=map(int,input().split()) grid[x][y] = 'O' # AI else: best = -2 best_move = [] for i in range(3): for j in range(3): if(grid[i][j] == " "): grid_cpy = [row[:] for row in grid] grid_cpy[i][j] = 'X' temp = minimax(grid_cpy, False) if(temp > best): best = temp best_move = [i,j] grid[best_move[0]][best_move[1]] = 'X' show(grid) if win(grid,'X'): print("X Won!!😍😍") elif win(grid,'O'): print("O Won!!👍.👌") turn+=1
def resolve(): ''' code here ''' N = int(input()) res = '' while N >= 1: N-=1 res += chr(ord('a') + N%26) N //= 26 print(res[::-1]) if __name__ == "__main__": resolve()
def getNome(): nome = input('Insira o nome: ') return nome def getSobrenome(): sobrenome = input('Insira o sobrenome: ') return sobrenome def getSalmens(): sal_mens = 0.0 while(not float(sal_mens)): try: sal_mens = float(input('Insira o salário mensal: ')) except: print('Valor Invalido!') return sal_mens def showNomecompleto(nome, sobrenome): return nome+' '+sobrenome
class Funcionario: def __init__(self): print('Sistema do Funcionário: ') self.nome_func = input("Nome do Funcionário: ") self.sobrenome_func = input("Sobrenome do Funcionário: ") self.sal_func = [] self.gasto_func = [] self.poupanca = [] def showName(self): print("Nome Completo: " + self.nome_func + " " + self.sobrenome_func) def getData(self): count = 0 while count < 12: try: sal = float(input("Informe o salário do Mês " + str(count + 1) + " : ")) self.sal_func.append(sal) gasto = float(input("Informe o gasto do Mês " + str(count + 1) + " : ")) self.gasto_func.append(gasto) if (gasto > sal): raise Exception('Gasto Demais, não pode!') count = count + 1 except Exception as e: print(str(e)) except: print("Valor Invalido.") def calculaSomaSal(self): count = 0 soma = 0 for i in range(0, 12): soma = soma + self.sal_func[count] count = count + 1 return soma def mediaSal(self): media_sal = self.calculaSomaSal() media_sal = media_sal / 12 return media_sal def calculaPoupanca(self): for i in range(0, 12): self.poupanca.append(self.sal_func[i] - self.gasto_func[i]) self.poupanca[i] = (self.poupanca[i] + self.poupanca[i]) def calculaImpostoRenda(self, soma_sal): if soma_sal <= 22847.76: return "Isento" elif soma_sal >= 22847.77 and soma_sal <= 33919.80: imposto_renda = soma_sal * 0.075 return imposto_renda elif soma_sal >= 33919.81 and soma_sal <= 45012.60: imposto_renda = soma_sal * 0.15 return imposto_renda elif soma_sal >= 45012.61 and soma_sal <= 55976.16: imposto_renda = soma_sal * 0.225 return imposto_renda elif soma_sal > 55976.16: imposto_renda = soma_sal * 0.275 return imposto_renda
print("Enter a name for the X player:") name1= input() print("\nEnter a name for the Y player e r:") name2= input() print("Game Start:") a = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']] print("---------") for i in range(0,3): print('\n|',a[i][0],a[i][1],a[i][2],'|') print("\n---------") print("Who plays first?",name1,"or", name2) input_name= input() if (input_name != name1 and input_name != name2): print(input_name,"is not a registered player") o ='row' k = 0 nrow = 0 ncolumn = 0 while(k == 0): if a[0][0] != " "and a[0][1] != " " and a[0][2] != " " and a[1][0] != " " and a[1][1] != " " and a[1][2] != " " and a[2][0] != " " and a[2][1] != " "and a[2][2] != " ": print("Draw") break if(a[0][0] == a[0][1] ==a[0][2] == 'row' or a[0][0] == a[1][1] == a[2][2] == 'row' or a[0][0] == a[1][0] == a[2][0] == 'row'or a[1][1] == a[0][0] == a[2][0] == 'row'or a[2][2] == a[2][1] == a[2][0] == 'row'or a[1][0] == a[1][1] == a[1][2] == 'row'or a[0][2] == a[1][2] == a[2][2] == 'row'or a[2][1] == a[0][1] == a[1][1] == 'row') : print(name1, "wins") break elif (a[0][0] ==a[0][1] ==a[0][2] == 'O' or a[0][0] == a[1][1] == a[2][2] == 'O' or a[0][0] == a[1][0] == a[2][0] == 'O'or a[1][1] == a[0][0] == a[2][0] == 'O'or a[2][2] == a[2][1] == a[2][0] == 'O'or a[1][0] == a[1][1] == a[1][2] == 'O'or a[0][2] == a[1][2] == a[2][2] == 'O'or a[2][1] == a[0][1] == a[1][1] == 'O') : print(name2," wins") break row, column = input("Enter the coordinates: ").split() row = int(row) column = int(column) if row <=3 and row >= 1 and column <= 3 and column >= 1: if a[row-1][abs(column - 3)] != ' ' : print("This cell is occupied! Choose another one!") continue else : a[row - 1][abs(column - 3)] = o if o == 'row' : o = '0' nrow += 1 else : o = 'row' ncolumn += 1 # break elif row >=3 and row<= 1 or column >= 3 or column <=1: print("Coordinates should be from 1 to 3!") continue else : print("column o u should enter numbers!") continue print("---------") for i in range(0,3): print('\n|',a[ i ][ 0 ],a[i][1],a[i][2],'|') print("\n---------")
class employee: count=0 def __init__(self,empid,empname,empsal): self.empid=empid self.empname=empname self.empsal=empsal employee.count=employee.count+1 def display(self): print("the employee id is:",self.empid) print("the employee name is:",self.empname) print("the employee salary is:",self.empsal) print("the no. of objects in the class:",employee.count) e1=employee(10,"ram",23400) e1.display() e2=employee(20,'aman',23500) e2.display() print(hasattr(e1,'empname')) print(getattr(e1,'empsal')) print(setattr(e1,'empname','shyam')) print(delattr(e1,'empid')) print("employee.__doc__",employee.__doc__) print("employee.__name__",employee.__name__) print("employee.__module__",employee.__module__) print("employee.__bases__",employee.__bases__) print("employee.__dict__",employee.__dict__)
#Name: Ashok Surujdeo #Email: [email protected] #Date: March 2, 2021 #This program runs: Snow Count import matplotlib.pyplot as plt import numpy as np name = input("Enter file name: ") ca = plt.imread(name) countSnow = 0 t = 0.8 for i in range(ca.shape[0]): for j in range(ca.shape[1]): if (ca[i,j,0] > t) and (ca[i,j,1] >t) and (ca[i,j,2] > t): countSnow = countSnow +1 print("Snow count is", countSnow)
#Name: Ashok Surujdeo #Email: [email protected] #Date: March 23, 2021 #This program runs: Dinosaurs import pandas as pd filename = input("Enter file name: ") dino = pd.read_csv(filename) print("There are", dino['Name'].count(),"dinosaur genera.") print("The number of dinosaur genera in each period:") print(dino['Period'].value_counts()) print("The three most dinosaur-populated countries were:") print(dino['Country'].value_counts()[:3])
#Name: Ashok Surujdeo #Email: [email protected] #Date: February 23, 2021 #This program runs: Marginal Tax Rate income = int(input("Enter taxable income: ")) if income < 0: print("Error") elif 0 <= income <= 9700: print("Marginal tax rate: 10%") elif 9701 <= income <= 39475: print("Marginal tax rate: 12%") elif 39476 <= income <= 84200: print("Marginal tax rate: 22%") elif 84201 <= income <= 160725: print("Marginal tax rate: 24%") elif 160726 <= income <= 204100: print("Marginal tax rate: 32%") elif 204101 <= income <= 510300: print("Marginal tax rate: 35%") elif income >= 510301: print("Marginal tax rate: 37%")
#Name: Ashok Surujdeo #Email: [email protected] #Date: March 2, 2021 #This program runs: Square Spiral import turtle alex = turtle.Turtle() length = 25 for i in range(100): alex.right(5) length = length*1.02 for i in range(4): alex.forward(length) alex.right(90)
#Name: Ashok Surujdeo #Email: [email protected] #Date: February 23, 2021 #This program runs: Turtle Spiral stamps = int(input("Enter number of stamps the turtle will print: ")) import turtle alex = turtle.Turtle() alex.shape('arrow') alex.color('cyan') alex.penup() steps = 10 for i in range (0, stamps): alex.stamp() if (i % 2 == 0): steps += 3 alex.forward(steps) alex.right(24)
""" Given a tower of [number] disks, initially stacked in decreasing size on one of three pegs. The objective is to transfer the entire tower to one of the other pegs, moving only one disk at a time and never moving a larger one onto a smaller. """ from __future__ import print_function def tower_of_hanoi(num, source, target, helper): """Moving num of the disks from source to target using helper""" if num == 0: return else: tower_of_hanoi(num - 1, source, helper, target) print("move the disk -", num, "from", source, "to", target) tower_of_hanoi(num - 1, helper, target, source) print("tower of 3 disks:") tower_of_hanoi(3, 'A', 'C', 'B') print("\ntower of 5 disks:") tower_of_hanoi(5, 'A', 'C', 'B')
from math import atan2 # for computing polar angle from random import randint # for sorting and creating data pts import shapely # for checking intersection from matplotlib import pyplot as plt # for plotting from shapely import geometry class Line(): def __init__(self): self.line_cor = [] # Returns a list of (x,y) coordinates, # each x and y coordinate is writen by user def create_line_points(self, point=2): print("Enter coordinates of Line: ") self.line_cor = [[int(input("Point " + str(_) + " X: ")), int(input("Point " + str(_) + " Y: "))] \ for _ in range(point)] class Polygon(): def __init__(self): self.pts = [] self.hull = [] self.points = 0 # Returns a list of (x,y) coordinates of length 'num_points', # each x and y coordinate is writen by user def create_points(self, ct): self.pts = [[int(input("\n" + "Point " + str(_) + " X: ")), int(input("Point " + str(_) + " Y: "))] \ for _ in range(ct)] # If Polygon is convex # Creates a scatter plot, input is a list of (x,y) coordinates. # The second input 'convex_hull' is another list of (x,y) coordinates # consisting of those points in 'coords' which make up the convex hull, # if not None, the elements of this list will be used to draw the outer # boundary (the convex hull surrounding the data points). def scatter_plot(self, coords, line_cor, convex_hull=None): hull = self.graham_scan(True) shapely_line = shapely.geometry.LineString(line_cor) shapely_poly = shapely.geometry.Polygon(hull) intersection_line = list(shapely_poly.intersection(shapely_line).coords) xs, ys = zip(*coords) # unzip into x and y coord lists xl, yl = zip(*line_cor) xi, yi = zip(*intersection_line) fig, ax = plt.subplots() if convex_hull != None: # plot the convex hull boundary, extra iteration at # the end so that the bounding line wraps around for i in range(1, len(convex_hull) + 1): if i == len(convex_hull): i = 0 # wrap c0 = convex_hull[i - 1] c1 = convex_hull[i] ax.plot((c0[0], c1[0]), (c0[1], c1[1]), 'b', marker='o') ax.plot(xs[0], ys[0], 'b', marker='o', label="Polygon") ax.plot(xl, yl, 'r', marker='o', label="Line") ax.plot(xi, yi, 'y', marker='o', label="Intersection") ax.legend() fig.set_figheight(5) fig.set_figwidth(8) plt.show() # If polygon isn`t convex # Creates a scatter plot, input is a list of (x,y) coordinates. def simple_plot(self, coords, line_cor): shapely_line = shapely.geometry.LineString(line_cor) shapely_poly = shapely.geometry.Polygon(coords) intersection_line = list(shapely_poly.intersection(shapely_line).coords) xs, ys = zip(*coords) # unzip into x and y coord lists xl, yl = zip(*line_cor) xi, yi = zip(*intersection_line) fig, ax = plt.subplots() ax.plot(xs, ys, 'b', marker='o', label="Polygon") ax.plot(xl, yl, 'r', marker='o', label="Line") ax.plot(xi, yi, 'y', marker='o', label="Intersection") ax.legend() fig.set_figheight(5) fig.set_figwidth(8) plt.show() # Returns the polar angle (radians) from p0 to p1. # If p1 is None, defaults to replacing it with the # global variable 'anchor', normally set in the # 'graham_scan' function. def polar_angle(self, p0, p1=None): if p1 == None: p1 = anchor y_span = p0[1] - p1[1] x_span = p0[0] - p1[0] return atan2(y_span, x_span) # Returns the euclidean distance from p0 to p1, # square root is not applied for sake of speed. # If p1 is None, defaults to replacing it with the # global variable 'anchor', normally set in the # 'graham_scan' function. def distance(self, p0, p1=None): if p1 == None: p1 = anchor y_span = p0[1] - p1[1] x_span = p0[0] - p1[0] return y_span ** 2 + x_span ** 2 # Returns the determinant of the 3x3 matrix... # [p1(x) p1(y) 1] # [p2(x) p2(y) 1] # [p3(x) p3(y) 1] # If >0 then counter-clockwise # If <0 then clockwise # If =0 then collinear def det(self, p1, p2, p3): return (p2[0] - p1[0]) * (p3[1] - p1[1]) \ - (p2[1] - p1[1]) * (p3[0] - p1[0]) # Sorts in order of increasing polar angle from 'anchor' point. # 'anchor' variable is assumed to be global, set from within 'graham_scan'. # For any values with equal polar angles, a second sort is applied to # ensure increasing distance from the 'anchor' point. def quicksort(self, a): if len(a) <= 1: return a smaller, equal, larger = [], [], [] piv_ang = self.polar_angle(a[randint(0, len(a) - 1)]) # select random pivot for pt in a: pt_ang = self.polar_angle(pt) # calculate current point angle if pt_ang < piv_ang: smaller.append(pt) elif pt_ang == piv_ang: equal.append(pt) else: larger.append(pt) return self.quicksort(smaller) \ + sorted(equal, key=self.distance) \ + self.quicksort(larger) # Returns the vertices comprising the boundaries of # convex hull containing all points in the input set. # The input 'points' is a list of (x,y) coordinates. # If 'show_progress' is set to True, the progress in # constructing the hull will be plotted on each iteration. def graham_scan(self, show_progress=False): global anchor # to be set, (x,y) with smallest y value # Find the (x,y) point with the lowest y value, # along with its index in the 'points' list. If # there are multiple points with the same y value, # choose the one with smallest x. min_idx = None for i, (x, y) in enumerate(self.pts): if min_idx == None or y < self.pts[min_idx][1]: min_idx = i if y == self.pts[min_idx][1] and x < self.pts[min_idx][0]: min_idx = i # set the global variable 'anchor', used by the # 'polar_angle' and 'distance' functions anchor = self.pts[min_idx] # sort the points by polar angle then delete # the anchor from the sorted list sorted_pts = self.quicksort(self.pts) del sorted_pts[sorted_pts.index(anchor)] # anchor and point with smallest polar angle will always be on hull hull = [anchor, sorted_pts[0]] for s in sorted_pts[1:]: while self.det(hull[-2], hull[-1], s) <= 0: del hull[-1] # backtrack # if len(hull)<2: break hull.append(s) if show_progress: pass # scatter_plot(points, hull) return hull # Check if Polygon is Convex def is_Convex(self, pts, hull): print("Is Convex") if len(pts) == len(hull) else print("Is not Convex ") # Check if Polygon is intersected by line # Work just with Polygon # Polygon created with 2 dots don`t work and cause error def is_Intersection(self, line_cor, pts, hull): shapely_line = shapely.geometry.LineString(line_cor) if len(pts) == len(hull): shapely_poly = shapely.geometry.Polygon(hull) intersection_line = list(shapely_poly.intersection(shapely_line).coords) else: shapely_poly = shapely.geometry.Polygon(pts) intersection_line = list(shapely_poly.intersection(shapely_line).coords) if len(intersection_line) == 0: print("Not Intersection") exit(0) elif len(intersection_line) == 1: print("Intersection") else: if line_cor[0] == intersection_line[0] and line_cor[1] == intersection_line[1] \ or line_cor[1] == intersection_line[0] and line_cor[0] == intersection_line[1]: print("Line in Polygon") elif line_cor[0] == intersection_line[0] or line_cor[1] == intersection_line[1] \ or line_cor[1] == intersection_line[0] or line_cor[0] == intersection_line[1]: print("Line cross Polygon but not intersection") else: print("Intersection") # Main function def on_going(self): line_par = Line() line_par.create_line_points() print(line_par.line_cor) self.points = int(input("\n" + "Enter count of Points: ")) self.create_points(self.points) print("Points:", self.pts) self.hull = self.graham_scan(True) print("Graham:", self.hull) self.is_Convex(self.pts, self.hull) if len(self.pts) == len(self.hull): self.is_Intersection(line_par.line_cor, self.pts, self.hull) self.scatter_plot(self.pts, line_par.line_cor, self.hull) else: self.is_Intersection(line_par.line_cor, self.pts, self.hull) plot = self.pts[0] self.pts.append(plot) self.simple_plot(self.pts, line_par.line_cor) if __name__ == '__main__': project = Polygon() project.on_going()
import turtle import math wn = turtle.Screen() turtle.screensize(900,900,"black") turtle.speed(0) colors = ["sea green","yellow","blue","orange","green","gray"] sun = turtle.Turtle() Mercury = turtle.Turtle() Venus = turtle.Turtle() earth = turtle.Turtle() Mars = turtle.Turtle() Jupiter = turtle.Turtle() Saturn = turtle.Turtle() turtle.hideturtle() turtle.penup() turtle.goto(30,-15) turtle.pendown() turtle.begin_fill() turtle.fillcolor("red") turtle.circle(20) turtle.end_fill() def place(planet,a,n): planet.shape("circle") planet.up() planet.fd(a) planet.down() planet.color(colors[n]) place(Mercury,100,0) place(Venus,130,1) place(earth,160,2) place(Mars,200,3) place(Jupiter,250,4) place(Saturn,300,5) def planet(planet,a,θ): b = (a**2-30**2)**0.5 x = a * math.cos(θ*0.006) y = b * math.sin(θ*0.006) planet.goto(x,y) for θ in range(1000): planet(Mercury,100,16*θ) planet(Venus,130,14*θ) planet(earth,160,12*θ) planet(Mars,200,10*θ) planet(Jupiter,250,8*θ) planet(Saturn,300,6*θ) turtle.done()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 27 13:34:55 2019 @author: hans """ from bs4 import BeautifulSoup import urllib3 import certifi def body_texter(url): """ input url and return teh text of the body """ # create pool c=urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) # download website content = c.request('GET', url) # make soup soup = BeautifulSoup(content.data) # get text from body text = soup.body.get_text() return text def write_file(text, file="output.txt"): """ write to file""" with open(file, 'w') as t: for line in text: line = line.replace('\n', ' ') line = line.replace('\t', ' ') t.write(line) return " {} written".format(file) if __name__ == "__main__": url = input("website? ") file = input("File? ") text = body_texter(url) write_file(text, file)
#!python3.6.1 # -*- coding: utf-8 -*- # author: https://github.com/vinlinch # 第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换, # 例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 # # 北京 # 程序员 # 公务员 # 领导 # 牛比 # 牛逼 # 你娘 # 你妈 # love # sex # jiangge from collections import Counter import os import re def get_filter_words(file): with open(file, 'r', encoding='utf-8') as f: return f.read().split('\n') def replace_words(sentence, filter_word): for word in filter_word: if sentence.find(word) > -1: sentence = sentence.replace(word,'**') return sentence if __name__ == "__main__": filter_file = "filtered_words.txt" filter_words = get_filter_words(filter_file) print(filter_words) while True: iw = input("please input a word: ") print(replace_words(iw,filter_words)) end_flag = input("want end?(Y/N): ") if end_flag.lower() == 'y': break
import random #for random numbers def createBoard(rows, columns): if rows <= 0: # if user puts bad input raise NameError("need to have more than zero rows") return [["-"]*columns for i in range(rows)] #return 2d array with all '-' def putBomb(board,row,column): board[row][column] = "*" #TODO change to named optional arguments def loopThroughBoardAndDo(board, function_on_each_element=None, function_after_each_row=None): rows = len(board[0]) #is this really columns?, test this for row in range(len(board)): for column in range(rows): if(function_on_each_element): #if it exists, maybe change to callable(function...) function_on_each_element(board,row ,column) if(function_after_each_row): function_after_each_row(board,row) def putBombsInBoard(board, bombs): if bombs >= len(board)*len(board[0]): # if the user wants as many bombs as their are spaces or more, fill the board with bombs loopThroughBoardAndDo(board, function_on_each_element=putBomb) else: bombsLeftToPlace = float(bombs) #convert to float so that we can do fractional math with it columns = len(board[0]) rows = len(board) row = column = 0 while bombsLeftToPlace > 0: if(random.random() > (bombsLeftToPlace/bombs - .1) and board[row][column] != "*"): #math formula to place bombs pseudo randomly board[row][column] = "*" bombsLeftToPlace = bombsLeftToPlace - 1.0 column = (column + 1)%columns #increment the column if column == 0: #if on the first column row = (row+1)%rows def printBoard(board): loopThroughBoardAndDo(board, function_on_each_element=lambda board,row,column: print(board[row][column],end=" "), # function to print each element without a new line function_after_each_row=lambda a,b: print("\n")) # function to print a new line at the beggining of each row def printPlayBoard(board,bombs): print("Bombs: " + str(bombs)) for i in range(len(board[0])): print(str(i), end=" ") print("") for i in range(len(board[0])*2): print("-",end="") print("") loopThroughBoardAndDo(board, function_on_each_element=lambda board,row,column: print(board[row][column],end=" "), function_after_each_row= lambda board,row: print("|" + str(row))) def playMineSweeper(rows, columns, bombs): fullBoard = createBoard(rows, columns) putBombsInBoard(fullBoard, bombs) fillInBoard(fullBoard) #printBoard(fullBoard) # for testing #print("") # for testing playBoard = createBoard(rows, columns) playingGame = True printPlayBoard(playBoard,bombs) totalFound = 0 while playingGame: ############################## Get Input ############################## row = int(input("enter the row: ")) column = int(input("enter the column: ")) ############################## Get Input ############################## if(playBoard[row][column] == "-"): element = playBoard[row][column] = fullBoard[row][column] totalFound += 1 else: continue if element == "*": #if bomb print("You lost") playingGame = False else: #if not bomb if element == 0: #if zero bombs surrounding def allDirectionsDo(totalFound,ifFunc, doFunc): directions = [(-1,1), (0,1), (1,1), (-1,0), (1,0), (-1,-1),(0,-1),(1,-1)] for direction in directions: x,y = direction try: #protect against index out of range if(ifFunc(x,y)): doFunc(totalFound,x,y) except IndexError: continue return totalFound def setBoard(totalFound,x,y): playBoard[x+row][y+column] = fullBoard[x+row][y+column] #if(playBoard[x+row][y+column] == "0"): # totalFound = allDirectionsDo(totalFound, lambda a,b: (a+x+row >= 0 and b+y+column >= 0 and playBoard[a+x+row][b+y+column] == "-"), setBoard) totalFound += 1 totalFound = allDirectionsDo(totalFound, lambda x,y: (x+row >= 0 and y+column >= 0 and playBoard[x+row][y+column] == "-"), setBoard) printPlayBoard(playBoard,bombs) if totalFound == rows*columns - bombs: print("You\'ve won!") playingGame = False
if hasattr(__builtins__, 'raw_input'): #input now works for both python2.7 and python3 input=raw_input #Much better than sys.stdin.readline() def between(start, end): return list(map(int, range(start, end + 1))) #returns list of numbers between start and end # will eventually combine this with other between() for characters for more English-like code def aNumber(value): try: float(value) return True # any float or int will return true as opposed to just ints except ValueError: return False def getName(): print('Enter a name: ') while True: student_name = input() if all(character.isalpha() or character.isspace() for character in student_name): return student_name print(student_name + " is not a name that only contains letters or spaces, re-enter: ") def getAge(): print('Enter your age: ') while True: age = input() if aNumber(age) and int(float(age)) in between(0, 120): #if number not between 0 and 120 return int(age) print(str(age) + " is not a number or reasonable age, re-enter: ") def findMaxIndex(array): maxIndex = 0 for i in range(len(array)): if aNumber(array[i]) and array[i] > maxIndex: maxIndex = i return maxIndex #change function to accept any string for any property def getStudents(numberOfStudents): names = [] ages = [] for i in range(numberOfStudents): names.append(getName()) ages.append(getAge()) return names, ages def maxProperty(names, property): maxIndex = findMaxIndex(property) #returns index of highest age return [names[maxIndex], property[maxIndex]] #example: names, ages = getStudents(3) print( maxProperty(names, ages) )
num = int(input('digite um numero: ')) for n in range(1, num + 1): if num % n == 0: print(n)
class Employee: """ Employee object to represent an employee """ def __init__(self, id=0, first_name='', manager_id=0, salary=0): # Store any employees under this employee self._employees = [] # Basic data model for an employee self.id = id self.first_name = first_name self.manager_id = manager_id self.salary = salary @staticmethod def fromDictionary(employee_data): # This is a nice factory design pattern used by Dart employee = Employee(employee_data['id'], employee_data['first_name'], employee_data['manager'], employee_data['salary']) return employee def add_employee(self, employee): """ Adds an employee to this manager """ self._employees.append(employee) def is_manager(self): # The employee is a manager if they have employees under them return len(self._employees) > 0 def assign_employee_data(self, employee): """ Assigns data to an employee. IDs must match when assigning data. This solves the problem of employees being added before their manager. An empty employee that is a manager can be created to manage the overall hiearchy and the employee details can be added later """ assert employee.id == self.id self.first_name = employee.first_name self.manager_id = employee.manager_id self.salary = employee.salary def get_employees(self): """ Returns the list of employees under this manager """ return self._employees def list_employees(self, spacing=0): # All subordinates will have this prefix to build the ascii hiearchy prefix = "--" + "--"*spacing # Print this employees name print(prefix + self.first_name) for subordinate in self._employees: subordinate.list_employees(spacing+1) # Python sort functions are guaranteed to use lt during # sorting, so define this to make sorting employees alphabetically easy. def __lt__(self, other): return self.first_name < other.first_name def __repr__(self): return self.first_name
# Distance from zero def distance_from_zero(num): if num[0] == '-' or num.isdigit(): if len(num.split(".")) > 1: return abs(float(num)) return abs(int(num)) return "Nope" num = input("Please enter a value: ") print(distance_from_zero(num))
#Tipos de elementos que son iterables iterCadena = iter('cadena') iterLista = iter(['l', 'i', 's', 't', 'a']) iterTupla = iter(('t','u','p','l','a')) iterConjunto = iter({'c','o','n','j','u','n','t','o'}) iterDiccionario = iter({'d': 1,'i': 2,'c': 3,'c': 4,'i': 5,'o': 6,'n': 7,'a': 8,'r': 9,'i': 10,'o': 11,}) print(iterCadena) print(iterLista) print(iterTupla) print(iterConjunto) print(iterDiccionario)
lista = [1, 2, 3] lista.append('cuatro') lista[1] = 'dos' for item in lista: print(item) a = [2, 4, 6] b = a # Se asigna la variable por referencia print(id(a)) print(id(b)) c = [a, b] # Lista que contiene a las listas a y b print(c) a.append(8) # Agrega el mismo elemento a las listas `a` y `b` porque acceden al mismo espacio de memoria print(c) #Clonación de listas a = [2, 4, 6] b = a # Maneras de clonar listas para que no se asigne la referencia c = list(a) d = a[::] print(id(a)) print(id(b)) print(id(c)) print(id(d)) lista = list(range(100)) print(lista) print() doble = [i * 2 for i in lista ] print(doble) print() pares = [i for i in lista if i % 2 == 0] print(pares)
a = [10,30,40,50] max = 0 for i in a: if max <= i: max=i print(max)
from datetime import date from time import sleep dates=[] d1=date(2018,4,17) d2=date(1995,11,17) d3=date(1995,11,4) dates.append(d1) dates.append(d2) dates.append(d3) dates.sort() sleep(5) print(dates) for d in dates: print(d)
""" Name: Daniel Gladkov Date: 27/05/2020 """ import pygame pygame.init() base_color = (255, 165, 0) text_color = (255, 255, 255) hovered_base_color = (255, 0, 0) font = pygame.font.SysFont('Comic Sans MS', 40) class Button: """ A class that represents a button Attributes ---------- :var screen: The screen the button is drawn on :type screen: pygame.display :var text: The text the button displays :type text: string :var x: The X position of the button :type x: int :var y: The Y position of the button :type y: int :var width: The width of the button :type width: int :var height: The height of the button :type height: int :var action: The actions the button does when pressed :type action: function :var active: Is the button active? :type active: boolean Methods ------- draw_self() draws the object hovered_over() checks if the mouse is on the button, if yes return True change its color, else return False pressed() checks if button is pressed, if yes activate its action activate() makes the button active deactivate() makes the button not active """ def __init__(self, screen, x, y, text, action): self.screen = screen self.text = font.render(text, True, text_color) self.x = x self.y = y self.width = 12 + self.text.get_width() self.height = 65 self.action = action self.active = False def draw_self(self, b_color=base_color): if self.active: pygame.draw.rect(self.screen, b_color, (self.x, self.y, self.width, self.height)) self.screen.blit(self.text, (self.x + 6, self.y)) pygame.display.update() def hovered_over(self): if self.active: mouse = pygame.mouse.get_pos() if (self.x + self.width > mouse[0] > self.x) and (self.y + self.height > mouse[1] > self.y): self.draw_self(hovered_base_color) return True else: self.draw_self() return False def pressed(self): if self.active: if self.hovered_over(): self.deactivate() self.action() def activate(self): self.active = True def deactivate(self): self.active = False
#BMI值# try: s, t = eval(input("请分别输入身高体重用逗号隔开:")) if s > 100: s /= 100 if t > 85: t /= 2 BMI = t/ s** 2 a, b = "", "" if BMI < 18.5: a, b = "偏瘦", "偏瘦" elif 18.5 <= BMI < 24: a, b = "正常", "正常" elif 24 <= BMI < 25: a, b = "偏胖", "正常" elif 25 <= BMI < 28: a, b = "偏胖", "偏胖" elif 28 <= BMI < 30: a, b = "肥胖", "偏胖" elif BMI >= 30: a, b = "肥胖", "肥胖" print("BMI值为{:.1f}\n国内标准为{}\n国际标准为{}".format(BMI, a, b)) except: print("输入格式错误")
def simple_numbers(a): '''На входе-натуральные числа от 0 до 1000. Функция проверяет числа на простоту. ''' if 0<a<=1000: for i in range(2,a+1): if a%i==0: break return a==i def vse_deliteli(a): '''На входе-натуральные числа от 0 до 1000. Возвращает список всех делителей числа. ''' if 0<a<=1000: list_del=[] for i in range(1,a+1): if a%i==0: list_del==list_del.insert(i,i) return(list_del) else: 'break' # Здесь 'break' проходит только в ковычках...почему? def max_simple_delitel(a): '''Возвращает самый большой простой делитель числа.''' list=vse_deliteli(a) list_max=[] for i in range(1,len(list)): if simple_numbers(list[i]):list_max == list_max.insert(i,list[i]) return max(list_max) print(simple_numbers(36)) print(vse_deliteli(36)) print(max_simple_delitel(36)) def simple_deliteli(a): ''' Возвращает каноническое разложение числа на простые множители. ''' if 0<a<=1000: list_simple_delitelei=[] for i in range(2,a): while simple_numbers(i)==1 and a%i==0: list_simple_delitelei.append(i) #список простых делителей 'a' a=a/i else: i+=1 return list_simple_delitelei print(simple_deliteli(36)) def max_delitel(a): ''' Функция выводит самый большой множитель (не обязательно простой) числа. ''' x=simple_deliteli(a) # выводит все множетели числа а x.reverse() # меняет порядок return x[0] # выводит самый первый print(max_delitel(36))
# coding: utf-8 # # Preliminaries import copy import itertools from collections import defaultdict from operator import itemgetter # #### Our dataset format # An event is a list of strings. # A sequence is a list of events. # A dataset is a list of sequences. # Thus, a dataset is a list of lists of lists of strings. # # E.g. #dataset = [ # [["a"], ["a", "b", "c"], ["a", "c"], ["c"]], # [["a"], ["c"], ["b", "c"]], # [["a", "b"], ["d"], ["c"], ["b"], ["c"]], # [["a"], ["c"], ["b"], ["c"]] #] # # Foundations # ### Subsequences """ This is a simple recursive method that checks if subsequence is a subSequence of mainSequence """ def isSubsequence(mainSequence, subSequence): subSequenceClone = list(subSequence) # clone the sequence, because we will alter it return isSubsequenceRecursive(mainSequence, subSequenceClone) #start recursion """ Function for the recursive call of isSubsequence, not intended for external calls """ def isSubsequenceRecursive(mainSequence, subSequenceClone, start=0): # Check if empty: End of recursion, all itemsets have been found if (not subSequenceClone): return True # retrieves element of the subsequence and removes is from subsequence firstElem = set(subSequenceClone.pop(0)) # Search for the first itemset... for i in range(start, len(mainSequence)): if (set(mainSequence[i]).issuperset(firstElem)): # and recurse return isSubsequenceRecursive(mainSequence, subSequenceClone, i + 1) return False # ### Size of sequences """ Computes the size of the sequence (sum of the size of the contained elements) """ def sequenceSize(sequence): return sum(len(i) for i in sequence) # ### Support of a sequence """ Computes the support of a sequence in a dataset """ def countSupport (dataset, candidateSequence): return sum(1 for seq in dataset if isSubsequence(seq, candidateSequence)) # # AprioriAll # ### 1 . Candidate Generation # #### For a single pair: """ Generates one candidate of size k from two candidates of size (k-1) as used in the AprioriAll algorithm """ def generateCandidatesForPair(cand1, cand2): cand1Clone = copy.deepcopy(cand1) cand2Clone = copy.deepcopy(cand2) # drop the leftmost item from cand1: if (len (cand1[0]) == 1): cand1Clone.pop(0) else: cand1Clone[0] = cand1Clone[0][1:] # drop the rightmost item from cand2: if (len (cand2[-1]) == 1): cand2Clone.pop(-1) else: cand2Clone[-1] = cand2Clone[-1][:-1] # if the result is not the same, then we dont need to join if not cand1Clone == cand2Clone: return [] else: newCandidate = copy.deepcopy(cand1) if (len (cand2[-1]) == 1): newCandidate.append(cand2[-1]) else: newCandidate [-1].extend(cand2[-1][-1]) return newCandidate # #### For a set of candidates (of the last level): """ Generates the set of candidates of size k from the set of frequent sequences with size (k-1) """ def generateCandidates(lastLevelCandidates): k = sequenceSize(lastLevelCandidates[0]) + 1 if (k == 2): flatShortCandidates = [item for sublist2 in lastLevelCandidates for sublist1 in sublist2 for item in sublist1] result = [[[a, b]] for a in flatShortCandidates for b in flatShortCandidates if b > a] result.extend([[[a], [b]] for a in flatShortCandidates for b in flatShortCandidates]) return result else: candidates = [] for i in range(0, len(lastLevelCandidates)): for j in range(0, len(lastLevelCandidates)): newCand = generateCandidatesForPair(lastLevelCandidates[i], lastLevelCandidates[j]) if (not newCand == []): candidates.append(newCand) candidates.sort() return candidates # ### 2 . Candidate Checking """ Computes all direct subsequence for a given sequence. A direct subsequence is any sequence that originates from deleting exactly one item from any element in the original sequence. """ def generateDirectSubsequences(sequence): result = [] for i, itemset in enumerate(sequence): if (len(itemset) == 1): sequenceClone = copy.deepcopy(sequence) sequenceClone.pop(i) result.append(sequenceClone) else: for j in range(len(itemset)): sequenceClone = copy.deepcopy(sequence) sequenceClone[i].pop(j) result.append(sequenceClone) return result """ Prunes the set of candidates generated for size k given all frequent sequence of level (k-1), as done in AprioriAll """ def pruneCandidates(candidatesLastLevel, candidatesGenerated): return [cand for cand in candidatesGenerated if all(x in candidatesLastLevel for x in generateDirectSubsequences(cand))] # ### Put it all together: """ The AprioriAll algorithm. Computes the frequent sequences in a seqeunce dataset for a given minSupport Args: dataset: A list of sequences, for which the frequent (sub-)sequences are computed minSupport: The minimum support that makes a sequence frequent verbose: If true, additional information on the mining process is printed (i.e., candidates on each level) Returns: A list of tuples (s, c), where s is a frequent sequence, and c is the count for that sequence """ def apriori(dataset, minSupport, verbose=False): global numberOfCountingOperations numberOfCountingOperations = 0 Overall = [] itemsInDataset = sorted(set ([item for sublist1 in dataset for sublist2 in sublist1 for item in sublist2])) singleItemSequences = [[[item]] for item in itemsInDataset] singleItemCounts = [(i, countSupport(dataset, i)) for i in singleItemSequences if countSupport(dataset, i) >= minSupport] Overall.append(singleItemCounts) if verbose: print "Result, lvl 1: " + str(Overall[0]) k = 1 while (True): if not Overall [k - 1]: break # 1. Candidate generation candidatesLastLevel = [x[0] for x in Overall[k - 1]] candidatesGenerated = generateCandidates (candidatesLastLevel) # 2. Candidate pruning (using a "containsall" subsequences) candidatesPruned = [cand for cand in candidatesGenerated if all(x in candidatesLastLevel for x in generateDirectSubsequences(cand))] # 3. Candidate checking candidatesCounts = [(i, countSupport(dataset, i)) for i in candidatesPruned] resultLvl = [(i, count) for (i, count) in candidatesCounts if (count >= minSupport)] if verbose: print "Candidates generated, lvl " + str(k + 1) + ": " + str(candidatesGenerated) print "Candidates pruned, lvl " + str(k + 1) + ": " + str(candidatesPruned) print "Result, lvl " + str(k + 1) + ": " + str(resultLvl) Overall.append(resultLvl) k = k + 1 # "flatten" Overall Overall = Overall [:-1] Overall = [item for sublist in Overall for item in sublist] return Overall
import pandas as pd import gmplot from IPython.display import display data = pd.read_excel('Locations.xlsx') # latitude and longitude list latitude_list = data['LATITUDE'] longitude_list = data['LONGITUDE'] # center co-ordinates of the map gmap = gmplot.GoogleMapPlotter(00.00000,0.0000000,0) # plot the co-ordinates on the google map gmap.scatter( latitude_list, longitude_list, '# FF0000', size = 40, marker = True) # the following code will create the html file view that in your web browser gmap.heatmap(latitude_list, longitude_list) gmap.draw( "mymap.html" )
import re phoneRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') resume = 'some random resume with lot of phone numbers' phoneRegex.search(resume) # Return the first match phoneRegex.findall(resume) # Return list of matches as string lyrics = '12 drummers drumming, 11 pipes piping, 10 lords a leaping, 9 ladies dancing' xmasRegex = re.compile(r'\d+\s\w+') print(xmasRegex.findall(lyrics))
value = 0 def sum( val, index ) : return val + index for i in range(2) : value = sum(value, i) print(value)
# https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def serialize(self, root): def _serialize(root, l= []): if root: l.append(root.val) _serialize(root.left,l) _serialize(root.right,l) else: l.append("null") return l return str(_serialize(root)) def deserialize(self, data): data = list(data) def _deserialize(root, data): val = data[0] if root == None and val!="null": return TreeNode(val) if root == None and val == "null": return None root.left = _deserialize(root.left,data[1:]) root.right = _deserialize(root.right,data[1:]) return root root = _deserialize(None, data) return root def build(): t1 = TreeNode(1) t2 = TreeNode(2) t3 = TreeNode(3) t4 = TreeNode(4) t5 = TreeNode(5) t1.left = t2 t1.right = t3 t3.left = t4 t3.right = t5 return t1 tree = build() codec = Codec() k = codec.serialize(tree) print(k) r = codec.deserialize(k) print("Done") # class Tree: # def __init__(self): # self.root = None # def insert(self, val): # self.root = self.__insert(self.root, val) # def __insert(self, root, val): # if root == None: # return TreeNode(val) # root.left = self.__insert(root.left, val) # root.right = self.__insert(root.right, val) # t = Tree() # for i in range(10): # t.insert(i) # print("done")
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None k = [] count = -1 def traversal(root): global count count+= 1 if len(k)==2: return if root == None: traversal(root.left) traversal(root.right) if root.left.value > root.value: k.append(count) if root.right.value < root.value: k.append(count) tree_root = None def __insert(root, val, side): if root == None: return TreeNode(val) if side == "l": root.left = __insert(root.left, val, side) elif side == "r": root.right = __insert(root.right, val, side) return root def insert(val,side): global tree_root tree_root = __insert(tree_root,val,side) from collections import deque def f(l): global tree_root queue = deque(l) while queue: item = queue.popleft() node = TreeNode(item) if tree_root == None: tree_root = node node.left = TreeNode(queue.popleft()) node.right = TreeNode(queue.popleft()) for i in range(10): insert(i) print("done")
from itertools import groupby def insert(): pass # def remove(l,c): # [x for x in l if ] def sol(board, hand): groups = groupby(board) result = [[label, sum(1 for _ in group)] for label, group in groups] return result board = "WRRBBW" hand = "RB" board = "WWRRBBWW" k = sol(board, hand) print(k)
# https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/ grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] from collections import deque info = {} for i in range(len(grid)): for j in range(len(grid[0])): info[(i,j)] = False def is_valid(grid, index): if index[0]<0 or index[1]<0 \ or index[0]>= len(grid) or index[1]>=len(grid[0]) : return False,index return True,index def get_next(grid, index, val = None): x,y = index[0],index[1] if val == None: val = grid[x][y] next_ = None if val == 1: next_ = is_valid(grid,(x,y+1)) elif val == 2: next_ = is_valid(grid,(x,y-1)) elif val == 3: next_ = is_valid(grid,(x+1,y)) elif val == 4: next_ = is_valid(grid,(x-1,y)) return next_[0],next_[1],val # print(get_next(grid,(0,3))) def bfs(grid): f = [] vals = [1,2,3,4] visited = set() visited.add((0,0)) queue = deque([[(0,0),0]]) while queue: item = queue.popleft() if item[0] == (len(grid)-1,len(grid[0])-1): f.append(item) next_ = get_next(grid,item[0]) nbors = [] if next_[0] == False: for val in vals: if next_[2]!=val: _ = get_next(grid,next_[1],val)[1] nbors.append(_) else: nbors.append(next_[1]) for nbor in nbors: if nbor not in visited: visited.add(nbor) queue.append([nbor,item[1]+1]) return f k = bfs(grid) print(k)
def number_of_vowels(my_string): vowels = ["a","e","i","o","u", "A", "E", "I", "O", "U"] def reverse(my_string): s = " " for i in my_string[::-1]: s+= i return s def reverse_order(my_string): s = " " for i in my_string.split(" ")[::-1]: s+= i+" " return s def rotate(s1, s2, no_of_chars): return s1[-1*no_of_chars:] + s1[:-1*no_of_chars] == s2 if __name__ == "__main__": my_string = "my name is uchiha Madara" print(reverse_order(my_string)) print(rotate("ABCD", "CDAB",2))
from Graph import Graph from collections import defaultdict, deque def add_edge(graph, vertex_a, vertex_b): graph[vertex_a].add(vertex_b) graph[vertex_b].add(vertex_a) def build_graph(board_size): graph = defaultdict(set) for row in range(board_size): for col in range(board_size): for to_row, to_col in legal_moves_from(row, col, board_size): add_edge(graph, (row, col), (to_row, to_col)) vertices = [x for x in graph] edges = [] for i in graph: for j in graph[i]: edges.append([i,j]) graph = Graph() for i in vertices: graph.add_vertex(i) for i in edges: graph.add_edge(*i) return graph, vertices, edges MOVE_OFFSETS = ( (-1, -2), ( 1, -2), (-2, -1), ( 2, -1), (-2, 1), ( 2, 1), (-1, 2), ( 1, 2), ) def legal_moves_from(row, col, board_size): for row_offset, col_offset in MOVE_OFFSETS: move_row, move_col = row + row_offset, col + col_offset if 0 <= move_row < board_size and 0 <= move_col < board_size: yield move_row, move_col def dfs_rec(graph, start, visited = []): #it can be bfs if start not in visited: visited.append(start) for neighbor in graph.get_neighbors(start): dfs_rec(graph, neighbor, visited) return visited if __name__ == "__main__": dimension = 8 graph, vertices, edges = build_graph(dimension) count = 0 for v in vertices: visited = dfs_rec(graph,v) if len(set(visited)) == dimension*dimension: count+=1 # print(v) # print(visited) # print("\n\n") print(count)
print("my_dictonarys") run = 1 while run == 1: a = input("Введите данные словаря:") b = input("Введите данные второго словаря:") def mergedicts(a, b): for key in b: if isinstance(a.get(key), dict) or isinstance(b.get(key), dict): mergedicts(a[key], b[key]) else: a[key] = b[key] return a print(a,b)
print("Простий калькулятор") a = float(input("Введіть перше число: ")) b = float(input("Введіть друге число: ")) operation = input("ВВедіть необхідну операцію:") result = None if operation == "+": result = a + b elif operation == "-": result = a - b elif operation == "*": result = a * b elif operation == "/": result = a / b else: print("Помилка") if result is not None: print("Результат:", result)
class sausage(): ## OK NOW I AM HUNGRY!!! def __init__(self, mince = "pork!", volume = 1): self.mince = mince self.size = eval(str(volume)) * 12 if len(mince) > 12: self.mince_str = mince[:12] else: self.mince_str = mince * (12 // len(mince)) + mince[:12 % len(mince)] def __str__(self): blocks = int(self.size) // 12 left = int(self.size) % 12 up = "/------------\\" * blocks down = "\\------------/" * blocks s = "|" + self.mince_str + "|" body = s * blocks if left: body += s[:left + 1] + "|" up += "/------------"[:left +1] + "|" down += "\\------------"[:left + 1] + "|" if int(self.size) == 0: up = "/|" down = "\\|" body = "||" return "\n".join((up, body, body, body, down)) def __truediv__(self, num): return sausage(self.mince, (self.size / num) / 12) def __mul__(self, num): return sausage(self.mince, (self.size * num) / 12) def __add__(self, other): return sausage(self.mince, (self.size + other.size) / 12) def __sub__(self, other): size = (self.size - other.size) / 12 if size < 0: size = 0 return sausage(self.mince, size) def __bool__(self): return bool(self.size) __rmul__ = __mul__
from math import * func = input() A, B = eval(input()) x = A while abs(eval(func)) > 0.0000001: x = (A + B) / 2 if eval(func) < 0: A = x else: B = x print(x)
# Score: 15/15 def partition(arr, low, high): # Partition function i = low-1 # Index of smaller element pivot = arr[high][0] # Pivot which will be moved to the correct spot for j in range(low, high): if arr[j][0] <= pivot: # If the value is smaller than the pivot i = i+1 # Increments index of smaller element arr[i],arr[j] = arr[j],arr[i] # Switches elements arr[i + 1], arr[high] = arr[high], arr[i + 1] # Switches elements return (i + 1) def quickSort(arr, low, high): # Quick sort function if low < high: partitionIndex = partition(arr, low, high) # Partition index # Continues sorting quickSort(arr, low, partitionIndex-1) quickSort(arr, partitionIndex+1, high) input_amount = int(input()) # Number of inputs provided # 2D arrays are initialized like this: [[number of elements with value x] number of rows of that array] inputs = [[0 for i in range(2)] for j in range(input_amount)] # Defines a 2D array initialized with 0s for row in range(input_amount): # Python does not separate inputs with a space like C++, you have to take input as a string and split it inputs[row][0], inputs[row][1] = map(int, input().split()) # Takes in inputs one at a time and then splits them by the space and stores them as integers # Sort array in ascending order by time len = len(inputs) quickSort(inputs, 0, len-1) # Calls function to quick sort maxSpeed = 0 speed = 0 displacement = 0 time = 0 for i in range(1, input_amount): time = abs(inputs[i][0] - inputs[i-1][0]) displacement = abs(inputs[i][1] - inputs[i - 1][1]) speed = displacement/time # calculates speed if speed > maxSpeed: # if speed beats max speed maxSpeed = speed print(str(maxSpeed)) # answer
# -*- coding: utf-8 -*- #import some dope import sys import os import re import time from random import randrange from itertools import repeat numbers = { 'adam' :"+41111111111", 'bob' :"+41222222222", 'chris' :"+41333333333", 'dave' :"+41444444444", } print "Gespeicherte Empfänger: " for name in numbers: print "%10s - %s"%(name,numbers[name]) number = "" while number == "": numberID = raw_input("\nEmpfänger eingeben: ") if numberID in numbers: number = numbers[numberID] pause = int(raw_input("\nIntervall in Sekunden: ")) print """ Verfügbare Optionen: [1] Zeitansagen im Format 'Es ist 17:34:22' [2] Zufällige 'Chuck Norris' Jokes [3] Satz für Satz aus einem Buch (Twilight) [4] Fifty Shades of HEX [5] Fröhliches Flaggen raten """ option = int(raw_input("Option auswählen: ")) if option == 1: anzahl = int(raw_input("\nAnzahl Nachrichten: ")) start = 0 elif option == 2: anzahl = int(raw_input("\nAnzahl Nachrichten: ")) start = 0 replaceName = raw_input("\n'Chuck Norris' durch Namen ersetzen: ") if replaceName == "": replaceName = "Chuck Norris" elif option == 3: p = open('content/twilight.txt') book = p.read() pat = re.compile(r'([A-Z][^\.!?]*[\.!?])', re.M) sentences = pat.findall(book) anzahl = int(raw_input("\nAnzahl Nachrichten: ")) start = int(raw_input("\nBei n. Satz anfangen: "))-1 anzahl = anzahl + (start) elif option == 4: anzahl = 50 start = 0 elif option == 5: anzahl = 50 start = 0 import Countries else: anzahl = 0 start = 0 print "\n\nSenden beginnt...\n\n" #tunay bei 207 for i in range(start,anzahl,1): if option == 1: cmdCode = "date +'%H:%M:%S'" message = "Es ist jetzt " + os.popen(cmdCode).read() elif option == 2: curlCode = "curl 'http://api.icndb.com/jokes/random' -s | sed -e 's/.*joke\\\": \\\"//' -e 's/\\\", \\\".*//' -e 's/Chuck Norris/" + replaceName + "/g' -e 's/&quot;/\"/g'" message = os.popen(curlCode).read() elif option == 3: message = sentences[i] elif option == 4: message = "#%s" % "".join(list(repeat(hex(randrange(16, 255))[2:],3))).upper() elif option == 5: flags = os.listdir("content/flags") country = Countries.iso[flags[randrange(1,len(flags))][:2]] message = "Dies ist die Flagge von '%s'."%(country["Name"]) filePath = os.path.abspath("content/flags/%s.png"%country["ISO"]) osaCode = "osascript sendImage.scpt \"%s\" \"%s\""%(number,filePath) osaReturn = os.popen(osaCode).read() print message message = message.replace('"', r'\"') osaCode = "osascript sendText.scpt \"%s\" \"%s\""%(number,message) print "%3d > %s"%((i+1),message) osaReturn = os.popen(osaCode).read() time.sleep(pause)
# Class for each individual node within the Linked List # you do not need to change this class class Node: def __init__(self, data): self.data = data self.next = None # Class for the list structure itself class LinkedList: # This method will run when you create a new # linked list object instance def __init__(self, elements=None): if elements: self.head = Node(elements[0]) # next item to link with next_item = self.head for i in range(1, len(elements)): next_item.next = Node(elements[i]) next_item = next_item.next else: self.head = None # for item, index in enumerate(list): # item = Node(item) # for item, index in enumerate(list.reverse): # if index == len(list.reverse): # self.head = list[0] # else: # if index != 0: # item.next = list.reverse[index-1] # This method will make a nicely printed version # of your linked list structure, don't change it! def __repr__(self): node = self.head nodes = [] while node is not None: nodes.append(node.data) node = node.next nodes.append("None") return " -> ".join(nodes) # Method to add a new node to the start of the linked list def add_to_start(self, node): node.next = self.head self.head = node # Method to add a new node at the end of the linked list def add_to_end(self, node): if self.head: next_item = self.head while(next_item.next): next_item = next_item.next next_item.next=node else: self.head = node # Method to add a new node after an existing element def add_after(self, target_node_data, new_node): next_item = self.head while (next_item.next.data != target_node_data) and (next_item.next.next.data != target_node_data): next_item = next_item.next new_node.next = next_item.next.next next_item.next.next = new_node # Method to remove a node from the linked list def remove_node(self, target_node_data): next_item = self.head while (next_item.next.data != target_node_data) and (next_item.next.next.data != target_node_data): next_item = next_item.next next_item.next = next_item.next.next
############################################### #File Name: Simple_Calc.py #Created By: Ard Aunario #Date Created: 8/31/19 #Description: Simple calculator that does basic math operations ################################################ ################################################ KeepGoing = True Num = input("Enter Number(0 - 9) or 'q' to quit: ") # Check if user input is a number and continues # if Num == 'q': print("Goodbye!") elif int(Num) <= 0 or int(Num) >= 0: # Change Num to integer # value = float(Num) try: while (KeepGoing): Op_input = input("Enter operation ( +, -, *, /, =) or 'q' to quit: ") ValidOp = ['+', '-', '*', '/', '=', 'q'] Op = ValidOp.index(str(Op_input)) if Op == 4: # Print Value # print(str(value)) elif Op == 5: print("Goodbye!") KeepGoing = False else: # Second number user input # Num2 = input("Enter Number(0 - 9) or 'q' to quit: ") if Num2 == 'q': print("Goodbye!") KeepGoing = False elif int(Num2) <= 0 or int(Num2) >= 0: int(Num2) #Addition if Op == 0: value += float(Num2) #Subtraction elif Op == 1: value -= float(Num2) #Mulitplication elif Op == 2: value *= float(Num2) #Division elif Op == 3: value /= float(Num2) print(str(value)) except ZeroDivisionError: print("Invalid operation: Can't divide by zero.") except ValueError: print("Invalid operation: Not a valid operation.") else: print("Invalid input: User input is not an integer.")
#!/usr/bin/env python """ Demo-ing argparse. """ import argparse parser = argparse.ArgumentParser(description='This is a sample program') parser.add_argument("user", help="user") parser.add_argument("age", help="age for the user", type=int) parser.add_argument("-v", "--verbose", help="verbose mode", action="store_true") args = parser.parse_args() print('User {}, Age {}'.format(args.user, args.age)) if args.verbose: print('Running in verbose mode')
# Escribe tus funciones abajo de esta línea def pies_cm(pies): piescm=pies*30.48 return piescm def pulgadas_cm(pulgadas): pulgadascm=pulgadas*2.54 return pulgadascm def yardas_cm(yardas): yardascm=yardas*91.44 return yardascm def main(): print ('1. pies a cm, 2. pulgadas a cm, 3. yardas a cm') convertir=int(input('Introduce una opcion: ')) cantidad=int(input('Introduce la cantidad: ')) if cantidad>0: if convertir==1: print(pies_cm(cantidad)) elif convertir==2: print(pulgadas_cm(cantidad)) elif convertir==3: print(yardas_cm(cantidad)) else: print('Error') else: print('Error') # Escribe tu código abajo de esta línea if __name__ == '__main__': main()
#!/usr/bin/python3 def island_perimeter(grid): """ The amazing Five tas The amazing Five tas """ water = 0 land = 1 perimeter = 0 for col, level in enumerate(grid): for row, parcel in enumerate(level): if parcel == land: if row == 0 or grid[col][row - 1] == water: perimeter += 1 if (row + 1) == len(level) or grid[col][row + 1] == water: perimeter += 1 if row == 0 or grid[col - 1][row] == water: perimeter += 1 if (col + 1) == len(grid) or grid[col + 1][row] == water: perimeter += 1 return perimeter
from datetime import datetime, timedelta from itertools import cycle def timestamp_to_str(value): return value.strftime("%Y-%m-%dT%H:%M:%S.000Z") _now1day = [timestamp_to_str(datetime.now() + timedelta(minutes=i)) for i in range(1, 2400, 25)] print(_now1day) now1day = cycle(_now1day) print(next(now1day)) for i in range(len(_now1day) * 2): print(next(now1day))
# -*- coding: utf-8 -*- """Balance Checker This script allows the user to check if the braces in the given string are balanced The braces could be (), {}, [] or any combination of these This file contains the following function: * main - the main function of the script """ import json import logging.config def config_logger(): with open('configs\\check.json', 'r') as file: config = json.load(file) logging.config.dictConfig(config) config_logger() BALANCE_LOGGER = logging.getLogger(__name__) def check(): """ Main function to Check the balance, using the count of the opening and closing braces """ string = input('Please enter the string:\n') stack = [] open_bracket = ['(', '[', '{'] close_bracket = [')', ']', '}'] for char in string: if char in open_bracket: stack.append(char) elif char in close_bracket: if ((len(stack) > 0) and open_bracket[close_bracket.index(char)] == stack[-1]): stack.pop() else: BALANCE_LOGGER.info("UNBALANCED") return else: continue if len(stack) == 0: BALANCE_LOGGER.info("BALANCED") else: BALANCE_LOGGER.info("UNBALANCED") if __name__ == '__main__': check()
''' Which starting number, under one million, produces the longest chain? ''' MAX = 1000000 def get_next_num(n): if n%2 == 0: n = n/2 else: n = 3*n + 1 return n max_len = 0 max_num = 0 for num in range(2, MAX): count = 0 i = num print num while i!=1: i = get_next_num(i) count += 1 if count > max_len: max_len = count max_num = num print "answer", max_num, max_len
""" There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ MAX = 1000 def check(a,b): TP = 5*(10**5) lhs = 1000*(a+b) rhs = a*b + TP if lhs == rhs: print a,b, 1000-a-b print a*b*(1000-a-b) return True else: return False for a in range(1, MAX): flag = True for b in range(a+1, MAX): if check(a,b): flag = False break if not flag: break
""" Smallest positive integer divisible by all in (1, 20) """ from math import sqrt primes = {} for i in range(2,21): k = int(sqrt(i)) + 1 flag = True for j in range(2, k): if i%j == 0: flag = False break if flag: primes[i] = 1 for i in range(4,20): for p in primes: c = 0 num = i while num%p == 0: c += 1 num = num/p primes[p] = max(primes[p], c) print primes prod = 1 for p in primes: prod *= pow(p, primes[p]) print prod
# Leap year # def is_leap(year): # leap = False # if year%400==0: # leap=True # elif year%100 ==0: # leap=False # elif year%4==0: # leap=True # return leap # year = int(input()) # print(is_leap(year)) #initial matrix if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) list = [] for i in range(x+1): for j in range(y+1): for k in range(z+1): if i+j+k != n: list.append([i,j,k]) print(list)
filename = input("please type file name: ") try: fhand = open(filename) count = dict() for line in fhand: words = line.split() if len(words) == 0: continue if words[0] != "From" : continue if words[1] not in count: count[words[1]] = 1 else: count[words[1]] += 1 print(count) except: print("This file does not exist in this directory")
# counts lines in text document fhand = open('mbox-short.txt') count = 0 for line in fhand: count = count + 1 print('Line Count:', count)
celsius = input('Enter Degrees Celsius') fahrenheit = int(celsius)*9/5+32 print(fahrenheit)
fhand = open("data/words.txt") keys = dict() for lines in fhand: words = lines.split() for word in words: if word not in keys: keys[word] = 1 else: keys[word] += 1 print(keys)
import string fname = input("Enter the file: ") try: fhand = open(fname) except: print("File cannot be opened: ", fname) exit() counts = dict() for line in fhand: line = line.rstrip() line = line.translate(line.maketrans(" ", " ", string.punctuation)) line = line.lower() words = line.split() for word in words: letter = word.split() for letter in word: if letter not in counts: counts[letter] = 1 else: counts[letter] += 1 l = list() for key, val in list(counts.items()): l.append((val, key)) l.sort(reverse=True) for key, val in l: print(key,val)
hours = int(input('Enter Hours')) rate = input('Enter Pay') if hours > 40: regpay = hours * float(rate) overtime = (0.5 * float(rate)) * (hours - 40) pay = regpay + overtime else: pay = hours * float(rate) print(pay)
# a and b are aliased meaning the are referenced together a = [1,2,3,4] a = b print(b[0]) # changes made in one affect the other b = [17,2,3,4] print(a)
#Jen Anderson #[email protected] #CS311-400 #Homework2 #Question4 import sys import math numOfPrimes = int(sys.argv[1]) primeArray = [] #This function returns 1 if x is prime and 0 if x is not prime def isPrime(x): if x == 2 or x == 3: return int(1) if x%2 == 0: return int(0) if x%3 == 0: return int(0) maxToCheck = math.ceil(math.sqrt(x)) i = 4 while i <= maxToCheck: if x % i == 0: return int(0) i += 1 return int(1) x = 2 lengthOfArray = len(primeArray) while (lengthOfArray < numOfPrimes): if isPrime(x) == 1: primeArray.append(x) lengthOfArray += 1 x += 1 print primeArray[numOfPrimes - 1]
def _append_points(main_list, sublist): for item in sublist: main_list.append(item) class VertexPoints: def __init__(self): self.x = [] self.y = [] self.z = [] def add_point(self, x, y, z): self.x.append(x) self.y.append(y) self.z.append(z) def add_points(self, x_list, y_list, z_list): _append_points(self.x, x_list) _append_points(self.y, y_list) _append_points(self.z, z_list) if __name__ == '__main__': a = [1, 2, 3, 4] b = [5, 6, 7, 8] c = [5, 6, 7, 8] d = VertexPoints() d.add_points(a, b, c) print(d.x)
#!/usr/bin/python #-*- coding: utf-8 -*- # author:milittle # Given a test score, grade returns the corresponding letter grade. import bisect def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): # i = bisect.bisect(breakpoints, score) print(i) return grades[i] def main(): print([grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]) if __name__ == '__main__': main()
#!/usr/bin/python #-*- coding: utf-8 -*- # author: milittle # index.py uses dict.setdefault to fetch and update a list of word occur‐ # rences from the index in a single line Example 3-4. import re import collections import sys WORD_RE = re.compile('\w+') def test(): index = collections.defaultdict(list) #用什么作为默认类型,当键值不存在的时候,就会创建一个list,返回list的引用 with open('./test.txt', encoding='utf-8') as fp: for line_no, line in enumerate(fp, 1): for match in WORD_RE.finditer(line): word = match.group() column_no = match.start() + 1 location = (line_no, column_no) index[word].append(location) # print in alphabetical order for word in sorted(index, key=str.upper): print(word, index[word]) def main(): test() if __name__ == '__main__': main()
from pulp import * from pandas import DataFrame, read_csv import pandas as pd # Reading the data file file = r'diet.xls' df = pd.read_excel(file, index = True, nrows=64) #print(df.tail()) # Defining the LP model = LpProblem("The Diet problem",LpMinimize) # Setting up the problem foods = df['Foods'].values prices = df['Price/ Serving'].values food_price = dict(zip(foods,prices)) nut_cols = df.columns[3:] food_nuts = {food: {nut: df.loc[df["Foods"] == food, nut].values[0] for nut in nut_cols} for food in foods} # Defining the variables x = LpVariable.dicts("unit_of_food",foods,0) min_nuts = [1500,30,20,800,130,125,60,1000,400,700,10] max_nuts = [2500,240,70,2000,450,250,100,10000,5000,1500,40] # Generatings the constriants i = 0 for nut in nut_cols: model += lpSum([food_nuts[food][nut] * x[food] for food in foods]) >= min_nuts[i] model += lpSum([food_nuts[food][nut] * x[food] for food in foods]) <= max_nuts[i] i += 1 # Define the objective function model += lpSum([food_price[food] * x[food] for food in foods]), "Total Cost per food" # Solve LP model.writeLP("The_Diet.lp") model.solve() print("Status:", LpStatus[model.status]) for sol in model.variables(): print(sol.name, "=", sol.varValue)
# Fibonacci Sequence or Number # 0 1 1 2 3 5 8 13 21 def feb(n): a =0 b =1 print(a) print(b) for i in range(2,n): c = a + b a = b b = c print(c) feb(10)
# def add(x,y): # a = x+y # print(a) # add(90,80) def calculator(x,y): c = x + y return c num1 = int(input("Enter Num1 ?")) num2 = int(input("Enter Num2 ?")) final = calculator(num1,num2) print(final)
import string # x =int(input("Enter Any Number? ")) # r = x % 2 # if r==0: # print("This is an even number") # if x > 5: # print("This is even and also greater than 5") # else: # print("This is even less than 5") # else: # print("This is odd Number") # user = "admin" # if (user == "admin"): # print("You are authiise to login") # elif (user == "admin1"): # print("You can login now") # elif (user == "admin2"): # print("You are also not allow") # else: # print("Dont try it again") # Assignment # 1) write a code to check if a giving number is possitive or native # 2) Write a code to take three values from a user and check which of them is the greattest number a = float(input("Enter Number? ")) if a > 0: print("This is a Positive Number") elif a < 0: print("This is Nagative Number") else: print("Enter a number")
d = {1:[1,2],2:[2,4]} grid = [[True, True, True, True, True, False], [False, False, True, True, True, False], [True, True, True, False, True, True], [True, False, False, True, True, False], [True, False, True, True, False, True], [True, False, True, True, True, False]] n = 1 defM = [] matrix = [] for i in grid: matrix = [] for x in i: if (x == True): matrix.append(n) n=n+1 else: matrix.append(-1) defM.append(matrix) print (defM)
import pygame pygame.init() win = pygame.display.set_mode((500,540)) #properties for character x = 250 y = 400 radius = 20 vel_x = 10 vel_y = 10 jump = False run = True while run: pygame.time.delay(100) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False # movement # -y = up # +y = down userInput = pygame.key.get_pressed() # variable for movement if userInput[pygame.K_LEFT] and x > 0: # left x = 0 <-- will change with canvas size x -= vel_x if userInput[pygame.K_RIGHT] and x < 500: # Right x = 500 <-- will change with canvas size x += vel_x # Jumping effect # checking is jump is False AND if user is clicking the space button if jump is False and userInput[pygame.K_SPACE]: jump = True if jump is True: y -= vel_y * 5 vel_y -= 1 if vel_y < -10: jump = False vel_y = 10 win.fill((33, 75, 148)) #fill window with color so the window gets updated pygame.draw.circle(win,(232, 226, 176),(int(x), int(y)) ,radius) pygame.display.update() pygame.quit()
numero1 = 0 numero2 = 0 resultado = 0 operacao = '' numero1 = int(input("Digite o primeiro número:")) operacao = input('Coloque a operação:') numero2 = int(input("Digite o segundo número:")) if operacao =='+': resultado = numero1 + numero2 elif operacao =='-': resultado = numero1 - numero2 elif operacao =='*': resultado = numero1 * numero2 elif operacao =='/': resultado = numero1 / numero2 else: resultado = 'Operação inválida!' print(str(numero1) + ' ' + str(operacao) + ' ' + str(numero2) + ' = ' + str(resultado))
from enum import Enum class ChoiceEnum(Enum): @classmethod def choices(cls): choices = list() # Loop thru defined enums for item in cls: choices.append((item.value, item.name)) # return as tuple return tuple(choices) def __str__(self): return self.name def __int__(self): return self.value class QuestionType(ChoiceEnum): radio = 1 multiselect = 2 informational = 3
"""RGB Flashing Lights ## Overview This excercise will show you how to flash the LED's of the board rotating through three different colors; Red, Green, and Blue. ## Setup In this excercise there's no need to configure the board with anything besides coping `code.py` onto the CPE board. """ import time from adafruit_circuitplayground.express import cpx # Here we define three different colors using a tuple structure. There # are three numbers in the tuple, each representing how much of a # specific color should be displayed. For the CPE board, the three # colors are Red, Green, and Blue (RGB). The values possible ranges # from 0 (none of that color) to 256 (all of that color). In this # example we only do three colors; Red, Green, and Blue. RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # We know place these colors into another tuple for us to iterate # (step through) later on. COLORS = (RED, GREEN, BLUE) # Adjust the brightness to 30% of the possibility. Possible range is # 0.0 to 1.0 cpx.pixels.brightness = 0.3 # This option ensures that the LED's are only updated when the `.show()` # is called on the LED's. cpx.pixels.auto_write = False # Get the current time as "start" to see how much time has passed later # on. start = time.monotonic() # color_i is used to keep track of which color to display next. color_i = 0 # This is the main loop of the board. This will run infinetly. while True: # Get the current time now = time.monotonic() # Because of how fast this loop is going, if we switched colors each # loop, it would be too fast to see the changes correctly. So, we # only update the LED's after at least 0.5 seconds have passed. if now - start > 0.5: # Get the color from the tuple we defined above, set that to be # the next color for the LED's `.fill()`, and then update the # board to actually display that color `.show()` color = COLORS[color_i] cpx.pixels.fill(color) cpx.pixels.show() # The `%` operator may be unfamiliar to you. This is the # "modulo" operator and basically returns the "remainder" of # the division. For example, in our case, there are three # colors in our tuple `COLORS` above, so that tuple has a length # of 3. With that in mind: # # 2 % 3 = 2 # 3 % 3 = 0 # 4 % 3 = 1 (Note: this will never happen in our code; see below) # # When we reach the last item in the `COLORS` list, we need to # restart back to the beginning, so we use this "modulo" aka mod # operator to do just that. This means that we'll infintely # change `color_i` like so: # # 0, 1, 2, 0, 1, 2, 0, ... color_i = (color_i + 1) % len(COLORS) # Since we've made an update to the LED's we want to reset when # we make the update to the LED's to another 0.5 seconds from # now, so we need to update `start` to the current time. start = now
a, b, c = input().split() a = float(a) b = float(b) c = float(c) lista = [a, b, c] lista.sort(reverse = True) a = lista[0] b = lista[1] c = lista[2] if (a >= b + c): print("NAO FORMA TRIANGULO") else: if(a ** 2 == b ** 2 + c ** 2): print("TRIANGULO RETANGULO") if(a ** 2 > b ** 2 + c ** 2): print("TRIANGULO OBTUSANGULO") if(a ** 2 < b ** 2 + c ** 2): print("TRIANGULO ACUTANGULO") if(a == b and b == c): print("TRIANGULO EQUILATERO") if((a == b and b != c) or (a == c and b != c) or (b == c and c != a)): print("TRIANGULO ISOSCELES")
aux = 0 n1 = int(input("Numero 1: ")) n2 = int(input("Numero 2: ")) n3 = int(input("Numero 3: ")) if (n1 > n2): aux = n1 n1 = n2 n2 = aux if (n1 > n3): aux = n1 n1 = n3 n3 = aux if (n2 < n1): aux = n2 n2 = n1 n1 = aux if (n2 > n3): aux = n2 n2 = n3 n3 = aux if (n3 < n1): aux = n3 n3 = n1 n1 = aux if (n3 < n2): aux = n3 n3 = n2 n2 = aux print(n1, " - ", n2, " - ", n3)
from random import * numUser = int(input("Tente adivinhar o número (de 0 a 5) que o computador está pensando... ")) numComputer = randint(0, 5) if numUser == numComputer: print(f""""Quanta sorte! Seu numero {numUser}, numero computador {numComputer}""") else: print(f"""Mais sorte da próxima vez! Seu numero {numUser}, numero computador {numComputer}""")
#funcao zip lista1 = [1, 2, 3, 4, 5] lista2 = ["Pão", "Ovo", "Leite", "Sabonete", "Amaciante"] #mesma quantidade de itens da lista1 lista3 = ["R$4,00", "R$10,00", "R$3,00", "R$1,00", "R$12,00"] # o zip serve para concatenar (juntar) duas ou mais listas em uma só for numero, nome, valor in zip(lista1, lista2, lista3): print(numero, nome, valor)
''' Criar uma classe Carro com no mínimo 3 propriedades e métodos. ''' # Criando a calsse Carro class Carro: # Definindo o construtor e passando os parâmetros da classe def __init__(self, marca, cor, combustivel, kmRodado): self.marca = marca self.cor = cor self.combustivel = combustivel self.kmRodado = kmRodado # Criando os métodos da classe: postoGasolina, elogioCorCarro, exibeTodasInformacoes # Vê se o combustivel do carro está na promoção def postoGasolina(self): if self.combustivel == 'Comum': print('Que legal a comum está na promoção! Pode encher o tanque :D') else: print('Poxa vida só a comum está na promoção, vou ver o outro posto D:') # Pega a cor do carro e da um elogio def elogioCorCarro(self): print(f"Carros de cor {self.cor} são estilosos") # Printa na tela todas as informações do carro def exibeTodasInformacoes(self): print(f"Marca: {self.marca}\nCor: {self.cor}\nCombustível: {self.combustivel}\nKm andado: {self.kmRodado}") # Criando um objeto da classe Carro e passando os parâmetros carro1 = Carro("Honda", "Preto", "Comum", 150000) carro1.postoGasolina() carro1.elogioCorCarro() carro1.exibeTodasInformacoes()
#--- Exercício 4 - Funções #--- Crie uma função que imprima um cabeçalho de acordo com uma variável de nome da empresa (passada por parametro) #--- A impressão deve ocorrer via multiplicação de strings #--- A multiplicação deve ser feita com base em uma variável que contenha o caracter a ser multiplicado #--- Crie uma segunda função que imprima um rodapé utilizando a mesma técnica #--- Crie uma chamada para as duas função, para exibir o resultado no console def cabecalho(empresa): print("-" * 20 + empresa + "-" * 20) def rodape(): print("-" * 45) nomeEmpresa = input("Qual é o nome da empresa? ") cabecalho(nomeEmpresa) rodape()
#Funcao enumarate lista = ["abacate", "bola", "cachorro"] #com o enumarate for i, item in enumerate(lista): print(i, "-", item) #sem o enumarate: #for i in range(len(lista)): # print(i, "-", lista[i])
import sqlite3 conn = sqlite3.connect('clientes.db') cursor = conn.cursor() cursor.execute(""" SELECT * FROM clientes WHERE id = ?; """, [1]) print(cursor.fetchone()) cursor.execute(""" SELECT * FROM clientes WHERE idade > ?; """, [21]) print(cursor.fetchall()) cursor.execute(""" SELECT * FROM clientes WHERE cidade like '%Belo%'; """) # Belo% - devolve as cidades que terminam com Belo // %Belo - devolve as cidades que comecam com Belo print(cursor.fetchall()) conn.close()
# https://www.youtube.com/watch?v=RhtsCbKyYoA # Classes deixa o programador utilizar variáveis 'locais' fora do escopo delas # Boa prática: Nomes de classes com letras maiúsculas class DidaticaTech(): def __init__(self, valorAntigo: int, valorNovo:int): self.valorAntigo = valorAntigo self.valorNovo = valorNovo def incrementa(self): # O objeto que instancia a classe torna-se o self self.valorNovo += self.valorAntigo return self.valorNovo # Esse método verificará se o valor (após ser incrementado) passar de 12 def verifica(self): if(self.valorNovo > 12): return("Ultrapassou 12") else: return("Não ultrapassou 12") # Esse método eleva o resultado a algum número def exponencial(self, a): return self.valorNovo ** a # Esse método além de incrementar eleva ao número passado (2) def incrementa_quadrado(self): self.incrementa() self.exponencial(2) # Quando se instancia uma classe você tem acesso a tudo dentro dela objDidaticaTech = DidaticaTech(10, 1) # Modo 1 de acessar um método de uma classe a = DidaticaTech(10, 5).incrementa() # Modo 2 de acessar um método de uma classe x = objDidaticaTech.incrementa() # Método é o nome dado a uma funça dentro de uma classe print(x, a) print(objDidaticaTech.exponencial(2)) # Com o obj instanciado da classe temos acesso a 'variaveis locais' os atributos #print(objDidaticaTech.valorAntigo) # Essa classe herda tudo de sua super classe (DidaticaTech). Com isso ela tem acesso # a todos os atributos e métodos que existem dentro dela, além disso pode criar seu próprio # atributos e métodos. class Calculo(DidaticaTech): # Para não sobrescever o contrutor da superclasse (DidaticaTech) é necessário usar o super (invoca os atributos do construtor da classe pai) def __init__(self, divisor): super().__init__(valorAntigo: int, valorNovo:int) self.divisor = divisor def decrementa(self, n): return self.valorNovo - n def divide(self): return self.valorNovo / self.divisor c = Calculo(10, 5) print(c.incrementa()) # Aqui mesmo criando um objeto de Calculo ele ainda pode acessar informações de DidaticaTech print(c.decrementa(3))
preco = 0 distancia = int(input("Qual a distância da viagem? ")) if distancia <= 200: preco = distancia * 0.50 else: preco = distancia * 0.45 print("O preço é {:.2f}".format(preco))
####################################################################################################### # Faça um programa que simule um lançamento de dados. Lance o dado 100 vezes e armazene os resultados em um vetor. # Depois, mostre quantas vezes cada valor foi conseguido. Dica: use um vetor de contadores(1-6) e uma função para # gerar numeros aleatórios, simulando os lançamentos dos dados. ####################################################################################################### from random import randint lista = [] for i in range(100): lista.append(randint(1, 6)) print(f"O número 1 apareceu {lista.count(1)} vezes\n" f"O número 2 apareceu {lista.count(2)} vezes\n" f"O número 3 apareceu {lista.count(3)} vezes\n" f"O número 4 apareceu {lista.count(4)} vezes\n" f"O número 5 apareceu {lista.count(5)} vezes\n" f"O número 6 apareceu {lista.count(6)} vezes")
def cadastroPessoa(): nome = input("Digite o nome: ") if(nome.isspace() or nome == ''): while(nome.isspace() or nome == ''): nome = input("Nome em branco. Digite novamente: ") sobrenome = input("Digite o sobrenome: ") if(sobrenome.isspace() or sobrenome == ''): while(sobrenome.isspace() or sobrenome == ''): sobrenome = input("Sobrenome em branco. Digite novamente: ") idade = input("Digite a idade: ") if(idade.isspace() or idade == ''): while(idade.isspace() or idade == ''): idade = input("Idade em branco. Digite novamente: ") idade = int(idade) if (idade >= 18): dictPessoa = {'Nome':nome, 'Sobrenome':sobrenome, 'Idade':idade} arquivoPessoas = open('pessoas.txt', 'a') arquivoPessoas.write(f"{dictPessoa['Nome']};{dictPessoa['Sobrenome']};{dictPessoa['Idade']};") arquivoPessoas.close() arqPessoas = open('pessoas.txt', 'r') numeroCadastro = 0 for contador in arqPessoas: numeroCadastro = numeroCadastro + 1 arqPessoas.close() dictPessoa = {'ID':numeroCadastro} arquivoPessoas = open('pessoas.txt', 'a') arquivoPessoas.write(f"{dictPessoa['ID']} \n") print(f"Cadastrado com sucesso! Seu é é {numeroCadastro}") else: print("Não é possivel cadastrar menores de 18 anos")
frase = input("Digite a frase: ") letra = input("Digite a letra que você deseja pesquisar: ") print(f"A letra {letra} aparece {frase.count(letra)} vezes") # Tem como pesquisar uma letra específica -> frase.count('u') # Tem como pesquisar uma apenas um pedaço da frase -> frase.count('u', 0, 13) # Uma outra função legal é o frase.find('qualquercoisa') -> retorna a posição de onde começa a palavra qualquercoisa, # caso a frase não tenha a palavra 'qualquercoisa' o retorno será -1 # Pode-se utilizar o 'in' para verificar se existe uma palavra na frase, o retorno é um boleano -> 'Curso' in frase
metros = float(input("Entre com os metros: ")) print("{}km".format(metros/1000)) print("{}hm".format(metros/100)) print("{}dam".format(metros/10)) print("{}dm".format(metros*10)) print("{}cm".format(metros*100)) print("{}mm".format(metros*1000))
####################################################################################################### # Faça um Programa que peça os 3 lados de um triângulo. # O programa deverá informar se os valores podem ser um triângulo. # Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno. ####################################################################################################### def triangulos(lado1, lado2, lado3): lista_lados = [lado1, lado2, lado3] lista_lados = sorted(lista_lados, reverse=True) lado1, lado2, lado3 = lista_lados[0], lista_lados[1], lista_lados[2] if (lado1 >= lado2 + lado3): print("Não forma triângulo") else: if lado1 == lado2 and lado1 == lado3: print("Triângulo equilátero") elif lado1 == lado2 and lado1 != lado3 or lado2 == lado3 and lado2 != lado1 or lado1 == lado3 and lado1 != lado2: print("Triângulo isósceles") elif lado1 != lado2 and lado1 != lado3: print("Triângulo escaleno") lado1 = float(input("Digite o primeiro lado do triângulo: ")) lado2 = float(input("Digite o segundo lado do triângulo: ")) lado3 = float(input("Digite o terceiro lado do triângulo: ")) triangulos(lado1, lado2, lado3)
from random import randint movimentos= 0 casa = 1 venceu = 0 jogada= 0 while venceu == 0: if movimentos >= 6: print("Você atingiu o limite de movimentos!") break; else: while casa == 1 and movimentos <7: print("Você esta na casa: ",casa) print("Você ainda tem", 7-movimentos,"movimentos") print("Escolha seu caminho:") print("[1]- Caminho vermelho") print("[2]- Caminho preto") jogada = int(input("")) print("") if jogada == 1: casa = 2 movimentos = movimentos+1 break; elif jogada == 2: casa = 4 movimentos = movimentos+1 break; else: print("Opção inválida!") print("") break; while casa == 3 and movimentos <7: print("Você esta na casa: ",casa) print("Você ainda tem", 7-movimentos,"movimentos") print("Escolha seu caminho:") print("[1]- Caminho vermelho") print("[2]- Caminho preto") jogada = int(input("")) print("") if jogada == 1: casa = 4 movimentos = movimentos+1 break; elif jogada == 2: casa = 5 movimentos = movimentos+1 break; else: print("Opção inválida!") print("") break; while casa == 4 and movimentos <7: print("Você esta na casa: ",casa) print("Você ainda tem", 7-movimentos,"movimentos") print("Escolha seu caminho:") print("[1]- Caminho vermelho") print("[2]- Caminho preto") jogada = int(input("")) print("") if jogada == 1: casa = 5 movimentos = movimentos+1 break; elif jogada == 2: casa = 6 movimentos = movimentos+1 break; else: print("Opção inválida!") print("") break;
# 题目:将一个列表的数据复制到另一个列表中。 list=[1,5,6,40] m=list[:] print(m)
class Module: def __init__(self, nom, voulumeHoraireTotal): self.nom = nom self.voulumeHoraireTotal = voulumeHoraireTotal def ajouterModule (self, my_liste): nom = input("\n Nom : \n") voulumeHoraireTotal = input("\n voulume Horaire Total : \n") Module1 = Module (nom,voulumeHoraireTotal) my_liste.append(Module1) return my_liste def ModifierModule (self , my_liste): try: id = int(input("\n Saisir l\'id : \n")) pos = -1 i = 0 while i <= len(my_liste): if i == id : pos = id i = i + 1 if pos == -1: print(len(my_liste)) print(" cet Module n\'existe pas dans la liste ") else: nom = input("\n Nom : \n") voulumeHoraireTotal = input("\n voulume Horaire Total : \n") my_liste[pos].nom = nom my_liste[pos].voulumeHoraireTotal = voulumeHoraireTotal except: print(" Vous devez saisir un entier svp !! ") return my_liste def printListModule(self,my_liste): for i,Module in enumerate(my_liste): print("\n-------------------------------------------------------------------------\n") print(" id : ", i , "\n Nom : ", Module.nom,"\n Volume Horaire Total ", Module.voulumeHoraireTotal) print("\n-------------------------------------------------------------------------\n") def printInfosModuleById(self,my_liste): try: id = int(input("\n Saisir l\'id : \n")) pos = -1 i = 0 while i <= len(my_liste): if i == id : pos = id i = i + 1 if pos == -1: print(len(my_liste)) print(" cet Module n\'existe pas dans la liste ") else: for i,Module in enumerate(my_liste): if i == pos : print("\n-------------------------------------------------------------------------\n") print(" id : ", i , "\n Nom : ", Module.nom,"\n Volume Horaire Total ", Module.voulumeHoraireTotal) except: print(" Vous devez saisir un entier svp !! ") def deletModuleById(self,my_liste): try: id = int(input("\n Saisir l\'id : \n")) pos = -1 i = 0 while i <= len(my_liste): if i == id : pos = id i = i + 1 if pos == -1: print(len(my_liste)) print(" cet Module n\'existe pas dans la liste ") else: my_liste.pop(pos) print(" Supprission effectuee avec succes ....!!! ") except: print(" Vous devez saisir un entier svp !! ") return my_liste
# source: https://cses.fi/problemset/task/1071 def find(y, x): hightest = max(x, y) lowest = min(x, y) if ((y == hightest and y % 2 == 0) or (x == hightest and x % 2 != 0)): return hightest ** 2 - lowest + 1 return hightest ** 2 - 2 * hightest + lowest + 1 n = int(input()) inputs = [] for i in range(0, n): line = input().split() inputs.append( [ int(line[0]), int(line[1]) ] ) for i in inputs: y = i[0] x = i[1] print(find(y, x))
name = input("enter your name") print(name) a= """My name is Lekshmi I work for IBS Software. I am working in Traveldoo""" print(a)
thisset = {"apple", "banana", "cherry"} print(thisset) thisset = set(("apple", "banana", "cherry")) print("banana" in thisset) thisset.add("orange") print(thisset) thisset = {"apple", "banana", "cherry"} thisset.update(["orange", "mango", "grapes"]) print(thisset) thisset.pop() print(thisset)
# -*- coding = utf-8 -*- # Author:ZhouShuyu # @Time : 2021/8/19 15:10 # @File : p6_while_loop.py ''' i = 0 while i< 5 : print("当前是第%d次执行循环" %(i+1)) print("i=%d" %i) i+=1 ''' #1-100求和 #我自己写的 i=0 a = 0 while i<100 : i += 1 a += i print(a) n = 100 sum = 0 counter = 1 while counter <=n: sum=sum+counter counter+=1 print("1- %d 和为:%d"%(n,sum)) count=0 while count<5: print(count,"<5") count+=1 else: print(count,"大于或等于5") i=0 while i<10: i=i+1 print("-"*30) if i==5: break print(i) i=0 while i<10: i=i+1 print("-"*30) if i==5: continue #跳过了第五次循环 print(i)
# -*- coding = utf-8 -*- # Author:ZhouShuyu # @Time : 2021/8/19 14:54 # @File : p6_for_loop.py ''' for i in range(5): #for循环的基本使用方式,可以打印 0 1 2 3 4 print(i) ''' ''' for i in range(0,10,3): #表示从 0 开始到 10 ,步进值为 3 .打印结果 0 3 6 9 ,每次加 3 相当于 for(int i=0;i<10;i+=3) print(i) ''' ''' for i in range(-10,-100,-30) : #结果 -10 -40 -70 print(i) ''' ''' name = "kunming" for x in name : #会依次打印kunming里的每个字母 print(x,end="\t") ''' a = ["aa","bb","cc","dd"] for i in range(len(a)): #加入len() 可以获取数组元素个数 print(i,a[i])
# -*- coding = utf-8 -*- # Author:ZhouShuyu # @Time : 2021/9/15 14:56 # @File : def.py #函数的定义 ''' def printinfo(): print("----------------------") print(" 人生苦短,我用python ") print("----------------------") #函数的调用 printinfo() ''' #带参的函数 ''' def add2Num(a,b): c = a+b print(c) add2Num(11,22) ''' #带返回值的函数 ''' def add2Num(a,b): return a+b #通过 return来返回运算结果 result = add2Num(11,22) print(result) #print(add2Num(11,22)) ''' #返回多个值的函数 ''' def divide(a,b): shang = a//b yushu = a%b return shang,yushu #多个返回值用逗号分隔 sh,yu = divide(5,2) #需要使用多个值来保存返回内容 print("商:%d,余数:%d"%(sh,yu)) ''' ''' #打印一条线 def hengxian(n): a= print("-"*n) #调用上面的函数打印任意长度的线 def shuru(): c = int(input("请输入想打印的横线的长度:")) hengxian(c) shuru() ''' ''' #求三个数的和 def sum(a,b,c): return a+b+c print(sum(10,20,30)) #求三个数的平均值 def avg(a,b,c): sumresult=sum(a,b,c) avg=sumresult//3 return avg result = avg(10,20,30) print("平均值为:%d"%result) ''' #全局变量和局部变量 ''' def test1(): a = 300 #局部变量 print("test1-------修改前: a = %d"%a) a = 100 print("test1-------修改前: a = %d"%a) def test2(): a = 500 #不同的函数可以定义相同的名字,彼此无关 print("test2------a= %d"%a) test1() test2() ''' ''' a= 100 #全局变量 def test1(): print(a) def test2(): print(a) #调用全局变量a test1() test2() ''' #全局变量和局部变量相同名字:局部变量优先使用;没有局部变量,默认访问全局变量 #在函数中修改全局变量 a = 100 def test1(): global a #声明全局变量在函数中的标识符 global print("test1-------修改前: a = %d"%a) a = 200 print("test1-------修改前: a = %d"%a) def test2(): print("test2------a= %d"%a) #全局变量已经被修改 test1() test2()