text
stringlengths
37
1.41M
""" 给定一个正整数,返回它在 Excel 表中相对应的列名称。 例如, 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... 示例 1: 输入: 1 输出: "A" 示例 2: 输入: 28 输出: "AB" 示例 3: 输入: 701 输出: "ZY" """ # 解答:相当于是把10进制数转换成26进制数,只是转换后要-1 class Solution: def convertToTitle(self, n: int) -> str: answer = "" ...
""" 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。 注意: 答案中不可以包含重复的四元组。 示例: 给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ] """ # 解答: 类似三数之和的做法,排序后排除不可能的情况为了加快速度,然后二重循环,并用首尾指针来找到适合...
""" 根据一棵树的中序遍历与后序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3] 返回如下的二叉树: 3 / \ 9 20 / \ 15 7 """ # 解答:类似105题的做法,只是把前序改成了后序,而后序最后一位是根节点,仍然用递归来做 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x ...
""" 给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回锯齿形层次遍历如下: [ [3], [20,9], [15,7] ] """ # 解答:和102类似,就是需要用一个序号来判断该层需不需要逆序 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # se...
""" 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。 示例 1: 输入: nums = [1,2,3,1], k = 3 输出: true 示例 2: 输入: nums = [1,0,1,1], k = 1 输出: true 示例 3: 输入: nums = [1,2,3,1,2,3], k = 2 输出: false """ # 解答:直接二重循环会超时,利用hashmap记录上一个元素的下标,当存在hashmap时和当前下标做比较看是否于等于k即可 class Solution: def co...
""" 请判断一个链表是否为回文链表。 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1->2->2->1 输出: true 进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题? """ # 解答:快慢指针找到中点,然后翻转后半部分 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def isPalindrome(self, head...
""" 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。 示例: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // 返回 true trie.search("app"); // 返回 false trie.startsWith("app"); // 返回 true trie.insert("app"); trie.search("app"); // 返回 true 说明: 你可以假设所有的输入都是由小写字母 a-z 构成的。 保证所有输入均为非空字符...
""" 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 必须原地修改,只允许使用额外常数空间。 以下是一些例子,输入位于左侧列,其相应输出位于右侧列。 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 """ # 解答: 首先从最后一个元素开始往前遍历,每一个元素再从后往前直到自己为止和后面的元素进行比较,如果当前元素小于遍历到的某个元素(此元素同时为后面元素的最小元素),即和其交换, # 然后把当前遍历元素后面的元素进行升序排序 # 如果已经是降序,最后再进行逆序即可 class...
""" 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。 示例 1: 输入: 11110 11010 11000 00000 输出: 1 示例 2: 输入: 11000 11000 00100 00011 输出: 3 """ # 解答:dfs做,碰到1的结果+1然后进行dfs,把相连的1都设为0 class Solution: def numIslands(self, grid) -> int: if len(grid) == 0: return...
""" 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 进阶: 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 """ # 解答:用分治做,注意处理跨越中间的一段 class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ ...
#Data input x = int(input("Please input the 4-digit number \n")) #Calculation workflow first_digit = x // 1000 print(first_digit) last_digit = x % 1000 % 100 % 10 result = first_digit % last_digit #Output the result print("Result is " + str(result))
# Get the users names user1 = input("What is Player 1's name? ") user2 = input("What is Player 2's name? ") # Get the users choices user1_answer = input(user1 + ", do you want to choose rock, paper or scissors? ").lower() user2_answer = input(user2 + ", do you want to choose rock, paper or scissors? ").lower() if user...
# Python is case-sensitive a = 3.1 flag = False c = '*' * 10 # type conversion and type checking d = type(str(1)) # multi-line string course = '''Hi John, Thank you ''' # square bracket of a string course = 'Python for beginners' a = course[:] b = type(course[0:3]) # formatted string first = 'John' last = 'Smith'...
# load the iris dataset as an example from sklearn.datasets import load_iris iris = load_iris() # store the feature matrix (X) and response vector (y) X = iris.data y = iris.target # splitting X and y into training and testing sets from sklearn.model_selection import train_test_split X_train, X_test, y_tr...
from tkinter import * root=Tk() root.title("Simple Calculator") e=Entry(root, width=35, borderwidth=5) e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def buttonAdd(): return button_1=Button(root, text="1", padx=40, pady=20, command=buttonAdd) button_2=Button(root, text="2", padx=40, pady=20, command=bu...
str1 = 'First String' try: istr = int(str1) except: istr = 'hoi nai' print('1st', istr) str1 = '123' try: istr = int(str1) except: istr = 'hoi nai' print('2nd', istr)
from datetime import date #Año, mes y dia (el presente) actual_Year = date.today().year actual_Month = date.today().month actual_Day = date.today().day def menu(): print('\nHola! Calculemos el tiempo que has vivido') age = int(input('¿En que año naciste?: ')) print(''' Meses del año 1. Enero 2...
def operacion(base, repeticiones): for i in range(1, repeticiones): print(str(base) + ' x ' + str(i) + ' = ' + str(base*i)) factor_1 = '''Tablas de multiplicar Elige el numero que quieres multiplicar: ''' base = int(input(factor_1)) factor_2 = int(input('Elige el numero de veces que lo quieres multiplicar...
#!/usr/bin/env python import random # Quick sort using hoarse partition is not stable sort either! # Think about this array: # 4 3 2 5 2 4 5 2 5 def hoare_partition(A, p, r): x = A[p] i = p - 1 j = r + 1 while True: j -= 1 while A[j] > x: j -= 1 i += 1 w...
#!/usr/bin/env python def find_max_subarray_brute_force(A, p, r): max_array_sum = A[p] max_left = p max_right = p for i in xrange(p,r + 1): array_sum = 0 for j in xrange(i, r + 1): array_sum += A[j] if array_sum > max_array_sum: max_array_sum = ...
#!/usr/bin/env python import random # Some notes: hight is from bottom to top class MYHEAP(list): def __init__(self, i): self.__heap_size = 0 list.__init__(self, i) @property def heap_size(self): return self.__heap_size @heap_size.setter def heap_size(self, value): ...
#!/usr/bin/env python import random def partition(A, p, r): key = A[p] i = p - 1 for j in xrange(p + 1, r + 1): if A[j] < key: i += 1 A[i] , A[j] = A[j], A[i] i += 1 return i def randomized_partition(A, p, r): i = random.randint(p, r) A[p], A[i] = A[i],...
file = open("mbox-short.txt") count = dict() for lines in file: words = lines.split() if len(words) < 1 : continue if words[0] == "From": name = words[1] count[name] = count.get(name,0) + 1 biggestcount = None biggestword = None for name,count in count.items(): if biggestcount i...
""" More list manipulations """ def split(in_list, index): """ Parameters ---------- in_list: list index: int Returns ------- Two lists, spliting in_list by 'index' Examples ------- >>> split(['a', 'b', 'c', 'd'], 3) (['a', 'b', 'c'], ['d']) """ list1 = in_l...
def find_duplicate(list_of_numbers): n = len(list_of_numbers)-1 no_duplicate_sum = (n+1)*n/2 duplicate_sum = 0 for number in list_of_numbers: duplicate_sum += number return duplicate_sum - no_duplicate_sum print(find_duplicate([1,2,3,4,5,5]))
a = round(float(input()), 1) b = round(float(input()), 1) if 0 <= a <= 10 and 0 <= b <= 10: media = ((3.5*a) + (7.5*b))/11 print(f'MEDIA = {media:.5f}')
import re # re --> importa a biblioteca de expressões regulares (regex) linhas = int(input()) for i in range(linhas): msg = str(input()) msg_new = '' for j in msg: # Se o string presente em j for compativel com os padrões alfabeticos(alpha) a-z e A-Z, os caracteres serão deslocados 3 posi...
from datetime import datetime, time class Bank: name= "Bank of Africa" def __init__(self,id,accountNumber,accountType,branch): self.id= id self.accountNumber= accountNumber self.accountType= accountType self.branch= branch self.transaction= []; def withdraw(self): ...
import matplotlib.pyplot as plt class Perceptron(): def __init__(self, num_features): self.num_features = num_features self.weights = [] for i in range(num_features): self.weights.append([0.]) self.bias = [0.] def forward(self, x): linear = [] dot_pr...
#!/usr/bin/env python # coding: utf-8 # ## Naive Bayes Classifier # In[1]: import numpy as np import pandas as pd # In[2]: df = pd.read_csv("car_data.csv") # In[3]: df.shape # In[4]: df.head() # ### Converting Datavalues in Labels # In[5]: from sklearn.preprocessing import LabelEncoder le = LabelEn...
print('-*-'*20) print('Analisador de triângulos ') print('-*-'*20) r1=float(input('Primeiro segmento:')) r2=float(input('Segundo segmento:')) r3=float(input('Terceiro segmento:')) if r1<r2+r3 and r2<r1+r3 and r3<r1+r2: print('Os segmentos acima podem formar um triangulo') else: print('Os segmentos acima não pod...
import random print('-*-'*20) print('PEDRA PAPEL TESOURA') print('-*-'*20) jogador=int(input('PEDRA:1\nTESOURA:2\nPAPEL:3\nEscolha PEDRA PAPEL ou TESOURA:')) p=4 pa=6 t=5 lista=[p,pa,t] computador=random.choices(lista) print('A escolha do computador foi {}!'.format(computador)) if jogador==1 and computador==5: pr...
import math co=float(input('Qual o comprimento do cateto oposto?')) ca=float(input('Qual o comprimento do cateto adjacente?')) h=math.hypot(ca, co) print('O valor da hipotenusa é {:.2f}!'.format(h))
print('TABUADA') n=int(input('Digite o número que quer saber a tabuada:')) t1=1*n t2=2*n t3=3*n t4=4*n t5=5*n t6=6*n t7=7*n t8=8*n t9=9*n t10=10*n print('\nRESULTADO:') print('\n{}x1={}\n{}x2={}\n{}x3={}\n{}x4={}\n{}x5={}\n{}x6={}\n{}x7={}\n{}x8={}\n{}x9={}\n{}x10={}'.format(n, t1, n, t2, n, t3, n, t4, n, t5, n, t6, n...
s=int(input('Qual seu salario?')) if s>1250: p=s*0.1 ns=s+p print('Você recebeu um aumento de {:.2f} e seu novo salaraio é {:.2f}.'.format(p, ns)) else: p2=s*0.15 ns2=s+p2 print('Você recebeu um aumento de {:.2f} e seu novo salario é {:.2f}.'.format(p2, ns2))
n=str(input('Digite o nome da sua cidade:')).strip() d=(n.lower()).split() pn=d[0] print('O nome da sua cidade começa com santo?') print('santo' in pn)
c=0 s=0 n=int(input('Digite um numero:')) while n!=999: if n!=999: n = int(input('Digite um numero:')) c=c+1 s=s+n print('Você digitou {} numeros antes de encerrar o programa e a soma destes numeros foi {}.'.format(c,s))
soma=0 cont=0 for c in range(1,501,2): if c%3==0: cont=cont + 1 soma=soma + c print('A soma de todos os {} valores solicitados é {}.'.format(cont,soma))
class Node: def __init__(self,data): self.data=data self.next=None self.prev=None class Linklist: def __init__(self): self.head=None self.tail=None def add(self,data): node=Node(data) if self.head==None: self.head=node ...
class Tree: def __init__(self,data): self.data=data self.left=None self.right=None class bst: def addit(self,root,v): if root is None: root=v else: if root.data>=v.data: if root.left is None: root.left=v ...
import itertools def combination(input_list, k): for print_combinations in itertools.combinations(input_list,k): print(print_combinations) input_str = input("Insert list (each numbers are separated by space) :") input_list = input_str.split(' ') k_str = input("How many do you want to choose?(only integer) ") ...
import turtle from turtle import Turtle from turtle import Screen from random import * scrn = Screen() scrn.title("Pong game 🎉 🏓") scrn.setup(width=1000, height=600) scrn.colormode(255) scrn.bgcolor(51, 0, 25) # changing variables speed= 0 # Left paddle left_pad = turtle.Turtle() left_pad.speed(0) left_pa...
#! /usr/bin/env python # -*- coding: utf-8 -*- ''' Author: Xihao Liang Created: 2016.02.09 Description: functions for cutting sentences into unigrams or tokens, specifically for chinese based text ''' import sys reload(sys) sys.setdefaultencoding('utf8') import re import jieba from jieba import posseg jieba.initiali...
info=["priti",21,'mca'] print(info) cap = ['MCA','MCA2'] print(cap) print(cap[0]) cap.append('MSC') print(cap) empty=[] empty.append(1) print(empty) nos=[2,1,5,3] print(nos) print(nos[-2]) #x=[letters,numbers] x=[['a','b','c'],[1,2,3]] print(x) letters=['a','b','c','d'] print(letters) letters[2:5] = ['C', 'D'] p...
####### Return multiple values ############# def raise_to_power(value1, value2): """Raise value1 to the power of value2.""" new_value = value1 ** value2 new_value1 = value1 + value2 return new_value,new_value1 result = raise_to_power(2, 3) print(result) '''def raise_both(value1, value2): """R...
# Chris Burkhart: Create function that returns average of numbers input by user # import statstics module import statistics # create averageInput function def averageInput(): # define values variable as list values = [] # define n variable as user input integer with prompt n = int(input("Enter n...
# Chris Burkhart: Create a function that finds and prints the length of a line segment between two coordinates. # Import Math module import math # Define function to calculate distance to coordinate sets def lenLineSeg(x1, y1, x2, y2): # x = [10, 12] # y = [15, 20] # Define my length variable as pyth...
#Programa de controle de estoque ESTOQUE = "estoque_produtos.txt" def le_arquivo(): try: arq = open(ESTOQUE, "r+") print('\n' + arq.read()) arq.close() except IOError: print("Desculpe arquivo não encontrado") def escrevendo_no_arquivo(texto): try: arq...
# def repeatedString(s, n): # full_string = "" # while len(full_string) <= n: # full_string += s # concat_string = full_string[:n] # return concat_string.count('a') def repeatedString(s, n): one_pass = s.count('a') # find the number of full passes full_passes = n // len(s) rem_l...
#! /usr/bin/env python3 #Amanda Sill #Group 6 print('Content-type: text/html\n') import cgitb cgitb.enable() import cgi form = cgi.FieldStorage() html=""" <!doctype html> <html> <head><meta charset="utf-8"> <title>Robot Delivery System Confirmation</title></head> <body> <h1>Robot Delivery System Confirmatio...
from bs4 import BeautifulSoup as soup # HTML data structure from urllib.request import urlopen as uReq # Web client import re # Given the Menu Dict and Key Value, returns the total cost for every item in Menu_Items[KeyVal] def Find_Total(Menu_Items, item): total_cost = 0 for container in Menu_Items[...
# Project Description: # For fun I decided to try to port a general equation parser from Ruby to Python to learn the theory behind it # I had never looked at or used Ruby before so that was a learning experience in itself. # This was also my first dive into unit tests # Project time: ~8 hours over two days (1/30/15) # ...
print("Oyuncu kaydetme programı") ad= input("oyuncunun adı:") soyad= input("oyuncunun soyadı:") takim= input("oyuncunun takımı:") bilgiler = [ad,soyad,takim] print("ad: ",ad," soyad: ",soyad," takim: ", takim) print("bilgiler kaydedildi")
import controller # function to display the main menu def print_menu(): print('\n----------- MAIN MENU -----------\n') print('Select a menu option:') print('[A]: Show all products.') print('[B]: Create a new product.') print('[C]: Search product by ID.') print('[D]: Update product by ID.') ...
# 1 引入opencv 2 API 3 stop # 1 文件的读取 2 封装格式解析 3 数据解码 4 数据加载 import cv2 img = cv2.imread('image/1.png', 1) # 0 gray 1 color # cv2.imwrite('image/2.png', img) # 写图片 # 设置图片的质量 # JPG 压缩比范围0 - 100 ,有损压缩 cv2.imwrite('image/2.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 50]) # PNG 压缩比范围0-9 1 无损 2 透明度属性 cv2.imwrite('image/3.png', ...
x1,x2,y1,y2,z1,z2=eval(input('Enter three points for a triangle:')) s1=((y2-x2)**2+(y1-x1)**2)**0.5 s2=((y2-z2)**2+(y1-z1)**2)**0.5 s3=((x2-z2)**2+(x1-z1)**2)**0.5 s=(s1+s2+s3)/2 a=(s*(s-s1)*(s-s2)*(s-s3))**0.5 print('Area',int(a*100)/100)
x1,y1 = eval (input ('Enter co-ordinates of Point 1:')) x2,y2 = eval (input ('Enter co-ordinates of Point 2:')) import turtle turtle.penup() turtle.goto(x1,y1) turtle.pendown() turtle.dot(5,'black') turtle.write('p1 (' +str(x1) +',' +str(y1)+')',font = ('Times New Roman',15,'bold')) turtle.goto(x2,y2) turtle.dot(5,'bla...
def isSort(lst): for i in range(len(lst)-1): if lst[i]>lst[i+1]: return False return True def main(): s = input('Enter list:').split() n = [eval(x) for x in s] if isSort(n): print('The list is already sorted') else: print('The list is not sorted') ...
import random a= random.randint(100,999) a=str(a) d=eval(input('Enter three digit no:')) d=str(d) print('The lottery number is',a) if (a == d): print('Exact order ,User Wins $10000') elif (a[0]==d[1] and a[1]==d[2] and a[2]==d[0]) or \ (a[0]==d[2] and a[1]==d[0] and a[2]==d[1]) or \ (a[0]==d[0] and a[1]==...
class LinearEquation: def __init__(self,a,b,c,d,e,f): self.__a = a self.__b = b self.__c = c self.__d = d self.__e = e self.__f = f def geta(self): return float(self.__a) def getb(self): return float(self.__b) ...
def countLetters(s): count=0 for ch in s: if(ch.isalpha()): count=count+1 return(count) def main(): string = input('Enter String:') c = countLetters(string) print('No of letters in string are:',c) main()
import os.path import sys def main(): vow = {'a','e','i','o','u'} cons = {'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'} fln = input('Enter file path:').strip() if not os.path.isfile(fln): print('File does not exist') sys.exit() infile ...
#Q.No17 Rock,paper and scissor game import random a=random.randint(0,2) b=eval(input('scissor(0), rock(1), paper(2) :')) c='scissor','rock','paper' if(a==b): print('The computer is',c[a],'.','You are',c[b],'too.It is a draw.' ) elif(b==0 and a==2) or (b==1 and a==0) or (b==2 and a==1): print('The computer is',c...
#!/usr/bin/env python # -*- coding:utf-8 -*- #作者:ChrisChan #用途: from tkinter import * ''' 1、这个程序实现文本框输入。 2、使用grid方法按照Excel表格方式对组件位置进行安排 3、通过Button提交按钮实现获取用户的输入信息。 ''' root = Tk() Label1 = Label(root, text='会员名称:').grid(row=0, column=0) Label2 = Label(root, text='会员代号:').grid(row=1, column=0) v1 = StringVar() p1 = S...
class Device(object): def __init__(self, name, is_broken, repair_price): self.__name = name self.__is_broken = is_broken self.__repair_price = repair_price def get_name(self): return self.__name def get_broken_status(self): return self.__is_broken def get_repair_p...
import random dict_rps={ 0:"ROCK", 1:"PAPER", 2:"SISSIORS" } list_win=[[0,2],[2,1],[1,0]] list_compare=[] count_user=0 count_computer=0 while True: user_input= int(input("\n\nENTER 0 FOR ROCK, 1 for PAPER, 2 for SISSIORS: ")) com_input = random.randint(0, 2) if(user_input>3): print("E...
for count in range(11): if count != 0 and count % 2 == 0: print(count) print("Goodbye!")
class Node: def __init__(self,val=None): self.val=val self.left=None self.right=None class BST: def __init__(self): self.root=None def insert(self,val): if self.root==None: self.root=Node(val) else: self._insert(val,self.root) def _insert(self,val,cur_node)...
#Import the necessary modules import turtle import time #Setup the background screen and its properties wn = turtle.Screen() wn.bgcolor("black") wn.title("Analog clock by Neeraj") wn.setup(height = wn.window_height(), width = wn.window_width()) wn.tracer(0) #Make a turtle object named pen. Set its width an...
from random import randint attempt=0 no_of_tries= 5 check= False actual_no = randint(0,100) print(actual_no) while ( _try <= no_of_tries): attempt+=1 guess_no = int(raw_input('Guess the number ;)\n')) if guess_no == actual_no: print('Damn, you are phenomenal at this game!\n') check= True break ...
import csv # Функции для консоли # def CallHistory(b): loop = True count = 0 while loop == True: print("Enter the target phone number: ") mun = str(input()) for phone in b: if phone['recipent'] == mun or phone['sender'] == mun: loop = Fals...
''' 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. ''' t = input('Введите время в секундах: ') h = int(t) // 3600 s = int(t) % 3600 m = s // 60 sec = s % 60 print(f'{h:02}:{m:02}:{sec:02}')
""" Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]. ...
""" Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». В рамках класса реализовать два метода. Первый, с декоратором @classmethod, должен извлекать число, месяц, год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, должен...
""" Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод __init__()), который должен принимать данные (список списков) для формирования матрицы. Подсказка: матрица — система некоторых математических величин, расположенных в виде прямоугольной схемы. Примеры матриц: 3 на 2, 3 на 3, 2 ...
import re def tokenize(string): # Replace n't with not. string = string.lower().replace('n\'t', ' not') # Split words on non-alphanumerical characters. words = re.split("[^a-z0-9]", string) # Remove words that are not alphanumerical. words = [word for word in words if word.isalnum()] #...
repeat = input("Dime números separados por comas") numbers = repeat.split(",") print(numbers) numbers = [int(numero) for numero in numbers] print(numbers)
n = int(input('enter height')) i = 0 while i < n: j = n k = 0 x = '' while j > i + 1: x += ' ' j = j - 1 while k <= i: x += '#' k = k + 1 print(x) i = i + 1
# SSW 540 - Assignment 07 - P7: Finding unique strings # Akshay Sunderwani import re def parsefileforpath(filepath): try: # opening the file with open ( filepath ) as filetoread: senderlist = [ ] for lines in filetoread: linelist = lines.split ( ) ...
class BSTreeNode: def __init__(self, node_value): self.value = node_value self.left = self.right = None def _insert_node_into_binarysearchtree(node, data): if node == None: node = BSTreeNode(data) else: if (data <= node.value): node.left = _insert_node_into_binar...
def maxofthree(value1, value2, value3): if value1 > value2 and value1 > value3: return value1 elif value2 > value1 and value2 > value3: return value2 else: return value3 def wanttocontinue(): yesorno = input("Do you want to continue? Yes or No: ") if yesorno == "Yes" or yes...
# -*- coding:utf-8 -*- nota_1 = float(input('Digite a nota 1: ')) nota_2 = float(input('Digite a nota 2: ')) nota_3 = float(input('Digite a nota 3: ')) nota_4 = float(input('Digite a nota 4: ')) media = (nota_1*2 + nota_2*3 + nota_3*4 + nota_4*1) / float(2+3+4+1) print '\nMédia %.1f' % media if media >= ...
# -*- coding: utf-8 -*- # Imprimir o quadrado dos números de 1 a 20. for i in range(1,21): print(i**2)
# -*- coding : utf-8 -*- def to_unidade_dezena_centena(valor): centena = valor // 100 dezena = ( valor - centena * 100) // 10 unidade = valor - (centena * 100 + dezena * 10) resultado = str(unidade)+str(dezena)+str(centena) return resultado print(to_unidade_dezena_centena(435))
# -*- coding : utf-8 -*- salario = 1200 c1 = 200 c2 = 120 dois_por_cento = lambda valor : valor * 0.02 acrescimo = c1 + dois_por_cento(c1) + c2 + dois_por_cento(c2) restante = salario - acrescimo print("Terá de pagar : R$ {:.2f}".format(acrescimo)) print("E restará R$ {:.2f}".format(restante))
# -*- coding : utf-8 -*- # Retornar verdadeiro se foi digitado uma vogal def isVogal(letra): if letra == 'a' or \ letra == 'e' or \ letra == 'i' or \ letra == 'o' or \ letra == 'u': return True return False assert isVogal('a') == True assert isVogal('b') == False assert isVogal('...
# -*- coding : utf-8 -*- def change_valores(valor_a,valor_b): intermediario = valor_a valor_a = valor_b valor_b = intermediario return {"a":valor_a,"b":valor_b} a = 12 b = 25 print("Valor de a : {}".format(a)) print("Valor de b : {}".format(b)) resultado = change_valores(a,b) print("Valores trocados") print("...
valorA , valorB , valorC = [float(i) for i in raw_input().split()] pi = 3.14159 triangulo_retangulo = ( valorA * valorC ) / 2 circulo = pi * valorC**2 trapezio = ( ( valorA + valorB ) * valorC ) / 2 quadrado = valorB**2 retangulo = valorA * valorB print 'TRIANGULO: %.3f' %triangulo_retangulo prin...
# -*- coding:utf8 -*- def maior(a,b): return (a + b + abs(a - b)) / 2 num1,num2,num3 = [int(i) for i in raw_input().split()] #pega o maior entre os dois primeiros num_maior = maior(num1,num2) #mostra direto comparando com o terceiro número print '{} eh o maior'.format(maior(num_maior,num3))
# -*- coding:utf8 -*- def conta_letra(palavra,letra): #Manualmente cont = 0 for i in palavra: if i == letra: cont += 1 # return cont #Compreensão de Listas cont = len([i for i in palavra if i == letra]) return cont #Pythônica #return palavra.count(letra) # return cont print co...
from math import sqrt def distancia(x1,x2,y1,y2): distancia = sqrt( pow(( float(x2)-float(x1) ),2) + pow( ( float(y2)-float(y1) ),2) ) return distancia x1,y1 = raw_input('Dois valores do ponto 1: ').split() x2,y2 = raw_input('Dois valores do ponto 2: ').split() distancia = distancia(x1,x2,y1,y2) pri...
num_funcionario = int(input('Numero do funcionario: ')) horas_trab = int(input('Horas trabalhadas: ')) valor_horas = float(input('Valor da hora: ')) salario = horas_trab * valor_horas print 'NUMBER =',num_funcionario print 'SALARY = U$ %.2f' % salario
#config=utf-8 print('Welcome!') g=input('Input means Get input vlaue from User: ') guess=int(g) if guess==5: print('You Win!') else: print('You Lose!') print('----------------') # 분기를 위해서는 들여쓰기 print('Welcome!') g=input('Input input vlaue second chance: ') guess=int(g) if guess==5: print('You Win!') else:...
# 리스트 자료형이란 집합이다 list = [1,2,3,4,'a','b','c'] list2 = [1,2,[3,4,5],'a','b'] # 집합 안에 또 집합 # 인덱싱 - 순서 알아내기 i = list[0] + list2[0] print(i) # 2 # [-1]은 리스트의 마지막 요소 print(list[-1]) # c print(list2[-1]) # b 만약 부분집합에서 하나를 꺼내려면 순서대로 [][] (콤마 없음) print(list2[-3][-1]) # 5, 부분 집합이 몇개라도 상관 없이 [][] print('') # 슬라이싱 : 슬라이싱이란 ~부터...
# coding=utf-8 # 상속 - 위로부터 물려 받는 것. class parent(): def lastname(self): print("King") class child(parent): def firstname(self): print("James") james=child() james.firstname() james.lastname() print('-----------------'+"\n") # multi inheritance class parent(): def lastname(self): ...
''' OpenCV Script - We will detect a face in this script using Haarcascade algorithm Process :- 1. Creating a cascade classifier. It will contain the face features. 2. Search for the row and column values of the face in the numpy array (The face rectangle coordinates). 3. Display the image with rectangle ...
# -*- coding: utf-8 -*- ''' a = input("Lietotāj, lūdzu, ievadi skaitli: ") if a > 0: print "Tu esi ievadījis pozitīvu skaitli" elif a == 0: print "Tu esi ievadījis NULLI" else: print "Tu esi ievadījis negatīvu skaitli" print "Bet šo tekstu Tu redzēsi katru reizi!!!" ''' ''' if a > 0: print "Tu esi iev...
hrs = raw_input("Enter Hours:") rate = raw_input("Enter Rate:") h = float(hrs) if h > 40: h = (h - 40) * 1.5 + 40 r = float(rate) print h * r
import re def abbreviate(s): words = [w for w in re.split('[^a-zA-Z]', s) if w != ''] replaced = {w:w[0] + str(len(w[1:-1])) + w[-1] if len(w) > 3 else w for w in words} res = s for k, v in replaced.items(): res = res.replace(k, v) return res
def what_is_the_time(time_in_mirror): [h, m] = [int(s) for s in time_in_mirror.split(':')] mh = 12 if (h == 12 and m == 0) or (h == 11 and m != 0) else 11 if h == 12 else 12 - h if m == 0 else 11 - h mm = 0 if m == 0 else 60 - m return '{:02}:{:02}'.format(mh, mm)