text
stringlengths
37
1.41M
def BinaryToDecimal(binary): return int(binary, base=2) test_str = """ Lately I'm feeling lonely, I am getting bored of torturing primates all of the time. At least I'm doing the world a favor my punishing them. Just remember we are good. Not Cruel """ res = ''.join('{0:08b}'.format(ord(i), 'b') for i in test_...
N = int(input()) if N == 3: print("* . .\n. . *\n. . .") exit() mat = [['.' for i in range(N)] for j in range(N)] for i in range(N // 2): mat[i][2 * i] = '*' for i in range(N // 2): if i + N // 2 == N - 1: break mat[1 + i + N // 2][1 + 2 * i] = '*' for row in mat: ...
import random count = 10**6; print(count) for i in range(count): print(random.randint(5 * 10**5, 10**6), end = ' ') print() for i in range(1, count): print(random.randint(1, i), end = ' ') print()
import calendar import datetime import time print(calendar.weekheader(3)) print() print(calendar.firstweekday()) print() print(calendar.month(2020, 3, 3)) print() print(calendar.monthcalendar(2020, 3)) print() print(calendar.calendar(2020)) day_of_the_week = calendar.weekday(2020, 9, 22) print(day_of_the_week) i...
# unittest skip # conditinal skipping import unittest def divide(la, lb): return la/lb class TestAdd(unittest.TestCase): data = 10 datb = 30 def test_add(self): self.assertRaises (ZeroDivisionError, divide, self.datb, self.data) "test fails if exception is not raised" "test passes if ZeroDivisionError is ra...
#!/usr/bin/env python # coding: utf-8 # In[1]: import time # In[2]: def funca(): i = 0 for i in range(-9, 1): print('A will take {} seconds more'.format(i)) time.sleep(1) def funcb(): i = 0 for i in range(-3, 1): print('B will take {} seconds more'.format(...
#!/usr/bin/env python """This script uses a trained convtransformer model to translate a sentence from the source to the target language. It expects two arguments: - The path to the trained model - The sentence to be translated The beam width used in the beam search can be specified by using the flag --beam-...
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 # without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def smallest_number(): i= 2520 primes = [2,3,5,7,11,13,17,19] max_num = 20 while Tr...
import numpy as np def choice(x): if(x > 0): return 1 else: return 0 # input and output dataset training_data = [ (np.array([0, 0, 1]), 0), (np.array([0, 1, 1]), 1), (np.array([1, 0, 1]), 1), (np.array([1, 1, 1]), 1), ] w = random.rand(3) a = [] mu = 0.001 n = 50 for i in xr...
# 문제2. 다음과 같은 텍스트에서 모든 태그를 제외한 텍스트만 출력하세요. import re def cleanhtml(raw_html): cleanr = re.compile('<.*?>') cleantext = re.sub(cleanr, '', raw_html) return cleantext s = """ <html> <body style='background-color:#ffff'> <h4>Click</h4> <a href='http://www.python.org'>Here</a> <p> ...
# Write a function named readable_timedelta. The function should take one argument, # an integer days, and return a string that says how many weeks and days that is. # For example, calling the function and printing the result like this: # print(readable_timedelta(10)) # should output the following: # 1 week(s) and ...
# Quiz: Assign and Modify Variables # Now it's your turn to work with variables. The comments in this quiz (the lines that begin with #) # have instructions for creating and modifying variables. After each comment write a line of code # that implements the instruction. # Note that this code uses scientific notation ...
#!/usr/bin/env python3 """ command-line utility to convert date to day of year """ from argparse import ArgumentParser from sciencedates import date2doy p = ArgumentParser(description="convert date to day of year") p.add_argument("date", help="yyyy-mm-dd") P = p.parse_args() doy, year = date2doy(P.date) print(doy.i...
def pairCorrelationFunction_2D(x, y, S, rMax, dr): """Compute the two-dimensional pair correlation function, also known as the radial distribution function, for a set of circular particles contained in a square region of a plane. This simple function finds reference particles such that a circle of radi...
print 'printing correct sequence' dipanjan=2 dipanjan=dipanjan-2 if dipanjan == 0: print ('dipanjan0') else: dipanjan=1 print (dipanjan) extra = [2,3,4] for x in extra: y=x+1; print (y)
import pandas as pd df = pd.read_csv('Tech.csv') print(df) print(df.columns) print(df.head()) for col in df.columns: if col[:2] == 'nu': df.rename(columns = { col: 'Employees'}, inplace = True) print(df.head())
# Databricks notebook source # MAGIC %md # MAGIC #Titanic Survivor Analysis # COMMAND ---------- # MAGIC %md # MAGIC Let's read our dataset from s3, and explore provided variables # COMMAND ---------- from pyspark.sql.functions import split, size td = spark.read.csv('/mnt/ts/titanic.csv', header=True) titanic_data ...
import math #solicitando os valores de A, B e C a = float(input("Informe o valor de A: ")) b = float(input("Informe o valor de B: ")) c = float(input("Informe o valor de C: ")) #cálculo do delta delta = (b * b) - 4 * a *c #verificação das condições com elif if delta > 0.0: #cálculo de 2 valores para x x1 = (-b...
import json #módulo python que gera dados em formato json #criando um dicionário contatos = { "Clark Kent": {"Celular":"123456", "Email":"super@krypton.com"}, "Bruce Wayne": {"Celular":"654321", "Email":"bat@caverna.com.br"} } #convertendo o dicionário para uma string o form...
#valores fora de ordem valores = [1, 7, 7, 19, 3, 2, 11, 15, 6, 1, 5] #exibição da lista print("A lista foi criada assim: {}".format(valores)) #contagem de elementos contagem = valores.count(7) print("Nessa lista o número 7 aparece {} vezes".format(contagem)) #invertendo a lista valores.reverse() print("A lista agor...
#usando a função open para criar um objeto do tipo arquivo arquivo = open("C:\\Users\\carol\\Documents\\Documentos\\tiworkspace\\python-fundamentos\\manipulaçao-arquivos\\arquivo_texto.txt") #verificando o tipo do objeto arquivo print(type(arquivo)) #lendo o conteúdo do objeto arquivo #print(arquivo) print(arquivo.re...
def make_division_by(n): """This closure returns a function that returns the division of an x number by n """ # You have to code here! pass def run(): division_by_3 = make_division_by(3) print(division_by_3(18)) # The expected output is 6 division_by_5 = make_division_by(5) p...
# Funktioner er noget vi kan bruge til at # give et navn til et lille stykke kode, # som vi så kan bruge igen. Hvis du nogensinde # har copy-pastet noget kode, skulle du nok # have brugt en funktion i stedet. # Opgave A - Kan du finde de steder der er # blevet copy-pastet? Skriv dem som en funktion # i stedet. # Hi...
"""Instances generation. An instance is a tuple of (pid, t_obs, t_end, t_evt, x), where * pid : str - a patient ID * t_obs : np.datetime64 - the datetime of the instance observation * t_end : np.datetime64 - the datetime of the final obs. in the patient record * t_evt : np.datetime64 or NaT - the date of the event...
""" From the code below create 3 students and add them to a list. sort the list based on the students age. Print out the Students names from the list (use a list comprehension for this) """ class Student: def __init__(self, name, age): self.name = name self.age = age
from collections import deque def search(name): search_queue=deque()#一个队列 search_queue+=graph[name] searched=[] while search_queue:#当队列不为空 person=search_queue.popleft()#同时将搜索过的人清除 if person not in searched: if person_is_seller(person): print(person+" is a man...
def quicksort(array): if len(array)<2: return array else: pivot=array[0] less=[i for i in array[1:] if i<=pivot] greater=[i for i in array[1:] if i>pivot] return quicksort(less)+[pivot]+quicksort(greater) def mergeSort(array): #归并排序 if len(array)<2: retur...
from assignment1 import assignment1 from assignment2 import assignment2 from assignment3 import assignment3 def main(): while True: print("""\n\nEnter the assignment number that you want to run:- 1) Assignment 1 2) Assignment 2 3) Assignment 3 4) Assignment ...
n = 20 for i in range(1, n): for j in range(1, n): if j % 2 == 0: print('/', i, '*', j, '=', i * j) else: print(i, '*', j, '=', i * j, end=' ') if j == 19: print()
import matplotlib.pyplot as plt import numpy as np # x(t)の関数 def func(x,t,a): return a * x[t] * (1 - x[t]) def set_a_range(): # a_range = np.arange(3,4,0.001) ← 誤差がでる。 a_range = np.arange(3000,4000,1) return np.array(list(map(lambda x: x/1000, a_range))) # a_range * a_range の二次配列 (1000 ...
import pygame import random import pygame_menu pygame.init() bg = pygame.image.load("snake.png") FRAME_COLOR = (0, 25, 51) APPLE_COLOR = (204, 0, 102) RECT_COLOR = (0, 51, 102) LIGHT_RECT_COLOR = (31, 63, 118) HEADER_COLOR = (0, 21, 44) SNAKE_COLOR = (0, 128, 255) COLS = 25 BLOCK_SIZE = 20 MARGIN = 1 SIDES_MARGIN = 20...
# Task 1 a: sort list by first element of sublists l = [[4, 3], [2, 7], [1, 8], [9, 1], [5, 6]] sorted_l = sorted(l) print(sorted_l)
# Task 1d: get counts statistics for the sequence dna_seq = "GATTACA" rna_seq = "GAUUACA" permitted_letters = "ATCGU" seq_list = [dna_seq, rna_seq] for seq in seq_list: print("Validating sequence:", seq) seq = seq.upper() for letter in seq: if not letter in permitted_letters: print("...
# Task 1b: create index file for specified dinucleotide # To get the data required for this script, download it from http://hgdownload.soe.ucsc.edu/goldenPath/hg19/chromosomes/chr21.fa.gz # Decompress the file (e.g. using 7-zip) and store it in the 'data' subdir of 'exercises_4'. # Step 1: Save the script parameter fo...
# Beginners MNIST / Tensorflow website import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Adapted from https://www.tensorflow.org/get_started/mnist/beginners # and https://www.tensorflow.org/get_started/mnist/pros def train(): # Download MNIST data using input_data.read_data_sets...
from math import * from random import randrange def bozo(arr, direction=True): narr = [] if isinstance(arr[0], list): for li in arr: narr.extend(li) else: narr = arr.copy() len_narr = len(narr) while not sort(narr, direction): first, second = randrange(len_narr)...
""" Author: Lucky Adogun (zen_coder) License: MIT Date: 26-10-2020 PROBLEM: Given an array of integers and a target integer, find the position of the integers that make up the target. Example: array = [1,2,3,4] target = 7 result = [2,3] """ def solution_one(nums, target): c...
class Game: def __init__(number_of_players): for n in range(number_of_players): self.players.append(Player(range(0, width), range(0, height))) def start(self): print("It's adventure time!") print("How many people are adventuring?") number_of_players = int(input()) game = G...
class Reading: """ A class to represent an atmospheric pressure reading from a smartphone """ def __init__(self, observation_unit, value, model, latitude, longitude, altitude): self.observation_unit = observation_unit self.value = value self.latitude = latitude # ... def to...
def is_palindrome(string): if len(string) <= 1: return 1 elif string[0] == string[-1]: return(is_palindrome(string[1:-1])) else: return 0 #print is_palindrome("kajak") #print is_palindrome("kajak")
#library classes to help import math import random import sys def nodeDistance(node1, node2): hDist = abs(node1.getX() - node2.getX()) vDist = abs(node1.getY() - node2.getY()) return math.sqrt(hDist**2 + vDist**2) def dnaDistance(DNAObj1, DNAObj2): dna1 = DNAObj1.getDNA() dna2 = DNAObj2.getDNA() if (len(dna1) !...
# -*- coding: utf-8 -*- """ Spyder Editor Create a Perceptron class with methods to train a Perceptron binary classifier. Test your classifer on test data. """ # in terminal, >> spyder3 class Perceptron: # class fields # weights = [] # constructor def __init__(self, dim): # initialize wei...
n1 = float(input('Qual a n1? ')) n2 = float(input('Qual a n2? ')) media = (n1+n2)/2 if media < 5: print('Reprovado') elif media >= 7: print('Aprovado') else: print('Recuperação né Filhao')
from random import randint computador = randint(1,10) print('Vamos começar o jogo da Advinhação.') contador = 0 while True: chute = 0 while chute < 1 or chute > 10: chute = int(input('Digite um valor:')) if chute < 1 or chute > 10: print('Digite novamente, valor inserido não...
saque = int(input('Qual o valor que você deseja sacar? ')) while True: if saque // 50 > 0: print('Foi sacado {} notas de 50'.format(saque//50)) saque = saque % 50 if saque // 20 > 0: print('Foi sacado {} notas de 20'.format(saque//20)) saque = saque % 20 if saque // 1...
import math ang = float(input("Digite o Angulo: ")) ang = (ang*math.pi)/180 senang = round(math.sin(ang),3) cosang = round(math.cos(ang),3) tanang = round(math.tan(ang),3) print("Os valores são: {} , {} , {}".format(senang,cosang,tanang))
from random import randint from time import sleep def sorteia(lista): for cont in range (0,5): n = randint(1,10) lista.append(n) def somapar(lista): s = 0 print('Os números sorteados são: ', end='') sleep(0.3) for valor in lista: print(valor, end=' ')...
def notas(*num): ''' Função notas utiliza de uma lista de notas para processamento de dados :param num: Lista de notas dos alunos de uma sala :return: Total, maior nota, menor nota, média geral da sala e situacao de aproveitamento ''' sala = dict() sala['total'] = len(num) sala['...
from random import randint opcao = ['Pedra','Papel','Tesoura'] computador = randint(0,2) print('=-='*10) print('''Escolha sua opção: [ 1 ] Pedra [ 2 ] Papel [ 3 ] Tesoura ''') jogador = int(input('Digite o número da sua opcao: '))-1 if computador == 0: #PC joga pedra if jogador == 0: print("EMPA...
num = int(input('Digite o número para verificaçao: ')) for i in range (2, 1000): if i == num: continue if num % i == 0: print ("O número não é primo", i) break if i == 999: print("O número é primo")
expressao = input('Digite a expressão: ').strip() validade = True tipo_error = '' quant_parenteses_abrir = expressao.count('(') quant_parenteses_fechar = expressao.count(')') parenteses_para_fechar = 0 if quant_parenteses_abrir == quant_parenteses_fechar: for v in expressao: if v == ')' and parentes...
import math catopo = int(input("Digite o Cateto Oposto: ")) catadj = int(input("Digite o Cateto Adjacente: ")) hipote = int(math.sqrt(pow(catopo,2)+pow(catadj,2))) print("A hipotenusa desse triangulo é: {}".format(hipote))
# -*- coding: utf-8 -*- """ Created on Sun Apr 11 21:11:28 2021 @author: Raza_Jutt """ def hexaToDec(hexval): length = len(hexval) base = 1 dec_val = 0 for i in range(length - 1, -1, -1): if hexval[i] >= '0' and hexval[i] <= '9': dec_val += (ord(hexval[i]) - 48) * base...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Mon Jan 21 13:28:28 2013 modified 4th Fib 2012 to help use Git and gitHub rock paper scissors @author: graham naylor; For use in linux console. Enter rock paper or scissors (or their initial!).. use: ./mit_rps.py """ import os # to allow to clear the consol...
from tkinter import * from tkinter import filedialog from PIL import Image, ImageTk class MainScreen: def __init__(self, master): self.pic = "" master.minsize(width=600, height=400) #master.configure(background="firebrick3") frame = Frame(master) self.directoryLabel = Lab...
#!/usr/bin/python #encoding:utf-8 #Filename:while.py number = 23 running = True while (running) : #不加encoding:utf-8连中文注释都会报错 #这里如果不加int()会一直走到guess>number里面不知道为什 guess = int(raw_input("Enter an integer :")) if guess == number : print "Congratulations, you guessed it " running = False elif guess...
#!/usr/bin/python #encoding:utf-8 #Filename:continue.py while True : s = raw_input("Enter something :") if s == 'quit' : break elif len(s) < 3 : print '<3' continue print "Input is of sufficient length" #Do other kinds of processing here
# # # # Python: 3.7.4 # # Author: Keith Korter # # # # Purpose: creates a database and adds new data into that database. # # # import os import sqlite3 conn = sqlite3.connect('data.db') with conn: cur = conn.cursor() cur....
import pandas import matplotlib.pyplot as plt def mean(L): return(sum(L) / float(len(L))) def calc_equity_premium(p, q, sigma, rho, theta, b): first = sigma*sigma * theta second= mean(map(lambda x: pow(1-x, -1*theta), b)) third = mean(map(lambda x: pow(1-x, 1-theta), b)) fourth = mean(b) return(first + p*(1-q)*...
from datetime import datetime from pytz import timezone class DateTimeManager: # current date+time captured upon class's creation def __init__(self): self.date_time_in_pt = self.standardize_to_pt_time(datetime.now()) self.day_of_the_week = self.shift_week_start_num(self.date_time_in_pt.isoweekd...
from creative_ai.utils.print_helpers import ppGramJson class TrigramModel(): def __init__(self): """ Requires: nothing Modifies: self (this instance of the NGramModel object) Effects: This is the NGramModel constructor. It sets up an empty dictionary as a member ...
#作业1. 实现一个文件复制器的函数,通过给函数传入一个路径,复制该路径下面所有的文件(目录不需要复制)到当前目录 import os def file_copy(file_path): #file_path ='/Users/zhangcaiyan/Desktop/Lemon_python/lemon_python_08' try: res = os.listdir(file_path) print(res) os.chdir(file_path) except Exception as e: print(e) else: ...
# game.py print("'Rock', 'Paper', 'Scissors,' 'Shoot!'") import random import os import dotenv dotenv.load_dotenv() PLAYER_NAME = os.getenv("PLAYER_NAME") print(f"Welcome '{PLAYER_NAME}' to my Rock-Paper-Scissors game!") #non .env way #PLAYER_NAME = input ("Please select a player name:") #print("WELCOME" f"{PLAY...
#!/usr/bin/env python # coding: utf-8 import os import csv filepath = os.path.join("Resources", "budget_data.csv") budget_info = {} #Made an empty dictionary to store information from the csv so I don't have to keep it open #opening CSV file and storing info in the dictionary with open(filepath) as csvfile: csvr...
from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize ps = PorterStemmer() words = ['python', 'pythoned', 'pythoning', 'pythoned', 'pythonly'] # for w in words: # print(ps.stem(w)) new_text = "It is important to be pythonly while you are pythoning with python. All pythoners have poorly pyth...
cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers car_pool_capacity = cars_driven * space_in_a_car average_passenger_per_car = passengers / cars_driven print("there are", cars, "cars available") print("there are only", drivers, "drivers available") prin...
def myFileWordCounter(): myFileInput = input("Write a file name here! :") file = open(myFileInput, 'r+') #readLines = file.readlines() splitWordsInFile = file.read().split() # for i in readLines: # print(i) print(len(splitWordsInFile)) # takeAddedText = input("Write what you w...
# first ask base case # if the len of the list is less than or equal to one, then we have a sorted list # otherwise, we will use splice to extract the left and right halves. def mergeSort(n): print("Splitting ", n) if len(n) > 1: mid = len(n) // 2 left = n[:mid] right = n[mid:] ...
# here we use 2 lists to create a HashTable class that implements # the Map abstract data type. One list, called slots, will hold the # key item. A parrallel list, called data, will hold the data # values. When we look up a key, the corresponding position in the # data list will hold the associated data value. We wi...
# ordinal value hash function def hash(astring, tableSize): sum = 0 for pos in range(len(astring)): sum += ord(astring[pos]) return sum%tableSize print(hash('cat', 11))
# Uses Heath Nutrition and Population statistics, # stored in the file HNP_Data.csv.gz, # assumed to be located in the working directory. # Prompts the user for an Indicator Name. If it exists and is associated with # a numerical value for some countries or categories, for some the years 1960-2015, # then finds out the...
#!/usr/bin/python3 # Unsing the template offered by Zac Partridge, thanks a lot ### Question anwser: # This AI program is implemented by using alpha-beta algorithm # The main function is ab_pruning() function(implementing alpha-beta algorithm), which is actually a recursive function, return a int value to de...
""" This module provides functionality for plotting in jupyter (http://jupyter.org/) notebooks based on dygraphs (http://dygraphs.com/) and pandas (https://pandas.pydata.org/). """ import json import uuid import pandas from IPython.display import HTML def dygraphplot(*dataframeandoptions): """ Plots the given...
""" Exercício 2 Receba um número inteiro positivo na entrada e imprima os N primeiros números ímpares naturais. Para a saída, siga o formato do exemplo abaixo. Exemplo: Digite o valor de n: 5 1 3 5 7 9 """ def calculo_n_impares(n): contador = 0 numero_natural = 0 while contador < n: resultado = n...
""" Escreva a função maior_primo que recebe um número inteiro maior ou igual a 2 como parâmetro e devolve o maior número primo menor ou igual ao número passado à função. Exemplo: > maior_primo(100) 97 > maior_primo(7) 7 Dica: escreva uma função éPrimo(k) e faça um laço percorrendo os números até o número dado checand...
''' Faça um programa em Python que receba quatro notas, calcule e imprima a média aritmética. Observe o exemplo abaixo: Exemplo: Entrada de Dados: Digite a primeira nota: 4 Digite a segunda nota: 5 Digite a terceira nota: 6 Digite a quarta nota: 7 Saída de Dados: A média aritmética é 5.5 Dica: uso do print Quando vo...
# -*- coding: utf-8 -*- """ Coursework 3: Clustering References: https://scikit-learn.org/stable/modules/clustering.html https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html https://docs.scipy.org/doc/scipy/reference/spatial.distance.html """ import numpy as np from sklearn.clu...
idadeAnos = int(input("Informe sua idade (em anos): ")) idadeMeses = int(input("Informe sua idade (os meses): ")) idadeDias = int(input("Informe sua idade (os dias): ")) idade = idadeDias+(idadeMeses*30)+(idadeAnos*365) print("Você já viveu ",idade, " dias!")
lado = float(input("Informe o lado do quadrado: ")) print("Área do quadrado: ",lado**2)
salarioA = float(input('Informe seu salario: R$')) percent = float(input('Inforem percentual de reajuste: ')) novoSalario = salarioA+(salarioA*percent/100) print('Seu salario Reajustado: ', novoSalario)
maior = 0 nMaior = 0 for x in range(10): n=x+1 valor = float(input('Informe o '+str(n)+'º valor: ')) while valor < 0: print("O valor deve ser positivo!\n") valor = float(input('Informe o '+str(n)+'º valor novamente: ')) if valor > maior: maior = valor nMaior = n print("O ...
import os repetir = True while(repetir): os.system('cls' if os.name == 'nt' else 'clear') valor = float(input('Informe um valor: ')) if valor >=0: print('\nÉ positivo!') else: print('\nÉ negativo!') continuar = input("Deseja continuar: \n1 - SIM \nQualquer outra tecla - Não \n")...
tempC = float(input("Informe a temperatura em °C: ")) tempF = (tempC*(9/5))+32 print('Temp °F: ', tempF)
s = ["ACESSO PERMITIDO", "ACESSO NEGADO"] senha = input('Informe a senha: ') if senha == "1234": print(s[0]) else: print(s[1])
class Solution(object): def hammingDistance(self, x, y): res = 0; while not (x == 0 and y == 0): if not x%2 == y%2: res = res + 1; x = x/2; y = y/2; return res;
''' Mean_Average_Precision: takes two arguments: the first argument is a list of the correct values the second argument is a list of tuples, the values in the tuple are the guesses in its current form this code is only suitable for use in the Best Buy competitionand the fact that it is MAP@5 is gauranteed ...
import time import random characters = ["troll", "gorgon", "pirate", "wicked fairie"] character = random.choice(characters) def print_pause(message): print(message) time.sleep(2) def introduction(): print_pause("You find yourself standing in an open field, " "filled with grass and yello...
def faculty(num): num = int(num) fac = 1 while num != 0: fac *= num num -= 1 return fac def is_curious(number): number = str(number) total = 0 answer = 0 for digit in number: total += faculty(int(digit)) if int(number) == total: print "found!", number...
def main(): tri = [] pen = [] hexa = [] for a in range(284, 2000000): tri.append(a*(a+1)/2) for b in range(165, 2000000): pen.append(b*(3*b-1)/2) for c in range(143, 2000000): hexa.append(c*(2*c-1)) for number in tri: if number in pen: print ...
import sys def isprime(n): n = abs(int(n)) if n < 2: return False if n == 2: return True if not n & 1: return False for i in range(3, int(n**0.5)+1, 2): if n%i == 0: return False return True def test(num): num = str(num) check = [] for di...
# -*- coding: utf-8 -*- """ find the root of equation polynomial in a simple case (x^2-y) """ epsillon=0.01 y=24 guess=y/2.0 while abs((guess**2)-y)>epsillon: guess=guess-((guess**2)-y)/(2*guess) print(guess)
import re nome = input("Digite seu nome: ") telefone = input("Digite seu telefone ( xx xxxxx-xxxx): ") email = input("Digite seu email: ") pattern_nome = '[A-Z]' pattern_tel = '([0-9]{2}\s[0-9]{4,5}\-?[0-9]{4})' pattern_email = '^\w*(\.\w*)?@\w*\.[a-z]+(\.[a-z]+)?$' resultado_nome = None resultado_tel= Non...
#Simple registration app in python with a GUI built from tkinter # # Created by Robert Zeelie 26\09\19 # #Just Run program but you can change type of output by changing button1 command between either print1 or print2 from tkinter import * from PIL import Image, ImageTk #------------------------------------...
def merge(list1, list2): if list1 is None: list1 = [] if list2 is None: list2 = [] m = len(list1)+len(list2) list = [0 for i in range(m)] for k in range(m): if not list1: list[k] = list2[0] list2 = list2[1:] elif not list2: l...
from turtle import Screen from Paddle import Paddle from Ball import Ball from Score import ScoreBoard import time screen = Screen() screen.setup(width=1000, height=600) screen.bgcolor('black') screen.title('PONG') screen.tracer(0) score_board = ScoreBoard() left_paddle = Paddle((-400, 0)) right_paddle = Paddle((40...
# 9. Palindrome Number # https://leetcode.com/problems/palindrome-number/ class Solution: # 주어진 숫자가 회문인지 판별하는 문제다. def isPalindrome(self, x: int) -> bool: return str(x) == str(x)[::-1] if __name__ == '__main__': # 1년전에 풀었는데 풀이를 보니 다시 푼 것과 코드가 완전히 일치했다. # 놀라운 점은 코드는 같은데 걸린 시간 7배 빨라졌다. LeetCod...
''' program to check if number is prime or not prime number is always greater than 1 if (num % ) == 0: ''' def prime_number(num): if num > 1: for i in range(2, num): if (num % i) == 0: print(num, ": Number is not a prime") break else: print(n...
''' Convert given temperature from Celsius to Fahreneit and Fahrenheit to Celsius a is a given number ''' def celsiusTofahrenheit(C): fahrenheit = (C * 9/5) + 32 return fahrenheit def fahrenheitTocelsius(F): celsisus = (F - 32) * 5/9 return celsisus for i in range(1): print(f"running for the {...
class User: users_list = [] def __init__(self, first_name, last_name, password): self.first_name = first_name self.last_name = last_name self.password = password @classmethod def save_user(cls, user): cls.users_list.append(user) @classmethod def find_u...
class Woman: def __init__(self, name): self.name = name self.__age = 18 def __secret(self): # 在对象的方法内部,是可以访问对象的私有属性 print("%s的年龄是 %d" % (self.name, self.__age)) xiaofang = Woman("小芳") # 私有属性在外界不能直接被访问 print(xiaofang._Woman__age) # 私有方法,同样不允许在外界直接访问 xiaofang._Woman__secret(...