text stringlengths 37 1.41M |
|---|
#Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
#Faça um programa que ajude ele, lendo o onme deles e escrevendo o nome do escolhido.
alunos = []
#['d','a','e','g']
for i in range(4):
alunos.append(input('Inform o nome do {}º aluno(a): '.format(i+1)))
from random import random, ran... |
#Crie um programa que leia um número inteiro e mostre na tela se ele é PAR OU IMPAR.
numero = int(input('Informe o número inteiro a ser verificado: '))
print('Número é PAR' if numero % 2 == 0 else 'Número é IMPAR' ) |
tempo = int(input('Quanto antos tem o seu carro? '))
if tempo <=3:
print('Carro novo')
else:
print('Carro usado')
print('--FIM--')
print('carro novo' if tempo<=3 else 'carro velho')
#PARTE 2
nome = str(input('Qual é o seu nome? '))
if nome == 'Michael':
print('Que nome lindo você tem!!')
else:
print('... |
#Faça um progrma que leia um âgulo qualquer e
# mostre na tela o valor do seno, cosseno e tangete
# desse ângulo.
from math import cos, sin, tan, radians
angulo = float(input('Informe o ângulo para calcular o seno e cosseno: '))
print('O seno deste ângulo radial é: {:.2f}.'.format(sin(radians(angulo))))
print('O coss... |
#Faça um programa que mostre na tela uma contagem regressiva
#para o estouro de fogos de artifício, indo de 10 até 0, com uma pausa de 1 segundo entre eles.
import time
for i in range(10,0,-1):
print(i)
time.sleep(1)
print('Xablau, tempo acabou!')
|
#Crie um programa que leia o nome completo de uma pessoa e mostra:
# * O nome com todas as letras maiúsculas.
# * O nome com todas minúsculas
# * Quantas letras ao todo(sem considerar espaços)
nomeCompleto = input('Favor informar o seu nome completo!')
print(nomeCompleto.upper())
print(nomeCompleto.lower())
print(l... |
#!/usr/bin/env python
"""Audit phones (phone numbers)"""
import xml.etree.cElementTree as ET
import re
import pprint
phone_re = re.compile(r'^\+1-[2-9]\d{2}-\d{3}-\d{4}$')
# dictionary for lookup searches
malformed_numbers = {}
wellformed_numbers = set()
duplicate_numbers = set()
did_not_catch = []
... |
import random
# Letters, numbers and symbols that password can contain
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V'... |
import random, time
def mergeSort(arr):
print("Splitting ", arr)
if len(arr) > 1:
mid = len(arr) // 2
lefthalf = arr[:mid]
righthalf = arr[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i = 0
j = 0
k = 0
while i < len(le... |
# Module 2 - Practice / letter to Number Function
def let_to_num() :
phone_letters = [' ',"","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"]
letter = input("Enter a single letter, space, or empty string: ")
key = 0
while key < 10 :
if letter == "" :
return 1
break
... |
class listNode:
def __init__(self,x):
self.val = x
self.next = None
def createList(self,a):
if a is None:
print 'no elements'
return
head=listNode(a[0])
p=head
i=1
n=len(a)
while i<n:
... |
#coding:utf-8
def half_search(lst,value,low,high):
if high < low:
return None
mid = (low + high)/2
if lst[mid] > value:
return half_search(lst, value, low, mid-1)
elif lst[mid] < value:
return half_search(lst, value, mid+1, high)
else:
return mid
def bin... |
import math
from tempfile import NamedTemporaryFile
from openpyxl import Workbook, load_workbook
wb = Workbook()
ws = wb.active
ws1 = wb.create_sheet('MySheet') # insert at the end (default)
ws2 = wb.create_sheet('MySheet1', 0) # insert at first position
ws3 = wb.create_sheet('MySheet2', -1) # insert at the penul... |
def change(i, s):
l = list(t)
l[i] = s
return tuple(l)
def main():
# tuple的陷阱:当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来
# t = ('骆昊', 38, True, '四川成都')
print('元组: ', t)
print(t[::-1])
for member in t:
print(member, end=' ')
print()
tuple1 = ('王大锤', 20, True, '云南昆明')
prin... |
import sys
def main():
f = [x for x in range(1, 10)] # 数列初始化
print(f)
f = [x + y for x in 'ABCDE' for y in '123']
print(f)
f = [x ** 2 for x in range(1, 100)]
print(sys.getsizeof(f))
print(f)
for val in f:
print(val, end=' ')
if __name__ == '__main__':
main()
|
'''
Created on 2019年8月28日
打印各种三角形图案
*
**
***
****
*****
*
**
***
****
*****
*
***
*****
*******
*********
@author: jinshuang1
'''
row = int(input('请输入行数:'))
for i in range(row):
for j in range(i + 1):
print('*', end='') # 给end赋值为空,就不会换行
print()
for i in range(row):
for j in... |
'''
Provides several utility functions for extracting data from websites (including HTML pages as well as JSON files from APIs).
'''
from contextlib import closing
from bs4 import BeautifulSoup
from requests import get
from requests.exceptions import RequestException
__author__ = "Finn Frankis"
__copyright__ = "Copyr... |
def parzyste(wyraz):
for index in range(0,len(wyraz),2):
yield wyraz[index]
prz=parzyste("Zadanie")
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
print(next(prz))
|
import unittest
from Calculator import Calculator as calc
class TestCalc(unittest.TestCase):
def test_add(self):
self.assertEqual(calc.add(1, 5), 6)
self.assertEqual(calc.add(-1, 2), 1)
self.assertEqual(calc.add(-1, -3), -4)
def test_subtract(self):
self.assertEqual(calc.sub... |
import numpy as np
from sklearn.linear_model import LinearRegression
def rss(y_true,y_pred):
"""
A utility function that returns residual sum of squares
"""
return np.sum((y_true-y_pred)**2)
num_splits = 5
"""
Store all errors and coefficients in arrays and find optimum after all iterations
"""
err = []
coeffs ... |
"""
A program to visualise feature extraction by PCA and its decision boundary
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # For 3-D plot of dataset
from matplotlib.axes import Axes
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklear... |
import numpy as np
np.random.seed(7)# To ensure repeatability
"""
The number of features and the number of examples per class
"""
num_features = 20
num_examples = 2000
# The centroid of the first class is generated randomly.
mean1 = np.random.rand(num_features)
"""
Since second centroid must be close to first one ... |
import random
while True:
### Prompts user for attack modifier then simulates d20 roll
while True:
try:
attack_modifer = int(input("What is your Attack Modifier? "))
break
except ValueError:
print("That is not a valid modifier")
base = random.randint(1, 20... |
import random
# TODO:
# "Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors,
# scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock,
# and as it always has, rock crushes scissors."
while True:
print("Make your choice")
... |
#-*-coding:utf-8-*-
# 6.py说明 将新增的TXT文件删除
import os
def del_files(path):
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".txt"):
os.remove(os.path.join(root, name))
print("Delete File: " + os.path.join(root, name))
# test
if __name_... |
import matplotlib.pyplot as plt
import numpy as np
x = [0,20,50,75,100,150,200,250,300,350,400,450,500]
y1=[0,0.56, 0.72, 0.81,0.9,0.94,0.93,0.92,0.95,0.96,0.96,0.96,0.96]
y2=[0,0.26, 0.36,0.58,0.65,0.73,0.82,0.86,0.84,0.85,0.87,0.88,0.88]
nnet_100_line = plt.plot(x, y1, label='MCTS with NNet')
mcts_100_line = plt.... |
is_asian = True
is_american = False
name = input()
age = int(input())
kids = int(input())
print(name)
if name == "Nurtazim":
print("Asian")
else:
print("American")
if age > 18:
print("Mojno voity")
else:
print("Nelzya")
if kids < 2:
print("Mojno s detmi")
else:
print("Nelzya")
if False:
... |
age = int(input())
currency = str(float(int(input())))
print(type(age))
print(type(currency))
print(age + 90 + 12341)
print(currency)
|
print("Hello, World!")
# print(input("Введите текст: "))
def ab():
a = int(input())
b = int(input())
print(a + b)
def a_mul_b():
a = int(input())
b = int(input())
print(a * b)
def a_div_b():
a = int(input())
b = int(input())
while b == 0:
print("нельзя делить на 0")
... |
#!/usr/bin/python3
import json
MSG_WELCOME = "Welcome to the birthday dictionary. We know the birthdays of:"
MSG_WHOSBDAY = "\nWho's birthday do you want to look up?\n"
MSG_NO_RES = "\nNo such name in the dictionary!"
MSG_RES = "\n{}'s birthday is {}."
MSG_SAVE = "New name and birthday saved!"
FILE = "birthday_dictio... |
#!/usr/bin/python3
MAX_X = 3
MAX_Y = 3
ERROR_MSG_NO_COMMA = "ERROR: There is no , in the input!"
ERROR_MSG_ONLY_XY = "ERROR: Only X and Y coordinates are needed!"
ERROR_MSG_NUMERIC = "ERROR: Inputs should be numeric!"
ERROR_MSG_X_BETWEEN = "ERROR: X should be between 1 and "
ERROR_MSG_Y_BETWEEN = "ERROR: Y should be ... |
#!/usr/bin/python3
def save_to_file(filename, content):
open_file = open(filename, 'w')
open_file.write(content)
open_file.close()
def get_input(message):
input_message = str(input(message))
return input_message
filename = get_input("Enter the filename: ")
content = get_input("Enter the content: ")
save... |
# !/usr/bin/python3
class Animal:
numberOfAnimals = 0
def __init__(self, name):
Animal.numberOfAnimals += 1
print("Animal {} created.".format(Animal.numberOfAnimals))
self.name = name
def getInfo(self):
print("{} is the name of the animal.".format(self.name))
class Mammal(Animal):
def __init_... |
#!/usr/bin/python3
from random import randint
def user_input():
player_1_name = str(input("Player 1: "))
player_2_name = str(input("Player 2: "))
players = [player_1_name,player_2_name]
return players
def num_to_value(num):
if(num == 0):
return "rock"
elif(num == 1):
return "paper"
else:
... |
"""
搭建一个最简单的网络,只有输入层和输出层
输入数据的维度是 28*28 = 784
输出数据的维度是 10个特征
激活函数使用softmax
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
# one_hot 表示的是一个长度为n的数组,只有一个元素是1.0,其他元素都是0.0
# 比如在n=4的情况下,标记2对用的one_hot 的标记是 [0.0 , 0.0 , 1.0 ,0.0]
# 使用 one_hot 的直接原因是,我们使用 0~9 个类别的多... |
# 这个是sklearn带的一个手写字符集合
# 可以熟悉一下这个数据集合,然后使用pca + kmeans 对这个数据进行一个处理
from sklearn import datasets
from matplotlib import pyplot as plt
from sklearn import decomposition
from sklearn.cluster import KMeans
import numpy as np
digits_data = datasets.load_digits()
for index,image in enumerate(digits_data.images[:5]):
p... |
#Projeto Sistemas Operacionais 2018.2
#Fabio e Raissa
#Gerenciamento de Memória
#Imports
from random import shuffle
#Define Functions
# exemplo de entrada print(calculadora("12+34-+"))
def calculadora(equacao):
stack = []
a = b = 0
for c in equacao:
if c == '-':
if len(stack) != 0:
b = stack.pop()
a... |
# Created 27 March 2021
from math import radians, sin, cos, asin, sqrt
def haversine_formula(lat1, lon1, lat2, lon2):
R = 6371000 # radius of Earth in metres
# convert latitudes and longitudes to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
inside = sin((lat2-lat1)/2)**2+co... |
from collections import namedtuple
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', 100, (0,1))
if __name__ == '__main__':
print(f"city = {City}")
print(f"tokyo = {tokyo}")
print(f"tokyo.population = {tokyo.population}")
print(f"tokyo.coordinates = {tokyo.co... |
'''
Created on Dec 9, 2017
@author:akash
'''
a=int(input("1st number?\n"))
b=int(input("2nd number?\n"))
'''a=a+b
b=a-b
a=a-b'''
a=a^b
b=a^b
a=a^b
print("1st number is = ",a,end='\n')
print("2nd number is = ",b,end='\n') |
'''
Created on Jan 27, 2018
files
@author: akash
'''
f=open("readme1.txt",mode='r',encoding='utf-8')
print(f.read(200))
f.close()
f=open("readme1.txt",mode='w',encoding='utf-8')
a=['akash','mummy','papa']
f.write(input())
f.write("\nhello\nmy name is khan\n:-)\n")
lines=['hello\n','my name\n','is mogambo\n'... |
'''to find grade according to the given system
90-100--->O
80-89---->E
70-79---->A
else ---->F'''
n=float(input("Enter marks of the student\n"))
if n>100 or n<0:
print("Marks should be in range 0 to 100")
elif n>=90 and n<=100:
print("O grade")
elif n>=80 and n<=89:
print("E grade")
elif n>=70 a... |
from tkinter import *
# creating the root window
root = Tk()
# creating a Label widget-defining widget
# Essentially answers the question of how the
# widget should look
myLabel1 = Label (root, text = "Hello World!")
myLabel2 = Label (root, text = "My name is Dennis")
#shoving it on the screen
# Essentially puts w... |
import random, sys
print('ROCK, PAPER, SCISSORS')
wins = 0
losses = 0
ties = 0
while True:
print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))
while True:
print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
move = input()
if move == 'q':
sys.exit()
if move == 'r' or move ... |
import requests
from bs4 import BeautifulSoup
import string
import os
import sys
import re
class GeniusApi:
def __init__(self, access_token):
self.base_url = 'https://api.genius.com'
self.headers = {
'Authorization': f'Bearer {access_token}'
}
self.script_... |
from random import randint
from . import game
class AI:
"""
a class representing an AI object which plays 4 in a row.
"""
def __init__(self, game):
"""
the initializng method of the AI, which gets a game object.
"""
self.game = game
def find_legal_move(self, timeo... |
import turtle # may need to pip install turtle
def main():
turtle.setup(500, 500) # size in pixels
# we need a window
window = turtle.Screen()
window.title('Move and rotate using arrow keys')
window.bgcolor('lightblue')
Gordon = turtle.Turtle()
def moveForward():
Gordon.... |
class NewsPublisher:
def __init__(self):
self.__subscribers = []
self.__latestNews = None
def attach(self, subscriber): # attach a new subscriber
self.__subscribers.append(subscriber)
def detach(self):
self.__subscribers.pop()
def subscribers(self):
retur... |
import threading
import time
import random
class TicketSeller(threading.Thread):
ticketsSold = 0
def __init__(self, semaphore):
threading.Thread.__init__(self)
self.__semaphore = semaphore
print('Ticket seller starts selling tickets')
def run(self):
global tickets... |
currency_str_value = input("请输带单位的货币金额:")
RATE = 6.77
if currency_str_value[-3:] == 'CNY':
rmb_str_value = currency_str_value[:-3]
rmb_value = eval(rmb_str_value)
usd_value = rmb_value / RATE
print("美元:", usd_value)
elif currency_str_value[-3:] == 'USD':
usd_str_value = currency_str_value[:-3]
u... |
'''def sample():
print("hello function")
def sam():
print("inside function")
sam()
sample()'''
'''#a=int(input())
#b=int(input())
#c=int(input())
def sample(a,b,c):
#def sample(a,b,c=10):
if(a==b and b==c and c==a):
print(0)
elif(a!=b and b!=c and a!=c):
print(a+b+c)
els... |
a =(int(input("Enter the number to taken the factorial")))
counter=a
resault=1
for i in range(a):
resault*=a-(a-counter)
counter-=1
print(resault)
|
# toplama fonksiyonu
def topla():
sayi1 = int(input(" Sayı1: "))
sayi2 = int(input(" Sayı2: "))
print( sayi1 + sayi2 )
# çıkarma fonksiyonu
def cikar():
sayi1 = int(input(" Sayı1: "))
sayi2 = int(input(" Sayı2: "))
print( sayi1 - sayi2)
# çarpma fonksiyonu
def carp():
... |
ay=int(input("Enter the month value between 1 and 12."))
if ay ==1 or ay ==2 or ay =12 :
print("winter")
if ay ==3 or ay ==4 or ay =5 :
print(" spring")
if ay ==6 or ay ==7 or ay =8 :
print("summer")
if ay ==9 or ay ==10 or ay =11 :
print("autumn")
|
class Node:
def __init__(self, letter):
self.letter = letter
self.children = [None]*26
# isEndOfWord is True if node represent the end of a word
self.isEndOfWord = False
self.meaning = ''
class Trie:
def __init__(self):
self.root = Node('')
def insertion(se... |
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def insertion(self, key):
node = Node(key)
if self.root is None:
self.root = node
else:
c... |
import os
import sys
from argparse import ArgumentParser, HelpFormatter
import startds
class CommandParser(ArgumentParser):
"""
Customized ArgumentParser class to improve some error messages and prevent
SystemExit in several occasions, as SystemExit is unacceptable when a
command is called programmati... |
"""
Capstone Project. Code to run on a LAPTOP (NOT the robot).
Constructs and returns Frame objects for the basics:
-- teleoperation
-- arm movement
-- stopping the robot program
This code is SHARED by all team members. It contains both:
-- High-level, general-purpose methods for a Snatch3r EV3 robot... |
'''
Created on Nov 3, 2018
@authors: Haram Koo, Duncan Van Keulen
'''
def file_to_line(file):
'''
This function turns a file into a string
'''
with open(file, 'r') as file:
list_1 = []
for line in file:
list_1.append(str(line))
string_list = ''.joi... |
# This is the program for rock paper scissor game
# import random module to select random characters from the list
import random
print("Enter the number to select your characters")
print("0 for rock")
print("1 for paper")
print("2 for scissor")
print("only 6 rounds.... let's play the game")
def main():
... |
class Player(object) :
"""
A player for a specific team with needed stats.
Class is designed for input of the url for player's advanced stats page.
"""
def __init__(self,html_link) :
'''
Takes in a player's advanced stats page from kenpom.com and breaks it into a usuable class
... |
from .Converters import *
# print(,file=args["output"], file=args["output"])
def call_(args):
fn_name = args["remaining_command"][0]
arguments = args["remaining_command"][1]
# Function can be called multiple times in a file.
# We need to create labels uniquely in the same file.
unique_key = fn_n... |
print('-'*20)
print('Gerador de PA: ')
p = int(input('Primeiro termo: '))
r = int(input('Razao da PA: '))
amais = 10
total = 0
termo = p
c = 1
while amais != 0:
total += amais
while c <=total:
print('{} - '.format(termo), end='')
termo += r
c += 1
amais = int(input('Quantos termo ... |
n = int(input('Digite um numero: '))
c = 1
print('O numero escolhido foi: {}. Vamos ver a sua tabuada:'.format(n))
while c < 10:
print('{} x {} = {}'.format(n, c, c * n))
c += 1
for i in range (10):
print('{} x {} = {}'.format(n, i, i * n)) |
l = float(input('Digite a largura: '))
c = float(input('Digite o comprimento: '))
area = l * c
litros = area/2
print('Com a largura de {} e o comprimento de {} a area será de {}.'.format(l, c, area))
print('Para pintar uma area de {:.2f} será necessario {:.2f} litros de tinta.'.format(area, litros)) |
grupo = [[], []]
for p in range(0, 7):
n = int(input('Digite um valor: '))
if n % 2 == 0:
grupo[0].append(n)
if n % 2 == 1:
grupo[1].append(n)
print(f'A lista com numeros pares foi {sorted(grupo[0])}')
print(f'A lista com numeros impares foi {sorted(grupo[1])}') |
s = 0
n = int(input('Digite um numero para saber se ele é primo: '))
for x in range(1, n + 1):
if n % x == 0:
s += 1
if s == 2:
print('O numero {} é Primo'.format(n))
else:
print('O numero {} nao é primo'.format(n)) |
contador = 0
total = 0
res = ''
maior = 0
menor = 0
while res != "N":
n = int(input('Digite um valor: '))
res = str(input('Deseja continuar? [s/n] ')).strip().upper()[0]
contador += 1
total += n
if contador == 1:
maior = menor = n
else:
if n > maior:
maior = n
... |
something = input('Digite alguma coisa para ser avaliada: ')
print('O tipo primitivo desse valor é', type(something))
print('So tem espaco:', something.isspace())
print('É um numero: ', something.isnumeric())
print('É alfabetico: ', something.isalpha())
print('É alfanumerico:', something.isalnum())
print('Está maiscula... |
import random
computador = 0
user = int(input('Digite um numero inteiro e tente adivinhar o numero que o computador pensou de 0 a 5: '))
while computador != user:
computador = random.randint(0, 5)
user = int(input('Voce perdeu, digite novamente para tentar acertar!'))
print('Acertou voces pensaram no {}'.for... |
s = 0
c = 0
contador = 0
# caso queria tirar a subtracao 999 basta adicionar antes do while
# c = int(input('Digite um numero: [999 para parar] '))
while c != 999:
c = int(input('Digite um numero: [999 para parar] '))
contador+= 1
s+=c
print('O total de numeros digitados foi {}'.format(contador-1))
print(... |
reais = float(input('Quantos reais R$ voce tem na carteira: '))
dolar = reais / 3.27
print('Com R${:.2f} voce conseguirá comprar {:.2f} USD'.format(reais, dolar)) |
# Perceptron.py
import numpy as np
class Perceptron(object):
def __init__(self, no_of_inputs, threshold=100, learning_rate=0.01):
self.threshold = threshold
self.learning_rate = learning_rate
self.weights = np.zeros(no_of_inputs + 1)
self.errors = [0]
self.squareError= [0]
... |
from SecondSem.CG.Lab_03.src.Sorter import Sorter
import math
class GiftWrap2D:
def __init__(self, points):
self.length = len(points)
self.points = points
def getMinYPoint(self):
index = 0
minY = self.points[0][1]
minPoint = self.points[0]
for i in range(1, sel... |
import string
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
if not S:
return []
res = ['']
for i in S:
temp = []
for j in res:
if i in string.ascii_letters:
temp.append(j + i.upper())
... |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}\nAge: {self.age}"
def print(self):
print(self.__str__())
class Staff(Person):
def __init__(self, name, age, job_title, salary):
super()._... |
import sqlite3
connection = sqlite3.connect("../resources/dummy.db")
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS PERSON
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL);
''')
# cursor.execute("INSERT INTO PERSON ('ID', 'NAME', 'AGE') VALUES ('1', 'Jo... |
def divide(x, y):
try:
return x / y
except ZeroDivisionError:
print("cannot divide by zero")
except TypeError:
print("Incorrect type")
except:
pass
def open_file(file_path):
try:
f = open(file_path, "r")
except FileNotFoundError:
print(f"{file_pa... |
# -*- coding: utf-8 -*-
"""
nome: prog5.py
@author: auro
"""
#este programa converte milimetros em metros
x = float(input("digite um valor em milimetros: "))
#calculo
metros = x / 1000
print("o valor em metros eh: ", metros, "m") |
#
# CS6613 Artificial Intelligence
# Project 1 Mini-Checkers Game
# Shang-Hung Tsai
#
import tkinter
from CheckerGame import *
class BoardGUI():
def __init__(self, game):
# Initialize parameters
self.game = game
self.ROWS = 6
self.COLS = 6
self.WINDOW_WIDTH = 600
... |
def read_nums(filename):
with open(filename) as f:
content = f.readlines()
content = [line.strip() for line in content]
return content
def main():
nums = read_nums('./nums.txt')
carry = 0
total = ''
index = len(nums[0]) - 1
while index >= 0:
cur = carry % 10
carr... |
#! /usr/bin/python
import unittest
class TestBasicString(unittest.TestCase):
testString = "APRIL is the cruellest month, breeding"
def test_concat(self):
result = "Tonle " + "Sap"
self.assertEqual(result, "Tonle Sap")
def test_repeat(self):
result = "Ha" * 5 + "!"
self.a... |
#primer ejercicio
a = int(input('Ingrese el primer número entero : '))
b = int(input('Ingrese el segundo número entero : '))
def numeros (a,b):
if a > b :
print (f'{a} es el número mayor')
elif b > a :
print (f'{b} es el número mayor')
else:
print ('Los números ingresados son iguale... |
#Cree la clase Torta con atributos forma, sabor, altura, también tendrá una función donde muestre todos sus atributos
class Torta ():
def __init__ (self,formaIn, saborIn,alturaIn):
self.forma = formaIn
self.sabor = saborIn
self.altura = alturaIn
def mostrar_atributos(self):
print... |
#-----Numeroteclado-----#
preguntaNumero = "Ingrese un número entero o digite cero para finalizar y realizar la sumatoria : "
numeroIngresado = int(input(preguntaNumero))
suma = 0
while(numeroIngresado != 0) :
suma += numeroIngresado
numeroIngresado = int(input(preguntaNumero))
print(f"Este es el resultado de... |
#lista
def mostrarLista (lista):
for elemento in lista :
print (elemento)
listaEdades = [20,18,18,18,21,20,18,18]
mostrarLista (listaEdades)
#mayor, menor, promedio
listaD = [20000,30000,4000,2500,1000,7600]
mayor = max (listaD)
menor = min (listaD)
totalSuma = 0
for elemento in listaD :
totalSuma += ... |
import unittest
from user_file import User, Credentials
import pyperclip
class Test(unittest.TestCase):
'''
Test class that defines test cases for the user class
Args:
unittest.TestCase: TestCase class helping to create test cases
'''
def setUp(self):
'''
set up method to run b... |
"""
ハングマンゲーム(単語当てゲーム)
回答者が1文字ずつ文字を入力して、最終的に単語を当てる。
単語に含まれていない文字を入力した場合、変数stagesの絵を1パーツ毎表示する。
最終的に絵が全て表示されたら負け、絵が表示される前に単語を当てられたら勝ち。
word : 答える単語
wrong : 間違った回数
rletters : 答えを1文字ずつ分けたリスト。答えなければならない残りの文字を記憶させておく
bord : rlettersと同様のリスト。回答者に見せるヒント用
"""
import random
def hangman(word):
wrong = 0
stages = ["",... |
from selenium.webdriver.support.ui import Select
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(executable_path='C:/Users/user/PycharmProjects/selenium_python/driver/chromedriver.exe')
driver.get("https://fs2.formsite.com/meherpavan/form2/index.html?15377025... |
#assignment-1
'''
a = 'AbcdefghIjk'
b = list(a.lower())
print(b)
count = 0
for i in b:
if i =='a' or i == 'e' or i =='i' or i=='o' or i=='u':
print(b.index(i), i)
'''
a = 'HArsha PatnAIk'
b = list(a.lower())
print(b)
count_a, count_i = 0 , 0
for i in b:
if i =='a':
co... |
import numpy as np
from scipy import ndimage
import os
import random
import glob
def toOnehot(array, num_classes=10):
"""
Takes a 1 dimensional array and returns a 2 dimensional array of one-hots with the dimension 0 with the same size of input array and dimension 1 with the size of `num_of_classes`.
Inp... |
# Given a non-empty array of positive integers arr[]. Write a program to find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
# Example 1
# Input: arr[] = [1, 6, 11, 6]
# Output: true
# Explanation: The array can be partitioned as [6, 6] and [1, 11].
# Example ... |
# File with sample functions.
def sum(x, y): # sums up two numbers
""" Adds two numbers.
Returns the sum."""
return x + y
# Returns the product.
def mul(x, y): # multiplies two numbers
# z is a local variable
z = x * y
return z
def print_pretty(a):
print("The result is {:.3f}.".... |
# DWAYNE FRASER
############## Problem 4. Function Visualization ##############################
import math
import numpy as np
import matplotlib.pyplot as plt
# Defines Plot Function
def plot_function(fun_str, domain, ns):
# Computes x-list
interval = (domain[1] - domain[0]) / ns
xs = [... |
# TASK:
# Шоколадка имеет вид прямоугольника, разделенного на n×m долек. Шоколадку можно один
# раз разломить по прямой на две части. Определите, можно ли таким образом отломить от
# шоколадки часть, состоящую ровно из k долек. Программа получает на вход три числа: n, m, k
# и должна вывести YES или NO.
# SOLUTION:
im... |
# TASK:
# два цілих невід'ємних числа (0<=a1<=a2<=999999) - аргументи командного
# рядка.
# Результат роботи: кількість "щасливих квитків", чиї номери лежать на проміжку від a1 до
# a2 включно.
# SOLUTION:
import sys
a1 = int(sys.argv[1])
a2 = int(sys.argv[2])
# Initializing variables
input_str = ''
counter = 0
# I... |
class A():
def sum(self, a,b):
self.c = a+b
print (self.c)
class B():
def sum(self, a,b):
self.c = a-b
print (self.c)
class C(B,A):
def sum(self,a,b):
self.c = a*b
print (self.c)
obj1 = C()
obj1.sum(10,20)
|
#from collections import namedtuple
import collections
emp1 =collections.namedtuple("Learntek", 'name age empid', rename= False ) # creating own data type
list1 = ['shankar',28, 123456]
record1 = emp1._make(list1)
print (record1)
print (record1.name)
print (record1.age)
print (record1.empid) |
import re
p1 = "wit+h"
text = "Peace begin wittth with smile "
m1 = re.findall(p1, text)
print (m1)
print ("Total number of occurrence ", len(m1))
'''
if m1:
print (m1.group())
print ("start at ",m1.start())
print ("Ends at ", m1.end())
''' |
str1 = "Learning Python in Learntekeee"
i=0
for each in str1:
if "e" == each:
i= i+1
print ("e repeated %d times"%(i)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.