text
stringlengths 37
1.41M
|
---|
'''
Created on Feb 4, 2016
@author: sumkuma2
'''
class MyString():
def reverse(self,some_seq):
"""
Input: Sequence
output: Sequence:
reversed version
"""
return some_seq[::-1]
def is_palindrom(self,some_seq):
"""
@param some_seq: sequence of anything
@return: Boolean:
palindrome check of sequence passed
"""
return some_seq == self.reverse(some_seq)
#if __name__ == '__main__':
X = MyString()
string = "a barbie vanquished the knights of the round table by hitting them in the face"
print(X.reverse(string));
number='11011'
ispalindrom = X.is_palindrom(number);
if (ispalindrom == False):
print "Not a Palindrom"
else:
print "Palindrom"
|
def separate_categories(invoice_lines: dict):
"""
This function separates categories and counts their prices. Decimal euros are converted into integer cents.
:param invoice_lines: dictionary with invoice lines
:return: dictionary with separated categories
"""
categories = {}
for invoice in invoice_lines:
price = int(invoice['unit_price_net'].replace('.', '')) * invoice['quantity']
if invoice['category'] in categories:
categories[invoice['category']] += price
else:
categories[invoice['category']] = price
return categories
def prepare_payment_data(payments):
"""
This function converts decimal euros into integer cents in the list of payments.
:param payments: a list of raw payments
:return: a list of converted payments
"""
for payment in payments:
converted_amount = int(payment['amount'].replace('.', ''))
payment['amount'] = converted_amount
return payments
def distribute_amounts(available: int, categories: dict, distributed_by_categories: dict):
"""
This function distributes total amount into categories in proportion to their prices.
:param available: amount of available money from a payment
:param categories: a dict of categories with their prices
:param distributed_by_categories: a dict of distributed categories
:return: a list of proportionally distributed amounts
"""
data = []
total_price = sum(categories.values())
for category, price in categories.items():
distributed_amount = round(price / total_price * available)
# Check if sum of already distributed amount and current distributed amount does not exceeds the price
if distributed_by_categories[category] + distributed_amount >= price:
distributed_amount = price - distributed_by_categories[category]
distributed_by_categories[category] += distributed_amount
total_price -= price
available -= distributed_amount
data.append({
'category': category,
'net_amount': distributed_amount
})
return data, distributed_by_categories
def generate_bookkeeping_data(payments: list, categories: dict):
"""
This function generates bookkeeping data based on categories and payments. Integer cents are converted
into decimal euros.
:param payments: a list of payments
:param categories: a dict of categories and their prices
:return: a dict of bookkeeping data
"""
payment_data = []
# This dictionary represents how much money is already distributed to each category, it helps us not to pay more
# than the original price for the category
distributed_by_categories = {category: 0 for category in categories}
for payment in payments:
data = {'id': payment['id'], 'categorisations': []}
categorisations, distributed_by_categories = distribute_amounts(
payment['amount'], categories, distributed_by_categories
)
# Convert integer cents into decimal euros
for categorisation in categorisations:
data['categorisations'].append({
'category': categorisation['category'],
'net_amount': f'{categorisation["net_amount"] / 100:.2f}'
})
payment_data.append(data)
return payment_data
|
# -*- coding: utf-8 -*-
"""
Create 3 functions: multiply, add, divide for the calculator class
Each student should make their own branch and work on one of the functions in
the corresponding file.
"""
import multiply as ml
import addition as ad
import division as dv
class Calculator:
def __init__(self):
return None
def add(self, a, b):
return ad(a, b)
def multiply(self, a, b):
return ml(a, b)
|
class NodeData:
"""This class represents a node data of the graph with simple functions."""
def __init__(self, key, pos=None):
self.key = key
self.pos = pos
self.parent = 0
self.tag = 0
def __repr__(self) -> str:
return f"|Key: {self.key}|"
def __lt__(self, other):
return self.tag < other.tag
def __eq__(self, other):
return self.key == other.key and self.pos == other.pos
|
# Exemplo 1:
produtos = [1, 3, 1, 1, 2, 3]
# resultado = 4
# Os índices (0, 2), (0, 3), (1, 5), (2, 3) formam combinações.
# Exemplo 2:
# produtos = [1, 1, 2, 3]
# resultado = 1
# Os índices (0, 1) formam a única combinação.
def good_combinations(array):
size = len(array)
# result = []
# for x in range(size):
# for y in range(size):
# if array[x] == array[y] and y != x and y > x:
# result.append((x, y))
# return result
result = [(x, y) for x in range(size)
for y in range(size) if array[x] == array[y] and y > x]
return len(result)
print(good_combinations(produtos))
|
"""Perceba que temos uma coleção de valores
e operações que atuam sobre estes valores,
de acordo com o que foi definido pelo TAD."""
class Array:
def __init__(self):
self.data = []
def __len__(self):
# quando pedido o tamanho do array
# retorne o tamanho de data
return len(self.data)
def __str__(self):
# converte para string e exibe os valores de data
return str(self.data)
def get(self, index):
return self.data[index]
def set(self, index, value):
self.data.insert(index, value)
# vamos inicializar e preencher uma estrutura de dados array
array = Array()
array.insert(0, "Felipe")
array.insert(1, "Ana")
array.insert(2, "Shirley")
array.insert(3, "Miguel")
# para acessar um elemento do array, utilizamos seu índice
print(array.get(0)) # saída: Felipe
print(array.get(2)) # saída: Shirley
print("-----")
# podemos iterar sobre seus elementos da seguinte maneira
index = 0
# enquanto há elementos no array
while index < len(array):
# recupera o elemento através de um índice
print("Index:", index, ", Nome:", array.get(index))
index += 1
|
""" Exercício 5: Consulte a forma de se criar um
dicionário chamado de dict comprehension e crie
um dicionário que mapeia inteiros de 3 a 20 para
o seu dobro. Exemplo:
"""
result = {x: x*2 for x in range(3, 20)}
print(result)
|
import sys
print("Please insert the sequence: "+sys.argv[1])
strs = sys.argv[1].split(' ')
v = [int(num) for num in strs]
n = len(v)
# python way of defining a n-dimensional list initialized to 0
sub_sums = [0 for i in range(0, n)]
best = (0, 0)
best_sum = 0
for i in range(0, n):
sub_sums[i] = v[i]
best_end_index = i
# after this loop v[j] = (sum from k=i to j of v[k])
for j in range(i+1, n):
sub_sums[j] = sub_sums[j-1] + v[j]
if sub_sums[j] > sub_sums[best_end_index]:
best_end_index = j
if sub_sums[best_end_index] > best_sum:
best_sum = sub_sums[best_end_index]
best = (i, best_end_index)
print("Best with a sum of", best_sum, "is: (x%d,...,x%d)" % best)
|
import sys
print("$ python3 reversed.py")
print("Please insert n:", sys.argv[1])
n = int(sys.argv[1])
res = 0
i = 0
while n != 0:
res *= 10
res += n % 10
n //= 10
i += 1
print("Result:", res)
|
import sys
print("$ python3 shaker_sort.py")
print("Please insert the array:", sys.argv[1])
strs = sys.argv[1].split(' ')
v = [int(num) for num in strs]
def impl(start, end, step):
sorted = True
for i in range(start, end, step):
if v[i] > v[i+1]:
t = v[i]
v[i] = v[i+1]
v[i+1] = t
sorted = False
return sorted
begin = 0
end = len(v) - 1
while True:
if impl(begin, end, 1): break
if impl(end-1, begin-1, -1): break
end -= 1
begin += 1
print(v)
|
# Author - Shivam Kapoor
# This code is written as minimal as possible.
# Github - https://github.com/ConanKapoor/Elliptic_Curve_Implementation.git
# importing libraries
import matplotlib.pyplot as plt
import numpy as np
# Function to plot graph
def Plot_Graph(a,b):
print("\nThe Graph for given equation is : \n")
fig, ax = plt.subplots()
y, x = np.ogrid[-4:4:1000j, -2:5:1000j]
plt.contour(
x.ravel(), y.ravel(), y**2 - x**3 - a*x -b, [0])
plt.show()
|
#-*- encoding: utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def genLinkedList(l):
"""
genLinkedList([integers]) -> linkedlist
"""
if l==[]:
return None
else:
length=len(l)
if length==1:
return ListNode(l[0])
else:
head=ListNode(l[0])
h=head
for i in range(1,length):
h.next=ListNode(l[i])
h=h.next
return head
def printLinkedList(head):
s=[]
while head!=None:
s.append(head.val)
head=head.next
print s
|
import pygame
class Square:
def __init__(self, h, w):
self.h = h
self.w = w
def draw_square(surface):
pygame.draw.rect(surface, (255,255,255), (250, 250, 10,10))
def drawGrid(surface, n_squares, x_dim, y_dim):
delta_x = x_dim//n_squares
delta_y = y_dim//n_squares
x = 0
y = 0
for i in range(n_squares+1):
# horizontal line
pygame.draw.line(surface, (0, 255, 0), (0, y),(x_dim, y))
# vertical line
pygame.draw.line(surface, (0, 255, 0), (x, 0),(x, y_dim))
x += delta_x
y += delta_y
def main():
pygame.init()
window = pygame.display.set_mode((500,500))
pygame.display.set_caption("MySnake")
drawGrid(window, 10, 500, 500)
s = Square(10, 10)
s.draw_square(window)
pygame.display.update()
print("Works")
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
main()
|
n = int(input("Podaj ile liczb chcesz wprowadzić: "))
wynik = 0;
for i in range(1, n + 1):
wynik = wynik + float(input("Podaj " + str(i) + " liczbe: "))
print("Wynik wynosi", wynik)
# print(float(input("podaj liczbe")) + float(input("podaj liczbe")))
|
should_be_true_graph = {
"s": ["w"],
"w": ["t", "y"],
"y": ["z", "x"],
"x": ["s"],
"z": ["t"],
"t": [], # dest
}
should_be_false = {
"a": ["b"],
"b": ["c"],
"c": ["a"],
}
countmap = {}
path = []
def three_walk(src, dst, length, g):
if src == dst:
return length % 3 == 0
if src in countmap:
countmap[src] += 1
else:
countmap[src] = 0
if countmap[src] == 3:
return False
for nxt in g[src]:
if three_walk(nxt, dst, length + 1, g):
path.append(src)
return True
return False
path.append("t")
print(three_walk("s", "t", 0, should_be_true_graph))
path.reverse()
print(path)
countmap = {}
path.clear()
print(three_walk("a", "b", 0, should_be_false))
path.reverse()
print(path)
|
def prime(n):
if n == 2:
return n
elif n>1:
for i in range(n):
if n%2!=0:
return n
else:
pass
|
import re
namestring = False
while namestring is False:
name = input("Hey person, what is your name? ")
x = re.search('[0-9]', name)
if x:
namestring = False
else:
namestring = True
print(name)
|
TICKET_PRICE = 10
SERVICE_CHARGE = 2
tickets_remaining = 100
def calculate_price(number_of_tickets):
return (TICKET_PRICE * number_of_tickets) + SERVICE_CHARGE
while tickets_remaining > 0:
print("There are {} tickets remaining".format(tickets_remaining))
name = input("What's your name? ")
try:
number_of_tickets = int(input("Hello {}. How many tickets do you need? ".format(name)))
if number_of_tickets > tickets_remaining:
raise ValueError("Sorry, don't have this quantity available. Please chose a different quantity".format(tickets_remaining))
elif number_of_tickets < 1:
raise ValueError("The mininum amount for purchase is 1")
except ValueError as err:
print("That's not a valid value. ({}). Please try again.".format(err))
else:
amount_due = calculate_price(number_of_tickets)
order_confirmed = input("Is this information correct? (Y/N)")
if order_confirmed.lower() == "y":
print("Thanks for shopping with us!")
print("You are buying {} tickets and your total is ${}".format(number_of_tickets, amount_due))
tickets_remaining -= number_of_tickets
else:
print("Thank you anyway, {}.".format(name))
print("Oh no, the tickets are sold out!") |
frase = str(input("Digite aqui uma frase:")).lower().replace(" ", "")
if frase == frase[::-1]:
print(" {} é um palíndromo".format(frase))
else:
print(" {} Não é um palíndromo".format(frase)) |
from random import randint
numeros = []
for i in range(5):
numeros.append(randint(0, 100))
tupla = (numeros[0], numeros[1], numeros[2], numeros[3], numeros[4])
print(tupla)
maior = menor = tupla[0]
for i in range(1, len(tupla)):
if tupla[i] > maior:
maior = tupla[i]
if tupla[i] < menor:
menor = tupla[i]
print(f"O maior valor da tupla eh {maior}")
print(f"O menor valor da tupla eh {menor}") |
def triangulo(a, b, c):
if a*b*c <= 0:
return False
if a <= abs(b - c) or a > (b+c):
return False
return True
def tipoTriangulo(a, b, c):
if a == b and b == c:
return 0
if a == b or a == c or b == c:
return 1
return 2
tipos = ["Equilatero", "Isosceles", "Escaleno"]
a = int(input("Digite o valor do lado a: "))
b = int(input("Digite o valor do lado b: "))
c = int(input("Digite o valor do lado c: "))
if triangulo(a, b, c):
print("Forma um triangulo do tipo {}".format(tipos[tipoTriangulo(a, b, c)]))
else:
print("{}Nao forma triangulo{}".format("\033[31m", "\033[m")) |
from time import sleep
text = {
"fecha":"\033[m",
"branco":"\033[30m",
"vermelho":"\033[31m",
"verde":"\033[32m",
"amarelo":"\033[33m",
"azul":"\033[34m",
"roxo": "\033[35m",
"ciano": "\033[36m",
"cinza": "\033[37m",
}
back = {
"fecha":"\033[m",
"branco":"\033[40m",
"vermelho":"\033[41m",
"verde":"\033[42m",
"amarelo":"\033[43m",
"azul":"\033[44m",
"roxo": "\033[45m",
"ciano": "\033[46m",
"cinza": "\033[47m",
}
style = {
"fecha":"\033[m",
"negrito":"\033[1",
"italico":"\033[4",
"invertido":"\033[7",
}
def aprovaEmprestimo(valor, tempo, salario):
if salario*0.3 >= (valor / (tempo*12)):
return True
return False
entrada = input("Digite o valor da casa, seu salario e em quantos anos pretende pagar: ")
divisao = entrada.split(" ")
casa = float(divisao[0])
salario = float(divisao[1])
anos = int(divisao[2])
prestacao = casa / (anos*12)
print("Para pagar uma casa no valor de R${:.2f} em {} terá prestação no valor de {:.2f}".format(casa, anos, prestacao))
print("{}{}{}".format(text["amarelo"], "-=-" * 20, text["fecha"]))
print("{}{:^60}{}".format(text["amarelo"], "ANALISANDO A SITUAÇÃO", text["fecha"]))
print("{}{}{}".format(text["amarelo"], "-=-" * 20, text["fecha"]))
sleep(3)
if aprovaEmprestimo(casa, anos, salario):
print("{}Parabens! Emprestimo aprovado{}".format(text["verde"], text["fecha"]))
else:
print("{}Emprestimo Negado{}".format(text["vermelho"], text["fecha"]))
|
inicio = 1
fim = 500
primeiro = inicio + 3 - (inicio%3)
soma = 0
for i in range(primeiro, fim+1, 6):
soma += i
print(soma)
|
"""
026
Faça um programa que leia uma frase pelo teclado e mostre:
Quantas vezes aparece a letra "a"
Em que posição ela aparece a primeira vez
Em que posição ela aparece a última vez
"""
def conta(ref, frase):
return frase.lower().count(ref.lower())
def primeraOcorrencia(ref,frase):
return frase.lower().find(ref)
def ultimaOcorrencia(ref, frase):
x = -1
for i in range(len(frase)):
if frase[i].lower() == ref:
x = i
return x
frase = str(input("Digite uma frase: ")).strip()
ref = "a"
contador = conta(ref, frase)
print("A frase possui {} letra(s) {}".format(contador, ref))
ocorrencia = primeraOcorrencia(ref, frase)
ultima = ultimaOcorrencia(ref, frase)
if (ocorrencia >= 0):
print("A primeira ocorrência da letra {} foi na posicao {}".format(ref, ocorrencia+1))
print("A ultima ocorrência da letra {} foi na posicao {}".format(ref, ultima + 1))
else:
print("A letra {} nao aparece na frase \"{}\"".format(ref, frase))
|
nome = input("Informe seu nome: ")
#20 alinhamento esquerda, centralizado e direta
print("Prazer em te conhecer, {:<20}!".format(nome)) #Alinhado a esquerda
print("Prazer em te conhecer, {:^20}!".format(nome)) #Centralizado
print("Prazer em te conhecer, {:>20}!".format(nome)) #Alinha a direita
print("Prazer em te conhecer, {:=^20}!".format(nome))
n1 = int(input("Digite o primeiro numero: "))
n2 = int(input("Digite o segundo numero: "))
soma = n1+n2
produto = n1*n2
divisao = n1/n2
divisaoInteira = n1 // n2
potencia = n1 ** n2
print("A soma eh {}, o produto eh {} e a divisao eh {}".format(soma, produto, divisao), end=" ")
print("Divisoa inteira {} e potencia {}".format(divisaoInteira, potencia)) |
personagens = ("Eren", "Mikasa", "Armin", "Levi", "Erwin", "Zeke",
"Ichigo", "Orihime", "Yhwach", "Byakuya", "Renji", "Rukia",
"Sakamoto", "Himiko", "Kira", "Oda",
"Kirito", "Asuna", "Shino",
"Elesis", "Lire", "Arme", "Lass", "Ryan", "Ronan", "Amy")
vogais = "aeiou"
for nome in personagens:
print(f"O nome {nome} possui as seguintes vogais: ", end="")
for i in range(len(nome)):
if nome[i].lower() in vogais:
print(nome[i], end=" ")
print("")
|
"""
066
Crie um progra que leia vários numeros inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999.
No final, mostre quantos numeros foram digitados e qual foi a soma entre eles (desocnsiderando 999)
"""
contador = 0
soma = 0
while True:
n = int(input("Digite um numero: "))
if n == 999:
break
soma += n
contador += 1
if contador == 0:
print("Nao houve valores processados")
elif contador == 1:
print("Soh teve um valor lido que foi {}".format(soma))
else:
print("A soma dos {} valores lidos eh igual a {}".format(contador, soma))
|
"""
071
Crie um programa que simule o funcionamento de um caixa eletrônico.
no início, pergunte ao usuário qual será o valor a ser sacado
e o programa vai informar quantas cédulas de cada valor serão entregues.
obs: considere que o caixa possua cédulas de 50 20 10 e 1
"""
def sacar(valorSaque, cedulasDisponiveis):
for i in range(len(cedulas)):
notas = valorSaque // cedulasDisponiveis[i]
print(f"{notas} notas de R${cedulasDisponiveis[i]}")
valorSaque = valorSaque % cedulas[i]
cedulas = [50, 20, 10, 1]
saque = int(input("Digite o valor que deseja sacar: "))
sacar(saque, cedulas) |
def escreve(string):
tam = len(string)
tam += 2
linha = "-"*(tam)
print(linha)
print(f" {string}")
print(linha)
string = str(input("Digite sua frase: "))
escreve(string) |
"""
Faça um programa que leia algo pelo teclado e mostre na tela o
seu tipo primitivo e todas as informações possível sobre ele
"""
algo = input("Digite algo: ")
print("Tipo do dado lido: {}".format(type(algo)))
print("Eh numero: {}".format(algo.isnumeric()))
print("Eh alfabetico: {}".format(algo.isalpha()))
print("Eh alfanumerico: {}".format(algo.isalnum()))
print("Eh digito: {}".format(algo.isdigit()))
print("Eh minusculo: {}".format(algo.islower()))
print("Eh maiusculo: {}".format(algo.isupper()))
print("Eh capitalizada: {}".format(algo.istitle())) |
num=int(input())
#num1=int(input())
if(num<0):
print ("Negative")
elif(num==0):
print ("Zero")
else:
print ("Positive")
|
file = open("input.txt", "r")
groups = [string.split() for string in file.read().split(sep="\n\n")]
total = 0
total2 = 0
for group in groups:
# Create a dict of all questions and start the count at zero
question_dict = {}
for i in range(26):
question_dict[chr(ord('a')+i)] = 0
# For each person's response, add one to that question's count
for person in group:
for yes in person:
question_dict[yes] += 1
# Check the criteria for part 1 and 2 of the prompt
for q, count in question_dict.items():
if count != 0: # If anyone answered yes
total += 1
if count == len(group): # If ALL answered yes
total2 += 1
print(f"Part1: {total}")
print(f"Part2: {total2}")
|
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
# In this example, I walk through how to use sklearn to classify users into male or female
# based on their user description.
# First, we need to get some tweets in JSON format.
# Create a tweets.json file with something like:
# twitter-curl --query "track=obama" > tweets.json
# This will query twitter for tweets containing the word obama.
# Now, we'll parse that file into a list of (name, description) tuples.
import json
import io
# open the json file
fp = io.open('tweets.json', mode='rt', encoding='utf8')
# read the names and description fields from each tweet.
data = []
for line in fp:
js = json.loads(line) # parse into a JSON object.
name = js['user']['name']
description = js['user']['description']
if name and description: # if fields aren't blank
data.append((name.lower(), description.lower()))
print 'read', len(data), 'users'
print 'example:', data[0]
# <codecell>
# Now, we need to label them as male or female.
# To do that, we get the top 500 male/female names from census
import requests # This is a very handy library for html requests.
males = requests.get('http://www.census.gov/genealogy/www/data/1990surnames/dist.male.first').text.split('\n')
males = [m.split()[0].lower() for m in males[:500]] # lower case and take top 500
print 'first male is', males[0]
females = requests.get('http://www.census.gov/genealogy/www/data/1990surnames/dist.female.first').text.split('\n')
females = [f.split()[0].lower() for f in females[:500]] # lower case and take top 500
print 'first female is', females[0]
# Remove ambiguous names (those that appear on both lists)
# Note that the plus operator is overloaded to mean concatentation for lists.
ambiguous = [f for f in females + males if f in males and f in females]
print 'ambiguous is', ambiguous[0]
males = [m for m in males if m not in ambiguous]
females = [f for f in females if f not in ambiguous]
print 'got', len(males), 'males and', len(females), 'females'
# <codecell>
# sort male, female users
male_users = [d for d in data if len(d[0].split()) > 0 and d[0].split()[0] in males]
print len(male_users), 'males'
print male_users[0]
female_users = [d for d in data if len(d[0].split()) > 0 and d[0].split()[0] in females]
print len(female_users), 'females'
print female_users[0]
# <codecell>
# Make target vector. Female=1, Male=0
import numpy as np
y = np.array([0.] * len(male_users) + [1.] * len(female_users))
data = [d[1] for d in male_users + female_users]
print 'first label=', y[0]
print 'first description=', data[0]
# <codecell>
# Convert descriptions into feature vectors.
from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer()
X = vec.fit_transform(data)
print data[0],'\nis transformed into the sparse vector\n', X[0]
print 'the word THE is mapped to index', vec.vocabulary_['the']
print 'there are', len(vec.vocabulary_), 'unique features'
# <codecell>
# Compute cross validation accuracy
from sklearn import cross_validation
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression()
print 'avg accuracy=%.3f' % np.average(cross_validation.cross_val_score(clf, X, y, cv=5, scoring='accuracy'))
# <codecell>
# Try Naive Bayes
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB()
print 'avg accuracy=%.3f' % np.average(cross_validation.cross_val_score(clf, X, y, cv=5, scoring='accuracy'))
# <codecell>
# Try adding bigrams
vec = CountVectorizer(ngram_range=(1,2))
X = vec.fit_transform(data)
print 'there are', len(vec.vocabulary_), 'unique features'
print 'ten feature examples:', vec.vocabulary_.keys()[:10]
from sklearn import cross_validation
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression()
print 'avg accuracy with bigrams=%.3f' % np.average(cross_validation.cross_val_score(clf, X, y, cv=5, scoring='accuracy'))
# <codecell>
# Print top feature weights for female
clf = LogisticRegression()
clf.fit(X, y) # fit on all data
top_indices = clf.coef_[0].argsort()[::-1] # sort in decreasing order
# reverse the alphabet to map from idx->word
vocab_r = dict((idx, word) for word, idx in vec.vocabulary_.iteritems())
print 'female words:\n', '\n'.join(['%s=%.3f' % (vocab_r[idx], clf.coef_[0][idx]) for idx in top_indices[:20]])
top_indices = clf.coef_[0].argsort() # sort in increasing order
print '\n\nmale words:\n', '\n'.join(['%s=%.3f' % (vocab_r[idx], clf.coef_[0][idx]) for idx in top_indices[:20]])
# <codecell>
# Use PCA to reduce the dimensionality of X to only 2 dimensions,
# then compute cross-validation accuracy of resulting data X2.
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
X2 = pca.fit_transform(X.toarray())
print 'first document with reduced representation'
print X2[0]
dim1 = pca.components_[0]
print 'first PCA dimension (eigenvector):', dim1
top_indices = dim1.argsort()[::-1]
print 'top words of first dimension:\n', '\n'.join(['%s=%.3f' % (vocab_r[idx], dim1[idx]) for idx in top_indices[:20]])
dim2 = pca.components_[1]
print 'second PCA dimension (eigenvector):', dim2
top_indices = dim2.argsort()[::-1]
print 'top words of second dimension:\n', '\n'.join(['%s=%.3f' % (vocab_r[idx], dim2[idx]) for idx in top_indices[:20]])
print 'avg accuracy using only 2 dimensions=%.3f' % np.average(cross_validation.cross_val_score(clf, X2, y, cv=5, scoring='accuracy'))
# <codecell>
|
from __future__ import print_function
import tensorflow as tf
import numpy as np
# -------- Getting the dataset --------
# Functions for downloading and reading MNIST data
from tensorflow.examples.tutorials.mnist import input_data
# Load the training and test data into constants
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# Displaying the first image
import matplotlib.pyplot as plt
first_image = np.array(mnist.train.images[0], dtype='float')
pixels = first_image.reshape((28, 28))
plt.imshow(pixels, cmap='gray')
plt.colorbar()
plt.show()
# -------- Defining the model IO --------
# Parameters
learning_rate = 0.1
num_steps = 500
batch_size = 128
display_step = 100
# Network Parameters
n_hidden_1 = 256 # 1st layer number of neurons
n_hidden_2 = 256 # 2nd layer number of neurons
num_input = 784 # MNIST data input (img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)
# tf Graph inputs
X_feed = tf.placeholder("float", [None, num_input])
Y_feed = tf.placeholder("float", [None, num_classes])
# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([num_classes]))
}
# -------- Creating the model --------
# Hidden fully connected layer with 256 neurons
layer_1 = tf.add(tf.matmul(X_feed, weights['h1']), biases['b1'])
# Hidden fully connected layer with 256 neurons
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
# Output fully connected layer with a neuron for each class
logits = tf.matmul(layer_2, weights['out']) + biases['out']
prediction = tf.nn.softmax(logits)
# -------- Defining the loss function --------
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y_feed))
# -------- Defining the optimization algorithm --------
train_optim = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
# -------- Evaluating --------
# Vector of True/False
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y_feed, 1))
# Mean (float32)correct_pred
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Global variable initialization of the default graph
init = tf.global_variables_initializer()
# -------- Training the model --------
with tf.Session() as sess:
# Run the initializer
sess.run(init)
for step in range(1, num_steps+1):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# Run optimization op (backprop)
sess.run(train_optim, feed_dict={X_feed: batch_x, Y_feed: batch_y})
if step % display_step == 0 or step == 1:
# Calculate batch loss and accuracy
loss_train, acc_train = sess.run([loss, accuracy], feed_dict={ X_feed: batch_x,
Y_feed: batch_y})
print("Step " + str(step) + ", Minibatch Loss= " + \
"{:.4f}".format(loss_train) + ", Training Accuracy= " + \
"{:.3f}".format(acc_train))
print("Optimization Finished!")
# -------- Testing the trained model --------
# Calculate accuracy for MNIST test images
print("Testing Accuracy:", \
sess.run(accuracy, feed_dict={ X_feed: mnist.test.images,
Y_feed: mnist.test.labels}))
"""
- MNIST info:
-------------
http://yann.lecun.com/exdb/mnist/
- tf.reduce_mean:
-----------------
Computes the mean of elements across dimensions of a tensor.
- Loss: softmax_cross_entropy_with_logits (tf.nn):
--------------------------------------------------
Softmax: generalization of logistic regression used for multi-class classification
Cross entropy: Quantify the difference between two probability distributions
Tensorflow's logit is defined as the output of a neuron without applying activation function.
- AdamOptimizer class (tf.train):
----------------------------------
Optimizer that implements the Adam algorithm.
"minimize" method:
Adds operations to minimize loss by updating var_list.
- tf.equal:
-----------
Returns the truth value of (x == y) element-wise.
- tf.argmax:
------------
Returns the index with the largest value across axes of a tensor.
- mnist.train.next_batch(batch_size):
-------------------------------------
Returns a tuple of two arrays, where the first represents a batch of
batch_size MNIST images, and the second represents a batch of batch-size labels
corresponding to those images.
"""
|
"""
Goal : Choose a random word from a given dictionary
"""
# Importing the required libraries
import random
import pandas as pd
def get_a_word():
"""
A function to read the words, also select a random word, return the board and the word.
return <[char, char...], string>
"""
words = pd.read_csv('words.txt', sep='\n', header=None).iloc[:, 0].tolist()
word = random.choice(words)
blank = ['_'] * len(word)
return (blank, word)
|
__author__ = 'coty'
from math import pow
def calc_amortization(rate, P, n):
"""
Method to calculate amortization given rate, principal, and terms remaining.
"""
# calc monthly interest rate
# doing this funky conversion stuff to drop off the remaining digits instead of round up.
i = float(str(rate / 12)[:10])
# calc amortization for a single month
amort = round(((i * P * pow((1 + i), n)) / (pow((1 + i), n) - 1)), 2)
# calc monthly interest
mi = round((P * i), 2)
# calc monthly principal portion
mp = round((amort - mi), 2)
# return array of amount/interest/principal/monthly_rate
return {"amount": amort, "interest": mi, "principal": mp, "monthly_rate": i}
|
import random
import logging
logger = logging.getLogger(__name__)
class Board:
def __init__(self, max_row=1, max_column=1):
assert max_row >= 1, f"Max row must be 1 or higher"
self.max_row = max_row
assert max_column >= 1, f"Max column must be 1 or higher"
self.max_column = max_column
self._board = [[False for c in range(self.max_column)] for r in range(self.max_row)]
def get(self, row=0, column=0):
return self._board[row % self.max_row][column % self.max_column]
def set(self, row=0, column=0, state=True):
self._board[row % self.max_row][column % self.max_column] = state
def __str__(self):
result = "-{:}-\n".format("-"*self.max_column)
for r in range(self.max_row):
result += "|"
for c in range(self.max_column):
result += "X" if self.get(r, c) else " "
result += "|\n"
result += "-{:}-".format("-"*self.max_column)
return result
def get_living_neighbours(self, row, column):
# Nested for loops will also count cell(row, column), account for it
living_neighbours = -1 if self.get(row, column) else 0
for r in range(row-1, row+2):
for c in range(column-1, column+2):
if self.get(r, c):
living_neighbours += 1
return living_neighbours
class BoardPair:
def __init__(self, max_row=1, max_column=1):
assert max_row >= 1, f"Max row must be 1 or higher"
self.max_row = max_row
assert max_column >= 1, f"Max column must be 1 or higher"
self.max_column = max_column
self._boards = (Board(max_row, max_column), Board(max_row, max_column))
self._active_board = 0
def get_active_board(self):
return self._boards[self._active_board]
def get_next_board(self):
return self._boards[(self._active_board+1) % 2]
def get(self, row=0, column=0):
return self.get_active_board().get(row, column)
def set(self, row=0, column=0, state=True):
self.get_active_board().set(row, column, state)
def __str__(self):
result = 'Active\n'
result += str(self.get_active_board())
result += '\nNext\n'
result += str(self.get_next_board())
return result
def flip(self):
self._active_board = (self._active_board+1) % 2
def set_glider(row, column, board):
board.set(row, column)
board.set(row+1, column+1)
board.set(row+1, column+2)
board.set(row+2, column)
board.set(row+2, column+1)
def set_random(board):
for r in range(board.max_row):
for c in range(board.max_column):
if random.randint(0, 1):
board.set(r, c)
|
person1 = {
'first_name': 'Kirk',
'last_name': 'Tolliver',
'age': '31',
'city': 'Chicago',
}
person2 = {
'first_name': 'Greg',
'last_name': 'Migos',
'age': '76',
'city': 'Mississippi',
}
person3 = {
'first_name': 'David',
'last_name': 'Banner',
'age': '45',
'city': 'Lousiana',
}
people = [person1,person2,person3]
for p in people:
print(p)
#
#print('You are ' + person['first_name'])
#print('Your last name is ' + person['last_name'])
#print('You are ' + person['age'])
#print('You live in ' + person['city'])
#
|
import time
class Restaurant():
""" A simple Restaurant class"""
def __init__(self,r_name, r_cuisine):
""" Initialize restaurantaurant instances"""
self.r_name = r_name
self.r_cuisine = r_cuisine
self.number_served = 0
def describe_restaurant(self):
print(self.r_name + ' ' + self.r_cuisine)
def open_restaurant(self):
print(time.ctime())
print(self.r_name + " is now opened. ")
def set_number_served(self, number_served):
print(time.ctime())
self.number_served = int(number_served)
print(" # serverd: " + str(self.number_served))
def incr_num_served(self,inc_num):
self.number_served += inc_num
def show_served(self):
print(time.ctime())
print("Total Served: " + str(self.number_served))
class IceCreamStand(Restaurant):
def __init__(self,r_name,r_cuisine="icecream"):
super().__init__(r_name,r_cuisine)
self.flavors = []
def show_flavors(self):
for f in self.flavors:
print("flavors: " + f)
my_restaurant = Restaurant("Portillos","Italian Beef")
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
my_restaurant.set_number_served(6)
my_restaurant.incr_num_served(4)
my_restaurant.show_served()
print(my_restaurant.r_name)
print(my_restaurant.r_cuisine)
ice = IceCreamStand("Luigis")
ice.flavors = ["strawberry","watermelon"," chocolate","vanilla"]
ice.describe_restaurant()
ice.show_flavors()
|
pizzas = ["Cheese", "Suasage","Peperoni", "Olives", "Jalepeno"]
""" This is teext for git hub """
for pizza in pizzas:
print("I have "+ pizza +" Pizzas.")
print("I Love Pizza!")
freinds_pizza = pizzas[:]
freinds_pizza.append("Macaroni")
my_pizzas = [pie for pie in pizzas]
print("My favorite pizza is " + str(my_pizzas))
friends = [pie for pie in freinds_pizza]
print("My friends favorite pizza is " + str(friends) )
|
rental_car = input("Enter a car you would like to drive: ")
print("Let me see if we have a " + rental_car )
|
""" For loop inside of a list prints a list"""
cubes = [num**3 for num in range(1,11)]
print(cubes)
|
""" A class that displays characteristics of a Restaurant. """
import time
class Restaurant():
""" A simple Restaurant class"""
def __init__(self,name, cuisine):
""" Initialize restaurantaurant instances"""
self.name = name
self.cuisine = cuisine
self.number_served = 0
def describe_restaurant(self):
print(self.name + ' ' + self.cuisine)
def open_restaurant(self):
print(time.ctime())
print(self.name + " is now opened. ")
def set_number_served(self, number_served):
self.number_served = int(number_served)
print(" # serverd: " + str(self.number_served))
def incr_num_served(self,inc_num):
self.number_served += inc_num
def show_served(self):
print(time.ctime())
print("Total Served: " + str(self.number_served))
class IceCreamStand(Restaurant):
def __init__(self,name,cuisine="icecream"):
super().__init__(name,cuisine)
self.flavors =[]
def show_flavors(self):
for flavor in self.flavors:
print("- " + flavor)
|
#! /usr/bin/python
# Exercise No. 4
# File Name: extraCredit.py
# Programmer: Chris Adkins
# Date: Feb. 11, 2020
#
# Problem Statement: This program takes two numbers and divides them outputting using whole numbers and remainders.
#
# Overall Plan:
# 1. Define the numerator and denominator using user input.
# 2. define the result as the integer division of the two numbers.
# 3. define the remainder as numerator % denominator.
# 4. Print the result to the user.
#
# Import the necessary python libraries
# For this example none are needed
def main():
numerator = eval(input("Enter the numerator: "))
denominator = eval(input("Enter the denominator: "))
result = numerator // denominator
remainder = numerator % denominator
print(result, "R", remainder)
main()
|
# Exercise No. 1
# File Name: hw7project1.py
# Programmer: Chris Adkins
# Date: Mar. 9, 2020
#
# Problem Statement: This program takes a number between 0 and 100 and returns the proper letter grade
# in accordance with the CS 138 grading scale.
#
# Overall Plan:
# 1. Create a function to receive input from the user.
# 2. Use the user's input for the second function, numToGrade()
# 3. NumToGrade will be a series of if-else statements that check the input against the grade scale.
# 4. Depending on the user input, print a letter grade to the user.
#
# Import the necessary python libraries.
# None needed.
def getInput(): # Function to get input from our user.
percentage = eval(input("What percentage of the points did you get? "))
return percentage # Returning whatever the user typed in.
def numToGrade(num):
if (num < 60): # If we have a number that is less than 60.
print("F") # Any number under 60 is an F, so we print f.
elif (num < 70):
print("D")
elif (num < 80):
print("C")
elif (num < 90):
print("B")
elif (num <= 100): # If the number is less than, or equal to 100.
print("A")
else: # This point is only reached if the user enters a number over 100.
print("Invalid Input")
def main():
numToGrade(getInput()) # Calling our numToGrade function with getInput() as the argument.
main() |
#! /usr/bin/python
# Exercise No. 1
# File Name: hw2project1.py
# Programmer: Chris Adkins
# Date: Feb. 4, 2020
#
# Problem Statement: Modify the convert.py program to have an introduction.
#
#
# Overall Plan:
# 1. add a print statement to the beginning of the program.
#
# Import the necessary python libraries
# For this example none are needed
def main():
print("This program takes a celsius temperature given by the user and converts that number to the equivalent "
"fahrenheit temperature.")
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit.")
main()
|
#!/usr/bin/env python
## Script to obfuscate given email address
##
import re
def obfuscate_id(email_id):
ret_list = []
components = re.split(r'(\.|\@)',email_id)
for ii in components:
if ii=='@':
ret_list.append("at")
elif ii==".":
ret_list.append("(dot)")
else:
ret_list.append(ii)
return " ".join(ret_list)
def main():
obfuscated_id = obfuscate_id("[email protected]")
print obfuscated_id
if __name__ == "__main__":
main()
|
#!/usr/bin/python
import sys
## Kaprekar's number 6174
def high_to_low(n):
n_as_str=str(n)
slist = sorted(n_as_str)
slist.reverse()
sdigit_str = ''.join(slist)
return int(sdigit_str)
def low_to_high(n):
n_as_str=str(n)
slist = sorted(n_as_str)
sdigit_str = ''.join(slist)
return int(sdigit_str)
# main
def main():
if len(sys.argv)!=2:
print "USAGE: kaprekarno.py <4-digit-number>"
sys.exit(1)
n=int(sys.argv[1])
if (n<1000) or (n>9999):
print "Digit has to be between 1000 and 9999 .."
exit(1)
KNUM=6174
print "You started with initial number = " + str(n)
while(n!=KNUM):
a=high_to_low(n)
print "high_to_low: " + str(a)
b=low_to_high(n)
print "low_to_high: " + str(b)
n=a-b
if(n<=0):
print "digits should be unique, please try again"
exit(1)
print "intermediate number is: " + str(n)
print "We have hit kaprekars number: " + str(n)
main()
|
#!/usr/bin/env python3
nums1 = [1, 2, 3, 4, 4, 5] # expect true
nums2 = [7, 6, 3] # expect true
nums3 = [8, 4, 6] # expect false
# Returns True if list is sorted in ascending order
# False otherwise
def mono_incr(mylist):
sorted_ascending=True
for index in range(len(mylist)-1):
if mylist[index]>mylist[index+1]:
sorted_ascending=False
return sorted_ascending
# Returns True if list is sorted in descending order
# False otherwise
def mono_decr(mylist):
sorted_descending=True
for index in range(len(mylist)-1):
if mylist[index]<mylist[index+1]:
sorted_descending=False
return sorted_descending
# Returns True if list is sorted in either ascending or descending order
# False otherwise (not sorted at all)
def mono_incr_or_decr(mylist):
return mono_incr(mylist) or mono_decr(mylist)
# main
print(nums1)
print(mono_incr_or_decr(nums1)) # True
print()
print(nums2)
print(mono_incr_or_decr(nums2)) # True
print()
print(nums3)
print(mono_incr_or_decr(nums3)) # False
print()
|
#!/usr/bin/env python
# Script to create Hash of Hash
# after reading a file containing
# 3 fields per row
import sys
filename = sys.argv[1]
f = open (filename, "r")
# HashOfHash = { a => { c => d } }
HashOfHash={}
for line in f.readlines():
if len(line) <=0:
continue
col1,col2,col3=line.rstrip('\n').split()
# First create inner hash
InnerHash={}
InnerHash[col2]=col3
# Now create outer hash
HashOfHash[col1]=InnerHash
# Print the hash we constructed
print HashOfHash
|
#!/usr/bin/env python3
import typing
# 3.9 and above supports typing
def fact_with_type(n: int) -> int:
if n<=0:
return 1
else:
return n*fact_with_type(n-1)
# main
print(fact_with_type(10))
try:
print(fact_with_type("10.0"))
except TypeError as e:
print("MyError: This indicates that type is properly handled")
print(e)
|
from datetime import datetime
from implementations.code_df.utils import read_json_file
from implementations.code_df.issue_github import IssueGitHub
class IssuesNewGitHub(IssueGitHub):
"""
Class for Issues New
"""
def compute(self):
"""
Compute the number of new issues in the Perceval data.
:returns new_issues: the number of issues created
"""
new_issues = len(self.df.index)
return new_issues
def _agg(self, df, period):
"""
Perform an aggregation operation on a DataFrame to find
the number of issues created in a every interval of the
period specified in the time_series method, like 'M', 'W',etc.
It computes the count of the 'category' column of the
DataFrame.
:param df: a pandas DataFrame on which the aggregation will be
applied.
:param period: A string which can be any one of the pandas time
series rules:
'W': week
'M': month
'D': day
:returns df: The aggregated dataframe, where aggregations have
been performed on the "category" column.
"""
df = df.resample(period)['category'].agg(['count'])
return df
def _get_params(self):
"""
Return parameters for creating a timeseries plot
:returns: A dictionary with axes to plot, a title
and if use_index should be true when creating
the plot.
"""
title = "Trends in Issues Opened"
x = None
y = 'count'
use_index = True
return {'x': x, 'y': y, 'title': title, 'use_index': use_index}
def __str__(self):
return "Issues New"
if __name__ == "__main__":
date_since = datetime.strptime("2018-09-07", "%Y-%m-%d")
items = read_json_file('../issues_events.json')
# the GitHub API considers all pull requests to be issues. Any
# pull request represented as an issue has a 'pull_request'
# attribute, which is used to filter them out from the issue
# data.
items = [item for item in items if 'pull_request' not in item['data']]
# total new issues
new_issues = IssuesNewGitHub(items, reopen_as_new=False)
print("The total number of new issues is {:.2f}"
.format(new_issues.compute()))
# new issues created after a certain date
new_issues = IssuesNewGitHub(items, (date_since, None), reopen_as_new=True)
print("The number of issues created after 2018-09-07, considering reopened issues"
" as new, is {:.2f}"
.format(new_issues.compute()))
# time-series for issues created after a certain date
print("The changes in the number of issues created on a monthly basis: ")
print(new_issues.time_series('M'))
|
from datetime import date
print('Hello Patient !')
print('* ' * 10)
name = input("Name of the patient : ")
birth_year = input("Birth year the patient : ")
is_admitted_before = input("Was the patient admitted before (Yes/No) : ")
print("-" * 20)
print("Name : " + name)
todays_date = date.today()
print(type(todays_date))
print("Age : " + str(todays_date.year - int(birth_year))) #Need to convert it to String
if is_admitted_before == "No":
print("Admission : New")
else:
print("Admission : Old")
print("-" * 20) |
# students1 = []
# for _ in range(int(input("Number of students :"))):
# name = input("Name :")
# score = float(input("Score :"))
# students1.append([name, score])
# print(students1)
students = [['Atharva', 32.0], ['Uma', 32.8], ['Mangesh', 32.0], ['Tejashri', 32.8], ['Ameya', 32.0],
['Suman', 32.8]]
list_marks = []
for i in range(len(students)):
if students[i][1] not in list_marks:
list_marks.append(students[i][1])
list_marks.sort()
result_list = []
for i in range(len(students)):
if students[i][1] == list_marks[1]:
result_list.append(students[i])
sorted_result = sorted(result_list)
for i in range(len(sorted_result)):
print(sorted_result[i][0])
|
a = [11, 22, 33]
#浅拷贝
b = a
#深拷贝
import copy
c = copy.deepcopy(a)
print(id(a))
print(id(b))
print(id(c))
a = [11, 22, 33]
b = [44, 55, 66]
c = [a, b]
d = c
e = copy.deepcopy(c)
f = copy.copy(c)
a.append(00)
print(c[0])
print(e[0])
print(f[0])
|
import datetime
type_of_article = input("What type of article is this ( Electronic ): ")
author = input("What is the author's name: ")
title = input("What is the paper's title: ")
source = input("Where was the article sourced from ( Like New York Times, etc ): ")
datePublished = input("When was the paper published ( MM/DD/YY ): ")
articleURL = input("Url for article: ")
if type_of_article == "Electronic":
#Working on formatting article inputs
split_author1 = author.split(" ")
split_author1.insert(1, ', ')
split_author = ''.join(split_author1)
formatted_title = "\"{}\".".format(title)
formatted_date = datePublished.split("/")
converted_date = datetime.datetime(int(formatted_date[2]), int(formatted_date[0]), int(formatted_date[1]))
month = converted_date.strftime("%B")
day = converted_date.strftime("%m")
year = converted_date.strftime("%Y")
fullformat = "{}. {} {}, {} {} {}, {}. Accessed [ insert date ]".format(split_author, formatted_title,source, day, month, year, articleURL )
print(fullformat)
|
# name = input("Hello what is your name? ")
# age = int(input(f"Nice to meet you {name}. How old are you?"))
# List of films in each category
films_to_watch = {"under_12": ["All Dogs Go to Heaven", "Chicken Little", "The Mighty Ducks", "D2: The Mighty Ducks"],
"under_15": ["Forest Gump", "Black Panther", "Home Alone", "Avengers", "Godzilla vs. Kong"],
"under_18": ["Nobody", "Zack Snyder's Justice League", "Sound of Metal"],
"over_18": ["Fifty Shades Of Grey", "The Wolf Of Wall Street", "Hannibal", "Legend"]
}
# ASK for AGE VIA USER INPUT AND GET NAME LIMIT THE AGE
name_prompt = True
age_prompt = True
while name_prompt:
name = input("Hello what is your name? ").capitalize()
if name.isalpha():
name_prompt = False
else:
print("Please provide your name in letters")
while age_prompt:
age = input(f"Nice to meet you {name}. How old are you? ")
if age.isdigit() and 0 <= int(age) < 130:
age_prompt = False
else:
print("Please provide your answer as a positive whole number")
# FROM THAT GIVE US THE TYPES OF FILM THEY CAN WATCH AT THE CINEMA
if int(age) < 12:
print(f"In that case these are the films you can watch ")
print(films_to_watch["under_12"])
elif 12 <= int(age) < 15:
print(f"In that case these are the films you can watch ")
print(films_to_watch["under_12"])
print(films_to_watch["under_15"])
elif 15 <= int(age) < 18:
print(f"In that case these are the films you can watch ")
print(films_to_watch["under_12"])
print(films_to_watch["under_15"])
print(films_to_watch["under_18"])
else:
print(f"In that case these are the films you can watch ")
print(films_to_watch["under_12"])
print(films_to_watch["under_15"])
print(films_to_watch["under_18"])
print(films_to_watch["over_18"])
|
# isogram = input("Which word would you like to test for being an isogram? ").lower()
def iso_test(word):
isogram = word.replace(" ", "").replace("-", "")
if isogram and len(set(isogram)) == len(isogram) or len(word) == 0:
return True
else:
return False
def iso_test2(string):
for item in string:
if string.count(item) > 1:
return False
elif string.count(" ") > 1 or string.count("-") > 1:
return True
else:
pass
return True
|
#!/usr/bin/python
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
"""
import math, sys
def isPrime(number):
if number < 4:
return True
if number % 2 == 0 or number % 3 == 0:
return False
numMax = int(math.ceil(math.sqrt(number)))
i = 2
bPrime = True
while i <= numMax :
if number % i == 0 :
return False
i += 1
return bPrime
#target = 6
target = 10001
primeCount = 0
i = 2
while primeCount <= target :
if isPrime(i):
primeCount += 1
if primeCount == target:
break;
if i < 3:
i += 1
else :
i += 2
print "============="
print i
|
#!/usr/bin/python
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""
a = 1
b = 2
sum = 0
while (b < 4000000):
print " a: " + str(a)
print " b:" + str(b)
if b % 2 == 0:
print "** Even!!"
sum += b
print "-----"
tmp = b
b = a + b
a = tmp
print "Answer:"
print sum
|
from exercise_21 import Product
# Create an instance
pro1 = Product(101, "Coke", 25.00)
pro2 = Product(208, "Lays Chips", 105.00)
pro3 = Product(560, "Mott's Apple Juice", 200.00)
products = [pro1, pro2, pro3]
for product in products:
print("ID: " + str(product.id))
print("Description: " + product.description)
print("Price: " + str(product.price))
print() |
import random
class Flight: # flight class
def __init__(self, flight_name, flight_no): # constructor
self.flight_name = flight_name
self.flight_no = flight_no
def display(self): # display flight details
print('airlines: ', self.flight_name)
print('flight number: ', self.flight_no)
class Employee: # employee class
def __init__(self, e_id, e_name, e_age, e_gender): # constructor
self.e_name = e_name
self.e_age = e_age
self.__e_id = e_id # private data member
self.e_gender = e_gender
def emp_display(self): # display employee details
print("name of employee: ", self.e_name)
print('employee id: ', self.__e_id) # retrieving private data member
print('employee age: ', self.e_age)
print('employee gender: ', self.e_gender)
class Passenger: # Passenger class
def __init__(self): # constructor
Passenger.__passport_number = input("enter the passport number : ") # private data member
Passenger.name = input('enter the name : ')
Passenger.age = input('enter the age ')
Passenger.gender = input('enter the gender: ')
Passenger.class_type = input('select type of class: ')
class Baggage(): # baggage class
cabin_bag = 1
bag_fare = 0
def __init__(self, checked_bags): # calculate cost if passenger has more than 2 checked bags
self.checked_bags = checked_bags
if checked_bags > 2:
for item in checked_bags:
self.bag_fare += 100
print("number of checked bags allowed:", checked_bags, "bag fare:", self.bag_fare)
class Fare(Baggage): # fare class which is the sub class of baggage class
counter = 150 # fixed cost if ticket is purchased at counter
online = random.randint(100, 200) # if purchased through online, cost is generated from a random function
total_fare = 0
def __init__(self): # constructor
super().__init__(2) # super call to baggage (parent class)
x = input('buy ticket through online or counter:')
if x == 'online':
Fare.total_fare = self.online + self.bag_fare
elif x == 'counter':
Fare.total_fare = self.counter + self.bag_fare
else:
x = input('enter correct transaction type:')
print("Total Fare before class type:", Fare.total_fare)
class Ticket(Passenger, Fare): # multiple inheritance
def __init__(self): # constructor
print("Passenger name:", Passenger.name) # accessing the passenger (parent) class variable
if Passenger.class_type == "business": # cost varies with business and economy class
Fare.total_fare += 100
else:
pass
print("Passenger class type:", Passenger.class_type)
print("Total fare:", Fare.total_fare) # total fare is displayed
f1 = Flight('Etihad', 1000) # Instance of Flight class
f1.display()
e1 = Employee('E1', 'dhruv', 29, 'M') # instance of Employee class
e1.emp_display()
p1 = Passenger() # instance of passenger class
fare1 = Fare() # instance of fare class
t = Ticket() # instance of ticket class |
import smtplib
import getpass
def connect_to_server():
"""
Connects to gmail server
Returns
-------
server : smtplib.SMTP_SSL
gmail email server
"""
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
return server
def get_credentials():
"""
Gets email to be used and credentials to the email
Returns
-------
credentials : dict
Contains keys
+ email
+ password
"""
credentials = {'email': '', 'password': ''}
email = input('Which email would you like to use? (Enter q to exit)\n')
if email == 'q':
credentials['email'] = email
return credentials
password = getpass.getpass(
'Please input the password to {}: '.format(email))
credentials['email'] = email
credentials['password'] = password
return credentials
def login_to_server(server):
"""
Attempts to log in to server until successfully
authenticated or quit char is entered
Parameters
----------
server : smtplib.SMTP_SSL
Server with which to authenticate
Returns
-------
(authenticated, credentials['email']) : tuple
+ authenticated
Boolean indicated whether client successfully authenticated
+ credentials['email']
Email address of sender
"""
authenticated = False
for i in range(3):
try:
credentials = get_credentials()
if credentials['email'] == 'q':
break
print('Authenticating...')
server.login(credentials['email'], credentials['password'])
except Exception as e:
print('\n**********ERROR**********\n')
print(e)
print('Please try again\n')
else:
authenticated = True
break
return (authenticated, credentials['email'])
|
import time
def is_amstrong_number(number):
digits_of_number = [int(x) for x in str(number)]
total = 0
number_of_digits = len(digits_of_number)
i = 0
while ( i < number_of_digits ):
total = total + ( digits_of_number[i] ** number_of_digits )
i = i + 1
if ( total == number ) :
return True
else:
return False
def next_or_previous_amstrong_number(number,next_or_previous): # next_or_previous = True for next and False for previous
current_number = number
i = 0
while (True):
i = i + 1
if (i > 100000):
print ('Iteration limit exceeded')
return 0
if (next_or_previous == True) :
current_number = current_number + 1
else:
current_number = current_number - 1
check_amstrong_of_current_number = is_amstrong_number(current_number)
if (check_amstrong_of_current_number == True):
return current_number
def main_function(number):
time_beginning = time.time()
if (number < 1):
print('Only natural Numbers as input')
return True
checK_if_number_is_amstrong = is_amstrong_number(number)
if (checK_if_number_is_amstrong == True):
print('given number ' + str(number) + ' is amstrong')
else:
print('Given number ' + str(number) + ' is not amstrong')
previous_amstrong_number = next_or_previous_amstrong_number( number , 0 )
print (' previous amstrong number is ' + str(previous_amstrong_number) )
next_amstrong_number = next_or_previous_amstrong_number( number , 1 )
print (' Next amstrong number is ' + str(next_amstrong_number) )
time_end = time.time()
time_of_execution = time_end - time_beginning
print ('Time taken to execution the script was ' + str(time_of_execution) )
return True
main_function(8208)
main_function(15000) |
class Solution:
def thirdMax(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
first = nums[0]
second = third = float('-inf')
for num in nums:
if num > first:
third = second
second = first
first = num
elif num > second and num < first:
third = second
second = num
elif num > third and num < second:
third = num
return third if third != float('-inf') else first |
#виведіть на екран елементи лінійного масиву (заданий користувачем) у зворотньому порядку
#Курдупов Олексій 122-Г
import numpy as np#імпорт бібліотеки нампі
while True:
while True:
try:
a=int(input('Введіть кількість елементів: '))#вводимо кількість елементів
break
except ValueError:#якщо х не число програма запросить заново вести х
print('Введіть число')
b=np.zeros(a,dtype=int)#ініціалізуєм матрицю 0,і робим тип данних int
z=[]# робимо пустий список для вихідного масива
for i in range(a):#проходимся по елементам матриці
b[i] = int(input('Введіть ваші елементи: '))#вводимо значення
for j in range(a):#проходимся по елементам матриці
l=b[a-1-j]#присваюєм елементи масива b з x элементів в зворотньому порядку
z.append(l)#добавляем в список
print(z)
result = input('Хочите продовжити ? Якщо да - 1, Якщо ні - інше: ')#запуск програми заново
if result == '1':
continue
else:
break
|
"""
Problem statement:
It was one of the places, where people need to get their provisions only through fair price (“ration”) shops.
As the elder had domestic and official work to attend to, their wards were asked to buy the items from these shops.
Needless to say, there was a long queue of boys and girls. To minimize the tedium of standing in the serpentine queue,
the kids were given mints. I went to the last boy in the queue and asked him how many mints he has. He said that the
number of mints he has is one less than the sum of all the mints of kids standing before him in the queue.
So I went to the penultimate kid to know how many mints she has.
She said that if I add all the mints of kids before her and subtract one from it,
the result equals the mints she has. It seemed to be a uniform response from everyone.
So, I went to the boy at the head of the queue consoling myself that he would not give the same response as others.
He said, “I have four mints”.
Given the number of first kid’s mints (n) and the length (len) of the queue as input,
write a program to display the total number of mints with all the kids.
"""
s,n = map(int,input().split())
sum=s
for i in range(1,n):
prev=sum-1
sum+=prev
print(sum) |
"""
Common Elements in Three Array
"""
def commonele(A,B,C):
common = list(set(A) & set(B) & set(C))
return common
arr1 = [1,2,3,4,5]
arr2 = [2,3,4,6,9,8]
arr3 = [2,3,6]
print(commonele(arr1,arr2,arr3)) |
def sortt(a):
a.sort()
return a
numbers = [0,2,1,2,0]
# Sorting list of Integers in ascending
print(sortt(numbers))
|
"""
ar = [1,2,3]
max=3
min=1
"""
def maxmin(a):
return (max(a),min(a))
arr = [1000, 11, 445, 1, 330, 3000]
print(maxmin(arr)) |
#!/usr/bin/python
import math
for i in range(1, 15):
denorminator = math.factorial(3*i)
temp = math.factorial(i)
divisor = pow(temp, 3)
print i, denorminator/divisor
|
# create the initial variables below
age = 28
sex = 0
bmi = 26.2
num_of_children = 3
smoker = 0
# Add insurance estimate formula below
insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
print("This person's insurance cost is " + str(insurance_cost) + " dollars.")
# Age Factor
age += 4
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
print("This person's insurance cost is " + str(new_insurance_cost) + " dollars.")
# Difference
change_in_insurance_cost = new_insurance_cost - insurance_cost
print("People who are four years older have estimated insurance costs that are " + str(change_in_insurance_cost) + " dollars different, where the sign of " + str(change_in_insurance_cost) + " tells us whether the cost is higher or lower.") |
def get_sum_2020_2n(numberslist):
numberslist2020 = [2020 - x for x in numberslist]
for en, x in enumerate(numberslist):
if x in numberslist2020[en:]:
return x, 2020 - x
def get_sum_2020_3n(numberslist):
numberslist2020 = [2020 - x for x in numberslist]
for en, x in enumerate(numberslist):
residuals = [y - x for y in numberslist2020[en:]]
for r in residuals:
# only search if residual >0
if r and r in numberslist[en:]:
return r, x, 2020 - r - x
with open("numbers.txt", "r") as numbersfile:
lineslist = numbersfile.readlines()
numberslist = [int(x) for x in lineslist]
x, y = get_sum_2020_2n(numberslist)
# multiply
print(f"2n result: {x * y}")
x, y, z = get_sum_2020_3n(numberslist)
# multiply
print(f"3n result: {x * y * z}")
|
##Check whether the input number is an odd number or not
##And then, if the input number is an odd number, print next 5 odd numbers
##else, print next 5 even numbers
run = True
print('Type "break" if you want to stop')
while(run):
userInput = input('Your number : ')
if(userInput == 'break'):
run = False
try:
input_num = float(userInput)
if(input_num.is_integer()):
if(input_num % 2 == 0):
print('It is an even number')
for i in range(2,11,2):
print(input_num + i)
else:
print('It is an odd number')
for i in range(2,11,2):
print(input_num + i)
else:
print('Please enter an integer')
except ValueError:
print('Please enter an integer')
|
import os
def SaveCSV(array_to_write, output_filename):
#initialize variables
i = 1
ensureDir(output_filename)
root_filename = stripCSV(output_filename)
# check filename doesn't exist
csv_filename = root_filename
while os.path.exists(csv_filename + '.csv'):
print csv_filename + '.csv already exists. Filename changed...'
i += 1
csv_filename = root_filename + str(i)
# write array into CSV file
from csv import writer
csv_filename = csv_filename + '.csv'
wfile = open(csv_filename, 'wb')
the_writer = writer(wfile)
the_writer.writerows(array_to_write)
wfile.close()
print "File created: %s" % csv_filename
def ensureDir(filename):
i = filename.rfind("\\")
dir_name = filename[:i]
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print "Directory %s created" % dir_name
def checkDir(filename):
if filename.endswith("\\"):
rtn_filename = filename
else:
rtn_filename = "%s\\" % filename
return rtn_filename
def stripCSV(strip_filename):
# strip '.csv' off filenames
if strip_filename.endswith('.csv'):
rtn_filename = strip_filename.rsplit('.csv')[0]
else:
rtn_filename = strip_filename
return rtn_filename
def appendCSV(arrays_to_append, append_filename, first_row):
import csv
if os.path.isfile(append_filename):
#append row to end of append_filename
fd = open(append_filename,'ab')
writer = csv.writer(fd)
writer.writerows(arrays_to_append)
fd.close()
print "File appended: %s" % append_filename
else:
arrays_to_write = [first_row]
arrays_to_write.extend(arrays_to_append)
SaveCSV(arrays_to_write, append_filename)
def sortCSV(filename_to_read):
# import packages
import csv
csv.field_size_limit(50000000)
import operator
# read input filename
rfile = open(filename_to_read, 'rb')
csv_reader = csv.reader(rfile)
columns = csv_reader.next()
sortedlist = sorted(csv_reader, key=operator.itemgetter(3))
arrays_to_write = [columns]
arrays_to_write.extend(sortedlist)
rfile.close()
return arrays_to_write
|
#
# An exercise script on random number generation/manipulation.
# ref. http://effbot.org/librarybook/random.htm
#
import random
import sys
print '0.0<=float<1.0 10<=float<20 100<=int<= 1000 100<=even int.< 1000'
for i in range(5):
#print '| random float: 0.0 <= number < 1.0'
print '%15.13f' % random.random(),
#print '| random float: 10 <= number < 20'
print '%16.14f' % random.uniform(10, 20),
#print '| random integer: 100 <= number <= 1000'
print '%5d' % random.randint(100, 1000),
#print '| random integer: even numbers in 100 <= number < 1000'
print '%5d' % random.randrange(100, 1000, 2)
print ''
histogram = [0] * 20
histogram2 = [0] * 20
for i in range(1000):
j = int(random.gauss(5, 1) * 2)
k = int(random.uniform(0, 10) * 2)
# print i
histogram[j] = histogram[j] + 1
histogram2[k] = histogram2[k] + 1
print 'Generate gaussian random number sequence and show histogram picture'
m = max(histogram)
for v in histogram:
print '| %s' % ("*" * (v * 50 / m))
print 'Generate uniform and gaussian random number sequences and show histogram'
for v in range(0,20):
print '%4.1f - %4.1f : %5d %5d' % (float(v) / 2, (float(v) + 1) / 2, histogram[v], histogram2[v])
#random.seed()
#
#count = 0
#while True:
# if count > 100:
# sys.exit(0)
# print random()
# print uniform(0,10)
|
import numpy as np
import matplotlib.pyplot as plt
class Perceptron(object):
def __init__(self, no_of_inputs, name, threshold=100, learning_rate=0.01):
self.threshold = threshold
self.learning_rate = learning_rate
self.weights = np.zeros(no_of_inputs + 1)
self.name = name
def predict(self, inputs):
summation = np.dot(inputs, self.weights[1:]) + self.weights[0]
if summation > 0:
activation = 1
else:
activation = 0
return activation
def train(self, training_inputs, labels):
a = []
b = []
for i in range(self.threshold):
for inputs, label in zip(training_inputs, labels):
prediction = self.predict(inputs)
self.weights[1:] += self.learning_rate * (label - prediction) * inputs
self.weights[0] += self.learning_rate * (label - prediction)
a.append(label-prediction)
b.append(i)
plt.plot(b, a, 'b.')
plt.title(self.name)
plt.show()
|
print("野兽先辈XX说自动论证机")
name = input("你想论证的人是?")
sex = input("他/他的性别是?(男性或者女性)")
true = input("他是在现实中存在的人吗?(是或不是):")
hurt = input("他是否被当成群友的乐子?(是或不是):")
win = input("他做过的好事:")
fail = input("他做过的坏事:")
want = input("他的梦想:")
print("迄今为止,野兽先辈的身份说法已经有1145141919810种,笔者今天经过考证发现了另一种可能!野兽先辈的本体乃是" + name +"!论证如下:")
if sex == "男性":
print("1." + name + "是男性,野兽先辈也是男性")
else:
print("1." + name + "是女性,野兽先辈喜欢男人,也是女性(暴论)")
if true == "是":
print("2.野兽先辈在《真夏夜的银梦》中本色出演,事真实存在的人物;而" + name + "也在三次元中真实存在。")
else:
print("2." + name + "事虚拟人物;而先辈也是《真夏夜的银梦》中的虚拟人物。")
if hurt == "是":
print("3.先辈遭到n站无数人迫害,是屑。而" + name +"也被群友迫害,也是屑")
else:
print("3.先辈遭到n站无数人迫害却顽强地站起来爆破nico本社,是鉴。而" + name + "没有被群友迫害过,也是鉴")
print("4.野兽先辈关心后辈(大嘘),事鉴;" + name + win + ",也是鉴")
print("5.野兽先辈雷普后辈,事屑;" + name + fail +",也事屑。")
print("6." + name + want + ",事王道征途;野兽先辈也崇尚王道征途。")
print("最后,没有任何证据表明" + name + "一定不事野兽先辈。而基于以上论据,以及“如果一个东西长得像鸭子,游泳像鸭子,叫声像鸭子,那么它就是鸭子”的原理,我们可以完全确信," + name + "就事野兽先辈。")
print("Q.E.D")
close = input("Press <Enter>") |
animals = ['dog','cat','pig']#animals列表中共有3中动物
for animal in animals:#将animals中三种动物储存在animal中
print(animal)#打印列表animals中的元素
print('i like animal like,'+animal.title()+',\n')
print('i am really like animal,i think ther are my friend'+'\n')
numbers = list(range(0,8))
print(numbers) |
"""
* About
*
* Author: seventeeen@GitHub <[email protected]>
* Date : 2017-02-22
* URL : https://www.acmicpc.net/problem/10820
*
"""
try:
while True:
a = raw_input()
length = len(a)
u = l = d = s = 0
for i in range(length):
if a[i].isupper():
u += 1
elif a[i].islower():
l += 1
elif a[i].isdigit():
d += 1
else:
s += 1
print str(l) + ' ' + str(u) + ' ' + str(d) + ' ' + str(s)
except:
pass
|
"""
* About
*
* Author: seventeeen@GitHub <[email protected]>
* Date : 2017-02-21
* URL : https://www.acmicpc.net/problem/5598
*
"""
s=raw_input()
x=''
for i in range(len(s)):
if ord(s[i])-ord('A')<3:
x+=chr(ord(s[i])+23)
else:
x+=chr(ord(s[i])-3)
print x
|
"""
* About
*
* Author: seventeeen@GitHub <[email protected]>
* Date : 2017-02-21
* URL : https://www.acmicpc.net/problem/5363
*
"""
n = input()
for i in range(n):
s = raw_input().split(' ')
s.append(s[0])
s.append(s[1])
s.pop(0)
s.pop(0)
result = ''
for j in range(len(s)):
result += s[j] + ' '
print result
|
"""
* About
*
* Author: seventeeen@GitHub <[email protected]>
* Date : 2017-02-22
* URL : https://www.acmicpc.net/problem/11655
*
"""
s = raw_input()
c=''
for i in range(len(s)):
if s[i].isupper():
if ord(s[i])-ord('A')<13:
c += chr(ord(s[i])+13)
else:
c += chr(ord(s[i])-13)
elif s[i].islower():
if ord(s[i])-ord('a')<13:
c += chr(ord(s[i])+13)
else:
c += chr(ord(s[i])-13)
else:
c += s[i]
print c
|
def partition(array, left, right):
pivot_value = array[left]
left_marker = left
right_marker = right
while left_marker < right_marker:
while left_marker <= right and array[left_marker] <= pivot_value:
left_marker += 1
while left <= right_marker and array[right_marker] > pivot_value:
right_marker -= 1
if left_marker < right_marker:
array[left_marker], array[right_marker] = array[right_marker],array[left_marker]
array[left],array[right_marker] = array[right_marker],array[left]
return right_marker
def quick_sort(left,right, array):
if left < right:
split_point = partition(array, left, right)
array = quick_sort(left,split_point-1,array)
array = quick_sort(split_point+1,right,array)
return array
if __name__ == '__main__':
pass
|
total = int(input())
for i in range(1,total+1):
n = int(input())
sum = 0
for c in range(1,n+1):
sum = sum + c**3
print(str(sum))
|
import random
random_num = random.random()*100
def grade(num):
if num <60:
print "Score:", num, "; Your grade is F"
elif num <= 69 and num >= 60:
print "Score:", num, "; Your grade is D"
elif num <= 79 and num >= 70:
print "Score:", num, "; Your grade is C"
elif num <= 89 and num >= 80:
print "Score:", num, "; Your grade is B"
elif num <= 100 and num >= 90:
print "Score:", num, "; Your grade is A"
grade(random_num) |
class MathDojo(object):
def __init__(self):
self.result = 0
def add(self, *j):
for i in j:
if type(i) == int:
self.result += i
else:
for x in i:
self.result += x
return self
def subtract(self, *j):
for i in j:
if type(i) == int:
self.result -= i
else:
for x in i:
self.result -= x
return self
def total(self):
print self.result
md = MathDojo()
# md.add([2,1,2],3).add(4,3).total()
md.subtract(2,3).subtract([1,2,4,3],2,3,2).total()
|
def odd_even():
for x in range(1, 2001):
if x % 2 == 0:
print "Number is", x,"This is an even number."
else:
print "Number is", x,"This is an odd number."
odd_even()
def multiply(arr, num):
for x in range(0, len(arr)):
#print x
arr[x] *= num
return arr
print multiply([2,3,5,6], 5)
def layered_multiples(arr):
#print arr
new_arr1 = []
for x in arr:
print x
new_arr2 = []
#print new_arr2
for y in range(0, x):
new_arr2.append(1)
new_arr1.append(new_arr2)
return new_arr1
x = layered_multiples(multiply([2,4,5],3))
print x
|
bio = {"name": "Justin",
"age": 27,
"country of birth": "The United States",
"favorite language": "Python"}
#print bio["name"]
def info():
for key in bio:
#bio[key] ---> look at it as if the key to the
#dictionary unlocks the value, and that is what
#is displayed
print "My",key, "is", bio[key]
info() |
class Animal(object):
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
print self.health
# # Animal1 = Animal("Elephant", 100)
# Animal1.walk().walk().walk().run().run().display_health()
class Dog(Animal):
def __init__(self, name):
super(Dog, self).__init__(name, 150)
def pet(self):
self.health += 5
return self
dog1 = Dog("Stella")
dog1.walk().walk().walk().run().run().pet().display_health()
class Dragon(Animal):
def __init__(self, name):
super(Dragon, self).__init__(name, 170)
def fly(self):
self.health -= 10
# print self.health, "I am a Dragon"
return self
dragon1 = Dragon("Drogon")
dragon1.fly().display_health()
class Kangaroo(Animal):
def __init__(self, name):
super(Kangaroo, self).__init__(name, 150)
def hop(self):
self.health -= 4
return self
Kangaroo1 = Kangaroo("Kango")
Kangaroo1.hop().display_health()
# dog1.fly().display_health() |
'''
@Title: Testing triangle classification
@Author: PuzhuoLi CWID:10439435
@Date: 2019-01-26 13:24:16
'''
import unittest
import math
from HW01_pli import classify_triangle
class TestTriangle(unittest.TestCase):
'''
Test HW01 triangle classification
equilateral triangles have all three sides with the same length
isosceles triangles have two sides with the same length
scalene triangles have three sides with different lengths
right triangles have three sides with lengths, a, b, and c where a2 + b2 = c2
'''
# test 8 case
def test_classify_triangle1(self):
self.assertEqual(
"It is a isoscele triangle and a right triangle as well!",
classify_triangle(1, 1, math.sqrt(2)))
def test_classify_triangle2(self):
self.assertEqual("It is a right triangle!", classify_triangle(5, 4, 3))
def test_classify_triangle3(self):
self.assertEqual(
"It is an equilateral triangle but not a right triangle!",
classify_triangle(3, 3, 3))
def test_classify_triangle4(self):
self.assertEqual("It is a isoscele triangle but not a right triangle!",
classify_triangle(3, 3, 4))
def test_classify_triangle5(self):
self.assertEqual("It is a scalene triangle and not a right triangle!",
classify_triangle(2, 3, 4))
def test_classify_triangle6(self):
self.assertEqual("Please double check the enter, it is not a triangle",
classify_triangle(1, 2, 3))
def test_classify_triangle7(self):
with self.assertRaises(TypeError):
classify_triangle(1, 2, "l")
def test_classify_triangle8(self):
with self.assertRaises(ValueError):
classify_triangle(1, 2, -13)
if __name__ == "__main__":
unittest.main(exit=False, verbosity=2)
|
from datetime import datetime, timedelta, date
def month_ago(dt):
"""
>>> month_ago(datetime(1969, 7, 21, 14, 56, 15))
datetime.datetime(1969, 6, 21, 4, 27, 9)
"""
return dt - timedelta(days=30.436875)
datetime.now() - timedelta(hours=3)
date(1961, 4, 12) - timedelta(days=3)
now = datetime.now()
month_ago(now)
|
class File:
def __init__(self, name, content=[]):
self.name = name
self.content = content
def append(self, line):
self.content.extend(line)
def write(self):
with open(self.name, 'w') as file:
file.write(self.content)
def __enter__(self):
pass
def __exit__(self, **kwargs):
return self.write()
with File('asd.txt') as file:
file.append('nowa linia')
# dopiero po wyjsciu z with, plik zostanie zapisany
|
import pygame
from pygame import *
import time
import random
pygame.init()
width=800
length=600
gamedisp=pygame.display.set_mode((width,length))
pygame.display.set_caption("wwwooww")
clock=pygame.time.Clock()
blue=(255,255,255)
black=(0,0,0)
green=(0,255,0)
myimg=pygame.image.load("car.png").convert_alpha()
x=width/2
y=length-180
score=0
x_change=0
y_change=0
o_w=100
o_x=random.randrange(0,width-o_w)
o_h=100
o_y=0
speed=20 #random.randrange(3,6,1)
def car(x,y):
gamedisp.blit(myimg,(x,y))
def objects(o_x,o_y,o_w,o_h,color):
global score
pygame.draw.rect(gamedisp,green,(o_x,o_y,o_w,o_h))
def object_crash():
global x,y,o_x,o_y,green,o_h,o_w,score
if(y+10<o_y+100 and y+10>o_y and x<o_x+100 and x>o_x ):
print("1")
score=0
crash()
if(y+144<o_y+100 and y+144>o_y and x<o_x+100 and x>o_x ):
print("2")
score=0
crash()
if(y+5<o_y+100 and y+5>o_y and x+60<o_x+100 and x+60>o_x ):
print("3")
score=0
crash()
if(y+144<o_y+100 and y+144>o_y and x+64<o_x+100 and x+64>o_x ):
print("4")
score=0
car(x,y)
pygame.display.update()
crash()
if(y+10<o_y+100 and x<o_x and x+64>x+100):
print("5")
score=0
crash()
def new_object():
global o_x,o_y,green,o_h,o_w,score,speed
if(o_y>600+147):
o_y=0
o_x=random.randrange(0,800-o_w)
score+=1
speed=speed+5
objects(o_x,o_y,o_w,o_h,green)
def boundary(a,b):
if(a>width-64):
a=width-64
crash()
if(a<0):
a=0
crash()
if(b>length-144):
b=length-144
crash()
if(b<0):
b=0
crash()
return (a,b)
def crash():
display_text('you crashed dude')
def display_text(text):
fonttext=pygame.font.Font('freesansbold.ttf',50)
textdisp=fonttext.render(text, True, black)
position=textdisp.get_rect()
position.center=(400,300)
gamedisp.blit(textdisp,position)
pygame.display.update()
time.sleep(1)
game()
def intro():
introdisp=[1,2,3]
introposition=[1,2,3]
myintro=pygame.image.load("intro.jpg").convert_alpha()
gamedisp.blit(myintro,(0,0))
logo=pygame.image.load("logo.png").convert_alpha()
gamedisp.blit(logo,(200,25))
'''introfont=pygame.font.Font('freesansbold.ttf',100)'''
enter_quitfont=pygame.font.Font('freesansbold.ttf',25)
#introdisp[0]=introfont.render("car race ",True,(0,0,0))
introdisp[1]=enter_quitfont.render("*enter ",True,(255,255,255))
introdisp[2]=enter_quitfont.render("*quit ",True,(255,255,255))
#introposition[0]=introdisp[0].get_rect()
introposition[1]=introdisp[1].get_rect()
introposition[2]=introdisp[2].get_rect()
#introposition[0].center=(300,50)
introposition[1].center=(750,400)
introposition[2].center=(750,450)
#gamedisp.blit(introdisp[0],introposition[0])
gamedisp.blit(introdisp[1],introposition[1])
gamedisp.blit(introdisp[2],introposition[2])
pygame.display.update()
while(True):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == K_RETURN:
game()
def game():
global x,y,x_change,y_change,o_w,o_h,o_x,o_y,speed
end=False
while not end:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
quit()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_LEFT:
x_change=-20
o_y=o_y+speed
if event.key==pygame.K_RIGHT:
x_change=+20
o_y=o_y+speed
if event.type==pygame.KEYUP:
if event.key==pygame.K_LEFT:
x_change=0
if event.key==pygame.K_RIGHT:
x_change=0
#car change
x=x+x_change
y=y+y_change
#object_crash
object_crash()
#new object
new_object()
#boundary
(x,y)=boundary(x,y)
gamedisp.fill(blue)
#score
fonttext=pygame.font.Font('freesansbold.ttf',15)
scoretext=fonttext.render("score:"+str(score),True,black)
gamedisp.blit(scoretext,(0,0))
#def objects(o_x,o_y,o_w,o_h,color):
objects(o_x,o_y,o_w,o_h,green)
#car
car(x,y)
pygame.display.update()
clock.tick(30)
intro()
pygame.quit()
quit()
|
# Урок 7, задача №2
# Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50).
# Выведите на экран исходный и отсортированный массивы.
import random
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 49
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
def merge_sort_asc(arr, left_index, right_index):
# Функция делит входной массив на 2 половины
# и рекурсивно сортирует его
if left_index >= right_index:
return
middle = (left_index + right_index) // 2
merge_sort_asc(arr, left_index, middle)
merge_sort_asc(arr, middle + 1, right_index)
merge_arrays(arr, left_index, right_index, middle)
def merge_arrays(arr, left_index, right_index, middle):
# Функция выполняет слияние двух массивов в один,
# при этом сортирует их элементы по возрастанию
# создаются копии входного массива
left_copy = arr[left_index:middle + 1]
right_copy = arr[middle + 1:right_index + 1]
# начальные значения счетчиков для продвижения по массивам
left_copy_index = 0
right_copy_index = 0
sorted_index = left_index
# обход массивов, пока в одном из них не закончатся элементы
while left_copy_index < len(left_copy) and right_copy_index < len(right_copy):
# если в массиве left_copy содержится меньший элемент,
# он помещается в отсортированный массив,
# счетчик продвижения по саммиву left_copy увеличивается на 1
if left_copy[left_copy_index] <= right_copy[right_copy_index]:
arr[sorted_index] = left_copy[left_copy_index]
left_copy_index += 1
# в противном случае происходит выбор элемента и
# продвижение по массиву right_copy
else:
arr[sorted_index] = right_copy[right_copy_index]
right_copy_index += 1
# в любом случае счетчик продвижения по
# отсортированному массиву увеличивается на 1
sorted_index += 1
# если раньше закончились элементы в массиве right_copy,
# в отсортированный массив добавляются оставшиеся элементы из left_copy
while left_copy_index < len(left_copy):
array[sorted_index] = left_copy[left_copy_index]
left_copy_index += 1
sorted_index += 1
# если раньше закончились элементы в массиве left_copy,
# в отсортированный массив добавляются оставшиеся элементы из right_copy
while right_copy_index < len(right_copy):
array[sorted_index] = right_copy[right_copy_index]
right_copy_index += 1
sorted_index += 1
merge_sort_asc(array, 0, len(array) - 1)
print(array)
|
# Урок 2, задача №4
"""
Найти сумму n элементов следующего ряда чисел:
1, -0.5, 0.25, -0.125,…
Количество элементов (n) вводится с клавиатуры.
"""
# https://drive.google.com/file/d/1GT181Ddb1Aa7eHZa0Z7IvIQe6Mg5Nyww/view?usp=sharing
def rec(count, base_num):
if count <= 1:
return base_num
else:
return base_num + rec(count - 1, base_num * -0.5)
base_num = 1
n = int(input('Введите натуральное число N: '))
result = rec(n, base_num)
print(result)
|
# Урок 3, задача №2
"""
Во втором массиве сохранить индексы четных элементов первого массива.
Например, если дан массив со значениями 8, 3, 15, 6, 4, 2,
второй массив надо заполнить значениями 0, 3, 4, 5, (индексация начинается с нуля),
т.к. именно в этих позициях первого массива стоят четные числа.
"""
import random
SIZE = 50
MIN_ITEM = 1
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
even_numbers = [array.index(i) for i in array if i % 2 == 0]
print(even_numbers)
|
from rectangle import Rectangle, Square, Circle
rectangle_1 = Rectangle(5, 10, 50, 100)
square_1 = Square(10, 10, 30)
circle_1 = Circle(30, 50, 70)
print("Rectangle init: " + str(rectangle_1))
print("Square init: " + str(square_1))
print("Circle init: " + str(circle_1))
|
from utilities import *
# Advent of Code 2020
# Brendan Thompson
# Day 08
# Star 1
def run_script(path):
"""
Execute the program specified in the data: tracking the accumulator, and printing the accumulator before executing a line twice
"""
# Read Data
print("Reading file: ", path, "...")
data_file = open(path,'r')
lines = data_file.readlines()
data_file.close()
# Solve
sum = 0
i = 0
lines_visited = []
while i not in lines_visited:
lines_visited.append(i)
(op_code, sign, value) = parse_line(lines[i].strip())
# Handle Operation
if op_code == "acc":
if sign == "+":
sum = sum + value
else:
sum = sum - value
i = i + 1
if op_code == "jmp":
if sign == "+":
i = i + value
else:
i = i - value
if op_code == "nop":
i = i + 1
# Return
print("Sum:", sum)
def parse_line(line):
"""
Get the op_code, sign, and value from the line
"""
j = 0
(j, op_code) = get_next_word(j, line)
j = j + 1
(j, parameter) = get_next_word(j, line)
sign = parameter[:1]
value = int(parameter[1:])
return (op_code, sign, value)
|
# Advent of Code
# Brendan Thompson
# Day 03
# Star 2
# https://adventofcode.com/2020/day/3
print("Advent of Code Day 03")
def get_next_position(x, y, movement_x, movement_y, map):
# Get the next position given the current row and height
x = x + movement_x
y = y + movement_y
# Handle Wrap
map_width = len(map[0])
if x >= map_width - 1:
x = x - map_width + 1
return (x, y)
def get_num_trees_hit(movement_x, movement_y, map):
# Get the number of trees ('#') hit given the map and slope
x = 0
y = 0
num_trees_hit = 0
while (y < len(map)):
position_contents = map[y][x]
print("(", x, ",", y, ")")
print("\t", position_contents)
if position_contents == '#':
num_trees_hit = num_trees_hit + 1
print("\tHit")
(x, y) = get_next_position(x, y, movement_x, movement_y, map)
return num_trees_hit
# Read Data
path = './Day03/data.txt'
print("Reading file: ", path, "...")
data_file = open(path,'r')
map = data_file.readlines()
data_file.close()
# Solve
num_trees_slope_1_1 = get_num_trees_hit(1, 1, map)
num_trees_slope_3_1 = get_num_trees_hit(3, 1, map)
num_trees_slope_5_1 = get_num_trees_hit(5, 1, map)
num_trees_slope_7_1 = get_num_trees_hit(7, 1, map)
num_trees_slope_1_2 = get_num_trees_hit(1, 2, map)
product = num_trees_slope_1_1 * num_trees_slope_3_1 * num_trees_slope_5_1 * num_trees_slope_7_1 * num_trees_slope_1_2
print("Product:", product) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.