text
stringlengths
37
1.41M
import sys class Hero(object): def __init__(self,usr,pwd): self.name = usr self.pwd = pwd self.hp = 100 def change_Pwd(self): while True: old_Pwd = input('please input old password:') if old_Pwd != self.pwd: print('Your password is wrong ...
import math class Point: def __init__(self, x=0.0, y=0.0): self.__x = x self.__y = y def getx(self): return self.__x def gety(self): return self.__y class Triangle: def __init__(self, vertice1, vertice2, vertice3): self.one = vertice1 ...
str1 = input("enter a word: ") str2 = input("enter another word: ") lst1 = sorted(list(str1.upper())) lst2 = sorted(list(str2.upper())) ana = True if(len(lst1)!=len(lst2)): ana = False print("different length words can't be anagrams") if(len(lst1)==0): ana = False print("empty strings can't be anag...
class Timer: def __init__(self, hour, min, sec): self.hour = hour self.min = min self.sec = sec def __str__(self): fH = format(self.hour, '02') fM = format(self.min, '02') fS = format(self.sec, '02') time = fH + ':' + fM + ":" + fS ...
list_1 = [] for ex in range(6): list_1.append(10 ** ex) list_2 = [10 ** ex for ex in range(6)] print(list_1) print(list_2)
#main progam file #run from AziziFunctions import* ''' turtle.bgcolor("sienna") ''' bob.speed(0) jump(0,365) #text of "Louis Vuitton" bob.color("darkgoldenrod") bob.write("Louis Vuitton", align="center", font=(None, 30, "bold")) #outline for the "LV #for reference jump (150,150) for ti...
dict01 = {"a":1,"b":2,"c":3,"d":4,"e":5} # 1,获取迭代器 iterator = dict01.__iter__() # 2,循环获取下一个元素 while True: try: key = iterator.__next__() print(key,dict01[key]) # 3,遇到异常停止迭代 except StopIteration: break
""" 生成器: 定义:能够动态(循环一次,计算一次,返回一次)提供数据的可迭代对象. 作用:在循环过程中,按照某种算法推算数据,不必创建容器存储完整的结果, 从而节省内存空间.数据量越大,优势越明显. 以上作用也称之为延迟操作或惰性操作, 通俗地讲就是在需要的时候才计算结果, 而不是一次构建出所有结果. 生成器函数: 定义:含有yield语句的函数,返回值为生成器对象. 语法: 创建: def 函数名(...
""" UDP套接字服务端流程(重点代码) """ from socket import * # 1,创建数据报套接字(socket) sockfd = socket(AF_INET,SOCK_DGRAM) # 2,绑定本机网络地址(bind) sockfd.bind(("127.0.0.1",8888)) # sockfd.bind(("0.0.0.0",8888)) while True: # 3,收发消息(recvfrom/sendto) data,addr = sockfd.recvfrom(1024) print("服务端接收数据:", data.decode()) print("服务...
class Bank: def __init__(self,money = 0): self.__money = money def save(self,x): self.__money += x print("账户有",self.__money,"元") def withdraw(self,x): if x > self.__money: print("余额不足") else: self.__money -= x print("账户剩余",self.__mo...
""" 基于thread的多线程网络并发模型(重点代码) 主线程负责循环连接 accept 分支线程负责循环收发 recv """ from socket import * from threading import Thread import sys # 全局变量 HOST = "0.0.0.0" PORT = 8888 ADDR = (HOST,PORT) # 不能不传参,进程可以,线程不能 def handle(c): """ 循环处理客户端的收发请求(分支线程有分支线程的循环) :param c: 客户端连接套接字 """ # s.close() # 分支线程不能关闭流式套接字...
""" ftp 文件服务器(第二种方法:类封装) 功能: 1. 查看 2. 下载 3. 上传 协议: LIST 查看文件 DOWNLOAD 下载文件 UPLOAD 上传文件 QUIT 退出 模仿三次握手 客户端单线程 """ from socket import * import sys import time # 区别于第一版 from threading import Thread # 服务器地址 HOST = "127.0.0.1" PORT = 8888 ADDR = (HOST,PORT) # 区别于第一版 # 线程信号量 # 同时下载数量限制 number_limit = 0 # “非...
""" 两个线程 一个打印 1-52 另一个打印 A-Z 要求打印顺序是 12A34B...5152Z """ from threading import Thread,Lock lock_1 = Lock() lock_2 = Lock() # 打印数字 def print_num(): for i in range(1,52,2): lock_1.acquire() print(i) print(i+1) lock_2.release() # 打印字母 def print_chr(): for i in range(65,91): ...
# 复制文件 filename = input("Please enter filename:") try: fr = open(filename, "rb") except FileExistsError as e: print(e) else: fw = open("picture_new.jpg", "wb") # +++++++++++++++++++++++++++++++++++++++++++++ # 老师的方法: # while True: # data = fr.read(1024) # 1024用来防止文件过大 # if not da...
""" 单链表(重点代码) """ class Node: """ 抽象的 Node 类 具体的 Person 类 """ def __init__(self,value,next = None): self.value = value self.next = next class LinkList: def __init__(self): """ 头节点: value 永远为 None next 永远指向第一个有效节点 """ self....
list01 = [0,1,4,9,16,25,36,49,64,81] for item in enumerate(list01): print(item) for index,element in enumerate(list01): print(index,element) print(enumerate(list01)) print(list(enumerate(list01))) print(list(enumerate(list01,start = 1))) print("##########################################") def my_enumerate(...
""" pymysql读流程: 1. 创建连接 db = pymysql.connect(...) 2. 创建游标 cur = db.cursor() 3. 执行语句 cur.execute("select ...") 4. 获取数据 cur.fetchone()/cur.fetchmany(n)/cur.fetchall() 5. 关闭游标 cur.close() 6. 关闭连接 db.close() pymysql写流程: 1. 创建连接 db = pymysql.connect(...) 2. 创建游标 cur = db.cursor() 3. 执行语句 cur.execute("insert/delete/update ....
""" 只能在终端运行 不能在PyCharm运行 一级界面 --> 注册 登录 退出 二级界面 --> 查询单词 历史记录 注销 """ from socket import * import sys from getpass import getpass # 只能在终端运行,不能在PyCharm运行 # 全局变量 ADDR = ("127.0.0.1",8000) s = socket() s.connect(ADDR) # 查询单词 def handle_query(name): while True: word = input("单词:") if word == "##": # 结...
# class NumberIterator: # def __init__(self,stop): # self.__stop = stop # self.__index = 0 # # def __next__(self): # if self.__index == self.__stop: # raise StopIteration("索引越界") # self.__index += 1 # return self.__index - 1 class MyRange: def __init__(s...
class Enemy: def __init__(self, name, base_damage, blood, *equipment): self.name = name self.base_damage = base_damage self.blood = blood self.equipment = equipment @property def name(self): return self.__name @name.setter def name(self,name): self.__...
""" 只能在终端运行 不能在PyCharm运行 """ import getpass print("==========getpass==========") for item in dir(getpass): print(item) # 输入隐藏 # password = getpass.getpass() password = getpass.getpass("password:") print(password)
list01 = [100,1.41,"hello",3.14,"world",2.72,200] # 获取列表中所有的字符串 # 1,生成器函数 def get_str(list_target): for item in list_target: if type(item) == str: yield item # re = get_str(list01) for item in get_str(list01): print(item) # 2,生成器表达式 # re = (item for item in list01 if type(item) == str) for i...
#Desafio 36, programa para aprovar um empréstimo bancario para a compra de uma casa. #o programa vai perguntar o valor da casa, o salario do comprador e em quantos anos ela #vai pagar. #Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou #então o emprestimo sera negado. cas...
""" Solution to an exercise from Think Python: An Introduction to Software Design Allen B. Downey This program requires Gui.py, which is part of Swampy; you can download it from thinkpython.com/swampy. This program started with a recipe by Noah Spurrier at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/5219...
import math class Point(object): """Represents a point in 2D space.""" def print_point(p): print '(%g, %g)' % (p.x, p.y) # Exercise 1 solution def distance_between_points(p1, p2): """Computes the Euclidean distance between two Point objects.""" dist = math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y...
def main(): print('A program to check is it a leap year or not.') year = eval(input('Please enter any year: ')) if year%400==0: print('It is a leap year.') elif year%100==0: print('It is a not leap year.') ...
def gui(): samples=3#number of sample texts to be used language=['French','French','French','French','French']#contains list of languages that will be compared selected by user return samples, language def translate(language,baselang): for z in baselang: #z will be the text to be trans...
import string import secrets print("Recomendamos o uso de uma senha com mais de 8 caracteres.") n = input("Digite o tamanho da senha (Recomendado = 16): ") or 16 n = int(n) special_chars = "!@#$%^&*()" def isspecial(char): if char in special_chars: return True return False def password_generator(n)...
import itertools original_list = [[2, 4, 3], [1, 5, 6], [9], [7, 9, 0]] def solution(list_of_list): l = [] for x in list_of_list: for y in x: l.append(y) return l solution(original_list)
#def FindPrePostFix(String) #Short: Takes String and returns the ending index of the longest Prefix with a matching PostFix #Long: This is used by KMP_SubStringSearch to provide repeating PrePostFix Strings inorder to shorten the Substring search, by removing repeated strings. #Big O(N) #Example: FindPrePostFix("6969...
import random import math class Math(): def __init__(self, val1, val2): self.val1 = val1 self.val2 = val2 def GetVersion(self): return "v0.1" def GetNumSquared(self, num): return num ** 2 def GetAuthorName(self): return "Nfynt" def GetNumCubed(self, num):...
""" x=0 number=[1,2,3,4,5,6] for p in number: x = x + p print(x) """ n = list(input("Enter the list of numbers: ").split(",")) sum=0 for x in n: sum += int (x) print(sum)
import pandas dataframe= pandas.read_csv("sample.csv") print("Print all the data from file") print(dataframe) print("============") print("Print all the usernames data from file") print(dataframe["Usernames"]) print("============") print("Print all the data from the second row") print(dataframe["Userna...
from cs50 import get_int height = 0 while (height < 1 or height > 8): height = get_int("Height of pyramid") for i in range(height): print((height - 1 - i) * " ", end="") print((i + 1) * "#") for
''' Created on 12 Nov 2016 @author: Erick ''' def main(num): fibonaccis = [1, 2] while num > next = len(fibonaccis) fibonacci = fibonaccis[len(next-2)] + fibonaccis[len(next-1)] fibonaccis.append(fibonacci) if __name__ == '__main__': main(5)
from stack import Stack print("\nLet's play Towers of Hanoi!!") #Create the Stacks stacks = [] left_stack = Stack('Left') middle_stack = Stack('Middle') right_stack = Stack('Right') stacks.append(left_stack) stacks.append(middle_stack) stacks.append(right_stack) #Set up the Game num_disks = int(input("\nHow many dis...
from random import randint as ri a = (int(input("Введіть бажану довжину першого списку та натисніть Enter: "))) b = (int(input("Введіть бажане максимальне значення елементів першого списку та натисніть Enter: "))) c = (int(input("Введіть бажану довжину другого списку та натисніть Enter: "))) d = (int(input("Введіть ба...
test_cases = int(input()) for i in range(test_cases): green_balloon_cost,blue_balloon_cost = map(int,input().split()) participants = int(input()) total_cost = 0 for num in range(participants): ans1,ans2 = map(int,input().split()) if i%2 == 0: total_cost = tota...
""" Number spiral diagonals Problem 28 Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum ...
""" p 14 : The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing ...
"""Triangular, pentagonal, and hexagonal Problem 45 Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ... It can be verified that T285 = P165 = ...
""" Truncatable primes Problem 37 : The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven pri...
""" 03 : The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def largest_prime_factor(n): i = 2 while i * i <= n: if n % i: i += 1 else: n //= i return n def prime_factors(n): i = 2 factors = [] ...
""" Circular primes Problem 35 The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? """ from collec...
""" Programs may name their own exception by creating a new exception class. Exception should typically be derived from the Exception class. When creating a module that can raise several distinct exception a common practice is to create a base class for exception defined by that module and subclass that to create spec...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Tutorial on how to use the PyCascades Python framework for simulating tipping cascades on complex networks. The core of PyCascades consists of the basic classes for tipping elements, couplings between them and a tipping_network class that contains information about ...
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' Created on 2017年10月2日 @author: Administrator ''' import logging # ref: http://blog.csdn.net/dezhihuang/article/details/72122356 # define the log file, file mode and logging level logging.basicConfig(filename='example.log', filemode="w", level=logging.DEBUG) ...
#!/usr/bin/env python3 #coding: utf-8 import sys import SSH import common import config if __name__ == '__main__': common.print_info('''how to use function: run command in remote machine example: ./exec.py id cmd1 cmd2 cmd3 ... ''') if not common.check_argv(sys.argv, 3): common.print_err...
class Node: def __init__(self, data): self.key = data self.left = None self.right = None def secondLargestUtil(root, c): # Base cases, the second condition # is important to avoid unnecessary # recursive calls if root == None or c[0] >= 2: return # Follow reverse inorder traversal so that # the l...
from datatypes.Rec13 import Rec13 from datetime import datetime class Rec13Impl(Rec13): """Implementation of the application data type Rec13. Generated by: EASy-Producer.""" intField: int stringField: str def getIntField(self) -> int: """Returns the value of {@code intField}. ...
#If else statements #Inicio de ejemplos print 'Ejemplo 1' a=6 b=7 if a <b: print 'a es menor que b' print 'a es definitivamente menor que b' print 'No estoy seguro que a sea menor que b' #ejemplo 2 print 'Ejemplo 2' c=5 d=4 if c<d: print 'c es menor que d' else: print 'c NO es menor que d' print 'F...
#7ma entrega #Numpy #Ejemplo 1 print 'Ejemplo 1' import numpy as np a=np.zeros(4) #Se crea un array de tamano 4 print a b=type(a) #Arroja el tipo de variable de a print b c=type(a[0]) #Arroja el tipo de variable del primer valor del array print c d=a.shape #Arroja la forma del array print d #Ejemplo 2 e=...
#7ma entrega #Numpy #Ejemplo 1 print 'Ejemplo 1' import numpy as np a=np.zeros(4) #Se crea un array de tamano 4 print a b=type(a) #Arroja el tipo de variable de a print b c=type(a[0]) #Arroja el tipo de variable del primer valor del array print c d=a.shape #Arroja la forma del array print d #Ejemplo 2 e=...
import csv import sqlite3 import datetime import time import re #defining object to change date format in CSV: ie.19040605(yyyymmdd) to date object def parsedate(s): s_date = None try: s_date = datetime.datetime.strptime(s, '%Y%m%d').date() except: s_date = datetime.datetime.str...
# Module-10 Visual Graphs #Matplot lib line plot plt.plot(stock.reset_index().iloc[:,0],stock["Adj Close"]) plt.show() print("e") print("e") #Set x and y x=PlottingData["Adj Close"] y=PlottingData.reset_index()["Date"] #matplot bar plot fig = plt.figure() ax = fig.add_axes([0,0,1,1]) langs = y students = x ax.bar(la...
from Fecha1 import Fecha1 class Persona1(): def __init__(self,nombre,apellido,fdia,fmes,fanio): self.__nombre = nombre self.__apellido = apellido self.__fnacimiento = Fecha1(fdia,fmes,fanio) @property def nombre(self): return self.__nombre @nombre.setter def nombre(s...
Day31 = {1, 3, 5, 7, 8, 10, 12} Day30 = {4, 6, 9, 11} def days2(yearmon) : year = int(yearmon[0:4]) mon = int(yearmon[4:6]) if mon in Day31 : day = 31 elif mon in Day30 : day = 30 else : if (year % 4 == 0 and year % 100 != 0 or year % 400 == 0) : day = 29 ...
##################################### [ 도전문제 19 ] ################################### # # 3 # x 12 #------- # 36 # a = 3 b = 12 print("{:>8}".format(a)) print("x{:>6}".format(b)) print('--' * 4) print("{:>7}".format(a*b)) print('--' * 45) ##################################### [ 도전문제 20 ] #########...
############################ 리스트 할당과 복사 ################################ # # - 리스트의 할당은 두 리스트가 한 메모리 공간을 공유하는 형태이다. # - 한 리스트의 내용이 변경되면 같은 리스트가 할당된 다른 리스트에서도 변경된 내용에 # 접근할 수 있다. # a = [1, 2, 3, 4, 5] b = a print(id(a)) print(id(b)) print(a) print(b) b[3] = 400 print(a) # - 리스트 b의 값을 리스트를 공유하는 a도 내용이 변경되어있다...
"""This function returns a list of every third number between a number 'start' and 100 (inclusive). If start is greater than 100, the function returns an empty list. """ def every_three_nums(start): nums = [] if start <= 100: for n in range(start, 100 + 1, 3): nums.append(n) return nums print(every_t...
"""Create a function that returns a list where All elements in lst with an index between start and end (inclusive) have been removed. """ def remove_middle(lst, start, end): first_half = lst[:start] second_half = lst[end + 1:] return first_half + second_half print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
# selectivecopy.py - copies only selected type of files # input - root location, file types # output - all the files are copied and placed in selectivecopy folder under root location # import os import shutil def selectivecopy(folder, *types): folder = os.path.abspath(folder) # make sure folder is...
from __future__ import with_statement import os CWD = os.path.dirname(os.path.abspath(__file__)) WORDS_DIR = os.path.join(CWD, "words") class WordList(dict): ''' Useful for testing whether a word is in a wordlist file. A wordlist file is a plain text file containing either one word per line or one w...
import time class Counter(object): ''' Track iterations and items iterated over. ''' def __init__(self, desc=''): self.desc = desc self.starts, self.items = 0, 0 def __call__(self, seq): '''Yield items in sequence while counting.''' self.starts += 1 for i ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import random df = pd.read_csv("perceptron_data.csv") #The learning rate of the classifier learning_rate = 0.01 #The number of iterations of gradient descent. #TODO: Optimize number of rounds needed to train. N = 10000 #The initial range of rand...
#!/bin/env python3 # -*- encoding: utf-8 -*- """ Script to remember you to do your backups. This program use python-gtk to send notifications to the user's gnome shell. The only thing this script requiere is a text file containing the last backup date as the last line, located in /var/log and named las...
from copy import deepcopy class Solution(object): """ Combinatorics """ # 78 def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ return self.subsetsIterExpansion(nums) """ Iteratively build upon subsets of smaller size: ...
from math import sqrt def sum_squares( a, b ): return pow( a, 2 ) + pow( b, 2 ) def hypot(a,b): return sqrt(pow(a,2) + pow(b,2)) ELASTICITY = 0.9 DRAG = 0.95 def move(eye, aX, aY): (x, y) = eye.pupil_position # print("starting pupil_position: " + str(eye.pupil_position)) # print("starting ...
''' 2. Доработать алгоритм Дейкстры (рассматривался на уроке), чтобы он дополнительно возвращал список вершин, которые необходимо обойти. ''' from collections import deque from collections import namedtuple g=[ [0,0,1,1,9,0,0,0], [0,0,9,4,0,0,5,0], [0,9,0,0,3,0,6,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,...
arr=[1,2,3,4,5,6,7] #array which we are going to rotate using reversal algorithm d=2 #number of rotations or value upto which we have to rotate n=len(arr) #length of the array def reversal_algo(arr,start,end): #function for reversal algorithm while(start<end): temp=arr[start] #first value of the array is ...
class Node: def __init__(self, element=None, next_node=None): self.element = element self.next = next_node def __repr__(self): return str(self.element) class Queue: def __init__(self): self.head = Node() self.tail = self.head def is_empty(self): return...
''' Created on 24 Oca 2013 @author: tr1u4323 ''' def getNextTriangularNumber(number): return number * (number + 1) //2 def getNextPentagonalNumber(number): return number * (3 * number - 1) // 2 def getNextHexagonalNumber(number): return number * (2 * number - 1) if __name__ == '__main__': trian...
''' Created on 17 Oca 2013 @author: tr1u4323 ''' def getSmallestDivisibleNumber(upperLimit): number = 223092870 while True: hits = 0 for i in range(1, upperLimit + 1): if (number % i) != 0: break else: hits += 1 ...
from tkinter import * raiz = Tk() miFrame = Frame(raiz) miFrame.pack() operacion = "" # def var para operaciones aritmeticas resultado = 0 # def variable para resultados aritmeticos # --------------------------------------------------------------- numPantalla = StringVar() # recibe un valor "string" # pantalla ...
'''This file contains tests for the conservation of energy in an n-body simulation. ''' import numpy as np from Particle import Particle from Simulation import ( Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, ) """ Let's test if the kinetic energy of the Sol...
import numpy as np file = open("input.txt") # Open file content = file.read() # Read contents to string file.close() # Close file list = content.split("\n") # Split to list of strings list.remove("") # ...
""" Encendemos/apagamos el riego (bomba controlada por un relé) automáticamente según el valor de un sensor de humedad de suelo: * Por debajo de un valor de humedad se enciende el motor * Por encima se apaga * Se usa un sensor de lluvia para detectar si la planta ya está expulsando agua por abajo Controlamos el niv...
# ############################################################ # FILE : y_tree.py # WRITER : Assaf Mor , assafm04 , 036539096 # EXERCISE : intro2cs ex6 # DESCRIPTION: # this is a method which draws a "Y" tree using the turtle library. # the drawing is done recursively. # ################################################...
############################################################################### #FILE: decimalToBinary.py #WRITER: Assaf_Mor + assafm04 + 036539096 #EXCERSICE: intro2cs ex3 2014-2015 #DESCRIPTION: #a program which converts a decimal number to its binary number representation ############################################...
############################################################################### #FILE: totalWeight.py #WRITER: Assaf_Mor + assafm04 + 036539096 #EXCERSICE: intro2cs ex3 2014-2015 #DESCRIPTION: #this program counts non-negative weights and adds them, up until the sum is #over 100 which then the program quits or up until...
WINNER_SUM = 29 def take_turn(turn_num, total_sum): game_won = False while not game_won: while 0 <= turn_num < 10: if turn_num + total_sum <= WINNER_SUM: print()
""" Simple language for defining predicates against a list or set of strings. Operator Precedence: - ``!`` high - opposite truth value of its predicate - ``/`` high - starts a regex that continues until whitespace unless quoted - ``&`` medium - "and" of two predicates - ``|`` low - "or" of two predicat...
from copy import deepcopy class GO: def __init__(self, n): self.size = n self.X_move = True self.died_pieces = [] self.n_move = 0 self.max_move = n * n - 1 self.komi = n/2 self.board = [[]] self.previous_board = [[]] def init_board(self, n): ...
x1= 0 v1 = 2 x2 = 5 v2 = 3 aux=0 while (x1 <10000) or (x2>x1) or (x2<10000): x1 = x1 + v1 x2 = x2 + v2 aux=0 if x1==x2: aux=1 break if aux==1: print("yes") else: print("no")
s = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] def find_short(s): s = s.split() # splits the string into a list of individual words l = min(s, key = len) # finds the shortest string in the list ...
def devuelve_ciudades(*ciudades): #el asteristico significa que recivira un numero indeterminado de elementos for elemento in ciudades: #for subelemento in elemento: yield from elemento ciudades_devueltas = devuelve_ciudades("Madrid","Barcelona","Bilbao","Valencia") print(next(ciudades_devueltas)...
class Vehiculos(): def __init__(self,marca,modelo): self.marca=marca self.modelo=modelo self.enmarcha=False self.acelera=False self.frena=False def arrancar(self): self.enmarcha=True def acelerar(self): self.acelera=True def frenar(self): ...
""" This module provides several validation functions used by the estimator. """ import numpy as np _NON_CATEGORICAL_ERROR = RuntimeError("L3 cannot handle numeric inputs. Use only 'object' or 'StringDtype'" + " if you are using pandas.") def check_column_names(X, column_nam...
# Pida un número que como máximo tenga tres cifras / # (por ejemplo serían válidos 1, 99 i 213 pero no 1001). / # Si el usuario introduce un número de más de tres cifras debe un informar/ # con un mensaje de error como este / # "ERROR: El número 1005 tiene más de tres cifras" print("Por favor introduce un n�mero de t...
# -*- coding: utf-8 -*- """ Created on Tue Feb 28 15:10:00 2017 @author: confocal generates a list of dates between two specified dates at a specified interval """ import datetime date1 = '2017/01/01' date2 = '2017/03/01' interval = 7 start = datetime.datetime.strptime(date1, '%Y/%m/%d') end = datetime.datetime.str...
#Se da numarul natural n. Sa se compare sumele S1 si S2, unde: #a)S1=1^3+2^3+...+n^3 si S2=(1+2+...+n)^2 #b)S1=3(1^2+2^2+...+n^2) si S2=n^3+n^2+(1+2+...+n) n=int(input("Dati valoarea lui n:")) s1a=0 ss=0 s2a=0 ss1=0 s1b=0 s2b=0 for i in range(1,n+1): s1a+=(i**3) ss+=i s2a=(ss**2) ss1+=(i**...
num = int(input('Digite um número inteiro: ')) print('Verificando os números primos..') numPrimo = 0 for c in range(1, num + 1): if num % c == 0: numPrimo += 1 if numPrimo == 2: print('{} é primo'.format(num)) else: print('{} não é primo!'.format(num)) print('FIM!')
from time import sleep valueHouse = float(input('Value of house: R$')) valuePayment = float(input('Value of your payment: R$')) yearsBuy = float(input('Years of payment: ')) valueMonth = valueHouse / (yearsBuy * 12) print('Processando as informações...') sleep(2) if valueMonth <= (valuePayment * 0.3): ...
sexo = input('Qual seu sexo? ').strip().upper()[0] while sexo not in 'MmFf': sexo = input('Valor incorreto! Digite seu sexo [F/M]: ').strip().upper()[0] if sexo == 'M': sexo = 'Masculino' else: sexo = 'Feminino!' print('Correto, você é do gênero {}'.format(sexo))
aula = {} print('-=' * 25) print(f'{"SITUAÇÃO FINAL":^50}') print('-=' * 25) print() aula['nome'] = str(input('Nome do aluno: ')) aula['media'] = float(input(f'Média de {aula["nome"]}: ')) print() if aula['media'] >= 7: aula['situação'] = 'APROVADO' print(f'Aluno(a) {aula["nome"]} teve média de {aula[...
payment = float(input('How much is your payment? ')) print('Your payment this month was R${:.2f}, but with increase of 15%, go to R${:.2f}.'.format(payment, payment + (payment*0.15)))
from vehicle import Vehicle class Car(Vehicle): def __init__(self, color, brand, tank, wheels=4): Vehicle.__init__(self, color, brand, tank, wheels) def to_fuel(self, quantity_liters): if self.tank + quantity_liters > 100: print(f'Number of liters greater than the tank.') ...
times = ('Cruzeiro', 'Náutico', 'Vitória', 'América Mineiro', 'Chapecoense', 'Avaí', 'Botafogo-SP', 'Brasil de Pelotas', 'Confiança', 'CRB', 'CSA', 'Cuiabá', 'Figueirense', 'Guarani', 'Juventude', 'Oeste', 'Operário-PR', 'Paraná', 'Ponte Preta', 'Sampaio Corrêa') print(f'Os 5 primeiros times da Série B 202...
produtos = ('Lápis', 2, 'Borracha', 0.50, 'Caderno', 15.90, 'Mochila', 125.90) print('-' * 40) print(f'{"Listagem de Preços":^40}') print('-' * 40) for pos in range(0, len(produtos)): if pos % 2 == 0: print(f'{produtos[pos]:.<30}', end='') else: print(f'R${produtos[pos]:>7.2f}') print('...
number = int(input('Type a integer number: ')) if number % 2 == 0: print('The number {} is pair!'.format(number)) else: print('The number {} is odd!'.format(number))