text stringlengths 37 1.41M |
|---|
from keyword import iskeyword
def contains_keyword(*arg):
for string in arg:
if iskeyword(string):
return True
return False
print(contains_keyword("hello", "goodbye")) |
cities = ['Los Angeles', 'San Jose', 'San Luis Obispo', 'Los Angeles']
print(f"{cities =}")
print(f"{set(cities) =}")
print(f"{list(set(cities)) =}") |
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, -1].values
print(f"X = {X}")
print(f"Y = {Y}")
print()
# Split Dataset: Training Set and Test Set
from sklearn.model_selecti... |
from random import choice
print('Rock...')
print('Paper...')
print('Scissors...')
player1 = input('Player 1, make your move: ').lower()
player2 = choice(['rock', 'paper', 'scissors'])
print(f'Computer plays {player2}')
if player1 == player2:
print('Its a TIE!')
elif player1 == 'rock' and player2 == 'scissors':
p... |
sum1 = 0 #sum of all numbers<1000 divisible by 3
sum2 = 0 #sum of all numbers <1000 divisible by 5
sum3 = 0 #sum of all numbers <1000 divisible by 15
i = 3
j = 5
k = 15
while i<1000: #slowest pointer
sum1+=i
i+=3
if j<1000:
sum2+=j
j+=5
if k <1000:
sum3+=k
k+=15
print(sum1+sum2-sum3) #excluding the double ... |
# input data
# I propose to change "sudoku" var to input_list_of_digits - OK, no prob :)
input_list_of_digits = "..5..79...2..9..4.3..8....66.....4...7.....3...8.....28....2..3.6..7..9...45....."
print "Number of sudoku elements: %d" % len(input_list_of_digits)
def sudoku_grid(data):
for i in range(len(data)):
... |
'''19. Faça um programa que:
insira dez números inteiros em um vetor
crie um segundo vetor, substituindo os números multiplos de 3 por "999""
exiba os dois vetores
não use nenhuma função pronta da linguagem Python'''
vetor1 = []
vetor2 = []
for i in range(5):
vetor1.append(int(input('Digite um número inteiro: '))... |
# 9. Criar um algoritmo que leia dados para um vetor de 10 elementos inteiros, imprimir o maior, o menor, o percentual de números pares e a média dos elementos do vetor. Obs.: percentual = quantidade contada * 100 / quantidade total. Não use nenhuma função pronta da linguagem Python.
numeros = []
pares = []
cont = 0
s... |
salario = float(input("Informe aqui o salário base do funcionario: "))
perImposto = float(input("Informe aqui a porcentagem do imposto: "))
imposto = salario * perImposto / 100
salario_a_receber = salario + 50 - imposto
print("O salário a receber é de R$ {:.2f}".format(salario_a_receber)) |
num = []
pares = []
impares = []
cont_par = cont_impar = 0
for i in range(6):
num.append(int(input('Digite um número inteiro: ')))
for i in range(6):
if num[i] % 2 == 0:
pares.append(num[i])
cont_par += 1
else:
impares.append(num[i])
cont_impar += 1
print(f'A quantidade d... |
i = 0
soma = 0
while i < 5:
preco = (float(input("Coloque o preço de um produto: ")))
soma += preco
i += 1
media = soma / i
print(f"A média dos 5 produtos são de R$ {media:.2f}") |
deposito = float(input("Coloque aqui o valor que você deseja depositar: "))
taxa = float(input("Coloque aqui o valor da taxa de juros: "))
rendimento = deposito * taxa / 100
total = deposito + rendimento
print("O valor do rendimento é de R$ {:.2f}".format(rendimento))
print("O valor total do rendimento de um mês é ... |
valor_salario = float(input("Coloque o valor salário mínimo: "))
qtde_quilowatt = float(input("Informe a quantidade de quilowatts consumido: "))
valor_quilowatt = valor_salario / 5
valor_em_reais = valor_quilowatt * qtde_quilowatt
valor_descontado = valor_em_reais * 15 / 100
valor_com_desconto = valor_em_reais - valo... |
angulo = int(input('Insira aqui um valor de ângulo em graus: '))
if angulo > 360 or angulo < -360:
voltas = angulo // 360
angulo = angulo % 360
else:
voltas = 0
if angulo == 0 or angulo == 90 or angulo == 180 or angulo == 270 or angulo == 360 or angulo == -90 or angulo == -180 or angulo == -270 or angulo... |
"""Faça um programa que preencha um vetor com sete números inteiros. Calcule e mostre:
os números múltiplos de 2;
os números múltiplos de 3;
os números múltiplos de 2 e de 3."""
numeros = []
num2 = []
num3 = []
num = []
for i in range (7):
numeros.append(int(input("Digite um número inteiro: ")))
for i in range (... |
# 7. Faça um algoritmo que calcule e apresente a média de alturas superior a 1,80 de 10 alunos. Informe também quantos e quais (índice/posição) são os alunos. Não use nenhuma função pronta da linguagem Python.
import sys
altura = []
altura_m = 0
cont = 0
indice = []
for i in range(10):
altura.append(float(input("... |
codigo_estado = int(input('Digite aqui o codigo do estado de origem da carga (codigo de 1 a 5): '))
peso_carga = float(input("Insira o peso da carga do caminhão em toneladas: "))
codigo_carga = int(input('Digite o codigo da carga (codigo de 10 a 40): '))
peso_kg = peso_carga * 1000
print(f'O peso da carga do caminhão ... |
print("Vamos aumentar teu salário")
salario = float(input("Informe aqui teu salário: "))
percentual = float(input("Informe aqui qual a porcentagem de aumento do salario: "))
aumento = salario * percentual/100
novo_salario = salario + aumento
print("O salário a receber é de R$ {:.2f}".format(novo_salario)) |
#Faça um programa que carregue um vetor com a média de dez alunos, calcule e mostre a MÉDIA DA SALA e quantos alunos estão acima e abaixo da média da sala.
vet_media = []
soma_media = 0
alunos_cima = 0
alunos_baixo = 0
for i in range(10):
vet_media.append(float(input(f'Insira a média do {i+1}º aluno: ')))
som... |
import sqlite3
import SQLExample
def UpdateFactionStats(fname, ftype, ftier, stat, newvalue):
# connecting to the database
connection = sqlite3.connect("myTable.db")
# cursor
cursor = connection.cursor()
#fname = input("Choose a Faction: ")
#Faction does not have to be validated ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
column_name = ['user_id', 'item_id', 'rating', 'timestamp']
df = pd.read_csv('u.data', sep='\t', names= column_name)
print(df.head())
movie_titles = pd.read_csv('Movie_Id_Titles')
# Mergi... |
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param new_interval, a Interval
# @return a list of Interval
def insert(self, intervals, new_interval):
d... |
# File: proj3.py
# Author: Dylan McQuaid
# Date: 11/27/17
# Section: 27
# E-mail: mcdyl1@umbc.edu
# Description: This program uses a recursive search algorithm to solve a maze
# read in from file
# 1, 0, 0, 1
#wall on right, open bottom, open left, wall on top
#constants for indexes representing the sides of the squ... |
while True:
try:
num1 = int(input("Enter THE number: "))
result = num1%3
res2 = num1%5
if result == 0 and res2 == 0:
print("fizzbuzz")
elif result == 0:
print("fizz")
elif res2 == 0:
print("buzz")
except ValueError:
... |
def list_handler(in_list):
max = 0
min = 100
for item in in_list:
if item > max:
max = item
if item < min:
min = item
result = max - min
return result
def userinput(text):
usr_in = input(text)
return usr_in
def handle_input(text):
proper_inpu... |
import random
coordsys = []
for x in range(0, 5):
coordsys.append([])
for y in range(0, 5):
coordsys[x].append(0)
coordsys[2][2] = "X"
middle_x = 2
middle_y = 2
robot_snail_pos_x = random.randint(0, 5)
robot_snail_pos_y = random.randint(0, 5)
robot_snail_pos = coordsys[robot_snail_pos_x][robot_snail_p... |
stringlist = {}
string = "egy kettő kfasédf 3 négy"
def checkio(string):
stringlist = list(string.split())
count = 0
for i in range(len(stringlist)):
variable = stringlist[i]
if variable.isdigit():
count = 0
else:
count += 1
if count == 3:
... |
#!/usr/bin/env python
'''
Created on Oct 1, 2012
@author: josh
'''
from player import playerone
import random
from dice import Die
def fight():
from enemylist import enemylist
# PICKS AN ENEMY FROM ENEMYLIST FILE
opponent=random.choice(enemylist)
print "You are fighting "+opponent.Name, "\n\tOpponent's ... |
#!/usr/bin/env python
'''
Created on Sep 27, 2012
@author: josh
'''
import random
def roll(dice, sides):
total=0
for x in range(1, dice+1):
total += random.randrange(1, sides+1)
return int(total)
|
# 类调用实例
# 列表
# 递归
def print_test(the_list):
if isinstance(the_list, list):
for t in the_list:
print(t)
print_test("not list")
else:
print(the_list)
|
'''
Created on Nov 12, 2015
@author: prefalo
'''
from random import random
from timeit import timeit
def aList():
lst = []
for _ in range(1000000):
lst.append(random())
return lst
def aGen():
for _ in range(1000000):
yield random()
print("List Comprehension from List")
print(timeit(... |
#!/usr/local/bin/python3
"""Lesson 16 Obj 2 - final.py
Read in text from a file given on the command line. Count the frequency
of words of each length without punctuation and display results.
USAGE: ./final.py file.txt
"""
import sys
import collections
import string
def len_no_punctuation(w):
"""... |
from tkinter import *
ALL = N+S+W+E
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master.rowconfigure(0, weight=1, minsize="100px")
self.master.columnconfigure(0, weight=1, minsize="170px")
self.grid(sticky=ALL)
for r in ... |
################################################################################
# Differential Op Amp
################################################################################
# Author: N. Dodds
# Written on: Python xy (python 2.7)
# References:
# [1] http://www.electronics-tutorials.ws/opamp/opamp_5.... |
from cipher import *
from math import sqrt
from copy import copy
import argparse
messages = ["1989\nOver hill, over dale,\n\
Thorough bush, thorough brier,\n\
Over park, over pale,\n\
Thorough flood, thorough fire!\n\
I do wander everywhere,\n\
Swifter than the moon's sphere;\n\
And I serve the Fairy Queen,\n\
To dew ... |
"""
calcgpa.py
Calculates GPA of certain courses according to a query.
"""
import argparse
from sys import exit
from os import path
def filter_courses(original_courses_list, year, upper_bound, lower_bound, semester):
"""
Returns the filtered list of courses by fulfilling ALL of the filter demands specifi... |
import nltk
def openFile(file_path_name):
with open(file_path_name) as file:
text = file.read()
return text
paragraph = openFile("nltk_file2.txt")
token_words = nltk.word_tokenize(paragraph)
# # porter stemming the words
# stemmer = nltk.PorterStemmer()
# stem_words = [stemmer.stem(wd) for wd in ... |
from nltk.corpus import stopwords
# stop words to be removed
stop_words = stopwords.words('english')
base = "hurricane ophelia hits ireland and schools close"
# List of sentences
sentences = ["hurricane ophelia hits ireland and schools close",
"hurricane ophelia misses england and work still closed",
... |
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
else:
newNum = num * 3 + 1
print(newNum)
return newNum
print('Enter number:')
num = int(input())
while num != 1:
num = collatz(num)
|
num = int(input('Enter any number: '))
if num % 2 == 0:
print('Oh yeah this bitch is even')
else:
print('No thank you i dont mess with odds')
|
import numpy as np
def hNeuron(W, X):
'''
Task 3.1
Function immitating functionality of neuron using step function
:param W: weight vector of (D+1)-by-1
:param X: data matrix of D-by-N
:return: Y: output vector of N-by-1
'''
bias = W[0]
W = np.delete(W, 0)
a = np.dot(W.T,X) + bi... |
from math import *
from random import *
from copy import *
from Direction import *
class IA():
def __init__(self,liste):
"""
Constructeur de la classe, prend en paramètre la liste qui correspond à la grille du 2048
Initialise également la liste de Direction qui servira dans play() et playA... |
#https://www.hackerrank.com/contests/algoritmos-2018-i-contest-1/challenges/sherlock-and-array
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the balancedSums function below.
def balancedSums(arr):
leng = len(arr)
nos=arr
for i in range(1,leng):
... |
#set inn et tak for hvor høyt du vil finne summen av alle tallene delelig med 3 eller 5
def multiple3n5():
n=1 #vi starter tellingen fra n=1
tak=int(input("input a roof")) #set inn et tak for hvor høyt du vil finne summen av alle tallene delelig med 3 eller 5
list=[] #etable... |
def read_from_file(filename):
file=open(filename)
return file.read()
def make_dict_CSV(filename):
text=read_from_file(filename)
output={}
for i in text.splitlines():
items=i.split(",")
output[items[0]]=items[1]
return output
def åpnestudier(filename):
dictionary=make_dict_CSV... |
n=input()
def evenfibonacci(n):
a=1
b=2
fibs=[]
EvenFibs=[]
while a<n:
fibs.append(a)
fibs.append(b)
a=a+b
b=a+b
print(fibs)
for n in fibs:
if n%2==0:
EvenFibs.append(n)
print(sum(EvenFibs))
return EvenFibs
evenfibonacci(100000)
|
def Factor(n):
i = 2
factors = []
while i * i <= n: #alle primtallsfaktorer av n er mindre eller lik kvadratroten av n
if n % i != 0: #vi sjekker om vi kan dele på i, dersom resten er ulik 0 er i ikke en faktor av n
i += 1 #vi øker i for å sjekke om i+1 er en... |
# coding=utf-8
import random as rnd
import numpy as np
import scipy as sci
import matplotlib.pyplot as plt # Import plotting library
def draw(nums,n):
li=[0]*n
i=0
while li[-1]==0:
draw=rnd.randint(0,len(nums)-1)
if nums[draw] not in li:
li[i]=nums[draw]
i+=1
ret... |
longest=0
length_max=0
for i in range(1000000):
startpoint=i
length=0
while i>1:
if i%2==1:
i=3*i+1
length+=1
else:
i=i//2
length += 1
if length>length_max:
longest=startpoint
print (longest) |
# Created by: Yusuf Moussa
# Created on: 01 April 2019
# Created for: ICS3U
# Daily Assignment Unit 4-04
# This is convert levels into grades
from tkinter import *
root = Tk()
root.title("Cylinder volume calculator")
root.geometry("500x300")
Label(root, text="This is a program to calculate the volume of ... |
# -*- coding:utf-8 -*-
class BlockChain(object):
def __init__(self):
self.head = None # 指向最新的一个区块
self.blocks = {} # 包含所有区块的一个字典
def add_block(self, new_block):
previous_hash = self.head.hash() if self.head else None
new_block.previous_hash = previous_hash
self.blocks[... |
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
data=pd.read_csv('wineQualityReds.csv')
#print(data.head())
pri... |
class Hangman():
#Thanks to Darvyn for this code!
#Thanks to Jessica for helping me debug the code.
#We start with a function that descibes the game and instructions.
#In []: is an example of an absolute value function
#Def X(): defines a function
#Print (): is a function that prints whatever is in the single ... |
from karel.stanfordkarel import *
"""
File: RampClimbingKarel.py
--------------------
When you finish writing this file, RampClimbingKarel should be
able to draw a line with slope 1/2 in any odd sized world
"""
def main():
"""
You should write your code to make Karel do its task in
this function. Make sur... |
def largest_ten(l):
# Assuming list size greater than 10
'''
@l: list of integers
remember to mention your runtime as comment!
@return: largest ten elements in list l, as a new list. (Order doesn't matter.)
'''
top_ten = []
for i in range(0, 10):
max_num = 0
f... |
def hash_str(string):
''' return a integer hash value for the given string.
you should follow the hash function property:
1. hash same thing gives the same result.
2. hash different thing should give different result. The more different, the better.
@string: the string to be hashed.... |
def merge(I1, I2):
'''
@I1: the first iterable object. Can be a string!
@I2: the second iterable object.
required runtime: O(n).
@return: alternately merged I1, I2 elements in a list.
'''
a = []
b = []
c = []
for i in I1:
a.append(i)
fo... |
class LeakyStack():
def __init__(self, max_size):
self._data = [None] * max_size # Static size
self._size = 0 # Track current number of elements
self._top = 0 # Use this variable to make the stack circular
def push(self, e): # O(1)
if self._size < len(self._data):
... |
import copy
def knapsack_driver(capacity, weights):
'''
@capacity: positive integer. the value we are summing up to.
@weights: list of positive integers.
### Friendly tip: This function can't solve the problem,
### you need more parameters to pass information for recursive functions.
### So,... |
# twoOperandInstruction.py
# Author: Tanner Shephard
# Description: Decodes and holds data for any double operand instruction. Value
# is given as a number and then all relevant variables are written
# via shifts and masks
class twoOperandInstruction:
def __init__(self,instructionValu... |
import os
import pandas as pd
import sqlite3
def create_dataframe(db_filename):
"""
Creates a dataframe by concatenating the tables in the database specified
by db_filename, following the specific instructions in the homework.
"""
if not os.path.exists(db_filename):
raise ValueError(f"'{db... |
"""
Contains the querying interface.
Starting with :class:`~tinydb.queries.query` you can construct complex
queries:
>>> ((where('f1') == 5) & (where('f2') != 2)) | where('s').matches('^\w+$')
(('f1' == 5) and ('f2' != 2)) or ('s' ~= ^\w+$ )
Queries are executed by using the ``__call__``:
>>> q = where('val') == 5
... |
"""
Splits large CSVs into multiple shards.
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import argparse
import gzip
import pandas as pd
def parse_args(input_args=None):
parser = argparse.ArgumentParser()
parser.add_argument(
"--csv-file", re... |
from numpy import *
# input format : dot(transpose(w), x)
# w = (w0, w1, w2, ...)
# x = (1, x1, x2, ...)
def sigmoid(x):
return 1/(1+exp(-x))
def sigmoid_differential(x):
return x*(1-x)
# gradient descent
# activation function: f(x)
# cost function for pattern mode: J(w) = (y_i - f(dot(transpose(w), X_i))... |
#!/bin/python
import os
os.system('clear')
os.system('cls')
# @author: [ Paulino Bermúdez R.]
# @Description: What is the output of the following snippet?
lst = [1, 2, 3, 4, 5]
# Insert in:
# Position: 1
# Value: 6
lst.insert(1, 6)
print("Insert ",lst)
# Delete 1st element
del lst[0]
print("Delete ",lst)
# Add (in fi... |
# @Title: Creación de carreras de tortugas con PyGame
# @Description: En este programa se creará una competición de carreras de tortugas con la ayuda de la libreria
# pygame. Para ello, es necesario instalar el paquete, por defecto no lo está, para ello:
# > Tools
# >> Manage packages..
# >>> En la barra de 'Find p... |
# anagrama('amor', 'roma')
def anagrama(p1, p2):
comparacionLetras = []
if len(p1) != len(p2): # recorer para comparar longitud de palabras
return False
for caracter1 in p1:
haPasado = False
for caracter2 in p2:
if caracter1 == caracter2 :
haPasado =... |
# @Title: Crear Termómetro Gráfico
# @Description: Creacion de un termometro con interfaz grafica de usuario,
#
# Nota: En los proyectos tkinter principalmente suelen poner la palabra 'root' como objeto principal de inicio de los programas,
# sin embargo, puedo llamarlo como quiera.
#
# @Version: 1.1
# @Author: Chunch... |
notas = (2,4,6,8,10,4,6,8,10,4,6,8,10,4,6,8,10,4,6,8,10,4,6,8,10,4,6,8,10)
def contenido(lista,indice):
try:
resultado = lista[indice]
except:
resultado = None
return resultado
def longitud(lista):
indice = 0
while contenido (lista,indice) != None:
indice = indice +1
re... |
aclNum = int(input("What is the IPv4 ACL number? "))
if aclNum >= 1 and aclNum <= 99:
print("This is a standard IPv4 ACL.")
elif aclNum >= 100 and aclNum <= 199:
print("This is an extended IPv4 ACL.")
else:
print("This is not a standard or extended IPv4 ACL.")
|
import ANSIEscapeSequences
entradas = {
'baby':{'cantidad':0,'precio':0},
'niño':{'cantidad':0,'precio':14},
'adulto':{'cantidad':0,'precio':23},
'jubilado':{'cantidad':0,'precio':18}
}
lineaPantalla = {'baby':4, 'niño':5,'jubilado':6,'adulto':7}
def tipoEntrada(miedad):
# Segun ed... |
country = [
"Brazil",
"Russia",
"India",
"China",
"South Africa"
]
capitals = {
"Brazil": "Brasilia",
"Russia": "Moscow",
"India": "New Delhi",
"China": "Beijing",
"South Africa": [
"Pretoria",
... |
# bloque de entrada
numero1 = float(input( "Número uno :")) / 10
numero2 = float(input( "Número dos :")) / 10
# bloque de procesos
suma = numero1 + numero2
resta = numero1 - numero2
producto = numero1 * numero2
division = numero1 / numero2
# bloque de salida de datos
print(" La suma de los valores es :" ,suma )
pri... |
#!/bin/python
import os
os.system("clear")
os.system("cls")
while True:
print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
income = float(input("Enter the annual income: "))
print("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv \n")
base = 85528
#
# Calculating tax.
#
if in... |
# Creo una funcion que guarda las operaciones de comprobracion del anagrama
def isAnagram(p1,p2):
# Inicializo una lista que guarda las comparaciones de las letras
listaComparacionLetras = []
# Comparo la longitud de las palabras para que sean iguales, en numero de letras
if len(p1) != len(p2):
... |
#!/bin/python
import os
os.system('clear')
os.system('cls')
# @author: [ Paulino Bermúdez R.]
# @Description: Ejercicio 5 de la seccion 3.1.3.10
myList = [1, 2, "in", True, "ABC"]
??? = input("¿Qué pongo? ")
print(1 ??? myList) # outputs True
print(" outputs True")
??? = input("¿Qué pongo? ")
print("A" ??? myList) # ... |
precios = float(input("Introduzca precio : "))
unidades = float(input("Introduzca unidades de producto : "))
precioTotal = 0
totalUnidades = 0
_PRECIOS = 0
_UNIDADES = 1
def informaItem( precios, Unidades ):
item = dict()
item['precios'] = precios
item['unidades'] = unidades
return item
listaLineasF... |
import programaPantalla
def tipoEntrada(e):
if e > 0 and e <= 2:
tipo = 'bebe'
elif e <= 12:
tipo = 'niño'
elif e < 65:
tipo = 'adulto'
else:
tipo = 'jubilado'
return tipo
def validaEdad(cadena): # validar solo positivos
try:
n = int(cadena)
if n... |
myList = [0, 3, 12, 8, 2]
print(5 in myList)
print(5 not in myList)
print(12 in myList) |
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib import animation
lifes=[]
def play_life(a):
xmax, ymax = a.shape
b = a.copy()
for x in range(xmax):
for y in range(ymax):
n = np.sum(a[max(x - 1, 0):min(x + 2, xmax), max(y - 1, 0):min(y + 2, ymax)]) - a[x, y... |
#!/bin/python
import os
os.system('clear')
os.system('cls')
# @author: [ Paulino Bermúdez R.]
# @Description: Hipótenisis de Collatz
# Dice que un nº natural positivo distinto de cero, sí es:
# 1 - Un nº par
# + lo divido entre 2
# 2 - Un nº impar
# + lo multiplico x 3
# + y... |
# Creamos una función para la validación de los datos de entrada
def esDecimal(numero):
try:
float(numero)
return True
except:
return False
# Entrada de parámetros:
B = input ("Base del triangulo: ")
if esDecimal(B):
# Guardamos y convertimos los valores de entrada.
b = float(B)... |
# Funcion que nos indica el tiempo de ejecucion de cada una de las funciones del programa
import timeit
# Creo una funcion que guarda las operaciones de comprobracion del anagrama
def isAnagramE(p1,p2):
# Inicializo una lista que guarda las comparaciones de las letras
listaComparacionLetras = []
# Comparo ... |
cadenaUnidades = input("Cantidad: ")
unidades = float(cadenaUnidades)
cadenaPrecio = input("Precio Unitario (€): ")
precio = float(cadenaPrecio)
totalItems = 0
precioTotal = 0
cadenaAImprimir= ""
while unidades > 0 and precio > 0:
totalUnitario = unidades * precio
#cadenaAImprimir += str(precio) + " € - " + s... |
#!/bin/python
import os
from datetime import date
os.system('clear')
os.system('cls')
# @author: [ Paulino Bermúdez R.]
# @Description: Continue function.
print(40*'·')
print(date.today())
print(40*'·')
largestNumber = -99999999
counter = 0
number = int(input("Enter a number or type -1 to end program: "))
while n... |
# Write a program to read through the mbox-short.txt
filehandle = open('mbox-short.txt')
distribution = dict()
# figure out the distribution by hour of the day for each of the messages.
for line in filehandle :
if line.startswith("From") and not line.startswith("From:") :
# You can pull the hour out fro... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
""""
Initial Thoughts:
- palindrome reads the same forward and backwards
- need two pointers
- have to check first and last node and see if it's the same, and then keep moving inwards ... |
class node:
def __init__(self,value = None):
self.value = value
self.next = None
class linked_list:
def __init__(self):
self.head = node()
#this append will append this node to the end
def append(self,value):
new_node = node(value)
cur = self.head
while cu... |
# -*- coding: utf-8 -*-
#if文の条件には:
#else:
#pythonはindentを統一する必要がある
import numpy as np
def AND(x1, x2):
w1, w2, theta = 0.5, 0.5, 0.7
tmp = x1*w1+ x2*w2
#tmp = np.sum(w*x)
if tmp <= theta:
return 0
elif tmp > theta:
return 1
print(AND(0,0))
def NAND(... |
class Nodo():
def __init__(self, valor, izq=None, der=None):
self.valor=valor
self.izq=izq
self.der=der
class Variable():
def __init__ (self, nombre, valor):
self.Nombre=nombre
self.Valor=valor
def evaluar(arbol):
if arbol.valor == "+":
return ... |
#!/usr/local/bin/python3.8
import random
num=int(input("Please enter the number: "))
List=[]
def addfun(num):
count=0
while count < 5:
List.append(num)
num=num+1
count=count+1
print (List)
x=len(List)
con=str(List)
ran=random.randint(0,x-1)
print ("random num is: ",... |
import sqlite3
conn = sqlite3.connect('test.sqlite') # 建立資料庫連線
cursor = conn.cursor() # 建立 cursor 物件
# 建立一個資料表
sqlstr='CREATE TABLE IF NOT EXISTS table01 \
("num" INTEGER PRIMARY KEY NOT NULL ,"tel" TEXT)'
cursor.execute(sqlstr)
# 新增一筆記錄
sqlstr='insert into table01 values(1,"02-1234567")'
cursor.execute(sqlstr)
conn... |
# # function input
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
# #function output
# [("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")]
def dictInTupleOut(xyz):
dict_list = xyz.items()
return dict_list
# print (d... |
myself = {"name": "Victor A.", "age":"27", "country of birth": "The United States",
"favorite language": "Python"}
def printMyself(dict):
for key, val in dict.items():
print ("My {} is {}".format(key, val))
printMyself(myself) |
import states
class Game:
def __init__(self, num_players: int, locations: list):
"""
Initialize the game.
Arguments:
- num_players: Number of players in this game.
- locations: An array of counts of controls in the locations.
"""
self.num_players = num_playe... |
#By: Luis Febro
#Goal: Hangman game with a robot character. You have to find the right answer for each question before your robot end up being hung tragically.
#Date: 05/20/19
#Issues: if you guys know how to fix this box that appears at the beginning before it supossed to pop up, just let me know in the comments.... |
try:
no1 = int(input("1st Integer No :"))
no2 = int(input("2nd Integer No :"))
print("Sum = ", no1 + no2)
print("Div = ", no1 / no2)
except ValueError:
print("Only Integer's are allowed")
except ZeroDivisionError:
print("Cannot Divide By Zero")
else:
print("Sub = ", no1 - no2)
... |
# Example on Global and local variables
a = 1000 # Global variable
def show():
print("I am show")
print(a)
b = 20 # Local Variale
print(b)
print("Sum = ",a+b)
print("Hi")
print(a)
show()
print(a)
print("Bye")
|
import random as ra
from pathlib import*
from turtle import*
def actscore(score,pseudo):
out=False
listevar=["a","b","c","d","e","f","g","h","i",'j']
liste=[1,2,3,4,5,6,7,8,9,10]
#print(score)
with open ("score.txt","r") as sco:
for i in range(10):
liste[i]=int(s... |
def evaluate(root, facts):
assert root is not None
if root.value == '!':
return not evaluate(root.left, facts)
if root.value in ['|', '&']:
if root.value == '|':
return evaluate(root.left, facts) or evaluate(root.right, facts)
elif root.value == '&':
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.